-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
383 lines (329 loc) · 11.9 KB
/
index.js
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
const EventEmitter = require('events');
const { sessionBus: SessionBus, Variant } = require('dbus-next');
const checkTypes = require('./utils/checkTypes');
const ActionInvokedSymbol = Symbol('actionInvoked');
const ActionKeys = Object.freeze({
default: 'default',
inlineReply: 'inline-reply',
});
const DbusEvents = Object.freeze({
ActionInvoked: 'ActionInvoked',
NotificationClosed: 'NotificationClosed',
NotificationReplied: 'NotificationReplied',
});
let externalSessionBus;
let selfSessionBus;
let Notifications;
let getInterfaceStat = false;
const notificationCounter = [];
const Config = {
autoDisconnectSessionBus: true,
closeReplacedNotify: false,
};
const notifierEmitter = new EventEmitter();
const disconnectSessionBus = function disconnectSessionBus() {
if (!selfSessionBus) {
return;
}
// Save it for delayed disconnection.
const sessionBus = selfSessionBus;
selfSessionBus = undefined;
// dbus-next bug
// disconnecting the dbus connection immediately will throw an error, so let's delay the disconnection just in case.
setTimeout(() => {
sessionBus.disconnect();
}, 100);
};
const actionInvoked = function actionInvoked(id, actionKey) {
notifierEmitter.emit(`${DbusEvents.ActionInvoked}:${id}`, actionKey);
};
const notificationClosed = function notificationClosed(id, reason) {
notifierEmitter.emit(`${DbusEvents.NotificationClosed}:${id}`, reason);
};
const notificationReplied = function notificationReplied(id, message) {
notifierEmitter.emit(`${DbusEvents.NotificationReplied}:${id}`, message);
};
const bindNotifications = function bindNotifications(notificationInterface) {
// Since the NotificationClosed event will fire when any notification is closed
// using ID to trigger the event here allows us to use once() elsewhere without binding too many events.
notificationInterface.on(DbusEvents.ActionInvoked, actionInvoked);
notificationInterface.on(DbusEvents.NotificationClosed, notificationClosed);
notificationInterface.on(DbusEvents.NotificationReplied, notificationReplied);
Notifications = notificationInterface;
return Notifications;
};
const unsetNotifications = function unsetNotifications() {
if (!Notifications) {
return;
}
Notifications.off(DbusEvents.ActionInvoked, actionInvoked);
Notifications.off(DbusEvents.NotificationClosed, notificationClosed);
Notifications.off(DbusEvents.NotificationReplied, notificationReplied);
Notifications = undefined;
};
const getSessionBus = function getSessionBus() {
if (externalSessionBus) {
return externalSessionBus;
}
if (!selfSessionBus) {
selfSessionBus = SessionBus();
}
return selfSessionBus;
};
const setSessionBus = function setSessionBus(sessionBus) {
unsetNotifications();
disconnectSessionBus();
externalSessionBus = sessionBus;
Config.autoDisconnectSessionBus = Config.autoDisconnectSessionBus && !sessionBus;
};
const getInterface = function getInterface() {
if (Notifications) {
return Promise.resolve(Notifications);
}
if (getInterfaceStat) {
return new Promise((resolve, reject) => {
notifierEmitter.once('getInterface', resolve);
notifierEmitter.once('getInterfaceError', reject);
});
}
getInterfaceStat = true;
return new Promise((reslove, reject) => {
getSessionBus().getProxyObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
.then((obj) => {
const i = bindNotifications(obj.getInterface('org.freedesktop.Notifications'));
notifierEmitter.emit('getInterface', i);
reslove(i);
})
.catch((err) => {
if (Config.autoDisconnectSessionBus) {
disconnectSessionBus();
}
notifierEmitter.emit('getInterfaceError', err);
reject(err);
})
.finally(() => {
getInterfaceStat = false;
});
});
};
const setInterface = function setInterface(notificationInterface) {
unsetNotifications();
disconnectSessionBus();
if (notificationInterface) {
bindNotifications(notificationInterface);
} else {
// Get a new one to continue processing old events.
getInterface();
}
};
const genIdentifier = function* genIdentifier() {
let IX = 0;
while (true) {
IX = IX >= 25 ? 0 : IX + 1;
const ide = String.fromCharCode(64 + IX);
yield ide;
}
};
const identifier = genIdentifier();
notifierEmitter.on('push', () => {
notificationCounter.push(true);
});
notifierEmitter.on('pop', () => {
notificationCounter.pop();
if (Config.autoDisconnectSessionBus && selfSessionBus && notificationCounter.length === 0) {
unsetNotifications();
disconnectSessionBus();
}
});
class Notify extends EventEmitter {
#id = 0;
#status = 0;
#actions = new Map();
#config = {};
// NodeJS 12 private method not supported
[ActionInvokedSymbol](key, ...args) {
const action = this.#actions.get(key);
if (typeof action.callback === 'function') {
action.callback(...args);
}
}
get id() {
return this.#id;
}
get status() {
return this.#status;
}
constructor(config) {
super();
this.#config = {
appName: config.appName || '',
replacesId: config.replacesId || 0,
appIcon: config.appIcon || '',
summary: config.summary || '',
body: config.body || '',
hints: config.hints || {},
timeout: config.timeout || 0,
};
checkTypes.string(this.#config.appName, 'appName is not string.');
checkTypes.integer(this.#config.replacesId, 'replacesId is not integer.');
checkTypes.string(this.#config.appIcon, 'appIcon is not string.');
checkTypes.string(this.#config.summary, 'summary is not string.');
checkTypes.string(this.#config.body, 'body is not string.');
checkTypes.object(this.#config.hints, 'hints is not object.');
checkTypes.integer(this.#config.timeout, 'timeout is not integer.');
const { hints } = this.#config;
this.#config.hints = {};
if ('actionIcons' in hints && checkTypes.boolean(hints.actionIcons, 'hints.actionIcons is not boolean.')) {
this.#config.hints['action-icons'] = new Variant('b', hints.actionIcons);
}
if ('category' in hints && checkTypes.string(hints.category, 'hints.category is not string.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['category'] = new Variant('s', hints.category);
}
if ('desktopEntry' in hints && checkTypes.string(hints.desktopEntry, 'hints.desktopEntry is not string.')) {
this.#config.hints['desktop-entry'] = new Variant('s', hints.desktopEntry);
}
if ('imagePath' in hints && checkTypes.string(hints.imagePath, 'hints.imagePath is not string.')) {
this.#config.hints['image-path'] = new Variant('s', hints.imagePath);
}
if ('imageData' in hints && checkTypes.object(hints.imageData, 'hints.imageData is not object.')) {
const channel = hints.imageData.hasAlpha ? 4 : 3;
this.#config.hints['image-data'] = new Variant('(iiibiiay)', [
hints.imageData.width,
hints.imageData.height,
hints.imageData.width * channel,
hints.imageData.hasAlpha,
8,
channel,
[...hints.imageData.data],
]);
}
if ('resident' in hints && checkTypes.boolean(hints.resident, 'hints.resident is not boolean.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['resident'] = new Variant('b', hints.resident);
}
if ('soundFile' in hints && checkTypes.string(hints.soundFile, 'hints.soundFile is not string.')) {
this.#config.hints['sound-file'] = new Variant('s', hints.soundFile);
}
if ('soundName' in hints && checkTypes.string(hints.soundName, 'hints.soundName is not string.')) {
this.#config.hints['sound-name'] = new Variant('s', hints.soundName);
}
if ('suppressSound' in hints && checkTypes.boolean(hints.suppressSound, 'hints.suppressSound is not boolean.')) {
this.#config.hints['suppress-sound'] = new Variant('b', hints.suppressSound);
}
if ('transient' in hints && checkTypes.boolean(hints.transient, 'hints.transient is not boolean.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['transient'] = new Variant('b', hints.transient);
}
if ('value' in hints && checkTypes.integer(hints.value, 'hints.value is not integer.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['value'] = new Variant('i', hints.value);
}
if ('x' in hints && checkTypes.integer(hints.x, 'hints.x is not integer.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['x'] = new Variant('i', hints.x);
}
if ('y' in hints && checkTypes.integer(hints.y, 'hints.y is not integer.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['y'] = new Variant('i', hints.y);
}
if ('urgency' in hints && checkTypes.integer(hints.urgency, 'hints.urgency is not integer.')) {
// eslint-disable-next-line dot-notation
this.#config.hints['urgency'] = new Variant('y', hints.urgency);
}
}
addAction(text, key, callback) {
const actionCallback = callback === undefined ? key : callback;
const actionKey = callback === undefined ? `__action_key__::${identifier.next().value}` : key;
checkTypes.string(text, 'text is not string.');
checkTypes.string(actionKey, 'key is not string.');
checkTypes.function(actionCallback, 'callback is not function.');
if (this.#actions.has(actionKey)) {
throw new Error(`'${actionKey}' action already exists.`);
}
this.#actions.set(actionKey, {
text,
callback: actionCallback,
});
return actionKey;
}
close() {
if (this.#id !== 0) {
return getInterface()
.then((i) => i.CloseNotification(this.#id));
}
return Promise.resolve();
}
removeAction(key) {
checkTypes.string(key, 'key is not string.');
return this.#actions.delete(key);
}
removeDefaultAction() {
return this.removeAction(ActionKeys.default);
}
setDefaultAction(callback) {
this.addAction('', ActionKeys.default, callback);
}
show() {
const actions = [];
this.#actions.forEach((item, key) => {
actions.push(key, item.text);
});
const params = [
this.#config.appName,
this.#config.replacesId,
this.#config.appIcon,
this.#config.summary,
this.#config.body,
actions,
this.#config.hints,
this.#config.timeout,
];
return new Promise((resolve, reject) => {
getInterface()
.then((i) => {
i.Notify(...params)
.then((id) => {
this.#id = id;
this.#status = 1;
notifierEmitter.emit('push');
this.emit('show', id);
if (Config.closeReplacedNotify && this.#config.replacesId === id) {
notifierEmitter.emit(`${DbusEvents.NotificationClosed}:${id}`, 101);
}
const invoked = this[ActionInvokedSymbol].bind(this);
const inlineReplyInvoked = this[ActionInvokedSymbol].bind(this, ActionKeys.inlineReply);
notifierEmitter.on(`${DbusEvents.ActionInvoked}:${id}`, invoked);
notifierEmitter.on(`${DbusEvents.NotificationReplied}:${id}`, inlineReplyInvoked);
notifierEmitter.once(`${DbusEvents.NotificationClosed}:${id}`, (reason) => {
this.#status = 2;
notifierEmitter.off(`${DbusEvents.ActionInvoked}:${id}`, invoked);
notifierEmitter.off(`${DbusEvents.NotificationReplied}:${id}`, inlineReplyInvoked);
notifierEmitter.emit('pop');
const result = {
id,
reason,
};
this.emit('close', result);
resolve(result);
});
})
.catch(reject);
})
.catch(reject);
});
}
static supportedCapabilities() {
return getInterface()
.then((i) => i.GetCapabilities());
}
}
module.exports = {
Notify,
Config,
disconnectSessionBus,
getInterface,
setInterface,
getSessionBus,
setSessionBus,
};