-
Notifications
You must be signed in to change notification settings - Fork 11
/
twitter-click-and-save.user.js
2419 lines (2123 loc) · 101 KB
/
twitter-click-and-save.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 Twitter Click'n'Save
// @version 1.13.2-2024.11.17
// @namespace gh.alttiri
// @description Add buttons to download images and videos in Twitter, also does some other enhancements.
// @match https://twitter.com/*
// @match https://x.com/*
// @homepageURL https://github.com/AlttiRi/twitter-click-and-save
// @supportURL https://github.com/AlttiRi/twitter-click-and-save/issues
// @license GPL-3.0
// @grant GM_registerMenuCommand
// ==/UserScript==
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// Please, report bugs and suggestions on GitHub, not Greasyfork. I rarely visit Greasyfork.
// --> https://github.com/AlttiRi/twitter-click-and-save/issues <--
// ---------------------------------------------------------------------------------------------------------------------
const sitename = location.hostname.replace(".com", ""); // "twitter" | "x"
// ---------------------------------------------------------------------------------------------------------------------
// --- "Imports" --- //
const {StorageNames, StorageNamesOld} = getStorageNames();
const {verbose, debugPopup} = getDebugSettings(); // --- For debug --- //
const {
sleep, fetchResource, downloadBlob,
addCSS,
getCookie,
throttle,
xpath, xpathAll,
responseProgressProxy,
dateToDayDateString,
toLineJSON,
isFirefox,
getBrowserName,
removeSearchParams,
} = getUtils({verbose});
const LS = hoistLS({verbose});
const API = hoistAPI();
const Tweet = hoistTweet();
const Features = hoistFeatures();
const I18N = getLanguageConstants();
// ---------------------------------------------------------------------------------------------------------------------
function getStorageNames() {
// New LocalStorage key names 2023.07.05
const StorageNames = {
settings: "ujs-twitter-click-n-save-settings",
settingsImageHistoryBy: "ujs-twitter-click-n-save-settings-image-history-by",
downloadedImageNames: "ujs-twitter-click-n-save-downloaded-image-names",
downloadedImageTweetIds: "ujs-twitter-click-n-save-downloaded-image-tweet-ids",
downloadedVideoTweetIds: "ujs-twitter-click-n-save-downloaded-video-tweet-ids",
migrated: "ujs-twitter-click-n-save-migrated", // Currently unused
browserName: "ujs-twitter-click-n-save-browser-name", // Hidden settings
verbose: "ujs-twitter-click-n-save-verbose", // Hidden settings for debug
debugPopup: "ujs-twitter-click-n-save-debug-popup", // Hidden settings for debug
};
const StorageNamesOld = {
settings: "ujs-click-n-save-settings",
settingsImageHistoryBy: "ujs-images-history-by",
downloadedImageNames: "ujs-twitter-downloaded-images-names",
downloadedImageTweetIds: "ujs-twitter-downloaded-image-tweet-ids",
downloadedVideoTweetIds: "ujs-twitter-downloaded-video-tweet-ids",
};
return {StorageNames, StorageNamesOld};
}
function getDebugSettings() {
let verbose = false;
let debugPopup = false;
try {
verbose = Boolean(JSON.parse(localStorage.getItem(StorageNames.verbose)));
} catch (err) {}
try {
debugPopup = Boolean(JSON.parse(localStorage.getItem(StorageNames.debugPopup)));
} catch (err) {}
return {verbose, debugPopup};
}
const historyHelper = getHistoryHelper();
historyHelper.migrateLocalStore();
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
if (globalThis.GM_registerMenuCommand /* undefined in Firefox with VM */ || typeof GM_registerMenuCommand === "function") {
GM_registerMenuCommand("Show settings", showSettings);
}
const settings = loadSettings();
if (verbose) {
console.log("[ujs][settings]", settings);
}
if (debugPopup) {
showSettings();
}
// ---------------------------------------------------------------------------------------------------------------------
const fetch = ujs_getGlobalFetch({verbose, strictTrackingProtectionFix: settings.strictTrackingProtectionFix});
function ujs_getGlobalFetch({verbose, strictTrackingProtectionFix} = {}) {
const useFirefoxStrictTrackingProtectionFix = strictTrackingProtectionFix === undefined ? true : strictTrackingProtectionFix; // Let's use by default
const useFirefoxFix = useFirefoxStrictTrackingProtectionFix && typeof wrappedJSObject === "object" && typeof wrappedJSObject.fetch === "function";
// --- [VM/GM + Firefox ~90+ + Enabled "Strict Tracking Protection"] fix --- //
function fixedFirefoxFetch(resource, init = {}) {
verbose && console.log("[ujs][wrappedJSObject.fetch]", resource, init);
if (init.headers instanceof Headers) {
// Since `Headers` are not allowed for structured cloning.
init.headers = Object.fromEntries(init.headers.entries());
}
return wrappedJSObject.fetch(cloneInto(resource, document), cloneInto(init, document));
}
return useFirefoxFix ? fixedFirefoxFetch : globalThis.fetch;
}
// ---------------------------------------------------------------------------------------------------------------------
// --- Features to execute --- //
const doNotPlayVideosAutomatically = false; // Hidden settings
function execFeaturesOnce() {
settings.goFromMobileToMainSite && Features.goFromMobileToMainSite();
settings.addRequiredCSS && Features.addRequiredCSS();
settings.hideSignUpBottomBarAndMessages && Features.hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically);
settings.hideTrends && Features.hideTrends();
settings.highlightVisitedLinks && Features.highlightVisitedLinks();
settings.hideLoginPopup && Features.hideLoginPopup();
}
function execFeaturesImmediately() {
settings.expandSpoilers && Features.expandSpoilers();
}
function execFeatures() {
settings.imagesHandler && Features.imagesHandler();
settings.videoHandler && Features.videoHandler();
settings.expandSpoilers && Features.expandSpoilers();
settings.hideSignUpSection && Features.hideSignUpSection();
settings.directLinks && Features.directLinks();
settings.handleTitle && Features.handleTitle();
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// --- Script runner --- //
(function starter(feats) {
const {once, onChangeImmediate, onChange} = feats;
once();
onChangeImmediate();
const onChangeThrottled = throttle(onChange, 250);
onChangeThrottled();
const targetNode = document.querySelector("body");
const observerOptions = {
subtree: true,
childList: true,
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
function callback(mutationList, _observer) {
verbose && console.log("[ujs][mutationList]", mutationList);
onChangeImmediate();
onChangeThrottled();
}
})({
once: execFeaturesOnce,
onChangeImmediate: execFeaturesImmediately,
onChange: execFeatures
});
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
function loadSettings() {
const defaultSettings = {
hideTrends: true,
hideSignUpSection: false,
hideSignUpBottomBarAndMessages: false,
doNotPlayVideosAutomatically: false,
goFromMobileToMainSite: false,
highlightVisitedLinks: true,
highlightOnlySpecialVisitedLinks: true,
expandSpoilers: true,
directLinks: true,
handleTitle: true,
imagesHandler: true,
videoHandler: true,
addRequiredCSS: true,
hideLoginPopup: false,
addBorder: false,
downloadProgress: true,
strictTrackingProtectionFix: false,
};
let savedSettings;
try {
savedSettings = JSON.parse(localStorage.getItem(StorageNames.settings)) || {};
} catch (err) {
console.error("[ujs][parse-settings]", err);
localStorage.removeItem(StorageNames.settings);
savedSettings = {};
}
savedSettings = Object.assign(defaultSettings, savedSettings);
return savedSettings;
}
function showSettings() {
closeSetting();
if (window.scrollY > 0) {
document.querySelector("html").classList.add("ujs-scroll-initial");
document.body.classList.add("ujs-scrollbar-width-margin-right");
}
document.body.classList.add("ujs-no-scroll");
const modalWrapperStyle = `
color-scheme: light;
width: 100%;
height: 100%;
position: fixed;
display: flex;
justify-content: center;
align-items: center;
z-index: 99999;
backdrop-filter: blur(4px);
background-color: rgba(255, 255, 255, 0.5);
`;
const modalSettingsStyle = `
background-color: white;
min-width: 320px;
min-height: 320px;
border: 1px solid darkgray;
padding: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
`;
const s = settings;
const downloadProgressFFTitle = `Disable the download progress if you use Firefox with "Enhanced Tracking Protection" set to "Strict" and ViolentMonkey, or GreaseMonkey extension`;
const strictTrackingProtectionFixFFTitle = `Choose this if you use ViolentMonkey, or GreaseMonkey in Firefox with "Enhanced Tracking Protection" set to "Strict". It is not required in case you use TamperMonkey.`;
document.body.insertAdjacentHTML("afterbegin", `
<div class="ujs-modal-wrapper" style="${modalWrapperStyle}">
<div class="ujs-modal-settings" style="${modalSettingsStyle}">
<fieldset>
<legend>Optional</legend>
<label title="Makes the button more visible"><input type="checkbox" ${s.addBorder ? "checked" : ""} name="addBorder">Add a white border to the download button<br/></label>
<label title="WARNING: It may broke the login page, but it works fine if you logged in and want to hide 'Messages'"><input type="checkbox" ${s.hideSignUpBottomBarAndMessages ? "checked" : ""} name="hideSignUpBottomBarAndMessages">Hide <strike><b>Sign Up Bar</b> and</strike> <b>Messages</b> and <b>Cookies</b> (in the bottom). <span title="WARNING: It may broke the login page!">(beta)</span><br/></label>
<label><input type="checkbox" ${s.hideTrends ? "checked" : ""} name="hideTrends">Hide <b>Trends</b> (in the right column)*<br/></label>
<label hidden><input type="checkbox" ${s.doNotPlayVideosAutomatically ? "checked" : ""} name="doNotPlayVideosAutomatically">Do <i>Not</i> Play Videos Automatically</b><br/></label>
<label hidden><input type="checkbox" ${s.goFromMobileToMainSite ? "checked" : ""} name="goFromMobileToMainSite">Redirect from Mobile version (beta)<br/></label>
</fieldset>
<fieldset>
<legend>Recommended</legend>
<label><input type="checkbox" ${s.highlightVisitedLinks ? "checked" : ""} name="highlightVisitedLinks">Highlight Visited Links<br/></label>
<label title="In most cases absolute links are 3rd-party links"><input type="checkbox" ${s.highlightOnlySpecialVisitedLinks ? "checked" : ""} name="highlightOnlySpecialVisitedLinks">Highlight Only Absolute Visited Links<br/></label>
<label title="Note: since the recent update the most NSFW spoilers are impossible to expand without an account"><input type="checkbox" ${s.expandSpoilers ? "checked" : ""} name="expandSpoilers">Expand Spoilers (if possible)*<br/></label>
</fieldset>
<fieldset>
<legend>Highly Recommended</legend>
<label><input type="checkbox" ${s.directLinks ? "checked" : ""} name="directLinks">Direct Links</label><br/>
<label><input type="checkbox" ${s.handleTitle ? "checked" : ""} name="handleTitle">Enchance Title*<br/></label>
</fieldset>
<fieldset ${isFirefox ? '': 'style="display: none"'}>
<legend>Firefox only</legend>
<label title='${downloadProgressFFTitle}'><input type="radio" ${s.downloadProgress ? "checked" : ""} name="firefoxDownloadProgress" value="downloadProgress">Download Progress<br/></label>
<label title='${strictTrackingProtectionFixFFTitle}'><input type="radio" ${s.strictTrackingProtectionFix ? "checked" : ""} name="firefoxDownloadProgress" value="strictTrackingProtectionFix">Strict Tracking Protection Fix<br/></label>
</fieldset>
<fieldset>
<legend>Main</legend>
<label><input type="checkbox" ${s.imagesHandler ? "checked" : ""} name="imagesHandler">Image Download Button<br/></label>
<label><input type="checkbox" ${s.videoHandler ? "checked" : ""} name="videoHandler">Video Download Button<br/></label>
<label hidden><input type="checkbox" ${s.addRequiredCSS ? "checked" : ""} name="addRequiredCSS">Add Required CSS*<br/></label><!-- * Only for the image download button in /photo/1 mode -->
</fieldset>
<fieldset>
<legend title="Outdated due to Twitter's updates, or impossible to reimplement">Outdated</legend>
<strike>
<label><input type="checkbox" ${s.hideSignUpSection ? "checked" : ""} name="hideSignUpSection">Hide <b title='"New to Twitter?" (If yoy are not logged in)'>Sign Up</b> section (in the right column)*<br/></label>
<label title="Hides the modal login pop up. Useful if you have no account. \nWARNING: Currently it will close any popup, not only the login one.\nIt's recommended to use only if you do not have an account to hide the annoiyng login popup."><input type="checkbox" ${s.hideLoginPopup ? "checked" : ""} name="hideLoginPopup">Hide <strike>Login</strike> Popups. (beta)<br/></label>
</strike>
</fieldset>
<hr>
<div style="display: flex; justify-content: space-around;">
<div>
History:
<button class="ujs-reload-export-button" style="padding: 5px" >Export</button>
<button class="ujs-reload-import-button" style="padding: 5px" >Import</button>
<button class="ujs-reload-merge-button" style="padding: 5px" >Merge</button>
</div>
<div>
<button class="ujs-reload-setting-button" style="padding: 5px" title="Reload the web page to apply changes">Reload page</button>
<button class="ujs-close-setting-button" style="padding: 5px" title="Just close this popup.\nNote: You need to reload the web page to apply changes.">Close popup</button>
</div>
</div>
<hr>
<h4 style="margin: 0; padding-left: 8px; color: #444;">Notes:</h4>
<ul style="margin: 2px; padding-left: 16px; color: #444;">
<li><b>Reload the page</b> to apply changes.</li>
<li><b>*</b>-marked settings are language dependent. Currently, the follow languages are supported:<br/> "en", "ru", "es", "zh", "ja".</li>
<li hidden>The extension downloads only from twitter.com, not from <b>mobile</b>.twitter.com</li>
</ul>
</div>
</div>`);
async function onDone(button) {
button.classList.remove("ujs-btn-error");
button.classList.add("ujs-btn-done");
await sleep(900);
button.classList.remove("ujs-btn-done");
}
async function onError(button, err) {
button.classList.remove("ujs-btn-done");
button.classList.add("ujs-btn-error");
button.title = err.message;
await sleep(1800);
button.classList.remove("ujs-btn-error");
}
const exportButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-export-button");
const importButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-import-button");
const mergeButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-merge-button");
exportButton.addEventListener("click", (event) => {
const button = event.currentTarget;
historyHelper.exportHistory(() => onDone(button));
});
sleep(50).then(() => {
const infoObj = getStoreInfo();
exportButton.title = Object.entries(infoObj).reduce((acc, [key, value]) => {
acc += `${key}: ${value}\n`;
return acc;
}, "");
});
importButton.addEventListener("click", (event) => {
const button = event.currentTarget;
historyHelper.importHistory(
() => onDone(button),
(err) => onError(button, err)
);
});
mergeButton.addEventListener("click", (event) => {
const button = event.currentTarget;
historyHelper.mergeHistory(
() => onDone(button),
(err) => onError(button, err)
);
});
document.querySelector("body > .ujs-modal-wrapper .ujs-reload-setting-button").addEventListener("click", () => {
location.reload();
});
const checkboxList = document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox], body > .ujs-modal-wrapper input[type=radio]");
checkboxList.forEach(checkbox => {
checkbox.addEventListener("change", saveSetting);
});
document.querySelector("body > .ujs-modal-wrapper .ujs-close-setting-button").addEventListener("click", closeSetting);
function saveSetting() {
const entries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox]")]
.map(checkbox => [checkbox.name, checkbox.checked]);
const radioEntries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=radio]")]
.map(checkbox => [checkbox.value, checkbox.checked])
const settings = Object.fromEntries([entries, radioEntries].flat());
// verbose && console.log("[ujs][save-settings]", settings);
localStorage.setItem(StorageNames.settings, JSON.stringify(settings));
}
function closeSetting() {
document.body.classList.remove("ujs-no-scroll");
document.body.classList.remove("ujs-scrollbar-width-margin-right");
document.querySelector("html").classList.remove("ujs-scroll-initial");
document.querySelector("body > .ujs-modal-wrapper")?.remove();
}
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// --- Twitter Specific code --- //
const downloadedImages = new LS(StorageNames.downloadedImageNames);
const downloadedImageTweetIds = new LS(StorageNames.downloadedImageTweetIds);
const downloadedVideoTweetIds = new LS(StorageNames.downloadedVideoTweetIds);
// --- That to use for the image history --- //
/** @type {"TWEET_ID" | "IMAGE_NAME"} */
const imagesHistoryBy = LS.getItem(StorageNames.settingsImageHistoryBy, "IMAGE_NAME"); // Hidden settings
// With "TWEET_ID" downloading of 1 image of 4 will mark all 4 images as "already downloaded"
// on the next time when the tweet will appear.
// "IMAGE_NAME" will count each image of a tweet, but it will take more data to store.
// ---------------------------------------------------------------------------------------------------------------------
// --- Twitter.Features --- //
function hoistFeatures() {
class Features {
static createButton({url, downloaded, isVideo, isThumb, isMultiMedia}) {
const btn = document.createElement("div");
btn.innerHTML = `
<div class="ujs-btn-common ujs-btn-background"></div>
<div class="ujs-btn-common ujs-hover"></div>
<div class="ujs-btn-common ujs-shadow"></div>
<div class="ujs-btn-common ujs-progress" style="--progress: 0%"></div>
<div class="ujs-btn-common ujs-btn-error-text"></div>`.slice(1);
btn.classList.add("ujs-btn-download");
if (!downloaded) {
btn.classList.add("ujs-not-downloaded");
} else {
btn.classList.add("ujs-already-downloaded");
}
if (isVideo) {
btn.classList.add("ujs-video");
}
if (url) {
btn.dataset.url = url;
}
if (isThumb) {
btn.dataset.thumb = "true";
}
if (isMultiMedia) {
btn.dataset.isMultiMedia = "true";
}
return btn;
}
static _markButtonAsDownloaded(btn) {
btn.classList.remove("ujs-downloading");
btn.classList.remove("ujs-recently-downloaded");
btn.classList.add("ujs-downloaded");
btn.addEventListener("pointerenter", e => {
btn.classList.add("ujs-recently-downloaded");
}, {once: true});
}
// Banner/Background
static async _downloadBanner(url, btn) {
const username = location.pathname.slice(1).split("/")[0];
btn.classList.add("ujs-downloading");
// https://pbs.twimg.com/profile_banners/34743251/1596331248/1500x500
const {
id, seconds, res
} = url.match(/(?<=\/profile_banners\/)(?<id>\d+)\/(?<seconds>\d+)\/(?<res>\d+x\d+)/)?.groups || {};
const {blob, lastModifiedDate, extension, name} = await fetchResource(url);
Features.verifyBlob(blob, url, btn);
const filename = `[twitter][bg] ${username}—${lastModifiedDate}—${id}—${seconds}.${extension}`;
downloadBlob(blob, filename, url);
Features._markButtonAsDownloaded(btn);
}
static _ImageHistory = class {
static getImageNameFromUrl(url) {
const _url = new URL(url);
const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
return filename.match(/^[^.]+/)[0]; // remove extension
}
static isDownloaded({id, url}) {
if (imagesHistoryBy === "TWEET_ID") {
return downloadedImageTweetIds.hasItem(id);
} else if (imagesHistoryBy === "IMAGE_NAME") {
const name = Features._ImageHistory.getImageNameFromUrl(url);
return downloadedImages.hasItem(name);
}
}
static async markDownloaded({id, url}) {
if (imagesHistoryBy === "TWEET_ID") {
await downloadedImageTweetIds.pushItem(id);
} else if (imagesHistoryBy === "IMAGE_NAME") {
const name = Features._ImageHistory.getImageNameFromUrl(url);
await downloadedImages.pushItem(name);
}
}
}
static async imagesHandler() {
verbose && console.log("[ujs][imagesHandler]");
const images = document.querySelectorAll(`img:not([data-handled]):not([src$=".svg"])`);
for (const img of images) {
if (img.dataset.handled) {
continue;
}
img.dataset.handled = "true";
if (img.width === 0) {
const imgOnload = new Promise(async (resolve) => {
img.onload = resolve;
});
await Promise.any([imgOnload, sleep(500)]);
await sleep(10); // to get updated img.width
}
if (img.width < 140) {
continue;
}
verbose && console.log("[ujs][imagesHandler]", {img, img_width: img.width});
let anchor = img.closest("a");
// if expanded_url (an image is _opened_ "https://twitter.com/UserName/status/1234567890123456789/photo/1" [fake-url])
if (!anchor) {
anchor = img.parentNode;
}
const listitemEl = img.closest(`li[role="listitem"]`);
const isThumb = Boolean(listitemEl); // isMediaThumbnail
if (isThumb && anchor.querySelector("svg")) {
await Features.multiMediaThumbHandler(img);
continue;
}
const isMobileVideo = img.src.includes("ext_tw_video_thumb") || img.src.includes("amplify_video_thumb") || img.closest(`a[aria-label="Embedded video"]`) || img.alt === "Animated Text GIF" || img.alt === "Embedded video"
|| img.src.includes("tweet_video_thumb") /* GIF thumb */;
if (isMobileVideo) {
await Features.mobileVideoHandler(img, isThumb); // thumbVideoHandler
continue;
}
const btn = Features.createButton({url: img.src, isThumb});
btn.addEventListener("click", Features._imageClickHandler);
anchor.append(btn);
const downloaded = Features._ImageHistory.isDownloaded({
id: Tweet.of(btn).id,
url: btn.dataset.url
});
if (downloaded) {
btn.classList.add("ujs-already-downloaded");
}
}
}
static async _imageClickHandler(event) {
event.preventDefault();
event.stopImmediatePropagation();
const btn = event.currentTarget;
let url = btn.dataset.url;
const isBanner = url.includes("/profile_banners/");
if (isBanner) {
return Features._downloadBanner(url, btn);
}
const {id, author} = Tweet.of(btn);
verbose && console.log("[ujs][_imageClickHandler]", {id, author});
await Features._downloadPhotoMediaEntry(id, author, url, btn);
Features._markButtonAsDownloaded(btn);
}
static async _downloadPhotoMediaEntry(id, author, url, btn) {
const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
const btnProgress = btn.querySelector(".ujs-progress");
if (btn.textContent !== "") {
btnErrorTextElem.textContent = "";
}
btn.classList.remove("ujs-error");
btn.classList.add("ujs-downloading");
let onProgress = null;
if (settings.downloadProgress) {
onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
}
const originals = ["orig", "4096x4096"];
const samples = ["large", "medium", "900x900", "small", "360x360", /*"240x240", "120x120", "tiny"*/];
let isSample = false;
const previewSize = new URL(url).searchParams.get("name");
if (!samples.includes(previewSize)) {
samples.push(previewSize);
}
function handleImgUrl(url) {
const urlObj = new URL(url);
if (originals.length) {
urlObj.searchParams.set("name", originals.shift());
} else if (samples.length) {
isSample = true;
urlObj.searchParams.set("name", samples.shift());
} else {
throw new Error("All fallback URLs are failed to download.");
}
if (urlObj.searchParams.get("format") === "webp") {
urlObj.searchParams.set("format", "jpg");
}
url = urlObj.toString();
verbose && console.log("[ujs][handleImgUrl][url]", url);
return url;
}
async function safeFetchResource(url) {
while (true) {
url = handleImgUrl(url);
try {
const result = await fetchResource(url, onProgress);
if (result.status === 404) {
const urlObj = new URL(url);
const params = urlObj.searchParams;
if (params.get("name") === "orig" && params.get("format") === "jpg") {
params.set("format", "png");
url = urlObj.toString();
return await fetchResource(url, onProgress);
}
}
return result;
} catch (err) {
if (!originals.length) {
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "";
// Add ⚠
btnErrorTextElem.style = `background-image: url("https://abs-0.twimg.com/emoji/v2/svg/26a0.svg"); background-size: 1.5em; background-position: center; background-repeat: no-repeat;`;
btn.title = "[warning] Original images are not available.";
}
const ffAutoAllocateChunkSizeBug = err.message.includes("autoAllocateChunkSize"); // https://bugzilla.mozilla.org/show_bug.cgi?id=1757836
if (!samples.length || ffAutoAllocateChunkSizeBug) {
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "";
// Add ❌
btnErrorTextElem.style = `background-image: url("https://abs-0.twimg.com/emoji/v2/svg/274c.svg"); background-size: 1.5em; background-position: center; background-repeat: no-repeat;`;
const ffHint = isFirefox && !settings.strictTrackingProtectionFix && ffAutoAllocateChunkSizeBug ? "\nTry to enable 'Strict Tracking Protection Fix' in the userscript settings." : "";
btn.title = "Failed to download the image." + ffHint;
throw new Error("[error] Fallback URLs are failed.");
}
}
}
}
const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url);
Features.verifyBlob(blob, url, btn);
btnProgress.style.cssText = "--progress: 100%";
const sampleText = !isSample ? "" : "[sample]";
const filename = `[twitter]${sampleText} ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
downloadBlob(blob, filename, url);
const downloaded = btn.classList.contains("ujs-already-downloaded") || btn.classList.contains("ujs-downloaded");
if (!downloaded && !isSample) {
await Features._ImageHistory.markDownloaded({id, url});
}
if (btn.dataset.isMultiMedia && !isSample) { // dirty fix
const isDownloaded = Features._ImageHistory.isDownloaded({id, url});
if (!isDownloaded) {
await Features._ImageHistory.markDownloaded({id, url});
}
}
await sleep(40);
btnProgress.style.cssText = "--progress: 0%";
}
// Quick Dirty Fix // todo refactor
static async mobileVideoHandler(imgElem, isThumb) { // thumbVideoHandler // todo rename?
verbose && console.log("[ujs][mobileVideoHandler][vid]", imgElem);
const btn = Features.createButton({isVideo: true, url: imgElem.src, isThumb});
btn.addEventListener("click", Features._videoClickHandler);
let anchor = imgElem.closest("a");
if (!anchor) {
anchor = imgElem.parentNode;
}
anchor.append(btn);
const tweet = Tweet.of(btn);
const id = tweet.id;
const tweetElem = tweet.elem || btn.closest(`[data-testid="tweet"]`);
let vidNumber = 0;
if (tweetElem) {
const map = Features.tweetVidWeakMapMobile;
if (map.has(tweetElem)) {
vidNumber = map.get(tweetElem) + 1;
map.set(tweetElem, vidNumber);
} else {
map.set(tweetElem, vidNumber); // can throw an error for null
}
} // else thumbnail
const historyId = vidNumber ? id + "-" + vidNumber : id;
const downloaded = downloadedVideoTweetIds.hasItem(historyId);
if (downloaded) {
btn.classList.add("ujs-already-downloaded");
}
}
static async multiMediaThumbHandler(imgElem) {
verbose && console.log("[ujs][multiMediaThumbHandler]", imgElem);
let isVideo = false;
if (imgElem.src.includes("/ext_tw_video_thumb/") || imgElem.src.includes("/amplify_video_thumb/")) {
isVideo = true;
}
const btn = Features.createButton({url: imgElem.src, isVideo, isThumb: true, isMultiMedia: true});
btn.addEventListener("click", Features._multiMediaThumbClickHandler);
let anchor = imgElem.closest("a");
if (!anchor) {
anchor = imgElem.parentNode;
}
anchor.append(btn);
let downloaded;
const tweetId = Tweet.of(btn).id;
if (isVideo) {
downloaded = downloadedVideoTweetIds.hasItem(tweetId);
} else {
downloaded = Features._ImageHistory.isDownloaded({
id: tweetId,
url: btn.dataset.url
});
}
if (downloaded) {
btn.classList.add("ujs-already-downloaded");
}
}
static async _multiMediaThumbClickHandler(event) {
event.preventDefault();
event.stopImmediatePropagation();
const btn = event.currentTarget;
const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
if (btn.textContent !== "") {
btnErrorTextElem.textContent = "";
}
const {id} = Tweet.of(btn);
/** @type {TweetMediaEntry[]} */
let medias;
try {
medias = await API.getTweetMedias(id);
medias = medias.filter(mediaEntry => mediaEntry.tweet_id === id);
} catch (err) {
console.error(err);
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "Error";
btn.title = "API.getTweetMedias Error";
throw new Error("API.getTweetMedias Error");
}
for (const mediaEntry of medias) {
if (mediaEntry.type === "video") {
await Features._downloadVideoMediaEntry(mediaEntry, btn, id);
} else { // "photo"
const {screen_name: author,download_url: url, tweet_id: id} = mediaEntry;
await Features._downloadPhotoMediaEntry(id, author, url, btn);
}
await sleep(50);
}
Features._markButtonAsDownloaded(btn);
}
static tweetVidWeakMapMobile = new WeakMap();
static tweetVidWeakMap = new WeakMap();
static async videoHandler() {
const videos = document.querySelectorAll("video:not([data-handled])");
for (const vid of videos) {
if (vid.dataset.handled) {
continue;
}
vid.dataset.handled = "true";
verbose && console.log("[ujs][videoHandler][vid]", vid);
const poster = vid.getAttribute("poster");
const btn = Features.createButton({isVideo: true, url: poster});
btn.addEventListener("click", Features._videoClickHandler);
let elem = vid.closest(`[data-testid="videoComponent"]`).parentNode;
if (elem) {
elem.append(btn);
} else {
elem = vid.parentNode.parentNode.parentNode;
elem.after(btn);
}
const tweet = Tweet.of(btn);
const id = tweet.id;
const tweetElem = tweet.elem;
let vidNumber = 0;
if (tweetElem) {
const map = Features.tweetVidWeakMap;
if (map.has(tweetElem)) {
vidNumber = map.get(tweetElem) + 1;
map.set(tweetElem, vidNumber);
} else {
map.set(tweetElem, vidNumber); // can throw an error for null
}
} else { // expanded_url
await sleep(10);
const match = location.pathname.match(/(?<=\/video\/)\d/);
if (!match) {
verbose && console.log("[ujs][videoHandler] missed match for match");
}
vidNumber = Number(match[0]) - 1;
console.warn("[ujs][videoHandler] vidNumber", vidNumber);
// todo: add support for expanded_url video downloading
}
const historyId = vidNumber ? id + "-" + vidNumber : id;
const downloaded = downloadedVideoTweetIds.hasItem(historyId);
if (downloaded) {
btn.classList.add("ujs-already-downloaded");
}
}
}
static async _videoClickHandler(event) { // todo: parse the URL from HTML (For "Embedded video" (?))
event.preventDefault();
event.stopImmediatePropagation();
const btn = event.currentTarget;
const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
const {id} = Tweet.of(btn);
if (btn.textContent !== "") {
btnErrorTextElem.textContent = "";
}
btn.classList.remove("ujs-error");
btn.classList.add("ujs-downloading");
let mediaEntry;
try {
const medias = await API.getTweetMedias(id);
const posterUrl = btn.dataset.url; // [note] if `posterUrl` has `searchParams`, it will have no extension at the end of `pathname`.
const posterUrlClear = removeSearchParams(posterUrl);
mediaEntry = medias.find(media => media.preview_url.startsWith(posterUrlClear));
verbose && console.log("[ujs][_videoClickHandler] mediaEntry", mediaEntry);
} catch (err) {
console.error(err);
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "Error";
btn.title = "API.getVideoInfo Error";
throw new Error("API.getVideoInfo Error");
}
try {
await Features._downloadVideoMediaEntry(mediaEntry, btn, id);
} catch (err) {
console.error(err);
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "Error";
btn.title = err.message + " Error";
throw err;
}
Features._markButtonAsDownloaded(btn);
}
static async _downloadVideoMediaEntry(mediaEntry, btn, id /* of original tweet */) {
if (!mediaEntry) {
throw new Error("No mediaEntry found");
}
const {
screen_name: author,
tweet_id: videoTweetId,
download_url: url,
type_index: vidNumber,
} = mediaEntry;
if (!url) {
throw new Error("No video URL found");
}
const btnProgress = btn.querySelector(".ujs-progress");
let onProgress = null;
if (settings.downloadProgress) {
onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
}
async function safeFetchResource(url, onProgress) {
try {
return await fetchResource(url, onProgress);
} catch (err) {
const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
const ffAutoAllocateChunkSizeBug = err.message.includes("autoAllocateChunkSize"); // https://bugzilla.mozilla.org/show_bug.cgi?id=1757836
btn.classList.add("ujs-error");
btnErrorTextElem.textContent = "";
// Add ❌
btnErrorTextElem.style = `background-image: url("https://abs-0.twimg.com/emoji/v2/svg/274c.svg"); background-size: 1.5em; background-position: center; background-repeat: no-repeat;`;
const ffHint = isFirefox && !settings.strictTrackingProtectionFix && ffAutoAllocateChunkSizeBug ? "\nTry to enable 'Strict Tracking Protection Fix' in the userscript settings." : "";
btn.title = "Video download failed." + ffHint;
throw new Error("[error] Video download failed.");
}
}
const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url, onProgress);
btnProgress.style.cssText = "--progress: 100%";
Features.verifyBlob(blob, url, btn);
const filename = `[twitter] ${author}—${lastModifiedDate}—${videoTweetId}—${name}.${extension}`;
downloadBlob(blob, filename, url);
const downloaded = btn.classList.contains("ujs-already-downloaded");
const historyId = vidNumber /* not 0 */ ? videoTweetId + "-" + vidNumber : videoTweetId;
if (!downloaded) {
await downloadedVideoTweetIds.pushItem(historyId);
if (videoTweetId !== id) { // if QRT
const historyId = vidNumber ? id + "-" + vidNumber : id;
await downloadedVideoTweetIds.pushItem(historyId);
}
}
if (btn.dataset.isMultiMedia) { // dirty fix
const isDownloaded = downloadedVideoTweetIds.hasItem(historyId);
if (!isDownloaded) {
await downloadedVideoTweetIds.pushItem(historyId);
if (videoTweetId !== id) { // if QRT
const historyId = vidNumber ? id + "-" + vidNumber : id;
await downloadedVideoTweetIds.pushItem(historyId);
}
}
}
await sleep(40);
btnProgress.style.cssText = "--progress: 0%";
}
static verifyBlob(blob, url, btn) {
if (!blob.size) {
btn.classList.add("ujs-error");
btn.querySelector(".ujs-btn-error-text").textContent = "Error";
btn.title = "Download Error";
throw new Error("Zero size blob: " + url);
}
}
static addRequiredCSS() {
const code = getUserScriptCSS();
addCSS(code);
}
// it depends on `directLinks()` use only it after `directLinks()`
static handleTitle(title) {
if (!I18N.QUOTES) { // Unsupported lang, no QUOTES, ON_TWITTER, TWITTER constants
return;
}
// if not an opened tweet
if (!location.href.match(/(twitter|x)\.com\/[^\/]+\/status\/\d+/)) {
return;
}
let titleText = title || document.title;
if (titleText === Features.lastHandledTitle) {
return;
}
Features.originalTitle = titleText;
const [OPEN_QUOTE, CLOSE_QUOTE] = I18N.QUOTES;
const urlsToReplace = [
...titleText.matchAll(new RegExp(`https:\\/\\/t\\.co\\/[^ ${CLOSE_QUOTE}]+`, "g"))
].map(el => el[0]);
// the last one may be the URL to the tweet // or to an embedded shared URL
const map = new Map();
const anchors = document.querySelectorAll(`a[data-redirect^="https://t.co/"]`);
for (const anchor of anchors) {
if (urlsToReplace.includes(anchor.dataset.redirect)) {
map.set(anchor.dataset.redirect, anchor.href);
}
}
const lastUrl = urlsToReplace.slice(-1)[0];