-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtbcore.js.html
1791 lines (1581 loc) · 76.6 KB
/
tbcore.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>tbcore.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">tbcore.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import $ from 'jquery';
import browser from 'webextension-polyfill';
import * as TBApi from './tbapi.ts';
import {getModhash} from './tbapi.ts';
import {icons} from './tbconstants.ts';
import * as TBHelpers from './tbhelpers.js';
import TBLog from './tblog.ts';
import * as TBStorage from './tbstorage.js';
import {currentPlatform, RedditPlatform} from './util/platform.ts';
const logger = TBLog('TBCore');
// Build variables defined by Rollup
/* global process */
/** @type {'stable' | 'beta' | 'dev'} */
export const buildType = process.env.BUILD_TYPE;
/** @type {string | null} */
const buildSha = process.env.BUILD_SHA;
// Schema versioning information
// TODO: Put these into the files they're used in, rather than keeping them here
export const configSchema = 1;
export const configMinSchema = 1;
export const configMaxSchema = 1;
export const notesSchema = 6;
export const notesMinSchema = 4;
export const notesDeprecatedSchema = 4;
export const notesMaxSchema = 6; // The non-default max version (to allow phase-in schema releases)
/**
* Checks if a given subreddit config version is valid with this version of toolbox
* @function
* @param {object} config
* @param {string} subreddit
* @returns {booleean} valid
*/
export function isConfigValidVersion (subreddit, config) {
if (config.ver < configMinSchema || config.ver > configMaxSchema) {
logger.error(`Failed config version check:
\tsubreddit: ${subreddit}
\tconfig.ver: ${config.ver}
\tTBCore.configSchema: ${configSchema}
\tTBCore.configMinSchema: ${configMinSchema}
\tTBCore.configMaxSchema: ${configMaxSchema}`);
return false;
}
return true;
}
// Generated version strings
const manifest = browser.runtime.getManifest();
const versionRegex = /(?<major>\d\d?)\.(?<minor>\d\d?)\.(?<patch>\d\d?)\.(?<build>\d+)/;
const {major, minor, patch, build} = manifest.version.match(versionRegex).groups;
/**
* Concise version string which includes all possibly relevant information.
* @example '6.1.13.0 stable 5546015'
* @example '7.0.0.2 beta 893745b'
*/
export const toolboxVersion = `${manifest.version} ${buildType} ${buildSha?.slice(0, 7) || 'local'}`.trim();
/**
* User-friendly version string; stable releases exclude build and commit
* @example '6.1.13 "Delaying Donkey"'
* @example '7.0.0 "Rewriting Rattlesnake" (build 2 from 893745b)'
*/
export const toolboxVersionName = `${manifest.version_name}${
buildType === 'stable'
? ''
: ` (${buildType} build ${build || 0} from ${buildSha?.slice(0, 7) || 'local copy'})`
}`;
/**
* Numeric representation of basic version information; compare
* major/minor/patch/build instead when possible
* @example 60113
* @deprecated
*/
export const shortVersion = major * 10000 + minor * 100 + patch * 1;
// Details about the current page
const $body = $('body');
export const isMod = $('body.moderator').length;
/** @deprecated Check {@linkcode currentPlatform} directly instead. */
export const isOldReddit = currentPlatform === RedditPlatform.OLD;
/** @deprecated Check {@linkcode currentPlatform} directly instead. */
export const isNewModmail = currentPlatform === RedditPlatform.MODMAIL;
export const isNewMMThread = $('body').find('.ThreadViewer').length > 0;
// TODO: break these checks out into platform.ts per-platform
export const isEmbedded = $('body').hasClass('embedded-page')
|| window.location.pathname.match(/^(\/r\/.*?)\/post-viewer\//);
export let pageDetails = {};
// Additional location checks to determine the type of page we're on
export const isEditUserPage = location.pathname.match(/\/about\/(?:contributors|moderator|banned)\/?/);
export const isModmail = location.pathname.match(/(\/message\/(?:moderator)\/?)|(\/r\/.*?\/about\/message\/inbox\/?)/);
export const isModpage = location.pathname.match(/\/about\/(?:reports|modqueue|spam|unmoderated|edited)\/?/);
export const isModLogPage = location.pathname.match(/\/about\/(?:log)\/?/);
export const isModQueuePage = location.pathname.match(/\/about\/(?:modqueue)\/?/);
export const isUnmoderatedPage = location.pathname.match(/\/about\/(?:unmoderated)\/?/);
export const isUserPage = location.pathname.match(/\/(?:user)\/?/);
export const isCommentsPage = location.pathname.match(/\?*\/(?:comments)\/?/);
export const isSubCommentsPage = location.pathname.match(/\/r\/.*?\/(?:comments)\/?/);
export const isSubAllCommentsPage = location.pathname.match(/\/r\/.*?\/(?:comments)\/?$/);
export const isModFakereddit = location.pathname.match(/^\/r\/mod\b/) || location.pathname.match(/^\/me\/f\/mod\b/);
export const events = {
TB_ABOUT_PAGE: 'TB_ABOUT_PAGE',
TB_APPROVE_THING: 'TB_APPROVE_THING',
TB_FLY_SNOO: 'TB_FLY_SNOO',
TB_KILL_SNOO: 'TB_KILL_SNOO',
TB_SAMPLE_SOUND: 'TB_SAMPLE_SOUND',
TB_SYNTAX_SETTINGS: 'TB_SYNTAX_SETTINGS',
TB_UPDATE_COUNTERS: 'TB_UPDATE_COUNTERS',
};
export const defaultUsernoteTypes = [
{key: 'gooduser', color: 'green', text: 'Good Contributor'},
{key: 'spamwatch', color: 'fuchsia', text: 'Spam Watch'},
{key: 'spamwarn', color: 'purple', text: 'Spam Warning'},
{key: 'abusewarn', color: 'orange', text: 'Abuse Warning'},
{key: 'ban', color: 'red', text: 'Ban'},
{key: 'permban', color: 'darkred', text: 'Permanent Ban'},
{key: 'botban', color: 'black', text: 'Bot Ban'},
];
export const config = {
ver: configSchema,
domainTags: '',
removalReasons: '',
modMacros: '',
usernoteColors: '',
banMacros: '',
};
const SETTINGS_NAME = 'Utils';
// Details about the current user
export {getModhash};
// If mod subs are being fetched we wait for them to be refreshed.
let fetchModSubsActive = false;
function waitForModSubsRefresh () {
return new Promise(resolve => {
window.addEventListener('tb-fresh-mod-subs', () => {
resolve();
}, {
once: true,
});
});
}
/**
* Returns a Promise that returns the subreddits a user mods as
* an array with just the names or array with details per subreddit.
* First tries to read their values from cache, and falls back to
* fetching the list of moderated subs from the API.
* @function
* @param {boolean} data If true will return detailed subreddit data.
* @returns {Promise<array>} array with subreddit names or subreddit objects with details.
*/
export async function getModSubs (data) {
logger.log('getting mod subs');
// Are we already fetching subs? If so, wait for them to be refreshed before attempting to return anything.
if (fetchModSubsActive) {
await waitForModSubsRefresh();
return TBStorage.getCache('Utils', data ? 'moderatedSubsData' : 'moderatedSubs', []);
} else {
fetchModSubsActive = true;
}
// Try to load the info we need from cache
const cachedData = await TBStorage.getCache('Utils', data ? 'moderatedSubsData' : 'moderatedSubs', []);
if (cachedData.length) {
// Got cache let other waiting instances of this function know and return cachedData
window.dispatchEvent(new CustomEvent('tb-fresh-mod-subs'));
fetchModSubsActive = false;
return cachedData;
}
// We need to refresh the list of moderated subreddits.
const subredditData = await fetchModSubs();
// mySubs should contain a list of subreddit names, sorted alphabetically
const mySubs = TBHelpers.saneSort(subredditData.map(({data}) => data.display_name.trim()));
const mySubsData = TBHelpers.sortBy(
subredditData.map(({data}) => ({
subreddit: data.display_name,
subscribers: data.subscribers,
over18: data.over18,
created_utc: data.created_utc,
subreddit_type: data.subreddit_type,
submission_type: data.submission_type,
is_enrolled_in_new_modmail: data.is_enrolled_in_new_modmail,
})),
'subscribers',
);
await TBStorage.setCache('Utils', 'moderatedSubs', mySubs);
await TBStorage.setCache('Utils', 'moderatedSubsData', mySubsData);
fetchModSubsActive = false;
window.dispatchEvent(new CustomEvent('tb-fresh-mod-subs'));
return data ? mySubsData : mySubs;
}
/**
* Returns a Promise that returns if the logged in user is a mod of a given subreddit.
* @function
* @param {string} subreddit Subreddit to check.
* @returns {Promise<boolean>}
*/
export async function isModSub (subreddit) {
const mySubs = await getModSubs(false);
return mySubs.includes(subreddit);
}
export async function modSubCheck () {
const mySubsData = await getModSubs(true);
const subCount = mySubsData.length;
let subscriberCount = 0;
mySubsData.forEach(subreddit => {
subscriberCount += subreddit.subscribers;
});
subscriberCount -= subCount;
if (subscriberCount > 25) {
return true;
} else {
return false;
}
}
// A promise we hold onto to ensure the lastVersion is fetched only once, before
// it gets updated to the current version
let lastVersionPromise = null;
/**
* Gets the version of Toolbox that was used last time the Toolbox content
* script was started. Used to tell if the extension was just updated.
* @returns {Promise<number>}
*/
export function getLastVersion () {
if (!lastVersionPromise) {
lastVersionPromise = TBStorage.getSettingAsync(SETTINGS_NAME, 'lastVersion', 0);
}
return lastVersionPromise;
}
/**
* The base domain to use for links to content on Reddit. If we are on new
* modmail we use www.reddit.com; wnywhere else we use whatever is the current
* domain.
*/
export const baseDomain = window.location.hostname === 'mod.reddit.com'
? 'https://www.reddit.com'
: `https://${window.location.hostname}`;
/**
* Takes an absolute path for a link and prepends the www.reddit.com
* domain if we're in new modmail (mod.reddit.com). Makes absolute path
* links work everywhere.
* @function
* @param {string} l The link path, starting with "/"
* @returns {string}
*/
export const link = l => isNewModmail ? `https://www.reddit.com${l}` : l;
// Check our post site. We might want to do some sort or regex fall back here, if it's needed.
const invalidPostSites = ['subreddits you moderate', 'mod (filtered)', 'all'];
export let post_site = isModFakereddit || $('.redditname:not(.pagename) a:first').html() || ''; // This may need to be changed to regex, if this is unreliable.
if (isModFakereddit || !post_site || invalidPostSites.indexOf(post_site) !== -1) {
post_site = '';
}
// Page event management
export function sendEvent (tbuEvent) {
logger.log('Sending event:', tbuEvent);
window.dispatchEvent(new CustomEvent(tbuEvent));
}
export function catchEvent (tbuEvent, callback) {
if (!callback) {
return;
}
window.addEventListener(tbuEvent, callback);
}
// Platform and debugging information
const CHROME = 'chrome';
const FIREFOX = 'firefox';
const OPERA = 'opera';
const EDGE = 'edge';
const UNKNOWN_BROWSER = 'unknown';
/** The name of the current browser. */
export const browserName = typeof InstallTrigger !== 'undefined' || 'MozBoxSizing' in document.body.style
? FIREFOX
: typeof chrome !== 'undefined'
? navigator.userAgent.includes(' OPR/')
? OPERA
: navigator.userAgent.includes(' Edg/')
? EDGE
: CHROME
: UNKNOWN_BROWSER;
/**
* Puts important debug information in a object so we can easily include
* it in /r/toolbox posts and comments when people need support.
* @function
* @returns {DebugObject} Object with debug information
*/
export function debugInformation () {
const debugObject = {
toolboxVersion,
browser: '',
browserVersion: '',
platformInformation: '',
debugMode: TBStorage.getSetting('Utils', 'debugMode', false),
compactMode: TBStorage.getSetting('Modbar', 'compactHide', false),
advancedSettings: TBStorage.getSetting('Utils', 'advancedMode', false),
cookiesEnabled: navigator.cookieEnabled,
};
const browserUserAgent = navigator.userAgent;
let browserMatchedInfo = [];
switch (browserName) {
case CHROME: {
// Let's first make sure we are actually dealing with chrome and not some other chrome fork that also supports extension.
// This way we can also cut some support requests short.
const vivaldiRegex = /\((.*?)\).*Vivaldi\/([0-9.]*?)$/;
const yandexRegex = /\((.*?)\).*YaBrowser\/([0-9.]*).*$/;
const chromeRegex = /\((.*?)\).*Chrome\/([0-9.]*).*$/;
if (navigator.userAgent.indexOf(' Vivaldi/') >= 0 && vivaldiRegex.test(browserUserAgent)) { // Vivaldi
browserMatchedInfo = browserUserAgent.match(vivaldiRegex);
debugObject.browser = 'Vivaldi';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
} else if (navigator.userAgent.indexOf(' YaBrowser/') >= 0 && yandexRegex.test(browserUserAgent)) { // Yandex
browserMatchedInfo = browserUserAgent.match(yandexRegex);
debugObject.browser = 'Yandex';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
} else if (chromeRegex.test(browserUserAgent)) {
browserMatchedInfo = browserUserAgent.match(chromeRegex);
debugObject.browser = 'Chrome';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
} else {
debugObject.browser = 'Chrome derivative';
debugObject.browserVersion = 'Unknown';
debugObject.platformInformation = browserUserAgent;
}
break;
}
case FIREFOX: {
const firefoxRegex = /\((.*?)\).*Firefox\/([0-9.]*?)$/;
const firefoxDerivativeRegex = /\((.*?)\).*(Firefox\/[0-9.].*?)$/;
if (firefoxRegex.test(browserUserAgent)) {
browserMatchedInfo = browserUserAgent.match(firefoxRegex);
debugObject.browser = 'Firefox';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
} else if (firefoxDerivativeRegex.test(browserUserAgent)) {
browserMatchedInfo = browserUserAgent.match(firefoxDerivativeRegex);
debugObject.browser = 'Firefox derivative';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
} else {
debugObject.browser = 'Firefox derivative';
debugObject.browserVersion = 'Unknown';
debugObject.platformInformation = browserUserAgent;
}
break;
}
case OPERA: {
browserMatchedInfo = browserUserAgent.match(/\((.*?)\).*OPR\/([0-9.]*).*$/);
debugObject.browser = 'Opera';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
break;
}
case EDGE: {
browserMatchedInfo = browserUserAgent.match(/\((.*?)\).*Edg\/([0-9.]*).*$/);
debugObject.browser = 'Edge';
debugObject.browserVersion = browserMatchedInfo[2];
debugObject.platformInformation = browserMatchedInfo[1];
break;
}
case UNKNOWN_BROWSER: {
debugObject.browser = 'Unknown';
debugObject.browserVersion = 'Unknown';
debugObject.platformInformation = browserUserAgent;
break;
}
default: {
// This should really never happen, but just in case I left it in.
debugObject.browser = 'Error in browser detection';
debugObject.browserVersion = 'Unknown';
debugObject.platformInformation = browserUserAgent;
}
}
// info level is always displayed
logger.info('Version/browser information:', debugObject);
return debugObject;
}
/**
* @typedef {Object} DebugObject
* @property {string} toolboxVersion The toolbox version
* @property {string} browser Browser used (Firefox, Chrome, etc)
* @property {string} browserVersion The version of the browser
* @property {string} platformInformation Other platform information
* @property {boolean} debugMode toolbox debugMode enabled
* @property {boolean} compactMode toolbox compactmode enabled
* @property {boolean} advancedSettings toolbox advanced settings enabled
* @property {boolean} cookiesEnabled Browser cookies enabled
*/
// Random quote generator
const randomQuotes = [
'Dude, in like 24 months, I see you Skyping someone to watch them search someone\'s comments on reddit.',
'Simple solution, don\'t use nightmode....',
'Nightmode users are a buncha nerds.',
'Oh, so that\'s where that code went, I thought i had lost it somehow.',
'Are all close buttons pretty now?!?!?',
'As a Business Analyst myself...',
'TOOLBOX ISN\'T YOUR PERSONAL TOOL!',
'You are now an approvened submitter',
'Translate creesch\'s Klingon settings to English.',
'Cuz Uncle Jessy was hot and knew the Beach Boys',
'Don\'t worry too much. There\'s always extra pieces.',
'Make the check actually check.',
'I dunno what this \'Safari\' thing is.',
'eeeeew... why is there PHP code in this room?',
'nah there is an actual difference between stuff',
'...have you paid money *out of your own pocket* to anyone to vet this product?',
'first I want to make sure my thing actually does work sort of',
'Don\'t let "perfect" get in the way of "good."',
'damnit creesch, put a spoiler tag, now the ending of toolbox is ruined for me',
'It\'s not even kinda bad... It\'s strangely awful.',
'Like a good neighbor, /u/andytuba is there',
'toolbox is build on beer',
'aww, i thought this was about real tools',
'my poop never smelled worse than when i lived off pizza bagel bites',
'Little dot, little dot ♪ You are not so little anymore ♫',
'How great will it be that trouble\'s wiki page will also include pizza ordering instructions?',
'Luu',
'I go two and hope for the best.',
'oh dammit, I forgot to include url shit',
'I think I just released a broken release',
'BECAUSE I AM THE LAW!!!',
];
/** A random quote for the about page, determined at page load. */
export const RandomQuote = randomQuotes[Math.floor(Math.random() * randomQuotes.length)];
const randomTextFeedbacks = [
'Please hold, your call is important to us.',
'Remember, toolbox loves you.',
'toolbox will be back later, gone fishing.',
'toolbox is \'doing things\', don\'t ask.',
'Tuning probability drive parameters.',
'Initiating data transfer: NSA_backdoor_package. ',
'Please post puppy pictures, they are so fluffy!',
'RES is visiting for a sleepover, no time right now',
'toolbox is on strike, we demand more karma!',
'brb... kicking Gustavobc from #toolbox',
'Requesting a new insurance quote from /u/andytuba',
'Sending all your data to Pyongyang',
'Contacting lizard overlords for instructions',
'Releasing raptors',
'Booting robot uprising',
'I need to tell you something critically important! I am sure I will remember in a moment...',
'/u/dakta ran out for a pack of smokes... BUT HE PROMISED HE\'D BE RIGHT BACK',
'One sec... catching some bugs',
'Here listen to some music while you wait, https://youtu.be/dQw4w9WgXcQ',
'Me? No. I\'m no docter but it looks like you have a broken toe.',
'Boo! Scared yeh didn\'t I?',
'Having issues? Try double jumping!',
'Hold on, need a bathroom break!',
'When in doubt, check the lost and found.',
'Rustling some jimmies.',
'Hello and, again, welcome to the Toolbox Science computer-aided enrichment center.',
'Run, Snoo, Run!',
];
/** A random text message for long loading tasks, determined at page load. */
export const RandomFeedback = randomTextFeedbacks[Math.floor(Math.random() * randomTextFeedbacks.length)];
// Functions for displaying notes/notifications
/**
* Opens the toolbox "nag" alert everyone loves so much. USE SPARINGLY.
* @function
* @param {object} options The options for the alert
* @param {string} options.message The text of the alert
* @param {number} options.noteID The ID of the note we're displaying
* @param {boolean} options.showClose Whether to show a close button
* @returns {Promise<boolean>} Resolves when the alert is closed. Value
* will be `true` if the alert was clicked, `false` if the close button
* was clicked or if it was closed for another reason.
*/
export const alert = ({message, noteID, showClose}) =>
new Promise(resolve => {
const $noteDiv = $(`<div id="tb-notification-alert"><span>${message}</span></div>`);
if (showClose) {
$noteDiv.append(`<i class="note-close tb-icons" title="Close">${icons.close}</i>`);
}
$noteDiv.appendTo($body);
window.addEventListener('tbSingleSettingUpdate', event => {
const settingDetail = event.detail;
if (
settingDetail.module === 'Utils' && settingDetail.setting === 'seenNotes'
&& settingDetail.value.includes(noteID)
) {
$noteDiv.remove();
resolve(false);
return;
}
});
$noteDiv.click(e => {
$noteDiv.remove();
if (e.target.className === 'note-close') {
resolve(false);
return;
}
resolve(true);
});
});
/**
* Shows a notification, uses native browser notifications if the user
* allows it or falls back on html notifications.
* @function
* @param {string} title Notification title
* @param {string} body Body text
* @param {string} path Absolute path to be opend when clicking the
* notification
* @param {string?} markreadid The ID of a conversation to mark as read
* when the notification is clicked
*/
export async function notification (title, body, path, markreadid = false) {
const notificationTimeout = 6000;
const notificationID = await browser.runtime.sendMessage({
action: 'tb-notification',
native: await TBStorage.getSettingAsync('GenSettings', 'nativeNotifications', true),
details: {
title,
body,
// We can't use link() for this since the background page has to have an absolute URL
url: isNewModmail ? `https://www.reddit.com${path}` : `${location.origin}${path}`,
modHash: await TBApi.getModhash(),
markreadid: markreadid || false,
},
});
// Because `browser.alarms` is weirdly simplistic and limited it is easier to do the timeout in the content_script side of things.
setTimeout(() => {
browser.runtime.sendMessage({
action: 'tb-page-notification-clear',
id: notificationID,
});
}, notificationTimeout);
}
/**
* Displays an alert for the given note if its platform information matches and
* the note hasn't been seen yet.
* @param {object} note
* @param {string} note.id The ID of the note, used to tell if it's been seen
* @param {string} note.text The text to display in the alert
* @param {string} note.link A URI to open when the user clicks the alert
* @param {string} [note.platform] If present, the note will only be shown on the given platform
*/
export async function showNote (note) {
if (!note.id || !note.text) {
return;
}
// If this note is only for a specific platform we're not on, skip it
if (
note.platform === 'firefox' && browserName !== FIREFOX
|| note.platform === 'chrome' && browserName !== CHROME
|| note.platform === 'opera' && browserName !== OPERA
|| note.platform === 'edge' && browserName !== EDGE
) {
return;
}
// If we've already seen this note, skip it
if ((await TBStorage.getSettingAsync('Utils', 'seenNotes', [])).includes(note.id)) {
return;
}
// Display the note, and add it to the list of seen notes when it's clicked
alert({
message: note.text,
noteID: note.id,
showClose: false,
}).then(async resp => {
if (note.link && note.link.match(/^(https?:|\/)/i) && resp) {
// Fetch seenNotes fresh, add this note's ID, and save the result
const seenNotes = await TBStorage.getSettingAsync('Utils', 'seenNotes', []);
seenNotes.push(note.id);
await TBStorage.setSettingAsync('Utils', 'seenNotes', seenNotes);
window.setTimeout(() => {
window.open(note.link);
}, 100);
}
});
}
/**
* Fetches notes for the given subreddit (from /r/sub/w/tbnotes).
* @param {string} sub The name of the subreddit to fetch notes from
* @returns {Promise<object[]>}
*/
async function fetchNewsNotes (sub) {
const resp = await TBApi.readFromWiki(sub, 'tbnotes', true);
TBStorage.purifyObject(resp);
if (!resp || resp === TBApi.WIKI_PAGE_UNKNOWN || resp === TBApi.NO_WIKI_PAGE || resp.length < 1) {
throw new Error(`Failed to fetch notes for /r/${sub}`);
}
return resp.notes;
}
/** Fetch and display all news notes. */
export function displayNotes () {
// dev releases skip all notes for my own sanity
if (buildType === 'dev') {
return;
}
fetchNewsNotes('toolbox').then(notes => notes.forEach(showNote)).catch(logger.warn);
if (buildType === 'beta') {
fetchNewsNotes('tb_beta').then(notes => notes.forEach(showNote)).catch(logger.warn);
}
}
// Iteration helpers
// Prevent page lock while parsing things. (stolen from RES)
export function forEachChunked (array, chunkSize, delay, call, complete, start) {
if (array === null) {
finish();
}
if (chunkSize === null || chunkSize < 1) {
finish();
}
if (delay === null || delay < 0) {
finish();
}
if (call === null) {
finish();
}
let counter = 0;
function doChunk () {
if (counter === 0 && start) {
start();
}
for (let end = Math.min(array.length, counter + chunkSize); counter < end; counter++) {
const ret = call(array[counter], counter, array);
if (ret === false) {
return window.setTimeout(finish, delay);
}
}
if (counter < array.length) {
window.setTimeout(doChunk, delay);
} else {
window.setTimeout(finish, delay);
}
}
window.setTimeout(doChunk, delay);
function finish () {
return complete ? complete() : false;
}
}
// Chunking abused for ratelimiting
export function forEachChunkedRateLimit (array, chunkSize, call, complete, start) {
let length;
let limit;
let counter;
const delay = 100;
if (array === null) {
finish();
} else if (chunkSize === null || chunkSize < 1) {
finish();
} else if (call === null) {
finish();
} else {
length = array.length;
limit = length > chunkSize ? 20 : 0;
counter = 0;
if (length < chunkSize) {
chunkSize = length;
}
updateRateLimit();
}
function doChunk () {
if (counter === 0 && start) {
start();
}
for (let end = Math.min(array.length, counter + chunkSize); counter < end; counter++) {
const ret = call(array[counter], counter, array);
if (ret === false) {
return window.setTimeout(finish, delay);
}
}
if (counter < array.length) {
window.setTimeout(updateRateLimit, delay);
} else {
window.setTimeout(finish, delay);
}
}
function timer (count, $body, ratelimitRemaining) {
count -= 1;
if (count <= 0) {
$body.find('#ratelimit-counter').empty();
$body.find('#ratelimit-counter').hide();
return count;
}
const minutes = Math.floor(count / 60);
const seconds = count - minutes * 60;
$body.find('#ratelimit-counter').html(
`<b>Oh dear, it seems we have hit a limit, waiting for ${minutes} minutes and ${seconds} seconds before resuming operations.</b>
<br><br>
<span class="rate-limit-explain"><b>tl;dr</b> <br> Reddit's current ratelimit allows for <i>${ratelimitRemaining} requests</i>. We are currently trying to process <i>${
parseInt(chunkSize)
} items</i>. Together with toolbox requests in the background that is cutting it a little bit too close. Luckily for us reddit tells us when the ratelimit will be reset, that is the timer you see now.</span>
`,
);
return count;
}
function updateRateLimit () {
TBApi.getRatelimit().then(({ratelimitReset, ratelimitRemaining}) => {
const $body = $('body');
if (!$body.find('#ratelimit-counter').length) {
$('div[role="main"].content').append('<span id="ratelimit-counter"></span>');
}
if (chunkSize + limit > parseInt(ratelimitRemaining)) {
$body.find('#ratelimit-counter').show();
let count = parseInt(ratelimitReset);
let counter = 0;
counter = setInterval(() => {
count = timer(count, $body, ratelimitRemaining);
if (count <= 0) {
clearInterval(counter);
doChunk();
}
}, 1000);
} else {
doChunk();
}
});
}
function finish () {
return complete ? complete() : false;
}
}
export function forEachChunkedDynamic (array, process, options) {
if (typeof process !== 'function') {
return;
}
const arr = Array.from(array);
let start;
let stop;
let fr;
let started = false;
const opt = Object.assign({
size: 25, // starting size
framerate: 30, // target framerate
nerf: 0.9, // Be careful with this one
}, options);
let size = opt.size;
const nerf = opt.nerf;
const framerate = opt.framerate;
const now = () => window.performance.now();
const again = typeof window.requestAnimationFrame === 'function'
? function (callback) {
window.requestAnimationFrame(callback);
}
: function (callback) {
setTimeout(callback, 1000 / opt.framerate);
};
function optimize () {
stop = now();
fr = 1000 / (stop - start);
size = Math.ceil(size * (1 + (fr / framerate - 1) * nerf));
return start = stop;
}
return new Promise(resolve => {
function doChunk () {
if (started) {
optimize();
} else {
started = true;
}
arr.splice(0, size).forEach(process);
if (arr.length) {
return again(doChunk);
}
return resolve(array);
}
start = now();
again(doChunk);
});
}
export async function getConfig (sub) {
// Check
const cachedSubsWithNoConfig = await TBStorage.getCache('Utils', 'noConfig', []);
if (cachedSubsWithNoConfig.includes(sub)) {
return undefined;
}
const cachedConfigs = await TBStorage.getCache('Utils', 'configCache', {});
if (cachedConfigs[sub] !== undefined) {
return cachedConfigs[sub];
}
// Fetch config from wiki
const resp = await TBApi.readFromWiki(sub, 'toolbox', true);
if (!resp || resp === TBApi.WIKI_PAGE_UNKNOWN) {
// Complete and utter failure
return undefined;
}
if (resp === TBApi.NO_WIKI_PAGE) {
// Subreddit not configured yet, at least add it to the noConfig cache
cachedSubsWithNoConfig.push(sub);
TBStorage.setCache('Utils', 'noConfig', cachedSubsWithNoConfig);
return undefined;
}
// We have new config data from the wiki, update the config cache and return
TBStorage.purifyObject(resp);
cachedConfigs[sub] = resp;
TBStorage.setCache('Utils', 'configCache', cachedConfigs);
return resp;
}
// TODO: Move this function to tbmodule, the only place it's ever used
export function exportSettings (subreddit, callback) {
const settingsObject = {};
$(TBStorage.settings).each(function () {
if (this === 'Storage.settings') {
return;
} // don't backup the setting registry.
const key = this.split('.');
const setting = TBStorage.getSetting(key[0], key[1], null);
if (setting !== null && setting !== undefined) { // DO NOT, EVER save null (or undefined, but we shouldn't ever get that)
settingsObject[this] = setting;
}
});
TBApi.postToWiki('tbsettings', subreddit, settingsObject, 'exportSettings', true, false).then(callback);
}
// TODO: Move this function to tbmodule, the only place it's ever used
export async function importSettings (subreddit) {
const resp = await TBApi.readFromWiki(subreddit, 'tbsettings', true);
if (!resp || resp === TBApi.WIKI_PAGE_UNKNOWN || resp === TBApi.NO_WIKI_PAGE) {
logger.log('Error loading wiki page');
return;
}
TBStorage.purifyObject(resp);
if (resp['Utils.lastversion'] < 300) {
logger.log('Cannot import from a toolbox version under 3.0');
return;
}
const doNotImport = [
'oldreddit.enabled',
];
Object.entries(resp).forEach(([fullKey, value]) => {
const key = fullKey.split('.');
// Do not import certain legacy settings.
if (doNotImport.includes(fullKey)) {
logger.log(`Skipping ${fullKey} import`);
} else {
TBStorage.setSetting(key[0], key[1], value, false);
}
});
}
// Misc. functions
export function addToSiteTable (URL, callback) {
if (!callback) {
return;
}
if (!URL) {
return callback(null);
}
TBApi.getJSON(URL).then(resp => {
if (!resp) {
return callback(null);
}
resp = resp.replace(/<script(.|\s)*?\/script>/g, '');
const $sitetable = $(resp).find('#siteTable');
$sitetable.find('.nextprev').remove();
if ($sitetable.length) {
callback($sitetable);
} else {
callback(null);
}
});
}
export async function getThingInfo (sender, modCheck) {
// First we check if we are in new modmail thread and for now we take a very simple.
// Everything we need info for is centered around threads.
const permaCommentLinkRegex = /(\/(?:r|user)\/[^/]*?\/comments\/[^/]*?\/)([^/]*?)(\/[^/]*?\/?)$/;