-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlibrary.js
More file actions
750 lines (676 loc) · 26 KB
/
Copy pathlibrary.js
File metadata and controls
750 lines (676 loc) · 26 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
'use strict';
const nconf = require.main.require('nconf');
const winston = require.main.require('winston');
const db = require.main.require('./src/database');
const user = require.main.require('./src/user');
const groups = require.main.require('./src/groups');
const meta = require.main.require('./src/meta');
const notifications = require.main.require('./src/notifications');
const routeHelpers = require.main.require('./src/routes/helpers');
const controllerHelpers = require.main.require('./src/controllers/helpers');
const topics = require.main.require('./src/topics');
const privileges = require.main.require('./src/privileges');
const pagination = require.main.require('./src/pagination');
const helpers = require.main.require('./src/controllers/helpers');
const translator = require.main.require('./src/translator');
const controllers = require('./lib/controllers');
const plugin = {};
const assigneeFields = ['assignee', 'assigneeType', 'assigneeStatus', 'assigneeResolvedBy', 'assigneeResolvedAt'];
plugin.init = async (params) => {
const { router } = params;
const middleware = require.main.require('./src/middleware');
routeHelpers.setupAdminPageRoute(router, '/admin/plugins/internalnotes', controllers.renderAdminPage);
routeHelpers.setupPageRoute(router, '/assigned', [middleware.ensureLoggedIn], plugin.renderAssignedPage);
// Runs hourly so the ACP hour/timezone settings apply without re-registering the job
const cron = require.main.require('./src/cron');
await cron.addJob({
name: 'internalnotes:stale-reminders',
cronTime: '0 * * * *',
onTick: sendStaleReminders,
});
};
plugin.addRoutes = async ({ router, middleware, helpers }) => {
const ensurePrivileged = async (req, res, next) => {
const allowed = await canViewNotes(req.uid);
if (!allowed) {
return controllerHelpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]'));
}
next();
};
// --- Assignment routes (registered before /:noteId to avoid param collision) ---
routeHelpers.setupApiRoute(router, 'get', '/internalnotes/:tid/assign', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const assignee = await getAssignee(req.params.tid);
helpers.formatApiResponse(200, res, { assignee });
});
routeHelpers.setupApiRoute(router, 'put', '/internalnotes/:tid/assign', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const { type, id } = req.body;
if (!type || !id) {
return helpers.formatApiResponse(400, res, new Error('[[error:invalid-data]]'));
}
const assignee = await assignTopic(req.params.tid, type, id, req.uid);
helpers.formatApiResponse(200, res, { assignee });
});
routeHelpers.setupApiRoute(router, 'delete', '/internalnotes/:tid/assign', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
await unassignTopic(req.params.tid);
helpers.formatApiResponse(200, res, {});
});
// --- Assignment status (open/resolved) ---
routeHelpers.setupApiRoute(router, 'put', '/internalnotes/:tid/status', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const assignee = await setAssignmentStatus(req.params.tid, req.body.status, req.uid);
helpers.formatApiResponse(200, res, { assignee });
});
// --- Assignable users (quick-select list; must be before /:tid routes) ---
routeHelpers.setupApiRoute(router, 'get', '/internalnotes/assignable-users', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const users = await getAssignableUsers();
helpers.formatApiResponse(200, res, { users });
});
// --- Group search route ---
routeHelpers.setupApiRoute(router, 'get', '/internalnotes/groups/search', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const query = (req.query.query || '').trim();
if (query.length < 1) {
return helpers.formatApiResponse(200, res, { groups: [] });
}
const groupList = await groups.search(query, { sort: 'count', filterHidden: true });
const results = groupList
.filter(g => g && !groups.isPrivilegeGroup(g.name))
.slice(0, 15)
.map(g => ({
name: g.name,
slug: g.slug,
memberCount: g.memberCount,
icon: g.icon || '',
labelColor: g.labelColor || '',
}));
helpers.formatApiResponse(200, res, { groups: results });
});
// --- Notes routes ---
routeHelpers.setupApiRoute(router, 'get', '/internalnotes/:tid', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const notes = await getNotes(req.params.tid);
helpers.formatApiResponse(200, res, { notes });
});
routeHelpers.setupApiRoute(router, 'post', '/internalnotes/:tid', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
const { content } = req.body;
if (!content || !content.trim()) {
return helpers.formatApiResponse(400, res, new Error('[[error:invalid-data]]'));
}
const note = await createNote(req.params.tid, req.uid, content.trim());
helpers.formatApiResponse(200, res, { note });
});
routeHelpers.setupApiRoute(router, 'delete', '/internalnotes/:tid/:noteId', [middleware.ensureLoggedIn, ensurePrivileged], async (req, res) => {
await deleteNote(req.params.tid, req.params.noteId);
helpers.formatApiResponse(200, res, {});
});
};
plugin.addAdminNavigation = (header) => {
header.plugins.push({
route: '/plugins/internalnotes',
icon: 'fa-sticky-note',
name: 'Internal Notes',
});
return header;
};
plugin.addInternalNotesToTopic = async (data) => {
if (!data || !data.topic) {
return data;
}
const allowed = await canViewNotes(data.uid);
data.topic.canViewInternalNotes = allowed;
data.canViewInternalNotes = allowed; // so client can read from ajaxify.data.canViewInternalNotes
if (allowed) {
data.topic.assignee = await getAssignee(data.topic.tid);
data.topic.internalNoteCount = await db.sortedSetCard(`internalnotes:tid:${data.topic.tid}`);
}
return data;
};
plugin.addInternalNotesToTopics = async (data) => {
if (!data || !Array.isArray(data.topics) || !data.topics.length) {
return data;
}
const uid = data.uid || 0;
const allowed = await canViewNotes(uid);
if (!allowed) {
return data;
}
const assignees = await Promise.all(data.topics.map(t => getAssignee(t.tid)));
const noteCounts = await Promise.all(data.topics.map(t => db.sortedSetCard(`internalnotes:tid:${t.tid}`)));
data.topics.forEach((topic, i) => {
topic.canViewInternalNotes = true;
topic.assignee = assignees[i];
topic.internalNoteCount = noteCounts[i];
});
return data;
};
plugin.purgeTopicNotes = async ({ topics }) => {
if (!Array.isArray(topics) || !topics.length) {
return;
}
await Promise.all(topics.map(async (topic) => {
if (!topic || !topic.tid) {
return;
}
const tid = topic.tid;
await removeTidFromAssigneeSet(tid);
const noteIds = await db.getSortedSetRange(`internalnotes:tid:${tid}`, 0, -1);
const keys = noteIds.map(id => `internalnote:${id}`);
await db.deleteAll(keys);
await db.delete(`internalnotes:tid:${tid}`);
await db.deleteObjectFields(`topic:${tid}`, assigneeFields);
}));
};
plugin.addNavigation = (menu) => {
menu = menu.concat([{
route: '/assigned',
title: '[[internalnotes:menu.assigned]]',
iconClass: 'fa-user-check',
textClass: 'visible-xs-inline',
text: '[[internalnotes:menu.assigned]]',
}]);
return menu;
};
// --- Widget: Internal Notes & Assign Topic in sidebar (topic page only) ---
plugin.defineWidgets = (widgets) => {
widgets.push({
widget: 'internalnotes_sidebar',
name: 'Internal Notes & Assign Topic',
description: 'Shows Internal Notes and Assign Topic buttons for privileged users on topic pages. Add this widget to the Global Sidebar (the right sidebar with notifications, search, drafts, chat).',
content: '', // no admin config
});
return widgets;
};
plugin.renderInternalNotesWidget = async (widget) => {
// Show only on topic pages. Widget can be in:
// - Topic template sidebar (template === 'topic'), or
// - Global Sidebar (template === 'global') — same right sidebar as notifications/search/drafts/chat
const templateName = (widget.templateData && widget.templateData.template && widget.templateData.template.name) ||
(widget.area && widget.area.template) || '';
const path = (widget.req && widget.req.path) ? widget.req.path : (widget.area && widget.area.url) || '';
const isTopicPage = String(templateName) === 'topic' ||
(String(templateName) === 'global' && /^\/topic\//.test(String(path)));
if (!isTopicPage) {
widget.html = '';
return widget;
}
const uid = widget.req && widget.req.uid ? widget.req.uid : 0;
const allowed = await canViewNotes(uid);
if (!allowed) {
widget.html = '';
return widget;
}
const [notesLabel, assignLabel] = await Promise.all([
new Promise((resolve) => translator.translate('[[internalnotes:thread-tool-notes]]', resolve)),
new Promise((resolve) => translator.translate('[[internalnotes:thread-tool-assign]]', resolve)),
]);
const escapeHtml = (str) => {
if (str == null) return '';
const s = String(str);
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
widget.html = `
<div class="internal-notes-sidebar-actions mb-3">
<div class="btn-group-vertical w-100 d-flex flex-column gap-2" role="group">
<button type="button" class="btn btn-sm btn-outline-warning toggle-internal-notes w-100 text-start">
<i class="fa fa-sticky-note me-1"></i> ${escapeHtml(notesLabel)}
</button>
<button type="button" class="btn btn-sm btn-outline-primary assign-topic-user w-100 text-start">
<i class="fa fa-user-plus me-1"></i> ${escapeHtml(assignLabel)}
</button>
</div>
</div>`;
return widget;
};
plugin.renderAssignedPage = async (req, res) => {
const page = Math.max(1, parseInt(req.query.page, 10) || 1);
const statusFilter = ['open', 'resolved', 'all'].includes(req.query.status) ? req.query.status : 'open';
const uid = req.uid;
const [settings, tidsAll] = await Promise.all([
user.getSettings(uid),
getAssignedTids(uid),
]);
let tids = await privileges.topics.filterTids('read', tidsAll, uid);
// Partition by assignment status so the page can show Open/Resolved tabs
const statuses = await db.getObjectsFields(tids.map(tid => `topic:${tid}`), ['assigneeStatus']);
const counts = { open: 0, resolved: 0, all: tids.length };
const byStatus = { open: [], resolved: [] };
tids.forEach((tid, i) => {
const s = (statuses[i] && statuses[i].assigneeStatus === 'resolved') ? 'resolved' : 'open';
counts[s] += 1;
byStatus[s].push(tid);
});
if (statusFilter !== 'all') {
tids = byStatus[statusFilter];
}
const start = Math.max(0, (page - 1) * settings.topicsPerPage);
const stop = start + settings.topicsPerPage - 1;
const pageTids = tids.slice(start, stop + 1);
const topicsData = await topics.getTopicsByTids(pageTids, uid);
topics.calculateTopicIndices(topicsData, start);
const pageCount = Math.max(1, Math.ceil(tids.length / settings.topicsPerPage));
const data = {
topics: topicsData,
title: '[[internalnotes:menu.assigned]]',
breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[internalnotes:menu.assigned]]' }]),
pagination: pagination.create(page, pageCount, { status: statusFilter }),
internalnotesAssignedPage: true,
internalnotesStatusFilter: statusFilter,
internalnotesStatusCounts: counts,
};
res.render('recent', data);
};
// --- Permission helpers ---
async function canViewNotes(uid) {
if (parseInt(uid, 10) <= 0) {
return false;
}
const [isAdmin, isGlobalMod] = await Promise.all([
user.isAdministrator(uid),
user.isGlobalModerator(uid),
]);
if (isAdmin) {
return true;
}
const settings = await meta.settings.get('internalnotes');
if (settings.allowGlobalMods === 'on' && isGlobalMod) {
return true;
}
if (settings.allowCategoryMods === 'on') {
const isModOfAny = await user.isModeratorOfAnyCategory(uid);
return isModOfAny;
}
return false;
}
/** Returns users who can be assigned (admins and, per settings, global mods and/or category mods). */
async function getAssignableUsers() {
const settings = await meta.settings.get('internalnotes');
const uidSet = new Set();
// Administrators (always)
let adminUids = [];
try {
adminUids = await groups.getMembers('administrators', 0, -1);
} catch (_e) {
// ignore
}
adminUids.forEach((uid) => uidSet.add(parseInt(uid, 10)));
// Global moderators (if enabled)
if (settings.allowGlobalMods === 'on') {
let globalModUids = [];
try {
globalModUids = await groups.getMembers('Global Moderators', 0, -1);
} catch (_e) {
// ignore
}
globalModUids.forEach((uid) => uidSet.add(parseInt(uid, 10)));
}
// Category moderators (if enabled)
if (settings.allowCategoryMods === 'on') {
try {
const categories = require.main.require('./src/categories');
const cids = await categories.getAllCidsFromSet ? await categories.getAllCidsFromSet() : await db.getSortedSetRange('categories:cid', 0, -1);
const privilegesModule = require.main.require('./src/privileges');
const getModeratorUids = privilegesModule.categories && privilegesModule.categories.getModeratorUids;
if (getModeratorUids && Array.isArray(cids) && cids.length) {
for (const cid of cids) {
const uids = await getModeratorUids(cid);
if (Array.isArray(uids)) {
uids.forEach((uid) => uidSet.add(parseInt(uid, 10)));
}
}
}
} catch (_e) {
// Fallback: no category mods in quick list
}
}
const uids = Array.from(uidSet).filter((uid) => uid > 0);
if (!uids.length) {
return [];
}
const userData = await user.getUsersFields(uids, ['uid', 'username', 'picture', 'userslug']);
return userData
.filter(Boolean)
.sort((a, b) => (a.username || '').localeCompare(b.username || ''));
}
// --- Notes CRUD ---
async function getNotes(tid) {
const noteIds = await db.getSortedSetRevRange(`internalnotes:tid:${tid}`, 0, -1);
if (!noteIds.length) {
return [];
}
const keys = noteIds.map(id => `internalnote:${id}`);
const notes = await db.getObjects(keys);
const uids = [...new Set(notes.filter(Boolean).map(n => n.uid))];
const userData = await user.getUsersFields(uids, ['uid', 'username', 'picture', 'userslug']);
const userMap = {};
userData.forEach((u) => {
userMap[u.uid] = u;
});
return notes.filter(Boolean).map((note) => ({
...note,
user: userMap[note.uid] || {},
timestampISO: new Date(parseInt(note.timestamp, 10)).toISOString(),
}));
}
async function createNote(tid, uid, content) {
const noteId = await db.incrObjectField('global', 'nextInternalNoteId');
const timestamp = Date.now();
const note = {
noteId,
tid: parseInt(tid, 10),
uid: parseInt(uid, 10),
content,
timestamp,
};
await Promise.all([
db.setObject(`internalnote:${noteId}`, note),
db.sortedSetAdd(`internalnotes:tid:${tid}`, timestamp, noteId),
]);
// Notify users who can view notes and are watching the topic (excluding the author)
const followers = await topics.getFollowers(tid);
const authorUid = parseInt(uid, 10);
const recipientUids = [];
for (const followerUid of followers) {
const parsed = parseInt(followerUid, 10);
if (parsed > 0 && parsed !== authorUid && await canViewNotes(parsed)) {
recipientUids.push(parsed);
}
}
if (recipientUids.length > 0) {
const topicData = await topics.getTopicFields(tid, ['title', 'slug']);
const notifObj = await notifications.create({
type: 'internalnotes-note',
bodyShort: translator.compile('internalnotes:notif-internal-note', topicData.title),
nid: `internalnotes:note:${tid}:${noteId}`,
from: uid,
path: `/topic/${topicData.slug}`,
tid: tid,
});
if (notifObj) {
await notifications.push(notifObj, recipientUids);
}
}
const userData = await user.getUserFields(uid, ['uid', 'username', 'picture', 'userslug']);
return {
...note,
user: userData,
timestampISO: new Date(timestamp).toISOString(),
};
}
async function deleteNote(tid, noteId) {
await Promise.all([
db.delete(`internalnote:${noteId}`),
db.sortedSetRemove(`internalnotes:tid:${tid}`, noteId),
]);
}
// --- Assignment (user or group) ---
async function assignTopic(tid, type, id, callerUid) {
if (type === 'user') {
return assignToUser(tid, id, callerUid);
}
if (type === 'group') {
return assignToGroup(tid, id, callerUid);
}
throw new Error('[[error:invalid-data]]');
}
async function removeTidFromAssigneeSet(tid) {
const topicData = await db.getObjectFields(`topic:${tid}`, ['assignee', 'assigneeType']);
if (!topicData || !topicData.assignee) {
return;
}
if (topicData.assigneeType === 'group') {
await db.sortedSetRemove(`group:${topicData.assignee}:assignedTids`, tid);
} else {
await db.sortedSetRemove(`uid:${topicData.assignee}:assignedTids`, tid);
}
}
async function assignToUser(tid, assigneeUid, callerUid) {
const parsedUid = parseInt(assigneeUid, 10);
if (parsedUid <= 0) {
await unassignTopic(tid);
return null;
}
const exists = await user.exists(parsedUid);
if (!exists) {
throw new Error('[[error:no-user]]');
}
await removeTidFromAssigneeSet(tid);
const ts = Date.now();
await db.deleteObjectFields(`topic:${tid}`, ['assigneeResolvedBy', 'assigneeResolvedAt']);
await Promise.all([
db.setObject(`topic:${tid}`, { assignee: parsedUid, assigneeType: 'user', assigneeStatus: 'open' }),
db.sortedSetAdd(`uid:${parsedUid}:assignedTids`, ts, tid),
]);
// Set topic following status to watching for the assigned user
try {
await topics.follow(tid, parsedUid);
} catch (_err) {
// Non-fatal: assignment already saved
}
if (parsedUid !== parseInt(callerUid, 10)) {
const topicData = await topics.getTopicFields(tid, ['title', 'slug']);
const notifObj = await notifications.create({
type: 'topic-assign',
bodyShort: translator.compile('internalnotes:notif-assigned-user', topicData.title),
nid: `internalnotes:assign:${tid}:uid:${parsedUid}`,
from: callerUid,
path: `/topic/${topicData.slug}`,
tid: tid,
});
if (notifObj) {
await notifications.push(notifObj, [parsedUid]);
}
}
const userData = await user.getUserFields(parsedUid, ['uid', 'username', 'picture', 'userslug']);
return { type: 'user', user: userData, status: 'open' };
}
async function assignToGroup(tid, groupName, callerUid) {
if (!groupName) {
await unassignTopic(tid);
return null;
}
const exists = await groups.exists(groupName);
if (!exists) {
throw new Error('[[error:no-group]]');
}
await removeTidFromAssigneeSet(tid);
const ts = Date.now();
await db.deleteObjectFields(`topic:${tid}`, ['assigneeResolvedBy', 'assigneeResolvedAt']);
await Promise.all([
db.setObject(`topic:${tid}`, { assignee: groupName, assigneeType: 'group', assigneeStatus: 'open' }),
db.sortedSetAdd(`group:${groupName}:assignedTids`, ts, tid),
]);
// Set topic following status to watching for all group members
const memberUids = await groups.getMembers(groupName, 0, -1);
await Promise.all(memberUids.map((memberUid) => topics.follow(tid, memberUid).catch(() => {})));
const topicData = await topics.getTopicFields(tid, ['title', 'slug']);
const recipientUids = memberUids.filter(uid => uid !== parseInt(callerUid, 10));
if (recipientUids.length) {
const notifObj = await notifications.create({
type: 'topic-assign',
bodyShort: translator.compile('internalnotes:notif-assigned-group', topicData.title, groupName),
nid: `internalnotes:assign:${tid}:group:${groupName}`,
from: callerUid,
path: `/topic/${topicData.slug}`,
tid: tid,
});
if (notifObj) {
await notifications.push(notifObj, recipientUids);
}
}
const groupData = await groups.getGroupFields(groupName, ['name', 'slug', 'memberCount', 'icon', 'labelColor']);
return { type: 'group', group: groupData, status: 'open' };
}
async function unassignTopic(tid) {
await removeTidFromAssigneeSet(tid);
await db.deleteObjectFields(`topic:${tid}`, assigneeFields);
}
async function setAssignmentStatus(tid, status, callerUid) {
if (!['open', 'resolved'].includes(status)) {
throw new Error('[[error:invalid-data]]');
}
const topicData = await db.getObjectFields(`topic:${tid}`, ['assignee']);
if (!topicData || !topicData.assignee) {
throw new Error('[[internalnotes:error-not-assigned]]');
}
if (status === 'resolved') {
await db.setObject(`topic:${tid}`, {
assigneeStatus: status,
assigneeResolvedBy: parseInt(callerUid, 10),
assigneeResolvedAt: Date.now(),
});
} else {
await db.setObjectField(`topic:${tid}`, 'assigneeStatus', status);
await db.deleteObjectFields(`topic:${tid}`, ['assigneeResolvedBy', 'assigneeResolvedAt']);
}
return getAssignee(tid);
}
async function getAssignee(tid) {
const topicData = await db.getObjectFields(`topic:${tid}`, assigneeFields);
if (!topicData || !topicData.assignee) {
return null;
}
const status = await getStatusData(topicData);
if (topicData.assigneeType === 'group') {
const exists = await groups.exists(topicData.assignee);
if (!exists) {
return null;
}
const groupData = await groups.getGroupFields(topicData.assignee, ['name', 'slug', 'memberCount', 'icon', 'labelColor']);
return { type: 'group', group: groupData, ...status };
}
const uid = parseInt(topicData.assignee, 10);
if (uid <= 0) {
return null;
}
const exists = await user.exists(uid);
if (!exists) {
return null;
}
const userData = await user.getUserFields(uid, ['uid', 'username', 'picture', 'userslug']);
return { type: 'user', user: userData, ...status };
}
async function getStatusData(topicData) {
if (topicData.assigneeStatus !== 'resolved') {
return { status: 'open' };
}
const data = { status: 'resolved' };
const resolvedAt = parseInt(topicData.assigneeResolvedAt, 10);
if (resolvedAt) {
data.resolvedAtISO = new Date(resolvedAt).toISOString();
}
const resolvedBy = parseInt(topicData.assigneeResolvedBy, 10);
if (resolvedBy > 0) {
data.resolvedBy = await user.getUserFields(resolvedBy, ['uid', 'username', 'userslug']);
}
return data;
}
async function getAssignedTids(uid) {
const byScore = {};
const addFromSet = async (setKey) => {
const list = await db.getSortedSetRevRangeWithScores(setKey, 0, -1);
for (const { value, score } of list) {
const tid = parseInt(value, 10);
if (tid && (!byScore[tid] || score > byScore[tid])) {
byScore[tid] = score;
}
}
};
await addFromSet(`uid:${uid}:assignedTids`);
const userGroupsList = await groups.getUserGroups([uid]);
const groupNames = (userGroupsList && userGroupsList[0]) ? userGroupsList[0].map(g => g.name) : [];
for (const name of groupNames) {
await addFromSet(`group:${name}:assignedTids`);
}
const tids = Object.keys(byScore)
.map(t => ({ tid: parseInt(t, 10), score: byScore[t] }))
.sort((a, b) => b.score - a.score)
.map(x => x.tid);
return tids;
}
/**
* Register the plugin's notification types with core so they show up in
* Settings -> Notifications and can be delivered by email ('email' /
* 'notificationemail'). Unregistered types are always delivered in-app only.
*/
plugin.registerNotificationType = async (data) => {
['notificationType_topic-assign', 'notificationType_topic-assign-stale', 'notificationType_internalnotes-note'].forEach((type) => {
if (!data.types.includes(type)) {
data.types.push(type);
}
});
return data;
};
// --- Stale-assignment reminders ---
function escapeHtmlText(str) {
return String(str == null ? '' : str)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function getLocalDateParts(timeZone) {
const opts = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', hourCycle: 'h23' };
let formatter;
try {
formatter = new Intl.DateTimeFormat('en-US', { ...opts, timeZone: timeZone || undefined });
} catch (_err) {
winston.warn(`[internalnotes] invalid staleReminderTimezone "${timeZone}", using server time`);
formatter = new Intl.DateTimeFormat('en-US', opts);
}
const parts = Object.fromEntries(formatter.formatToParts(new Date()).map(p => [p.type, p.value]));
return {
hour: parseInt(parts.hour, 10),
dateKey: `${parts.year}-${parts.month}-${parts.day}`,
};
}
/**
* Hourly job that only acts at the configured hour: for every assignable user, find
* topics assigned directly to them that are still open and have had no posts (nor
* been assigned) for `staleReminderDays` days, and send one summary notification.
* Group assignments are skipped to avoid nagging every member of a group.
*/
async function sendStaleReminders() {
const settings = await meta.settings.get('internalnotes');
if (settings.staleReminderEnabled !== 'on') {
return;
}
const hourSetting = parseInt(settings.staleReminderHour, 10);
const targetHour = hourSetting >= 0 && hourSetting <= 23 ? hourSetting : 15;
const { hour, dateKey } = getLocalDateParts((settings.staleReminderTimezone || '').trim());
if (hour !== targetHour) {
return;
}
// DST fall-back repeats an hour; only send once per local day
const lastRun = await db.getObjectField('internalnotes:staleReminders', 'lastRun');
if (lastRun === dateKey) {
return;
}
await db.setObjectField('internalnotes:staleReminders', 'lastRun', dateKey);
const days = Math.max(1, parseInt(settings.staleReminderDays, 10) || 7);
const cutoff = Date.now() - (days * 86400000);
const relativePath = nconf.get('relative_path');
const assignableUsers = await getAssignableUsers();
for (const assignee of assignableUsers) {
const uid = parseInt(assignee.uid, 10);
const assigned = await db.getSortedSetRangeWithScores(`uid:${uid}:assignedTids`, 0, -1);
if (!assigned.length) {
continue;
}
const topicData = await topics.getTopicsFields(assigned.map(a => a.value), ['tid', 'title', 'slug', 'lastposttime', 'deleted']);
const stale = topicData.filter((t, i) => t && t.tid && !t.deleted &&
Math.max(t.lastposttime || 0, assigned[i].score) < cutoff);
if (!stale.length) {
continue;
}
const statuses = await db.getObjectsFields(stale.map(t => `topic:${t.tid}`), ['assigneeStatus']);
const staleOpen = stale.filter((t, i) => !(statuses[i] && statuses[i].assigneeStatus === 'resolved'));
if (!staleOpen.length) {
continue;
}
const notifObj = await notifications.create({
type: 'topic-assign-stale',
bodyShort: translator.compile('internalnotes:notif-stale', staleOpen.length, days),
bodyLong: `<ul>${staleOpen.map(t => `<li><a href="${relativePath}/topic/${t.slug}">${escapeHtmlText(t.title)}</a></li>`).join('')}</ul>`,
nid: `internalnotes:stale:${uid}:${dateKey}`,
path: '/assigned',
});
if (notifObj) {
await notifications.push(notifObj, [uid]);
}
}
}
module.exports = plugin;