Twitter Click'n'Save

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

当前为 2023-12-18 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址