-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules_usernotes.js.html
1642 lines (1413 loc) · 72.6 KB
/
modules_usernotes.js.html
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>modules/usernotes.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h2><a href="https://github.com/toolbox-team/reddit-moderator-toolbox" target="_blank" class="menu-item" >Github</a></h2><h2><a href="https://www.reddit.com/r/toolbox" target="_blank" class="menu-item" >Subreddit</a></h2><h3>Classes</h3><ul><li><a href="Module.html">Module</a><ul class='methods'><li data-type='method'><a href="Module.html#get">get</a></li><li data-type='method'><a href="Module.html#getEnabled">getEnabled</a></li><li data-type='method'><a href="Module.html#init">init</a></li><li data-type='method'><a href="Module.html#set">set</a></li><li data-type='method'><a href="Module.html#setEnabled">setEnabled</a></li></ul></li><li><a href="TBListener.html">TBListener</a><ul class='methods'><li data-type='method'><a href="TBListener.html#clear">clear</a></li><li data-type='method'><a href="TBListener.html#on">on</a></li><li data-type='method'><a href="TBListener.html#start">start</a></li><li data-type='method'><a href="TBListener.html#stop">stop</a></li></ul></li></ul><h3>Global</h3><ul><li><a href="global.html#DISPLAY_BOTTOM">DISPLAY_BOTTOM</a></li><li><a href="global.html#DISPLAY_CENTER">DISPLAY_CENTER</a></li><li><a href="global.html#FEEDBACK_NEGATIVE">FEEDBACK_NEGATIVE</a></li><li><a href="global.html#FEEDBACK_NEUTRAL">FEEDBACK_NEUTRAL</a></li><li><a href="global.html#FEEDBACK_POSITIVE">FEEDBACK_POSITIVE</a></li><li><a href="global.html#ModNotesBadge">ModNotesBadge</a></li><li><a href="global.html#ModNotesPager">ModNotesPager</a></li><li><a href="global.html#ModNotesPopup">ModNotesPopup</a></li><li><a href="global.html#NoteTableRow">NoteTableRow</a></li><li><a href="global.html#RandomFeedback">RandomFeedback</a></li><li><a href="global.html#RandomQuote">RandomQuote</a></li><li><a href="global.html#TBsettingsObject">TBsettingsObject</a></li><li><a href="global.html#actionButton">actionButton</a></li><li><a href="global.html#addModSubsToSidebar">addModSubsToSidebar</a></li><li><a href="global.html#addToSiteTable">addToSiteTable</a></li><li><a href="global.html#addTrophiesToSidebar">addTrophiesToSidebar</a></li><li><a href="global.html#alert">alert</a></li><li><a href="global.html#baseDomain">baseDomain</a></li><li><a href="global.html#browserName">browserName</a></li><li><a href="global.html#buildSha">buildSha</a></li><li><a href="global.html#buildType">buildType</a></li><li><a href="global.html#button">button</a></li><li><a href="global.html#checkForActions">checkForActions</a></li><li><a href="global.html#cleanSubredditName">cleanSubredditName</a></li><li><a href="global.html#clearCache">clearCache</a></li><li><a href="global.html#colorNameToHex">colorNameToHex</a></li><li><a href="global.html#contextTrigger">contextTrigger</a></li><li><a href="global.html#createDeferredProcessQueue">createDeferredProcessQueue</a></li><li><a href="global.html#daysToMilliseconds">daysToMilliseconds</a></li><li><a href="global.html#debounce">debounce</a></li><li><a href="global.html#debugInformation">debugInformation</a></li><li><a href="global.html#defaultNoteLabelValueToLabelType">defaultNoteLabelValueToLabelType</a></li><li><a href="global.html#delay">delay</a></li><li><a href="global.html#displayNotes">displayNotes</a></li><li><a href="global.html#domain">domain</a></li><li><a href="global.html#escapeHTML">escapeHTML</a></li><li><a href="global.html#fetchModSubs">fetchModSubs</a></li><li><a href="global.html#fetchNewsNotes">fetchNewsNotes</a></li><li><a href="global.html#figureOutMulti">figureOutMulti</a></li><li><a href="global.html#filterModdable">filterModdable</a></li><li><a href="global.html#getActions">getActions</a></li><li><a href="global.html#getAllModNotes">getAllModNotes</a></li><li><a href="global.html#getAnonymizedSettings">getAnonymizedSettings</a></li><li><a href="global.html#getCache">getCache</a></li><li><a href="global.html#getContextURL">getContextURL</a></li><li><a href="global.html#getLastVersion">getLastVersion</a></li><li><a href="global.html#getLatestModNote">getLatestModNote</a></li><li><a href="global.html#getModSubs">getModSubs</a></li><li><a href="global.html#getModlog">getModlog</a></li><li><a href="global.html#getRandomNumber">getRandomNumber</a></li><li><a href="global.html#getSetting">getSetting</a></li><li><a href="global.html#getSettingAsync">getSettingAsync</a></li><li><a href="global.html#getSettings">getSettings</a></li><li><a href="global.html#getSubmissionFullname">getSubmissionFullname</a></li><li><a href="global.html#getSubredditColors">getSubredditColors</a></li><li><a href="global.html#getTime">getTime</a></li><li><a href="global.html#getToolboxDevs">getToolboxDevs</a></li><li><a href="global.html#handleMessage">handleMessage</a></li><li><a href="global.html#handleTBThings">handleTBThings</a></li><li><a href="global.html#handleThing">handleThing</a></li><li><a href="global.html#hideModActionsThings">hideModActionsThings</a></li><li><a href="global.html#htmlDecode">htmlDecode</a></li><li><a href="global.html#htmlEncode">htmlEncode</a></li><li><a href="global.html#humaniseDays">humaniseDays</a></li><li><a href="global.html#init">init</a></li><li><a href="global.html#initialLoadPromise">initialLoadPromise</a></li><li><a href="global.html#isConfigValidVersion">isConfigValidVersion</a></li><li><a href="global.html#isEquivalent">isEquivalent</a></li><li><a href="global.html#isModSub">isModSub</a></li><li><a href="global.html#isNewModmail">isNewModmail</a></li><li><a href="global.html#isOldReddit">isOldReddit</a></li><li><a href="global.html#labelColors">labelColors</a></li><li><a href="global.html#labelNames">labelNames</a></li><li><a href="global.html#link">link</a></li><li><a href="global.html#listenerAliases">listenerAliases</a></li><li><a href="global.html#literalRegExp">literalRegExp</a></li><li><a href="global.html#makeCommentThread">makeCommentThread</a></li><li><a href="global.html#makeQueueOverlay">makeQueueOverlay</a></li><li><a href="global.html#makeSingleComment">makeSingleComment</a></li><li><a href="global.html#makeSubmissionEntry">makeSubmissionEntry</a></li><li><a href="global.html#makeUserSidebar">makeUserSidebar</a></li><li><a href="global.html#messageHandlers">messageHandlers</a></li><li><a href="global.html#millisecondsToDays">millisecondsToDays</a></li><li><a href="global.html#minutesToMilliseconds">minutesToMilliseconds</a></li><li><a href="global.html#modbarExists">modbarExists</a></li><li><a href="global.html#moveArrayItem">moveArrayItem</a></li><li><a href="global.html#newModmailSidebar">newModmailSidebar</a></li><li><a href="global.html#niceDateDiff">niceDateDiff</a></li><li><a href="global.html#notification">notification</a></li><li><a href="global.html#overlay">overlay</a></li><li><a href="global.html#pager">pager</a></li><li><a href="global.html#pagerForItems">pagerForItems</a></li><li><a href="global.html#parseComments">parseComments</a></li><li><a href="global.html#parser">parser</a></li><li><a href="global.html#popup">popup</a></li><li><a href="global.html#progressivePager">progressivePager</a></li><li><a href="global.html#purify">purify</a></li><li><a href="global.html#purifyObject">purifyObject</a></li><li><a href="global.html#regExpEscape">regExpEscape</a></li><li><a href="global.html#relativeTime">relativeTime</a></li><li><a href="global.html#reloadIframe">reloadIframe</a></li><li><a href="global.html#reloadToolbox">reloadToolbox</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeLastDirectoryPartOf">removeLastDirectoryPartOf</a></li><li><a href="global.html#removeQuotes">removeQuotes</a></li><li><a href="global.html#replaceAll">replaceAll</a></li><li><a href="global.html#replaceTokens">replaceTokens</a></li><li><a href="global.html#saneSort">saneSort</a></li><li><a href="global.html#saneSortAs">saneSortAs</a></li><li><a href="global.html#saveSettingsToBrowser">saveSettingsToBrowser</a></li><li><a href="global.html#searchProfile">searchProfile</a></li><li><a href="global.html#setCache">setCache</a></li><li><a href="global.html#setSetting">setSetting</a></li><li><a href="global.html#setSettingAsync">setSettingAsync</a></li><li><a href="global.html#settings">settings</a></li><li><a href="global.html#settingsToObject">settingsToObject</a></li><li><a href="global.html#shortVersion">shortVersion</a></li><li><a href="global.html#showNote">showNote</a></li><li><a href="global.html#sortBy">sortBy</a></li><li><a href="global.html#standardColors">standardColors</a></li><li><a href="global.html#stringToColor">stringToColor</a></li><li><a href="global.html#submissionFullnamesCache">submissionFullnamesCache</a></li><li><a href="global.html#tbRedditEvent">tbRedditEvent</a></li><li><a href="global.html#textFeedback">textFeedback</a></li><li><a href="global.html#timeConverterRead">timeConverterRead</a></li><li><a href="global.html#title_to_url">title_to_url</a></li><li><a href="global.html#toolboxVersion">toolboxVersion</a></li><li><a href="global.html#toolboxVersionName">toolboxVersionName</a></li><li><a href="global.html#typeNames">typeNames</a></li><li><a href="global.html#unescapeHTML">unescapeHTML</a></li><li><a href="global.html#unescapeJSON">unescapeJSON</a></li><li><a href="global.html#verifiedSettingsSave">verifiedSettingsSave</a></li><li><a href="global.html#watchForURLChanges">watchForURLChanges</a></li><li><a href="global.html#wrapWithLastValue">wrapWithLastValue</a></li><li><a href="global.html#zlibDeflate">zlibDeflate</a></li><li><a href="global.html#zlibInflate">zlibInflate</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">modules/usernotes.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import $ from 'jquery';
import * as TBApi from '../tbapi.ts';
import * as TBCore from '../tbcore.js';
import * as TBHelpers from '../tbhelpers.js';
import TBListener from '../tblistener.js';
import {Module} from '../tbmodule.jsx';
import * as TBStorage from '../tbstorage.js';
import * as TBui from '../tbui.js';
// FIXME: It no longer makes sense to bake logger functions into modules
// themselves, since functions the module defines may not have the module
// object in scope to use as a logger. For now I'm defining the module as
// `self` since that's the name module objects used to have; this is lazy
// and causes name shadowing since `self` is shadowed within the module
// init function for `this` management reasons.
const self = new Module({
name: 'User Notes',
id: 'UserNotes',
enabledByDefault: true,
settings: [
{
id: 'unManagerLink',
type: 'boolean',
default: true,
description: 'Show usernotes manager in modbox',
},
{
id: 'showDate',
type: 'boolean',
default: false,
description: 'Show date in note preview',
},
{
id: 'showOnModPages',
type: 'boolean',
default: false,
description: 'Show current usernote on ban/contrib/mod pages',
},
{
id: 'maxChars',
type: 'number',
default: 20,
advanced: true,
description: 'Max characters to display in current note tag (excluding date)',
},
{
id: 'onlyshowInhover',
type: 'boolean',
default: () => TBStorage.getSettingAsync('GenSettings', 'onlyshowInhover', true),
hidden: true,
},
],
}, async function init (initialSettings) {
startUsernotesManager.call(this, initialSettings);
await startUsernotes.call(this, initialSettings);
});
export default self;
function startUsernotes ({maxChars, showDate, onlyshowInhover}) {
const subs = [];
const $body = $('body');
const self = this;
let firstRun = true;
run();
function getUser (users, name) {
const userObject = {
name: '',
notes: [],
};
// Correct for faulty third party usernotes implementations.
const lowerCaseName = name.toLowerCase();
if (name !== lowerCaseName && Object.prototype.hasOwnProperty.call(users, lowerCaseName)) {
userObject.name = name;
const clonedNotes = JSON.parse(JSON.stringify(users[lowerCaseName].notes));
userObject.notes = clonedNotes;
userObject.nonCanonicalName = lowerCaseName;
}
if (Object.prototype.hasOwnProperty.call(users, name)) {
userObject.name = name;
const clonedNotes = JSON.parse(JSON.stringify(users[name].notes));
userObject.notes = userObject.notes.concat(clonedNotes);
}
if (userObject.notes.length) {
userObject.notes.sort((a, b) => b.time - a.time);
return userObject;
}
return undefined;
}
// NER support.
// It is entirely possible that TBNewThings is fired multiple times, so we
// use a debounce here to prevent run() from being triggered multiple times
window.addEventListener('TBNewThings', TBHelpers.debounce(run, 500));
// Queue the processing of usernotes.
let listnerSubs = {};
let queueTimeout;
function queueProcessSub (subreddit, $target) {
clearTimeout(queueTimeout);
if (Object.prototype.hasOwnProperty.call(listnerSubs, subreddit)) {
listnerSubs[subreddit] = listnerSubs[subreddit].add($target);
} else {
listnerSubs[subreddit] = $target;
}
queueTimeout = setTimeout(() => {
for (const sub in listnerSubs) {
if (Object.prototype.hasOwnProperty.call(listnerSubs, sub)) {
processSub(sub, listnerSubs[sub]);
}
}
listnerSubs = {};
}, 100);
}
function addTBListener () {
// event based handling of author elements.
TBListener.on('author', async e => {
const $target = $(e.target);
if ($target.closest('.tb-thing').length || !onlyshowInhover || TBCore.isOldReddit || TBCore.isNewModmail) {
const subreddit = e.detail.data.subreddit.name;
const author = e.detail.data.author;
if (author === '[deleted]') {
return;
}
$target.addClass('ut-thing');
$target.attr('data-subreddit', subreddit);
$target.attr('data-author', author);
const isMod = await TBCore.isModSub(subreddit);
if (isMod) {
attachNoteTag($target, subreddit, author);
foundSubreddit(subreddit);
queueProcessSub(subreddit, $target);
}
}
});
// event based handling of author elements.
TBListener.on('userHovercard', async e => {
const $target = $(e.target);
const subreddit = e.detail.data.subreddit.name;
const author = e.detail.data.user.username;
$target.addClass('ut-thing');
$target.attr('data-subreddit', subreddit);
$target.attr('data-author', author);
const isMod = await TBCore.isModSub(subreddit);
if (isMod) {
attachNoteTag($target, subreddit, author, {
customText: 'Usernotes',
});
foundSubreddit(subreddit);
queueProcessSub(subreddit, $target);
}
});
}
function run () {
self.log('Running usernotes');
// We only need to add the listener on pageload.
if (firstRun) {
addTBListener();
firstRun = false;
} else {
TBCore.forEachChunked(subs, 10, 200, processSub);
}
}
function attachNoteTag ($element, subreddit, author, options = {}) {
if ($element.find('.tb-usernote-button').length > 0) {
return;
}
const usernoteDefaultText = options.customText ? options.customText : 'N';
const $tag = $(`
<a href="javascript:;" id="add-user-tag" class="tb-bracket-button tb-usernote-button add-usernote-${subreddit}" data-author="${author}" data-subreddit="${subreddit}" data-default-text="${usernoteDefaultText}">${usernoteDefaultText}</a>
`);
$element.append($tag);
}
function foundSubreddit (subreddit) {
if (!subs.includes(subreddit)) {
subs.push(subreddit);
}
}
async function processSub (subreddit, customThings) {
if (!subreddit) {
self.warn('Tried to process falsy subreddit, ignoring:', subreddit);
return;
}
let notes;
try {
notes = await getUserNotes(subreddit);
} catch (error) {
self.warn('Error reading usernotes for subreddit ${subreddit}:', error);
return;
}
self.log(`Usernotes retrieved for ${subreddit}: status=${status}`);
if (!isNotesValidVersion(notes)) {
// Remove the option to add notes
$(`.add-usernote-${subreddit}`).remove();
// Alert the user
const message = notes.ver > TBCore.notesMaxSchema
? `You are using a version of toolbox that cannot read a newer usernote data format in: /r/${subreddit}. Please update your extension.`
: `You are using a version of toolbox that cannot read an old usernote data format in: /r/${subreddit}, schema v${notes.ver}. Message /r/toolbox for assistance.`;
TBCore.alert({message}).then(clicked => {
if (clicked) {
window.open(
notes.ver > TBCore.notesMaxSchema
? '/r/toolbox/wiki/get'
: `/message/compose?to=%2Fr%2Ftoolbox&subject=Outdated%20usernotes&message=%2Fr%2F${subreddit}%20is%20using%20usernotes%20schema%20v${notes.ver}`,
);
}
});
}
getSubredditColors(subreddit).then(colors => {
setNotes(notes, subreddit, colors, customThings);
});
}
function isNotesValidVersion (notes) {
if (notes.ver < TBCore.notesMinSchema || notes.ver > TBCore.notesMaxSchema) {
self.log('Failed usernotes version check:');
self.log(`\tnotes.ver: ${notes.ver}`);
self.log(`\tTBCore.notesSchema: ${TBCore.notesSchema}`);
self.log(`\tTBCore.notesMinSchema: ${TBCore.notesMinSchema}`);
self.log(`\tTBCore.notesMaxSchema: ${TBCore.notesMaxSchema}`);
return false;
}
return true;
}
function setNotes (notes, subreddit, colors, customThings) {
self.log(`Setting notes for ${subreddit}`);
let things;
if (customThings) {
things = customThings;
} else {
things = $(`.ut-thing[data-subreddit=${subreddit}]`);
}
TBCore.forEachChunked(things, 20, 100, thing => {
// Get all tags related to the current subreddit
const $thing = $(thing);
const user = $thing.attr('data-author');
const u = getUser(notes.users, user);
let $usertag;
if (TBCore.isEditUserPage) {
$usertag = $thing.parent().find(`.add-usernote-${subreddit}`);
} else {
$usertag = $thing.find(`.add-usernote-${subreddit}`);
}
// Only happens if you delete the last note.
const defaultButtonText = $usertag.attr('data-default-text');
const currentText = $usertag.text();
if ((u === undefined || u.notes.length < 1) && currentText !== defaultButtonText) {
$usertag.css('color', '');
$usertag.empty();
$usertag.text(defaultButtonText);
return;
} else if (u === undefined || u.notes.length < 1) {
return;
}
const noteData = u.notes[0];
const date = new Date(noteData.time);
let note = noteData.note;
// Add title before note concat.
$usertag.attr('title', `${note} (${date.toLocaleString()})`);
if (note.length > maxChars) {
note = `${note.substring(0, maxChars)}...`;
}
if (showDate) {
note = `${note} (${
date.toLocaleDateString({
year: 'numeric',
month: 'numeric',
day: 'numeric',
})
})`;
}
$usertag.empty();
$usertag.append($('<b>').text(note)).append(
$('<span>').text(u.notes.length > 1 ? ` (+${u.notes.length - 1})` : ''),
);
let type = u.notes[0].type;
if (!type) {
type = 'none';
}
const color = _findSubredditColor(colors, type);
if (color) {
$usertag.css('color', color.color);
} else {
$usertag.css('color', '');
}
});
}
function createUserPopup (subreddit, user, link, disableLink, e) {
const $overlay = $(e.target).closest('.tb-page-overlay');
let $appendTo;
if ($overlay.length) {
$appendTo = $overlay;
} else {
$appendTo = $('body');
}
const $popup = TBui.popup({
title: `<div class="utagger-title">
<span>User Notes - <a href="${
TBCore.link(`/user/${user}`)
}" id="utagger-user-link">/u/${user}</a></span>
</div>`,
tabs: [{
content: `
<div class="utagger-content">
<table class="utagger-notes">
<tbody>
<tr>
<td class="utagger-notes-td1">Author</td>
<td class="utagger-notes-td2">Note</td>
<td class="utagger-notes-td3"></td></tr>
</tbody>
</table>
<div class="utagger-types">
<div class="utagger-type-list"></div>
</div>
<div class="utagger-input-wrapper">
<input type="text" class="utagger-user-note tb-input" id="utagger-user-note-input" placeholder="something about the user..." data-link="${link}" data-subreddit="${subreddit}" data-user="${user}">
<label class="utagger-include-link">
<input type="checkbox" ${!disableLink ? 'checked' : ''}${
disableLink ? 'disabled' : ''
}>
<span>Include link</span>
</label>
</div>
</div>
`,
footer: `
<div class="utagger-footer">
<span class="tb-window-error" style="display: none;"></span>
<input type="button" class="utagger-save-user tb-action-button" id="utagger-save-user" value="Save for /r/${subreddit}">
</div>
`,
}],
cssClass: 'utagger-popup',
});
// defined so we can easily add things to these specific areas after loading the notes.
const $noteList = $popup.find('.utagger-content .utagger-notes tbody');
const $typeList = $popup.find('.utagger-types .utagger-type-list');
// We want to make sure windows fit on the screen.
const positions = TBui.drawPosition(e);
$popup.css({
left: positions.leftPosition,
top: positions.topPosition,
});
$appendTo.append($popup);
// Generate dynamic parts of dialog and show
getSubredditColors(subreddit).then(async colors => {
self.log('Adding colors to dialog');
// Create type/color selections
const group = `${Math.random().toString(36)}00000000000000000`.slice(2, 7);
colors.forEach(info => {
self.log(` ${info.key}`);
self.log(` ${info.text}`);
self.log(` ${info.color}`);
$typeList.append(`
<div>
<label class="utagger-type type-${info.key}">
<input type="checkbox" name="type-group-${group}" value="${info.key}" class="type-input type-input-${info.key}">
<div style="color: ${info.color}">${info.text}</div>
</label>
</div>
`);
});
// Radio buttons 2.0, now with deselection
$popup.find('.utagger-type').click(function () {
const $thisInput = $(this).find('input');
// Are we already checked?
if ($thisInput.prop('checked')) {
// just uncheck this thing so everything is blank
$thisInput.prop('checked', false);
} else {
// Uncheck all the things, then check this thing
$(this).closest('.utagger-types').find('input').prop('checked', false);
$thisInput.prop('checked', true);
}
});
$popup.show();
// Add notes
self.log('Adding notes to dialog');
let notes;
try {
notes = await getUserNotes(subreddit);
} catch (error) {
self.warn('Error reading usernotes for subreddit ${subreddit}:', error);
return;
}
const u = getUser(notes.users, user);
// User has notes
if (u !== undefined && u.notes.length > 0) {
// FIXME: not selecting previous type
$popup.find(`.utagger-type .type-input-${u.notes[0].type}`).prop('checked', true);
u.notes.forEach((note, i) => {
// if (!note.type) {
// note.type = 'none';
// }
self.log(` Type: ${note.type}`);
const info = _findSubredditColor(colors, note.type);
self.log(info);
// TODO: probably shouldn't rely on time truncated to seconds as a note ID; inaccurate.
// The ID of a note is set to its time when the dialog is generated. As of schema v5,
// times are truncated to second accuracy. This means newly-added notes that have yet
// to be saved — and therefore still retain millisecond accuracy — may not be considered
// equal to saved versions if compared. This caused problems when deleting new notes,
// which searches a saved version based on ID.
const noteId = Math.trunc(note.time / 1000) * 1000;
const noteString = TBHelpers.htmlEncode(note.note);
const date = new Date(note.time);
// Construct some elements separately
let $noteTime = TBui.relativeTime(date);
$noteTime.addClass('utagger-date');
$noteTime.id = `utagger-date-${i}`;
if (note.link) {
let noteLink = note.link;
if (TBCore.isNewModmail && !noteLink.startsWith('https://')) {
noteLink = `https://www.reddit.com${noteLink}`;
}
$noteTime = $(`<a href="${TBHelpers.escapeHTML(noteLink)}">`).append($noteTime);
}
let typeSpan = '';
if (info && info.text) {
typeSpan = `<span class="note-type" style="color: ${info.color}">[${
TBHelpers.htmlEncode(info.text)
}]</span>`;
}
// Add note to list
const $noteRow = $(`
<tr class="utagger-note">
<td class="utagger-notes-td1">
<div class="utagger-mod">${note.mod}</div>
</td>
<td class="utagger-notes-td2">
${typeSpan}
<span class="note-text">${noteString}</span>
</td>
<td class="utagger-notes-td3"><i class="utagger-remove-note tb-icons tb-icons-negative" data-note-id="${noteId}">${TBui.icons.delete}</i></td>
</tr>
`);
$noteRow.find('td:first-child').append($noteTime);
$noteList.append($noteRow);
});
} else {
// No notes on user
$popup.find('#utagger-user-note-input').focus();
}
});
}
// Click to open dialog
$body.on('click', '#add-user-tag', async e => {
const $target = $(e.target);
const $thing = $target.closest('.ut-thing');
const $button = $thing.find('#add-user-tag');
const subreddit = $button.attr('data-subreddit');
const user = $button.attr('data-author');
const disableLink = false; // FIXME: change to thing type
let link;
if (TBCore.isNewModmail) {
const thingInfo = await TBCore.getThingInfo($thing);
link = thingInfo.permalink_newmodmail;
createUserPopup(subreddit, user, link, disableLink, e);
} else {
let thingID;
let thingDetails;
if ($thing.data('tb-type') === 'TBcommentAuthor' || $thing.data('tb-type') === 'commentAuthor') {
thingDetails = $thing.data('tb-details');
thingID = thingDetails.data.comment.id;
} else if ($thing.data('tb-type') === 'userHovercard') {
thingDetails = $thing.data('tb-details');
thingID = thingDetails.data.contextId;
} else {
thingDetails = $thing.data('tb-details');
thingID = thingDetails.data.post.id;
}
if (!thingID) {
// we don't have the ID on /about/banned, so no thing data for us
return createUserPopup(subreddit, user, link, true, e);
}
const info = await TBCore.getApiThingInfo(thingID, subreddit, true);
link = info.permalink;
createUserPopup(subreddit, user, link, disableLink, e);
}
});
// Save or delete button clicked
$body.on('click', '.utagger-save-user, .utagger-remove-note', async function (e) {
self.log('Save or delete pressed');
const $popup = $(this).closest('.utagger-popup');
const $unote = $popup.find('.utagger-user-note');
const subreddit = $unote.attr('data-subreddit');
const user = $unote.attr('data-user');
const noteId = $(e.target).attr('data-note-id');
const noteText = $unote.val();
const deleteNote = $(e.target).hasClass('utagger-remove-note');
const type = $popup.find('.utagger-type input:checked').val();
let link = '';
if ($popup.find('.utagger-include-link input').is(':checked')) {
link = $unote.attr('data-link');
}
self.log('deleteNote', deleteNote);
// Check new note data states
if (!deleteNote) {
if (!noteText) {
// User forgot note text!
$unote.addClass('error');
const $error = $popup.find('.tb-window-error');
$error.text('Note text is required');
$error.show();
return;
} else if (!user || !subreddit) {
// We seem to have an problem beyond the control of the user
return;
}
}
// Create new note
let note = {
note: noteText.trim(),
time: new Date().getTime(),
mod: await TBApi.getCurrentUser(),
link,
type,
};
const userNotes = {
notes: [],
};
userNotes.notes.push(note);
$popup.remove();
const noteSkel = {
ver: TBCore.notesSchema,
constants: {},
users: {},
};
TBui.textFeedback(`${deleteNote ? 'Removing' : 'Adding'} user note...`, TBui.FEEDBACK_NEUTRAL);
let notes;
try {
notes = await getUserNotes(subreddit, true);
} catch (error) {
// If getting usernotes failed because the page doesn't exist, create it
if (error.message === TBApi.NO_WIKI_PAGE) {
self.log('usernotes page did not exist, creating it');
notes = noteSkel;
notes.users[user] = userNotes;
saveUserNotes(subreddit, notes, 'create usernotes config').then(run).catch(error => {
self.error('Error saving usernotes', error);
});
} else {
self.warn('Failed to get usernotes:', error);
}
return;
}
let saveMsg;
if (notes) {
if (notes.corrupted) {
TBCore.alert({
message:
'toolbox found an issue with your usernotes while they were being saved. One or more of your notes appear to be written in the wrong format; to prevent further issues these have been deleted. All is well now.',
});
}
const u = getUser(notes.users, user);
// User already has notes
if (u !== undefined) {
self.log('User exists');
// Delete note
if (deleteNote) {
self.log('Deleting note');
self.log(` ${noteId}`);
self.log('Removing note from:');
self.log(u.notes);
for (let n = 0; n < u.notes.length; n++) {
note = u.notes[n];
self.log(` ${note.time}`);
if (note.time.toString() === noteId) {
self.log(` Note found: ${noteId}`);
u.notes.splice(n, 1);
self.log(u.notes);
break;
}
}
if (u.notes.length < 1) {
self.log('Removing user (is empty)');
delete notes.users[user];
}
saveMsg = `delete note ${noteId} on user ${user}`;
} else {
// Add note
self.log('Adding note');
u.notes.unshift(note);
saveMsg = `create new note on user ${user}`;
}
if (Object.prototype.hasOwnProperty.call(u, 'nonCanonicalName')) {
self.log(`Non Canoncial Username "${u.nonCanonicalName}" found. Correcting entry on save`);
delete notes.users[u.nonCanonicalName];
delete u.nonCanonicalName;
}
notes.users[user] = u;
} else if (u === undefined && !deleteNote) {
// New user
notes.users[user] = userNotes;
saveMsg = `create new note on new user ${user}`;
}
} else {
self.log(' Creating new user');
// create new notes object
notes = noteSkel;
notes.users[user] = userNotes;
saveMsg = `create new notes object, add new note on user ${user}`;
}
// Save notes if a message was set (the only case it isn't is if notes are corrupt)
if (saveMsg) {
self.log('Saving notes');
saveUserNotes(subreddit, notes, saveMsg).then(() => run());
}
});
// Enter key pressed when adding new note
$body.on('keyup', '.utagger-user-note', function (event) {
if (event.keyCode === 13) {
const popup = $(this).closest('.utagger-popup');
popup.find('.utagger-save-user').click();
}
});
}
function startUsernotesManager ({unManagerLink}) {
const $body = $('body');
const showLink = unManagerLink;
const self = this;
let subUsenotes;
// Register context hook for opening the manager
if (showLink) {
window.addEventListener('TBNewPage', async event => {
if (event.detail.pageDetails.subreddit) {
const subreddit = event.detail.pageDetails.subreddit;
const isMod = await TBCore.isModSub(subreddit);
if (isMod) {
TBui.contextTrigger('tb-un-config-link', {
addTrigger: true,
triggerText: 'edit usernotes',
triggerIcon: TBui.icons.usernote,
title: `edit usernotes for /r/${subreddit}`,
dataAttributes: {
subreddit,
},
});
} else {
TBui.contextTrigger('tb-un-config-link', {addTrigger: false});
}
} else {
TBui.contextTrigger('tb-un-config-link', {addTrigger: false});
}
});
}
// Sets up the note manager's even listeners and runs timeago for relative dates
function registerManagerEventListeners (sub) {
$body.find('#tb-un-prune-sb').on('click', event => {
const $popup = TBui.popup({
title: `Pruning usernotes for /r/${sub}`,
tabs: [{
content: `
<p>
<input type="checkbox" id="tb-un-prune-by-note-age"/>
<label for="tb-un-prune-by-note-age">
Prune notes older than
<select id="tb-un-prune-by-note-age-limit">
<option value="15552000000">6 months</option>
<option value="31104000000">1 year</option>
<option value="62208000000">2 years</option>
<option value="93312000000">3 years</option>
<option value="124416000000">4 years</option>
</select>
</label>
</p>
<p>
<input type="checkbox" id="tb-un-prune-by-user-deleted"/>
<label for="tb-un-prune-by-user-deleted">
Prune deleted users (slow)
</label>
</p>
<p>
<input type="checkbox" id="tb-un-prune-by-user-suspended"/>
<label for="tb-un-prune-by-user-suspended">
Prune permanently suspended users (slow)
</label>
</p>
<p>
<input type="checkbox" id="tb-un-prune-by-user-inactivity"/>
<label for="tb-un-prune-by-user-inactivity">
Prune users who haven't posted or commented in
<select id="tb-un-prune-by-user-inactivity-limit">
<option value="15552000000">6 months</option>
<option value="31104000000">1 year</option>
<option value="62208000000">2 years</option>
<option value="93312000000">3 years</option>
<option value="124416000000">4 years</option>
</select>
(slow)
</label>
</p>
`,
footer: `
<button class="tb-action-button" id="tb-un-prune-confirm">Prune</button>
`,
}],
});
const $pruneByNoteAge = $popup.find('#tb-un-prune-by-note-age');
const $pruneByNoteAgeLimit = $popup.find('#tb-un-prune-by-note-age-limit');
const $pruneByUserDeleted = $popup.find('#tb-un-prune-by-user-deleted');
const $pruneByUserSuspended = $popup.find('#tb-un-prune-by-user-suspended');
const $pruneByUserInactivity = $popup.find('#tb-un-prune-by-user-inactivity');
const $pruneByUserInactivityLimit = $popup.find('#tb-un-prune-by-user-inactivity-limit');
const $confirmButton = $popup.find('#tb-un-prune-confirm');
$confirmButton.on('click', async () => {
const checkNoteAge = $pruneByNoteAge.is(':checked');
const checkUserDeleted = $pruneByUserDeleted.is(':checked');
const checkUserSuspended = $pruneByUserSuspended.is(':checked');
const checkUserActivity = $pruneByUserInactivity.is(':checked');
// Do nothing if no pruning criteria are selected
if (!checkNoteAge && !checkUserDeleted && !checkUserSuspended && !checkUserActivity) {
return;
}
// Create a deep copy of the users object to avoid overwriting live data
const users = JSON.parse(JSON.stringify(subUsenotes.users));
// Record initial number of notes and users
const totalNotes = Object.values(users).reduce((acc, {notes}) => acc + notes.length, 0);
const totalUsers = Object.keys(users).length;
// Keep track of the number of users and notes we prune
let prunedNotes = 0;
let prunedUsers = 0;
// Also keep track of what sorts of notes we're pruning (to generate the wiki edit message)
const pruneReasons = [];
// Prune by note age
if (checkNoteAge) {
const ageThreshold = Date.now() - parseInt($pruneByNoteAgeLimit.val(), 10);
pruneReasons.push(`notes before ${new Date(ageThreshold).toISOString()}`);
// delete all notes from earlier than ageThreshold
for (const [username, user] of Object.entries(users)) {
user.notes = user.notes.filter(note => {
if (note.time >= ageThreshold) {
return true;
}
prunedNotes += 1;
return false;
});
if (user.notes.length === 0) {
// delete in loop is safe because we're iterating over Object.values()
delete users[username];
prunedUsers += 1;
}
}
}
// Prune by user criteria we have to hit the API for
if (checkUserDeleted || checkUserSuspended || checkUserActivity) {
// Calculate the date threshold for activity checks
// NOTE: This value is only used if checkUserActivity is true, but because it's used in a couple
// different scopes and we don't want to recalculate it over and over, we just set it here
// and don't use it if we don't care about user activity. This could probably be cleaned.
const dateThreshold = Date.now() - parseInt($pruneByUserInactivityLimit.val(), 10);
// Add the appropriate notes for the wiki revision comment
if (checkUserActivity) {
pruneReasons.push(`users inactive since ${new Date(dateThreshold).toISOString()}`);
}
if (checkUserDeleted) {
pruneReasons.push('deleted users');
}
if (checkUserSuspended) {
pruneReasons.push('suspended users');
}
// Check each individual user
// `await Promise.all()` allows requests to be sent in parallel
TBui.longLoadSpinner(true, 'Checking user activity, this could take a bit', TBui.FEEDBACK_NEUTRAL);
await Promise.all(
Object.entries(users).map(async ([username, user]) => {
let accountDeleted = false;
let accountSuspended = false;
let accountInactive = false;
// Fetch the user's profile and see if they meet any of the criteria
await TBApi.getJSON(`/user/${username}.json`, {sort: 'new'}).then(({data}) => {
// The user exists and isn't suspended, and is considered inactive only if they have no
// public post or comment history more recent than the threshold
accountInactive = !data.children.some(thing =>
thing.data.created_utc * 1000 > dateThreshold
);
}).catch(error => {
if (!error.response) {
// There was a network error - never act based on this
self.error(`Network error while trying to prune check /u/${username}:`, error);
return;
}
if (error.response.status === 404) {
// 404 tells us the user is deleted
accountDeleted = true;
} else if (error.response.status === 403) {
// 403 tells us the user is permanently suspended
accountSuspended = true;
}
});
// If any of the specified criteria are true, delete all the user's notes
if (
checkUserDeleted && accountDeleted
|| checkUserSuspended && accountSuspended
|| checkUserActivity && accountInactive
) {
prunedNotes += user.notes.length;
prunedUsers += 1;
delete users[username];
}
}),
);
TBui.longLoadSpinner(false);
}
const confirmation = confirm(
`${prunedNotes} of ${totalNotes} notes will be pruned. ${prunedUsers} of ${totalUsers} users will no longer have any notes. Proceed?`,
);
if (!confirmation) {
return;
}
subUsenotes.users = users;
// TODO: don't swallow errors
await saveUserNotes(sub, subUsenotes, `prune: ${pruneReasons.join(', ')}`).catch(() => {});
window.location.reload();
});
const {topPosition, leftPosition} = TBui.drawPosition(event);
$popup.appendTo('#tb-un-note-content-wrap').css({
// position: 'absolute',
top: topPosition,
left: leftPosition,
});
});
// Update user status.
$body.on('click', '.tb-un-refresh', async function () {
const $this = $(this);
const user = $this.attr('data-user');
const $userSpan = $this.parent().find('.user');
if (!$this.hasClass('tb-un-refreshed')) {
$this.addClass('tb-un-refreshed');
self.log(`refreshing user: ${user}`);
const $status = TBHelpers.template(
'&nbsp;<span class="mod">[this user account is: {{status}}]</span>',
{
status: await TBApi.aboutUser(user).then(() => 'active').catch(() => 'deleted'),
},
);
$userSpan.after($status);
}
});
// Delete all notes for user.
$body.on('click', '.tb-un-delete', async function () {