Twitter Click'n'Save

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

当前为 2024-05-29 提交的版本,查看 最新版本

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