-
Notifications
You must be signed in to change notification settings - Fork 2
/
Notification.ts
184 lines (161 loc) · 6.26 KB
/
Notification.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import uuid from 'node-uuid';
const TraceError = require('trace-error');
import CancellationToken from 'cancellationtoken';
import Log from './Log';
import { ExpressApplication, AppContext } from "./ModuleBase";
import {CameraStatus, CameraDeviceSettings, BackofficeStatus, Sequence, NotificationStatus, NotificationItem} from './shared/BackOfficeStatus';
import JsonProxy, { has } from './shared/JsonProxy';
import { DriverInterface, Vector } from './Indi';
import {Task, createTask} from "./Task.js";
import {timestampToEpoch} from "./Indi";
import {IdGenerator} from "./IdGenerator";
import * as RequestHandler from "./RequestHandler";
import * as BackOfficeAPI from "./shared/BackOfficeAPI";
import ConfigStore from './ConfigStore';
const logger = Log.logger(__filename);
async function promiseOutcome(promise: Promise<any>) {
try {
return { rejected: false, value: await promise }
} catch (error) {
return { rejected: true, value: error }
}
}
export default class Notification
implements RequestHandler.APIAppProvider<BackOfficeAPI.NotificationAPI>
{
appStateManager: JsonProxy<BackofficeStatus>;
context: AppContext;
notificationIdGenerator = new IdGenerator();
readonly currentStatus : NotificationStatus;
readonly serverUuid: string;
readonly watchers: {[uid: string]: (b:boolean)=>(void)} = {};
readonly expires: {[uid: string]:NodeJS.Timeout} = {};
constructor(app:ExpressApplication, appStateManager:JsonProxy<BackofficeStatus>, context:AppContext, serverUuid: string) {
this.appStateManager = appStateManager;
this.appStateManager.getTarget().notification = {
byuuid: {},
list: [],
};
this.currentStatus = this.appStateManager.getTarget().notification;
this.context = context;
this.serverUuid = serverUuid;
// Report unhandled rejection (instead of killing the whole process)
process.on('unhandledRejection', async (reason: {} | null | undefined, promise: Promise<any>) => {
const { rejected, value } = await promiseOutcome(promise);
logger.error('unhandledRejection', promise);
this.error('Internal error (async)', value);
});
process.on('uncaughtException', (error: Error) => {
logger.error('uncaughtException', error);
this.error('Internal error', error);
});
process.on('rejectionHandled', ()=>{});
}
// Early draft...
doNotify(title: string, type: NotificationItem["type"], buttons: NotificationItem["buttons"]) {
const uid = this.serverUuid + ":" + this.notificationIdGenerator.next();
this.currentStatus.byuuid[uid] = {
time: new Date().getTime(),
title,
type,
buttons,
}
this.currentStatus.list.push(uid);
return uid;
}
notify(title: string) {
this.doNotify(title, "oneshot", null);
}
unnotify(uid: string) {
delete this.currentStatus.byuuid[uid];
while(true) {
const id = this.currentStatus.list.indexOf(uid);
if (id === -1) {
break;
}
this.currentStatus.list.splice(id, 1);
}
delete this.watchers[uid];
if (has(this.expires, uid)) {
clearTimeout(this.expires[uid]);
delete this.expires[uid];
}
}
onNotificationResult(uid: string, cb:(v: any)=>void) {
this.watchers[uid] = cb;
}
dialog<T>(ct: CancellationToken, title: string, options:Array<{title:string, value:T}>):Promise<T> {
return new Promise<T>((res, rej)=> {
let unrej: undefined|{ (): void; (): void; (): void; };
const uuid = this.doNotify(title, "dialog", options);
const doUnrej= ()=>{
if (unrej !== undefined) {
unrej();
unrej = undefined;
}
}
const done = (result: any)=>{
doUnrej();
res(result as T);
}
const abort=(reason?:any)=>{
doUnrej();
this.unnotify(uuid);
if (reason instanceof CancellationToken.CancellationError) {
rej(reason);
} else {
rej(new CancellationToken.CancellationError(reason));
}
}
this.watchers[uuid] = done;
unrej = ct.onCancelled(abort);
});
}
public exposedNotification = async(ct: CancellationToken, message:BackOfficeAPI.ExposedNotificationRequest)=>{
const uid = message.uuid;
if (has(this.currentStatus.byuuid, uid) && !has(this.expires, uid)) {
if (this.currentStatus.byuuid[uid].type === "oneshot") {
this.expires[uid] = setTimeout(()=>this.closeNotification(CancellationToken.CONTINUE, {uuid:uid}), 10000);
}
}
}
public closeNotification = async(ct: CancellationToken, message:BackOfficeAPI.CloseNotificationRequest)=>{
const uid = message.uuid;
if (has(this.currentStatus.byuuid, uid)) {
const watcher = has(this.watchers, uid) ? this.watchers[uid]: undefined;
this.unnotify(uid);
if (watcher) {
watcher(message.result);
}
}
logger.debug('Remaining notifications', {remainingNotifications: this.currentStatus});
}
private message(content: string) {
// add this to indi logs for now
this.context.indiManager.addMessage({
$$: "message",
$device: "",
$timestamp: new Date().toISOString().replace(/Z$/, ''),
$message: content,
});
}
public info(content: string) {
logger.info('INFO', {content});
this.message(content);
}
public error(content: string, reason?: any) {
if (reason) {
logger.info('ERROR', {content}, reason);
this.message(content + ": " + (reason.msg || reason));
} else {
logger.info('ERROR', {content});
this.message(content);
}
}
getAPI() {
return {
closeNotification: this.closeNotification,
exposedNotification: this.exposedNotification,
}
}
}