-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules_modbutton.js.html
862 lines (747 loc) · 43.2 KB
/
modules_modbutton.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>modules/modbutton.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/modbutton.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';
const MAX_BAN_REASON_LENGTH = 300;
const MAX_BAN_MESSAGE_LENGTH = 5000;
const self = new Module({
name: 'Mod Button',
id: 'ModButton',
enabledByDefault: true,
settings: [
{
id: 'savedSubs',
type: 'sublist',
default: [],
description: 'Saved subs (for quick access)',
},
{
id: 'rememberLastAction',
type: 'boolean',
default: false,
description: 'Remember last action',
},
{
id: 'globalButton',
type: 'boolean',
default: false,
advanced: true,
description: 'Enable Global Action button',
},
{
id: 'excludeGlobal',
type: 'sublist',
default: [],
advanced: true,
description: 'Exclude subs from Global Actions',
},
// private storage
{
id: 'onlyshowInhover',
type: 'boolean',
default: () => TBStorage.getSettingAsync('GenSettings', 'onlyshowInhover', true),
hidden: true,
},
{
id: 'lastAction',
type: 'text',
default: 'ban',
hidden: true,
},
],
}, init);
export default self;
const $body = $('body');
const titleText = 'Perform various mod actions on this user';
self.runRedesign = async function () {
// Not a mod, don't bother.
const mySubs = await TBCore.getModSubs(false);
if (mySubs.length < 1) {
return;
}
const onlyshowInhover = await self.get('onlyshowInhover');
TBListener.on('author', e => {
const $target = $(e.target);
// As the modbutton is already accessible in the sidebar and not needed for mods we don't show it in modmail threads.
if (e.detail.type === 'TBmodmailCommentAuthor') {
return;
}
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;
}
let parentID;
if (e.detail.data.comment) {
parentID = e.detail.data.comment.id;
} else if (e.detail.data.post) {
parentID = e.detail.data.post.id;
} else {
parentID = 'unknown';
}
requestAnimationFrame(() => {
$target.append(
`<a href="javascript:;" title="${titleText}" data-subreddit="${subreddit}" data-author="${author}" data-parentID="${parentID}" class="global-mod-button tb-bracket-button">M</a>`,
);
});
}
});
// event based handling of author elements.
TBListener.on('userHovercard', e => {
const $target = $(e.target);
const subreddit = e.detail.data.subreddit.name;
const author = e.detail.data.user.username;
const parentID = e.detail.data.contextId;
$target.append(
`<a href="javascript:;" title="${titleText}" data-subreddit="${subreddit}" data-author="${author}" data-parentID="${parentID}" class="global-mod-button tb-bracket-button">Mod Button</a>`,
);
});
};
/**
* updates the current savedsubs' listings in the mod button
*/
self.updateSavedSubs = async function () {
const mySubs = await TBCore.getModSubs();
//
// Refresh the settings tab and role tab sub dropdowns and saved subs tabls
//
const $popups = $body.find('.mod-popup');
const $savedSubsLists = $popups.find('.saved-subs');
// clear out the current stuff
$savedSubsLists.html('');
// add our saved subs to the "remove saved subs" dropdown on the setting tab
// and to the saved subs savedSubsList on the role tab
$popups.each(function () {
const $popup = $(this);
const $savedSubsList = $popup.find('.saved-subs');
const currentSub = $popup.find('.subreddit').text();
// repopulate the saved sub dropdowns with all the subs we mod
$popup.find('.edit-subreddits .savedSubs').remove();
$popup.find('.edit-subreddits').prepend(TBui.selectMultiple(mySubs, self.savedSubs).addClass('savedSubs'));
self.savedSubs.forEach(async subreddit => {
// only subs we moderate
// and not the current sub
const isMod = await TBCore.isModSub(subreddit);
if (isMod && subreddit !== currentSub) {
$savedSubsList.append(
`<div><input type="checkbox" class="action-sub" name="action-sub" value="${subreddit}" id="action-${subreddit}"><label for="action-${subreddit}">&nbsp;&nbsp;/r/${subreddit}</label></div>`,
);
}
});
});
mySubs.forEach(subreddit => {
$popups.find(`select.${self.OTHER}`).append(`<option value="${subreddit}">${subreddit}</option>`);
});
};
function init ({savedSubs, rememberLastAction, globalButton, excludeGlobal}) {
self.saveButton = 'Save';
self.OTHER = 'other-sub';
self.savedSubs = savedSubs;
let userFlairTemplates; // we need those in 2 functions and I don't think fetching twice is a good idea
self.savedSubs = TBHelpers.saneSort(self.savedSubs);
// it's Go Time™!
self.runRedesign();
async function openModPopup (event, info) {
const benbutton = event.target; // huehuehue
const $benbutton = $(benbutton);
self.log('displaying mod button popup');
const lastaction = await self.get('lastAction');
const subreddit = info.subreddit;
const user = info.user;
const thing_id = info.id;
// no user?
if (!user) {
TBui.textFeedback('No user', TBui.FEEDBACK_NEGATIVE);
// abort
return;
}
// generate the .mod-popup jQuery object
// We want to make sure windows fit on the screen.
const positions = TBui.drawPosition(event);
const $overlay = $benbutton.closest('.tb-page-overlay');
let $appendTo;
if ($overlay.length) {
$appendTo = $overlay;
} else {
$appendTo = $('body');
}
const $popup = TBui.popup({
title: `Mod Actions - /u/${user}`,
tabs: [
{
title: 'Role',
id: 'user-role', // reddit has things with class .role, so it's easier to do this than target CSS
tooltip: 'Add or remove user from subreddit ban, contributor, and moderator lists.',
content: `${
subreddit
? `
<div class="current-sub">
<input type="checkbox" class="action-sub" name="action-sub" value="${subreddit}" id="action-${subreddit}" checked>
<label for="action-${subreddit}">&nbsp;&nbsp;/r/${subreddit} (current)</label>
</div>`
: ''
}
<div class="saved-subs">
</div>
<div class="other-subs">
<input type="checkbox" class="action-sub ${self.OTHER}-checkbox name="action-sub" value="${self.OTHER}">
<select class="${self.OTHER} tb-action-button inline-button" for="action-${self.OTHER}"><option value="${self.OTHER}">(select subreddit)</option></select>
</div>
<div class="ban-note-container"><input id="ban-note" class="ban-note tb-input" type="text" placeholder="(ban note)" maxlength="${MAX_BAN_REASON_LENGTH}"></input><br>
<textarea name="ban-message" class="tb-input ban-message" placeholder="(ban message to user)" maxlength="${MAX_BAN_MESSAGE_LENGTH}"></textarea><br>
<input type="number" min="1" max="999" name="ban-duration" class="ban-duration tb-input" placeholder="time (days)">
</div>`,
footer: `
<span class="status error left"></span>
<select class="mod-action tb-action-button">
<option class="mod-action-negative" data-action="banned" data-api="friend">ban</option>
<option class="mod-action-positive" data-action="banned" data-api="unfriend">unban</option>
<option class="mod-action-positive" data-action="contributor" data-api="friend">add submitter</option>
<option class="mod-action-negative" data-action="contributor" data-api="unfriend" >remove submitter</option>
<option class="mod-action-positive" data-action="moderator" data-api="friend">mod</option>
<option class="mod-action-negative" data-action="moderator" data-api="unfriend" >demod</option>
</select>
${TBui.actionButton(self.saveButton, 'save')}
<button title="Global Action (perform action on all subs)" class="tb-action-button global-button inline-button"${
globalButton ? '' : 'style="display:none!important;"'
}>Global Action</button>`,
},
{
title: 'User Flair',
tooltip: 'Edit User Flair.',
content: `
<p style="clear:both;" class="mod-popup-flair-input">
<label for="flair-template-id" class="mod-popup-flair-label">Template:</label>
<select style="text-overflow: ellipsis; width: 150px;" id="flair-template-id-select" class="tb-action-button">
<option value="">None</option>
</select>
</p>
<p style="clear:both;" class="mod-popup-flair-input">
<label for="flair-text" class="mod-popup-flair-label">Text:</label>
<input id="flair-text" class="flair-text tb-input" type="text"></input>
</p>
<p style="clear:both;" class="mod-popup-flair-input">
<label for="flair-class" class="mod-popup-flair-label">Class:</label>
<input id="flair-class" class="flair-class tb-input" type="text"></input>
</p>`,
footer: `
<span class="status error left"></span>
${TBui.actionButton('Save Flair', 'flair-save')}
`,
},
{
title: 'Send Modmail',
tooltip: 'Send a modmail to the user.',
content: `
<input id="subreddit-message-subject" class="subreddit-message-subject tb-input" type="text" placeholder="(subject)" maxlength="100"></input><br>
<textarea name="subreddit-message" class="tb-input subreddit-message" placeholder="(message to user)" ></textarea><br>
<span id="subreddit-message-callback"></span>
`,
footer: `
<span class="status error left"></span>
${TBui.actionButton(`Send as /r/${subreddit}`, 'message-send')}
`,
},
],
cssClass: 'mod-popup',
meta:
`<label class="user">${user}</label><label class="subreddit">${subreddit}</label><label class="thing_id">${thing_id}</label>`,
}).appendTo($appendTo)
.css({
left: positions.leftPosition,
top: positions.topPosition,
display: 'block',
});
const $actionSelect = $popup.find('.mod-action');
// Set the action before setting up the initial interface
if (rememberLastAction) {
$actionSelect.val(lastaction);
}
// If we're not banning someone, we don't need these
if ($actionSelect.val() !== 'ban') {
$popup.find('.ban-note').hide();
$popup.find('textarea.ban-message').hide();
$popup.find('.ban-duration').hide();
$popup.find('.ban-span-include-time').hide();
}
// If we're doing global actions, add the button for that
// (there's a display none in the style attribute if this is disabled)
if (globalButton) {
const $globalButton = $popup.find('.global-button');
// unless we're doing a ban, because global bans are evil
if ($actionSelect.val() === 'ban') {
$globalButton.addClass('action-hidden');
}
$actionSelect.change(function () {
if (this.value === 'ban') {
$globalButton.addClass('action-hidden');
} else {
$globalButton.removeClass('action-hidden');
}
});
}
// Remove options that only apply to subs we mod
if (!subreddit) {
// Hide the flair tab and message tab
// TODO: add a "disabled" state, with tooltip, and use that instead
// We can only edit flair in the current sub.
$popup.find('.tb-window-tabs .user_flair').remove();
$popup.find('.tb-window-tabs .send_message').remove();
}
// get pre-definded ban message/note
if (subreddit) {
self.log('getting ban macros');
TBCore.getConfig(subreddit).then(config => {
if (!config || !config.banMacros) {
return;
}
const macros = config.banMacros;
if (macros.banNote) {
self.log(macros.banNote);
$popup.find('.ban-note').val(TBHelpers.replaceTokens(info, macros.banNote));
}
if (macros.banMessage) {
self.log(macros.banMessage);
$popup.find('.ban-message').val(TBHelpers.replaceTokens(info, macros.banMessage));
}
});
}
// only works if we're a mod of the sub in question
if (subreddit) {
// Show if current user is banned, and why. - thanks /u/LowSociety
try {
const banInfo = await TBApi.getBanState(subreddit, user);
if (banInfo) {
const user_fullname = banInfo.id; // we need this to extract data from the modlog
const timestamp = new Date(banInfo.date * 1000); // seconds to milliseconds
$popup.find('.current-sub').append(
$('<div class="already-banned">banned by <a href="#"></a> </div>'),
);
$popup.find('.current-sub .already-banned').append(TBui.relativeTime(timestamp));
$popup.find('select.mod-action option[data-api=unfriend][data-action=banned]').attr(
'selected',
'selected',
);
$popup.find('.ban-note').val(banInfo.note);
$popup.find('.tb-window-title').css('color', 'red');
// get the mod who banned them (need to pull request to get this in the banlist data to avoid this kind of stupid request)
const logData = await TBApi.getJSON(`/r/${subreddit}/about/log/.json`, {
type: 'banuser',
limit: '1000',
});
TBStorage.purifyObject(logData);
const logged = logData.data.children;
for (let i = 0; i < logged.length; i++) {
if (logged[i].data.target_fullname === user_fullname) {
$popup.find('.current-sub .already-banned a').attr('href', `/u/${logged[i].data.mod}`).text(
logged[i].data.mod,
);
break;
}
}
}
} catch (error) {
// We don't have permission to check the user's ban information
self.warn(`Error looking up ban information for ${user}:`, error);
}
}
// if we're on the mod page, it's likely we want to mod them to another sub.
// unselect current, change action to 'mod'.
if (location.pathname.match(/\/about\/(?:moderator)\/?/)) {
$popup.find('select.mod-action option[data-api=friend][data-action=moderator]').attr(
'selected',
'selected',
);
$popup.find('.ban-note').hide();
$popup.find('.action-sub:checkbox:checked').removeAttr('checked');
$popup.find('textarea.ban-message').hide();
$popup.find('.ban-duration').hide();
$popup.find('.ban-span-include-time').hide();
} else if (location.pathname.match(/\/about\/(?:contributors)\/?/)) {
$popup.find('select.mod-action option[data-api=friend][data-action=contributor]').attr(
'selected',
'selected',
);
$popup.find('.ban-note').hide();
$popup.find('.action-sub:checkbox:checked').removeAttr('checked');
$popup.find('textarea.ban-message').hide();
$popup.find('.ban-duration').hide();
$popup.find('.ban-span-include-time').hide();
}
// render the saved subs lists
self.updateSavedSubs();
// custom sub changed.
$popup.find(`select.${self.OTHER}`).change(function () {
$popup.find(`.${self.OTHER}-checkbox`).prop('checked', $(this).val() !== self.OTHER);
});
// show/hide ban reason text feild.
$actionSelect.change(function () {
const $banNote = $popup.find('.ban-note');
const $banMessage = $popup.find('textarea.ban-message');
const $banDuration = $popup.find('.ban-duration');
const $banIncludeTime = $popup.find('.ban-span-include-time');
if ($(this).val() === 'ban') {
$banNote.show();
$banMessage.show();
$banDuration.show();
$banIncludeTime.show();
} else {
$banNote.hide();
$banMessage.hide();
$banDuration.hide();
$banIncludeTime.hide();
}
});
}
// Mod button clicked
$body.on('click', '.global-mod-button', async function (event) {
const benbutton = event.target; // huehuehue
const $benbutton = $(benbutton);
if (TBCore.isNewModmail) {
const info = await TBCore.getThingInfo(this, true);
openModPopup(event, info);
} else {
const subreddit = $benbutton.attr('data-subreddit');
const id = $benbutton.attr('data-parentID');
const author = $benbutton.attr('data-author');
if (id === 'unknown' || id === 'undefined') {
const info = {
subreddit,
user: author,
author,
permalink: location.href,
url: location.href,
domain: '',
id,
body: '>',
raw_body: '',
uri_body: '',
approved_by: '',
title: '',
uri_title: '',
kind: 'comment',
postlink: '',
link: '',
banned_by: '',
spam: '',
ham: '',
rules: subreddit ? TBCore.link(`/r/${subreddit}/about/rules`) : '',
sidebar: subreddit ? TBCore.link(`/r/${subreddit}/about/sidebar`) : '',
wiki: subreddit ? TBCore.link(`/r/${subreddit}/wiki/index`) : '',
mod: await TBApi.getCurrentUser(),
};
openModPopup(event, info);
} else {
TBCore.getApiThingInfo(id, subreddit, true).then(info => {
// If the thing we're fetching info for is removed in a subreddit the current user doesn't mod,
// the API won't return information about it. However, we can still access such things if we're
// on the user's profile. In that context, we manually fill in the author since we know at least
// that much already.
if (!info.author) {
info.author = info.user = author;
}
openModPopup(event, info);
});
}
}
return false;
});
// 'save' button clicked... THIS IS WHERE WE BAN PEOPLE, PEOPLE!
$body.on('click', '.mod-popup .save, .global-button', async function () {
const $button = $(this);
const $popup = $button.parents('.mod-popup');
const $selected = $popup.find('.mod-action :selected');
const api = $selected.attr('data-api');
const action = $selected.attr('data-action');
const actionName = $selected.val();
const settingState = api === 'friend';
const $status = $popup.find('.status');
const banReason = $popup.find('.ban-note').val();
const banDuration = $popup.find('.ban-duration').val();
const banContext = $popup.find('.thing_id').text();
const subreddits = [];
const user = $popup.find('.user').text();
const banMessage = $popup.find('textarea.ban-message').val();
self.set('lastAction', actionName);
if (action === 'banned') {
if (banReason.length > MAX_BAN_REASON_LENGTH) {
return $status.text(
`error, ban note is ${banReason.length - MAX_BAN_REASON_LENGTH} characters over limit`,
);
}
if (banMessage.length > MAX_BAN_MESSAGE_LENGTH) {
return $status.text(
`error, ban message is ${banMessage.length - MAX_BAN_MESSAGE_LENGTH} characters over limit`,
);
}
}
// Check dem values.
if (!api) {
return $status.text('error, no action selected');
}
if (!$(this).hasClass('global-button')) {
// Get dem ban subs.
$popup.find('.action-sub:checkbox:checked').each(function () {
let subname = $(this).val();
if (subname !== self.OTHER) {
subreddits.push(subname);
} else {
subname = $(`.${self.OTHER} option:selected`).val();
if (subname !== self.OTHER) {
subreddits.push(subname);
}
}
});
// Check dem values.
if (subreddits.length < 1) {
return $status.text('error, no subreddits selected');
}
// do it.
massAction(subreddits);
} else {
if (actionName === 'ban') {
$status.text('Yeah...not happening');
} else {
let confirmban;
if (actionName === 'unban') {
confirmban = confirm(
`This will ${actionName} /u/${user} from every subreddit you moderate. \nAre you sure?`,
);
} else {
confirmban = confirm(
`This will ${actionName} /u/${user} on every subreddit you moderate. \nAre you sure?`,
);
}
if (confirmban) {
const subs = await TBCore.getModSubs(false);
excludeGlobal.forEach(val => {
subs.splice(subs.indexOf(val), 1);
});
massAction(subs);
}
}
}
function completeCheck (failedSubs) {
const failed = failedSubs.length;
self.log(`${failed} subs failed`);
if (failed > 0) {
self.log(`${failed} subs failed`);
const retry = confirm(`Action complete, however ${failed} failed. Would you like to retry these?`);
if (retry) {
self.log('retrying');
massAction(failedSubs);
} else {
self.log('not retrying');
$('.mod-popup').remove();
}
} else {
self.log('complete');
$('.mod-popup').remove();
// TBui.textFeedback('Mod actions complete' + subreddit, TBui.FEEDBACK_POSITIVE);
}
}
function massAction (subs) {
const failedSubs = [];
TBui.longLoadSpinner(true, 'Performing mod action', TBui.FEEDBACK_NEUTRAL);
Promise.all(subs.map(async subreddit => {
TBui.textFeedback(`${actionName}ning /u/${user} from /r/${subreddit}`, TBui.FEEDBACK_POSITIVE);
self.log(`performing action in: ${subreddit}`);
if (settingState) {
const params = {
user,
action,
subreddit,
};
// Only send ban-related fields if performing a ban action
if (action === 'banned') {
params.banReason = banReason;
params.banMessage = banMessage;
params.banDuration = banDuration;
params.banContext = banContext;
}
await TBApi.friendUser(params, false).then(response => {
if (response.json.errors.length) {
throw new Error('There were one or more errors banning the user');
}
}).catch(() => {
// catches the above `errors.length` condition as well as network errors
self.log('missed one');
failedSubs.push(subreddit);
});
} else {
await TBApi.unfriendUser(user, action, subreddit, false).catch(() => {
// only catches network errors because unfriend is weird
self.log('missed one');
failedSubs.push(subreddit);
});
}
})).then(() => {
TBui.longLoadSpinner(false);
window.setTimeout(() => {
completeCheck(failedSubs);
}, 2000);
});
}
});
// send a message to the user.
$body.on('click', '.mod-popup .message-send', function () {
let subject;
let message;
TBui.longLoadSpinner(true);
const $popup = $(this).parents('.mod-popup');
const user = $popup.find('.user').text();
const subreddit = $popup.find('.subreddit').text();
const $callbackSpan = $popup.find('#subreddit-message-callback');
const $subredditMessageSubject = $popup.find('.subreddit-message-subject');
const $subredditMessage = $popup.find('.subreddit-message');
if (!$subredditMessageSubject.val() || !$subredditMessage.val()) {
$callbackSpan.text('You forgot a subject or message');
$callbackSpan.css('color', 'red');
TBui.longLoadSpinner(false);
return;
} else {
subject = $subredditMessageSubject.val();
message = $subredditMessage.val();
}
TBApi.sendMessage(user, subject, message, subreddit).then(response => {
if (response.json.errors.length) {
$callbackSpan.text(response.json.errors[1]);
TBui.textFeedback(response.json.errors[1], TBui.FEEDBACK_NEGATIVE);
TBui.longLoadSpinner(false);
} else {
TBui.textFeedback('message sent.', TBui.FEEDBACK_POSITIVE, 1500);
$callbackSpan.text('message sent');
$callbackSpan.css('color', 'green');
TBui.longLoadSpinner(false);
}
}).catch(error => {
$callbackSpan.text(`an error occurred: ${error[0][1]}`);
TBui.longLoadSpinner(false);
});
});
// Flair ALL THE THINGS
$body.on('click', '.tb-window-tabs .user_flair', async function () {
const $popup = $(this).parents('.mod-popup');
const user = $popup.find('.user').text();
const subreddit = $popup.find('.subreddit').text();
const $textinput = $popup.find('.flair-text');
const $classinput = $popup.find('.flair-class');
const $flairDropdown = $popup.find('#flair-template-id-select');
if (!user || !subreddit) {
return;
}
const userFlairInfo = await TBApi.apiOauthPOST(`/r/${subreddit}/api/flairselector`, {name: user}).then(r =>
r.json()
);
userFlairTemplates = await TBApi.apiOauthGET(`/r/${subreddit}/api/user_flair_v2`).then(r => r.json());
if (!userFlairInfo.current) {
return;
}
TBStorage.purifyObject(userFlairInfo);
$textinput.val(userFlairInfo.current.flair_text);
$classinput.val(userFlairInfo.current.flair_css_class);
if (userFlairInfo.current.flair_template_id) {
$classinput
.attr('disabled', '')
.attr('title', 'Changing the class is disabled when using a flair template.');
}
if ($flairDropdown[0].options.length > 1) {
return;
}
userFlairTemplates.forEach(flair =>
$flairDropdown.append(`
<option
value="${flair.id}"
${userFlairInfo.current.flair_template_id === flair.id ? 'selected' : ''}
style="background-color: ${flair.background_color ? flair.background_color : 'initial'}; color: ${
flair.text_color === 'dark' ? '#000' : '#fff'
};"
>
${flair.text}
</option>
`)
);
$flairDropdown.change(e => {
if (!e.target.value) {
$textinput.val('');
$classinput
.val('')
.removeAttr('title')
.removeAttr('disabled');
return;
}
const selectedFlair = userFlairTemplates.find(el => el.id === e.target.value);
$textinput.val(selectedFlair.text);
$classinput
.val(selectedFlair.css_class)
.attr('disabled', '')
.attr('title', 'Changing the class is disabled when using a flair template.');
});
});
// Edit save button clicked.
$body.on('click', '.flair-save', function () {
const $popup = $(this).parents('.mod-popup');
const $status = $popup.find('.status');
const user = $popup.find('.user').text();
const subreddit = $popup.find('.subreddit').text();
const text = $popup.find('.flair-text').val();
const css_class = $popup.find('.flair-class').val();
const templateID = $popup.find('#flair-template-id-select').val();
TBui.textFeedback('saving user flair...', TBui.FEEDBACK_NEUTRAL);
TBApi.flairUser(user, subreddit, text, css_class, templateID).then(() => {
TBui.textFeedback('saved user flair', TBui.FEEDBACK_POSITIVE);
}).catch(error => {
self.error('Error saving user flair:', error);
TBui.textFeedback(`failed to save user flair: ${error.message}`, TBui.FEEDBACK_NEGATIVE);
$status.text(`error: ${error.message}`);
});
});
}
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 4.0.2</a> on Mon Dec 30 2024 00:15:02 GMT+0000 (Coordinated Universal Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/search.js" defer></script>
</body>
</html>