Twitter Click'n'Save

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

当前为 2022-10-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Twitter Click'n'Save
  3. // @version 0.13.4-2022.10.14
  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. if (globalThis.GM_registerMenuCommand /* undefined in Firefox with VM */ || typeof GM_registerMenuCommand === "function") {
  16. GM_registerMenuCommand("Show settings", showSettings);
  17. }
  18.  
  19. // --- For debug --- //
  20. const verbose = false;
  21.  
  22. const isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") !== -1;
  23. const settings = loadSettings();
  24.  
  25. function loadSettings() {
  26. const defaultSettings = {
  27. hideTrends: true,
  28. hideSignUpSection: true,
  29. hideTopicsToFollow: false,
  30. hideTopicsToFollowInstantly: false,
  31. hideSignUpBottomBarAndMessages: true,
  32. doNotPlayVideosAutomatically: false,
  33. goFromMobileToMainSite: false,
  34.  
  35. highlightVisitedLinks: true,
  36. highlightOnlySpecialVisitedLinks: true,
  37. expandSpoilers: true,
  38.  
  39. directLinks: true,
  40. handleTitle: true,
  41.  
  42. imagesHandler: true,
  43. videoHandler: true,
  44. addRequiredCSS: true,
  45. preventBlinking: false,
  46.  
  47. hideLoginPopup: false,
  48. addBorder: false,
  49.  
  50. downloadProgress: true,
  51. strictTrackingProtectionFix: false,
  52. };
  53.  
  54. let savedSettings;
  55. try {
  56. savedSettings = JSON.parse(localStorage.getItem("ujs-click-n-save-settings")) || {};
  57. } catch (e) {
  58. console.error("[ujs]", e);
  59. localStorage.removeItem("ujs-click-n-save-settings");
  60. savedSettings = {};
  61. }
  62. savedSettings = Object.assign(defaultSettings, savedSettings);
  63. return savedSettings;
  64. }
  65. function showSettings() {
  66. closeSetting();
  67. if (window.scrollY > 0) {
  68. document.querySelector("html").classList.add("ujs-scroll-initial");
  69. document.body.classList.add("ujs-scrollbar-width-margin-right");
  70. }
  71. document.body.classList.add("ujs-no-scroll");
  72.  
  73. const modalWrapperStyle = `
  74. width: 100%;
  75. height: 100%;
  76. position: fixed;
  77. display: flex;
  78. justify-content: center;
  79. align-items: center;
  80. z-index: 99999;
  81. backdrop-filter: blur(4px);
  82. background-color: rgba(255, 255, 255, 0.5);
  83. `;
  84. const modalSettingsStyle = `
  85. background-color: white;
  86. min-width: 320px;
  87. min-height: 320px;
  88. border: 1px solid darkgray;
  89. padding: 8px;
  90. box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  91. `;
  92. const s = settings;
  93. const downloadProgressFFTitle = `Disable the download progress if you use Firefox with "Enhanced Tracking Protection" set to "Strict" and ViolentMonkey, or GreaseMonkey extension`;
  94. 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.`;
  95. document.body.insertAdjacentHTML("afterbegin", `
  96. <div class="ujs-modal-wrapper" style="${modalWrapperStyle}">
  97. <div class="ujs-modal-settings" style="${modalSettingsStyle}">
  98. <fieldset>
  99. <legend>Optional</legend>
  100. <label><input type="checkbox" ${s.hideTrends ? "checked" : ""} name="hideTrends">Hide <b>Trends</b> (in the right column)*<br/></label>
  101. <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>
  102. <label><input type="checkbox" ${s.hideSignUpBottomBarAndMessages ? "checked" : ""} name="hideSignUpBottomBarAndMessages">Hide <b>Sign Up Bar</b> and <b>Messages</b> (in the bottom)<br/></label>
  103. <label hidden><input type="checkbox" ${s.doNotPlayVideosAutomatically ? "checked" : ""} name="doNotPlayVideosAutomatically">Do <i>Not</i> Play Videos Automatically</b><br/></label>
  104. <label hidden><input type="checkbox" ${s.goFromMobileToMainSite ? "checked" : ""} name="goFromMobileToMainSite">Redirect from Mobile version (beta)<br/></label>
  105. <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>
  106. <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 reccommended 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>
  107. </fieldset>
  108. <fieldset>
  109. <legend>Recommended</legend>
  110. <label><input type="checkbox" ${s.highlightVisitedLinks ? "checked" : ""} name="highlightVisitedLinks">Highlight Visited Links<br/></label>
  111. <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>
  112. <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>
  113. </fieldset>
  114. <fieldset>
  115. <legend>Highly Recommended</legend>
  116. <label><input type="checkbox" ${s.directLinks ? "checked" : ""} name="directLinks">Direct Links</label><br/>
  117. <label><input type="checkbox" ${s.handleTitle ? "checked" : ""} name="handleTitle">Enchance Title*<br/></label>
  118. </fieldset>
  119. <fieldset ${isFirefox ? '': 'style="display: none"'}>
  120. <legend>Firefox only</legend>
  121. <label title='${downloadProgressFFTitle}'><input type="radio" ${s.downloadProgress ? "checked" : ""} name="firefoxDownloadProgress" value="downloadProgress">Download Progress<br/></label>
  122. <label title='${strictTrackingProtectionFixFFTitle}'><input type="radio" ${s.strictTrackingProtectionFix ? "checked" : ""} name="firefoxDownloadProgress" value="strictTrackingProtectionFix">Strict Tracking Protection Fix<br/></label>
  123. </fieldset>
  124. <fieldset>
  125. <legend>Main</legend>
  126. <label><input type="checkbox" ${s.imagesHandler ? "checked" : ""} name="imagesHandler">Image Download Button<br/></label>
  127. <label><input type="checkbox" ${s.videoHandler ? "checked" : ""} name="videoHandler">Video Download Button<br/></label>
  128. <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 -->
  129. </fieldset>
  130. <fieldset>
  131. <legend title="Outdated due to Twitter's updates, or impossible to reimplement">Outdated</legend>
  132. <strike>
  133.  
  134. <label title="It seems Twitter no more shows this section."><input type="checkbox" ${s.hideTopicsToFollow ? "checked" : ""} name="hideTopicsToFollow">Hide <b>Topics To Follow</b> (in the right column)*<br/></label>
  135. <label title="Prevent the tweet backgroubd blinking on the button/image click. \nOutdated. \nTwitter have removed this disgusting behavior. This option is more no need."><input type="checkbox" ${s.preventBlinking ? "checked" : ""} name="preventBlinking">Prevent blinking on click (outdated)<br/></label>
  136.  
  137. <label hidden><input type="checkbox" ${s.hideTopicsToFollowInstantly ? "checked" : ""} name="hideTopicsToFollowInstantly">Hide <b>Topics To Follow</b> Instantly*<br/></label>
  138. </strike>
  139. </fieldset>
  140. <hr>
  141. <div style="display: flex; justify-content: space-around;">
  142. <button class="ujs-save-setting-button" style="padding: 5px">Save Settings</button>
  143. <button class="ujs-close-setting-button" style="padding: 5px">Close Settings</button>
  144. </div>
  145. <hr>
  146. <h4 style="margin: 0; padding-left: 8px; color: #444;">Notes:</h4>
  147. <ul style="margin: 2px; padding-left: 16px; color: #444;">
  148. <li>Click on <b>Save Settings</b> and <b>reload the page</b> to apply changes.</li>
  149. <li><b>*</b>-marked settings are language dependent. Currently, the follow languages are supported:<br/> "en", "ru", "es", "zh", "ja".</li>
  150. <li hidden>The extension downloads only from twitter.com, not from <b>mobile</b>.twitter.com</li>
  151. </ul>
  152. </div>
  153. </div>`);
  154.  
  155. document.querySelector("body > .ujs-modal-wrapper .ujs-save-setting-button").addEventListener("click", saveSetting);
  156. document.querySelector("body > .ujs-modal-wrapper .ujs-close-setting-button").addEventListener("click", closeSetting);
  157.  
  158. function saveSetting() {
  159. const entries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox]")]
  160. .map(checkbox => [checkbox.name, checkbox.checked]);
  161. const radioEntries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=radio]")]
  162. .map(checkbox => [checkbox.value, checkbox.checked])
  163. const settings = Object.fromEntries([entries, radioEntries].flat());
  164. settings.hideTopicsToFollowInstantly = settings.hideTopicsToFollow;
  165. // console.log("[ujs]", settings);
  166. localStorage.setItem("ujs-click-n-save-settings", JSON.stringify(settings));
  167. }
  168.  
  169. function closeSetting() {
  170. document.body.classList.remove("ujs-no-scroll");
  171. document.body.classList.remove("ujs-scrollbar-width-margin-right");
  172. document.querySelector("html").classList.remove("ujs-scroll-initial");
  173. document.querySelector("body > .ujs-modal-wrapper")?.remove();
  174. }
  175. }
  176.  
  177. // ---------------------------------------------------------------------------------------------------------------------
  178. // ---------------------------------------------------------------------------------------------------------------------
  179.  
  180. // --- Features to execute --- //
  181. const doNotPlayVideosAutomatically = false;
  182.  
  183. function execFeaturesOnce() {
  184. settings.goFromMobileToMainSite && Features.goFromMobileToMainSite();
  185. settings.addRequiredCSS && Features.addRequiredCSS();
  186. settings.hideSignUpBottomBarAndMessages && Features.hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically);
  187. settings.hideTrends && Features.hideTrends();
  188. settings.highlightVisitedLinks && Features.highlightVisitedLinks();
  189. settings.hideTopicsToFollowInstantly && Features.hideTopicsToFollowInstantly();
  190. settings.hideLoginPopup && Features.hideLoginPopup();
  191. }
  192. function execFeaturesImmediately() {
  193. settings.expandSpoilers && Features.expandSpoilers();
  194. }
  195. function execFeatures() {
  196. settings.imagesHandler && Features.imagesHandler(settings.preventBlinking);
  197. settings.videoHandler && Features.videoHandler(settings.preventBlinking);
  198. settings.expandSpoilers && Features.expandSpoilers();
  199. settings.hideSignUpSection && Features.hideSignUpSection();
  200. settings.hideTopicsToFollow && Features.hideTopicsToFollow();
  201. settings.directLinks && Features.directLinks();
  202. settings.handleTitle && Features.handleTitle();
  203. }
  204.  
  205. // ---------------------------------------------------------------------------------------------------------------------
  206. // ---------------------------------------------------------------------------------------------------------------------
  207.  
  208. if (verbose) {
  209. console.log("[ujs][settings]", settings);
  210. // showSettings();
  211. }
  212.  
  213. // --- [VM/GM + Firefox ~90+ + Enabled "Strict Tracking Protection"] fix --- //
  214. const fetch = (settings.strictTrackingProtectionFix && typeof wrappedJSObject === "object" && typeof wrappedJSObject.fetch === "function") ? function(resource, init = {}) {
  215. verbose && console.log("wrappedJSObject.fetch", resource, init);
  216.  
  217. if (init.headers instanceof Headers) {
  218. // Since `Headers` are not allowed for structured cloning.
  219. init.headers = Object.fromEntries(init.headers.entries());
  220. }
  221.  
  222. return wrappedJSObject.fetch(cloneInto(resource, document), cloneInto(init, document));
  223. } : globalThis.fetch;
  224.  
  225. // --- "Imports" --- //
  226. const {
  227. sleep, fetchResource, downloadBlob,
  228. addCSS,
  229. getCookie,
  230. throttle,
  231. xpath, xpathAll,
  232. responseProgressProxy,
  233. } = getUtils({verbose});
  234. const LS = hoistLS({verbose});
  235.  
  236. const API = hoistAPI();
  237. const Tweet = hoistTweet();
  238. const Features = hoistFeatures();
  239. const I18N = getLanguageConstants();
  240.  
  241. // --- That to use for the image history --- //
  242. // "TWEET_ID" or "IMAGE_NAME"
  243. const imagesHistoryBy = LS.getItem("ujs-images-history-by", "IMAGE_NAME");
  244. // With "TWEET_ID" downloading of 1 image of 4 will mark all 4 images as "already downloaded"
  245. // on the next time when the tweet will appear.
  246. // "IMAGE_NAME" will count each image of a tweet, but it will take more data to store.
  247.  
  248. // ---------------------------------------------------------------------------------------------------------------------
  249. // ---------------------------------------------------------------------------------------------------------------------
  250. // --- Script runner --- //
  251.  
  252. (function starter(feats) {
  253. const {once, onChangeImmediate, onChange} = feats;
  254.  
  255. once();
  256. onChangeImmediate();
  257. const onChangeThrottled = throttle(onChange, 250);
  258. onChangeThrottled();
  259.  
  260. const targetNode = document.querySelector("body");
  261. const observerOptions = {
  262. subtree: true,
  263. childList: true,
  264. };
  265. const observer = new MutationObserver(callback);
  266. observer.observe(targetNode, observerOptions);
  267.  
  268. function callback(mutationList, observer) {
  269. verbose && console.log(mutationList);
  270. onChangeImmediate();
  271. onChangeThrottled();
  272. }
  273. })({
  274. once: execFeaturesOnce,
  275. onChangeImmediate: execFeaturesImmediately,
  276. onChange: execFeatures
  277. });
  278.  
  279. // ---------------------------------------------------------------------------------------------------------------------
  280. // ---------------------------------------------------------------------------------------------------------------------
  281. // --- Twitter Specific code --- //
  282.  
  283. const downloadedImages = new LS("ujs-twitter-downloaded-images-names");
  284. const downloadedImageTweetIds = new LS("ujs-twitter-downloaded-image-tweet-ids");
  285. const downloadedVideoTweetIds = new LS("ujs-twitter-downloaded-video-tweet-ids");
  286.  
  287. // --- Twitter.Features --- //
  288. function hoistFeatures() {
  289. class Features {
  290. static goFromMobileToMainSite() {
  291. if (location.href.startsWith("https://mobile.twitter.com/")) {
  292. location.href = location.href.replace("https://mobile.twitter.com/", "https://twitter.com/");
  293. }
  294. // TODO: add #redirected, remove by timer // to prevent a potential infinity loop
  295. }
  296.  
  297. static createButton({url, downloaded, isVideo}) {
  298. const btn = document.createElement("div");
  299. btn.innerHTML = `
  300. <div class="ujs-btn-common ujs-btn-background"></div>
  301. <div class="ujs-btn-common ujs-hover"></div>
  302. <div class="ujs-btn-common ujs-shadow"></div>
  303. <div class="ujs-btn-common ujs-progress" style="--progress: 0%"></div>
  304. <div class="ujs-btn-common ujs-btn-error-text"></div>`.slice(1);
  305. btn.classList.add("ujs-btn-download");
  306. if (!downloaded) {
  307. btn.classList.add("ujs-not-downloaded");
  308. } else {
  309. btn.classList.add("ujs-already-downloaded");
  310. }
  311. if (isVideo) {
  312. btn.classList.add("ujs-video");
  313. }
  314. if (url) {
  315. btn.dataset.url = url;
  316. }
  317. return btn;
  318. }
  319.  
  320. static hasBlinkListenerWeakSet;
  321. static _preventBlinking(clickBtnElem) {
  322. const weakSet = Features.hasBlinkListenerWeakSet || (Features.hasBlinkListenerWeakSet = new WeakSet());
  323. let wrapper;
  324. clickBtnElem.addEventListener("mouseenter", () => {
  325. if (!weakSet.has(clickBtnElem)) {
  326. wrapper = Features._preventBlinkingHandler(clickBtnElem);
  327. weakSet.add(clickBtnElem);
  328. }
  329. });
  330. clickBtnElem.addEventListener("mouseleave", () => {
  331. verbose && console.log("[ujs] Btn mouseleave");
  332. if (wrapper?.observer?.disconnect) {
  333. weakSet.delete(clickBtnElem);
  334. wrapper.observer.disconnect();
  335. }
  336. });
  337. }
  338. static _preventBlinkingHandler(clickBtnElem) {
  339. let targetNode = clickBtnElem.closest("[aria-labelledby]");
  340. if (!targetNode) {
  341. return;
  342. }
  343. let config = {attributes: true, subtree: true, attributeOldValue: true};
  344. const wrapper = {};
  345. wrapper.observer = new MutationObserver(callback);
  346. wrapper.observer.observe(targetNode, config);
  347.  
  348. function callback(mutationsList, observer) {
  349. for (const mutation of mutationsList) {
  350. if (mutation.type === "attributes" && mutation.attributeName === "class") {
  351. if (mutation.target.classList.contains("ujs-btn-download")) {
  352. return;
  353. }
  354. // Don't allow to change classList
  355. mutation.target.className = mutation.oldValue;
  356.  
  357. // Recreate, to prevent an infinity loop
  358. wrapper.observer.disconnect();
  359. wrapper.observer = new MutationObserver(callback);
  360. wrapper.observer.observe(targetNode, config);
  361. }
  362. }
  363. }
  364.  
  365. return wrapper;
  366. }
  367.  
  368. // Banner/Background
  369. static async _downloadBanner(url, btn) {
  370. const username = location.pathname.slice(1).split("/")[0];
  371.  
  372. btn.classList.add("ujs-downloading");
  373.  
  374. // https://pbs.twimg.com/profile_banners/34743251/1596331248/1500x500
  375. const {
  376. id, seconds, res
  377. } = url.match(/(?<=\/profile_banners\/)(?<id>\d+)\/(?<seconds>\d+)\/(?<res>\d+x\d+)/)?.groups || {};
  378.  
  379. const {blob, lastModifiedDate, extension, name} = await fetchResource(url);
  380.  
  381. Features.verifyBlob(blob, url, btn);
  382.  
  383. const filename = `[twitter][bg] ${username}—${lastModifiedDate}—${id}—${seconds}.${extension}`;
  384. downloadBlob(blob, filename, url);
  385.  
  386. btn.classList.remove("ujs-downloading");
  387. btn.classList.add("ujs-downloaded");
  388. }
  389.  
  390. static _ImageHistory = class {
  391. static getImageNameFromUrl(url) {
  392. const _url = new URL(url);
  393. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  394. return filename.match(/^[^.]+/)[0]; // remove extension
  395. }
  396. static isDownloaded({id, url}) {
  397. if (imagesHistoryBy === "TWEET_ID") {
  398. return downloadedImageTweetIds.hasItem(id);
  399. } else if (imagesHistoryBy === "IMAGE_NAME") {
  400. const name = Features._ImageHistory.getImageNameFromUrl(url);
  401. return downloadedImages.hasItem(name);
  402. }
  403. }
  404. static async markDownloaded({id, url}) {
  405. if (imagesHistoryBy === "TWEET_ID") {
  406. await downloadedImageTweetIds.pushItem(id);
  407. } else if (imagesHistoryBy === "IMAGE_NAME") {
  408. const name = Features._ImageHistory.getImageNameFromUrl(url);
  409. await downloadedImages.pushItem(name);
  410. }
  411. }
  412. }
  413. static async imagesHandler(preventBlinking) {
  414. verbose && console.log("[ujs-cns][imagesHandler]");
  415. const images = document.querySelectorAll("img");
  416. for (const img of images) {
  417.  
  418. if (img.width < 150 || img.dataset.handled) {
  419. continue;
  420. }
  421. verbose && console.log(img, img.width);
  422.  
  423. img.dataset.handled = "true";
  424.  
  425. const btn = Features.createButton({url: img.src});
  426. btn.addEventListener("click", Features._imageClickHandler);
  427.  
  428. let anchor = img.closest("a");
  429. // if an image is _opened_ "https://twitter.com/UserName/status/1234567890123456789/photo/1" [fake-url]
  430. if (!anchor) {
  431. anchor = img.parentNode;
  432. }
  433. anchor.append(btn);
  434. if (preventBlinking) {
  435. Features._preventBlinking(btn);
  436. }
  437.  
  438. const downloaded = Features._ImageHistory.isDownloaded({
  439. id: Tweet.of(btn).id,
  440. url: btn.dataset.url
  441. });
  442. if (downloaded) {
  443. btn.classList.add("ujs-already-downloaded");
  444. }
  445. }
  446. }
  447. static async _imageClickHandler(event) {
  448. event.preventDefault();
  449. event.stopImmediatePropagation();
  450.  
  451. const btn = event.currentTarget;
  452. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  453. let url = btn.dataset.url;
  454.  
  455. const isBanner = url.includes("/profile_banners/");
  456. if (isBanner) {
  457. return Features._downloadBanner(url, btn);
  458. }
  459.  
  460. const {id, author} = Tweet.of(btn);
  461. verbose && console.log(id, author);
  462.  
  463. const btnProgress = btn.querySelector(".ujs-progress");
  464. if (btn.textContent !== "") {
  465. btnErrorTextElem.textContent = "";
  466. }
  467. btn.classList.remove("ujs-error");
  468. btn.classList.add("ujs-downloading");
  469.  
  470. let onProgress = null;
  471. if (settings.downloadProgress) {
  472. onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
  473. }
  474.  
  475. const originals = ["orig", "4096x4096"];
  476. const samples = ["large", "medium", "900x900", "small", "360x360", /*"240x240", "120x120", "tiny"*/];
  477. let isSample = false;
  478. const previewSize = new URL(url).searchParams.get("name");
  479. if (!samples.includes(previewSize)) {
  480. samples.push(previewSize);
  481. }
  482.  
  483. function handleImgUrl(url) {
  484. const urlObj = new URL(url);
  485. if (originals.length) {
  486. urlObj.searchParams.set("name", originals.shift());
  487. } else if (samples.length) {
  488. isSample = true;
  489. urlObj.searchParams.set("name", samples.shift());
  490. } else {
  491. throw new Error("All fallback URLs are failed to download.");
  492. }
  493. url = urlObj.toString();
  494. verbose && console.log("[handleImgUrl]", url);
  495. return url;
  496. }
  497.  
  498. async function safeFetchResource(url) {
  499. while (true) {
  500. url = handleImgUrl(url);
  501. try {
  502. return await fetchResource(url, onProgress);
  503. } catch (e) {
  504. if (!originals.length) {
  505. btn.classList.add("ujs-error");
  506. btnErrorTextElem.textContent = "";
  507. // Add ⚠
  508. 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;`;
  509. btn.title = "[warning] Original images are not available.";
  510. }
  511. if (!samples.length) {
  512. btnErrorTextElem.textContent = "";
  513. // Add ❌
  514. 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;`;
  515. btn.title = "Failed to download the image.";
  516. throw new Error("[error] Fallback URLs are failed.");
  517. }
  518. }
  519. }
  520. }
  521.  
  522. const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url);
  523.  
  524. Features.verifyBlob(blob, url, btn);
  525.  
  526. btnProgress.style.cssText = "--progress: 100%";
  527.  
  528. const sampleText = !isSample ? "" : "[sample]";
  529. const filename = `[twitter]${sampleText} ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
  530. downloadBlob(blob, filename, url);
  531.  
  532. const downloaded = btn.classList.contains("already-downloaded");
  533. if (!downloaded && !isSample) {
  534. await Features._ImageHistory.markDownloaded({id, url});
  535. }
  536. btn.classList.remove("ujs-downloading");
  537. btn.classList.add("ujs-downloaded");
  538.  
  539. await sleep(40);
  540. btnProgress.style.cssText = "--progress: 0%";
  541. }
  542.  
  543. static tweetVidWeakMap = new WeakMap();
  544. static async videoHandler(preventBlinking) {
  545. const videos = document.querySelectorAll("video");
  546.  
  547. for (const vid of videos) {
  548. if (vid.dataset.handled) {
  549. continue;
  550. }
  551. verbose && console.log(vid);
  552. vid.dataset.handled = "true";
  553.  
  554. const poster = vid.getAttribute("poster");
  555.  
  556. const btn = Features.createButton({isVideo: true, url: poster});
  557. btn.addEventListener("click", Features._videoClickHandler);
  558.  
  559. let elem = vid.parentNode.parentNode.parentNode;
  560. elem.after(btn);
  561. if (preventBlinking) {
  562. Features._preventBlinking(btn);
  563. }
  564.  
  565. const tweet = Tweet.of(btn);
  566. const id = tweet.id;
  567. const tweetElem = tweet.elem;
  568. let vidNumber = 0;
  569.  
  570. const map = Features.tweetVidWeakMap;
  571. if (map.has(tweetElem)) {
  572. vidNumber = map.get(tweetElem) + 1;
  573. map.set(tweetElem, vidNumber);
  574. } else {
  575. map.set(tweetElem, vidNumber);
  576. }
  577.  
  578. const historyId = vidNumber ? id + "-" + vidNumber : id;
  579.  
  580. const downloaded = downloadedVideoTweetIds.hasItem(historyId);
  581. if (downloaded) {
  582. btn.classList.add("ujs-already-downloaded");
  583. }
  584. }
  585. }
  586. static async _videoClickHandler(event) {
  587. event.preventDefault();
  588. event.stopImmediatePropagation();
  589.  
  590. const btn = event.currentTarget;
  591. const btnErrorTextElem = btn.querySelector(".ujs-btn-error-text");
  592. let {id, author} = Tweet.of(btn);
  593.  
  594. if (btn.textContent !== "") {
  595. btnErrorTextElem.textContent = "";
  596. }
  597. btn.classList.remove("ujs-error");
  598. btn.classList.add("ujs-downloading");
  599.  
  600. const posterUrl = btn.dataset.url;
  601.  
  602. let video; // {bitrate, content_type, url}
  603. let vidNumber = 0;
  604. try {
  605. ({video, tweetId: id, screenName: author, vidNumber} = await API.getVideoInfo(id, author, posterUrl));
  606. verbose && console.log(video);
  607. } catch (e) {
  608. btn.classList.add("ujs-error");
  609. btnErrorTextElem.textContent = "Error";
  610. btn.title = "API.getVideoInfo Error";
  611. throw new Error("API.getVideoInfo Error");
  612. }
  613.  
  614. const btnProgress = btn.querySelector(".ujs-progress");
  615.  
  616. const url = video.url;
  617. let onProgress = null;
  618. if (settings.downloadProgress) {
  619. onProgress = ({loaded, total}) => btnProgress.style.cssText = "--progress: " + loaded / total * 90 + "%";
  620. }
  621.  
  622. const {blob, lastModifiedDate, extension, name} = await fetchResource(url, onProgress);
  623.  
  624. btnProgress.style.cssText = "--progress: 100%";
  625.  
  626. Features.verifyBlob(blob, url, btn);
  627.  
  628. const filename = `[twitter] ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
  629. downloadBlob(blob, filename, url);
  630.  
  631. const downloaded = btn.classList.contains("ujs-already-downloaded");
  632. const historyId = vidNumber ? id + "-" + vidNumber : id;
  633. if (!downloaded) {
  634. await downloadedVideoTweetIds.pushItem(historyId);
  635. }
  636. btn.classList.remove("ujs-downloading");
  637. btn.classList.add("ujs-downloaded");
  638.  
  639. await sleep(40);
  640. btnProgress.style.cssText = "--progress: 0%";
  641. }
  642.  
  643. static verifyBlob(blob, url, btn) {
  644. if (!blob.size) {
  645. btn.classList.add("ujs-error");
  646. btn.querySelector(".ujs-btn-error-text").textContent = "Error";
  647. btn.title = "Download Error";
  648. throw new Error("Zero size blob: " + url);
  649. }
  650. }
  651.  
  652. static addRequiredCSS() {
  653. const code = getUserScriptCSS();
  654. addCSS(code);
  655. }
  656.  
  657. // it depends of `directLinks()` use only it after `directLinks()`
  658. static handleTitle(title) {
  659.  
  660. if (!I18N.QUOTES) { // Unsupported lang, no QUOTES, ON_TWITTER, TWITTER constants
  661. return;
  662. }
  663.  
  664. // if not an opened tweet
  665. if (!location.href.match(/twitter\.com\/[^\/]+\/status\/\d+/)) {
  666. return;
  667. }
  668.  
  669. let titleText = title || document.title;
  670. if (titleText === Features.lastHandledTitle) {
  671. return;
  672. }
  673. Features.originalTitle = titleText;
  674.  
  675. const [OPEN_QUOTE, CLOSE_QUOTE] = I18N.QUOTES;
  676. const urlsToReplace = [
  677. ...titleText.matchAll(new RegExp(`https:\\/\\/t\\.co\\/[^ ${CLOSE_QUOTE}]+`, "g"))
  678. ].map(el => el[0]);
  679. // the last one may be the URL to the tweet // or to an embedded shared URL
  680.  
  681. const map = new Map();
  682. const anchors = document.querySelectorAll(`a[data-redirect^="https://t.co/"]`);
  683. for (const anchor of anchors) {
  684. if (urlsToReplace.includes(anchor.dataset.redirect)) {
  685. map.set(anchor.dataset.redirect, anchor.href);
  686. }
  687. }
  688.  
  689. const lastUrl = urlsToReplace.slice(-1)[0];
  690. let lastUrlIsAttachment = false;
  691. let attachmentDescription = "";
  692. if (!map.has(lastUrl)) {
  693. const a = document.querySelector(`a[href="${lastUrl}?amp=1"]`);
  694. if (a) {
  695. lastUrlIsAttachment = true;
  696. attachmentDescription = document.querySelectorAll(`a[href="${lastUrl}?amp=1"]`)[1].innerText;
  697. attachmentDescription = attachmentDescription.replaceAll("\n", " — ");
  698. }
  699. }
  700.  
  701. for (const [key, value] of map.entries()) {
  702. titleText = titleText.replaceAll(key, value + ` (${key})`);
  703. }
  704.  
  705. titleText = titleText.replace(new RegExp(`${I18N.ON_TWITTER}(?= ${OPEN_QUOTE})`), ":");
  706. titleText = titleText.replace(new RegExp(`(?<=${CLOSE_QUOTE}) \\\/ ${I18N.TWITTER}$`), "");
  707. if (!lastUrlIsAttachment) {
  708. const regExp = new RegExp(`(?<short> https:\\/\\/t\\.co\\/.{6,14})${CLOSE_QUOTE}$`);
  709. titleText = titleText.replace(regExp, (match, p1, p2, offset, string) => `${CLOSE_QUOTE} ${p1}`);
  710. } else {
  711. titleText = titleText.replace(lastUrl, `${lastUrl} (${attachmentDescription})`);
  712. }
  713. document.title = titleText; // Note: some characters will be removed automatically (`\n`, extra spaces)
  714. Features.lastHandledTitle = document.title;
  715. }
  716. static lastHandledTitle = "";
  717. static originalTitle = "";
  718.  
  719. static profileUrlCache = new Map();
  720. static async directLinks() {
  721. verbose && console.log("[ujs][directLinks]");
  722. const hasHttp = url => Boolean(url.match(/^https?:\/\//));
  723. const anchors = xpathAll(`.//a[@dir="ltr" and child::span and not(@data-handled)]`);
  724. for (const anchor of anchors) {
  725. const redirectUrl = new URL(anchor.href);
  726. const shortUrl = redirectUrl.origin + redirectUrl.pathname; // remove "?amp=1"
  727. anchor.dataset.redirect = shortUrl;
  728. anchor.dataset.handled = "true";
  729. anchor.rel = "nofollow noopener noreferrer";
  730.  
  731. if (Features.profileUrlCache.has(shortUrl)) {
  732. anchor.href = Features.profileUrlCache.get(shortUrl);
  733. continue;
  734. }
  735.  
  736. const nodes = xpathAll(`./span[text() != "…"]|./text()`, anchor);
  737. let url = nodes.map(node => node.textContent).join("");
  738.  
  739. const doubleProtocolPrefix = url.match(/(?<dup>^https?:\/\/)(?=https?:)/)?.groups.dup;
  740. if (doubleProtocolPrefix) {
  741. url = url.slice(doubleProtocolPrefix.length);
  742. const span = anchor.querySelector(`[aria-hidden="true"]`);
  743. if (hasHttp(span.textContent)) { // Fix Twitter's bug related to text copying
  744. span.style = "display: none;";
  745. }
  746. }
  747.  
  748. anchor.href = url;
  749.  
  750. if (anchor.dataset?.testid === "UserUrl") {
  751. const href = anchor.getAttribute("href");
  752. const profileUrl = hasHttp(href) ? href : "https://" + href;
  753. anchor.href = profileUrl;
  754. verbose && console.log("[ujs][directLinks][UserUrl]", profileUrl);
  755.  
  756. // Restore if URL's text content is too long
  757. if (anchor.textContent.endsWith("…")) {
  758. anchor.href = shortUrl;
  759.  
  760. try {
  761. const author = location.pathname.slice(1).match(/[^\/]+/)[0];
  762. const expanded_url = await API.getUserInfo(author); // todo: make lazy
  763. anchor.href = expanded_url;
  764. Features.profileUrlCache.set(shortUrl, expanded_url);
  765. } catch (e) {
  766. verbose && console.error(e);
  767. }
  768. }
  769. }
  770. }
  771. if (anchors.length) {
  772. Features.handleTitle(Features.originalTitle);
  773. }
  774. }
  775.  
  776. // Do NOT throttle it
  777. static expandSpoilers() {
  778. const main = document.querySelector("main[role=main]");
  779. if (!main) {
  780. return;
  781. }
  782.  
  783. if (!I18N.YES_VIEW_PROFILE) { // Unsupported lang, no YES_VIEW_PROFILE, SHOW_NUDITY, VIEW constants
  784. return;
  785. }
  786.  
  787. const a = main.querySelectorAll("[data-testid=primaryColumn] [role=button]");
  788. if (a) {
  789. const elems = [...a];
  790. const button = elems.find(el => el.textContent === I18N.YES_VIEW_PROFILE);
  791. if (button) {
  792. button.click();
  793. }
  794.  
  795. // "Content warning: Nudity"
  796. // "The Tweet author flagged this Tweet as showing sensitive content."
  797. // "Show"
  798. const buttonShow = elems.find(el => el.textContent === I18N.SHOW_NUDITY);
  799. if (buttonShow) {
  800. // const verifying = a.previousSibling.textContent.includes("Nudity"); // todo?
  801. // if (verifying) {
  802. buttonShow.click();
  803. // }
  804. }
  805. }
  806.  
  807. // todo: expand spoiler commentary in photo view mode (.../photo/1)
  808. const b = main.querySelectorAll("article [role=presentation] div[role=button]");
  809. if (b) {
  810. const elems = [...b];
  811. const buttons = elems.filter(el => el.textContent === I18N.VIEW);
  812. if (buttons.length) {
  813. buttons.forEach(el => el.click());
  814. }
  815. }
  816. }
  817.  
  818. static hideSignUpSection() { // "New to Twitter?"
  819. if (!I18N.SIGNUP) {// Unsupported lang, no SIGNUP constant
  820. return;
  821. }
  822. const elem = document.querySelector(`section[aria-label="${I18N.SIGNUP}"][role=region]`);
  823. if (elem) {
  824. elem.parentNode.classList.add("ujs-hidden");
  825. }
  826. }
  827.  
  828. // Call it once.
  829. // "Don’t miss what’s happening" if you are not logged in.
  830. // It looks that `#layers` is used only for this bar.
  831. static hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically) {
  832. if (doNotPlayVideosAutomatically) {
  833. addCSS(`
  834. #layers > div:nth-child(1) {
  835. display: none;
  836. }
  837. `);
  838. } else {
  839. addCSS(`
  840. #layers > div:nth-child(1) {
  841. height: 1px;
  842. opacity: 0;
  843. }
  844. `);
  845. }
  846. }
  847.  
  848. // "Trends for you"
  849. static hideTrends() {
  850. if (!I18N.TRENDS) { // Unsupported lang, no TRENDS constant
  851. return;
  852. }
  853. addCSS(`
  854. [aria-label="${I18N.TRENDS}"]
  855. {
  856. display: none;
  857. }
  858. `);
  859. }
  860.  
  861. static highlightVisitedLinks() {
  862. if (settings.highlightOnlySpecialVisitedLinks) {
  863. addCSS(`
  864. a[href^="http"]:visited {
  865. color: darkorange;
  866. }
  867. `);
  868. return;
  869. }
  870. addCSS(`
  871. a:visited {
  872. color: darkorange;
  873. }
  874. `);
  875. }
  876.  
  877. // Hides "TOPICS TO FOLLOW" only in the right column, NOT in timeline.
  878. // Use it once. To prevent blinking.
  879. static hideTopicsToFollowInstantly() {
  880. if (!I18N.TOPICS_TO_FOLLOW) { // Unsupported lang, no TOPICS_TO_FOLLOW constant
  881. return;
  882. }
  883. addCSS(`
  884. div[aria-label="${I18N.TOPICS_TO_FOLLOW}"] {
  885. display: none;
  886. }
  887. `);
  888. }
  889.  
  890. // Hides container and "separator line"
  891. static hideTopicsToFollow() {
  892. if (!I18N.TOPICS_TO_FOLLOW) { // Unsupported lang, no TOPICS_TO_FOLLOW constant
  893. return;
  894. }
  895.  
  896. const elem = xpath(`.//section[@role="region" and child::div[@aria-label="${I18N.TOPICS_TO_FOLLOW}"]]/../..`);
  897. if (!elem) {
  898. return;
  899. }
  900. elem.classList.add("ujs-hidden");
  901.  
  902. elem.previousSibling.classList.add("ujs-hidden"); // a "separator line" (empty element of "TRENDS", for example)
  903. // in fact it's a hack // todo rework // may hide "You might like" section [bug]
  904. }
  905.  
  906. // todo split to two methods
  907. // todo fix it, currently it works questionably
  908. // not tested with non eng langs
  909. static footerHandled = false;
  910. static hideAndMoveFooter() { // "Terms of Service Privacy Policy Cookie Policy"
  911. let footer = document.querySelector(`main[role=main] nav[aria-label=${I18N.FOOTER}][role=navigation]`);
  912. const nav = document.querySelector("nav[aria-label=Primary][role=navigation]"); // I18N."Primary" [?]
  913.  
  914. if (footer) {
  915. footer = footer.parentNode;
  916. const separatorLine = footer.previousSibling;
  917.  
  918. if (Features.footerHandled) {
  919. footer.remove();
  920. separatorLine.remove();
  921. return;
  922. }
  923.  
  924. nav.append(separatorLine);
  925. nav.append(footer);
  926. footer.classList.add("ujs-show-on-hover");
  927. separatorLine.classList.add("ujs-show-on-hover");
  928.  
  929. Features.footerHandled = true;
  930. }
  931. }
  932.  
  933. static hideLoginPopup() { // When you are not logged in
  934. const targetNode = document.querySelector("html");
  935. const observerOptions = {
  936. attributes: true,
  937. };
  938. const observer = new MutationObserver(callback);
  939. observer.observe(targetNode, observerOptions);
  940.  
  941. function callback(mutationList, observer) {
  942. const html = document.querySelector("html");
  943. console.log(mutationList);
  944. // overflow-y: scroll; overscroll-behavior-y: none; font-size: 15px; // default
  945. // overflow: hidden; overscroll-behavior-y: none; font-size: 15px; margin-right: 15px; // popup
  946. if (html.style["overflow"] === "hidden") {
  947. html.style["overflow"] = "";
  948. html.style["overflow-y"] = "scroll";
  949. html.style["margin-right"] = "";
  950. }
  951. const popup = document.querySelector(`#layers div[data-testid="sheetDialog"]`);
  952. if (popup) {
  953. popup.closest(`div[role="dialog"]`).remove();
  954. verbose && (document.title = "⚒" + document.title);
  955. // observer.disconnect();
  956. }
  957. }
  958. }
  959.  
  960. }
  961.  
  962. return Features;
  963. }
  964.  
  965. // --- Twitter.RequiredCSS --- //
  966. function getUserScriptCSS() {
  967. const labelText = I18N.IMAGE || "Image";
  968.  
  969. // By default, the scroll is showed all time, since <html style="overflow-y: scroll;>,
  970. // so it works — no need to use `getScrollbarWidth` function from SO (13382516).
  971. const scrollbarWidth = window.innerWidth - document.body.offsetWidth;
  972.  
  973. const css = `
  974. .ujs-hidden {
  975. display: none;
  976. }
  977. .ujs-no-scroll {
  978. overflow-y: hidden;
  979. }
  980. .ujs-scroll-initial {
  981. overflow-y: initial!important;
  982. }
  983. .ujs-scrollbar-width-margin-right {
  984. margin-right: ${scrollbarWidth}px;
  985. }
  986.  
  987. .ujs-show-on-hover:hover {
  988. opacity: 1;
  989. transition: opacity 1s ease-out 0.1s;
  990. }
  991. .ujs-show-on-hover {
  992. opacity: 0;
  993. transition: opacity 0.5s ease-out;
  994. }
  995.  
  996. :root {
  997. --ujs-shadow-1: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  998. --ujs-shadow-2: linear-gradient(to top, rgba(0,0,0,0.25), rgba(0,0,0,0.05));
  999. --ujs-shadow-3: linear-gradient(to top, rgba(0,0,0,0.45), rgba(0,0,0,0.15));
  1000. --ujs-shadow-4: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.25));
  1001. --ujs-red: #e0245e;
  1002. --ujs-blue: #1da1f2;
  1003. --ujs-green: #4caf50;
  1004. --ujs-gray: #c2cbd0;
  1005. --ujs-error: white;
  1006. }
  1007.  
  1008. .ujs-progress {
  1009. background-image: linear-gradient(to right, var(--ujs-green) var(--progress), transparent 0%);
  1010. }
  1011.  
  1012. .ujs-shadow {
  1013. background-image: var(--ujs-shadow-1);
  1014. }
  1015. .ujs-btn-download:hover .ujs-hover {
  1016. background-image: var(--ujs-shadow-2);
  1017. }
  1018. .ujs-btn-download.ujs-downloading .ujs-shadow {
  1019. background-image: var(--ujs-shadow-3);
  1020. }
  1021. .ujs-btn-download:active .ujs-shadow {
  1022. background-image: var(--ujs-shadow-4);
  1023. }
  1024.  
  1025. article[role=article]:hover .ujs-btn-download {
  1026. opacity: 1;
  1027. }
  1028. div[aria-label="${labelText}"]:hover .ujs-btn-download {
  1029. opacity: 1;
  1030. }
  1031. .ujs-btn-download.ujs-downloaded {
  1032. opacity: 1;
  1033. }
  1034. .ujs-btn-download.ujs-downloading {
  1035. opacity: 1;
  1036. }
  1037.  
  1038. .ujs-btn-download {
  1039. cursor: pointer;
  1040. top: 0.5em;
  1041. left: 0.5em;
  1042. position: absolute;
  1043. opacity: 0;
  1044. }
  1045. .ujs-btn-common {
  1046. width: 33px;
  1047. height: 33px;
  1048. border-radius: 0.3em;
  1049. top: 0;
  1050. position: absolute;
  1051. border: 1px solid transparent;
  1052. border-color: var(--ujs-gray);
  1053. ${settings.addBorder ? "border: 2px solid white;" : "border-color: var(--ujs-gray);"}
  1054. }
  1055. .ujs-not-downloaded .ujs-btn-background {
  1056. background: var(--ujs-red);
  1057. }
  1058.  
  1059. .ujs-already-downloaded .ujs-btn-background {
  1060. background: var(--ujs-blue);
  1061. }
  1062.  
  1063. .ujs-downloaded .ujs-btn-background {
  1064. background: var(--ujs-green);
  1065. }
  1066.  
  1067. .ujs-error .ujs-btn-background {
  1068. background: var(--ujs-error);
  1069. }
  1070.  
  1071. .ujs-btn-error-text {
  1072. display: flex;
  1073. align-items: center;
  1074. justify-content: center;
  1075. color: black;
  1076. font-size: 100%;
  1077. }`;
  1078. return css.slice(1);
  1079. }
  1080.  
  1081. /*
  1082. Features depend on:
  1083.  
  1084. addRequiredCSS: IMAGE
  1085.  
  1086. expandSpoilers: YES_VIEW_PROFILE, SHOW_NUDITY, VIEW
  1087. handleTitle: QUOTES, ON_TWITTER, TWITTER
  1088. hideSignUpSection: SIGNUP
  1089. hideTrends: TRENDS
  1090. hideTopicsToFollowInstantly: TOPICS_TO_FOLLOW,
  1091.  
  1092. hideTopicsToFollow: TOPICS_TO_FOLLOW,
  1093.  
  1094. [unused]
  1095. hideAndMoveFooter: FOOTER
  1096. */
  1097.  
  1098. // --- Twitter.LangConstants --- //
  1099. function getLanguageConstants() { //todo: "de", "fr"
  1100. const defaultQuotes = [`"`, `"`];
  1101.  
  1102. const SUPPORTED_LANGUAGES = ["en", "ru", "es", "zh", "ja", ];
  1103.  
  1104. // texts
  1105. const VIEW = ["View", "Посмотреть", "Ver", "查看", "表示", ];
  1106. const YES_VIEW_PROFILE = ["Yes, view profile", "Да, посмотреть профиль", "Sí, ver perfil", "是,查看个人资料", "プロフィールを表示する", ];
  1107.  
  1108. const SHOW_NUDITY = ["Show", "Показать", "Mostrar", "显示", "表示", ];
  1109. // aria-label texts
  1110. const IMAGE = ["Image", "Изображение", "Imagen", "图像", "画像", ];
  1111. const SIGNUP = ["Sign up", "Зарегистрироваться", "Regístrate", "注册", "アカウント作成", ];
  1112. const TRENDS = ["Timeline: Trending now", "Лента: Актуальные темы", "Cronología: Tendencias del momento", "时间线:当前趋势", "タイムライン: トレンド", ];
  1113. const TOPICS_TO_FOLLOW = ["Timeline: ", "Лента: ", "Cronología: ", "时间线:", /*[1]*/ "タイムライン: ", /*[1]*/ ];
  1114. const WHO_TO_FOLLOW = ["Who to follow", "Кого читать", "A quién seguir", "推荐关注", "おすすめユーザー" ];
  1115. const FOOTER = ["Footer", "Нижний колонтитул", "Pie de página", "页脚", "フッター", ];
  1116. // *1 — it's a suggestion, need to recheck. But I can't find a page where I can check it. Was it deleted?
  1117.  
  1118. // document.title "{AUTHOR}{ON_TWITTER} {QUOTES[0]}{TEXT}{QUOTES[1]} / {TWITTER}"
  1119. const QUOTES = [defaultQuotes, [`«`, `»`], defaultQuotes, defaultQuotes, [`「`, `」`], ];
  1120. const ON_TWITTER = [" on Twitter:", " в Твиттере:", " en Twitter:", " 在 Twitter:", "さんはTwitterを使っています", ];
  1121. const TWITTER = ["Twitter", "Твиттер", "Twitter", "Twitter", "Twitter", ];
  1122.  
  1123. const lang = document.querySelector("html").getAttribute("lang");
  1124. const langIndex = SUPPORTED_LANGUAGES.indexOf(lang);
  1125.  
  1126. return {
  1127. SUPPORTED_LANGUAGES,
  1128. VIEW: VIEW[langIndex],
  1129. YES_VIEW_PROFILE: YES_VIEW_PROFILE[langIndex],
  1130. SIGNUP: SIGNUP[langIndex],
  1131. TRENDS: TRENDS[langIndex],
  1132. TOPICS_TO_FOLLOW: TOPICS_TO_FOLLOW[langIndex],
  1133. WHO_TO_FOLLOW: WHO_TO_FOLLOW[langIndex],
  1134. FOOTER: FOOTER[langIndex],
  1135. QUOTES: QUOTES[langIndex],
  1136. ON_TWITTER: ON_TWITTER[langIndex],
  1137. TWITTER: TWITTER[langIndex],
  1138. IMAGE: IMAGE[langIndex],
  1139. SHOW_NUDITY: SHOW_NUDITY[langIndex],
  1140. }
  1141. }
  1142.  
  1143. // --- Twitter.Tweet --- //
  1144. function hoistTweet() {
  1145. class Tweet {
  1146. constructor({elem, url}) {
  1147. if (url) {
  1148. this.elem = null;
  1149. this.url = url;
  1150. } else {
  1151. this.elem = elem;
  1152. this.url = Tweet.getUrl(elem);
  1153. }
  1154. }
  1155.  
  1156. static of(innerElem) {
  1157. // Workaround for media from a quoted tweet
  1158. const url = innerElem.closest(`a[href^="/"]`)?.href;
  1159. if (url && url.includes("/status/")) {
  1160. return new Tweet({url});
  1161. }
  1162.  
  1163. const elem = innerElem.closest(`[data-testid="tweet"]`);
  1164. if (!elem) { // opened image
  1165. verbose && console.log("no-tweet elem");
  1166. }
  1167. return new Tweet({elem});
  1168. }
  1169.  
  1170. static getUrl(elem) {
  1171. if (!elem) { // if opened image
  1172. return location.href;
  1173. }
  1174.  
  1175. const tweetAnchor = [...elem.querySelectorAll("a")].find(el => {
  1176. return el.childNodes[0]?.nodeName === "TIME";
  1177. });
  1178.  
  1179. if (tweetAnchor) {
  1180. return tweetAnchor.href;
  1181. }
  1182. // else if selected tweet
  1183. return location.href;
  1184. }
  1185.  
  1186. get author() {
  1187. return this.url.match(/(?<=twitter\.com\/).+?(?=\/)/)?.[0];
  1188. }
  1189.  
  1190. get id() {
  1191. return this.url.match(/(?<=\/status\/)\d+/)?.[0];
  1192. }
  1193. }
  1194.  
  1195. return Tweet;
  1196. }
  1197.  
  1198. // --- Twitter.API --- //
  1199. function hoistAPI() {
  1200. class API {
  1201. static guestToken = getCookie("gt");
  1202. static csrfToken = getCookie("ct0"); // todo: lazy — not available at the first run
  1203. // Guest/Suspended account Bearer token
  1204. static guestAuthorization = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
  1205.  
  1206. // Seems to be outdated at 2022.05
  1207. static async _requestBearerToken() {
  1208. const scriptSrc = [...document.querySelectorAll("script")]
  1209. .find(el => el.src.match(/https:\/\/abs\.twimg\.com\/responsive-web\/client-web\/main[\w.]*\.js/)).src;
  1210.  
  1211. let text;
  1212. try {
  1213. text = await (await fetch(scriptSrc)).text();
  1214. } catch (e) {
  1215. console.error(e, scriptSrc);
  1216. throw e;
  1217. }
  1218.  
  1219. const authorizationKey = text.match(/(?<=")AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D.+?(?=")/)[0];
  1220. const authorization = `Bearer ${authorizationKey}`;
  1221.  
  1222. return authorization;
  1223. }
  1224.  
  1225. static async getAuthorization() {
  1226. if (!API.authorization) {
  1227. API.authorization = await API._requestBearerToken();
  1228. }
  1229. return API.authorization;
  1230. }
  1231.  
  1232. static async apiRequest(url) {
  1233. const _url = url.toString();
  1234. verbose && console.log("[ujs][apiRequest]", _url);
  1235.  
  1236. // Hm... it is always the same. Even for a logged user.
  1237. // const authorization = API.guestToken ? API.guestAuthorization : await API.getAuthorization();
  1238. const authorization = API.guestAuthorization;
  1239.  
  1240. // for debug
  1241. verbose && sessionStorage.setItem("guestAuthorization", API.guestAuthorization);
  1242. verbose && sessionStorage.setItem("authorization", API.authorization);
  1243. verbose && sessionStorage.setItem("x-csrf-token", API.csrfToken);
  1244. verbose && sessionStorage.setItem("x-guest-token", API.guestToken);
  1245.  
  1246. const headers = new Headers({
  1247. authorization,
  1248. "x-csrf-token": API.csrfToken,
  1249. "x-twitter-client-language": "en",
  1250. "x-twitter-active-user": "yes"
  1251. });
  1252. if (API.guestToken) {
  1253. headers.append("x-guest-token", API.guestToken);
  1254. } else { // may be skipped
  1255. headers.append("x-twitter-auth-type", "OAuth2Session");
  1256. }
  1257.  
  1258. let json;
  1259. try {
  1260. const response = await fetch(_url, {headers});
  1261. json = await response.json();
  1262. } catch (e) {
  1263. console.error(e, _url);
  1264. throw e;
  1265. }
  1266.  
  1267. verbose && console.log("[ujs][apiRequest]", JSON.stringify(json, null, " "));
  1268. // 429 - [{code: 88, message: "Rate limit exceeded"}] — for suspended accounts
  1269.  
  1270. return json;
  1271. }
  1272.  
  1273. // @return {bitrate, content_type, url, vidNumber}
  1274. static async getVideoInfo(tweetId, screenName, posterUrl) {
  1275. // const url = new URL(`https://api.twitter.com/2/timeline/conversation/${tweetId}.json`); // only for suspended/anon
  1276. const url = new URL(`https://twitter.com/i/api/2/timeline/conversation/${tweetId}.json`);
  1277. url.searchParams.set("tweet_mode", "extended");
  1278.  
  1279. const json = await API.apiRequest(url);
  1280. let tweetData = json.globalObjects.tweets[tweetId];
  1281.  
  1282. if (tweetData.quoted_status_id_str) {
  1283. tweetId = tweetData.quoted_status_id_str;
  1284. const userIdStr = json.globalObjects.tweets[tweetId].user_id_str;
  1285. screenName = json.globalObjects.users[userIdStr].screen_name;
  1286. tweetData = json.globalObjects.tweets[tweetId];
  1287. }
  1288.  
  1289. // types: "photo", "video", "animated_gif"
  1290. let vidNumber = tweetData.extended_entities.media
  1291. .filter(e => e.type !== "photo")
  1292. .findIndex(e => e.media_url_https === posterUrl);
  1293.  
  1294. let mediaIndex = tweetData.extended_entities.media
  1295. .findIndex(e => e.media_url_https === posterUrl);
  1296.  
  1297. if (vidNumber === -1 || mediaIndex === -1) {
  1298. verbose && console.log("[ujs][warning]: vidNumber === -1 || mediaIndex === -1");
  1299. vidNumber = 0;
  1300. mediaIndex = 0;
  1301. }
  1302. const videoVariants = tweetData.extended_entities.media[mediaIndex].video_info.variants;
  1303. verbose && console.log("[getVideoInfo]", videoVariants);
  1304.  
  1305. const video = videoVariants
  1306. .filter(el => el.bitrate !== undefined) // if content_type: "application/x-mpegURL" // .m3u8
  1307. .reduce((acc, cur) => cur.bitrate > acc.bitrate ? cur : acc);
  1308.  
  1309. if (!video) {
  1310. throw new Error("No video URL");
  1311. }
  1312.  
  1313. return {video, tweetId, screenName, vidNumber};
  1314. }
  1315.  
  1316. static async getUserInfo(username) {
  1317. const qHash = "Bhlf1dYJ3bYCKmLfeEQ31A"; // todo: change
  1318. const variables = JSON.stringify({
  1319. "screen_name": username,
  1320. "withSafetyModeUserFields": true,
  1321. "withSuperFollowsUserFields": true
  1322. });
  1323. const url = `https://twitter.com/i/api/graphql/${qHash}/UserByScreenName?variables=${encodeURIComponent(variables)}`;
  1324. const json = await API.apiRequest(url);
  1325. verbose && console.log("[getUserInfo]", json);
  1326. return json.data.user.result.legacy.entities.url?.urls[0].expanded_url;
  1327. }
  1328. }
  1329.  
  1330. return API;
  1331. }
  1332.  
  1333. // ---------------------------------------------------------------------------------------------------------------------
  1334. // ---------------------------------------------------------------------------------------------------------------------
  1335. // --- Common Utils --- //
  1336.  
  1337. // --- LocalStorage util class --- //
  1338. function hoistLS(settings = {}) {
  1339. const {
  1340. verbose, // debug "messages" in the document.title
  1341. } = settings;
  1342.  
  1343. class LS {
  1344. constructor(name) {
  1345. this.name = name;
  1346. }
  1347. getItem(defaultValue) {
  1348. return LS.getItem(this.name, defaultValue);
  1349. }
  1350. setItem(value) {
  1351. LS.setItem(this.name, value);
  1352. }
  1353. removeItem() {
  1354. LS.removeItem(this.name);
  1355. }
  1356. async pushItem(value) { // array method
  1357. await LS.pushItem(this.name, value);
  1358. }
  1359. async popItem(value) { // array method
  1360. await LS.popItem(this.name, value);
  1361. }
  1362. hasItem(value) { // array method
  1363. return LS.hasItem(this.name, value);
  1364. }
  1365.  
  1366. static getItem(name, defaultValue) {
  1367. const value = localStorage.getItem(name);
  1368. if (value === undefined) {
  1369. return undefined;
  1370. }
  1371. if (value === null) { // when there is no such item
  1372. LS.setItem(name, defaultValue);
  1373. return defaultValue;
  1374. }
  1375. return JSON.parse(value);
  1376. }
  1377. static setItem(name, value) {
  1378. localStorage.setItem(name, JSON.stringify(value));
  1379. }
  1380. static removeItem(name) {
  1381. localStorage.removeItem(name);
  1382. }
  1383. static async pushItem(name, value) {
  1384. const array = LS.getItem(name, []);
  1385. array.push(value);
  1386. LS.setItem(name, array);
  1387.  
  1388. //sanity check
  1389. await sleep(50);
  1390. if (!LS.hasItem(name, value)) {
  1391. if (verbose) {
  1392. document.title = "🟥" + document.title;
  1393. }
  1394. await LS.pushItem(name, value);
  1395. }
  1396. }
  1397. static async popItem(name, value) { // remove from an array
  1398. const array = LS.getItem(name, []);
  1399. if (array.indexOf(value) !== -1) {
  1400. array.splice(array.indexOf(value), 1);
  1401. LS.setItem(name, array);
  1402.  
  1403. //sanity check
  1404. await sleep(50);
  1405. if (LS.hasItem(name, value)) {
  1406. if (verbose) {
  1407. document.title = "🟨" + document.title;
  1408. }
  1409. await LS.popItem(name, value);
  1410. }
  1411. }
  1412. }
  1413. static hasItem(name, value) { // has in array
  1414. const array = LS.getItem(name, []);
  1415. return array.indexOf(value) !== -1;
  1416. }
  1417. }
  1418.  
  1419. return LS;
  1420. }
  1421.  
  1422. // --- Just groups them in a function for the convenient code looking --- //
  1423. function getUtils({verbose}) {
  1424. function sleep(time) {
  1425. return new Promise(resolve => setTimeout(resolve, time));
  1426. }
  1427.  
  1428. async function fetchResource(url, onProgress = props => console.log(props)) {
  1429. try {
  1430. let response = await fetch(url, {
  1431. // cache: "force-cache",
  1432. });
  1433. const lastModifiedDateSeconds = response.headers.get("last-modified");
  1434. const contentType = response.headers.get("content-type");
  1435.  
  1436. const lastModifiedDate = dateToDayDateString(lastModifiedDateSeconds);
  1437. const extension = contentType ? extensionFromMime(contentType) : null;
  1438.  
  1439. if (onProgress) {
  1440. response = responseProgressProxy(response, onProgress);
  1441. }
  1442.  
  1443. const blob = await response.blob();
  1444.  
  1445. // https://pbs.twimg.com/media/AbcdEFgijKL01_9?format=jpg&name=orig -> AbcdEFgijKL01_9
  1446. // https://pbs.twimg.com/ext_tw_video_thumb/1234567890123456789/pu/img/Ab1cd2345EFgijKL.jpg?name=orig -> Ab1cd2345EFgijKL.jpg
  1447. // https://video.twimg.com/ext_tw_video/1234567890123456789/pu/vid/946x720/Ab1cd2345EFgijKL.mp4?tag=10 -> Ab1cd2345EFgijKL.mp4
  1448. const _url = new URL(url);
  1449. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  1450.  
  1451. const {name} = filename.match(/(?<name>^[^.]+)/).groups;
  1452. return {blob, lastModifiedDate, contentType, extension, name};
  1453. } catch (error) {
  1454. verbose && console.error("[fetchResource]", url, error);
  1455. throw error;
  1456. }
  1457. }
  1458.  
  1459. function extensionFromMime(mimeType) {
  1460. let extension = mimeType.match(/(?<=\/).+/)[0];
  1461. extension = extension === "jpeg" ? "jpg" : extension;
  1462. return extension;
  1463. }
  1464.  
  1465. // the original download url will be posted as hash of the blob url, so you can check it in the download manager's history
  1466. function downloadBlob(blob, name, url) {
  1467. const anchor = document.createElement("a");
  1468. anchor.setAttribute("download", name || "");
  1469. const blobUrl = URL.createObjectURL(blob);
  1470. anchor.href = blobUrl + (url ? ("#" + url) : "");
  1471. anchor.click();
  1472. setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
  1473. }
  1474.  
  1475. // "Sun, 10 Jan 2021 22:22:22 GMT" -> "2021.01.10"
  1476. function dateToDayDateString(dateValue, utc = true) {
  1477. const _date = new Date(dateValue);
  1478. function pad(str) {
  1479. return str.toString().padStart(2, "0");
  1480. }
  1481. const _utc = utc ? "UTC" : "";
  1482. const year = _date[`get${_utc}FullYear`]();
  1483. const month = _date[`get${_utc}Month`]() + 1;
  1484. const date = _date[`get${_utc}Date`]();
  1485.  
  1486. return year + "." + pad(month) + "." + pad(date);
  1487. }
  1488.  
  1489. function addCSS(css) {
  1490. const styleElem = document.createElement("style");
  1491. styleElem.textContent = css;
  1492. document.body.append(styleElem);
  1493. return styleElem;
  1494. }
  1495.  
  1496. function getCookie(name) {
  1497. verbose && console.log(document.cookie);
  1498. const regExp = new RegExp(`(?<=${name}=)[^;]+`);
  1499. return document.cookie.match(regExp)?.[0];
  1500. }
  1501.  
  1502. function throttle(runnable, time = 50) {
  1503. let waiting = false;
  1504. let queued = false;
  1505. let context;
  1506. let args;
  1507.  
  1508. return function() {
  1509. if (!waiting) {
  1510. waiting = true;
  1511. setTimeout(function() {
  1512. if (queued) {
  1513. runnable.apply(context, args);
  1514. context = args = undefined;
  1515. }
  1516. waiting = queued = false;
  1517. }, time);
  1518. return runnable.apply(this, arguments);
  1519. } else {
  1520. queued = true;
  1521. context = this;
  1522. args = arguments;
  1523. }
  1524. }
  1525. }
  1526.  
  1527. function throttleWithResult(func, time = 50) {
  1528. let waiting = false;
  1529. let args;
  1530. let context;
  1531. let timeout;
  1532. let promise;
  1533.  
  1534. return async function() {
  1535. if (!waiting) {
  1536. waiting = true;
  1537. timeout = new Promise(async resolve => {
  1538. await sleep(time);
  1539. waiting = false;
  1540. resolve();
  1541. });
  1542. return func.apply(this, arguments);
  1543. } else {
  1544. args = arguments;
  1545. context = this;
  1546. }
  1547.  
  1548. if (!promise) {
  1549. promise = new Promise(async resolve => {
  1550. await timeout;
  1551. const result = func.apply(context, args);
  1552. args = context = promise = undefined;
  1553. resolve(result);
  1554. });
  1555. }
  1556. return promise;
  1557. }
  1558. }
  1559.  
  1560. function xpath(path, node = document) {
  1561. let xPathResult = document.evaluate(path, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1562. return xPathResult.singleNodeValue;
  1563. }
  1564. function xpathAll(path, node = document) {
  1565. let xPathResult = document.evaluate(path, node, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  1566. const nodes = [];
  1567. try {
  1568. let node = xPathResult.iterateNext();
  1569.  
  1570. while (node) {
  1571. nodes.push(node);
  1572. node = xPathResult.iterateNext();
  1573. }
  1574. return nodes;
  1575. } catch (e) {
  1576. // todo need investigate it
  1577. console.error(e); // "The document has mutated since the result was returned."
  1578. return [];
  1579. }
  1580. }
  1581.  
  1582. const identityContentEncodings = new Set([null, "identity", "no encoding"]);
  1583. function getOnProgressProps(response) {
  1584. const {headers, status, statusText, url, redirected, ok} = response;
  1585. const isIdentity = identityContentEncodings.has(headers.get("Content-Encoding"));
  1586. const compressed = !isIdentity;
  1587. const _contentLength = parseInt(headers.get("Content-Length")); // `get()` returns `null` if no header present
  1588. const contentLength = isNaN(_contentLength) ? null : _contentLength;
  1589. const lengthComputable = isIdentity && _contentLength !== null;
  1590.  
  1591. // Original XHR behaviour; in TM it equals to `contentLength`, or `-1` if `contentLength` is `null` (and `0`?).
  1592. const total = lengthComputable ? contentLength : 0;
  1593. const gmTotal = contentLength > 0 ? contentLength : -1; // Like `total` is in TM and GM.
  1594.  
  1595. return {
  1596. gmTotal, total, lengthComputable,
  1597. compressed, contentLength,
  1598. headers, status, statusText, url, redirected, ok
  1599. };
  1600. }
  1601. function responseProgressProxy(response, onProgress) {
  1602. const onProgressProps = getOnProgressProps(response);
  1603. let loaded = 0;
  1604. const reader = response.body.getReader();
  1605. const readableStream = new ReadableStream({
  1606. async start(controller) {
  1607. while (true) {
  1608. const {done, /** @type {Uint8Array} */ value} = await reader.read();
  1609. if (done) {
  1610. break;
  1611. }
  1612. loaded += value.length;
  1613. try {
  1614. onProgress({loaded, ...onProgressProps});
  1615. } catch (e) {
  1616. console.error("[onProgress]:", e);
  1617. }
  1618. controller.enqueue(value);
  1619. }
  1620. controller.close();
  1621. reader.releaseLock();
  1622. },
  1623. cancel() {
  1624. void reader.cancel();
  1625. }
  1626. });
  1627. return new ResponseEx(readableStream, response);
  1628. }
  1629. class ResponseEx extends Response {
  1630. [Symbol.toStringTag] = "ResponseEx";
  1631.  
  1632. constructor(body, {headers, status, statusText, url, redirected, type}) {
  1633. super(body, {
  1634. status, statusText, headers: {
  1635. ...headers,
  1636. "content-type": headers.get("content-type").split("; ")[0] // Fixes Blob type ("text/html; charset=UTF-8") in TM
  1637. }
  1638. });
  1639. this._type = type;
  1640. this._url = url;
  1641. this._redirected = redirected;
  1642. this._headers = headers; // `HeadersLike` is more user-friendly for debug than the original `Headers` object
  1643. }
  1644. get redirected() { return this._redirected; }
  1645. get url() { return this._url; }
  1646. get type() { return this._type || "basic"; }
  1647. /** @returns {HeadersLike} */
  1648. get headers() { return this._headers; }
  1649. }
  1650.  
  1651. return {
  1652. sleep, fetchResource, extensionFromMime, downloadBlob, dateToDayDateString,
  1653. addCSS,
  1654. getCookie,
  1655. throttle, throttleWithResult,
  1656. xpath, xpathAll,
  1657. responseProgressProxy,
  1658. }
  1659. }
  1660.  
  1661. // ---------------------------------------------------------------------------------------------------------------------
  1662. // ---------------------------------------------------------------------------------------------------------------------