forked from samliew/SO-mod-userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserReviewBanHelper.user.js
1546 lines (1313 loc) · 60 KB
/
UserReviewBanHelper.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
// ==UserScript==
// @name User Review Ban Helper
// @description Display users' prior review bans in review, Insert review ban button in user review ban history page, Load ban form for user if user ID passed via hash
// @homepage https://github.com/samliew/SO-mod-userscripts
// @author Samuel Liew
// @version 9.1.13
//
// @include */review/close*
// @include */review/reopen*
// @include */review/suggested-edits*
// @include */review/helper*
// @include */review/low-quality-posts*
// @include */review/triage*
// @include */review/first-questions*
// @include */review/first-answers*
// @include */review/late-answers*
//
// @include */users/account-info/*
// @include */users/history/*?type=User+has+been+suspended+from+reviewing
// @include */users/*?tab=activity&sort=reviews*
// @include */users/*?tab=activity&sort=suggestions*
//
// @include */admin/review/failed-audits*
// @include */admin/review/audits*
// @include */admin/review/suspensions*
// @include */admin/links
//
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/se-ajax-common.js
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/common.js
// @require https://raw.githubusercontent.com/userscripters/storage/master/dist/browser.js
// ==/UserScript==
/* globals StackExchange, Store, fkey, SOMU, MS, _window */
/// <reference types="./globals" />
'use strict';
// This is a moderator-only userscript
if (!isModerator()) return;
const superusers = [584192, 6296561];
const isSuperuser = superusers.includes(selfId);
const disableGApiPrompts = true;
const messageCharLimit = 2000;
const defaultBanMessage = `A number of your [recent reviews](${location.origin}/users/current?tab=activity&sort=reviews) were incorrect. We suspect that you are not giving each task adequate attention. Please pay more attention to each review in future.`;
const permaBanMessage = `Due to your [poor review history](${location.origin}/users/current?tab=activity&sort=reviews) as well as no signs of improvement after many review suspensions, you won't be able to use any of the review queues on the site any longer.`;
// Use {POSTLINK} and {QUEUENAME} placeholders
const cannedMessages = {
current: '',
triageQuestionReqEdits: `You took incorrect action on the following task(s):\n{POSTLINK}. Choose the "Needs author edit" action for questions that should be closed and can be only improved/clarified by the question-asker. The "Needs community edit" action should only be used when other community users (like yourself) are able to improve an answerable question with editing or formatting. When in doubt, use the Skip action.`,
helperEditPoor: `Your review on {POSTLINK} wasn't helpful. If a question should be closed and you are unable to make the question on-topic in the "Help and Improvement" review, please use "Skip" instead of making trivial changes.`,
postNaa: `You recently reviewed this post {POSTLINK}. Although it was posted as an answer, it clearly did not attempt to provide an answer to the question. You should have flagged it as "not an answer" so that it could be removed.`,
postNaaEdited: `You recently edited this post {POSTLINK}. Please do not edit posts that should have been deleted. Use "edit" only when your edit salvages the post and makes it a valid answer.`,
postNaaCommentOnly: `You recently reviewed this post {POSTLINK}. Although you correctly identified it as not being an answer, you chose to leave a comment. That did not help to solve the problem. You should have flagged it as "not an answer" so that it could be removed.`,
postLinkOnly: `You recently reviewed this post {POSTLINK}. It contained nothing more than a link to an off-site resource, which does not meet our minimum standards for an answer (${location.origin}/help/how-to-answer). You should have flagged it as "not an answer" or "very low quality" so that it could be removed.`,
postEditPoor: `You approved poor edits to this post {POSTLINK}, which should have been rejected. Please pay more attention to each review in future.`,
postEditPlagiarism: `You reviewed this post {POSTLINK} incorrectly. The suggested edit was for the most part, plagiarism, and should have been rejected. Please pay more attention to each review in future.`,
postSpam: `You recently reviewed this spam post {POSTLINK} without flagging it as spam. Please pay more attention to each review in future.`,
failedAudit: `You have made too many incorrect reviews. For an example of a task you should have reviewed differently, see: {POSTLINK}.`,
recentGeneral: defaultBanMessage,
noLongerWelcome: permaBanMessage
};
// Use {QUEUEHELPLINK} placeholders
const cannedMessageSuffix = `\n\nBeing suspended can be a frustrating experience, but your help in moderation is still important. In the meantime, you can refer to {QUEUEHELPLINK} for more information, and revisit your [recent reviews](${location.origin}/users/current?tab=activity&sort=reviews) to see if you could have taken a different action instead.`;
const defaultCannedMessageHelpLink = `*[What are the review queues, and how do they work?](https://meta.stackexchange.com/q/161390)*`;
const cannedMessagesHelpLinks = {
current: defaultCannedMessageHelpLink,
triageQuestionReqEdits: `*[Getting banned from Triage reviews](https://meta.stackoverflow.com/q/389148)* and *[How does the Triage queue work?](https://meta.stackoverflow.com/q/295650)*`,
helperEditPoor: `*[The Help & Improvement Queue FAQ](https://meta.stackoverflow.com/q/287466)*`,
postNaa: `*[How should I get started reviewing Late Answers and First Posts?](https://meta.stackoverflow.com/q/288505)*`,
postNaaEdited: `*[How should I get started reviewing Late Answers and First Posts?](https://meta.stackoverflow.com/q/288505)*`,
postNaaCommentOnly: `*[How should I get started reviewing Late Answers and First Posts?](https://meta.stackoverflow.com/q/288505)*`,
postLinkOnly: `*[How should I get started reviewing Late Answers and First Posts?](https://meta.stackoverflow.com/q/288505)*`,
postEditPoor: defaultCannedMessageHelpLink,
postEditPlagiarism: defaultCannedMessageHelpLink,
postSpam: defaultCannedMessageHelpLink,
failedAudit: defaultCannedMessageHelpLink,
recentGeneral: defaultCannedMessageHelpLink,
noLongerWelcome: null // do not show suffix
};
// For review ban message
let textarea;
let params, uid, posts, reviewAction, allposts = '', posttext = '';
// Review unban user
function reviewUnban(uid) {
return new Promise(function (resolve, reject) {
if (typeof uid === 'undefined' || uid === null) { reject(); return; }
$.post({
url: `${location.origin}/admin/review/unsuspend-user`,
data: {
'fkey': fkey,
'userId': uid
}
})
.done(resolve)
.fail(reject);
});
}
// Review ban user
function reviewBan(uid, duration = 4, message = defaultBanMessage) {
return new Promise(function (resolve, reject) {
if (typeof uid === 'undefined' || uid === null) { reject(); return; }
$.post({
url: `${location.origin}/admin/review/suspend-user`,
data: {
'fkey': fkey,
'userId': uid,
'explanation': message,
'reviewSuspensionChoice': 'on',
'reviewSuspensionDays': duration
}
})
.done(resolve)
.fail(reject);
});
}
function reviewPermaBan(uid) {
return new Promise(function (resolve, reject) {
reviewUnban(uid).then(() =>
reviewBan(uid, 365, permaBanMessage)
.then(resolve).catch(reject)
).catch(reject);
});
}
// Find out if user is currently review banned and returns relative days to ban end date
// X > 0 : review banned for X more days
// X <= 0 : X days since ban
function daysReviewBanned(banStart, banDuration) {
let banEndDatetime = new Date(banStart);
// Simple validation
if (isNaN(banDuration) || banDuration <= 0) return false;
if (banEndDatetime.toString() == "Invalid Date") return false;
// Calculate ban end
banEndDatetime.setDate(banEndDatetime.getDate() + banDuration);
// Return difference (in days) to current time
return (banEndDatetime.getTime() - Date.now()) / 86400000;
}
function isReviewBanned(banStart, banDuration) {
return daysReviewBanned(banStart, banDuration) > 0;
}
function initCannedMessages() {
const cans = $(`<div id="canned-messages"></div>`).on('click', 'a', function (evt) {
textarea.val(this.dataset.message);
$('.js-lookup-result input:submit').focus(); // focus submit button
return false;
}).appendTo('.message-wrapper');
Object.keys(cannedMessages).forEach(function (v) {
let queuename = '';
if (posts && posts.length == 1) {
queuename = posts[0].split('/')[0] + ' ';
allposts = allposts.replace(/(\n|\r)+/g, '');
}
let suffix = cannedMessagesHelpLinks[v] !== null ? cannedMessageSuffix.replace(/{QUEUEHELPLINK}/g, cannedMessagesHelpLinks[v]) : '';
let msg = cannedMessages[v].replace(/"/g, '"').replace(/{POSTLINK}/g, allposts).replace(/{QUEUENAME}\s?/g, queuename);
if (posts && posts.length == 1) {
msg = msg.replace(/(\(\n|\n\))/g, '');
}
cans.append(`<a data-message="${msg}${suffix}">${v}</a>`);
});
}
// Completely new page
function initFailedAuditsByUserPage() {
document.title = 'Failed Review Audits - ' + StackExchange.options.site.name;
const queues = [
['Close Review', 'close'],
['First Questions', 'first-questions'],
['First Answers', 'first-answers'],
['Late Answers', 'late-answers'],
['Low Quality Posts', 'low-quality-posts'],
['Reopen Votes', 'reopen'],
['Suggested Edits', 'suggested-edits'],
['Triage', 'triage'],
];
// Valid values: last30days, last14days, last7days, last2days, today
const dateRange = 'last30days';
const cont = $('#content').removeClass('d-flex').addClass('failed-audits-page')
.empty().prepend(`<h1 class="bb bc-black-5 py8 s-subheader">Failed Audits (${dateRange.replace(/(\d+)/, ' $1 ')})</h1>`);
cont.append(`
<table class="history-table-filter"><tr>
<td><label class="d-block pt6"><input type="checkbox" id="js-toggle-date-format" /> toggle format</label></td>
<td><input type="text" id="js-filter-user" class="s-input s-input__sm w100" placeholder="username or userid" /></td>
<td></td>
<td></td>
</tr></table>`)
.on('change', '#js-toggle-date-format', function () {
cont.toggleClass('js-absolute-dates');
})
.on('change', '#js-filter-user', function () {
const rows = $('.s-table tr');
const val = this.value.toLowerCase().trim();
const userid = Number(val);
if (!isNaN(userid) && userid > 0) {
rows.hide().filter(function () {
const link = $(this).find('a').attr('href');
return link ? link.includes(`/users/${userid}/`) : false;
}).show();
}
else if (val.length > 0) {
rows.hide().filter(function () {
return $(this).find('a').first().text().toLowerCase().includes(val);
}).show();
}
else {
rows.show();
}
});
const filterField = $('#js-filter-user');
queues.forEach(q => {
cont.append(`<h3 class="s-subheader mt32 py8 bb bc-black-5"><a href="${location.origin}/admin/review/audits?queue=${q[1]}&daterange=${dateRange}&failuresOnly=true" target="_blank">${q[0]}</a></h3>`);
let numPages = 3;
if (q[1] === 'first-questions') numPages = 5; // add more pages for first questions and first answers queues
for (let i = 1; i <= numPages; i++) {
$(`<div id="${q[1]}-review-${i}"><i>loading...</i></div>`).appendTo(cont).load(`${location.origin}/admin/review/audits?queue=${q[1]}&daterange=${dateRange}&failuresOnly=true&page=${i} #content .s-table`, function () {
$(`#${q[1]}-review-${i}`).find('thead').remove();
filterField.trigger('change');
});
}
});
// Once on page load, read user querystring to filter results
const uid = Number(getQueryParam('uid')) || "";
filterField.val(uid);
}
/* For review pages */
function getUsersInfo() {
// If triage queue
if (location.pathname.includes('/review/triage/')) {
// Sort by action
$('.js-review-instructions .review-results').detach().sort(function (a, b) {
const ax = $(a).children('b').last().text();
const bx = $(b).children('b').last().text();
return ax < bx ? -1 : 1;
}).appendTo('.js-review-instructions');
// Add review-ban button for users who selected "Looks OK"
$(`<button class="s-btn s-btn__sm s-btn__filled mt12 js-ban-looksok">Review ban "Looks OK"</button>`).appendTo('.reviewable-post-stats').on('click', function () {
$('.review-results').filter((i, el) => el.innerText.includes('Looks OK')).find('.reviewban-link').each((i, el) => el.trigger('click'));
$(this).remove();
}).wrap('<div></div>');
// Add review-ban button for users who selected "Needs community edit"
$(`<button class="s-btn s-btn__sm s-btn__filled mt12 js-ban-reqedit">Review ban "Needs community edit"</button>`).appendTo('.reviewable-post-stats').on('click', function () {
$('.review-results').filter((i, el) => el.innerText.includes('Needs community edit')).find('.reviewban-link').each((i, el) => el.trigger('click'));
$(this).remove();
_window.top.close();
}).wrap('<div></div>');
// Add review ban all button
$(`<button class="s-btn s-btn__sm s-btn__filled mt12">Review ban ALL</button>`).appendTo('.reviewable-post-stats').on('click', function () {
$(this).parents('.reviewable-post-stats').find('.js-ban-looksok, .js-ban-reqedit').trigger('click');
$(this).remove();
_window.top.close();
}).wrap('<div></div>');
}
const reviewTaskId = location.pathname.split('/').pop();
// Get users review history
$('.js-review-instructions').find('a[href^="/users/"]').each(function () {
// Ignore mods
const hasModFlair = $(this).next('.mod-flair');
if (hasModFlair.length) return;
const uid = getUserId(this.getAttribute('href'));
const url = '/users/history/' + uid + '?type=User+has+been+suspended+from+reviewing';
const action = $(this).nextAll('b').last().text().toLowerCase().trim().replace(/\W+/g, '-');
const reviewActionQuerystring = `&reviewAction=${action}`;
// Can't get user id
if(!uid) return;
// Append review action to suspend link
$(this).nextAll('a').first()
.attr('href', function (i, href) {
return href + (href.includes('/suspend-user?') ? reviewActionQuerystring : `/suspend-user?userId=${uid}&reviewTaskId=${reviewTaskId}` + reviewActionQuerystring);
})
.attr({
'title': 'suspend user from reviews',
'target': '_blank',
})
.text((i, v) => v.replace(' user from reviews', ''));
// Skip fetching history for supermods since we will already be fetching that while attempting to ban
if (isSuperuser) {
// Grab user review ban history
$.ajax({
url: url,
xhr: jQueryXhrOverride,
success: function (data) {
// Parse user history page
var numBans = 0;
var summary = $('#summary', data);
var numBansLink = summary.find('a[href="?type=User+has+been+suspended+from+reviewing"]').get(0);
if (typeof numBansLink !== 'undefined') {
numBans = Number(numBansLink.nextSibling.nodeValue.match(/\d+/)[0]);
}
// Add annotation count
$(`<a class="reviewban-count ${numBans >= 10 ? 'warning' : ''}" href="${url}" title="${numBans} prior review suspensions" target="_blank">${numBans}</a>`)
.insertBefore(this);
}
});
}
});
}
/* For review ban page */
function getUserReviewBanHistory(uid) {
const url = `${location.origin}/users/history/${uid}?type=User+has+been+suspended+from+reviewing`;
// Change window/tab title so we can visually see the progress
document.title = '3.HISTORY';
// Grab user's history page
$.get(url).then(function (data) {
// Change window/tab title so we can visually see the progress
document.title = '4.READY';
// Parse user history page
let numBans = 0;
const summary = $('#summary', data);
const eventRows = $('#user-history tbody tr', data);
// Get number from filter menu, because user might have been banned more times and events will overflow to next page
const numBansLink = summary.find('a[href="?type=User+has+been+suspended+from+reviewing"]').get(0);
if (typeof numBansLink !== 'undefined') {
numBans = Number(numBansLink.nextSibling.nodeValue.match(/\d+/)[0]);
}
// Add annotation count
const banCountDisplay = $(`<div class="reviewban-history-summary">User was previously review suspended <b><a href="${url}" title="view history" target="_blank">${numBans} time${pluralize(numBans)}</a></b>. </div>`)
.insertAfter('.message-wrapper');
banCountDisplay.nextAll().wrapAll('<div class="grid history-duration-wrapper"><div class="grid--cell4 duration-wrapper"></div></div>');
const pastReviewMessages = $('<div class="grid--cell12 reviewban-history"></div>').appendTo('.history-duration-wrapper');
// Change user profile link to directly link to user reviews tab page
$('.duration-wrapper a').first().attr('href', (i, v) => v + '?tab=activity&sort=reviews').attr('title', 'view other recent reviews by user');
// Default to first radio button
$('.duration-radio-group input').first().trigger('click');
// Get hist items from filtered page
const histItems = eventRows.map(function (i, el) {
const event = Object.assign({}, null); // plain object
let startDate = new Date($(el).find('.relativetime').attr('title'));
let endDate = new Date(startDate);
event.begin = startDate;
event.reason = el.children[2].innerHTML.split('duration =')[0];
event.mod = el.children[2].innerHTML.split(/(duration = \d+ days?|{"Duration":\d+})/i)[2].replace(/\s*by\s*/, '');
event.duration = Number(el.children[2].innerText.match(/(\= (\d+) day|:(\d+)})/m)[0].replace(/\D+/g, ''));
// calculate end datetime
endDate.setDate(endDate.getDate() + event.duration);
event.end = endDate;
return event;
}).get();
// Append hist items to pastReviewMessages
histItems.forEach(function (event) {
pastReviewMessages.append(`
<div class="item">
<div class="item-meta">
<div><span class="relativetime" title="${dateToIsoString(event.begin)}">${event.begin.toDateString() + ' ' + event.begin.toLocaleTimeString()}</span></div>
<div>${event.duration} days</div>
<div><span class="relativetime" title="${dateToIsoString(event.end)}">${event.end.toDateString() + ' ' + event.end.toLocaleTimeString()}</span></div>
<div>${event.mod}</div>
</div>
<div class="item-reason">${event.reason}</div>
</div>`);
});
// No items
if (histItems.length == 0) {
pastReviewMessages.append('<em>(none)</em>');
}
else {
pastReviewMessages.find('a').attr('target', '_blank'); // links open in new tab/window
StackExchange.realtime.updateRelativeDates();
}
// Add copyable CommonMark review link
pastReviewMessages.find('.item-reason').each(function () {
const reviewLinks = $(this).children('a[href*="/review/"]');
if (reviewLinks.length == 0) return;
const links = reviewLinks.get().map(v => {
const b = v.href.split('/review/')[1];
return `[${b}](/review/${b})`;
});
$(`<input value="${links.join(', ')}" class="js-review-textlinks s-input s-input__sm" />`).insertAfter(this);
});
pastReviewMessages.on('focus', '.js-review-textlinks', function () {
this.select();
});
// Add currently/recently banned indicator if history found
let isCurrentlyBanned = false;
let isRecentlyBanned = false;
let newDuration = null, recommendedDuration = null;
let daysago = new Date();
daysago.setDate(daysago.getDate() - 60);
eventRows.eq(0).each(function () {
const datetime = new Date($(this).find('.relativetime').attr('title'));
const duration = Number(this.innerText.match(/(\= (\d+) day|:(\d+)})/m)[0].replace(/\D+/g, ''));
let banEndDatetime = new Date(datetime);
banEndDatetime.setDate(banEndDatetime.getDate() + duration);
const currtext = banEndDatetime.getTime() > Date.now() ? 'Current' : 'Recent';
newDuration = duration;
recommendedDuration = duration;
// Recent, double duration
if (banEndDatetime > daysago) {
isRecentlyBanned = true;
$(`<span class="reviewban-ending ${currtext === 'Current' ? 'current' : 'recent'}"><span class="type" title="recommended to double the previous ban duration">${currtext}ly</span> review suspended for <b>${duration} days</b> until <span class="relativetime" title="${dateToIsoString(banEndDatetime)}">${banEndDatetime}</span>.</span>`)
.appendTo(banCountDisplay);
newDuration *= 2;
// Also add warning to the submit button if currently banned
if (currtext === 'Current') {
isCurrentlyBanned = true;
$('.js-lookup-result input:submit').addClass('s-btn__danger s-btn__filled js-ban-again').val((i, v) => v + ' again');
}
}
// Halve duration
else {
$(`<span class="reviewban-ending">Last review suspended for <b>${duration} days</b> until <span class="relativetime" title="${dateToIsoString(banEndDatetime)}">${banEndDatetime}</span>.</span>`)
.appendTo(banCountDisplay);
newDuration = Math.ceil(duration / 2);
}
console.log('Calculated suspension duration:', newDuration);
// Select recommended duration radio from available options
if (newDuration < 2) newDuration = 2; // min duration
if (newDuration > 365) newDuration = 365; // max duration
$('.duration-radio-group input').each(function () {
if (Number(this.value) <= newDuration + (newDuration / 7)) {
this.click();
recommendedDuration = Number(this.value);
}
});
console.log('Closest suspension duration option:', recommendedDuration);
});
// If sam is review banning users in Triage
if (isSuperuser && location.hash.includes('/triage')) {
// If reviewAction is "Looks OK", and user is currently banned for >= 16, ignore (close tab)
if (reviewAction == 'looks-ok' && isCurrentlyBanned && recommendedDuration >= 8) {
_window.top.close();
}
// If recommended is up to 8, auto submit form
else if (recommendedDuration == null || recommendedDuration <= 8) {
// Change window/tab title so we can visually see which has been auto-processed
document.title = '5.AUTOBAN';
$('.js-lookup-result form').trigger('submit');
}
}
// If is currently banned, add confirmation prompt when trying to ban user
if (!isSuperuser && isCurrentlyBanned) {
$('.js-lookup-result form').on('submit', function () {
return confirm('User is currently review suspended!\n\nAre you sure you want to replace with a new ban?');
});
}
});
}
async function doPageLoad() {
// New suspend user form
if (location.pathname === '/admin/review/suspensions/suspend-user') {
const uid = getQueryParam('userId');
if (!uid) return;
const warning = $('.js-lookup-result .s-notice.s-notice__warning');
const isCurrentlySuspended = warning.length > 0 ? warning.text().includes('currently suspended') : false;
// Can't continue if user is currently suspended. Add a button to help us unban easily.
if (isCurrentlySuspended) {
const unbanAndRefreshBtn = $(`<a class="fr mtn8 s-btn s-btn__filled s-btn__sm">Unsuspend user and try again</a>`).appendTo(warning);
unbanAndRefreshBtn.on('click', function () {
reviewUnban(uid).then(() => {
location.reload();
});
});
}
// Keep button enabled
setInterval(() => $('.js-add-selected-actions').attr('disabled', false), 1000);
// TODO: Work in-progress
return;
}
// New historical page
else if (location.pathname === '/admin/review/suspensions/historical') {
// Load histories in a new window (instead of popup) to take advantage of userscript
$('.js-show-suspension-history').replaceWith(function (i, el) {
return `<a href="${location.origin}/admin/review/suspensions/historical/${this.dataset.userid}" target="_blank">${this.innerText}</a>`;
});
}
// New user historical page
else if (location.pathname.startsWith('/admin/review/suspensions/historical/')) {
const wrapper = $('.js-individual-history');
const heading = wrapper.children().first();
const notice = wrapper.find('aside.s-notice.s-notice__warning');
const table = wrapper.find('table.s-table').first();
const isBanned = notice.find('b').text().includes('currently suspended');
// Wrap heading text in a span
heading.addClass('d-flex');
$(heading.get(0).childNodes).wrapAll(`<span class="pt4"></span>`);
// Add additional links to new pages
heading.append(`<a href="/admin/review/failed-audits?uid=${currentUserId}" target="_blank" class="float-right s-btn s-btn__sm mr12" title="view all recently failed audits from all queues on a single page">see all failed audits</a>`);
if (isBanned) {
// Currently banned, show unban button
$(`<a class="fr s-btn s-btn__sm s-btn__filled s-btn__danger reviewban-button">Review Unban</a>`)
.on('click', function () {
if (confirm('Unban user from reviewing?')) {
$(this).remove();
reviewUnban(currentUserId);
}
})
.appendTo(heading);
}
// Move duration from third to second column for a little consistency
table.find('tr').each(function () {
const aftEl = $(this).children().eq(0);
$(this).children().eq(2).insertAfter(aftEl);
});
// Remove expando arrow icons
$('.js-message-grid > .flex--item').remove();
// Expand all messages
$('.js-message-body-container').removeClass('d-none');
// Remove unsuspended by column to save horizontal space
if (table.find('thead th').length === 6 && table.find('thead th').last().text().includes('Unsuspended')) {
table.find('tr').find('th, td').filter(':last-child').remove();
}
}
// Review suspension page /admin/review/suspensions
else if (location.pathname === '/admin/review/suspensions') {
const table = $('.js-current-suspensions, .js-historical-grid table').first();
// Save space on all columns except reason
table.find('thead th').addClass('w0').eq(4).removeClass('w0');
// Each table item row
table.find('tbody tr').each(function () {
const uid = this.dataset.userId;
// Remove (History) link to save space
const firstCell = $(this).children('td').eq(0);
firstCell.removeClass('ws-nowrap').addClass('w128').find('a').last().remove();
firstCell.html(function (i, html) {
return html.replace(/[\(\)\s]+$/, '');
});
// Linkify ban counts to user review ban history page
const countCell = $(this).children('td').eq(5);
countCell.addClass('px0').html(function (i, v) {
//return `<a href="/users/history/${uid}?type=User+has+been+suspended+from+reviewing" target="_blank" title="see review suspension history">${v}</a>`; // Old method uses user mod history filter
return `<a href="/admin/review/suspensions/historical/${uid}" class="px6" target="_blank" title="see review suspension history">${v}</a>`; // New user ban history page
});
});
// BETTER ban titles if "general" or "custom" type
$('.js-message-body-container').each(function () {
const btn = $(this).parent().find('.js-message-type');
if (!/(Custom|General)/i.test(btn.text())) return;
const reason = $(this).text().toLowerCase();
// Permabanned
if (/(won't be able|(any|no) longer|no signs of improvement)/.test(reason)) {
btn.text('Permabanned');
}
// Approved Plagiarism
else if (/approve/.test(reason) && /plagiari([sz]ed|sm)/.test(reason)) {
btn.text('Approved plagiarism');
}
// Approved Vandalism
else if (/approve/.test(reason) && /vandalis[]/.test(reason)) {
btn.text('Approved vandalism');
}
});
// Fix table date sorting
/*
setTimeout(() => {
if($('#banned-users-table').length == 0) return;
$.tablesorter.destroy('.sorter', true, function() {
// Add classes to date column headers
const headers = $('thead th', table);
headers.slice(1,3).addClass('sorter-miniDate').removeClass('headerSortDown');
headers.eq(3).addClass('sorter-false');
headers.last().addClass('sorter-false');
// Add duration column header
headers.eq(2).after(`<th class="tablesorter-header tablesorter-headerUnSorted">Duration</th>`);
// Reinit sorter
$('.sorter').tablesorter();
// Default sort header
headers.eq(1).addClass('tablesorter-headerDesc');
});
}, 2000);
*/
// Add duration column header
table.find('thead tr th').eq(2).after(`
<th scope="col" data-target="s-table.column" data-action="click->s-table#sort" class="w0">
Length
<svg aria-hidden="true" class="js-sorting-indicator js-sorting-indicator-asc svg-icon iconArrowUpSm" width="14" height="14" viewBox="0 0 14 14"><path d="M3 9h8L7 5 3 9z"></path></svg>
<svg aria-hidden="true" class="js-sorting-indicator js-sorting-indicator-desc svg-icon iconArrowDownSm d-none" width="14" height="14" viewBox="0 0 14 14"><path d="M3 5h8L7 9 3 5z"></path></svg>
<svg aria-hidden="true" class="js-sorting-indicator js-sorting-indicator-none svg-icon iconArrowUpDownSm d-none" width="14" height="14" viewBox="0 0 14 14"><path d="M7 2l4 4H3l4-4zm0 10l4-4H3l4 4z"></path></svg>
</th>`);
// Add duration column to the other rows
table.find('tbody tr').each(function () {
const cells = $(this).children('td');
let startDate = new Date(cells.eq(1).find('.relativetime').attr('title')).getTime();
let endDate = new Date(cells.eq(2).find('.relativetime').attr('title')).getTime();
let diffDays = (endDate - startDate) / 86400000;
cells.eq(2).after(`<td class="ta-center va-top">${diffDays}</td>`);
});
// Option to renew permanent bans
$('.js-message-body-container', table).filter((i, el) => el.innerText.includes('no longer welcome') || el.innerText.includes('no signs') || el.innerText.includes('any longer')).each(function () {
const row = $(this).closest('tr');
const reasonTemplate = $(this).parent().find('.js-message-type').text('Permabanned');
const unsuspendButton = row.find('.js-unsuspend');
const rebanLink = unsuspendButton.clone().insertAfter(this);
rebanLink.removeClass('s-btn__link js-unsuspend').addClass('s-btn__xs s-btn__filled mt8 js-suspend-again')
.attr('title', (i, s) => s.replace('Unsuspend', 'Renew review permaban for').replace(' from reviewing', '')).text((i, s) => s.replace('Unsuspend', 'Renew permaban'));
unsuspendButton.hide();
});
table.on('click', '.js-suspend-again', function (i, btn) {
if (confirm("Apply another year's suspension to this user?")) {
const uid = this.dataset.userid;
reviewPermaBan(uid).then(() => {
btn.replaceWith(`<em>done!</em>`);
});
}
return false;
});
// Add summary of currently review-banned users if we are not review banning users
if (!(location.hash === '' && location.search === '')) return;
const weekAgo = Date.now() - MS.oneWeek;
const weekAhead = Date.now() + MS.oneWeek;
const rows = table.find('tbody tr');
const banReasons = rows.find('.js-message-body-container');
const banTitles = banReasons.prev();
const reqEditing = banReasons.filter((i, el) => el.innerText.match(/(requires editing|needs community edit)/i)).length;
const forTriage = banReasons.filter((i, el) => el.innerText.toLowerCase().includes('triage')).length;
const auditFailures = banTitles.filter((i, el) => {
return el.innerText.includes('(Auto)');
}).length;
const hundred = rows.filter((i, el) => el.children[3].innerText >= 100).length;
const permaban = banReasons.filter((i, el) => el.innerText.match(/(no|any) (longer|signs)/)).length;
const firstTimers = rows.filter((i, el) => el.children[6].innerText == 1).length;
const fiveTimers = rows.filter((i, el) => el.children[6].innerText >= 5).length;
const tenTimers = rows.filter((i, el) => el.children[6].innerText >= 10).length;
const pastDay = rows.filter((i, el) => el.children[1].innerText.match(/(just|min|hour)/)).length;
const pastWeek = rows.filter((i, el) => new Date(el.children[1].children[0].title) > weekAgo).length;
const unbanDay = rows.filter((i, el) => el.children[2].innerText.match(/(just|min|hour)/)).length;
const unbanWeek = rows.filter((i, el) => new Date(el.children[2].children[0].title) < weekAhead).length;
// Grab constant stats; the usernames of the reviewers (without the "Bot" label or the diamond), plus the length for stats
const banners = rows.map((i, el) => el.children[4].children[0].innerText);
const totalBans = rows.length;
// Count elements
let bannerMap = {};
for (let username of banners) {
bannerMap[username] = (bannerMap[username] + 1) || 1;
}
let bannerHtml = "<div><br>Mod stats:<br><ul>";
for (let [username, count] of Object.entries(bannerMap)) {
bannerHtml += `<li>${username}: ${count} (${(count / totalBans * 100.0).toFixed(2)}%)</li>`;
}
bannerHtml += "</ul></div>";
// This gets added to the end of bannedStats, after copyTable if it's loaded
const bannerStats = $(bannerHtml);
const durations = rows.map((i, el) => Number(el.children[3].innerText)).get();
const tally = {
'count4': durations.filter(v => v <= 4).length,
'count8': durations.filter(v => v > 4 && v <= 8).length,
'count16': durations.filter(v => v > 8 && v <= 16).length,
'count32': durations.filter(v => v > 16 && v <= 32).length,
'count64': durations.filter(v => v > 32 && v <= 64).length,
'count128': durations.filter(v => v > 64 && v <= 128).length,
'count365': durations.filter(v => v > 128 && v <= 365).length,
'count366': durations.filter(v => v > 365).length
};
const bannedStats = $(`<div id="banned-users-stats" class="mb16"><ul>` +
(forTriage > 0 ? `<li><span class="copy-only">- </span>${forTriage} (${(forTriage / rows.length * 100).toFixed(1)}%) users are banned for Triage reviews in one way or another</li>` : '') +
(reqEditing > 0 ? `<li><span class="copy-only">- </span>${reqEditing} (${(reqEditing / rows.length * 100).toFixed(1)}%) users are banned for selecting "Needs community edit" in Triage when the question should be closed</li>` : '') + `
<li><span class="copy-only">- </span>${auditFailures} (${(auditFailures / rows.length * 100).toFixed(1)}%) users are automatically banned for failing multiple review audits</li>
<li><span class="copy-only">- </span>${firstTimers} (${(firstTimers / rows.length * 100).toFixed(1)}%) users are banned for the first time</li>
<li><span class="copy-only">- </span>${fiveTimers} (${(fiveTimers / rows.length * 100).toFixed(1)}%) users have at least five review bans</li>
<li><span class="copy-only">- </span>${tenTimers} (${(tenTimers / rows.length * 100).toFixed(1)}%) users have at least ten review bans</li>
<li><span class="copy-only">- </span>${hundred} (${(hundred / rows.length * 100).toFixed(1)}%) users have a duration of at least 100 days, of which ${permaban} users are permabanned</li>
<li><span class="copy-only">- </span>${pastDay} (${(pastDay / rows.length * 100).toFixed(1)}%) users are banned within the past day</li>
<li><span class="copy-only">- </span>${pastWeek} (${(pastWeek / rows.length * 100).toFixed(1)}%) users are banned within the past week</li>
<li><span class="copy-only">- </span>${unbanDay} (${(unbanDay / rows.length * 100).toFixed(1)}%) users will be unbanned by tomorrow</li>
<li><span class="copy-only">- </span>${unbanWeek} (${(unbanWeek / rows.length * 100).toFixed(1)}%) users will be unbanned in the next seven days</li>
</ul>
Breakdown:<br>
<ul>
<li><span class="copy-only">- </span><=4 : ${tally.count4} users (${(tally.count4 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>4 to <=8 : ${tally.count8} users (${(tally.count8 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>8 to <=16 : ${tally.count16} users (${(tally.count16 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>16 to <=32 : ${tally.count32} users (${(tally.count32 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>32 to <=64 : ${tally.count64} users (${(tally.count64 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>64 to <=128 : ${tally.count128} users (${(tally.count128 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>128 to <=365 : ${tally.count365} users (${(tally.count365 / rows.length * 100).toFixed(1)}%)</li>
<li><span class="copy-only">- </span>>365 : ${tally.count366} users (${(tally.count366 / rows.length * 100).toFixed(1)}%)</li>
</ul>
</div>`);
// For easier copying data to a spreadsheet
const copyTable = $(`<table><tr>
<td class="pl4">${rows.length}</td>
<td class="pl4">${forTriage}</td>
<td class="pl4">${reqEditing}</td>
<td class="pl4">${auditFailures}</td>
<td class="pl4">${firstTimers}</td>
<td class="pl4">${fiveTimers}</td>
<td class="pl4">${tenTimers}</td>
<td class="pl4">${hundred}</td>
<td class="pl4">${permaban}</td>
<td class="pl4">${pastDay}</td>
<td class="pl4">${pastWeek}</td>
<td class="pl4">${unbanDay}</td>
<td class="pl4">${unbanWeek}</td>
<td class="pl4">${tally.count4}</td>
<td class="pl4">${tally.count8}</td>
<td class="pl4">${tally.count16}</td>
<td class="pl4">${tally.count32}</td>
<td class="pl4">${tally.count64}</td>
<td class="pl4">${tally.count128}</td>
<td class="pl4">${tally.count365}</td>
<td class="pl4">${tally.count366}</td>
</tr></table>`);
// Add a table that we can copy into a spreadsheet
if (isSuperuser) {
copyTable.appendTo(bannedStats);
}
bannerStats.appendTo(bannedStats);
table.before(bannedStats);
bannedStats.prepend(`<span>Currently, there are ${rows.length} banned reviewers, out of which:</span>`).parent().addClass('banned-reviewers-section');
// Do not display upload to sheets option to all mods, so it's opt-in only
if (!isSuperuser) return;
const sheetsApiVersion = 4;
const sheetsApiBase = "https://sheets.googleapis.com";
const { locateStorage } = Store;
const storage = locateStorage();
window.addEventListener("load", async () => {
const name = "review_ban_helper_sheets_api";
const manager = typeof SOMU !== "undefined" ? SOMU : null;
if (manager) {
manager.store = storage;
manager.addOption(name, "client_id");
manager.addOption(name, "spreadsheet_id");
manager.addOption(name, "api_key");
}
const store = new Store.default(name, storage);
const appClientId = (manager && manager.getOptionValue(name, "client_id")) ||
await store.load("client_id") ||
(!disableGApiPrompts ? prompt("Enter the Google Cloud Project client id") : '');
const statsSpreadId = (manager && manager.getOptionValue(name, "spreadsheet_id")) ||
await store.load("spreadsheet_id") ||
(!disableGApiPrompts ? prompt("Enter the destination spreadsheet id") : '');
const sheetsApiKey = (manager && manager.getOptionValue(name, "api_key")) ||
await store.load("api_key") ||
(!disableGApiPrompts ? prompt("Enter the Sheets API key") : '');
await store.save("client_id", appClientId);
await store.save("spreadsheet_id", statsSpreadId);
await store.save("api_key", sheetsApiKey);
loadGAPI(appClientId, sheetsApiKey, statsSpreadId);
});
/**
* @param {string} clientId client id to use
* @param {string} apiKey API key to use
*/
const initGAPI = (clientId, apiKey) => {
return gapi.client.init({
apiKey,
clientId,
scope: "https://www.googleapis.com/auth/spreadsheets"
});
};
/**
* @param {string} apiBase base URL of the API
* @param {string|number} apiVer version of the API
* @param {string} id spreadsheet id
*/
const readValues = (apiBase, apiVer, id) => {
return gapi.client.request({
path: `${apiBase}/v${apiVer}/spreadsheets/${id}/values:batchGet`,
params: {
ranges: ["'Data'!A1:AB"],
majorDimension: "ROWS",
valueRenderOption: "UNFORMATTED_VALUE"
}
});
};
/**
* @param {string} apiBase base URL of the API
* @param {string|number} apiVer version of the API
* @param {string} id spreadsheet id
* @param {any[][]} values grid of values to set
* @param {string} range A1 range to insert into
*/
const updateValues = (apiBase, apiVer, id, values, range) => {
return gapi.client.request({
path: `${apiBase}/v${apiVer}/spreadsheets/${id}/values/${range}`,
method: "PUT",
body: { values },
params: { valueInputOption: "USER_ENTERED" }
});
};
/**
* @param {string} apiBase base URL of the API
* @param {string|number} apiVer version of the API
* @param {string} id spreadsheet id
* @param {any[][]} values grid of values to set
* @param {string} range A1 range to insert into
*/
const appendValues = (apiBase, apiVer, id, values, range) => {
return gapi.client.request({
path: `${apiBase}/v${apiVer}/spreadsheets/${id}/values/${range}:append`,
method: "POST",
body: { values },
params: { valueInputOption: "USER_ENTERED" }
});
};
/**
* @param {string} num serial number date
*/
const getDateValueFromSerialNumber = (num) => {
const dec30th1899 = -2209170617000;
return dec30th1899 + parseFloat(num) * 864e5;
};
/**
* @param {gapi.client.HttpRequestFulfilled<any>} response API response
* @param {string} raw non-JSON response from the API
*/
const handleValues = (response, raw) => {
if (!response) {
console.debug(`Sheets API did not respond with JSON:\n\n${raw}`);
return;
}
const { result } = response;
const { valueRanges, spreadsheetId } = result;
const today = new Date();
const todayReset = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate()
);
const todayVal = todayReset.valueOf();
const [{ values }] = valueRanges;
const { length: numRows } = values;
let rowIdx = numRows - 1;
for (rowIdx; rowIdx >= 0; rowIdx--) {
const [serialNumber] = values[rowIdx];
if (!serialNumber) continue;
const date = getDateValueFromSerialNumber(serialNumber);
if (date.valueOf() <= todayVal) break;
}
const newData = [[
todayReset.toISOString().slice(0, 10),
rows.length, // total banned, TODO: reuse
forTriage,
reqEditing,
auditFailures,
firstTimers,
fiveTimers,
tenTimers,
hundred,
permaban,
pastDay,
pastWeek,
unbanDay,
unbanWeek,
tally.count4,
tally.count8,
tally.count16,
tally.count32,
tally.count64,
tally.count128,
tally.count365,
tally.count366