-
-
Notifications
You must be signed in to change notification settings - Fork 784
/
Copy pathconverse-notification.js
384 lines (341 loc) · 15.9 KB
/
converse-notification.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
384
/**
* @module converse-notification
* @copyright 2020, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
import log from "@converse/headless/log";
import st from "@converse/headless/utils/stanza";
import { __ } from '@converse/headless/i18n';
import { _converse, api, converse } from "@converse/headless/converse-core";
const { $iq, Strophe, sizzle } = converse.env;
const u = converse.env.utils;
const supports_html5_notification = "Notification" in window;
function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
Strophe.addNamespace('WEBPUSH', 'urn:xmpp:webpush:0');
converse.plugins.add('converse-notification', {
dependencies: ["converse-chatboxes", "converse-disco"],
initialize () {
/* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery.
*/
api.settings.extend({
notify_all_room_messages: false,
show_desktop_notifications: true,
show_chat_state_notifications: false,
chatstate_notification_blacklist: [],
// ^ a list of JIDs to ignore concerning chat state notifications
play_sounds: true,
sounds_path: api.settings.get("assets_path")+'/sounds/',
notification_icon: 'logo/conversejs-filled.svg',
notification_delay: 5000
});
_converse.shouldNotifyOfGroupMessage = function (message) {
/* Is this a group message worthy of notification?
*/
let notify_all = api.settings.get('notify_all_room_messages');
const jid = message.getAttribute('from'),
resource = Strophe.getResourceFromJid(jid),
room_jid = Strophe.getBareJidFromJid(jid),
sender = resource && Strophe.unescapeNode(resource) || '';
if (sender === '' || message.querySelectorAll('delay').length > 0) {
return false;
}
const room = _converse.chatboxes.get(room_jid);
const body = message.querySelector('body');
if (body === null) {
return false;
}
const mentioned = (new RegExp(`\\b${room.get('nick')}\\b`)).test(body.textContent);
notify_all = notify_all === true ||
(Array.isArray(notify_all) && notify_all.includes(room_jid));
if (sender === room.get('nick') || (!notify_all && !mentioned)) {
return false;
}
return true;
};
_converse.isMessageToHiddenChat = function (message) {
if (_converse.isUniView()) {
const jid = Strophe.getBareJidFromJid(message.getAttribute('from'));
const view = _converse.chatboxviews.get(jid);
if (view) {
return view.model.get('hidden') || _converse.windowState === 'hidden' || !u.isVisible(view.el);
}
return true;
}
return _converse.windowState === 'hidden';
}
_converse.shouldNotifyOfMessage = function (message) {
const forwarded = message.querySelector('forwarded');
if (forwarded !== null) {
return false;
} else if (message.getAttribute('type') === 'groupchat') {
return _converse.shouldNotifyOfGroupMessage(message);
} else if (st.isHeadline(message)) {
// We want to show notifications for headline messages.
return _converse.isMessageToHiddenChat(message);
}
const is_me = Strophe.getBareJidFromJid(message.getAttribute('from')) === _converse.bare_jid;
return !u.isOnlyChatStateNotification(message) &&
!u.isOnlyMessageDeliveryReceipt(message) &&
!is_me &&
(api.settings.get('show_desktop_notifications') === 'all' || _converse.isMessageToHiddenChat(message));
};
/**
* Plays a notification sound
* @private
* @method _converse#playSoundNotification
*/
_converse.playSoundNotification = function () {
if (api.settings.get('play_sounds') && window.Audio !== undefined) {
const audioOgg = new Audio(api.settings.get('sounds_path')+"msg_received.ogg");
const canPlayOgg = audioOgg.canPlayType('audio/ogg');
if (canPlayOgg === 'probably') {
return audioOgg.play();
}
const audioMp3 = new Audio(api.settings.get('sounds_path')+"msg_received.mp3");
const canPlayMp3 = audioMp3.canPlayType('audio/mp3');
if (canPlayMp3 === 'probably') {
audioMp3.play();
} else if (canPlayOgg === 'maybe') {
audioOgg.play();
} else if (canPlayMp3 === 'maybe') {
audioMp3.play();
}
}
};
_converse.areDesktopNotificationsEnabled = function () {
return supports_html5_notification &&
api.settings.get('show_desktop_notifications') &&
Notification.permission === "granted";
};
/**
* Shows an HTML5 Notification with the passed in message
* @private
* @method _converse#showMessageNotification
* @param { String } message
*/
_converse.showMessageNotification = function (message) {
if (!_converse.areDesktopNotificationsEnabled()) {
return;
}
let title, roster_item;
const full_from_jid = message.getAttribute('from'),
from_jid = Strophe.getBareJidFromJid(full_from_jid);
if (message.getAttribute('type') === 'headline') {
if (!from_jid.includes('@') || api.settings.get("allow_non_roster_messaging")) {
title = __("Notification from %1$s", from_jid);
} else {
return;
}
} else if (!from_jid.includes('@')) {
// workaround for Prosody which doesn't give type "headline"
title = __("Notification from %1$s", from_jid);
} else if (message.getAttribute('type') === 'groupchat') {
title = __("%1$s says", Strophe.getResourceFromJid(full_from_jid));
} else {
if (_converse.roster === undefined) {
log.error("Could not send notification, because roster is undefined");
return;
}
roster_item = _converse.roster.get(from_jid);
if (roster_item !== undefined) {
title = __("%1$s says", roster_item.getDisplayName());
} else {
if (api.settings.get("allow_non_roster_messaging")) {
title = __("%1$s says", from_jid);
} else {
return;
}
}
}
// TODO: we should suppress notifications if we cannot decrypt
// the message...
const body = sizzle(`encrypted[xmlns="${Strophe.NS.OMEMO}"]`, message).length ?
__('OMEMO Message received') :
message.querySelector('body')?.textContent;
if (!body) {
return;
}
const n = new Notification(title, {
'body': body,
'lang': _converse.locale,
'icon': api.settings.get('notification_icon'),
'requireInteraction': !_converse.notification_delay
});
if (api.settings.get('notification_delay')) {
setTimeout(n.close.bind(n), api.settings.get('notification_delay'));
}
n.onclick = function (event) {
event.preventDefault();
window.focus();
const chat = _converse.chatboxes.get(from_jid);
chat.maybeShow(true);
}
n.onclick.bind(_converse);
};
_converse.showChatStateNotification = function (contact) {
/* Creates an HTML5 Notification to inform of a change in a
* contact's chat state.
*/
if (_converse.chatstate_notification_blacklist.includes(contact.jid)) {
// Don't notify if the user is being ignored.
return;
}
const chat_state = contact.chat_status;
let message = null;
if (chat_state === 'offline') {
message = __('has gone offline');
} else if (chat_state === 'away') {
message = __('has gone away');
} else if ((chat_state === 'dnd')) {
message = __('is busy');
} else if (chat_state === 'online') {
message = __('has come online');
}
if (message === null) {
return;
}
const n = new Notification(contact.getDisplayName(), {
body: message,
lang: _converse.locale,
icon: _converse.notification_icon
});
setTimeout(n.close.bind(n), 5000);
};
_converse.showContactRequestNotification = function (contact) {
const n = new Notification(contact.getDisplayName(), {
body: __('wants to be your contact'),
lang: _converse.locale,
icon: _converse.notification_icon
});
setTimeout(n.close.bind(n), 5000);
};
_converse.showFeedbackNotification = function (data) {
if (data.klass === 'error' || data.klass === 'warn') {
const n = new Notification(data.subject, {
body: data.message,
lang: _converse.locale,
icon: _converse.notification_icon
});
setTimeout(n.close.bind(n), 5000);
}
};
_converse.handleChatStateNotification = function (contact) {
/* Event handler for on('contactPresenceChanged').
* Will show an HTML5 notification to indicate that the chat
* status has changed.
*/
if (_converse.areDesktopNotificationsEnabled() && api.settings.get('show_chat_state_notifications')) {
_converse.showChatStateNotification(contact);
}
};
_converse.handleMessageNotification = function (data) {
/* Event handler for the on('message') event. Will call methods
* to play sounds and show HTML5 notifications.
*/
const message = data.stanza;
if (!_converse.shouldNotifyOfMessage(message)) {
return false;
}
/**
* Triggered when a notification (sound or HTML5 notification) for a new
* message has will be made.
* @event _converse#messageNotification
* @type { XMLElement }
* @example _converse.api.listen.on('messageNotification', stanza => { ... });
*/
api.trigger('messageNotification', message);
_converse.playSoundNotification();
_converse.showMessageNotification(message);
};
_converse.handleContactRequestNotification = function (contact) {
if (_converse.areDesktopNotificationsEnabled(true)) {
_converse.showContactRequestNotification(contact);
}
};
_converse.handleFeedback = function (data) {
if (_converse.areDesktopNotificationsEnabled(true)) {
_converse.showFeedbackNotification(data);
}
};
_converse.requestPermission = function () {
if (supports_html5_notification && !['denied', 'granted'].includes(Notification.permission)) {
// Ask user to enable HTML5 notifications
Notification.requestPermission();
}
};
_converse.sendWebPushCredentials = function (subscription) {
const iq = $iq({type: 'set'})
.c('enable', {xmlns: Strophe.NS.WEBPUSH})
;
subscription.getKey('auth');
subscription.getKey('p256dh');
iq.c('endpoint').t(subscription.endpoint).up();
iq.c('auth').t(buf2hex(subscription.getKey('auth'))).up();
iq.c('p256dh').t(buf2hex(subscription.getKey('p256dh'))).up();
return _converse.api.sendIQ(iq);
};
_converse.api.listen.on('pluginsInitialized', function () {
// We only register event handlers after all plugins are
// registered, because other plugins might override some of our
// handlers.
api.listen.on('contactRequest', _converse.handleContactRequestNotification);
api.listen.on('contactPresenceChanged', _converse.handleChatStateNotification);
api.listen.on('message', _converse.handleMessageNotification);
api.listen.on('feedback', _converse.handleFeedback);
api.listen.on('connected', _converse.requestPermission);
});
_converse.api.listen.on('connected', async function () {
// only bother continuing if the server supports webpush
if (!(await _converse.api.disco.supports(Strophe.NS.WEBPUSH, _converse.bare_jid))) {
return;
}
// get the server's VAPID public key from disco
const fields = await _converse.api.disco.getFields(_converse.bare_jid);
let vapid_key = fields.findWhere({'var': "webpush#public-key"})?.attributes.value;
// XXX: reattaching an existing BOSH session makes disco.getFields() empty?!
if (!vapid_key) {
vapid_key = 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhxZpb8yIVc/2hNesGLGAxEakyYy0MqEetjgL7BIOm8ybhVKxapKqNXjXJ+NOO5/b0Z0UuBg/HynGnf0xKKNhBQ==';
}
const converted_vapid_key = urlBase64ToUint8Array(vapid_key);
navigator.serviceWorker.register('./worker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
});
navigator.serviceWorker.ready
.then(function(registration) {
return registration.pushManager.getSubscription()
.then(subscription => {
if (subscription) {
console.log("existing", subscription);
_converse.sendWebPushCredentials(subscription);
return;
}
return registration.pushManager.subscribe({
applicationServerKey: converted_vapid_key,
userVisibleOnly: true,
});
});
}).then(function(subscription) {
if (subscription) {
console.log("new", subscription);
_converse.sendWebPushCredentials(subscription);
}
});
});
_converse.api.listen.on('addClientFeatures', () => _converse.api.disco.own.features.add(Strophe.NS.WEBPUSH));
}
});