forked from julianlam/nodebb-plugin-mentions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
384 lines (331 loc) · 10.6 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
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
'use strict';
var async = require('async');
var winston = module.parent.require('winston');
var XRegExp = require('xregexp');
var validator = require('validator');
var nconf = module.parent.require('nconf');
var Topics = module.parent.require('./topics');
var User = module.parent.require('./user');
var Groups = module.parent.require('./groups');
var Notifications = module.parent.require('./notifications');
var Privileges = module.parent.require('./privileges');
var Meta = module.parent.require('./meta');
var Utils = module.parent.require('../public/src/utils');
var batch = module.parent.require('./batch');
var SocketPlugins = module.parent.require('./socket.io/plugins');
var regex = XRegExp('(?:^|\\s)(@[\\p{L}\\d\\-_.]+)', 'g'); // used in post text transform, accounts for HTML
var rawRegex = XRegExp('(?:^|\\s)(@[\\p{L}\\d\-_.]+)', 'g'); // used in notifications, as raw text is passed in this hook
var isLatinMention = /@[\w\d\-_.]+$/;
var removePunctuationSuffix = function(string) {
return string.replace(/[!?.]*$/, '');
};
var Entities = require('html-entities').XmlEntities;
var entities = new Entities();
var Mentions = {
_settings: {},
_defaults: {
autofillGroups: 'off',
disableGroupMentions: '[]',
}
};
SocketPlugins.mentions = {};
Mentions.init = function (data, callback) {
var hostMiddleware = module.parent.require('./middleware');
var controllers = require('./controllers');
data.router.get('/admin/plugins/mentions', hostMiddleware.admin.buildHeader, controllers.renderAdminPage);
data.router.get('/api/admin/plugins/mentions', controllers.renderAdminPage);
// Retrieve settings
Meta.settings.get('mentions', function (err, settings) {
Object.assign(Mentions._settings, Mentions._defaults, settings);
callback();
});
};
Mentions.addAdminNavigation = function (header, callback) {
header.plugins.push({
route: '/plugins/mentions',
name: 'Mentions'
});
callback(null, header);
};
function getNoMentionGroups() {
var noMentionGroups = ['registered-users', 'guests'];
try {
noMentionGroups = noMentionGroups.concat(JSON.parse(Mentions._settings.disableGroupMentions));
} catch (err) {
winston.error(err);
}
return noMentionGroups;
}
Mentions.notify = function(data) {
var postData = data.post;
var cleanedContent = Mentions.clean(postData.content, true, true, true);
var matches = cleanedContent.match(rawRegex);
if (!matches) {
return;
}
var noMentionGroups = getNoMentionGroups();
matches = matches.map(function(match) {
return Utils.slugify(match);
}).filter(function(match, index, array) {
return match && array.indexOf(match) === index && noMentionGroups.indexOf(match) === -1;
});
if (!matches.length) {
return;
}
async.parallel({
userRecipients: function(next) {
async.filter(matches, User.existsBySlug, next);
},
groupRecipients: function(next) {
async.filter(matches, Groups.existsBySlug, next);
}
}, function(err, results) {
if (err) {
return;
}
if (!results.userRecipients.length && !results.groupRecipients.length) {
return;
}
async.parallel({
topic: function(next) {
Topics.getTopicFields(postData.tid, ['title', 'cid'], next);
},
author: function(next) {
User.getUserField(postData.uid, 'username', next);
},
uids: function(next) {
async.map(results.userRecipients, function(slug, next) {
User.getUidByUserslug(slug, next);
}, next);
},
groupData: function(next) {
getGroupMemberUids(results.groupRecipients, next);
},
topicFollowers: function(next) {
Topics.getFollowers(postData.tid, next);
}
}, function(err, results) {
if (err) {
return;
}
var title = entities.decode(results.topic.title);
var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
var uids = results.uids.filter(function(uid, index, array) {
return array.indexOf(uid) === index && parseInt(uid, 10) !== parseInt(postData.uid, 10) && results.topicFollowers.indexOf(uid.toString()) === -1;
});
var groupMemberUids = {};
results.groupData.groupNames.forEach(function(groupName, index) {
results.groupData.groupMembers[index] = results.groupData.groupMembers[index].filter(function(uid) {
if (!uid || groupMemberUids[uid]) {
return false;
}
groupMemberUids[uid] = 1;
return uids.indexOf(uid) === -1 &&
parseInt(uid, 10) !== parseInt(postData.uid, 10) &&
results.topicFollowers.indexOf(uid.toString()) === -1;
});
});
sendNotificationToUids(postData, uids, 'user', '[[notifications:user_mentioned_you_in, ' + results.author + ', ' + titleEscaped + ']]');
results.groupData.groupNames.forEach(function(groupName, index) {
var memberUids = results.groupData.groupMembers[index];
sendNotificationToUids(postData, memberUids, groupName, '[[notifications:user_mentioned_group_in, ' + results.author + ', ' + groupName + ', ' + titleEscaped + ']]');
});
});
});
};
Mentions.addFilters = function (data, callback) {
data.regularFilters.push({ name: '[[notifications:mentions]]', filter: 'mention' });
callback(null, data);
};
Mentions.notificationTypes = function (data, callback) {
data.types.push('notificationType_mention');
callback(null, data);
};
function sendNotificationToUids(postData, uids, nidType, notificationText) {
if (!uids.length) {
return;
}
var filteredUids = [];
var notification;
async.waterfall([
function (next) {
createNotification(postData, nidType, notificationText, next);
},
function (_notification, next) {
notification = _notification;
if (!notification) {
return next();
}
batch.processArray(uids, function (uids, next) {
async.waterfall([
function(next) {
Privileges.topics.filterUids('read', postData.tid, uids, next);
},
function(_uids, next) {
Topics.filterIgnoringUids(postData.tid, _uids, next);
},
function(_uids, next) {
if (!_uids.length) {
return next();
}
filteredUids = filteredUids.concat(_uids);
next();
}
], next);
}, {
interval: 1000,
batch: 500,
}, next);
},
], function (err) {
if (err) {
return winston.error(err);
}
if (notification) {
Notifications.push(notification, filteredUids);
}
});
}
function createNotification(postData, nidType, notificationText, callback) {
Notifications.create({
type: 'mention',
bodyShort: notificationText,
bodyLong: postData.content,
nid: 'tid:' + postData.tid + ':pid:' + postData.pid + ':uid:' + postData.uid + ':' + nidType,
pid: postData.pid,
tid: postData.tid,
from: postData.uid,
path: '/post/' + postData.pid,
importance: 6
}, callback);
}
function getGroupMemberUids(groupRecipients, callback) {
async.map(groupRecipients, function(slug, next) {
Groups.getGroupNameByGroupSlug(slug, next);
}, function(err, groupNames) {
if (err) {
return callback(err);
}
async.map(groupNames, function(groupName, next) {
Groups.getMembers(groupName, 0, -1, next);
}, function(err, groupMembers) {
if (err) {
return callback(err);
}
callback(null, {groupNames: groupNames, groupMembers: groupMembers});
});
});
}
Mentions.parsePost = function(data, callback) {
if (!data || !data.postData || !data.postData.content) {
return callback(null, data);
}
Mentions.parseRaw(data.postData.content, function(err, content) {
if (err) {
return callback(err);
}
data.postData.content = content;
callback(null, data);
});
};
Mentions.parseRaw = function(content, callback) {
var splitContent = Mentions.split(content, false, false, true);
var matches = [];
splitContent.forEach(function(cleanedContent, i) {
if ((i & 1) === 0) {
matches = matches.concat(cleanedContent.match(regex) || []);
}
});
if (!matches.length) {
return callback(null, content);
}
matches = matches.filter(function(cur, idx) {
// Eliminate duplicates
return idx === matches.indexOf(cur);
}).map(function(match) {
/**
* Javascript-favour of regex does not support lookaround,
* so need to clean up the cruft by discarding everthing
* before the @
*/
var atIndex = match.indexOf('@');
return atIndex !== 0 ? match.slice(atIndex) : match;
});
async.each(matches, function(match, next) {
var slug = Utils.slugify(match.slice(1));
match = removePunctuationSuffix(match);
async.parallel({
groupExists: async.apply(Groups.existsBySlug, slug),
uid: async.apply(User.getUidByUserslug, slug)
}, function(err, results) {
if (err) {
return next(err);
}
if (results.uid || results.groupExists) {
var regex = isLatinMention.test(match)
? new RegExp('(?:^|\\s)' + match + '\\b', 'g')
: new RegExp('(?:^|\\s)' + match, 'g');
splitContent = splitContent.map(function(c, i) {
if ((i & 1) === 1) {
return c;
}
return c.replace(regex, function(match) {
// Again, cleaning up lookaround leftover bits
var atIndex = match.indexOf('@');
var plain = match.slice(0, atIndex);
match = match.slice(atIndex);
var str = results.uid
? '<a class="plugin-mentions-user plugin-mentions-a" href="' + nconf.get('url') + '/uid/' + results.uid + '">' + match + '</a>'
: '<a class="plugin-mentions-group plugin-mentions-a" href="' + nconf.get('url') + '/groups/' + slug + '">' + match + '</a>';
return plain + str;
});
});
}
next();
});
}, function(err) {
callback(err, splitContent.join(''));
});
};
Mentions.clean = function(input, isMarkdown, stripBlockquote, stripCode) {
var split = Mentions.split(input, isMarkdown, stripBlockquote, stripCode);
split = split.filter(function(e, i) {
// only keep non-code/non-blockquote
return (i & 1) === 0;
});
return split.join('');
};
Mentions.split = function(input, isMarkdown, splitBlockquote, splitCode) {
if (!input) {
return [];
}
var matchers = [isMarkdown ? '\\[.*?\\]\\(.*?\\)' : '<a[\\s\\S]*?</a>|<[^>]+>'];
if (splitBlockquote) {
matchers.push(isMarkdown ? '^>.*$' : '^<blockquote>.*?</blockquote>');
}
if (splitCode) {
matchers.push(isMarkdown ? '`[^`\n]+`' : '<code[\\s\\S]*?</code>');
}
return input.split(new RegExp('(' + matchers.join('|') + ')', 'gm'));
};
/*
WebSocket methods
*/
SocketPlugins.mentions.listGroups = function(socket, data, callback) {
if (Mentions._settings.autofillGroups === 'off') {
return callback(null, []);
}
Groups.getGroups('groups:visible:createtime', 0, -1, function(err, groups) {
if (err) {
return callback(err);
}
var noMentionGroups = getNoMentionGroups();
groups = groups.filter(function(groupName) {
return groupName && !noMentionGroups.includes(groupName);
}).map(function(groupName) {
return validator.escape(groupName);
});
callback(null, groups);
});
};
module.exports = Mentions;