-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathtwitter.gt2eb.user.js
2653 lines (2275 loc) · 102 KB
/
twitter.gt2eb.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 GoodTwitter 2 - Electric Boogaloo
// @version 0.0.45
// @description A try to make Twitter look good again.
// @author schwarzkatz
// @license MIT
// @match https://twitter.com/*
// @match https://mobile.twitter.com/*
// @match https://x.com/*
// @match https://mobile.x.com/*
// @exclude https://twitter.com/i/cards/*
// @exclude https://twitter.com/i/release_notes
// @exclude https://twitter.com/*/privacy
// @exclude https://twitter.com/*/tos
// @exclude https://twitter.com/account/access
// @exclude https://x.com/i/cards/*
// @exclude https://x.com/i/release_notes
// @exclude https://x.com/*/privacy
// @exclude https://x.com/*/tos
// @exclude https://x.com/account/access
// @grant GM_deleteValue
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_info
// @grant GM_xmlhttpRequest
// @connect api.twitter.com
// @connect api.x.com
// @resource css https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/twitter.gt2eb.style.css
// @resource emojiRegex https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/data/emoji-regex.txt
// @resource pickrCss https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/classic.min.css
// @require https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/twitter.gt2eb.i18n.js
// @require https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/twitter.gt2eb.polyfills.js
// @require https://code.jquery.com/jquery-3.5.1.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @require https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.es5.min.js
// @updateURL https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/twitter.gt2eb.user.js
// @downloadURL https://github.com/Bl4Cc4t/GoodTwitter2/raw/master/twitter.gt2eb.user.js
// ==/UserScript==
(function($, waitForKeyElements) {
"use strict"
// do not execute on these pages
if (getPath().match(/^login(\?.*)?$/) || (!isLoggedIn() && getPath().match(/^(\?.*)?$/))) {
return
}
// redirect for mobile urls
if (window.location.host.startsWith("mobile.")) {
if (GM_getValue("opt_gt2").mobileRedirect) {
window.location.href = window.location.href.replace("//mobile.", "//")
} else return
}
// ###########################
// # convenience functions #
// ###########################
// seperate number with commas
Number.prototype.humanize = function() {
let t = this.toString().split("")
let out = ""
let c = 1
for (let i=t.length-1; i>=0; i--) {
out = `${t[i]}${out}`
if (c++ % 3 == 0 && i-1 >= 0) {
out = `,${out}`
}
}
return out
}
// shorter version: 1.4M, 23.4K, etc
Number.prototype.humanizeShort = function() {
let t = this.toString()
if (this >= 1000000) {
t = t.slice(0, -5)
return `${t.slice(0, -1)}${t.slice(-1) != 0 ? `.${t.slice(-1)}` : ""}M`
} else if (this >= 10000) {
t = t.slice(0, -2)
return `${t.slice(0, -1)}${t.slice(-1) != 0 ? `.${t.slice(-1)}` : ""}K`
} else return this.humanize()
}
// get kebab case (thisIsAString -> this-is-a-string)
String.prototype.toKebab = function() {
let arr = this.toString().split("")
return arr.map((e, i) => {
let add_dash = i > 0
&& ((!isNaN(e) && isNaN(arr[i-1]))
|| (isNaN(e) && !isNaN(arr[i-1]))
|| (isNaN(e) && e == e.toUpperCase()))
return `${add_dash ? "-" : ""}${e.toLowerCase()}`
}).join("")
}
String.prototype.replaceAt = function(index, length, text) {
return `${this.toString().slice(0, index)}${text}${this.toString().slice(index + length)}`
}
String.prototype.insertAt = function(index, text) {
return this.toString().replaceAt(index, 0, text)
}
const defaultAvatarUrl = "https://abs.twimg.com/sticky/default_profile_images/default_profile.png"
const emojiRegexp = new RegExp(`(${GM_getResourceText("emojiRegex")})`, "gu")
// get account information
let info = null
function getInfo() {
if (info)
return info
let user = null
try {
for (let e of Array.from(document.querySelectorAll("#react-root ~ script"))) {
if (e.textContent.includes("__INITIAL_STATE__")) {
let match = e.textContent.match(/__INITIAL_STATE__=(\{.*?\});window/)
if (match) {
let initialState = JSON.parse(match[1])
user = Object.values(initialState?.entities?.users?.entities)[0] ?? null
}
break
}
}
} catch (e) {
console.error(e)
}
if (user) {
info = {
bannerUrl: user.profile_banner_url,
avatarUrl: user.profile_image_url_https,
screenName: user.screen_name,
name: user.name,
id: user.id_str,
stats: {
tweets: user.statuses_count,
followers: user.followers_count,
following: user.friends_count
}
}
console.log("user info", info)
} else {
console.error("match of __INITIAL_STATE__ unsuccessful, falling back to default values")
info = {
bannerUrl: "",
avatarUrl: defaultAvatarUrl,
screenName: "youarenotloggedin",
name: "Anonymous",
id: "0",
stats: {
tweets: 0,
followers: 0,
following: 0
}
}
}
return info
}
// get current display language
function getLang() {
return $("html").attr("lang").trim()
}
// check if the user is logged in
function isLoggedIn() {
return document.cookie.match(/twid=u/)
}
// get localized version of a string.
// defaults to english version.
function getLocStr(key) {
let lang = getLang()
lang = Object.keys(i18n).includes(lang) ? lang : "en"
return i18n[Object.keys(i18n[lang]).includes(key) ? lang : "en"][key]
}
// current path
function getPath() {
return window.location.href.replace(/.*?(twitter|x)\.com\//, "")
}
// svg convenience
function getSvg(key) {
let svgs = {
lightning: `<g><path d="M8.98 22.698c-.103 0-.205-.02-.302-.063-.31-.135-.49-.46-.44-.794l1.228-8.527H6.542c-.22 0-.43-.098-.573-.266-.144-.17-.204-.393-.167-.61L7.49 2.5c.062-.36.373-.625.74-.625h6.81c.23 0 .447.105.59.285.142.18.194.415.14.64l-1.446 6.075H19c.29 0 .553.166.678.428.124.262.087.57-.096.796L9.562 22.42c-.146.18-.362.276-.583.276zM7.43 11.812h2.903c.218 0 .425.095.567.26.142.164.206.382.175.598l-.966 6.7 7.313-8.995h-4.05c-.228 0-.445-.105-.588-.285-.142-.18-.194-.415-.14-.64l1.446-6.075H8.864L7.43 11.812z"></path></g>`,
caret: `<g><path d="M20.207 8.147c-.39-.39-1.023-.39-1.414 0L12 14.94 5.207 8.147c-.39-.39-1.023-.39-1.414 0-.39.39-.39 1.023 0 1.414l7.5 7.5c.195.196.45.294.707.294s.512-.098.707-.293l7.5-7.5c.39-.39.39-1.022 0-1.413z"></path></g>`,
tick: `<g><path d="M9 20c-.264 0-.52-.104-.707-.293l-4.785-4.785c-.39-.39-.39-1.023 0-1.414s1.023-.39 1.414 0l3.946 3.945L18.075 4.41c.32-.45.94-.558 1.395-.24.45.318.56.942.24 1.394L9.817 19.577c-.17.24-.438.395-.732.42-.028.002-.057.003-.085.003z"></path></g>`,
moon: `<g><path d="M 13.277344 24 C 16.976562 24 20.355469 22.316406 22.597656 19.554688 C 22.929688 19.148438 22.566406 18.550781 22.054688 18.648438 C 16.234375 19.757812 10.886719 15.292969 10.886719 9.417969 C 10.886719 6.03125 12.699219 2.917969 15.644531 1.242188 C 16.097656 0.984375 15.984375 0.296875 15.46875 0.199219 C 14.746094 0.0664062 14.011719 0 13.277344 0 C 6.652344 0 1.277344 5.367188 1.277344 12 C 1.277344 18.625 6.644531 24 13.277344 24 Z M 13.277344 24 "/></g>`,
x: `<g><path d="M13.414 12l5.793-5.793c.39-.39.39-1.023 0-1.414s-1.023-.39-1.414 0L12 10.586 6.207 4.793c-.39-.39-1.023-.39-1.414 0s-.39 1.023 0 1.414L10.586 12l-5.793 5.793c-.39.39-.39 1.023 0 1.414.195.195.45.293.707.293s.512-.098.707-.293L12 13.414l5.793 5.793c.195.195.45.293.707.293s.512-.098.707-.293c.39-.39.39-1.023 0-1.414L13.414 12z"></path></g>`,
google: `<g><path d="M9.827 17.667c-4.82 0-8.873-3.927-8.873-8.747S5.007.173 9.827.173c2.667 0 4.567 1.047 5.993 2.413l-1.687 1.687c-1.027-.96-2.413-1.707-4.307-1.707-3.52 0-6.273 2.84-6.273 6.36s2.753 6.36 6.273 6.36c2.28 0 3.587-.92 4.413-1.747.68-.68 1.132-1.668 1.3-3.008H10v-2.4h7.873c.087.428.127.935.127 1.495 0 1.793-.493 4.013-2.067 5.587-1.54 1.6-3.5 2.453-6.106 2.453zm20.806-5.627c0 3.24-2.533 5.633-5.633 5.633-3.107 0-5.633-2.387-5.633-5.633 0-3.267 2.527-5.633 5.633-5.633 3.1.006 5.633 2.373 5.633 5.633zm-2.466 0c0-2.027-1.467-3.413-3.167-3.413-1.7 0-3.167 1.387-3.167 3.413 0 2.007 1.467 3.413 3.167 3.413 1.7 0 3.167-1.406 3.167-3.413zm15.133-.007c0 3.24-2.527 5.633-5.633 5.633s-5.633-2.387-5.633-5.633c0-3.267 2.527-5.633 5.633-5.633S43.3 8.773 43.3 12.033zm-2.467 0c0-2.027-1.467-3.413-3.167-3.413S34.5 10.007 34.5 12.033c0 2.007 1.467 3.413 3.167 3.413s3.166-1.406 3.166-3.413zm14.5-5.286V16.86c0 4.16-2.453 5.867-5.353 5.867-2.733 0-4.373-1.833-4.993-3.327l2.153-.893c.387.92 1.32 2.007 2.84 2.007 1.853 0 3.007-1.153 3.007-3.307v-.813H52.9c-.553.68-1.62 1.28-2.967 1.28-2.813 0-5.267-2.453-5.267-5.613 0-3.18 2.453-5.652 5.267-5.652 1.347 0 2.413.6 2.967 1.26h.087v-.92h2.346zm-2.173 5.306c0-1.987-1.32-3.433-3.007-3.433-1.707 0-3.007 1.453-3.007 3.433 0 1.96 1.3 3.393 3.007 3.393 1.68 0 3.007-1.426 3.007-3.393zM59.807.78v16.553h-2.473V.78h2.473zm9.886 13.113l1.92 1.28c-.62.92-2.113 2.493-4.693 2.493-3.2 0-5.587-2.473-5.587-5.633 0-3.347 2.413-5.633 5.313-5.633 2.92 0 4.353 2.327 4.82 3.587l.253.64-7.534 3.113c.573 1.133 1.473 1.707 2.733 1.707s2.133-.62 2.773-1.554zm-5.906-2.026l5.033-2.093c-.28-.707-1.107-1.193-2.093-1.193-1.254 0-3.007 1.107-2.94 3.287z"></path></g>`,
arrow: `<g><path d="M20 11H7.414l4.293-4.293c.39-.39.39-1.023 0-1.414s-1.023-.39-1.414 0l-6 6c-.39.39-.39 1.023 0 1.414l6 6c.195.195.45.293.707.293s.512-.098.707-.293c.39-.39.39-1.023 0-1.414L7.414 13H20c.553 0 1-.447 1-1s-.447-1-1-1z"></path></g>`,
location: `<g><path d="M12 14.315c-2.088 0-3.787-1.698-3.787-3.786S9.913 6.74 12 6.74s3.787 1.7 3.787 3.787-1.7 3.785-3.787 3.785zm0-6.073c-1.26 0-2.287 1.026-2.287 2.287S10.74 12.814 12 12.814s2.287-1.025 2.287-2.286S13.26 8.24 12 8.24z"></path><path d="M20.692 10.69C20.692 5.9 16.792 2 12 2s-8.692 3.9-8.692 8.69c0 1.902.603 3.708 1.743 5.223l.003-.002.007.015c1.628 2.07 6.278 5.757 6.475 5.912.138.11.302.163.465.163.163 0 .327-.053.465-.162.197-.155 4.847-3.84 6.475-5.912l.007-.014.002.002c1.14-1.516 1.742-3.32 1.742-5.223zM12 20.29c-1.224-.99-4.52-3.715-5.756-5.285-.94-1.25-1.436-2.742-1.436-4.312C4.808 6.727 8.035 3.5 12 3.5s7.192 3.226 7.192 7.19c0 1.57-.497 3.062-1.436 4.313-1.236 1.57-4.532 4.294-5.756 5.285z"></path></g>`,
url: `<g><path d="M11.96 14.945c-.067 0-.136-.01-.203-.027-1.13-.318-2.097-.986-2.795-1.932-.832-1.125-1.176-2.508-.968-3.893s.942-2.605 2.068-3.438l3.53-2.608c2.322-1.716 5.61-1.224 7.33 1.1.83 1.127 1.175 2.51.967 3.895s-.943 2.605-2.07 3.438l-1.48 1.094c-.333.246-.804.175-1.05-.158-.246-.334-.176-.804.158-1.05l1.48-1.095c.803-.592 1.327-1.463 1.476-2.45.148-.988-.098-1.975-.69-2.778-1.225-1.656-3.572-2.01-5.23-.784l-3.53 2.608c-.802.593-1.326 1.464-1.475 2.45-.15.99.097 1.975.69 2.778.498.675 1.187 1.15 1.992 1.377.4.114.633.528.52.928-.092.33-.394.547-.722.547z"></path><path d="M7.27 22.054c-1.61 0-3.197-.735-4.225-2.125-.832-1.127-1.176-2.51-.968-3.894s.943-2.605 2.07-3.438l1.478-1.094c.334-.245.805-.175 1.05.158s.177.804-.157 1.05l-1.48 1.095c-.803.593-1.326 1.464-1.475 2.45-.148.99.097 1.975.69 2.778 1.225 1.657 3.57 2.01 5.23.785l3.528-2.608c1.658-1.225 2.01-3.57.785-5.23-.498-.674-1.187-1.15-1.992-1.376-.4-.113-.633-.527-.52-.927.112-.4.528-.63.926-.522 1.13.318 2.096.986 2.794 1.932 1.717 2.324 1.224 5.612-1.1 7.33l-3.53 2.608c-.933.693-2.023 1.026-3.105 1.026z"></path></g>`,
calendar: `<g><path d="M19.708 2H4.292C3.028 2 2 3.028 2 4.292v15.416C2 20.972 3.028 22 4.292 22h15.416C20.972 22 22 20.972 22 19.708V4.292C22 3.028 20.972 2 19.708 2zm.792 17.708c0 .437-.355.792-.792.792H4.292c-.437 0-.792-.355-.792-.792V6.418c0-.437.354-.79.79-.792h15.42c.436 0 .79.355.79.79V19.71z"></path><circle cx="7.032" cy="8.75" r="1.285"></circle><circle cx="7.032" cy="13.156" r="1.285"></circle><circle cx="16.968" cy="8.75" r="1.285"></circle><circle cx="16.968" cy="13.156" r="1.285"></circle><circle cx="12" cy="8.75" r="1.285"></circle><circle cx="12" cy="13.156" r="1.285"></circle><circle cx="7.032" cy="17.486" r="1.285"></circle><circle cx="12" cy="17.486" r="1.285"></circle></g>`,
balloon: `<g><path d="M7.75 11.083c-.414 0-.75-.336-.75-.75C7 7.393 9.243 5 12 5c.414 0 .75.336.75.75s-.336.75-.75.75c-1.93 0-3.5 1.72-3.5 3.833 0 .414-.336.75-.75.75z"></path><path d="M20.75 10.333c0-5.01-3.925-9.083-8.75-9.083s-8.75 4.074-8.75 9.083c0 4.605 3.32 8.412 7.605 8.997l-1.7 1.83c-.137.145-.173.357-.093.54.08.182.26.3.46.3h4.957c.198 0 .378-.118.457-.3.08-.183.044-.395-.092-.54l-1.7-1.83c4.285-.585 7.605-4.392 7.605-8.997zM12 17.917c-3.998 0-7.25-3.402-7.25-7.584S8.002 2.75 12 2.75s7.25 3.4 7.25 7.583-3.252 7.584-7.25 7.584z"></path></g>`,
}
return `
<svg class="gt2-svg" viewBox="0 0 ${key == "google" ? 74 : 24} 24">
${svgs[key]}
</svg>`
}
// request headers
function getRequestHeaders(additionalHeaders) {
// found in https://abs.twimg.com/responsive-web/web/main.5c0baa34.js
let publicBearer = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
let csrf = window.document.cookie.match(/ct0=([^;]+)(;|$)/)[1]
let out = {
authorization: `Bearer ${publicBearer}`,
origin: "https://twitter.com",
referer: window.location.href,
"x-twitter-client-language": getLang(),
"x-csrf-token": csrf,
"x-twitter-active-user": "yes",
// "x-twitter-auth-type": "OAuth2Session"
}
Object.assign(out, additionalHeaders)
return out
}
function getRequestURL(base, param) {
let out = base
for (let [key, val] of Object.entries(param)) {
if (typeof val === "object") val = encodeURIComponent(JSON.stringify(val))
out += `&${key}=${val}`
}
return `${out.replace("&", "?")}`
}
// request a tweet
function requestTweet(id, cb) {
GM_xmlhttpRequest({
method: "GET",
url: getRequestURL("https://twitter.com/i/api/1.1/statuses/show.json", {
id,
tweet_mode: "extended",
trim_user: true,
include_cards: 1
}),
headers: getRequestHeaders(),
onload: function(res) {
if (res.status == "200") {
cb(JSON.parse(res.response))
} else {
console.warn(res)
}
}
})
}
// request tweet with content warnings
// the results from this api sometimes are missing the url entities, hence the new function.
function requestTweetCW(id, cb) {
GM_xmlhttpRequest({
method: "GET",
url: getRequestURL("https://twitter.com/i/api/graphql/bRL1YYMraLIBpo1PGLeFcw/TweetDetail", {
variables: {
focalTweetId: id,
includePromotedContent: false,
withBirdwatchNotes: false,
withDownvotePerspective: false,
withReactionsMetadata: false,
withReactionsPerspective: false,
withSuperFollowsTweetFields: false,
withSuperFollowsUserFields: false,
withVoice: false
}
}),
headers: getRequestHeaders(),
onload: function(res) {
if (res.status == "200") {
cb(
JSON.parse(res.response)
.data.threaded_conversation_with_injections.instructions
.find(e => e.type == "TimelineAddEntries").entries
.find(e => e.entryId.startsWith("tweet-"))
.content.itemContent.tweet_results.result.legacy
)
} else {
console.warn(res)
}
}
})
}
function requestUser(screenName, cb) {
GM_xmlhttpRequest({
method: "GET",
url: getRequestURL(`https://twitter.com/i/api/graphql/jMaTS-_Ea8vh9rpKggJbCQ/UserByScreenName`, {
variables: {
screen_name: screenName,
withHighlightedLabel: true
}
}),
headers: getRequestHeaders(),
onload: function(res) {
if (res.status == "200") {
cb(JSON.parse(res.response))
} else {
console.warn(res)
}
}
})
}
function blockUser(user_id, block, cb) {
GM_xmlhttpRequest({
method: "POST",
url: getRequestURL(`https://api.twitter.com/1.1/blocks/${block ? "create" : "destroy"}.json`, {
user_id,
skip_status: true
}),
headers: getRequestHeaders(),
onload: function(res) {
if (res.status == "200") {
cb()
} else {
console.warn(res)
}
}
})
}
// adds links from an entities object to a text
String.prototype.populateWithEntities = function(entities) {
let text = this.toString()
let out = text
let toReplace = []
// urls
if (entities.urls) {
for (let url of entities.urls) {
toReplace.push({
[url.indices[0]]: `<a href="`,
[url.indices[1]]: `" target="_blank">${url.display_url}</a> `
})
}
}
// users
if (entities.user_mentions) {
for (let user of entities.user_mentions) {
let x = text.slice(user.indices[0], user.indices[0]+1) == "@" ? 0 : 1
toReplace.push({
[user.indices[0]+x]: `<a href="/${user.screen_name}">`,
[user.indices[1]+x]: `</a> `
})
}
}
// hashtags
if (entities.hashtags) {
for (let hashtag of entities.hashtags) {
let x = text.slice(hashtag.indices[0], hashtag.indices[0]+1) == "#" ? 0 : 1
toReplace.push({
[hashtag.indices[0]+x]: `<a href="/hashtag/${hashtag.text}">`,
[hashtag.indices[1]+x]: `</a> `
})
}
}
// change indices if emoji(s) appear before the entity
// reason: multiple > 0xFFFF codepoint emojis are counted wrong: all but the first emoji have their length reduced by 1.
// also, if any emoji > 0xFFFF precedes a url, the indices of the url are misaligned by -1.
let match
let counter = 0
while ((match = emojiRegexp.exec(text)) != null) {
let e = match[1]
if (e.codePointAt(0) < 0xFFFF) continue
counter++
for (let i in toReplace) {
let tmp = Object.entries(toReplace[i])
// skip if not url and first element
if (tmp[0][1] != `<a href="` && counter == 1) continue
if (tmp[0][0] >= match.index) {
toReplace[i] = {
[parseInt(tmp[0][0]) + 1]: tmp[0][1],
[parseInt(tmp[1][0]) + 1]: tmp[1][1]
}
}
}
}
// sort array
toReplace = toReplace.sort((a, b) => parseInt(Object.keys(a)[0]) - parseInt(Object.keys(b)[0]))
// replace values
let offset = 0
for (let e of toReplace) {
for (let [index, value] of Object.entries(e)) {
out = out.insertAt(parseInt(index) + offset, value)
offset += value.length
}
}
if (GM_getValue("opt_gt2").expandTcoShortlinks) {
let re = /href="(https:\/\/t\.co\/[^"]+)"/
let match
while ((match = re.exec(out)) != null) {
out = out.replace(new RegExp(`href="${match[1]}"`), `href="${entities.urls.find(e => e.url == match[1]).expanded_url}"`)
}
}
return out
}
// replace emojis with the twitter svgs
String.prototype.replaceEmojis = function() {
let text = this.toString()
.replace(/([\*#0-9])\s\u20E3/ug, "$1\u20E3")
.replace(/([\*#0-9])\uFE0F/ug, "$1")
let out = text
let match
let offset = 0
while ((match = emojiRegexp.exec(text)) != null) {
let e = match[1]
// get unicode of emoji
let uni = []
for (let i = 0; i < e.length; i++) {
uni.push(e.codePointAt(i).toString(16))
if (e.codePointAt(i) > 0xFFFF) i++
}
// remove fe0f from non joined emojis
if (uni.length > 1 && uni[1].match(/^FE0F$/i)) uni.pop()
// replace with image
// https://abs-0.twimg.com/emoji/v2/svg/1f647.svg
// https://abs-0.twimg.com/emoji/v2/svg/1f647-200d-2640-fe0f.svg
let img = `<img src="https://abs-0.twimg.com/emoji/v2/svg/${uni.join("-")}.svg" alt="${e}" class="gt2-emoji" />`
out = out.replaceAt(match.index + offset, e.length, img)
offset += img.length - e.length
}
return out
}
// ###################
// # GT2 settings #
// ###################
// custom options and their default values
const opt_gt2 = {
// timeline
forceLatest: false,
biggerPreviews: false,
// tweets
hideTranslateTweetButton: false,
tweetIconsPullLeft: false,
hidePromoteTweetButton: false,
showMediaWithContentWarnings: false,
showMediaWithContentWarningsSel: 7,
hideTweetAnalytics: false,
// sidebars
stickySidebars: true,
smallSidebars: false,
hideTrends: false,
leftTrends: true,
show5Trends: false,
// profile
legacyProfile: false,
squareAvatars: false,
disableHexagonAvatars: false,
enableQuickBlock: false,
leftMedia: false,
profileMediaRedirect: false,
// global look
hideFollowSuggestions: false,
hideFollowSuggestionsSel: 7,
hideFollowSuggestionsLocSel: 3,
fontOverride: false,
fontOverrideValue: "Arial",
colorOverride: false,
colorOverrideValue: "85, 102, 68",
hideMessageBox: true,
rosettaIcons: false,
favoriteLikes: false,
birdIcon: true,
// other
updateNotifications: true,
expandTcoShortlinks: true,
mobileRedirect: true,
}
// set default options
if (GM_getValue("opt_gt2") == undefined) GM_setValue("opt_gt2", opt_gt2)
// add previously non existant options
if (JSON.stringify(Object.keys(GM_getValue("opt_gt2"))) != JSON.stringify(Object.keys(opt_gt2))) {
let old = GM_getValue("opt_gt2")
// remove default options that are modified
for (let k of Object.keys(opt_gt2)) {
if (Object.keys(old).includes(k)) delete opt_gt2[k]
}
// remove old options
for (let k of Object.keys(old)) {
if (Object.keys(opt_gt2).includes(k)) delete old[k]
}
Object.assign(old, opt_gt2)
GM_setValue("opt_gt2", old)
}
// toggle opt_gt2 value
function toggleGt2Opt(key) {
let x = GM_getValue("opt_gt2")
x[key] = !x[key]
GM_setValue("opt_gt2", x)
}
// insert the menu item
function addSettingsToggle() {
if (!$(".gt2-toggle-settings").length) {
$(`main section[aria-labelledby=root-header] div[role=tablist],
main > div > div > div > div:last-child > div[role=tablist],
main div[data-testid=loggedOutPrivacySection]`).append(`
<a class="gt2-toggle-settings" href="/settings/gt2">
<div>
<span>GoodTwitter2</span>
${getSvg("caret")}
</div>
</a>
`)
}
}
// toggle settings display
$("body").on("click", ".gt2-toggle-settings", function(event) {
event.preventDefault()
window.history.pushState({}, "", $(this).attr("href"))
addSettings()
changeSettingsTitle()
})
// disable settings display again when clicking on another menu item
$("body").on("click", `main section[aria-labelledby=root-header] div[role=tablist] a:not(.gt2-toggle-settings),
main section[aria-labelledby=root-header] div[data-testid=loggedOutPrivacySection] a:not(.gt2-toggle-settings)`, () => {
$(".gt2-settings-header, .gt2-settings").remove()
})
// get html for a gt2 toggle (checkbox)
function getSettingTogglePart(name, additionalHTML="") {
let d = `${name}Desc`
return `
<div class="gt2-setting">
<div>
<span>${getLocStr(name)}</span>
<div class="gt2-setting-toggle ${GM_getValue("opt_gt2")[name] ? "gt2-active" : ""}" data-setting-name="${name}">
<div></div>
<div>
${getSvg("tick")}
</div>
</div>
</div>
${additionalHTML}
${getLocStr(d) ? `<span>${getLocStr(d)}</span>` : ""}
</div>`
}
// add the settings to the display (does not yet work on screens smaller than 1050px)
function addSettings() {
if (!$(".gt2-settings").length) {
let elem = `
<div class="gt2-settings-header">
<div class="gt2-settings-back">
<div></div>
${getSvg("arrow")}
</div>
GoodTwitter2 v${GM_info.script.version}
</div>
<div class="gt2-settings">
<div class="gt2-settings-sub-header">${getLocStr("settingsHeaderTimeline")}</div>
${getSettingTogglePart("forceLatest")}
${getSettingTogglePart("biggerPreviews")}
<div class="gt2-settings-separator"></div>
<div class="gt2-settings-sub-header">${getLocStr("statsTweets")}</div>
${getSettingTogglePart("hideTranslateTweetButton")}
${getSettingTogglePart("tweetIconsPullLeft")}
${getSettingTogglePart("hidePromoteTweetButton")}
${getSettingTogglePart("showMediaWithContentWarnings", `
<div data-setting-name="showMediaWithContentWarningsBox" class="gt2-settings-multi-selection ${GM_getValue("opt_gt2").showMediaWithContentWarnings ? "" : "gt2-hidden"}">
<div data-setting-name="showMediaWithContentWarningsSel">
${["Nudity", "Violence", "SensitiveContent"].map((e, i) => {
let x = Math.pow(2, i)
return `
<div>
<span>${getLocStr(`contentWarning${e}`)}</span>
<div class="gt2-setting-toggle ${(GM_getValue("opt_gt2").showMediaWithContentWarningsSel & x) == x ? "gt2-active" : ""}" data-sel="${x}">
<div></div>
<div>${getSvg("tick")}</div>
</div>
</div>`
}).join("")}
</div>
</div>
`)}
${getSettingTogglePart("hideTweetAnalytics")}
<div class="gt2-settings-separator"></div>
<div class="gt2-settings-sub-header">${getLocStr("settingsHeaderSidebars")}</div>
${getSettingTogglePart("stickySidebars")}
${getSettingTogglePart("smallSidebars")}
${getSettingTogglePart("hideTrends")}
${getSettingTogglePart("leftTrends")}
${getSettingTogglePart("show5Trends")}
<div class="gt2-settings-separator"></div>
<div class="gt2-settings-sub-header">${getLocStr("navProfile")}</div>
${getSettingTogglePart("legacyProfile")}
${getSettingTogglePart("squareAvatars")}
${getSettingTogglePart("disableHexagonAvatars")}
${getSettingTogglePart("enableQuickBlock")}
${getSettingTogglePart("leftMedia")}
${getSettingTogglePart("profileMediaRedirect")}
<div class="gt2-settings-separator"></div>
<div class="gt2-settings-sub-header">${getLocStr("settingsHeaderGlobalLook")}</div>
${getSettingTogglePart("hideFollowSuggestions", `
<div data-setting-name="hideFollowSuggestionsBox" class="gt2-settings-multi-selection ${GM_getValue("opt_gt2").hideFollowSuggestions ? "" : "gt2-hidden"}">
${getLocStr("hideFollowSuggestionsBox").replace("$type$", `
<div data-setting-name="hideFollowSuggestionsSel">
${["topics", "users", "navLists"].map((e, i) => {
let x = Math.pow(2, i)
return `<div>
<span>${getLocStr(e)}</span>
<div class="gt2-setting-toggle ${(GM_getValue("opt_gt2").hideFollowSuggestionsSel & x) == x ? "gt2-active" : ""}" data-sel="${x}">
<div></div>
<div>${getSvg("tick")}</div>
</div>
</div>
`}).join("")}
</div>
`).replace("$location$", `
<div data-setting-name="hideFollowSuggestionsLocSel">
${["Timeline", "Sidebars"].map((e, i) => {
let x = Math.pow(2, i)
return `<div>
<span>${getLocStr(`settingsHeader${e}`)}</span>
<div class="gt2-setting-toggle ${(GM_getValue("opt_gt2").hideFollowSuggestionsLocSel & x) == x ? "gt2-active" : ""}" data-sel="${x}">
<div></div>
<div>${getSvg("tick")}</div>
</div>
</div>
`}).join("")}
</div>
`)}
</div>
`)}
${getSettingTogglePart("fontOverride", `
<div class="gt2-setting-input" data-setting-name="fontOverrideValue">
<input type="text" value="${GM_getValue("opt_gt2").fontOverrideValue}">
</div>
`)}
${getSettingTogglePart("colorOverride", `<div class="gt2-pickr"></div>`)}
${getSettingTogglePart("hideMessageBox")}
${getSettingTogglePart("rosettaIcons")}
${getSettingTogglePart("favoriteLikes")}
${getSettingTogglePart("birdIcon")}
<div class="gt2-settings-separator"></div>
<div class="gt2-settings-sub-header">${getLocStr("settingsHeaderOther")}</div>
${getSettingTogglePart("updateNotifications")}
${getSettingTogglePart("expandTcoShortlinks")}
${getSettingTogglePart("mobileRedirect")}
</div>
`
let $s = $("main section[aria-labelledby=detail-header]")
if ($s.length) {
$s.prepend(elem)
} else {
$("main > div > div > div").append(`
<section>${elem}</section>
`)
}
// add color pickr
Pickr.create({
el: ".gt2-pickr",
theme: "classic",
lockOpacity: true,
useAsButton: true,
appClass: "gt2-color-override-pickr",
inline: true,
default: `rgb(${GM_getValue("opt_gt2").colorOverrideValue})`,
components: {
preview: true,
hue: true,
interaction: {
hex: true,
rgba: true,
hsla: true,
hsva: true,
cmyk: true,
input: true
}
}
})
.on("change", e => {
let val = e.toRGBA().toString(0).slice(5, -4)
GM_setValue("opt_gt2", Object.assign(GM_getValue("opt_gt2"), { colorOverrideValue: val}))
document.documentElement.style.setProperty("--color-override", val)
})
disableTogglesIfNeeded()
}
}
// change the title to display GoodTwitter2
function changeSettingsTitle() {
let t = $("title").html()
$("title").html(`${t.startsWith("(") ? `${t.split(" ")[0]} ` : ""}GoodTwitter2 / Twitter`)
}
// handler for the toggles
$("body").on("click", ".gt2-setting-toggle:not(.gt2-disabled)", function() {
$(this).toggleClass("gt2-active")
if ($(this).is("[data-setting-name]")) {
let name = $(this).attr("data-setting-name").trim()
toggleGt2Opt(name)
$("body").toggleClass(`gt2-opt-${name.toKebab()}`)
}
// handle selector settings (hideFollowSuggestions, showMediaWithContentWarnings)
if ($(this).is("[data-sel]")) {
let sName = $(this).closest("[data-setting-name]").attr("data-setting-name")
let opt = GM_getValue("opt_gt2")
GM_setValue("opt_gt2", Object.assign(opt, { [sName]: opt[sName] ^ parseInt($(this).attr("data-sel")) }))
}
disableTogglesIfNeeded()
})
// handler for inputs
$("body").on("keyup", ".gt2-setting-input input", function() {
let name = $(this).parent().attr("data-setting-name").trim()
let val = $(this).val().trim()
GM_setValue("opt_gt2", Object.assign(GM_getValue("opt_gt2"), { [name]: val}))
document.documentElement.style.setProperty(`--${name.replace("Value", "").toKebab()}`, val)
})
function disableTogglesIfNeeded() {
// other trend related toggles are not needed when the trends are disabled
$("div[data-setting-name=leftTrends], div[data-setting-name=show5Trends]")
[GM_getValue("opt_gt2").hideTrends ? "addClass" : "removeClass"]("gt2-disabled")
// hide font input if fontOverride is disabled
$("[data-setting-name=fontOverrideValue]")
[GM_getValue("opt_gt2").fontOverride ? "removeClass" : "addClass"]("gt2-hidden")
// hide color input if colorOverride is disabled
$(".gt2-color-override-pickr")
[GM_getValue("opt_gt2").colorOverride ? "removeClass" : "addClass"]("gt2-hidden")
// hide follow suggestions
$("[data-setting-name=hideFollowSuggestionsBox]")
[GM_getValue("opt_gt2").hideFollowSuggestions ? "removeClass" : "addClass"]("gt2-hidden")
// showMediaWithContentWarnings
$("[data-setting-name=showMediaWithContentWarningsBox]")
[GM_getValue("opt_gt2").showMediaWithContentWarnings ? "removeClass" : "addClass"]("gt2-hidden")
}
// click on the back button
$("body").on("click", ".gt2-settings-back", () => window.history.back())
// #######################
// # various functions #
// #######################
// add navbar
function addNavbar() {
waitForKeyElements(`nav > a[href="/home"]`, () => {
if ($(".gt2-nav").length) return
$("main").before(`
<nav class="gt2-nav">
<div class="gt2-nav-left"></div>
<div class="gt2-nav-center">
<a href="/home"></a>
</div>
<div class="gt2-nav-right">
<div class="gt2-search"></div>
<div class="gt2-toggle-navbar-dropdown">
<img src="${getInfo().avatarUrl.replace(/_(bigger|normal|(reasonably_)?small|\d*x\d+)/, "_bigger")}" />
</div>
<div class="gt2-compose">${getLocStr("composeNewTweet")}</div>
</div>
</nav>
<div class="gt2-search-overflow-hider"></div>
`)
// home, notifications, messages
for (let type of [
"Home",
"Notifications",
"Messages",
window.innerWidth < 1005 ? "Explore" : null
]) {
if (!type) continue
let origElemSel = `nav > a[href^="/${type.toLowerCase()}"]:not([data-testid=AppTabBar_Profile_Link]):not([href$="/lists"])`
let $e = document.querySelector(origElemSel)
if (!$e) continue
document.querySelector(".gt2-nav-left").insertAdjacentHTML("beforeend", $e.outerHTML)
document.querySelectorAll(`.gt2-nav-left [data-testid]`)
.forEach(e => {
e.addEventListener("click", event => {
if (!event.ctrlKey) {
event.preventDefault()
let testid = event.target.closest("[data-testid]").dataset.testid
document.querySelector(`nav [data-testid=${testid}]`).click()
}
})
})
watchForChanges(origElemSel, e => {
let navbarElem = document.querySelector(`.gt2-nav-left [data-testid=${e.dataset.testid}]`)
if (!navbarElem) return
navbarElem.innerHTML = e.innerHTML
navbarElem.firstElementChild.setAttribute("data-gt2-color-override-ignore", "")
navbarElem.firstElementChild.insertAdjacentHTML("beforeend", `
<div class="gt2-nav-header">
${getLocStr(`nav${type}`)}
</div>
`)
})
// $e.appendTo(".gt2-nav-left")
$(`.gt2-nav a[href^="/${type.toLowerCase()}"] > div`)
.append(`
<div class="gt2-nav-header">
${getLocStr(`nav${type}`)}
</div>
`)
.attr("data-gt2-color-override-ignore", "")
}
// highlight current location
$(`.gt2-nav a[href^='/${getPath().split("/")[0]}']`).addClass("active")
// twitter logo
$("h1 a[href='/home'] svg")
.appendTo(".gt2-nav-center a")
})
}
function watchForChanges(selector, callback) {
waitForKeyElements(selector, $element => {
let element = $element[0]
if (element) {
new MutationObserver(mut => {
mut.forEach(() => callback(element))
}).observe(element, {
attributes: true,
subtree: true,
childList: true
})
}
})
}
// add navbar
function addNavbarLoggedOut() {
waitForKeyElements("nav > a[data-testid=AppTabBar_Explore_Link]", () => {
if ($(".gt2-nav").length) return
$("body").prepend(`
<nav class="gt2-nav">
<div class="gt2-nav-left"></div>
<div class="gt2-nav-center">
<a href="/"></a>
</div>
<div class="gt2-nav-right">
<div class="gt2-search"></div>
</div>
</nav>
<div class="gt2-search-overflow-hider"></div>
`)
// explore and settings
$(`nav > a[data-testid=AppTabBar_Explore_Link],
nav > a[href="/settings"]`)
.appendTo(".gt2-nav-left")
$(`.gt2-nav a[data-testid=AppTabBar_Explore_Link] > div`)
.append(`
<div class="gt2-nav-header">
${getLocStr(`navExplore`)}
</div>
`)
$(`.gt2-nav a[href="/settings"] > div`)
.append(`
<div class="gt2-nav-header">
${$(`.gt2-nav a[href="/settings"]`).attr("aria-label")}
</div>
`)
// highlight current location
$(`.gt2-nav a[href^='/${getPath().split("/")[0]}']`).addClass("active")
// twitter logo
$("header h1 a[href='/'] svg")
.appendTo(".gt2-nav-center a")
})
}
// add search
function addSearch() {
let search = "div[data-testid=sidebarColumn] > div > div:nth-child(2) > div > div > div > div:nth-child(1)"
waitForKeyElements(`${search} input[data-testid=SearchBox_Search_Input]`, () => {
// remove if added previously
$(".gt2-search").empty()
// add search
$(search)
.prependTo(".gt2-search")
$("body").addClass("gt2-search-added")
})
}
// add element to sidebar
function addToSidebar(elements) {
let w = window.innerWidth
let insertAt = ".gt2-left-sidebar"
// insert into the right sidebar
if ((!GM_getValue("opt_gt2").smallSidebars && w <= 1350) ||
( GM_getValue("opt_gt2").smallSidebars && w <= 1230)) {
insertAt = "div[data-testid=sidebarColumn] > div > div:nth-child(2) > div > div > div"
}
elements.unshift(`<div class="gt2-legacy-profile-info"></div>`)
waitForKeyElements(insertAt, () => {
if (!$(insertAt).find(".gt2-legacy-profile-info").length) {
for (let elem of elements.slice().reverse()) {
if (insertAt.startsWith(".gt2")) {
$(insertAt).prepend(elem)
} else {
$(`${insertAt} > div:empty:not(.gt2-legacy-profile-info)`).after(elem)
}
}
}
if ($(".gt2-dashboard-profile").length > 1) {
$(".gt2-dashboard-profile").last().remove()
}
})
}