Twitter Click'n'Save

Add buttons to download images and videos in Twitter, also does some other enhancements.

目前为 2025-04-27 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Twitter Click'n'Save
  3. // @version 1.14.0-2025.04.27
  4. // @namespace gh.alttiri
  5. // @description Add buttons to download images and videos in Twitter, also does some other enhancements.
  6. // @match https://twitter.com/*
  7. // @match https://x.com/*
  8. // @homepageURL https://github.com/AlttiRi/twitter-click-and-save
  9. // @supportURL https://github.com/AlttiRi/twitter-click-and-save/issues
  10. // @license GPL-3.0
  11. // @grant GM_registerMenuCommand
  12. // ==/UserScript==
  13. // ---------------------------------------------------------------------------------------------------------------------
  14. // ---------------------------------------------------------------------------------------------------------------------
  15.  
  16.  
  17.  
  18. // Please, report bugs and suggestions on GitHub, not Greasyfork. I rarely visit Greasyfork.
  19. // --> https://github.com/AlttiRi/twitter-click-and-save/issues <--
  20.  
  21.  
  22.  
  23. // ---------------------------------------------------------------------------------------------------------------------
  24. const sitename = location.hostname.replace(".com", ""); // "twitter" | "x"
  25. // ---------------------------------------------------------------------------------------------------------------------
  26. // --- "Imports" --- //
  27. const {StorageNames, StorageNamesOld} = getStorageNames();
  28.  
  29. const {verbose, debugPopup} = getDebugSettings(); // --- For debug --- //
  30.  
  31.  
  32. const {
  33. sleep, fetchResource, downloadBlob,
  34. addCSS,
  35. getCookie,
  36. throttle,
  37. xpath, xpathAll,
  38. responseProgressProxy,
  39. dateToDayDateString,
  40. toLineJSON,
  41. isFirefox,
  42. getBrowserName,
  43. removeSearchParams,
  44. } = getUtils({verbose});
  45.  
  46. const LS = hoistLS({verbose});
  47.  
  48. const API = hoistAPI();
  49. const Tweet = hoistTweet();
  50. const Features = hoistFeatures();
  51. const I18N = getLanguageConstants();
  52.  
  53.  
  54.  
  55. // ---------------------------------------------------------------------------------------------------------------------
  56.  
  57. function getStorageNames() {
  58. // New LocalStorage key names 2023.07.05
  59. const StorageNames = {
  60. settings: "ujs-twitter-click-n-save-settings",
  61. settingsImageHistoryBy: "ujs-twitter-click-n-save-settings-image-history-by",
  62. downloadedImageNames: "ujs-twitter-click-n-save-downloaded-image-names",
  63. downloadedImageTweetIds: "ujs-twitter-click-n-save-downloaded-image-tweet-ids",
  64. downloadedVideoTweetIds: "ujs-twitter-click-n-save-downloaded-video-tweet-ids",
  65.  
  66. migrated: "ujs-twitter-click-n-save-migrated", // Currently unused
  67. browserName: "ujs-twitter-click-n-save-browser-name", // Hidden settings
  68. verbose: "ujs-twitter-click-n-save-verbose", // Hidden settings for debug
  69. debugPopup: "ujs-twitter-click-n-save-debug-popup", // Hidden settings for debug
  70. };
  71. const StorageNamesOld = {
  72. settings: "ujs-click-n-save-settings",
  73. settingsImageHistoryBy: "ujs-images-history-by",
  74. downloadedImageNames: "ujs-twitter-downloaded-images-names",
  75. downloadedImageTweetIds: "ujs-twitter-downloaded-image-tweet-ids",
  76. downloadedVideoTweetIds: "ujs-twitter-downloaded-video-tweet-ids",
  77. };
  78. return {StorageNames, StorageNamesOld};
  79. }
  80.  
  81. function getDebugSettings() {
  82. let verbose = false;
  83. let debugPopup = false;
  84. try {
  85. verbose = Boolean(JSON.parse(localStorage.getItem(StorageNames.verbose)));
  86. } catch (err) {}
  87. try {
  88. debugPopup = Boolean(JSON.parse(localStorage.getItem(StorageNames.debugPopup)));
  89. } catch (err) {}
  90.  
  91. return {verbose, debugPopup};
  92. }
  93.  
  94. const historyHelper = getHistoryHelper();
  95. historyHelper.migrateLocalStore();
  96.  
  97. // ---------------------------------------------------------------------------------------------------------------------
  98.  
  99.  
  100. // ---------------------------------------------------------------------------------------------------------------------
  101.  
  102. if (globalThis.GM_registerMenuCommand /* undefined in Firefox with VM */ || typeof GM_registerMenuCommand === "function") {
  103. GM_registerMenuCommand("Show settings", showSettings);
  104. }
  105.  
  106. const settings = loadSettings();
  107.  
  108. if (verbose) {
  109. console.log("[ujs][settings]", settings);
  110. }
  111. if (debugPopup) {
  112. showSettings();
  113. }
  114.  
  115. // ---------------------------------------------------------------------------------------------------------------------
  116.  
  117. const fetch = ujs_getGlobalFetch({verbose, strictTrackingProtectionFix: settings.strictTrackingProtectionFix});
  118.  
  119. function ujs_getGlobalFetch({verbose, strictTrackingProtectionFix} = {}) {
  120. const useFirefoxStrictTrackingProtectionFix = strictTrackingProtectionFix === undefined ? true : strictTrackingProtectionFix; // Let's use by default
  121. const useFirefoxFix = useFirefoxStrictTrackingProtectionFix && typeof wrappedJSObject === "object" && typeof wrappedJSObject.fetch === "function";
  122. // --- [VM/GM + Firefox ~90+ + Enabled "Strict Tracking Protection"] fix --- //
  123. function fixedFirefoxFetch(resource, init = {}) {
  124. verbose && console.log("[ujs][wrappedJSObject.fetch]", resource, init);
  125. if (init.headers instanceof Headers) {
  126. // Since `Headers` are not allowed for structured cloning.
  127. init.headers = Object.fromEntries(init.headers.entries());
  128. }
  129. return wrappedJSObject.fetch(cloneInto(resource, document), cloneInto(init, document));
  130. }
  131. return useFirefoxFix ? fixedFirefoxFetch : globalThis.fetch;
  132. }
  133.  
  134. // ---------------------------------------------------------------------------------------------------------------------
  135. // --- Features to execute --- //
  136.  
  137. const doNotPlayVideosAutomatically = false; // Hidden settings
  138.  
  139. function execFeaturesOnce() {
  140. settings.goFromMobileToMainSite && Features.goFromMobileToMainSite();
  141. settings.addRequiredCSS && Features.addRequiredCSS();
  142. settings.hideSignUpBottomBarAndMessages && Features.hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically);
  143. settings.hideTrends && Features.hideTrends();
  144. settings.highlightVisitedLinks && Features.highlightVisitedLinks();
  145. settings.hideLoginPopup && Features.hideLoginPopup();
  146. }
  147. function execFeaturesImmediately() {
  148. settings.expandSpoilers && Features.expandSpoilers();
  149. }
  150. function execFeatures() {
  151. settings.imagesHandler && Features.imagesHandler();
  152. settings.videoHandler && Features.videoHandler();
  153. settings.expandSpoilers && Features.expandSpoilers();
  154. settings.hideSignUpSection && Features.hideSignUpSection();
  155. settings.directLinks && Features.directLinks();
  156. settings.handleTitle && Features.handleTitle();
  157. }
  158.  
  159. // ---------------------------------------------------------------------------------------------------------------------
  160.  
  161. // ---------------------------------------------------------------------------------------------------------------------
  162. // --- Script runner --- //
  163.  
  164. (function starter(feats) {
  165. const {once, onChangeImmediate, onChange} = feats;
  166.  
  167. once();
  168. onChangeImmediate();
  169. const onChangeThrottled = throttle(onChange, 250);
  170. onChangeThrottled();
  171.  
  172. const targetNode = document.querySelector("body");
  173. const observerOptions = {
  174. subtree: true,
  175. childList: true,
  176. };
  177. const observer = new MutationObserver(callback);
  178. observer.observe(targetNode, observerOptions);
  179.  
  180. function callback(mutationList, _observer) {
  181. verbose && console.log("[ujs][mutationList]", mutationList);
  182. onChangeImmediate();
  183. onChangeThrottled();
  184. }
  185. })({
  186. once: execFeaturesOnce,
  187. onChangeImmediate: execFeaturesImmediately,
  188. onChange: execFeatures
  189. });
  190.  
  191. // ---------------------------------------------------------------------------------------------------------------------
  192. // ---------------------------------------------------------------------------------------------------------------------
  193.  
  194. function loadSettings() {
  195. const defaultSettings = {
  196. hideTrends: true,
  197. hideSignUpSection: false,
  198. hideSignUpBottomBarAndMessages: false,
  199. doNotPlayVideosAutomatically: false,
  200. goFromMobileToMainSite: false,
  201.  
  202. highlightVisitedLinks: true,
  203. highlightOnlySpecialVisitedLinks: true,
  204. expandSpoilers: true,
  205.  
  206. directLinks: true,
  207. handleTitle: true,
  208.  
  209. imagesHandler: true,
  210. videoHandler: true,
  211. addRequiredCSS: true,
  212.  
  213. hideLoginPopup: false,
  214. addBorder: false,
  215.  
  216. downloadProgress: true,
  217. strictTrackingProtectionFix: false,
  218. };
  219.  
  220. let savedSettings;
  221. try {
  222. savedSettings = JSON.parse(localStorage.getItem(StorageNames.settings)) || {};
  223. } catch (err) {
  224. console.error("[ujs][parse-settings]", err);
  225. localStorage.removeItem(StorageNames.settings);
  226. savedSettings = {};
  227. }
  228. savedSettings = Object.assign(defaultSettings, savedSettings);
  229. return savedSettings;
  230. }
  231. function showSettings() {
  232. closeSetting();
  233. if (window.scrollY > 0) {
  234. document.querySelector("html").classList.add("ujs-scroll-initial");
  235. document.body.classList.add("ujs-scrollbar-width-margin-right");
  236. }
  237. document.body.classList.add("ujs-no-scroll");
  238.  
  239. const modalWrapperStyle = `
  240. color-scheme: light;
  241. width: 100%;
  242. height: 100%;
  243. position: fixed;
  244. display: flex;
  245. justify-content: center;
  246. align-items: center;
  247. z-index: 99999;
  248. backdrop-filter: blur(4px);
  249. background-color: rgba(255, 255, 255, 0.5);
  250. `;
  251. const modalSettingsStyle = `
  252. background-color: white;
  253. min-width: 320px;
  254. min-height: 320px;
  255. border: 1px solid darkgray;
  256. padding: 8px;
  257. box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  258. `;
  259. const s = settings;
  260. const downloadProgressFFTitle = `Disable the download progress if you use Firefox with "Enhanced Tracking Protection" set to "Strict" and ViolentMonkey, or GreaseMonkey extension`;
  261. 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.`;
  262. document.body.insertAdjacentHTML("afterbegin", `
  263. <div class="ujs-modal-wrapper" style="${modalWrapperStyle}">
  264. <div class="ujs-modal-settings" style="${modalSettingsStyle}">
  265. <fieldset>
  266. <legend>Optional</legend>
  267. <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>
  268. <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>
  269. <label><input type="checkbox" ${s.hideTrends ? "checked" : ""} name="hideTrends">Hide <b>Trends</b> (in the right column)*<br/></label>
  270. <label hidden><input type="checkbox" ${s.doNotPlayVideosAutomatically ? "checked" : ""} name="doNotPlayVideosAutomatically">Do <i>Not</i> Play Videos Automatically</b><br/></label>
  271. <label hidden><input type="checkbox" ${s.goFromMobileToMainSite ? "checked" : ""} name="goFromMobileToMainSite">Redirect from Mobile version (beta)<br/></label>
  272. </fieldset>
  273. <fieldset>
  274. <legend>Recommended</legend>
  275. <label><input type="checkbox" ${s.highlightVisitedLinks ? "checked" : ""} name="highlightVisitedLinks">Highlight Visited Links<br/></label>
  276. <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>
  277.  
  278. <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>
  279. </fieldset>
  280. <fieldset>
  281. <legend>Highly Recommended</legend>
  282. <label><input type="checkbox" ${s.directLinks ? "checked" : ""} name="directLinks">Direct Links</label><br/>
  283. <label><input type="checkbox" ${s.handleTitle ? "checked" : ""} name="handleTitle">Enchance Title*<br/></label>
  284. </fieldset>
  285. <fieldset ${isFirefox ? '': 'style="display: none"'}>
  286. <legend>Firefox only</legend>
  287. <label title='${downloadProgressFFTitle}'><input type="radio" ${s.downloadProgress ? "checked" : ""} name="firefoxDownloadProgress" value="downloadProgress">Download Progress<br/></label>
  288. <label title='${strictTrackingProtectionFixFFTitle}'><input type="radio" ${s.strictTrackingProtectionFix ? "checked" : ""} name="firefoxDownloadProgress" value="strictTrackingProtectionFix">Strict Tracking Protection Fix<br/></label>
  289. </fieldset>
  290. <fieldset>
  291. <legend>Main</legend>
  292. <label><input type="checkbox" ${s.imagesHandler ? "checked" : ""} name="imagesHandler">Image Download Button<br/></label>
  293. <label><input type="checkbox" ${s.videoHandler ? "checked" : ""} name="videoHandler">Video Download Button<br/></label>
  294. <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 -->
  295. </fieldset>
  296. <fieldset>
  297. <legend title="Outdated due to Twitter's updates, or impossible to reimplement">Outdated</legend>
  298. <strike>
  299.  
  300. <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>
  301. <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>
  302.  
  303. </strike>
  304. </fieldset>
  305. <hr>
  306. <div style="display: flex; justify-content: space-around;">
  307. <div>
  308. History:
  309. <button class="ujs-reload-export-button" style="padding: 5px" >Export</button>
  310. <button class="ujs-reload-import-button" style="padding: 5px" >Import</button>
  311. <button class="ujs-reload-merge-button" style="padding: 5px" >Merge</button>
  312. </div>
  313. <div>
  314. <button class="ujs-reload-setting-button" style="padding: 5px" title="Reload the web page to apply changes">Reload page</button>
  315. <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>
  316. </div>
  317. </div>
  318. <hr>
  319. <h4 style="margin: 0; padding-left: 8px; color: #444;">Notes:</h4>
  320. <ul style="margin: 2px; padding-left: 16px; color: #444;">
  321. <li><b>Reload the page</b> to apply changes.</li>
  322. <li><b>*</b>-marked settings are language dependent. Currently, the follow languages are supported:<br/> "en", "ru", "es", "zh", "ja".</li>
  323. <li hidden>The extension downloads only from twitter.com, not from <b>mobile</b>.twitter.com</li>
  324. </ul>
  325. </div>
  326. </div>`);
  327.  
  328. async function onDone(button) {
  329. button.classList.remove("ujs-btn-error");
  330. button.classList.add("ujs-btn-done");
  331. await sleep(900);
  332. button.classList.remove("ujs-btn-done");
  333. }
  334. async function onError(button, err) {
  335. button.classList.remove("ujs-btn-done");
  336. button.classList.add("ujs-btn-error");
  337. button.title = err.message;
  338. await sleep(1800);
  339. button.classList.remove("ujs-btn-error");
  340. }
  341.  
  342. const exportButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-export-button");
  343. const importButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-import-button");
  344. const mergeButton = document.querySelector("body > .ujs-modal-wrapper .ujs-reload-merge-button");
  345.  
  346. exportButton.addEventListener("click", (event) => {
  347. const button = event.currentTarget;
  348. historyHelper.exportHistory(() => onDone(button));
  349. });
  350. sleep(50).then(() => {
  351. const infoObj = getStoreInfo();
  352. exportButton.title = Object.entries(infoObj).reduce((acc, [key, value]) => {
  353. acc += `${key}: ${value}\n`;
  354. return acc;
  355. }, "");
  356. });
  357.  
  358. importButton.addEventListener("click", (event) => {
  359. const button = event.currentTarget;
  360. historyHelper.importHistory(
  361. () => onDone(button),
  362. (err) => onError(button, err)
  363. );
  364. });
  365. mergeButton.addEventListener("click", (event) => {
  366. const button = event.currentTarget;
  367. historyHelper.mergeHistory(
  368. () => onDone(button),
  369. (err) => onError(button, err)
  370. );
  371. });
  372.  
  373. document.querySelector("body > .ujs-modal-wrapper .ujs-reload-setting-button").addEventListener("click", () => {
  374. location.reload();
  375. });
  376.  
  377. const checkboxList = document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox], body > .ujs-modal-wrapper input[type=radio]");
  378. checkboxList.forEach(checkbox => {
  379. checkbox.addEventListener("change", saveSetting);
  380. });
  381.  
  382. document.querySelector("body > .ujs-modal-wrapper .ujs-close-setting-button").addEventListener("click", closeSetting);
  383.  
  384. function saveSetting() {
  385. const entries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox]")]
  386. .map(checkbox => [checkbox.name, checkbox.checked]);
  387. const radioEntries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=radio]")]
  388. .map(checkbox => [checkbox.value, checkbox.checked])
  389. const settings = Object.fromEntries([entries, radioEntries].flat());
  390. // verbose && console.log("[ujs][save-settings]", settings);
  391. localStorage.setItem(StorageNames.settings, JSON.stringify(settings));
  392. }
  393.  
  394. function closeSetting() {
  395. document.body.classList.remove("ujs-no-scroll");
  396. document.body.classList.remove("ujs-scrollbar-width-margin-right");
  397. document.querySelector("html").classList.remove("ujs-scroll-initial");
  398. document.querySelector("body > .ujs-modal-wrapper")?.remove();
  399. }
  400.  
  401.  
  402. }
  403.  
  404. // ---------------------------------------------------------------------------------------------------------------------
  405. // ---------------------------------------------------------------------------------------------------------------------
  406. // --- Twitter Specific code --- //
  407.  
  408. const downloadedImages = new LS(StorageNames.downloadedImageNames);
  409. const downloadedImageTweetIds = new LS(StorageNames.downloadedImageTweetIds);
  410. const downloadedVideoTweetIds = new LS(StorageNames.downloadedVideoTweetIds);
  411.  
  412. // --- That to use for the image history --- //
  413. /** @type {"TWEET_ID" | "IMAGE_NAME"} */
  414. const imagesHistoryBy = LS.getItem(StorageNames.settingsImageHistoryBy, "IMAGE_NAME"); // Hidden settings
  415. // With "TWEET_ID" downloading of 1 image of 4 will mark all 4 images as "already downloaded"
  416. // on the next time when the tweet will appear.
  417. // "IMAGE_NAME" will count each image of a tweet, but it will take more data to store.
  418.  
  419.  
  420. // ---------------------------------------------------------------------------------------------------------------------
  421. // --- Twitter.Features --- //
  422. function hoistFeatures() {
  423. class Features {
  424. static createButton({url, downloaded, isVideo, isThumb, isMultiMedia}) {
  425. const btn = document.createElement("div");
  426. btn.innerHTML = `
  427. <div class="ujs-btn-common ujs-btn-background"></div>
  428. <div class="ujs-btn-common ujs-hover"></div>
  429. <div class="ujs-btn-common ujs-shadow"></div>
  430. <div class="ujs-btn-common ujs-progress" style="--progress: 0%"></div>
  431. <div class="ujs-btn-common ujs-btn-error-text"></div>`.slice(1);
  432. btn.classList.add("ujs-btn-download");
  433. if (!downloaded) {
  434. btn.classList.add("ujs-not-downloaded");
  435. } else {
  436. btn.classList.add("ujs-already-downloaded");
  437. }
  438. if (isVideo) {
  439. btn.classList.add("ujs-video");
  440. }
  441. if (url) {
  442. btn.dataset.url = url;
  443. }
  444. if (isThumb) {
  445. btn.dataset.thumb = "true";
  446. }
  447. if (isMultiMedia) {
  448. btn.dataset.isMultiMedia = "true";
  449. }
  450. return btn;
  451. }
  452.  
  453. static _markButtonAsDownloaded(btn) {
  454. btn.classList.remove("ujs-downloading");
  455. btn.classList.remove("ujs-recently-downloaded");
  456. btn.classList.add("ujs-downloaded");
  457. btn.addEventListener("pointerenter", e => {
  458. btn.classList.add("ujs-recently-downloaded");
  459. }, {once: true});
  460. }
  461.  
  462. // Banner/Background
  463. static async _downloadBanner(url, btn) {
  464. const username = location.pathname.slice(1).split("/")[0];
  465.  
  466. btn.classList.add("ujs-downloading");
  467.  
  468. // https://pbs.twimg.com/profile_banners/34743251/1596331248/1500x500
  469. const {
  470. id, seconds, res
  471. } = url.match(/(?<=\/profile_banners\/)(?<id>\d+)\/(?<seconds>\d+)\/(?<res>\d+x\d+)/)?.groups || {};
  472.  
  473. const {blob, lastModifiedDate, extension, name} = await fetchResource(url);
  474.  
  475. Features.verifyBlob(blob, url, btn);
  476.  
  477. const filename = `[twitter][bg] ${username}—${lastModifiedDate}—${id}—${seconds}.${extension}`;
  478. downloadBlob(blob, filename, url);
  479.  
  480. Features._markButtonAsDownloaded(btn);
  481. }
  482.  
  483. static _ImageHistory = class {
  484. static getImageNameFromUrl(url) {
  485. const _url = new URL(url);
  486. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  487. return filename.match(/^[^.]+/)[0]; // remove extension
  488. }
  489. static isDownloaded({id, url}) {
  490. if (imagesHistoryBy === "TWEET_ID") {
  491. return downloadedImageTweetIds.hasItem(id);
  492. } else if (imagesHistoryBy === "IMAGE_NAME") {
  493. const name = Features._ImageHistory.getImageNameFromUrl(url);
  494. return downloadedImages.hasItem(name);
  495. }
  496. }
  497. static async markDownloaded({id, url}) {
  498. if (imagesHistoryBy === "TWEET_ID") {
  499. await downloadedImageTweetIds.pushItem(id);
  500. } else if (imagesHistoryBy === "IMAGE_NAME") {
  501. const name = Features._ImageHistory.getImageNameFromUrl(url);
  502. await downloadedImages.pushItem(name);
  503. }
  504. }
  505. }
  506. static async imagesHandler() {
  507. verbose && console.log("[ujs][imagesHandler]");
  508. const images = document.querySelectorAll(`img:not([data-handled]):not([src$=".svg"])`);
  509. for (const img of images) {
  510. if (img.dataset.handled) {
  511. continue;
  512. }
  513. img.dataset.handled = "true";
  514. if (img.width === 0) {
  515. const imgOnload = new Promise(async (resolve) => {
  516. img.onload = resolve;
  517. });
  518. await Promise.any([imgOnload, sleep(500)]);
  519. await sleep(10); // to get updated img.width
  520. }
  521. if (img.width < 140) {
  522. continue;
  523. }
  524. verbose && console.log("[ujs][imagesHandler]", {img, img_width: img.width});
  525.  
  526. let anchor = img.closest("a");
  527. // if expanded_url (an image is _opened_ "https://twitter.com/UserName/status/1234567890123456789/photo/1" [fake-url])
  528. if (!anchor) {
  529. anchor = img.parentNode;
  530. }
  531.  
  532. const listitemEl = img.closest(`li[role="listitem"]`);
  533. const isThumb = Boolean(listitemEl); // isMediaThumbnail
  534.  
  535. if (isThumb && anchor.querySelector("svg")) {
  536. await Features.multiMediaThumbHandler(img);
  537. continue;
  538. }
  539.  
  540. 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"
  541. || img.src.includes("tweet_video_thumb") /* GIF thumb */;
  542. if (isMobileVideo) {
  543. await Features.mobileVideoHandler(img, isThumb); // thumbVideoHandler
  544. continue;
  545. }
  546.  
  547. const btn = Features.createButton({url: img.src, isThumb});
  548. btn.addEventListener("click", Features._imageClickHandler);
  549. anchor.append(btn);
  550.  
  551. const downloaded = Features._ImageHistory.isDownloaded({
  552. id: Tweet.of(btn).id,
  553. url: btn.dataset.url
  554. });
  555. if (downloaded) {
  556. btn.classList.add("ujs-already-downloaded");
  557. }
  558. }
  559. }
  560. static async _imageClickHandler(event) {
  561. event.preventDefault();
  562. event.stopImmediatePropagation();
  563.  
  564. const btn = event.currentTarget;
  565. let url = btn.dataset.url;
  566.  
  567. const isBanner = url.includes("/profile_banners/");
  568. if (isBanner) {
  569. return Features._downloadBanner(url, btn);
  570. }
  571.  
  572. const {id, author} = Tweet.of(btn);
  573. verbose && console.log("[ujs][_imageClickHandler]", {id, author});
  574.  
  575. await Features._downloadPhotoMediaEntry(id, author, url, btn);
  576. Features._markButtonAsDownloaded(btn);
  577. }
  578. static async _downloadPhotoMediaEntry(id, author, url, btn) {
  579. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  580. const btnProgress = btn.querySelector(".ujs-progress");
  581. if (btn.textContent !== "") {
  582. btnErrorTextElem.textContent = "";
  583. }
  584. btn.classList.remove("ujs-error");
  585. btn.classList.add("ujs-downloading");
  586.  
  587. let onProgress = null;
  588. if (settings.downloadProgress) {
  589. onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
  590. }
  591.  
  592. const originals = ["orig", "4096x4096"];
  593. const samples = ["large", "medium", "900x900", "small", "360x360", /*"240x240", "120x120", "tiny"*/];
  594. let isSample = false;
  595. const previewSize = new URL(url).searchParams.get("name");
  596. if (!samples.includes(previewSize)) {
  597. samples.push(previewSize);
  598. }
  599.  
  600. function handleImgUrl(url) {
  601. const urlObj = new URL(url);
  602. if (originals.length) {
  603. urlObj.searchParams.set("name", originals.shift());
  604. } else if (samples.length) {
  605. isSample = true;
  606. urlObj.searchParams.set("name", samples.shift());
  607. } else {
  608. throw new Error("All fallback URLs are failed to download.");
  609. }
  610. if (urlObj.searchParams.get("format") === "webp") {
  611. urlObj.searchParams.set("format", "jpg");
  612. }
  613. url = urlObj.toString();
  614. verbose && console.log("[ujs][handleImgUrl][url]", url);
  615. return url;
  616. }
  617.  
  618. async function safeFetchResource(url) {
  619. while (true) {
  620. url = handleImgUrl(url);
  621. try {
  622. const result = await fetchResource(url, onProgress);
  623. if (result.status === 404) {
  624. const urlObj = new URL(url);
  625. const params = urlObj.searchParams;
  626. if (params.get("name") === "orig" && params.get("format") === "jpg") {
  627. params.set("format", "png");
  628. url = urlObj.toString();
  629. return await fetchResource(url, onProgress);
  630. }
  631. }
  632. return result;
  633. } catch (err) {
  634. if (!originals.length) {
  635. btn.classList.add("ujs-error");
  636. btnErrorTextElem.textContent = "";
  637. // Add ⚠
  638. 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;`;
  639. btn.title = "[warning] Original images are not available.";
  640. }
  641.  
  642. const ffAutoAllocateChunkSizeBug = err.message.includes("autoAllocateChunkSize"); // https://bugzilla.mozilla.org/show_bug.cgi?id=1757836
  643. if (!samples.length || ffAutoAllocateChunkSizeBug) {
  644. btn.classList.add("ujs-error");
  645. btnErrorTextElem.textContent = "";
  646. // Add ❌
  647. 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;`;
  648.  
  649. const ffHint = isFirefox && !settings.strictTrackingProtectionFix && ffAutoAllocateChunkSizeBug ? "\nTry to enable 'Strict Tracking Protection Fix' in the userscript settings." : "";
  650. btn.title = "Failed to download the image." + ffHint;
  651. throw new Error("[error] Fallback URLs are failed.");
  652. }
  653. }
  654. }
  655. }
  656.  
  657. const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url);
  658.  
  659. Features.verifyBlob(blob, url, btn);
  660.  
  661. btnProgress.style.cssText = "--progress: 100%";
  662.  
  663. const sampleText = !isSample ? "" : "[sample]";
  664. const filename = `[twitter]${sampleText} ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
  665. downloadBlob(blob, filename, url);
  666.  
  667. const downloaded = btn.classList.contains("ujs-already-downloaded") || btn.classList.contains("ujs-downloaded");
  668. if (!downloaded && !isSample) {
  669. await Features._ImageHistory.markDownloaded({id, url});
  670. }
  671.  
  672. if (btn.dataset.isMultiMedia && !isSample) { // dirty fix
  673. const isDownloaded = Features._ImageHistory.isDownloaded({id, url});
  674. if (!isDownloaded) {
  675. await Features._ImageHistory.markDownloaded({id, url});
  676. }
  677. }
  678.  
  679. await sleep(40);
  680. btnProgress.style.cssText = "--progress: 0%";
  681. }
  682.  
  683.  
  684. // Quick Dirty Fix // todo refactor
  685. static async mobileVideoHandler(imgElem, isThumb) { // thumbVideoHandler // todo rename?
  686. verbose && console.log("[ujs][mobileVideoHandler][vid]", imgElem);
  687.  
  688. const btn = Features.createButton({isVideo: true, url: imgElem.src, isThumb});
  689. btn.addEventListener("click", Features._videoClickHandler);
  690.  
  691. let anchor = imgElem.closest("a");
  692. if (!anchor) {
  693. anchor = imgElem.parentNode;
  694. }
  695. anchor.append(btn);
  696.  
  697. const tweet = Tweet.of(btn);
  698. const id = tweet.id;
  699. const tweetElem = tweet.elem || btn.closest(`[data-testid="tweet"]`);
  700. let vidNumber = 0;
  701.  
  702. if (tweetElem) {
  703. const map = Features.tweetVidWeakMapMobile;
  704. if (map.has(tweetElem)) {
  705. vidNumber = map.get(tweetElem) + 1;
  706. map.set(tweetElem, vidNumber);
  707. } else {
  708. map.set(tweetElem, vidNumber); // can throw an error for null
  709. }
  710. } // else thumbnail
  711.  
  712. const historyId = vidNumber ? id + "-" + vidNumber : id;
  713.  
  714. const downloaded = downloadedVideoTweetIds.hasItem(historyId);
  715. if (downloaded) {
  716. btn.classList.add("ujs-already-downloaded");
  717. }
  718. }
  719.  
  720.  
  721. static async multiMediaThumbHandler(imgElem) {
  722. verbose && console.log("[ujs][multiMediaThumbHandler]", imgElem);
  723. let isVideo = false;
  724. if (imgElem.src.includes("/ext_tw_video_thumb/") || imgElem.src.includes("/amplify_video_thumb/")) {
  725. isVideo = true;
  726. }
  727.  
  728. const btn = Features.createButton({url: imgElem.src, isVideo, isThumb: true, isMultiMedia: true});
  729. btn.addEventListener("click", Features._multiMediaThumbClickHandler);
  730. let anchor = imgElem.closest("a");
  731. if (!anchor) {
  732. anchor = imgElem.parentNode;
  733. }
  734. anchor.append(btn);
  735.  
  736. let downloaded;
  737. const tweetId = Tweet.of(btn).id;
  738. if (isVideo) {
  739. downloaded = downloadedVideoTweetIds.hasItem(tweetId);
  740. } else {
  741. downloaded = Features._ImageHistory.isDownloaded({
  742. id: tweetId,
  743. url: btn.dataset.url
  744. });
  745. }
  746. if (downloaded) {
  747. btn.classList.add("ujs-already-downloaded");
  748. }
  749. }
  750. static async _multiMediaThumbClickHandler(event) {
  751. event.preventDefault();
  752. event.stopImmediatePropagation();
  753. const btn = event.currentTarget;
  754. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  755. if (btn.textContent !== "") {
  756. btnErrorTextElem.textContent = "";
  757. }
  758. const {id} = Tweet.of(btn);
  759. /** @type {TweetMediaEntry[]} */
  760. let medias;
  761. try {
  762. medias = await API.getTweetMedias(id);
  763. medias = medias.filter(mediaEntry => mediaEntry.tweet_id === id);
  764. } catch (err) {
  765. console.error(err);
  766. btn.classList.add("ujs-error");
  767. btnErrorTextElem.textContent = "Error";
  768. btn.title = "API.getTweetMedias Error";
  769. throw new Error("API.getTweetMedias Error");
  770. }
  771.  
  772. for (const mediaEntry of medias) {
  773. if (mediaEntry.type === "video") {
  774. await Features._downloadVideoMediaEntry(mediaEntry, btn, id);
  775. } else { // "photo"
  776. const {screen_name: author,download_url: url, tweet_id: id} = mediaEntry;
  777. await Features._downloadPhotoMediaEntry(id, author, url, btn);
  778. }
  779. await sleep(50);
  780. }
  781. Features._markButtonAsDownloaded(btn);
  782. }
  783.  
  784. static tweetVidWeakMapMobile = new WeakMap();
  785. static tweetVidWeakMap = new WeakMap();
  786. static async videoHandler() {
  787. const videos = document.querySelectorAll("video:not([data-handled])");
  788. for (const vid of videos) {
  789. if (vid.dataset.handled) {
  790. continue;
  791. }
  792. vid.dataset.handled = "true";
  793. verbose && console.log("[ujs][videoHandler][vid]", vid);
  794.  
  795. const poster = vid.getAttribute("poster");
  796.  
  797. const btn = Features.createButton({isVideo: true, url: poster});
  798. btn.addEventListener("click", Features._videoClickHandler);
  799.  
  800. let elem = vid.closest(`[data-testid="videoComponent"]`).parentNode;
  801. if (elem) {
  802. elem.append(btn);
  803. } else {
  804. elem = vid.parentNode.parentNode.parentNode;
  805. elem.after(btn);
  806. }
  807.  
  808.  
  809. const tweet = Tweet.of(btn);
  810. const id = tweet.id;
  811. const tweetElem = tweet.elem;
  812. let vidNumber = 0;
  813.  
  814. if (tweetElem) {
  815. const map = Features.tweetVidWeakMap;
  816. if (map.has(tweetElem)) {
  817. vidNumber = map.get(tweetElem) + 1;
  818. map.set(tweetElem, vidNumber);
  819. } else {
  820. map.set(tweetElem, vidNumber); // can throw an error for null
  821. }
  822. } else { // expanded_url
  823. await sleep(10);
  824. const match = location.pathname.match(/(?<=\/video\/)\d/);
  825. if (!match) {
  826. verbose && console.log("[ujs][videoHandler] missed match for match");
  827. }
  828. vidNumber = Number(match[0]) - 1;
  829.  
  830. console.warn("[ujs][videoHandler] vidNumber", vidNumber);
  831. // todo: add support for expanded_url video downloading
  832. }
  833.  
  834. const historyId = vidNumber ? id + "-" + vidNumber : id;
  835.  
  836. const downloaded = downloadedVideoTweetIds.hasItem(historyId);
  837. if (downloaded) {
  838. btn.classList.add("ujs-already-downloaded");
  839. }
  840. }
  841. }
  842. static async _videoClickHandler(event) { // todo: parse the URL from HTML (For "Embedded video" (?))
  843. event.preventDefault();
  844. event.stopImmediatePropagation();
  845.  
  846. const btn = event.currentTarget;
  847. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  848. const {id} = Tweet.of(btn);
  849.  
  850. if (btn.textContent !== "") {
  851. btnErrorTextElem.textContent = "";
  852. }
  853. btn.classList.remove("ujs-error");
  854. btn.classList.add("ujs-downloading");
  855.  
  856. let mediaEntry;
  857. try {
  858. const medias = await API.getTweetMedias(id);
  859. const posterUrl = btn.dataset.url; // [note] if `posterUrl` has `searchParams`, it will have no extension at the end of `pathname`.
  860. const posterUrlClear = removeSearchParams(posterUrl);
  861. mediaEntry = medias.find(media => media.preview_url.startsWith(posterUrlClear));
  862. verbose && console.log("[ujs][_videoClickHandler] mediaEntry", mediaEntry);
  863. } catch (err) {
  864. console.error(err);
  865. btn.classList.add("ujs-error");
  866. btnErrorTextElem.textContent = "Error";
  867. btn.title = "API.getVideoInfo Error";
  868. throw new Error("API.getVideoInfo Error");
  869. }
  870. try {
  871. await Features._downloadVideoMediaEntry(mediaEntry, btn, id);
  872. } catch (err) {
  873. console.error(err);
  874. btn.classList.add("ujs-error");
  875. btnErrorTextElem.textContent = "Error";
  876. btn.title = err.message + " Error";
  877. throw err;
  878. }
  879. Features._markButtonAsDownloaded(btn);
  880. }
  881.  
  882. static async _downloadVideoMediaEntry(mediaEntry, btn, id /* of original tweet */) {
  883. if (!mediaEntry) {
  884. throw new Error("No mediaEntry found");
  885. }
  886. const {
  887. screen_name: author,
  888. tweet_id: videoTweetId,
  889. download_url: url,
  890. type_index: vidNumber,
  891. } = mediaEntry;
  892. if (!url) {
  893. throw new Error("No video URL found");
  894. }
  895.  
  896. const btnProgress = btn.querySelector(".ujs-progress");
  897.  
  898. let onProgress = null;
  899. if (settings.downloadProgress) {
  900. onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
  901. }
  902.  
  903. async function safeFetchResource(url, onProgress) {
  904. try {
  905. return await fetchResource(url, onProgress);
  906. } catch (err) {
  907. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  908. const ffAutoAllocateChunkSizeBug = err.message.includes("autoAllocateChunkSize"); // https://bugzilla.mozilla.org/show_bug.cgi?id=1757836
  909. btn.classList.add("ujs-error");
  910. btnErrorTextElem.textContent = "";
  911. // Add ❌
  912. 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;`;
  913.  
  914. const ffHint = isFirefox && !settings.strictTrackingProtectionFix && ffAutoAllocateChunkSizeBug ? "\nTry to enable 'Strict Tracking Protection Fix' in the userscript settings." : "";
  915. btn.title = "Video download failed." + ffHint;
  916. throw new Error("[error] Video download failed.");
  917. }
  918. }
  919.  
  920. const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url, onProgress);
  921.  
  922. btnProgress.style.cssText = "--progress: 100%";
  923.  
  924. Features.verifyBlob(blob, url, btn);
  925.  
  926. const filename = `[twitter] ${author}—${lastModifiedDate}—${videoTweetId}—${name}.${extension}`;
  927. downloadBlob(blob, filename, url);
  928.  
  929. const downloaded = btn.classList.contains("ujs-already-downloaded");
  930. const historyId = vidNumber /* not 0 */ ? videoTweetId + "-" + vidNumber : videoTweetId;
  931. if (!downloaded) {
  932. await downloadedVideoTweetIds.pushItem(historyId);
  933. if (videoTweetId !== id) { // if QRT
  934. const historyId = vidNumber ? id + "-" + vidNumber : id;
  935. await downloadedVideoTweetIds.pushItem(historyId);
  936. }
  937. }
  938.  
  939. if (btn.dataset.isMultiMedia) { // dirty fix
  940. const isDownloaded = downloadedVideoTweetIds.hasItem(historyId);
  941. if (!isDownloaded) {
  942. await downloadedVideoTweetIds.pushItem(historyId);
  943. if (videoTweetId !== id) { // if QRT
  944. const historyId = vidNumber ? id + "-" + vidNumber : id;
  945. await downloadedVideoTweetIds.pushItem(historyId);
  946. }
  947. }
  948. }
  949.  
  950. await sleep(40);
  951. btnProgress.style.cssText = "--progress: 0%";
  952. }
  953.  
  954. static verifyBlob(blob, url, btn) {
  955. if (!blob.size) {
  956. btn.classList.add("ujs-error");
  957. btn.querySelector(".ujs-btn-error-text").textContent = "Error";
  958. btn.title = "Download Error";
  959. throw new Error("Zero size blob: " + url);
  960. }
  961. }
  962.  
  963. static addRequiredCSS() {
  964. const code = getUserScriptCSS();
  965. addCSS(code);
  966. }
  967.  
  968. // it depends on `directLinks()` use only it after `directLinks()` // todo: handleTitleNew
  969. static handleTitle(title) {
  970.  
  971. if (!I18N.QUOTES) { // Unsupported lang, no QUOTES, ON_TWITTER, TWITTER constants
  972. return;
  973. }
  974.  
  975. // Handle only an opened tweet
  976. if (!location.href.match(/(twitter|x)\.com\/[^\/]+\/status\/\d+/)) {
  977. return;
  978. }
  979.  
  980. let titleText = title || document.title;
  981. if (titleText === Features.lastHandledTitle) {
  982. return;
  983. }
  984. Features.originalTitle = titleText;
  985.  
  986. const [OPEN_QUOTE, CLOSE_QUOTE] = I18N.QUOTES;
  987. const urlsToReplace = [
  988. ...titleText.matchAll(new RegExp(`https:\\/\\/t\\.co\\/[^ ${CLOSE_QUOTE}]+`, "g"))
  989. ].map(el => el[0]);
  990. // the last one may be the URL to the tweet // or to an embedded shared URL
  991.  
  992. const map = new Map();
  993. const anchors = document.querySelectorAll(`a[data-redirect^="https://t.co/"]`);
  994. for (const anchor of anchors) {
  995. if (urlsToReplace.includes(anchor.dataset.redirect)) {
  996. map.set(anchor.dataset.redirect, anchor.href);
  997. }
  998. }
  999.  
  1000. const lastUrl = urlsToReplace.slice(-1)[0];
  1001. let lastUrlIsAttachment = false;
  1002. let attachmentDescription = "";
  1003. if (!map.has(lastUrl)) {
  1004. const a = document.querySelector(`a[href="${lastUrl}?amp=1"]`);
  1005. if (a) {
  1006. lastUrlIsAttachment = true;
  1007. attachmentDescription = document.querySelectorAll(`a[href="${lastUrl}?amp=1"]`)[1].innerText;
  1008. attachmentDescription = attachmentDescription.replaceAll("\n", " — ");
  1009. }
  1010. }
  1011.  
  1012. for (const [key, value] of map.entries()) {
  1013. titleText = titleText.replaceAll(key, value + ` (${key})`);
  1014. }
  1015.  
  1016. titleText = titleText.replace(new RegExp(`${I18N.ON_TWITTER}(?= ${OPEN_QUOTE})`), ":");
  1017. titleText = titleText.replace(new RegExp(`(?<=${CLOSE_QUOTE}) \\\/ ${I18N.TWITTER}$`), "");
  1018. if (!lastUrlIsAttachment) {
  1019. const regExp = new RegExp(`(?<short> https:\\/\\/t\\.co\\/.{6,14})${CLOSE_QUOTE}$`);
  1020. titleText = titleText.replace(regExp, (match, p1, p2, offset, string) => `${CLOSE_QUOTE} ${p1}`);
  1021. } else {
  1022. titleText = titleText.replace(lastUrl, `${lastUrl} (${attachmentDescription})`);
  1023. }
  1024. document.title = titleText; // Note: some characters will be removed automatically (`\n`, extra spaces)
  1025. Features.lastHandledTitle = document.title;
  1026. }
  1027. static lastHandledTitle = "";
  1028. static originalTitle = "";
  1029.  
  1030. static profileUrlCache = new Map();
  1031. static async directLinks() {
  1032. verbose && console.log("[ujs][directLinks]");
  1033. const hasHttp = url => Boolean(url.match(/^https?:\/\//));
  1034. const anchors = xpathAll(`.//a[starts-with(@href, "https://t.co/") and @dir="ltr" and child::span and not(@data-handled)]`);
  1035. for (const anchor of anchors) {
  1036. const redirectUrl = new URL(anchor.href);
  1037. const shortUrl = redirectUrl.origin + redirectUrl.pathname; // remove "?amp=1"
  1038.  
  1039. const hrefAttr = anchor.getAttribute("href");
  1040. verbose && console.log("[ujs][directLinks]", {hrefAttr, redirectUrl_href: redirectUrl.href, shortUrl});
  1041.  
  1042. anchor.dataset.redirect = shortUrl;
  1043. anchor.dataset.handled = "true";
  1044. anchor.rel = "nofollow noopener noreferrer";
  1045.  
  1046. if (Features.profileUrlCache.has(shortUrl)) {
  1047. anchor.href = Features.profileUrlCache.get(shortUrl);
  1048. continue;
  1049. }
  1050.  
  1051. const nodes = xpathAll(`.//span[text() != "…"] | ./text()`, anchor);
  1052. let url = nodes.map(node => node.textContent).join("");
  1053.  
  1054. const doubleProtocolPrefix = url.match(/(?<dup>^https?:\/\/)(?=https?:)/)?.groups.dup;
  1055. if (doubleProtocolPrefix) {
  1056. url = url.slice(doubleProtocolPrefix.length);
  1057. const span = anchor.querySelector(`[aria-hidden="true"]`);
  1058. if (hasHttp(span.textContent)) { // Fix Twitter's bug related to text copying
  1059. span.style = "display: none;";
  1060. }
  1061. }
  1062.  
  1063. anchor.href = url;
  1064.  
  1065. if (anchor.dataset?.testid === "UserUrl") {
  1066. const href = anchor.getAttribute("href");
  1067. const profileUrl = hasHttp(href) ? href : "https://" + href;
  1068. anchor.href = profileUrl;
  1069. verbose && console.log("[ujs][directLinks][profileUrl]", profileUrl);
  1070.  
  1071. // Restore if URL's text content is too long
  1072. if (anchor.textContent.endsWith("…")) {
  1073. anchor.href = shortUrl;
  1074.  
  1075. try {
  1076. const author = location.pathname.slice(1).match(/[^\/]+/)[0];
  1077. const expanded_url = await API.getUserInfo(author); // todo: make lazy
  1078. anchor.href = expanded_url;
  1079. Features.profileUrlCache.set(shortUrl, expanded_url);
  1080. } catch (err) {
  1081. verbose && console.error("[ujs]", err);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. if (anchors.length) {
  1087. Features.handleTitle(Features.originalTitle);
  1088. }
  1089. }
  1090.  
  1091. // Do NOT throttle it
  1092. static expandSpoilers() {
  1093. const main = document.querySelector("main[role=main]");
  1094. if (!main) {
  1095. return;
  1096. }
  1097.  
  1098. if (!I18N.YES_VIEW_PROFILE) { // Unsupported lang, no YES_VIEW_PROFILE, SHOW_NUDITY, VIEW constants
  1099. return;
  1100. }
  1101.  
  1102. const a = main.querySelectorAll("[data-testid=primaryColumn] [role=button]");
  1103. if (a) {
  1104. const elems = [...a];
  1105. const button = elems.find(el => el.textContent === I18N.YES_VIEW_PROFILE);
  1106. if (button) {
  1107. button.click();
  1108. }
  1109.  
  1110. // "Content warning: Nudity"
  1111. // "The Tweet author flagged this Tweet as showing sensitive content."
  1112. // "Show"
  1113. const buttonShow = elems.find(el => el.textContent === I18N.SHOW_NUDITY);
  1114. if (buttonShow) {
  1115. // const verifying = a.previousSibling.textContent.includes("Nudity"); // todo?
  1116. // if (verifying) {
  1117. buttonShow.click();
  1118. // }
  1119. }
  1120. }
  1121.  
  1122. // todo: expand spoiler commentary in photo view mode (.../photo/1)
  1123. const b = main.querySelectorAll("article [role=presentation] div[role=button]");
  1124. if (b) {
  1125. const elems = [...b];
  1126. const buttons = elems.filter(el => el.textContent === I18N.VIEW);
  1127. if (buttons.length) {
  1128. buttons.forEach(el => el.click());
  1129. }
  1130. }
  1131. }
  1132.  
  1133. static hideSignUpSection() { // "New to Twitter?"
  1134. if (!I18N.SIGNUP) {// Unsupported lang, no SIGNUP constant
  1135. return;
  1136. }
  1137. const elem = document.querySelector(`section[aria-label="${I18N.SIGNUP}"][role=region]`);
  1138. if (elem) {
  1139. elem.parentNode.classList.add("ujs-hidden");
  1140. }
  1141. }
  1142.  
  1143. // Call it once.
  1144. // "Don’t miss what’s happening" if you are not logged in.
  1145. // It looks that `#layers` is used only for this bar.
  1146. static hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically) {
  1147. if (doNotPlayVideosAutomatically) {
  1148. addCSS(`
  1149. #layers > div:nth-child(1) {
  1150. display: none;
  1151. }
  1152. `);
  1153. } else {
  1154. addCSS(`
  1155. #layers > div:nth-child(1) {
  1156. height: 1px;
  1157. opacity: 0;
  1158. }
  1159. `);
  1160. }
  1161. // "Did someone say … cookies?" // fix invisible bottom bar
  1162. addCSS(`[data-testid="BottomBar"] {
  1163. pointer-events: none;
  1164. }`);
  1165. }
  1166.  
  1167. // "Trends for you"
  1168. static hideTrends() {
  1169. if (!I18N.TRENDS) { // Unsupported lang, no TRENDS constant
  1170. return;
  1171. }
  1172. addCSS(`
  1173. [aria-label="${I18N.TRENDS}"]
  1174. {
  1175. display: none;
  1176. }
  1177. `);
  1178. }
  1179.  
  1180. static highlightVisitedLinks() {
  1181. if (settings.highlightOnlySpecialVisitedLinks) {
  1182. addCSS(`
  1183. a[href^="http"]:visited {
  1184. color: darkorange !important;
  1185. }
  1186. `);
  1187. return;
  1188. }
  1189. addCSS(`
  1190. a:visited {
  1191. color: darkorange !important;
  1192. }
  1193. `);
  1194. }
  1195.  
  1196. // todo split to two methods
  1197. // todo fix it, currently it works questionably
  1198. // not tested with non eng languages
  1199. static footerHandled = false;
  1200. static hideAndMoveFooter() { // "Terms of Service Privacy Policy Cookie Policy"
  1201. let footer = document.querySelector(`main[role=main] nav[aria-label=${I18N.FOOTER}][role=navigation]`);
  1202. const nav = document.querySelector("nav[aria-label=Primary][role=navigation]"); // I18N."Primary" [?]
  1203.  
  1204. if (footer) {
  1205. footer = footer.parentNode;
  1206. const separatorLine = footer.previousSibling;
  1207.  
  1208. if (Features.footerHandled) {
  1209. footer.remove();
  1210. separatorLine.remove();
  1211. return;
  1212. }
  1213.  
  1214. nav.append(separatorLine);
  1215. nav.append(footer);
  1216. footer.classList.add("ujs-show-on-hover");
  1217. separatorLine.classList.add("ujs-show-on-hover");
  1218.  
  1219. Features.footerHandled = true;
  1220. }
  1221. }
  1222.  
  1223. static hideLoginPopup() { // When you are not logged in
  1224. const targetNode = document.querySelector("html");
  1225. const observerOptions = {
  1226. attributes: true,
  1227. };
  1228. const observer = new MutationObserver(callback);
  1229. observer.observe(targetNode, observerOptions);
  1230.  
  1231. function callback(mutationList, _observer) {
  1232. const html = document.querySelector("html");
  1233. verbose && console.log("[ujs][hideLoginPopup][mutationList]", mutationList);
  1234. // overflow-y: scroll; overscroll-behavior-y: none; font-size: 15px; // default
  1235. // overflow: hidden; overscroll-behavior-y: none; font-size: 15px; margin-right: 15px; // popup
  1236. if (html.style["overflow"] === "hidden") {
  1237. html.style["overflow"] = "";
  1238. html.style["overflow-y"] = "scroll";
  1239. html.style["margin-right"] = "";
  1240. }
  1241. const popup = document.querySelector(`#layers div[data-testid="sheetDialog"]`);
  1242. if (popup) {
  1243. popup.closest(`div[role="dialog"]`).remove();
  1244. verbose && (document.title = "⚒" + document.title);
  1245. // observer.disconnect();
  1246. }
  1247. }
  1248. }
  1249.  
  1250. static goFromMobileToMainSite() { // uncompleted
  1251. if (location.href.startsWith("https://mobile.twitter.com/")) {
  1252. location.href = location.href.replace("https://mobile.twitter.com/", "https://twitter.com/");
  1253. }
  1254. // TODO: add #redirected, remove by timer // to prevent a potential infinity loop
  1255. }
  1256. }
  1257.  
  1258. return Features;
  1259. }
  1260.  
  1261. function getStoreInfo() {
  1262. const resultObj = {
  1263. total: 0
  1264. };
  1265. for (const [name, lsKey] of Object.entries(StorageNames)) {
  1266. const valueStr = localStorage.getItem(lsKey);
  1267. if (valueStr) {
  1268. try {
  1269. const value = JSON.parse(valueStr);
  1270. if (Array.isArray(value)) {
  1271. const size = new Set(value).size;
  1272. resultObj[name] = size;
  1273. resultObj.total += size;
  1274. }
  1275. } catch (err) {
  1276. // ...
  1277. }
  1278. }
  1279. }
  1280. return resultObj;
  1281. }
  1282.  
  1283. // --- Twitter.RequiredCSS --- //
  1284. function getUserScriptCSS() {
  1285. const labelText = I18N.IMAGE || "Image";
  1286.  
  1287. // By default, the scroll is showed all time, since <html style="overflow-y: scroll;>,
  1288. // so it works — no need to use `getScrollbarWidth` function from SO (13382516).
  1289. const scrollbarWidth = window.innerWidth - document.body.offsetWidth;
  1290.  
  1291. const css = `
  1292. .ujs-modal-wrapper .ujs-modal-settings {
  1293. color: black;
  1294. }
  1295. .ujs-hidden {
  1296. display: none;
  1297. }
  1298. .ujs-no-scroll {
  1299. overflow-y: hidden;
  1300. }
  1301. .ujs-scroll-initial {
  1302. overflow-y: initial!important;
  1303. }
  1304. .ujs-scrollbar-width-margin-right {
  1305. margin-right: ${scrollbarWidth}px;
  1306. }
  1307.  
  1308. .ujs-show-on-hover:hover {
  1309. opacity: 1;
  1310. transition: opacity 1s ease-out 0.1s;
  1311. }
  1312. .ujs-show-on-hover {
  1313. opacity: 0;
  1314. transition: opacity 0.5s ease-out;
  1315. }
  1316.  
  1317. :root {
  1318. --ujs-shadow-1: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  1319. --ujs-shadow-2: linear-gradient(to top, rgba(0,0,0,0.25), rgba(0,0,0,0.05));
  1320. --ujs-shadow-3: linear-gradient(to top, rgba(0,0,0,0.45), rgba(0,0,0,0.15));
  1321. --ujs-shadow-4: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.25));
  1322. --ujs-red: #e0245e;
  1323. --ujs-blue: #1da1f2;
  1324. --ujs-green: #4caf50;
  1325. --ujs-gray: #c2cbd0;
  1326. --ujs-error: white;
  1327. }
  1328.  
  1329. .ujs-progress {
  1330. background-image: linear-gradient(to right, var(--ujs-green) var(--progress), transparent 0%);
  1331. }
  1332.  
  1333. .ujs-shadow {
  1334. background-image: var(--ujs-shadow-1);
  1335. }
  1336. .ujs-btn-download:hover .ujs-hover {
  1337. background-image: var(--ujs-shadow-2);
  1338. }
  1339. .ujs-btn-download.ujs-downloading .ujs-shadow {
  1340. background-image: var(--ujs-shadow-3);
  1341. }
  1342. .ujs-btn-download:active .ujs-shadow {
  1343. background-image: var(--ujs-shadow-4);
  1344. }
  1345.  
  1346. .ujs-btn-download.ujs-downloaded.ujs-recently-downloaded {
  1347. opacity: 0;
  1348. }
  1349.  
  1350. li[role="listitem"]:hover .ujs-btn-download {
  1351. opacity: 1;
  1352. }
  1353. article[role=article]:hover .ujs-btn-download {
  1354. opacity: 1;
  1355. }
  1356. div[aria-label="${labelText}"]:hover .ujs-btn-download {
  1357. opacity: 1;
  1358. }
  1359. .ujs-btn-download.ujs-downloaded {
  1360. opacity: 1;
  1361. }
  1362. .ujs-btn-download.ujs-downloading {
  1363. opacity: 1;
  1364. }
  1365. [data-testid="videoComponent"]:hover + .ujs-btn-download {
  1366. opacity: 1;
  1367. }
  1368. [data-testid="videoComponent"] + .ujs-btn-download:hover {
  1369. opacity: 1;
  1370. }
  1371.  
  1372. .ujs-btn-download {
  1373. cursor: pointer;
  1374. top: 0.5em;
  1375. left: 0.5em;
  1376. position: absolute;
  1377. opacity: 0;
  1378. }
  1379. .ujs-btn-common {
  1380. width: 33px;
  1381. height: 33px;
  1382. border-radius: 0.3em;
  1383. top: 0;
  1384. position: absolute;
  1385. border: 1px solid transparent;
  1386. border-color: var(--ujs-gray);
  1387. ${settings.addBorder ? "border: 2px solid white;" : "border-color: var(--ujs-gray);"}
  1388. }
  1389. .ujs-not-downloaded .ujs-btn-background {
  1390. background: var(--ujs-red);
  1391. }
  1392.  
  1393. .ujs-already-downloaded .ujs-btn-background {
  1394. background: var(--ujs-blue);
  1395. }
  1396.  
  1397. .ujs-btn-done {
  1398. box-shadow: 0 0 6px var(--ujs-green);
  1399. }
  1400. .ujs-btn-error {
  1401. box-shadow: 0 0 6px var(--ujs-red);
  1402. }
  1403.  
  1404. .ujs-downloaded .ujs-btn-background {
  1405. background: var(--ujs-green);
  1406. }
  1407.  
  1408. .ujs-error .ujs-btn-background {
  1409. background: var(--ujs-error);
  1410. }
  1411.  
  1412. .ujs-btn-error-text {
  1413. display: flex;
  1414. align-items: center;
  1415. justify-content: center;
  1416. color: black;
  1417. font-size: 100%;
  1418. }`;
  1419. return css.slice(1);
  1420. }
  1421.  
  1422. /*
  1423. Features depend on:
  1424.  
  1425. addRequiredCSS: IMAGE
  1426.  
  1427. expandSpoilers: YES_VIEW_PROFILE, SHOW_NUDITY, VIEW
  1428. handleTitle: QUOTES, ON_TWITTER, TWITTER
  1429. hideSignUpSection: SIGNUP
  1430. hideTrends: TRENDS
  1431.  
  1432. [unused]
  1433. hideAndMoveFooter: FOOTER
  1434. */
  1435.  
  1436. // --- Twitter.LangConstants --- //
  1437. function getLanguageConstants() { // todo: "de", "fr"
  1438. const defaultQuotes = [`"`, `"`];
  1439.  
  1440. const SUPPORTED_LANGUAGES = ["en", "ru", "es", "zh", "ja", ];
  1441.  
  1442. // texts
  1443. const VIEW = ["View", "Посмотреть", "Ver", "查看", "表示", ];
  1444. const YES_VIEW_PROFILE = ["Yes, view profile", "Да, посмотреть профиль", "Sí, ver perfil", "是,查看个人资料", "プロフィールを表示する", ];
  1445. const SHOW_NUDITY = ["Show", "Показать", "Mostrar", "显示", "表示", ];
  1446.  
  1447. // aria-label texts
  1448. const IMAGE = ["Image", "Изображение", "Imagen", "图像", "画像", ];
  1449. const SIGNUP = ["Sign up", "Зарегистрироваться", "Regístrate", "注册", "アカウント作成", ];
  1450. const TRENDS = ["Timeline: Trending now", "Лента: Актуальные темы", "Cronología: Tendencias del momento", "时间线:当前趋势", "タイムライン: トレンド", ];
  1451. const FOOTER = ["Footer", "Нижний колонтитул", "Pie de página", "页脚", "フッター", ];
  1452.  
  1453. // document.title "{AUTHOR}{ON_TWITTER} {QUOTES[0]}{TEXT}{QUOTES[1]} / {TWITTER}"
  1454. const QUOTES = [defaultQuotes, [`«`, `»`], defaultQuotes, defaultQuotes, [`「`, `」`], ];
  1455. const ON_TWITTER = [" on X:", " в X:", " en X:", " 在 X:", "さんはXを使っています", ];
  1456. const TWITTER = ["X", "X", "X", "X", "X", ];
  1457.  
  1458. const lang = document.querySelector("html").getAttribute("lang");
  1459. const langIndex = SUPPORTED_LANGUAGES.indexOf(lang);
  1460.  
  1461. return {
  1462. SUPPORTED_LANGUAGES,
  1463. VIEW: VIEW[langIndex],
  1464. YES_VIEW_PROFILE: YES_VIEW_PROFILE[langIndex],
  1465. SHOW_NUDITY: SHOW_NUDITY[langIndex],
  1466. IMAGE: IMAGE[langIndex],
  1467. SIGNUP: SIGNUP[langIndex],
  1468. TRENDS: TRENDS[langIndex],
  1469. FOOTER: FOOTER[langIndex],
  1470. QUOTES: QUOTES[langIndex],
  1471. ON_TWITTER: ON_TWITTER[langIndex],
  1472. TWITTER: TWITTER[langIndex],
  1473. }
  1474. }
  1475.  
  1476. // --- Twitter.Tweet --- //
  1477. function hoistTweet() {
  1478. class Tweet {
  1479. constructor({elem, url}) {
  1480. if (url) {
  1481. this.elem = null;
  1482. this.url = url;
  1483. } else {
  1484. this.elem = elem;
  1485. this.url = Tweet.getUrl(elem);
  1486. }
  1487. }
  1488.  
  1489. static of(innerElem) {
  1490. // Workaround for media from a quoted tweet
  1491. const url = innerElem.closest(`a[href^="/"]`)?.href;
  1492. if (url && url.includes("/status/")) {
  1493. return new Tweet({url});
  1494. }
  1495.  
  1496. const elem = innerElem.closest(`[data-testid="tweet"]`);
  1497. if (!elem) { // opened image
  1498. verbose && console.log("[ujs][Tweet.of]", "No-tweet elem");
  1499. }
  1500. return new Tweet({elem});
  1501. }
  1502.  
  1503. static getUrl(elem) {
  1504. if (!elem) {
  1505. verbose && console.log("[ujs][Tweet.getUrl]", "Opened full screen image");
  1506. return location.href;
  1507. }
  1508. const quotedTweetAnchorEl = [...elem.querySelectorAll("a")].find(el => {
  1509. return el.childNodes[0]?.nodeName === "TIME";
  1510. });
  1511. if (quotedTweetAnchorEl) {
  1512. verbose && console.log("[ujs][Tweet.getUrl]", "Quoted/Re Tweet");
  1513. return quotedTweetAnchorEl.href;
  1514. }
  1515. verbose && console.log("[ujs][Tweet.getUrl]", "Unreachable"); // Is it used?
  1516. return location.href;
  1517. }
  1518.  
  1519. get author() {
  1520. return this.url.match(/(?<=(twitter|x)\.com\/).+?(?=\/)/)?.[0];
  1521. }
  1522.  
  1523. get id() {
  1524. return this.url.match(/(?<=\/status\/)\d+/)?.[0];
  1525. }
  1526. }
  1527.  
  1528. return Tweet;
  1529. }
  1530.  
  1531. // --- Twitter.API --- //
  1532. function hoistAPI() {
  1533. class API {
  1534. static guestToken = getCookie("gt");
  1535. static csrfToken = getCookie("ct0"); // todo: lazy — not available at the first run
  1536. // Guest/Suspended account Bearer token
  1537. static guestAuthorization = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
  1538.  
  1539. // Seems to be outdated at 2022.05
  1540. static async _requestBearerToken() {
  1541. const scriptSrc = [...document.querySelectorAll("script")]
  1542. .find(el => el.src.match(/https:\/\/abs\.twimg\.com\/responsive-web\/client-web\/main[\w.]*\.js/)).src;
  1543.  
  1544. let text;
  1545. try {
  1546. text = await (await fetch(scriptSrc)).text();
  1547. } catch (err) {
  1548. /* verbose && */ console.error("[ujs][_requestBearerToken][scriptSrc]", scriptSrc);
  1549. /* verbose && */ console.error("[ujs][_requestBearerToken]", err);
  1550. throw err;
  1551. }
  1552.  
  1553. const authorizationKey = text.match(/(?<=")AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D.+?(?=")/)[0];
  1554. const authorization = `Bearer ${authorizationKey}`;
  1555.  
  1556. return authorization;
  1557. }
  1558.  
  1559. static async getAuthorization() {
  1560. if (!API.authorization) {
  1561. API.authorization = await API._requestBearerToken();
  1562. }
  1563. return API.authorization;
  1564. }
  1565.  
  1566. static requestCache = new Map();
  1567. static vacuumCache() {
  1568. if (API.requestCache.size > 16) {
  1569. API.requestCache.delete(API.requestCache.keys().next().value);
  1570. }
  1571. }
  1572.  
  1573. static async apiRequest(url) {
  1574. const _url = url.toString();
  1575. verbose && console.log("[ujs][apiRequest]", _url);
  1576.  
  1577. if (API.requestCache.has(_url)) {
  1578. verbose && console.log("[ujs][apiRequest] Use cached API request", _url);
  1579. return API.requestCache.get(_url);
  1580. }
  1581.  
  1582. // Hm... it is always the same. Even for a logged user.
  1583. // const authorization = API.guestToken ? API.guestAuthorization : await API.getAuthorization();
  1584. const authorization = API.guestAuthorization;
  1585.  
  1586. // for debug
  1587. verbose && sessionStorage.setItem("guestAuthorization", API.guestAuthorization);
  1588. verbose && sessionStorage.setItem("authorization", API.authorization);
  1589. verbose && sessionStorage.setItem("x-csrf-token", API.csrfToken);
  1590. verbose && sessionStorage.setItem("x-guest-token", API.guestToken);
  1591.  
  1592. const headers = new Headers({
  1593. authorization,
  1594. "x-csrf-token": API.csrfToken,
  1595. "x-twitter-client-language": "en",
  1596. "x-twitter-active-user": "yes",
  1597. // "x-client-transaction-id": "", // todo?
  1598. "content-type": "application/json",
  1599. });
  1600. if (API.guestToken) {
  1601. headers.append("x-guest-token", API.guestToken);
  1602. } else { // may be skipped
  1603. headers.append("x-twitter-auth-type", "OAuth2Session");
  1604. }
  1605.  
  1606. let json;
  1607. try {
  1608. const response = await fetch(_url, {headers});
  1609. json = await response.json();
  1610. if (response.ok) {
  1611. verbose && console.log("[ujs][apiRequest]", "Cache API request", _url);
  1612. API.vacuumCache();
  1613. API.requestCache.set(_url, json);
  1614. }
  1615. } catch (err) {
  1616. /* verbose && */ console.error("[ujs][apiRequest]", _url);
  1617. /* verbose && */ console.error("[ujs][apiRequest]", err);
  1618. throw err;
  1619. }
  1620.  
  1621. verbose && console.log("[ujs][apiRequest][json]", JSON.stringify(json, null, " "));
  1622. // 429 - [{code: 88, message: "Rate limit exceeded"}] — for suspended accounts
  1623.  
  1624. return json;
  1625. }
  1626.  
  1627. /** return {tweetResult, tweetLegacy, tweetUser} */
  1628. static parseTweetJsonFrom_TweetDetail(json, tweetId) {
  1629. const instruction = json.data.threaded_conversation_with_injections_v2.instructions.find(ins => ins.type === "TimelineAddEntries");
  1630. const tweetEntry = instruction.entries.find(ins => ins.entryId === "tweet-" + tweetId);
  1631. let tweetResult = tweetEntry.content.itemContent.tweet_results.result; // {"__typename": "Tweet"} // or {"__typename": "TweetWithVisibilityResults", tweet: {...}} (1641596499351212033)
  1632. if (tweetResult.tweet) {
  1633. tweetResult = tweetResult.tweet;
  1634. }
  1635. verbose && console.log("[ujs][parseTweetJsonFrom_TweetDetail] tweetResult", tweetResult, JSON.stringify(tweetResult));
  1636. const tweetUser = tweetResult.core.user_results.result; // {"__typename": "User"}
  1637. const tweetLegacy = tweetResult.legacy;
  1638. verbose && console.log("[ujs][parseTweetJsonFrom_TweetDetail] tweetLegacy", tweetLegacy, JSON.stringify(tweetLegacy));
  1639. verbose && console.log("[ujs][parseTweetJsonFrom_TweetDetail] tweetUser", tweetUser, JSON.stringify(tweetUser));
  1640. return {tweetResult, tweetLegacy, tweetUser};
  1641. }
  1642.  
  1643. /** return {tweetResult, tweetLegacy, tweetUser} */
  1644. static parseTweetJsonFrom_TweetResultByRestId(json, tweetId) {
  1645. const tweetResult = json.data.tweetResult.result; // {__typename: "Tweet"}
  1646. const tweetUser = tweetResult.core.user_results.result; // {"__typename": "User"}
  1647. const tweetLegacy = tweetResult.legacy;
  1648. return {tweetResult, tweetLegacy, tweetUser};
  1649. }
  1650.  
  1651. /**
  1652. * @typedef {Object} TweetMediaEntry
  1653. * @property {string} screen_name - "kreamu"
  1654. * @property {string} tweet_id - "1687962620173733890"
  1655. * @property {string} download_url - "https://pbs.twimg.com/media/FWYvXNMXgAA7se2?format=jpg&name=orig"
  1656. * @property {"photo" | "video"} type - "photo"
  1657. * @property {"photo" | "video" | "animated_gif"} type_original - "photo"
  1658. * @property {number} index - 0
  1659. * @property {number} type_index - 0
  1660. * @property {number} type_index_original - 0
  1661. * @property {string} preview_url - "https://pbs.twimg.com/media/FWYvXNMXgAA7se2.jpg"
  1662. * @property {string} media_id - "1687949851516862464"
  1663. * @property {string} media_key - "7_1687949851516862464"
  1664. * @property {string} expanded_url - "https://twitter.com/kreamu/status/1687962620173733890/video/1"
  1665. * @property {string} short_expanded_url - "pic.twitter.com/KeXR8T910R"
  1666. * @property {string} short_tweet_url - "https://t.co/KeXR8T910R"
  1667. * @property {string} tweet_text - "Tracer providing some In-flight entertainment"
  1668. */
  1669. /** @returns {TweetMediaEntry[]} */
  1670. static parseTweetLegacyMedias(tweetResult, tweetLegacy, tweetUser) {
  1671. if (!tweetLegacy.extended_entities || !tweetLegacy.extended_entities.media) {
  1672. return [];
  1673. }
  1674.  
  1675. const medias = [];
  1676. const typeIndex = {}; // "photo", "video", "animated_gif"
  1677. let index = -1;
  1678.  
  1679. for (const media of tweetLegacy.extended_entities.media) {
  1680. index++;
  1681. let type = media.type;
  1682. const type_original = media.type;
  1683. typeIndex[type] = (typeIndex[type] === undefined ? -1 : typeIndex[type]) + 1;
  1684. if (type === "animated_gif") {
  1685. type = "video";
  1686. typeIndex[type] = (typeIndex[type] === undefined ? -1 : typeIndex[type]) + 1;
  1687. }
  1688.  
  1689. let download_url;
  1690. if (media.video_info) {
  1691. const videoInfo = media.video_info.variants
  1692. .filter(el => el.bitrate !== undefined) // if content_type: "application/x-mpegURL" // .m3u8
  1693. .reduce((acc, cur) => cur.bitrate > acc.bitrate ? cur : acc);
  1694. download_url = videoInfo.url;
  1695. } else {
  1696. if (media.media_url_https.includes("?format=")) {
  1697. download_url = media.media_url_https;
  1698. } else {
  1699. // "https://pbs.twimg.com/media/FWYvXNMXgAA7se2.jpg" -> "https://pbs.twimg.com/media/FWYvXNMXgAA7se2?format=jpg&name=orig"
  1700. const parts = media.media_url_https.split(".");
  1701. const ext = parts[parts.length - 1];
  1702. const urlPart = parts.slice(0, -1).join(".");
  1703. download_url = `${urlPart}?format=${ext}&name=orig`;
  1704. }
  1705. }
  1706.  
  1707. const screen_name = tweetUser.legacy.screen_name; // "kreamu"
  1708. const tweet_id = tweetResult.rest_id || tweetLegacy.id_str; // "1687962620173733890"
  1709.  
  1710. const type_index = typeIndex[type]; // 0
  1711. const type_index_original = typeIndex[type_original]; // 0
  1712.  
  1713. const preview_url = media.media_url_https; // "https://pbs.twimg.com/ext_tw_video_thumb/1687949851516862464/pu/img/mTBjwz--nylYk5Um.jpg"
  1714. const media_id = media.id_str; // "1687949851516862464"
  1715. const media_key = media.media_key; // "7_1687949851516862464"
  1716.  
  1717. const expanded_url = media.expanded_url; // "https://twitter.com/kreamu/status/1687962620173733890/video/1"
  1718. const short_expanded_url = media.display_url; // "pic.twitter.com/KeXR8T910R"
  1719. const short_tweet_url = media.url; // "https://t.co/KeXR8T910R"
  1720. const tweet_text = tweetLegacy.full_text // "Tracer providing some In-flight entertainment https://t.co/KeXR8T910R"
  1721. .replace(` ${media.url}`, "");
  1722.  
  1723. // {screen_name, tweet_id, download_url, preview_url, type_index}
  1724. /** @type {TweetMediaEntry} */
  1725. const mediaEntry = {
  1726. screen_name, tweet_id,
  1727. download_url, type, type_original, index,
  1728. type_index, type_index_original,
  1729. preview_url, media_id, media_key,
  1730. expanded_url, short_expanded_url, short_tweet_url, tweet_text,
  1731. };
  1732. medias.push(mediaEntry);
  1733. }
  1734.  
  1735. verbose && console.log("[ujs][parseTweetLegacyMedias] medias", medias);
  1736. return medias;
  1737. }
  1738.  
  1739. /**
  1740. * Returns an array like this (https://x.com/kirachem/status/1805456475893928166):
  1741. * [
  1742. {
  1743. "screen_name": "kirachem",
  1744. "tweet_id": "1805456475893928166",
  1745. "download_url": "https://video.twimg.com/amplify_video/1805450004041285634/vid/avc1/1080x1080/2da-wiS9XJ42-9rv.mp4?tag=16",
  1746. "type": "video",
  1747. "type_original": "video",
  1748. "index": 0,
  1749. "type_index": 0,
  1750. "type_index_original": 0,
  1751. "preview_url": "https://pbs.twimg.com/media/GQ4_SPoakAAnW8e.jpg",
  1752. "media_id": "1805450004041285634",
  1753. "media_key": "13_1805450004041285634",
  1754. "expanded_url": "https://twitter.com/kirachem/status/1805456475893928166/video/1",
  1755. "short_expanded_url": "pic.twitter.com/VnOcUSsGaC",
  1756. "short_tweet_url": "https://t.co/VnOcUSsGaC",
  1757. "tweet_text": "Bunny Tifa (Cloud's POV)"
  1758. }
  1759. ]
  1760. */
  1761. static async getTweetMedias(tweetId) {
  1762. /* "old" (no more works / requires "x-client-transaction-id" header) and "new" API selection */
  1763.  
  1764. // const url = API.createTweetJsonEndpointUrl(tweetId); // old 2025.04
  1765. const url = API.createTweetJsonEndpointUrlById(tweetId);
  1766.  
  1767. const json = await API.apiRequest(url);
  1768. verbose && console.log("[ujs][getTweetMedias]", json, JSON.stringify(json));
  1769.  
  1770. // const {tweetResult, tweetLegacy, tweetUser} = API.parseTweetJsonFrom_TweetDetail(json, tweetId); // old 2025.04
  1771. const {tweetResult, tweetLegacy, tweetUser} = API.parseTweetJsonFrom_TweetResultByRestId(json, tweetId);
  1772.  
  1773. let result = API.parseTweetLegacyMedias(tweetResult, tweetLegacy, tweetUser);
  1774.  
  1775. if (tweetResult.quoted_status_result && tweetResult.quoted_status_result.result /* check is the qouted tweet not deleted */) {
  1776. const tweetResultQuoted = tweetResult.quoted_status_result.result;
  1777. const tweetLegacyQuoted = tweetResultQuoted.legacy;
  1778. const tweetUserQuoted = tweetResultQuoted.core.user_results.result;
  1779. result = [...result, ...API.parseTweetLegacyMedias(tweetResultQuoted, tweetLegacyQuoted, tweetUserQuoted)];
  1780. }
  1781.  
  1782. return result;
  1783. }
  1784.  
  1785. /* // dev only snippet (to extract params):
  1786. a = new URL(`https://x.com/i/api/graphql/VwKJcAd7zqlBOitPLUrB8A/TweetDetail?...`);
  1787. console.log("variables", JSON.stringify(JSON.parse(Object.fromEntries(a.searchParams).variables), null, " "))
  1788. console.log("features", JSON.stringify(JSON.parse(Object.fromEntries(a.searchParams).features), null, " "))
  1789. console.log("fieldToggles", JSON.stringify(JSON.parse(Object.fromEntries(a.searchParams).fieldToggles), null, " "))
  1790. */
  1791.  
  1792. // todo: keep `queryId` updated
  1793. // https://github.com/fa0311/TwitterInternalAPIDocument/blob/master/docs/json/API.json
  1794. static TweetDetailQueryId = "_8aYOgEDz35BrBcBal1-_w"; // TweetDetail (for videos and media tab)
  1795. static UserByScreenNameQueryId = "1VOOyvKkiI3FMmkeDNxM9A"; // UserByScreenName (for the direct user profile url)
  1796. static TweetResultByRestIdQueryId = "zAz9764BcLZOJ0JU2wrd1A"; // TweetResultByRestId (an alternative for TweetDetail)
  1797.  
  1798.  
  1799. // get a URL for TweetResultByRestId endpoint
  1800. static createTweetJsonEndpointUrlById(tweetId) {
  1801. const variables = {
  1802. "tweetId": tweetId,
  1803. "withCommunity": false,
  1804. "includePromotedContent": false,
  1805. "withVoice": false
  1806. };
  1807. const features = {
  1808. "creator_subscriptions_tweet_preview_api_enabled": true,
  1809. "premium_content_api_read_enabled": false,
  1810. "communities_web_enable_tweet_community_results_fetch": true,
  1811. "c9s_tweet_anatomy_moderator_badge_enabled": true,
  1812. "responsive_web_grok_analyze_button_fetch_trends_enabled": false,
  1813. "responsive_web_grok_analyze_post_followups_enabled": false,
  1814. "responsive_web_jetfuel_frame": false,
  1815. "responsive_web_grok_share_attachment_enabled": true,
  1816. "articles_preview_enabled": true,
  1817. "responsive_web_edit_tweet_api_enabled": true,
  1818. "graphql_is_translatable_rweb_tweet_is_translatable_enabled": true,
  1819. "view_counts_everywhere_api_enabled": true,
  1820. "longform_notetweets_consumption_enabled": true,
  1821. "responsive_web_twitter_article_tweet_consumption_enabled": true,
  1822. "tweet_awards_web_tipping_enabled": false,
  1823. "responsive_web_grok_show_grok_translated_post": false,
  1824. "responsive_web_grok_analysis_button_from_backend": false,
  1825. "creator_subscriptions_quote_tweet_preview_enabled": false,
  1826. "freedom_of_speech_not_reach_fetch_enabled": true,
  1827. "standardized_nudges_misinfo": true,
  1828. "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": true,
  1829. "longform_notetweets_rich_text_read_enabled": true,
  1830. "longform_notetweets_inline_media_enabled": true,
  1831. "profile_label_improvements_pcf_label_in_post_enabled": true,
  1832. "rweb_tipjar_consumption_enabled": true,
  1833. "verified_phone_label_enabled": false,
  1834. "responsive_web_grok_image_annotation_enabled": true,
  1835. "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
  1836. "responsive_web_graphql_timeline_navigation_enabled": true,
  1837. "responsive_web_enhance_cards_enabled": false
  1838. };
  1839. const fieldToggles = {
  1840. "withArticleRichContentState": true,
  1841. "withArticlePlainText": false,
  1842. "withGrokAnalyze": false,
  1843. "withDisallowedReplyControls": false
  1844. };
  1845.  
  1846. const urlBase = `https://${sitename}.com/i/api/graphql/${API.TweetResultByRestIdQueryId}/TweetResultByRestId`;
  1847. const urlObj = new URL(urlBase);
  1848. urlObj.searchParams.set("variables", JSON.stringify(variables));
  1849. urlObj.searchParams.set("features", JSON.stringify(features));
  1850. urlObj.searchParams.set("fieldToggles", JSON.stringify(fieldToggles));
  1851. const url = urlObj.toString();
  1852. return url;
  1853. }
  1854.  
  1855. // get a URL for TweetDetail endpoint
  1856. static createTweetJsonEndpointUrl(tweetId) {
  1857. const variables = {
  1858. "focalTweetId": tweetId,
  1859. "rankingMode": "Relevance",
  1860. "includePromotedContent": true,
  1861. "withCommunity": true,
  1862. "withQuickPromoteEligibilityTweetFields": true,
  1863. "withBirdwatchNotes": true,
  1864. "withVoice": true
  1865. };
  1866. const features = {
  1867. "rweb_video_screen_enabled": false,
  1868. "profile_label_improvements_pcf_label_in_post_enabled": true,
  1869. "rweb_tipjar_consumption_enabled": true,
  1870. "verified_phone_label_enabled": false,
  1871. "creator_subscriptions_tweet_preview_api_enabled": true,
  1872. "responsive_web_graphql_timeline_navigation_enabled": true,
  1873. "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
  1874. "premium_content_api_read_enabled": false,
  1875. "communities_web_enable_tweet_community_results_fetch": true,
  1876. "c9s_tweet_anatomy_moderator_badge_enabled": true,
  1877. "responsive_web_grok_analyze_button_fetch_trends_enabled": false,
  1878. "responsive_web_grok_analyze_post_followups_enabled": true,
  1879. "responsive_web_jetfuel_frame": false,
  1880. "responsive_web_grok_share_attachment_enabled": true,
  1881. "articles_preview_enabled": true,
  1882. "responsive_web_edit_tweet_api_enabled": true,
  1883. "graphql_is_translatable_rweb_tweet_is_translatable_enabled": true,
  1884. "view_counts_everywhere_api_enabled": true,
  1885. "longform_notetweets_consumption_enabled": true,
  1886. "responsive_web_twitter_article_tweet_consumption_enabled": true,
  1887. "tweet_awards_web_tipping_enabled": false,
  1888. "responsive_web_grok_show_grok_translated_post": false,
  1889. "responsive_web_grok_analysis_button_from_backend": true,
  1890. "creator_subscriptions_quote_tweet_preview_enabled": false,
  1891. "freedom_of_speech_not_reach_fetch_enabled": true,
  1892. "standardized_nudges_misinfo": true,
  1893. "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": true,
  1894. "longform_notetweets_rich_text_read_enabled": true,
  1895. "longform_notetweets_inline_media_enabled": true,
  1896. "responsive_web_grok_image_annotation_enabled": true,
  1897. "responsive_web_enhance_cards_enabled": false
  1898. };
  1899. const fieldToggles = {
  1900. "withArticleRichContentState":true,
  1901. "withArticlePlainText":false,
  1902. "withGrokAnalyze":false,
  1903. "withDisallowedReplyControls":false
  1904. };
  1905.  
  1906. const urlBase = `https://${sitename}.com/i/api/graphql/${API.TweetDetailQueryId}/TweetDetail`;
  1907. const urlObj = new URL(urlBase);
  1908. urlObj.searchParams.set("variables", JSON.stringify(variables));
  1909. urlObj.searchParams.set("features", JSON.stringify(features));
  1910. urlObj.searchParams.set("fieldToggles", JSON.stringify(fieldToggles));
  1911. const url = urlObj.toString();
  1912. return url;
  1913. }
  1914.  
  1915. // get data from UserByScreenName endpoint
  1916. static async getUserInfo(username) {
  1917. const variables = {
  1918. "screen_name":"unbound_figure"
  1919. };
  1920. const features = {
  1921. "hidden_profile_subscriptions_enabled": true,
  1922. "profile_label_improvements_pcf_label_in_post_enabled": true,
  1923. "rweb_tipjar_consumption_enabled": true,
  1924. "verified_phone_label_enabled": false,
  1925. "subscriptions_verification_info_is_identity_verified_enabled": true,
  1926. "subscriptions_verification_info_verified_since_enabled": true,
  1927. "highlights_tweets_tab_ui_enabled": true,
  1928. "responsive_web_twitter_article_notes_tab_enabled": true,
  1929. "subscriptions_feature_can_gift_premium": true,
  1930. "creator_subscriptions_tweet_preview_api_enabled": true,
  1931. "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
  1932. "responsive_web_graphql_timeline_navigation_enabled": true
  1933. };
  1934. const fieldToggles = {
  1935. "withAuxiliaryUserLabels": true
  1936. };
  1937.  
  1938. const urlBase = `https://${sitename}.com/i/api/graphql/${API.UserByScreenNameQueryId}/UserByScreenName?`;
  1939. const urlObj = new URL(urlBase);
  1940. urlObj.searchParams.set("variables", JSON.stringify(variables));
  1941. urlObj.searchParams.set("features", JSON.stringify(features));
  1942. urlObj.searchParams.set("fieldToggles", JSON.stringify(fieldToggles));
  1943. const url = urlObj.toString();
  1944.  
  1945. const json = await API.apiRequest(url);
  1946. verbose && console.log("[ujs][getUserInfo][json]", json);
  1947. return json.data.user.result.legacy.entities.url?.urls[0].expanded_url;
  1948. }
  1949. }
  1950.  
  1951. return API;
  1952. }
  1953.  
  1954. function getHistoryHelper() {
  1955. function migrateLocalStore() {
  1956. // 2023.07.05 // todo: uncomment after two+ months
  1957. // Currently I disable it for cases if some browser's tabs uses the old version of the script.
  1958. // const migrated = localStorage.getItem(StorageNames.migrated);
  1959. // if (migrated === "true") {
  1960. // return;
  1961. // }
  1962.  
  1963. const newToOldNameMap = [
  1964. [StorageNames.settings, StorageNamesOld.settings],
  1965. [StorageNames.settingsImageHistoryBy, StorageNamesOld.settingsImageHistoryBy],
  1966. [StorageNames.downloadedImageNames, StorageNamesOld.downloadedImageNames],
  1967. [StorageNames.downloadedImageTweetIds, StorageNamesOld.downloadedImageTweetIds],
  1968. [StorageNames.downloadedVideoTweetIds, StorageNamesOld.downloadedVideoTweetIds],
  1969. ];
  1970.  
  1971. /**
  1972. * @param {string} newName
  1973. * @param {string} oldName
  1974. * @param {string} value
  1975. */
  1976. function setValue(newName, oldName, value) {
  1977. try {
  1978. localStorage.setItem(newName, value);
  1979. } catch (err) {
  1980. localStorage.removeItem(oldName); // if there is no space ("exceeded the quota")
  1981. localStorage.setItem(newName, value);
  1982. }
  1983. localStorage.removeItem(oldName);
  1984. }
  1985.  
  1986. function mergeOldWithNew({newName, oldName}) {
  1987. const oldValueStr = localStorage.getItem(oldName);
  1988. if (oldValueStr === null) {
  1989. return;
  1990. }
  1991. const newValueStr = localStorage.getItem(newName);
  1992. if (newValueStr === null) {
  1993. setValue(newName, oldName, oldValueStr);
  1994. return;
  1995. }
  1996. try {
  1997. const oldValue = JSON.parse(oldValueStr);
  1998. const newValue = JSON.parse(newValueStr);
  1999. if (Array.isArray(oldValue) && Array.isArray(newValue)) {
  2000. const resultArray = [...new Set([...newValue, ...oldValue])];
  2001. const resultArrayStr = JSON.stringify(resultArray);
  2002. setValue(newName, oldName, resultArrayStr);
  2003. }
  2004. } catch (err) {
  2005. // return;
  2006. }
  2007. }
  2008.  
  2009. for (const [newName, oldName] of newToOldNameMap) {
  2010. mergeOldWithNew({newName, oldName});
  2011. }
  2012. // localStorage.setItem(StorageNames.migrated, "true");
  2013. }
  2014.  
  2015. function exportHistory(onDone) {
  2016. const exportObject = [
  2017. StorageNames.settings,
  2018. StorageNames.settingsImageHistoryBy,
  2019. StorageNames.downloadedImageNames, // only if "settingsImageHistoryBy" === "IMAGE_NAME" (by default)
  2020. StorageNames.downloadedImageTweetIds, // only if "settingsImageHistoryBy" === "TWEET_ID" (need to set manually with DevTools)
  2021. StorageNames.downloadedVideoTweetIds,
  2022. ].reduce((acc, name) => {
  2023. const valueStr = localStorage.getItem(name);
  2024. if (valueStr === null) {
  2025. return acc;
  2026. }
  2027. let value = JSON.parse(valueStr);
  2028. if (Array.isArray(value)) {
  2029. value = [...new Set(value)];
  2030. }
  2031. acc[name] = value;
  2032. return acc;
  2033. }, {});
  2034. const browserName = localStorage.getItem(StorageNames.browserName) || getBrowserName();
  2035. const browserLine = browserName ? "-" + browserName : "";
  2036.  
  2037. downloadBlob(new Blob([toLineJSON(exportObject, true)]), `ujs-twitter-click-n-save-export-${dateToDayDateString(new Date())}${browserLine}.json`);
  2038. onDone();
  2039. }
  2040.  
  2041. function verify(jsonObject) {
  2042. if (Array.isArray(jsonObject)) {
  2043. throw new Error("Wrong object! JSON contains an array.");
  2044. }
  2045. if (Object.keys(jsonObject).some(key => !key.startsWith("ujs-twitter-click-n-save"))) {
  2046. throw new Error("Wrong object! The keys should start with 'ujs-twitter-click-n-save'.");
  2047. }
  2048. }
  2049.  
  2050. function importHistory(onDone, onError) {
  2051. const importInput = document.createElement("input");
  2052. importInput.type = "file";
  2053. importInput.accept = "application/json";
  2054. importInput.style.display = "none";
  2055. document.body.prepend(importInput);
  2056. importInput.addEventListener("change", async _event => {
  2057. let json;
  2058. try {
  2059. json = JSON.parse(await importInput.files[0].text());
  2060. verify(json);
  2061.  
  2062. Object.entries(json).forEach(([key, value]) => {
  2063. if (Array.isArray(value)) {
  2064. value = [...new Set(value)];
  2065. }
  2066. localStorage.setItem(key, JSON.stringify(value));
  2067. });
  2068. onDone();
  2069. } catch (err) {
  2070. onError(err);
  2071. } finally {
  2072. await sleep(1000);
  2073. importInput.remove();
  2074. }
  2075. });
  2076. importInput.click();
  2077. }
  2078.  
  2079. function mergeHistory(onDone, onError) { // Only merges arrays
  2080. const mergeInput = document.createElement("input");
  2081. mergeInput.type = "file";
  2082. mergeInput.accept = "application/json";
  2083. mergeInput.style.display = "none";
  2084. document.body.prepend(mergeInput);
  2085. mergeInput.addEventListener("change", async _event => {
  2086. let json;
  2087. try {
  2088. json = JSON.parse(await mergeInput.files[0].text());
  2089. verify(json);
  2090. Object.entries(json).forEach(([key, value]) => {
  2091. if (!Array.isArray(value)) {
  2092. return;
  2093. }
  2094. const existedValue = JSON.parse(localStorage.getItem(key));
  2095. if (Array.isArray(existedValue)) {
  2096. const resultValue = [...new Set([...existedValue, ...value])];
  2097. localStorage.setItem(key, JSON.stringify(resultValue));
  2098. } else {
  2099. localStorage.setItem(key, JSON.stringify(value));
  2100. }
  2101. });
  2102. onDone();
  2103. } catch (err) {
  2104. onError(err);
  2105. } finally {
  2106. await sleep(1000);
  2107. mergeInput.remove();
  2108. }
  2109. });
  2110. mergeInput.click();
  2111. }
  2112.  
  2113. return {exportHistory, importHistory, mergeHistory, migrateLocalStore};
  2114. }
  2115.  
  2116. // ---------------------------------------------------------------------------------------------------------------------
  2117. // ---------------------------------------------------------------------------------------------------------------------
  2118. // --- Common Utils --- //
  2119.  
  2120. // --- LocalStorage util class --- //
  2121. function hoistLS(settings = {}) {
  2122. const {
  2123. verbose, // debug "messages" in the document.title
  2124. } = settings;
  2125.  
  2126. class LS {
  2127. constructor(name) {
  2128. this.name = name;
  2129. }
  2130. getItem(defaultValue) {
  2131. return LS.getItem(this.name, defaultValue);
  2132. }
  2133. setItem(value) {
  2134. LS.setItem(this.name, value);
  2135. }
  2136. removeItem() {
  2137. LS.removeItem(this.name);
  2138. }
  2139. async pushItem(value) { // array method
  2140. await LS.pushItem(this.name, value);
  2141. }
  2142. async popItem(value) { // array method
  2143. await LS.popItem(this.name, value);
  2144. }
  2145. hasItem(value) { // array method
  2146. return LS.hasItem(this.name, value);
  2147. }
  2148.  
  2149. static getItem(name, defaultValue) {
  2150. const value = localStorage.getItem(name);
  2151. if (value === undefined) {
  2152. return undefined;
  2153. }
  2154. if (value === null) { // when there is no such item
  2155. LS.setItem(name, defaultValue);
  2156. return defaultValue;
  2157. }
  2158. return JSON.parse(value);
  2159. }
  2160. static setItem(name, value) {
  2161. localStorage.setItem(name, JSON.stringify(value));
  2162. }
  2163. static removeItem(name) {
  2164. localStorage.removeItem(name);
  2165. }
  2166. static async pushItem(name, value) {
  2167. const array = LS.getItem(name, []);
  2168. array.push(value);
  2169. LS.setItem(name, array);
  2170.  
  2171. //sanity check
  2172. await sleep(50);
  2173. if (!LS.hasItem(name, value)) {
  2174. if (verbose) {
  2175. document.title = "🟥" + document.title;
  2176. }
  2177. await LS.pushItem(name, value);
  2178. }
  2179. }
  2180. static async popItem(name, value) { // remove from an array
  2181. const array = LS.getItem(name, []);
  2182. if (array.indexOf(value) !== -1) {
  2183. array.splice(array.indexOf(value), 1);
  2184. LS.setItem(name, array);
  2185.  
  2186. //sanity check
  2187. await sleep(50);
  2188. if (LS.hasItem(name, value)) {
  2189. if (verbose) {
  2190. document.title = "🟨" + document.title;
  2191. }
  2192. await LS.popItem(name, value);
  2193. }
  2194. }
  2195. }
  2196. static hasItem(name, value) { // has in array
  2197. const array = LS.getItem(name, []);
  2198. return array.indexOf(value) !== -1;
  2199. }
  2200. }
  2201.  
  2202. return LS;
  2203. }
  2204.  
  2205. // --- Just groups them in a function for the convenient code looking --- //
  2206. function getUtils({verbose}) {
  2207. function sleep(time) {
  2208. return new Promise(resolve => setTimeout(resolve, time));
  2209. }
  2210.  
  2211. async function fetchResource(url, onProgress = props => console.log(props)) {
  2212. try {
  2213. /** @type {Response} */
  2214. let response = await fetch(url, {
  2215. // cache: "force-cache",
  2216. });
  2217. const lastModifiedDateSeconds = response.headers.get("last-modified");
  2218. const contentType = response.headers.get("content-type");
  2219.  
  2220. const lastModifiedDate = dateToDayDateString(lastModifiedDateSeconds);
  2221. const extension = contentType ? extensionFromMime(contentType) : null;
  2222.  
  2223. if (onProgress) {
  2224. response = responseProgressProxy(response, onProgress);
  2225. }
  2226.  
  2227. const blob = await response.blob();
  2228.  
  2229. // https://pbs.twimg.com/media/AbcdEFgijKL01_9?format=jpg&name=orig -> AbcdEFgijKL01_9
  2230. // https://pbs.twimg.com/ext_tw_video_thumb/1234567890123456789/pu/img/Ab1cd2345EFgijKL.jpg?name=orig -> Ab1cd2345EFgijKL.jpg
  2231. // https://video.twimg.com/ext_tw_video/1234567890123456789/pu/vid/946x720/Ab1cd2345EFgijKL.mp4?tag=10 -> Ab1cd2345EFgijKL.mp4
  2232. const _url = new URL(url);
  2233. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  2234.  
  2235. const {name} = filename.match(/(?<name>^[^.]+)/).groups;
  2236. return {blob, lastModifiedDate, contentType, extension, name, status: response.status};
  2237. } catch (error) {
  2238. verbose && console.error("[ujs][fetchResource]", url);
  2239. verbose && console.error("[ujs][fetchResource]", error);
  2240. throw error;
  2241. }
  2242. }
  2243.  
  2244. function extensionFromMime(mimeType) {
  2245. let extension = mimeType.match(/(?<=\/).+/)[0];
  2246. extension = extension === "jpeg" ? "jpg" : extension;
  2247. return extension;
  2248. }
  2249.  
  2250. // the original download url will be posted as hash of the blob url, so you can check it in the download manager's history
  2251. function downloadBlob(blob, name, url) {
  2252. const anchor = document.createElement("a");
  2253. anchor.setAttribute("download", name || "");
  2254. const blobUrl = URL.createObjectURL(blob);
  2255. anchor.href = blobUrl + (url ? ("#" + url) : "");
  2256. anchor.click();
  2257. setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
  2258. }
  2259.  
  2260. // "Sun, 10 Jan 2021 22:22:22 GMT" -> "2021.01.10"
  2261. function dateToDayDateString(dateValue, utc = true) {
  2262. const _date = new Date(dateValue);
  2263. function pad(str) {
  2264. return str.toString().padStart(2, "0");
  2265. }
  2266. const _utc = utc ? "UTC" : "";
  2267. const year = _date[`get${_utc}FullYear`]();
  2268. const month = _date[`get${_utc}Month`]() + 1;
  2269. const date = _date[`get${_utc}Date`]();
  2270.  
  2271. return year + "." + pad(month) + "." + pad(date);
  2272. }
  2273.  
  2274. function addCSS(css) {
  2275. const styleElem = document.createElement("style");
  2276. styleElem.textContent = css;
  2277. document.body.append(styleElem);
  2278. return styleElem;
  2279. }
  2280.  
  2281. function getCookie(name) {
  2282. verbose && console.log("[ujs][getCookie]", document.cookie);
  2283. const regExp = new RegExp(`(?<=${name}=)[^;]+`);
  2284. return document.cookie.match(regExp)?.[0];
  2285. }
  2286.  
  2287. function throttle(runnable, time = 50) {
  2288. let waiting = false;
  2289. let queued = false;
  2290. let context;
  2291. let args;
  2292.  
  2293. return function() {
  2294. if (!waiting) {
  2295. waiting = true;
  2296. setTimeout(function() {
  2297. if (queued) {
  2298. runnable.apply(context, args);
  2299. context = args = undefined;
  2300. }
  2301. waiting = queued = false;
  2302. }, time);
  2303. return runnable.apply(this, arguments);
  2304. } else {
  2305. queued = true;
  2306. context = this;
  2307. args = arguments;
  2308. }
  2309. }
  2310. }
  2311.  
  2312. function throttleWithResult(func, time = 50) {
  2313. let waiting = false;
  2314. let args;
  2315. let context;
  2316. let timeout;
  2317. let promise;
  2318.  
  2319. return async function() {
  2320. if (!waiting) {
  2321. waiting = true;
  2322. timeout = new Promise(async resolve => {
  2323. await sleep(time);
  2324. waiting = false;
  2325. resolve();
  2326. });
  2327. return func.apply(this, arguments);
  2328. } else {
  2329. args = arguments;
  2330. context = this;
  2331. }
  2332.  
  2333. if (!promise) {
  2334. promise = new Promise(async resolve => {
  2335. await timeout;
  2336. const result = func.apply(context, args);
  2337. args = context = promise = undefined;
  2338. resolve(result);
  2339. });
  2340. }
  2341. return promise;
  2342. }
  2343. }
  2344.  
  2345. function xpath(path, node = document) {
  2346. let xPathResult = document.evaluate(path, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  2347. return xPathResult.singleNodeValue;
  2348. }
  2349. function xpathAll(path, node = document) {
  2350. let xPathResult = document.evaluate(path, node, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  2351. const nodes = [];
  2352. try {
  2353. let node = xPathResult.iterateNext();
  2354.  
  2355. while (node) {
  2356. nodes.push(node);
  2357. node = xPathResult.iterateNext();
  2358. }
  2359. return nodes;
  2360. } catch (err) {
  2361. // todo need investigate it
  2362. console.error(err); // "The document has mutated since the result was returned."
  2363. return [];
  2364. }
  2365. }
  2366.  
  2367. const identityContentEncodings = new Set([null, "identity", "no encoding"]);
  2368. function getOnProgressProps(response) {
  2369. const {headers, status, statusText, url, redirected, ok} = response;
  2370. const isIdentity = identityContentEncodings.has(headers.get("Content-Encoding"));
  2371. const compressed = !isIdentity;
  2372. const _contentLength = parseInt(headers.get("Content-Length")); // `get()` returns `null` if no header present
  2373. const contentLength = isNaN(_contentLength) ? null : _contentLength;
  2374. const lengthComputable = isIdentity && _contentLength !== null;
  2375.  
  2376. // Original XHR behaviour; in TM it equals to `contentLength`, or `-1` if `contentLength` is `null` (and `0`?).
  2377. const total = lengthComputable ? contentLength : 0;
  2378. const gmTotal = contentLength > 0 ? contentLength : -1; // Like `total` is in TM and GM.
  2379.  
  2380. return {
  2381. gmTotal, total, lengthComputable,
  2382. compressed, contentLength,
  2383. headers, status, statusText, url, redirected, ok
  2384. };
  2385. }
  2386. function responseProgressProxy(response, onProgress) {
  2387. const onProgressProps = getOnProgressProps(response);
  2388. let loaded = 0;
  2389. const reader = response.body.getReader();
  2390. const readableStream = new ReadableStream({
  2391. async start(controller) {
  2392. while (true) {
  2393. const {done, /** @type {Uint8Array} */ value} = await reader.read();
  2394. if (done) {
  2395. break;
  2396. }
  2397. loaded += value.length;
  2398. try {
  2399. onProgress({loaded, ...onProgressProps});
  2400. } catch (err) {
  2401. console.error("[ujs][onProgress]:", err);
  2402. }
  2403. controller.enqueue(value);
  2404. }
  2405. controller.close();
  2406. reader.releaseLock();
  2407. },
  2408. cancel() {
  2409. void reader.cancel();
  2410. }
  2411. });
  2412. return new ResponseEx(readableStream, response);
  2413. }
  2414. class ResponseEx extends Response {
  2415. [Symbol.toStringTag] = "ResponseEx";
  2416.  
  2417. constructor(body, {headers, status, statusText, url, redirected, type, ok}) {
  2418. super(body, {
  2419. status, statusText, headers: {
  2420. ...headers,
  2421. "content-type": headers.get("content-type")?.split("; ")[0] // Fixes Blob type ("text/html; charset=UTF-8") in TM
  2422. }
  2423. });
  2424. this._type = type;
  2425. this._url = url;
  2426. this._redirected = redirected;
  2427. this._ok = ok;
  2428. this._headers = headers; // `HeadersLike` is more user-friendly for debug than the original `Headers` object
  2429. }
  2430. get redirected() { return this._redirected; }
  2431. get url() { return this._url; }
  2432. get type() { return this._type || "basic"; }
  2433. get ok() { return this._ok; }
  2434. /** @returns {Headers} - `Headers`-like object */
  2435. get headers() { return this._headers; }
  2436. }
  2437.  
  2438. function toLineJSON(object, prettyHead = false) {
  2439. let result = "{\n";
  2440. const entries = Object.entries(object);
  2441. const length = entries.length;
  2442. if (prettyHead && length > 0) {
  2443. result += `"${entries[0][0]}":${JSON.stringify(entries[0][1], null, " ")}`;
  2444. if (length > 1) {
  2445. result += `,\n\n`;
  2446. }
  2447. }
  2448. for (let i = 1; i < length - 1; i++) {
  2449. result += `"${entries[i][0]}":${JSON.stringify(entries[i][1])},\n`;
  2450. }
  2451. if (length > 0 && !prettyHead || length > 1) {
  2452. result += `"${entries[length - 1][0]}":${JSON.stringify(entries[length - 1][1])}`;
  2453. }
  2454. result += `\n}`;
  2455. return result;
  2456. }
  2457.  
  2458. const isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") !== -1;
  2459.  
  2460. function getBrowserName() {
  2461. const userAgent = window.navigator.userAgent.toLowerCase();
  2462. return userAgent.indexOf("edge") > -1 ? "edge-legacy"
  2463. : userAgent.indexOf("edg") > -1 ? "edge"
  2464. : userAgent.indexOf("opr") > -1 && !!window.opr ? "opera"
  2465. : userAgent.indexOf("chrome") > -1 && !!window.chrome ? "chrome"
  2466. : userAgent.indexOf("firefox") > -1 ? "firefox"
  2467. : userAgent.indexOf("safari") > -1 ? "safari"
  2468. : "";
  2469. }
  2470.  
  2471. function removeSearchParams(url) {
  2472. const urlObj = new URL(url);
  2473. const keys = []; // FF + VM fix // Instead of [...urlObj.searchParams.keys()]
  2474. urlObj.searchParams.forEach((v, k) => { keys.push(k); });
  2475. for (const key of keys) {
  2476. urlObj.searchParams.delete(key);
  2477. }
  2478. return urlObj.toString();
  2479. }
  2480.  
  2481. return {
  2482. sleep, fetchResource, extensionFromMime, downloadBlob, dateToDayDateString,
  2483. addCSS,
  2484. getCookie,
  2485. throttle, throttleWithResult,
  2486. xpath, xpathAll,
  2487. responseProgressProxy,
  2488. toLineJSON,
  2489. isFirefox,
  2490. getBrowserName,
  2491. removeSearchParams,
  2492. }
  2493. }
  2494.  
  2495. // ---------------------------------------------------------------------------------------------------------------------
  2496. // ---------------------------------------------------------------------------------------------------------------------