-
Notifications
You must be signed in to change notification settings - Fork 2
/
UserStalkerHelper.user.js
1471 lines (1364 loc) · 57.2 KB
/
UserStalkerHelper.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 Stalker Helper
// @namespace https://github.com/SOBotics/UserStalker
// @description Helper userscript for interacting with reports from the User Stalker bot posted in certain Stack Exchange chat rooms.
// @author Cody Gray
// @contributor Oleg Valter
// @contributor VLAZ
// @version 3.2.4
// @homepageURL https://github.com/SOBotics/UserStalkerHelper
// @updateURL https://github.com/SOBotics/UserStalkerHelper/raw/master/UserStalkerHelper.user.js
// @downloadURL https://github.com/SOBotics/UserStalkerHelper/raw/master/UserStalkerHelper.user.js
// @supportURL https://github.com/SOBotics/UserStalkerHelper/issues
// @icon https://raw.githubusercontent.com/SOBotics/UserStalkerHelper/master/UserStalkerHelper.png
// @icon64 https://raw.githubusercontent.com/SOBotics/UserStalkerHelper/master/UserStalkerHelper64.png
//
// @match *://chat.stackexchange.com/rooms/59667/*
// @match *://chat.stackexchange.com/search*room=59667
//
// @match *://chat.stackexchange.com/rooms/132064/*
// @match *://chat.stackexchange.com/search*room=132064
//
// @match *://chat.stackexchange.com/transcript/*
// @match *://chat.stackexchange.com//transcript/*
//
// @match *://chat.stackoverflow.com/rooms/239107/*
// @match *://chat.stackoverflow.com/search*room=239107
//
// @match *://chat.stackoverflow.com/rooms/239425/*
// @match *://chat.stackoverflow.com/search*room=239425
//
// @match *://chat.stackoverflow.com/transcript/*
// @match *://chat.stackoverflow.com//transcript/*
//
// @connect stackoverflow.com
// @connect superuser.com
// @connect serverfault.com
// @connect askubuntu.com
// @connect mathoverflow.net
// @connect stackexchange.com
// @connect stackapps.com
//
// @require https://unpkg.com/sweetalert/dist/sweetalert.min.js
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// @run-at document-end
// ==/UserScript==
/* eslint-disable no-multi-spaces */
/* global $:readonly */ // SO/SE sites always provides jQuery, free-of-charge
/* global CHAT:readonly */ // \ these two global objects always
/* global fkey:readonly */ // / exist on SO/SE chat.* domains
/* global swal:readonly */ // defined by the @required "sweetalert" library
(() =>
{
/**********************************************
* Global Constants
**********************************************/
'use strict';
// Registered on Stack Apps in order to obtain an API key.
// Client ID is 21280 (https://stackapps.com/apps/oauth/view/21280)
const SE_API_KEY = 'F9msnTSnUmKMKD7BnjHAxA((';
const GM_XML_HTTP_REQUEST = ((typeof GM !== 'undefined') ? GM.xmlHttpRequest.bind(GM)
: GM_xmlhttpRequest); /* eslint-disable-line no-undef */
const IS_TRANSCRIPT = window.location.pathname.startsWith('/transcript') ||
window.location.pathname.startsWith('//transcript');
const IS_SEARCH = window.location.pathname.startsWith('/search');
const BOT_ACCOUNT_ID = {
'chat.stackexchange.com': 530642,
'chat.stackoverflow.com': 17363584,
}[window.location.hostname];
const BOMB_EMOJI = String.fromCodePoint(0x1F4A3);
const BOMB_IMAGE_URL = 'https://raw.githubusercontent.com/joypixels/emoji-assets/master/png/32/1f4a3.png';
const RENAME_EMOJI = String.fromCodePoint(0x1F4DD);
const RENAME_IMAGE_URL = 'https://raw.githubusercontent.com/joypixels/emoji-assets/master/png/32/1f4dd.png';
const CHECK_EMOJI = String.fromCodePoint(0x2714);
const CHECK_IMAGE_URL = 'https://raw.githubusercontent.com/joypixels/emoji-assets/master/png/32/2714.png';
const CROSS_EMOJI = String.fromCodePoint(0x274C);
const CROSS_IMAGE_URL = 'https://raw.githubusercontent.com/joypixels/emoji-assets/master/png/32/274c.png';
const DESTROY_OPTIONS =
{
spammer:
{
description : 'Spam in user profile.',
templateName : 'destroy spammer',
suspendReason: 'for promotional content',
},
evasion:
{
description : 'Recreated troll and/or suspension-evasion account.',
templateName : 'no longer welcome',
suspendReason: 'because of low-quality contributions',
},
custom:
{
description : 'A custom reason:',
templateName : 'destroy user',
suspendReason: 'for rule violations',
},
};
/**********************************************
* Initialization
**********************************************/
// Attempt to restrict the running of this script to users with moderator privileges.
// Unfortunately, there's no way to detect whether the current user is a moderator
// from the transcript pages, so we just punt in that case. It cannot actually do
// any *harm* to run this script without moderator privileges; it just won't do
// any *good*, either.
if (!((CHAT?.RoomUsers?.current?.().is_moderator) /* for normal room */ ||
(($('.topbar-menu-links').text().includes('\u2666'))) /* for search */ ||
(CHAT && IS_TRANSCRIPT) /* for transcript */))
{
return;
}
(() => // initialization function
{
appendStyles();
if (document.location.href.includes('chat.stackoverflow.com/rooms/239425') ||
document.location.href.includes('chat.stackexchange.com/rooms/132064'))
{
document.getElementById('chat-body').classList.add('userstalker-testing');
}
$('#getmore, #getmore-mine').click(() => decorateExistingMessages(500));
$('body').on('click', 'img.userstalker-nuke-button' , onClickNukeButton);
$('body').on('click', 'img.userstalker-rename-button', onClickRenameButton);
$('body').on('click', 'span.userstalker-check-button', onClickCheckButton);
$('body').on('click', 'span.userstalker-cross-button', onClickCrossButton);
decorateExistingMessages(0);
if (CHAT?.addEventHandlerHook)
{
CHAT.addEventHandlerHook(chatMessageListener);
}
}
)(window);
/**********************************************
* Chat Message Listeners & Decorators
**********************************************/
function chatMessageListener({event_type, user_id, message_id})
{
if ((event_type === 1) && (user_id === BOT_ACCOUNT_ID))
{
setTimeout(() => { decorateChatMessage($(`#message-${message_id}`)); });
}
}
function decorateExistingMessages(timeout)
{
decorateChatMessages();
const chat = $(/^\/(?:search|users)/.test(window.location.pathname) ? '#content'
: '#chat, #transcript');
chat.one('DOMSubtreeModified', () =>
{
// A second timeout is required because the first modification
// to the DOM occurs before the chat messages have been loaded.
setTimeout(() =>
{
if (chat.html().length > 0) { decorateChatMessages(); }
else { setTimeout(decorateExistingMessages, timeout, timeout); }
}, timeout);
});
}
function decorateChatMessages()
{
$(`.user-${BOT_ACCOUNT_ID} .message`).each((i, element) => decorateChatMessage(element));
}
function decorateChatMessage(message)
{
const $message = $(message);
const messageId = $message.attr('id').replace(/^(message-)/, '');
if (!($message.find('.userstalker-nuke-button').length))
{
// Match only <a>s that are direct descendants of .content in order to
// exclude those <a>s that are wrapped within a <strike>.
const userLink = $message.find('.content > a + a[href*="/users/"]');
if (userLink.length > 0)
{
userLink[0].classList.add('userstalker-user-link');
// The transcript and search pages don't open links in a new window by default,
// so fix that. Although it is normally considered dreadful behavior to wrest
// this control out of the user's hands, in this case, we don't want to lose
// our place in the transcript, and if one is used to handling it from the
// room view (where links do open in a new window by default), one might be
// caught very off-guard and end up all discombobulated. Can't have that!
//
// The simple solution for this is to check (IS_TRANSCRIPT || IS_SEARCH)
// and set the "target" attribute to "_blank". However, instead of "_blank",
// we can use "blank", which will reuse the same window/tab. This opens up
// a new possibility, where the "target" attribute is forcibly set to "blank"
// everywhere, including in the normal chat view (which defaults to opening
// links in a new tab, as if "_blank" were set). This makes it possible to
// rapidly assess multiple user profiles by clicking one, moving the window
// to a second screen, and then clicking additional ones to update the
// profile displayed in that same window.
userLink[0].target = 'blank';
// Add the inline links.
const userUrl = userLink.attr('href');
const content = userLink.parent();
const contentHtml = content.html();
content.html(contentHtml.replace(/(User Stalker<\/a> \] (?!✔ )?)(✔ )?(?!<strike>)/,
function($0, $1, $2)
{
return $1
+ ($2 ?? '<span class="userstalker-check-button"'
+ ' title="mark this user account as appearing to be legitimate"'
+ ` data-messageid="${messageId}"`
+ ` data-userurl="${userUrl}"`
+ `>${CHECK_EMOJI}</span>`
+ ' ')
+ ' '
+ '<span class="userstalker-cross-button"'
+ ' title="mark this user account as already destroyed"'
+ ` data-messageid="${messageId}"`
+ ` data-userurl="${userUrl}"`
+ `>${CROSS_EMOJI}</span>`
+ ' '
+ '<img class="userstalker-nuke-button"'
+ ` src="${BOMB_IMAGE_URL}"`
+ ` alt="${BOMB_EMOJI}"`
+ ' title="destroy this user account"'
+ ' width="32" height="32"'
+ ` data-messageid="${messageId}"`
+ ` data-userurl="${userUrl}"`
+ '>'
+ ' '
+ ($2 ? ''
: '<img class="userstalker-rename-button"'
+ ` src="${RENAME_IMAGE_URL}"`
+ ` alt="${RENAME_EMOJI}"`
+ ' title="reset this user\'s display name and send a boilerplate mod message about it"'
+ ' width="32" height="32"'
+ ` data-messageid="${messageId}"`
+ ` data-userurl="${userUrl}"`
+ '>'
+ ' ')
;
}));
}
}
}
/**********************************************
* Chat Helper Functions
**********************************************/
/**
* Retrieves the fkey for the current (moderator) user's chat account on the current chat server.
*/
async function getChatFkey()
{
if (fkey?.fkey)
{
return fkey.fkey();
}
// The "search" page does not define the user's chat FKEY anywhere,
// so we need to fetch it from a page that does.
const result = await GM_XML_HTTP_REQUEST(
{
method : 'GET',
url : window.location.origin,
});
const fkeyInput = $(result.response).find('input#fkey');
if (fkeyInput.length)
{
return fkeyInput.val();
}
// TODO: Remove alert from this and other helper functions;
// centralize error reporting in one place.
alert('Failed to get your chat account\'s FKEY.');
throw new Error('Failed to get your chat account\'s FKEY.');
}
/**
* Retrieves the contents of a chat message on the current chat server.
* @param {string} fkeyChat The fkey for the current (moderator) user on the chat server.
* @param {number} messageId The ID of the chat message to retrieve.
*/
async function getChatMessageText(fkeyChat, messageId)
{
const params = new URLSearchParams(
{
fkey : fkeyChat,
plain: 'true',
});
const url = new URL(`${window.location.origin}/message/${messageId}`);
url.search = params.toString();
const result = await GM_XML_HTTP_REQUEST(
{
method : 'GET',
url : url.toString()
});
if (!(result?.response))
{
throw new Error('Failed to get the text of the specified chat message.');
}
return result.response;
}
/**
* Edits the contents of a chat message on the current chat server.
* @param {string} fkeyChat The fkey for the current (moderator) user on the chat server.
* @param {number} messageId The ID of the chat message to edit.
* @param {string} messageText The new contents of the chat message.
*/
async function editChatMessage(fkeyChat, messageId, messageText)
{
do
{
for (let attempts = 0; attempts < 5; ++attempts)
{
try
{
const result = await Promise.resolve($.post(`${window.location.origin}/messages/${messageId}`,
{
fkey: fkeyChat,
text: messageText,
}));
if (result)
{
// The transcript and search pages do not auto-update when a message is edited,
// so force a refresh at this point.
if (IS_TRANSCRIPT || IS_SEARCH)
{
setTimeout(() => { window.location.reload(); },
1000);
}
return;
}
else
{
alert('DEBUG: Operation failed, without throwing an exception. This should probably be investigated, as it was not the expected behavior.');
throw new Error('Failed to edit chat message.');
}
}
catch (ex)
{
const timeout = (2 * (attempts + 1));
console.warn(`Failed to edit chat message; trying again in ${timeout} seconds.`);
await new Promise((result) => setTimeout(result, (timeout * 1000)));
}
}
} while (confirm('Failed to edit chat message, despite multiple retries. Do you want to try again now?'));
}
/**
* Edits a chat message from the User Stalker bot on the current chat server to prepend and/or append text in the appropriate places.
* @param {number} messageId The ID of the chat message to edit.
* @param {string} messagePrefix The string to prepend to the chat message.
* @param {string} messageSuffix The string to append to the chat message.
*/
async function bookendChatMessage(messageId, messagePrefix, messageSuffix)
{
const fkeyChat = await getChatFkey();
const messageText = await getChatMessageText(fkeyChat, messageId);
const messageTag = messageText.match(/\[ \[.*\]\(.*\) \] /)[0];
if (!messageTag)
{
throw new Error('Failed to find expected pattern in chat message from User Stalker bot.');
}
// Prevent the modified chat message from becoming longer than the maximum supported length.
const messageContents = messageText.slice(messageTag.length,
500 - (messagePrefix.length + messageSuffix.length));
return editChatMessage(fkeyChat,
messageId,
`${messageTag}${messagePrefix}${messageContents}${messageSuffix}`);
}
/**
* Edits a chat message from the User Stalker bot on the current chat server to add strike-through formatting.
* @param {number} messageId The ID of the chat message to edit.
*/
async function strikeoutChatMessage(messageId)
{
const STRIKEOUT_MARKDOWN = '---';
return bookendChatMessage(messageId, STRIKEOUT_MARKDOWN, STRIKEOUT_MARKDOWN);
}
/**
* Edits a chat message from the User Stalker bot on the current chat server to add a checkmark.
* @param {number} messageId The ID of the chat message to edit.
*/
async function checkmarkChatMessage(messageId)
{
return bookendChatMessage(messageId, `${CHECK_EMOJI} `, '');
}
function extractDetectionReasonsFromChatMessageText(chatMessageText)
{
const iReasonsStart = chatMessageText.indexOf('(') + 1;
let iReasonsEnd = chatMessageText.indexOf(')');
if (iReasonsEnd === -1)
{
// If the character count got too long to fit into a single message, the bot
// will automatically break it up into multiple messages, but this means
// that the trailing parenthesis will not be found, so just take it all
// the way to the end.
iReasonsEnd = chatMessageText.length;
}
let detectionReasons = chatMessageText.substring(iReasonsStart, iReasonsEnd);
if (iReasonsEnd === -1)
{
detectionReasons += '...';
}
return detectionReasons;
}
/**********************************************
* Main Site General Helper Functions
**********************************************/
function getUserIdFromUrl(userUrl)
{
return Number(userUrl.match(/(?:\/u(?:sers)?\/)(-?\d+)\//)[1]);
}
/**
* Retrieves the "ticks" value from the specified site.
* @param {string} siteHostname The full host name of a main site.
*/
async function getTicks(siteHostname)
{
if (siteHostname == null)
{
throw new Error('The required "siteHostname" parameter is missing.');
}
const result = await GM_XML_HTTP_REQUEST(
{
method : 'GET',
url : `//${siteHostname}/questions/ticks`,
});
if (!(result?.response))
{
throw new Error('Failed to retrieve "ticks" value.');
}
return result.response;
}
/**
* Retrieves the fkey for the current user's account on the specified site.
* @param {string} siteHostname The full host name of a main site.
*/
async function getMainSiteFkey(siteHostname)
{
if (siteHostname == null)
{
throw new Error('The required "siteHostname" parameter is missing.');
}
const result = await GM_XML_HTTP_REQUEST(
{
method : 'GET',
url : `//${siteHostname}`
});
const fkeyInput = $(result.response).find('input[name="fkey"]');
if (!fkeyInput)
{
throw new Error('Failed to retrieve "fkey" value for main site.');
}
return fkeyInput.val();
}
/**********************************************
* SE API Helper Functions
**********************************************/
/**
* Retrieves information for the specified user account on the specified site.
* @param {string} siteHostname The full host name of a main site.
* @param {number} userId The ID of the user account to retrieve information about.
*/
function getUserInfofromApi(siteHostname, userId)
{
return new Promise(function(resolve, reject)
{
if ((siteHostname == null) ||
(userId == null))
{
reject();
}
// NOTE: Must be explicitly prefixed with "https://" in order to avoid a
// CORS violation. Yes, even though the current protocol for the
// page is already "https://"...
$.get(`https://api.stackexchange.com/2.3/users/${userId}?`
+ `&site=${siteHostname}`
+ '&sort=creation'
+ '&order=desc'
+ '&filter=!0QpX)x1ay6IhAe)0*WS(wn'
+ `${SE_API_KEY ? `&key=${SE_API_KEY}` : ''}`)
.done((data) =>
{
if (data.items[0].user_id == userId)
{
resolve(data.items[0]);
}
else
{
reject();
}
})
.fail(reject);
});
}
/**********************************************
* Main Site User-Specific Helper Functions
**********************************************/
/**
* Retrieves PII for the specified user account on the specified site.
* @param {string} mainSiteFkey The fkey for the current (moderator) user on the main site.
* @param {string} siteHostname The full host name of a main site.
* @param {number} userId The ID of the user account to retrieve information about.
*/
async function getUserPii(mainSiteFkey, siteHostname, userId)
{
if ((mainSiteFkey == null) ||
(siteHostname == null) ||
(userId == null))
{
throw new Error('One or more required parameters is missing.');
}
const data = new URLSearchParams(
{
'fkey': mainSiteFkey,
'id' : userId.toString(),
});
const result = await GM_XML_HTTP_REQUEST(
{
method : 'POST',
url : `//${siteHostname}/admin/all-pii`,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data : data.toString()
});
const html = $(result.responseText);
const ip = html.find('div:contains("IP Address:") + div > span.ip-address-lookup');
return { name : html.find('div:contains("Real Name:") + div > a').text().trim(),
email : html.find('div:contains("Email:") + div > a').text().trim(),
ip : ip.text().trim(),
tor : ip.data('tor').trim(),
};
}
/**
* Edits the profile for the specified user account on the specified site.
* @param {string} mainSiteFkey The fkey for the current (moderator) user on the main site.
* @param {string} siteHostname The full host name of a main site.
* @param {number} userId The ID of the user account to edit.
* @param {object} profileData The user profile data fields, to pass as the "data" for the request.
*/
async function editUserInfo(mainSiteFkey, siteHostname, userId, profileData)
{
if ((mainSiteFkey == null) ||
(siteHostname == null) ||
(userId == null))
{
throw new Error('One or more required parameters is missing.');
}
// Get "ticks" value, which substitutes for the hidden "i1l" field on the
// user profile "edit" page, which cannot be retrieved programmatically.
const ticks = await getTicks(siteHostname);
// A delay of at least 2 seconds is required between fetching the "ticks"
// value and submitting the edit to the profile. This is an old bug that
// manifests not only programmatically, but also when attempting to edit
// the profile using the web interface. Apparently, this throttle is a
// "security" measure. See: https://meta.stackexchange.com/q/223761 and
// https://meta.stackexchange.com/q/183508, with answers by (former)
// SE developers.
await new Promise((result) => setTimeout(result, 2000));
// Ensure that certain fields in the specified data are set properly.
profileData.set('fkey', mainSiteFkey);
profileData.set('i1l', ticks);
// Submit the request to edit the user profile.
return GM_XML_HTTP_REQUEST(
{
method : 'POST',
url : `//${siteHostname}/users/edit/${userId}/post`,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data : profileData.toString()
});
}
/**
* Edits the profile for the specified user account on the specified site, resetting the display name to the default (auto-generated) value.
* @param {string} mainSiteFkey The fkey for the current (moderator) user on the main site.
* @param {string} siteHostname The full host name of a main site.
* @param {number} userId The ID of the user account to edit.
*/
async function resetUserDisplayName(mainSiteFkey, siteHostname, userId)
{
const profileData = new URLSearchParams(
{
'fields' : '',
'author' : '',
'push' : true, // copy changes to all sites
'DisplayName' : '', // clear this field (will implicitly set to default/auto)
//'RealName' : '', // do not reset this field
//'ProfileImageUrl': '', // do not reset this field
//'Location' : '', // do not reset this field
//'LocationPlaceId': '', // do not reset this field
//'Title' : '', // do not reset this field
//'WebsiteUrl' : '', // do not reset this field
//'TwitterUrl' : '', // do not reset this field
//'GitHubUrl' : '', // do not reset this field
//'AboutMe' : '', // do not reset this field
});
return editUserInfo(mainSiteFkey, siteHostname, userId, profileData);
}
/**
* Edits the profile for the specified user account on the specified site, removing all fields that might contain spam.
* @param {string} mainSiteFkey The fkey for the current (moderator) user on the main site.
* @param {string} siteHostname The full host name of a main site.
* @param {number} userId The ID of the user account to edit.
*/
async function bowdlerizeUserInfo(mainSiteFkey, siteHostname, userId)
{
const profileData = new URLSearchParams(
{
'fields' : '',
'author' : '',
'push' : true, // copy changes to all sites
'DisplayName' : 'Spammer',
//'RealName' : '', // do not reset this field
'ProfileImageUrl': '',
'Location' : '',
'LocationPlaceId': '',
'Title' : '',
'WebsiteUrl' : '',
'TwitterUrl' : '',
'GitHubUrl' : '',
'AboutMe' : '',
});
return editUserInfo(mainSiteFkey, siteHostname, userId, profileData);
}
function sendModMessage(mainSiteFkey,
siteHostname,
userId,
templateName = '',
suspendReason = 'for rule violations',
message = '',
sendEmail = true,
suspendDays = 0)
{
return new Promise(function(resolve, reject)
{
if ((mainSiteFkey == null) ||
(siteHostname == null) ||
(userId == null))
{
reject();
}
if ((templateName == null) || (templateName.trim().length === 0))
{
alert('Mod message template name cannot be empty.');
reject();
}
if ((suspendReason == null) || (suspendReason.trim().length === 0))
{
alert('Mod message suspension reason cannot be empty.');
reject();
}
if ((message == null) || (message.trim().length === 0))
{
alert('Mod message body cannot be empty.');
reject();
}
if ((suspendDays < 0) || (suspendDays > 365))
{
alert('Invalid number of days to suspend.');
reject();
}
const data = new URLSearchParams(
{
'fkey' : mainSiteFkey,
'userId' : userId,
'lastMessageDate': 0,
'email' : sendEmail,
'suspendUser' : (suspendDays > 0),
'suspend-choice' : ((suspendDays > 0) ? suspendDays : 0),
'suspendDays' : suspendDays,
'templateName' : templateName,
'suspendReason' : suspendReason,
'templateEdited' : false,
'post-text' : message,
'author' : null,
});
GM_XML_HTTP_REQUEST(
{
method : 'POST',
url : `//${siteHostname}/users/message/save`,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data : data.toString(),
onload : resolve,
onerror: reject,
onabort: reject,
});
});
}
async function destroyUserHelper(mainSiteFkey,
siteHostname,
userInfo,
details)
{
do
{
for (let attempts = 0; attempts < 10; ++attempts)
{
try
{
const data = new URLSearchParams(
{
'fkey' : mainSiteFkey,
'annotation' : '',
'deleteReasonDetails' : '',
'mod-actions' : 'destroy',
'destroyReason' : 'This user was created to post spam or nonsense and has no other positive participation',
'destroyReasonDetails': details,
});
const result = await GM_XML_HTTP_REQUEST(
{
method : 'POST',
url : `//${siteHostname}/admin/users/${userInfo.user_id}/destroy`,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data : data.toString(),
});
if ((result != null) && (result.status == 200))
{
return true;
}
else
{
throw new Error(`Failed to destroy user account: API returned error ${result.status}.`);
}
}
catch (ex)
{
const timeout = (attempts + 1);
console.warn(ex + ` Trying again in ${timeout} second(s).`);
await new Promise((result) => setTimeout(result, (timeout * 1000)));
}
}
} while (confirm('Failed to destroy user account, despite multiple retries. Do you want to try again now?'));
return false;
}
function destroyUser(mainSiteFkey,
siteHostname,
userInfo,
bowdlerizeFirst = false,
destroyDetails = null)
{
return new Promise(function(resolve, reject)
{
if ((mainSiteFkey == null) ||
(siteHostname == null) ||
(userInfo?.user_id == null))
{
reject();
}
// If destroyDetails was not provided, prompt user interactively for additional details.
if ((destroyDetails == null) || (!destroyDetails.trim().length))
{
destroyDetails = prompt('Please enter a more detailed message to include with the destroyed user record, if desired.' +
'\n' +
'(Cancel button safely terminates without destroying the account.)');
}
// If destroyDetails is still not provided, reject the promise and return early.
if (destroyDetails == null)
{
alert('Destroy operation cancelled: user was not destroyed.');
reject();
}
// Retrieve user PII, and record it in the additional details, to work around the fact
// that the system does not record this or make it accessible after account deletion.
// TODO: Retrieve "past names"!
// TODO: Retrieve "Title" field from profile. (Unfortunately, this field cannot be
// retrieved from the SE /users API, presumably because it is SO-only, so
// it must be scraped from the user's profile page on the site proper.)
getUserPii(mainSiteFkey, siteHostname, userInfo.user_id)
.then((pii) =>
{
(bowdlerizeFirst ? bowdlerizeUserInfo(mainSiteFkey, siteHostname, userInfo.user_id)
: Promise.resolve())
.then(() =>
{
const details = destroyDetails.trim()
+ '\n'
+ `\nDisplay Name: ${userInfo.display_name}`
+ `\nReal Name: ${pii.name}`
+ `\nEmail Address: ${pii.email}`
+ `\nIP Address: ${pii.ip} (tor: ${pii.tor})`
+ `\nCreation Date: ${userInfo.creation_date}`
+ `\nProfile Location: ${userInfo.location}`
+ `\nWebsite URL: ${userInfo.website_url}`
+ `\nAvatar Image: ${userInfo.profile_image}`
;
destroyUserHelper(mainSiteFkey, siteHostname, userInfo, details)
.then(resolve)
.catch(reject);
})
.catch(reject);
})
.catch(reject);
});
}
function nukeUser(mainSiteFkey,
siteHostname,
userInfo,
bowdlerizeFirst,
destroyDetails = null,
templateName = null,
suspendReason = null)
{
return new Promise(function(resolve, reject)
{
// If requested, apply the maximum suspension period (1 year) before destroying the account,
// skipping the sending of an email to the user's registered email address. Although most
// users won't see this message (since it'll only be displayed on the site, and we're about
// to destroy their account), it is possible they see it upon re-creation of the account.
// In that case, they can only see the first few words of the message in the global inbox
// (the system will notify them of a new message, though); they *cannot* click on the inbox
// item to view the full message. Therefore, we must keep it *very* short, if they are to
// be able to see anything. It's difficult to give much guidance, but this is a pretty good
// compromise. It is all that will fit in the preview, down to the *letter* (i.e., it is
// essential to use the contraction "you're"; "you are" makes the message too long)!
// See also: https://chat.stackexchange.com/transcript/message/59625219#59625219
const suspendFirst = !((templateName == null) && (suspendReason == null));
(suspendFirst ? sendModMessage(mainSiteFkey,
siteHostname,
userInfo.user_id,
templateName,
suspendReason,
'Account removed for spamming and/or abusive behavior. You\'re no longer welcome to participate here.',
false,
365)
: Promise.resolve())
.then(() =>
{
destroyUser(mainSiteFkey, siteHostname, userInfo, bowdlerizeFirst, destroyDetails)
.then(resolve)
.catch(reject);
})
.catch(reject);
});
}
/**********************************************
* Userscript UI & Handlers: Nuke Button
**********************************************/
function createDestroyOptions()
{
// Iterate through all of the properties in DESTROY_OPTIONS and create
// the appropriate DOM elements for each of them. Also wire up listeners
// for the "click" events.
const table = document.createElement('table');
for (let destroyOption in DESTROY_OPTIONS)
{
if (Object.prototype.hasOwnProperty.call(DESTROY_OPTIONS, destroyOption))
{
const id = destroyOption;
const row = document.createElement('tr');
row.innerHTML = `<td>
<input type = "radio"
name = "userstalker-destroy-reason"
value = "${id}"
id = "${id}"
/>
<label for="${id}">
${DESTROY_OPTIONS[destroyOption].description}
${(id === 'custom')
? '<textarea '
+ ' autocapitalize="sentences"'
+ ' autocomplete="on"'
+ ' autocorrect="on"'
+ ' placeholder="An optional explanation for why you are destroying the account, to be included with the deleted user profile '
+ '(e.g., "This user\'s profile is filled with Nazi propaganda and other hate speech.")."'
+ '></textarea>'
: ''}
</label>
</td>`;
table.appendChild(row);
row.addEventListener('click', (event) =>
{
if (destroyOption !== 'custom')
{
// For the non-custom option, where there's nothing else to do
// but submit after choosing one, pre-select the submit button.
document.querySelector('.swal-button--danger').focus();
}
else
{
// For the custom option, a click on the radio button should
// focus the textarea, and a click on the (always-visible)
// textarea should select the corresponding radio button.
const target = event.target;
if (target.tagName === 'INPUT')
{
row.querySelector('textarea').focus();
}
else if (target.tagName === 'TEXTAREA')
{
row.querySelector('input').checked = true;
}
}
document.querySelector('.swal-content input#userstalker-bowdlerize-toggle').checked = (destroyOption === 'spammer');
document.querySelector('.swal-content input#userstalker-suspend-toggle') .checked = (destroyOption !== 'spammer');
});
}
}
// Default to the first option being selected.
table.querySelector(`#${Object.keys(DESTROY_OPTIONS)[0]}`).checked = true;
return table;
}
function createDestroyPopupContent()
{
const content = createDestroyOptions();
const instructions = document.createElement('div');
instructions.classList.add('swal-text');
instructions.innerHTML = 'The reason you specify here will be saved in the record when this user account is destroyed. '
+ 'A reason is optional; if you don\'t want to include additional information, '
+ 'choose the "custom" reason and simply leave the associated textbox blank. '
+ 'The user\'s PII and other metadata will always be automatically fetched and '
+ 'included in the record.';
content.append(instructions);
const checkboxes = document.createElement('div');
checkboxes.classList.add('swal-content');
checkboxes.innerHTML = '<table>' +
'<tr>' +
'<td>' +
'<label title="Enabling this option will clear all fields in the user\'s profile to remove spam content and set the display name to "Spammer" before destroying the account. (The original info is still retrieved and recorded in the deleted user record.)">' +
'<input type="checkbox" name="userstalker-bowdlerize-toggle" id="userstalker-bowdlerize-toggle" checked />' +
'Bowdlerize profile and push edits to all sites before destroying' +
'</label>' +
'</td>' +
'</tr>' +
'<tr>' +
'<td>' +
'<label title="Enabling this option will automatically send a message that suspends the user for the maximum duration that is permitted for moderators (365 days) before destroying the account. This ensures that, even if the destroyed account is re-created at any time within the next year, it will be automatically suspended by the system, thus restricting the account\'s ability to post anything.">' +
'<input type="checkbox" name="userstalker-suspend-toggle" id="userstalker-suspend-toggle" />' +