Twitter Click'n'Save

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

目前为 2023-12-19 提交的版本。查看 最新版本

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