-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
246 lines (203 loc) · 7.16 KB
/
library.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
'use strict';
const nconf = require.main.require('nconf');
const winston = require.main.require('winston');
const webPush = require('web-push');
const validator = require('validator');
const db = require.main.require('./src/database');
const user = require.main.require('./src/user');
const meta = require.main.require('./src/meta');
const utils = require.main.require('./src/utils');
const translator = require.main.require('./src/translator');
const notifications = require.main.require('./src/notifications');
const controllers = require('./lib/controllers');
const subscriptions = require('./lib/subscriptions');
const routeHelpers = require.main.require('./src/routes/helpers');
const plugin = {};
plugin.init = async (params) => {
const { router, middleware/* , controllers */ } = params;
const accountMiddlewares = [
middleware.exposeUid,
middleware.ensureLoggedIn,
middleware.canViewUsers,
middleware.checkAccountPermissions,
middleware.buildAccountData,
];
await assertVapidConfiguration();
routeHelpers.setupPageRoute(router, '/user/:userslug/web-push', accountMiddlewares, controllers.renderSettings);
routeHelpers.setupAdminPageRoute(router, '/admin/plugins/web-push', controllers.renderAdminPage);
};
plugin.appendConfig = async (config) => {
const { publicKey } = await meta.settings.get('web-push');
config['web-push'] = {
vapidKey: publicKey,
};
return config;
};
plugin.registerServiceWorker = async (data) => {
const { scripts } = data;
scripts.add(`nodebb-plugin-web-push/static/web-push.js`);
return data;
};
async function assertVapidConfiguration() {
let { publicKey, privateKey } = await meta.settings.get('web-push');
if (!publicKey || !privateKey) {
winston.warn('[plugins/web-push] VAPID key pair not found or invalid, regenerating.');
({ publicKey, privateKey } = webPush.generateVAPIDKeys());
await meta.settings.set('web-push', { publicKey, privateKey });
} else {
winston.info('[plugins/web-push] VAPID keys OK.');
}
webPush.setVapidDetails(
nconf.get('url'),
publicKey,
privateKey
);
}
plugin.addRoutes = async ({ router, middleware, helpers }) => {
const middlewares = [
middleware.ensureLoggedIn,
// middleware.admin.checkPrivileges,
];
routeHelpers.setupApiRoute(router, 'post', '/web-push/subscription', middlewares, async (req, res) => {
if (!req.uid) {
return helpers.formatApiResponse(204, res);
}
const { subscription } = req.body;
await subscriptions.add(req.uid, subscription);
helpers.formatApiResponse(200, res);
});
routeHelpers.setupApiRoute(router, 'delete', '/web-push/subscription', middlewares, async (req, res) => {
if (!req.uid) {
return helpers.notAllowed(req, res);
}
const { subscription } = req.body;
await subscriptions.remove(req.uid, subscription);
helpers.formatApiResponse(200, res);
});
routeHelpers.setupApiRoute(router, 'post', '/web-push/test', middlewares, async (req, res) => {
if (!req.uid) {
return helpers.notAllowed(req, res);
}
const { userLang } = await user.getSettings(req.uid);
const { subscription } = req.body;
const payload = await constructPayload({
nid: utils.generateUUID(),
bodyShort: 'Test notification',
bodyLong: 'This is a test message sent from NodeBB',
path: `/me/web-push`,
}, req.uid, userLang);
await webPush.sendNotification(subscription, JSON.stringify(payload));
});
};
plugin.addAdminNavigation = (header) => {
header.plugins.push({
route: '/plugins/web-push',
icon: 'fa-tint',
name: 'Push Notifications (via Push API)',
});
return header;
};
plugin.onNotificationPush = async ({ notification, uidsNotified: uids }) => {
const subs = await subscriptions.list(uids);
uids = uids.filter(uid => subs.get(uid).size);
const userSettings = await user.getMultipleUserSettings(uids);
// Save recipients by nid (for use by .rescind)
const refKey = `web-push:nid:${notification.mergeId || notification.nid}:uids`;
await db.setAdd(refKey, uids);
db.pexpire(refKey, 1000 * 60 * 60 * 48); // only track last 48 hours
let payloads = await Promise.all(uids.map(async (uid, idx) => {
const payload = await constructPayload(notification, uid, userSettings[idx].userLang);
return [uid, payload];
}));
payloads = new Map(payloads);
payloads.forEach((payload, uid) => {
const targets = subs.get(uid);
targets.forEach(async (subscription) => {
try {
await webPush.sendNotification(subscription, JSON.stringify(payload));
} catch (e) {
// Errored — remove subscription from user
winston.info(`[plugins/web-push] Push failed: ${e.code}; ${e.message}; statusCode: ${e.statusCode}`);
// subscriptions.remove(uid, subscription);
}
});
});
};
plugin.onNotificationRescind = async ({ nids }) => {
const notificationKeys = nids.map(nid => `notifications:${nid}`);
let mergeIds = await db.getObjectsFields(notificationKeys, ['mergeId']);
mergeIds = mergeIds.map(o => o.mergeId);
// Favour mergeIds over nids, then eliminate dupes
const tags = new Set(notificationKeys.map((key, i) => mergeIds[i] || key));
const recipients = await db.getSetsMembers(Array.from(tags).map(tag => `web-push:nid:${tag}:uids`));
Promise.all(Array.from(tags).map(async (tag, idx) => {
let subs = await subscriptions.list(recipients[idx]);
subs = new Set(...Object.values(Object.fromEntries(subs))); // wtf
if (subs.size) {
subs.forEach(async (subscription) => {
await webPush.sendNotification(subscription, JSON.stringify({ tag }));
});
}
}));
};
plugin.addProfileItem = async (data) => {
const title = await translator.translate('[[web-push:profile.label]]');
data.links.push({
id: 'web-push',
route: 'web-push',
icon: 'fa-bell-o',
name: title,
visibility: {
self: true,
other: false,
moderator: false,
globalMod: false,
admin: false,
},
});
return data;
};
async function constructPayload(notification, uid, lang) {
let { maxLength, icon, badge } = await meta.settings.get('web-push');
maxLength = parseInt(maxLength, 10) || 256;
// i18n/rtl
if (!lang) {
lang = meta.config.defaultLang || 'en-GB';
}
const dir = await translator.translate('[[language:dir]]', lang);
// Merge with related unread notifications
if (notification.mergeId) {
const related = await notifications.findRelated([notification.mergeId], `uid:${uid}:notifications:unread`);
const merged = await notifications.getMultiple(related).then(notifications.merge);
if (merged.length) {
notification = merged.pop();
}
}
const { nid, mergeId, bodyShort, bodyLong, path } = notification;
let [title, body] = await translator.translateKeys([bodyShort, bodyLong], lang);
([title, body] = [title, body].map(str => validator.unescape(utils.stripHTMLTags(str))));
const tag = mergeId || nid;
const url = `${nconf.get('url')}${path}`;
// Handle empty bodyLong
if (!bodyLong) {
body = title;
title = meta.config.title || 'NodeBB';
}
// Truncate body if needed
if (body.length > maxLength) {
body = `${body.slice(0, maxLength)}…`;
}
icon = icon || `${nconf.get('url')}/apple-touch-icon`;
if (!badge) { // badge fallbacks
badge = `${nconf.get('url')}${meta.config['brand:maskableIcon'] || '/apple-touch-icon'}`;
}
return {
title,
body,
tag,
lang,
dir,
data: { url, icon, badge },
};
}
module.exports = plugin;