-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEGO Forum Enhancement.ts
More file actions
2287 lines (2156 loc) · 84.6 KB
/
Copy pathEGO Forum Enhancement.ts
File metadata and controls
2287 lines (2156 loc) · 84.6 KB
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 EdgeGamers Forum Enhancement%RELEASE_TYPE%
// @namespace https://github.com/blankdvth/eGOScripts/blob/master/src/EGO%20Forum%20Enhancement.ts
// @version 4.11.7
// @description Add various enhancements & QOL additions to the EdgeGamers Forums that are beneficial for Leadership members.
// @author blank_dvth, Skle, MSWS, PixeL
// @match https://www.edgegamers.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=edgegamers.com
// @require https://peterolson.github.io/BigInteger.js/BigInteger.min.js
// @require https://s3.blankdvth.com/mirror-steamid-converter-min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js
// @require https://raw.githubusercontent.com/pieroxy/lz-string/861d3feda0c9a8b7a48aaf3c028ab57606f1c02f/libs/lz-string.min.js
// @require https://raw.githubusercontent.com/sizzlemctwizzle/GM_config/2207c5c1322ebb56e401f03c2e581719f909762a/gm_config.js
// @connect maul.edgegamers.com
// @connect api.findsteamid.com
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// ==/UserScript==
/// <reference path="../types/config/index.d.ts" />
/// <reference path="../types/moment.d.ts" />
/// <reference path="../types/lz-string.d.ts" />
/// <reference path="../types/forum_maul_c.d.ts" />
// Declare TypeScript types
interface Completed_Map {
originId: string;
completedId: string;
}
interface NavbarURL_Map {
text: string;
url: string;
}
interface CannedResponse {
name: string;
response: string;
}
const completedMap: Completed_Map[] = [];
const signatureBlockList: string[] = [];
const navbarURLs: NavbarURL_Map[] = [];
const navbarRemovals: string[] = [];
const autoMentionForums: string[] = [];
const cannedResponses: { [category: string]: CannedResponse[] } = {};
const appealForums: string[] = ["1234", "1236"];
const reportForums: string[] = ["1233", "1235"];
const countingURL: string = "https://www.edgegamers.com/threads/333944/";
/**
* Creates a preset button
* @param {string} text Button text
* @param {function(HTMLElementEventMap)} callback Function to call on click
* @returns {HTMLSpanElement} Button
*/
function createForumsPresetButton(
text: string,
id: string,
callback: (event: MouseEvent) => void,
): HTMLSpanElement {
const button = document.createElement("span");
button.classList.add("button");
button.innerHTML = text;
button.onclick = callback;
button.style.marginLeft = "4px";
button.style.marginTop = "4px";
button.dataset.presetId = id;
return button;
}
/**
* Adds a preset button to the div
* @param {string} name Name of button
* @param {HTMLDivElement} div Div to add to
* @param {function(HTMLElementEventMap)} func Function to call on click
*/
function addForumsPreset(
name: string,
id: string,
div: HTMLDivElement,
func: (event: MouseEvent) => void,
) {
div.appendChild(createForumsPresetButton(name, id, func));
}
/**
* Creates a button and adds it to the given div
* @param {string} href URL that button should link to
* @param {string} text Buttons' text
* @param {HTMLDivElement} div Div to add/append to
* @param {string} target Meta target for button
* @param {boolean} append True to append, false to insert
* @param {HTMLElement} ins_el Element to insert before, only used if append is false
*/
function createButton(
href: string,
text: string,
div: HTMLDivElement,
target: string = "_blank",
append: boolean = false,
ins_el: HTMLElement | null = null,
) {
const button = document.createElement("a");
button.href = href;
button.target = target;
button.classList.add("button--link", "button");
const button_text = document.createElement("span"); // Create button text
button_text.classList.add("button-text");
button_text.innerHTML = text;
// Add all elements to their respective parents
button.appendChild(button_text);
append
? div.appendChild(button)
: div.insertBefore(button, ins_el ?? div.lastElementChild);
}
/**
* Setup the configuration manager and create an event to find and add a button to open it
*/
function setupForumsConfig() {
// Initialize the configuration manager
GM_config.init({
id: "forums-config",
title: "Forums Enhancement Script Configuration",
fields: {
"maul-dropdown": {
label: "Use dropdown for MAUL links",
section: ["Feature Settings"],
title: "When checked, all additional MAUL links will be in a dropdown in the original MAUL button. When unchecked, all MAUL buttons will be added to the navigation bar after the MAUL button.",
type: "checkbox",
default: true,
},
"show-confidential-watermark": {
label: "Show confidential watermarks on LE forums",
title: "When checked, all LE forums will have a red confidential watermark on them.",
type: "checkbox",
default: true,
},
"confidential-reports": {
label: "Show confidential watermark on reports",
title: "When checked, reports will have a red confidential watermark on them. This only works if the above setting is enabled.",
type: "checkbox",
default: true,
},
"lookup-unknown-ids": {
label: "Lookup unknown Steam IDs",
title: "When checked, the script will attempt to lookup unknown IDs automatically by reaching out to an external API. Please ensure the ID is correct before taking any action, this is not always accurate.",
type: "checkbox",
default: true,
},
"show-list-bans-unknown": {
label: "Show List Bans for unknown Steam IDs",
title: "Whether to show the List Bans button alongside Lookup ID if the Steam ID is in an unknown format.",
type: "checkbox",
default: true,
},
"confirm-trash": {
label: "Confirm Trash",
title: "Whether to show a confirmation dialog when clicking the trash button.",
type: "checkbox",
default: true,
},
"maul-reauth-enable": {
label: "Enable MAUL Reauthenthication",
title: "When checked, the script will automatically reauthenthicate with MAUL in the background if it's been a while since the last authenthication (see timeout below).",
type: "checkbox",
default: true,
},
"maul-reauth": {
label: "MAUL Reauthenthication Timeout",
title: "The minimum duration to wait before automatically reauthenthicating MAUL in the background (in milliseconds).",
type: "int",
default: 1800000, // half an hour
min: 300000, // 5 minutes, we don't want to spam the server
},
"autofill-counting": {
label: "Autofill Counting",
title: " Autofill the next number in the counting thread on click.",
type: "checkbox",
default: true,
},
"logo-link": {
label: "Logo Link",
title: "Replace the link the eGO logo (top-left) links to with the given URL. Leave empty to disable.",
type: "text",
default: "",
},
"enable-post-unapprove-btn": {
label: "Enable post & unapprove button",
title: "Whether to add a button that will safely post an unapproved reply.",
type: "checkbox",
default: true,
},
"rich-override": {
label: "Allow post & unapprove in rich editor (NOT SUPPORTED)",
title: "The post & unapprove button in the rich editor is not supported, and will cause formatting issues in your message. If you want to use it anyway, check this box, no support will be provided.",
type: "checkbox",
default: false,
},
"move-to-completed-unchecked": {
label: "Completed Forums Map",
section: [
"Move to Completed",
'One map (forum -> completed) per line, use the format "origin id;completed id". The ID is usually present in the URL bar when viewing that subforum list (/forums/ID here), otherwise, open Inspect Element and look for the number after "node-" in "data-container-key" in the <html> tag. For example: "1234;1236".<br>Note: This will not apply until the page is refreshed (your updated maps also won\'t show if you reopen the config popup until you refresh).',
],
type: "textarea",
save: false,
default: "1234;1236\n1233;1235\n852;853",
},
"move-to-completed": {
type: "hidden",
default: "1234;1236\n1233;1235\n852;853",
},
"signature-block-unchecked": {
label: "Signature Block List",
section: [
"Signature Block List",
"List of User IDs whose signatures will be blocked from loading automatically, separated by newlines.",
],
type: "textarea",
save: false,
default: "",
},
"signature-block": {
type: "hidden",
default: "",
},
"navbar-urls-unchecked": {
label: "Navigation Bar URLs",
section: [
"Navigation Bar URLs",
"List of URLs to add to the navigation bar, separated by newlines. Each line should be in the format 'text;url'. Your URLs cannot have a semicolon in them.",
],
type: "textarea",
save: false,
default:
"GitLab;https://gitlab.edgegamers.io/\nGameME;https://edgegamers.gameme.com/",
},
"navbar-urls": {
type: "hidden",
default:
"GitLab;https://gitlab.edgegamers.io/\nGameME;https://edgegamers.gameme.com/",
},
"navbar-removals": {
label: "Navigation Bar Removals",
section: [
"Navigation Bar Removals",
"List of entries to remove from the navigation bar, separated by newlines. This removes the first full match for the text in the button, case-insensitive.",
],
type: "textarea",
default: "",
},
"auto-mention-unchecked": {
label: "Auto Mention (Subforum IDs)",
section: [
"Automention",
"Automatically mention the OP in the editor in certain forums. This is not guaranteed to work on the Rich Text editor (although it should).",
],
type: "textarea",
save: false,
default: "",
},
"auto-mention": {
type: "hidden",
default: "",
},
"auto-mention-newlines": {
label: "Number of newlines to add after mention",
title: "This may be off by one when using the Rich Text editor.",
type: "int",
min: 0,
default: 2,
},
"auto-mention-onclick": {
label: "Fill on click instead of on load",
type: "checkbox",
default: true,
},
"auto-mention-focus": {
label: "Focus after mentioning (only on load mode)",
type: "checkbox",
default: false,
},
"canned-responses-unchecked": {
label: "Canned Responses",
section: [
"Canned Responses",
"See <a href='https://github.com/blankdvth/eGOScripts/wiki/Canned-Responses' target='_blank'>this guide</a> on how to format your canned responses.",
],
type: "textarea",
save: false,
default: "",
},
"canned-responses": {
type: "hidden",
default: "",
},
"canned-response-min-width": {
label: "Minimum width of dropdown (in pixels)",
type: "int",
min: 0,
default: 125,
},
"canned-response-focus": {
label: "Focus after inserting canned response",
type: "checkbox",
default: true,
},
"canned-response-trigger-automention": {
label: "Attempt to trigger automention before inserting canned response",
type: "checkbox",
default: true,
},
"canned-responses-hide-scrollbar": {
label: "Hide scrollbars (scrolling will still work)",
title: "May not work on all browsers.",
type: "checkbox",
default: false,
},
"ban-display-enable": {
label: "Enable",
section: [
"Ban Display",
"Automatically retrieve and display ban info in appeals. Only works when MAUL is authenticated.",
],
type: "checkbox",
default: true,
},
"ban-display-hidden": {
label: "Hide behind button",
title: "Whether to hide the ban display behind a button.",
type: "checkbox",
default: false,
},
"ban-display-silent-fail": {
label: "Silently fail",
title: "Whether to silently fail when a ban cannot be retrieved. No error message will be shown.",
type: "checkbox",
default: false,
},
"ban-display-hyperlink": {
label: "Hyperlink",
title: "Whether to hyperlink URLs in ban notes.",
type: "checkbox",
default: true,
},
"ban-display-steamid": {
label: "Link Steam IDs",
title: "Whether to link Steam IDs to their MAUL List Bans page. This is a bit finnicky, turn it off if you're experiencing problems.",
type: "checkbox",
default: true,
},
"ban-display-show-expired": {
label: "Show expired bans",
title: "Whether to show bans info if the latest ban is expired.",
type: "checkbox",
default: false,
},
"ban-display-expiration-format": {
label: "Expiration Format",
title: "Format used to show expiration date",
type: "text",
default: "YYYY-MM-DD HH:mm",
},
"ban-display-show-date": {
label: "Show date",
title: "Whether to show the date of the ban in the display table.",
type: "checkbox",
default: true,
},
"ban-display-show-handle": {
label: "Show handle",
title: "Whether to show the handle in the display table.",
type: "checkbox",
default: true,
},
"ban-display-show-id": {
label: "Show Steam ID",
title: "Whether to show the Steam ID in the display table.",
type: "checkbox",
default: false,
},
"ban-display-show-division": {
label: "Show division",
title: "Whether to show the division in the display table.",
type: "checkbox",
default: false,
},
"ban-display-show-banning-admin": {
label: "Show banning admin",
title: "Whether to show the banning admin in the display table.",
type: "checkbox",
default: true,
},
"ban-display-show-admins-online": {
label: "Show admins online",
title: "Whether to show the admins online in the display table.",
type: "checkbox",
default: false,
},
"ban-display-show-duration": {
label: "Show duration",
title: "Whether to show the duration of the ban in the display table. The expiration is shown on hover.",
type: "checkbox",
default: true,
},
"ban-display-show-expiration": {
label: "Show expiration",
title: "Whether to show the expiration datetime of the ban in the display table. The duration is shown on hover.",
type: "checkbox",
default: false,
},
"ban-display-show-reason": {
label: "Show reason",
title: "Whether to show the reason for the ban in the display table.",
type: "checkbox",
default: true,
},
},
events: {
init: function () {
GM_config.set(
"move-to-completed-unchecked",
GM_config.get("move-to-completed"),
);
GM_config.set(
"signature-block-unchecked",
GM_config.get("signature-block"),
);
GM_config.set(
"navbar-urls-unchecked",
GM_config.get("navbar-urls"),
);
GM_config.set(
"auto-mention-unchecked",
GM_config.get("auto-mention"),
);
GM_config.set(
"canned-responses-unchecked",
GM_config.get("canned-responses"),
);
},
open: function (doc) {
GM_config.fields[
"move-to-completed-unchecked"
].node?.addEventListener(
"change",
function () {
const maps = GM_config.get(
"move-to-completed-unchecked",
true,
) as string;
if (
maps.length == 0 ||
maps
.split(/\r?\n/)
.every((map) => map.match(/^\d+;\d+$/))
)
GM_config.set("move-to-completed", maps);
},
false,
);
GM_config.fields[
"signature-block-unchecked"
].node?.addEventListener("change", function () {
const ids = GM_config.get(
"signature-block-unchecked",
true,
) as string;
if (ids.split(/\r?\n/).every((id) => id.match(/^\d+$/)))
GM_config.set("signature-block", ids);
});
GM_config.fields[
"navbar-urls-unchecked"
].node?.addEventListener("change", function () {
const urls = GM_config.get(
"navbar-urls-unchecked",
true,
) as string;
if (
urls.length == 0 ||
urls
.split(/\r?\n/)
.every((url) =>
url.match(
/^[^;\r\n]+;https?:\/\/(www\.)?[-a-zA-Z0-9.]{1,256}\.[a-zA-Z0-9]{2,6}\b(?:\/[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/,
),
)
)
GM_config.set("navbar-urls", urls);
});
GM_config.fields[
"auto-mention-unchecked"
].node?.addEventListener("change", function () {
const autoMention = GM_config.get(
"auto-mention-unchecked",
true,
) as string;
if (
autoMention.length == 0 ||
autoMention
.split(/\r?\n/)
.every((id) => id.match(/^\d+$/))
)
GM_config.set("auto-mention", autoMention);
});
GM_config.fields[
"canned-responses-unchecked"
].node?.addEventListener("change", function () {
const cannedResponses = GM_config.get(
"canned-responses-unchecked",
true,
) as string;
// Check if entire config matches the regex by matching all and rejoining the matches, then comparing to the original
if (
[
...cannedResponses.matchAll(
/(?:===\n|^)- (?<name>.+)\n- (?<category>.+)\n(?<response>(?:.|\n)+?)\n===/gm,
),
]
.map((i) => i[0])
.join("\n") === cannedResponses
)
GM_config.set("canned-responses", cannedResponses);
});
},
save: function (forgotten) {
if (
forgotten["move-to-completed-unchecked"] !==
GM_config.get("move-to-completed")
)
alert(
'Invalid move to completed map, verify that all lines are in the format "origin id:completed id".',
);
if (
forgotten["signature-block-unchecked"] !==
GM_config.get("signature-block")
)
alert(
"Invalid signature block ID list. Ensure each ID is on it's own line and all IDs are numerical.",
);
if (
forgotten["navbar-urls-unchecked"] !==
GM_config.get("navbar-urls")
)
alert(
"Invalid navbar URL list. Ensure each URL is valid, on it's own line, and all URLs are in the format 'text;url'.",
);
if (
forgotten["auto-mention-unchecked"] !==
GM_config.get("auto-mention")
)
alert(
"Invalid auto mention list. Ensure each ID is on it's own line and all IDs are numerical.",
);
if (
forgotten["canned-responses-unchecked"] !==
GM_config.get("canned-responses")
)
alert(
"Invalid canned responses list. Ensure each response is in the proper format (see the wiki for more information).",
);
},
},
css: "textarea {width: 100%; height: 160px; resize: vertical;}",
});
const profileMenu = document.querySelector("div.js-visitorMenuBody");
if (profileMenu) {
const profileMenuObserver = new MutationObserver(() => {
// Manually performing querySelector here due to odd failure to identify added node by MutationObserver
const tabPanes = profileMenu.querySelector("ul.tabPanes");
if (tabPanes) {
// Found tabbed menu (forum mod w/ bookmarks tab)
const insertParent = tabPanes.querySelector("li.is-active");
const insertBefore = insertParent?.querySelector(
":scope > a.menu-linkRow",
);
if (insertBefore)
insertConfigButton(
insertParent as HTMLElement,
insertBefore as HTMLElement,
);
} else if (profileMenu.querySelector("a.menu-linkRow")) {
// Didn't find, but has menu buttons now (normal direct menu)
const insertParent = profileMenu;
const insertBefore = insertParent.querySelector(
":scope > a.menu-linkRow",
);
if (insertBefore)
insertConfigButton(
insertParent as HTMLElement,
insertBefore as HTMLElement,
);
} else return; // Still didn't find, wait for next mutation
profileMenuObserver.disconnect();
});
profileMenuObserver.observe(profileMenu, {
childList: true,
subtree: true,
});
}
}
/**
* Automatically authenthicates with MAUL in the background if it's been a while since the last authenthication
*/
function autoMAULAuth() {
console.warn(
"MAUL reauth feature is currently disabled due to issues with the feature. Your config settings have been preserved, and the feature will return once fixed.",
);
// if (!GM_config.get("maul-reauth-enable")) return;
// const lastAuth = GM_getValue("lastMAULAuth", 0);
// if (Date.now() - lastAuth < (GM_config.get("maul-reauth") as number))
// return;
// const authLink = document.querySelector(
// 'a.p-navEl-link[href^="/maul"]',
// ) as HTMLAnchorElement;
// if (!authLink) return;
// GM_xmlhttpRequest({
// method: "GET",
// url: authLink.href,
// onload: function () {
// GM_setValue("lastMAULAuth", Date.now());
// },
// });
}
/**
* Loads completed threads map from config
*/
function loadCompletedMap() {
const completedMapRaw = GM_config.get("move-to-completed") as string;
if (completedMapRaw.length == 0) return;
completedMapRaw.split(/\r?\n/).forEach((map) => {
const parts = map.split(";");
if (parts.length != 2) {
alert("Invalid completed map: " + map);
return;
} else if (!parts[1].match(/\d+/)) {
alert("Invalid ID: " + parts[1]);
} else if (!parts[0].match(/\d+/)) {
// Separate to provide update notice
alert(
`Invalid ID: ${parts[0]}.\nThe completed map format has been changed to use IDs instead of regexes. Please update your config.`,
);
}
completedMap.push({
originId: parts[0],
completedId: parts[1],
});
});
}
/**
* Loads the signature block list IDs from config
*/
function loadSignatureBlockList() {
const signatureBlockListRaw = GM_config.get("signature-block") as string;
signatureBlockListRaw.split(/\r?\n/).forEach((id) => {
signatureBlockList.push(id);
});
}
/**
* Loads the navbar URL list from config
*/
function loadNavbarURLs() {
const navbarURLsRaw = GM_config.get("navbar-urls") as string;
if (navbarURLsRaw.length == 0) return;
navbarURLsRaw.split(/\r?\n/).forEach((url) => {
const parts = url.split(";");
if (parts.length != 2) {
alert("Invalid URL: " + url);
return;
}
navbarURLs.push({
text: parts[0],
url: parts[1],
});
});
}
/**
* Loads the navbar removals from config
*/
function loadNavbarRemovals() {
const navbarRemovalsRaw = GM_config.get("navbar-removals") as string;
if (navbarRemovalsRaw.length == 0) return;
navbarRemovalsRaw.split(/\r?\n/).forEach((removal) => {
navbarRemovals.push(removal.toLowerCase());
});
}
/**
* Loads the auto mention list from config
*/
function loadAutoMentionList() {
const autoMentionListRaw = GM_config.get("auto-mention") as string;
autoMentionListRaw.split(/\r?\n/).forEach((id) => {
autoMentionForums.push(id);
});
}
/**
* Loads the canned responses from config
*/
function loadCannedResponses() {
const cannedResponsesRaw = GM_config.get("canned-responses") as string;
[
...cannedResponsesRaw.matchAll(
/(?:===\n|^)- (?<name>.+)\n- (?<category>.+)\n(?<response>(?:.|\n)+?)\n===/gm,
),
].forEach((match) => {
const category = match.groups!.category;
if (!cannedResponses[category]) cannedResponses[category] = [];
cannedResponses[category].push({
name: match.groups!.name,
response: match.groups!.response,
});
});
}
/**
* Adds a MAUL profile button to the given div
* @param {HTMLDivElement} div Div to add to
* @param {number} member_id Member's ID
*/
function addMAULProfileButton(div: HTMLDivElement, member_id: number | string) {
createButton(
"https://maul.edgegamers.com/index.php?page=home&id=" + member_id,
"MAUL",
div,
"_blank",
);
}
/**
* Adds a "Add Ban" button to the div
* @param {HTMLDivElement} div Div to add to
* @param {data} data Data to pass to the ban page
*/
function addAddBanButton(div: HTMLDivElement, data: AddBan_Data) {
const urlData = LZString.compressToEncodedURIComponent(
JSON.stringify(data),
);
createButton(
`https://maul.edgegamers.com/index.php?page=editban#${urlData}`,
"Add Ban",
div,
"_blank",
false,
document.querySelector(
"a.button--link.button[href*='move']",
) as HTMLAnchorElement | null,
);
}
/**
* Adds a "List Bans" button to the div
* @param {HTMLDivElement} div Div to add to
* @param {number} steam_id_64 Steam ID to check
* TODO: Add support for other game IDs
*/
function addBansButton(div: HTMLDivElement, steam_id_64: string) {
createButton(
"https://maul.edgegamers.com/index.php?page=bans&qType=gameId&q=" +
steam_id_64,
"List Bans",
div,
"_blank",
false,
document.querySelector(
"a.button--link.button[href*='move']",
) as HTMLAnchorElement | null,
);
}
/**
* Adds a "Lookup ID" button to the div
* @param {HTMLDivElement} div Div to add to
* @param {string} post_title Title of the post
*/
function addLookupButton(div: HTMLDivElement, post_title: string) {
const steam_id_unknown = post_title.match(
/^.* - .* - (?<game_id>[\w\d\/\[\]\-\.:]*)$/,
);
if (steam_id_unknown)
createButton(
"https://steamid.io/lookup/" + steam_id_unknown.groups!.game_id,
"Lookup ID",
div,
"_blank",
false,
document.querySelector(
"a.button--link.button[href*='move']",
) as HTMLAnchorElement | null,
);
}
/**
* Adds a Move button to the div {@see handleThreadMovePage}
* @param {HTMLDivElement} div Div to add to
* @param {string} url URL to move to
* @param {string} text Text for the button
* @param {string} id Movement ID, this is a parameter in the URL that is used to determine where to move in the movement handling page
*/
function addMoveButton(
div: HTMLDivElement,
url: string,
text = "Move to Completed",
id = "to_completed",
) {
const post_id = url.match(/threads\/(?<post_id>\d+)/);
if (post_id)
createButton(
"https://www.edgegamers.com/threads/" +
post_id.groups!.post_id +
"/move#" +
id,
text,
div,
"_self",
);
}
/**
* Adds a button to move a thread to the trash, with a confirmation dialog (if enabled)
* @param {HTMLDivElement} before Element to add button before
*/
function addTrashButton(before: HTMLDivElement) {
const trashButton = document.createElement("a");
const post_id = window.location.href.match(/threads\/(?<post_id>\d+)/);
if (!post_id) return;
trashButton.innerHTML = "Trash thread";
trashButton.style.cursor = "pointer";
trashButton.onclick = function () {
if (!GM_config.get("confirm-trash") || confirm("Trash this thread?"))
window.location.href =
"https://www.edgegamers.com/threads/" +
post_id!.groups!.post_id +
"/move#685";
};
trashButton.classList.add("menu-linkRow");
before.parentElement?.insertBefore(trashButton, before);
}
/**
* Adds additional buttons to post action bars to make it easier to perform some actions.
*/
function addPostActionBarButtons() {
const threadId = getThreadId();
if (!threadId || threadId.length == 0) return;
const posts = document.querySelectorAll(
".message.message--post",
) as NodeListOf<HTMLElement>;
if (posts.length == 0) return;
const isThreadUnapproved = document.querySelector(
".blockStatus-message--moderated",
);
for (let i = 0; i < posts.length; i++) {
const post = posts[i] as HTMLElement;
if (!post) continue;
const actionBarSet = post.querySelector(
".actionBar-set.actionBar-set--internal",
);
if (!actionBarSet) continue;
// There is no point in adding additional buttons on deleted posts currently.
const isDeleted =
post.classList.contains("message--deleted") ||
post.querySelector(".messageNotice--deleted");
if (isDeleted) continue;
const postId = post.dataset.content?.substring(5);
if (!postId) continue;
let isUnapproved = post.querySelector(".messageNotice--moderated")
? true
: false;
let isThreadOP = false;
// Check the post counter to see if it is the original post so we can make sure we change the button action correctly.
if (i == 0) {
const attributionListElements = post.querySelectorAll(
".message-attribution-opposite.message-attribution-opposite--list li",
);
for (let j = 0; j < attributionListElements.length; j++) {
const element = attributionListElements[j] as HTMLElement;
if (element.innerText == "#1") {
isThreadOP = true;
break;
}
}
}
if (isThreadOP && isThreadUnapproved) isUnapproved = true;
const approvalButton = document.createElement("a");
approvalButton.classList.add(
"actionBar-action",
"actionBar-action--menuItem",
);
approvalButton.setAttribute("tabindex", "0");
if (isThreadOP) {
approvalButton.innerText = isUnapproved
? "Approve Thread"
: "Unapprove Thread";
} else {
approvalButton.innerText = isUnapproved ? "Approve" : "Unapprove";
}
approvalButton.onclick = () => {
setPostApprovalStatus(threadId[1], postId, isUnapproved);
};
actionBarSet.appendChild(approvalButton);
}
}
/**
* Handles (un)approving a thread post by ID.
*/
async function setPostApprovalStatus(
threadId: string,
postId: string,
approve: boolean,
reload: boolean = true,
) {
const xfToken = getXFToken();
if (!xfToken) {
console.error("Failed to get XF token");
return;
}
// cookies cannot be set in the request unfortunately.
document.cookie = `xf_inlinemod_post=${postId}; Path=/; Secure=true;`;
const searchParams = new URLSearchParams({
type: "post",
_xfRequestUri: `/threads/${threadId}/`,
_xfWithData: "1",
_xfToken: xfToken,
_xfResponseType: "json",
});
// First we send a GET to signify we want to do moderation actions with the given post.
let response = await fetch(
`https://www.edgegamers.com/inline-mod/?${searchParams.toString()}`,
{
credentials: "same-origin",
},
);
if (!response.ok) {
console.error("Failed to fetch inline-mod");
document.cookie =
"xf_inlinemod_post=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
return;
}
searchParams.set("action", approve ? "approve" : "unapprove");
// Then we send the POST with the actual mod actions
response = await fetch("https://www.edgegamers.com/inline-mod/", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
credentials: "same-origin",
body: searchParams,
});
document.cookie =
"xf_inlinemod_post=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
if (!response.ok) {
console.error("Failed to change post approval status");
return;
}
const data = await response.json();
if (data.status != "ok") {
console.error("Server rejected post approval change");
console.log(data);
return;
}