Twitter Click'n'Save

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

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

  1. // ==UserScript==
  2. // @name Twitter Click'n'Save
  3. // @version 0.6.1-2022.04.10
  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.  
  20. const settings = loadSettings();
  21.  
  22. function loadSettings() {
  23. const defaultSettings = {
  24. hideTrends: true,
  25. hideSignUpSection: true,
  26. hideTopicsToFollow: false,
  27. hideTopicsToFollowInstantly: false,
  28. hideSignUpBottomBarAndMessages: true,
  29. doNotPlayVideosAutomatically: false,
  30. goFromMobileToMainSite: false,
  31.  
  32. highlightVisitedLinks: true,
  33. expandSpoilers: true,
  34.  
  35. directLinks: true,
  36. handleTitle: true,
  37.  
  38. imagesHandler: true,
  39. videoHandler: true,
  40. addRequiredCSS: true,
  41. preventBlinking: true,
  42. };
  43.  
  44. let savedSettings;
  45. try {
  46. savedSettings = JSON.parse(localStorage.getItem("ujs-click-n-save-settings")) || {};
  47. } catch (e) {
  48. console.error("[ujs]", e);
  49. localStorage.removeItem("ujs-click-n-save-settings");
  50. savedSettings = {};
  51. }
  52. savedSettings = Object.assign(defaultSettings, savedSettings);
  53. return savedSettings;
  54. }
  55. function showSettings() {
  56. closeSetting();
  57. if (window.scrollY > 0) {
  58. document.querySelector("html").classList.add("ujs-scroll-initial");
  59. document.body.classList.add("ujs-scrollbar-width-margin-right");
  60. }
  61. document.body.classList.add("ujs-no-scroll");
  62.  
  63. const modalWrapperStyle = `
  64. width: 100%;
  65. height: 100%;
  66. position: fixed;
  67. display: flex;
  68. justify-content: center;
  69. align-items: center;
  70. z-index: 99999;
  71. backdrop-filter: blur(4px);
  72. background-color: rgba(255, 255, 255, 0.5);
  73. `;
  74. const modalSettingsStyle = `
  75. background-color: white;
  76. min-width: 320px;
  77. min-height: 320px;
  78. border: 1px solid darkgray;
  79. padding: 8px;
  80. box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  81. `;
  82. const s = settings;
  83. document.body.insertAdjacentHTML("afterbegin", `
  84. <div class="ujs-modal-wrapper" style="${modalWrapperStyle}">
  85. <div class="ujs-modal-settings" style="${modalSettingsStyle}">
  86. <fieldset>
  87. <legend>Optional</legend>
  88. <label><input type="checkbox" ${s.hideTrends ? "checked" : ""} name="hideTrends">Hide <b>Trends</b> (in the right column)*<br/></label>
  89. <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>
  90. <label><input type="checkbox" ${s.hideSignUpBottomBarAndMessages ? "checked" : ""} name="hideSignUpBottomBarAndMessages">Hide <b>Sign Up Bar</b> and <b>Messages</b> (in the bottom)<br/></label>
  91. <label hidden><input type="checkbox" ${s.doNotPlayVideosAutomatically ? "checked" : ""} name="doNotPlayVideosAutomatically">Do <i>Not</i> Play Videos Automatically</b><br/></label>
  92. <label hidden><input type="checkbox" ${s.goFromMobileToMainSite ? "checked" : ""} name="goFromMobileToMainSite">Redirect from Mobile version (beta)<br/></label>
  93. </fieldset>
  94. <fieldset>
  95. <legend>Recommended</legend>
  96. <label><input type="checkbox" ${s.highlightVisitedLinks ? "checked" : ""} name="highlightVisitedLinks">Highlight Visited Links<br/></label>
  97. <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>
  98. </fieldset>
  99. <fieldset>
  100. <legend>Highly Recommended</legend>
  101. <label><input type="checkbox" ${s.directLinks ? "checked" : ""} name="directLinks">Direct Links</label><br/>
  102. <label><input type="checkbox" ${s.handleTitle ? "checked" : ""} name="handleTitle">Enchance Title*<br/></label>
  103. </fieldset>
  104. <fieldset>
  105. <legend>Main</legend>
  106. <label><input type="checkbox" ${s.imagesHandler ? "checked" : ""} name="imagesHandler">Image Download Button<br/></label>
  107. <label><input type="checkbox" ${s.videoHandler ? "checked" : ""} name="videoHandler">Video Download Button<br/></label>
  108. <label title="Prevent the tweet backgroubd blinking on the button click"><input type="checkbox" ${s.preventBlinking ? "checked" : ""} name="preventBlinking">Prevent blinking on click<br/></label>
  109. <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 -->
  110. </fieldset>
  111. <fieldset>
  112. <legend title="Outdated due to Twitter's updates, impossible to reimplement">Outdated</legend>
  113. <strike>
  114. <label><input type="checkbox" ${s.hideTopicsToFollow ? "checked" : ""} name="hideTopicsToFollow">Hide <b>Topics To Follow</b> (in the right column)*<br/></label>
  115. <label hidden><input type="checkbox" ${s.hideTopicsToFollowInstantly ? "checked" : ""} name="hideTopicsToFollowInstantly">Hide <b>Topics To Follow</b> Instantly*<br/></label>
  116. </strike>
  117. </fieldset>
  118. <hr>
  119. <div style="display: flex; justify-content: space-around;">
  120. <button class="ujs-save-setting-button" style="padding: 5px">Save Settings</button>
  121. <button class="ujs-close-setting-button" style="padding: 5px">Close Settings</button>
  122. </div>
  123. <hr>
  124. <h4 style="margin: 0; padding-left: 8px; color: #444;">Notes:</h4>
  125. <ul style="margin: 2px; padding-left: 16px; color: #444;">
  126. <li>Click on <b>Save Settings</b> and reload the page to apply changes.</li>
  127. <li><b>*</b>-marked settings are language dependent. Currently, the follow languages are supported:<br/> "en", "ru", "es", "zh", "ja".</li>
  128. <li hidden>The extension downloads only from twitter.com, not from <b>mobile</b>.twitter.com</li>
  129. </ul>
  130. </div>
  131. </div>`);
  132.  
  133. document.querySelector("body > .ujs-modal-wrapper .ujs-save-setting-button").addEventListener("click", saveSetting);
  134. document.querySelector("body > .ujs-modal-wrapper .ujs-close-setting-button").addEventListener("click", closeSetting);
  135.  
  136. function saveSetting() {
  137. const entries = [...document.querySelectorAll("body > .ujs-modal-wrapper input[type=checkbox]")]
  138. .map(checkbox => [checkbox.name, checkbox.checked]);
  139. const settings = Object.fromEntries(entries);
  140. settings.hideTopicsToFollowInstantly = settings.hideTopicsToFollow;
  141. // console.log("[ujs]", settings);
  142. localStorage.setItem("ujs-click-n-save-settings", JSON.stringify(settings));
  143. }
  144.  
  145. function closeSetting() {
  146. document.body.classList.remove("ujs-no-scroll");
  147. document.body.classList.remove("ujs-scrollbar-width-margin-right");
  148. document.querySelector("html").classList.remove("ujs-scroll-initial");
  149. document.querySelector("body > .ujs-modal-wrapper")?.remove();
  150. }
  151. }
  152.  
  153.  
  154.  
  155. // ---------------------------------------------------------------------------------------------------------------------
  156. // ---------------------------------------------------------------------------------------------------------------------
  157.  
  158. // --- Features to execute --- //
  159. const doNotPlayVideosAutomatically = false;
  160.  
  161. function execFeaturesOnce() {
  162. settings.goFromMobileToMainSite && Features.goFromMobileToMainSite();
  163. settings.addRequiredCSS && Features.addRequiredCSS();
  164. settings.hideSignUpBottomBarAndMessages && Features.hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically);
  165. settings.hideTrends && Features.hideTrends();
  166. settings.highlightVisitedLinks && Features.highlightVisitedLinks();
  167. settings.hideTopicsToFollowInstantly && Features.hideTopicsToFollowInstantly();
  168. }
  169. function execFeaturesImmediately() {
  170. settings.expandSpoilers && Features.expandSpoilers();
  171. }
  172. function execFeatures() {
  173. settings.imagesHandler && Features.imagesHandler(settings.preventBlinking);
  174. settings.videoHandler && Features.videoHandler(settings.preventBlinking);
  175. settings.expandSpoilers && Features.expandSpoilers();
  176. settings.hideSignUpSection && Features.hideSignUpSection();
  177. settings.hideTopicsToFollow && Features.hideTopicsToFollow();
  178. settings.directLinks && Features.directLinks();
  179. settings.handleTitle && Features.handleTitle();
  180. }
  181.  
  182. // ---------------------------------------------------------------------------------------------------------------------
  183. // ---------------------------------------------------------------------------------------------------------------------
  184.  
  185.  
  186. // --- For debug --- //
  187. const verbose = false;
  188. if (verbose) {
  189. console.log(settings);
  190. // showSettings();
  191. }
  192.  
  193.  
  194. // --- [VM/GM + Firefox ~90+ + Enabled "Strict Tracking Protection"] fix --- //
  195. const fetch = (globalThis.wrappedJSObject && typeof globalThis.wrappedJSObject.fetch === "function") ? function(resource, init) {
  196. verbose && console.log("wrappedJSObject.fetch", resource, init);
  197.  
  198. if (init.headers instanceof Headers) {
  199. // Since `Headers` are not allowed for structured cloning.
  200. init.headers = Object.fromEntries(init.headers.entries());
  201. }
  202.  
  203. return globalThis.wrappedJSObject.fetch(cloneInto(resource, document), cloneInto(init, document));
  204. } : globalThis.fetch;
  205.  
  206.  
  207. // --- "Imports" --- //
  208. const {
  209. sleep, fetchResource, download,
  210. addCSS,
  211. getCookie,
  212. throttle,
  213. xpath, xpathAll,
  214. getNearestElementByType, getParentWithSiblingDataset,
  215. } = getUtils({verbose});
  216. const LS = hoistLS({verbose});
  217.  
  218. const API = hoistAPI();
  219. const Tweet = hoistTweet();
  220. const Features = hoistFeatures();
  221. const I18N = getLanguageConstants();
  222.  
  223.  
  224. // --- That to use for the image history --- //
  225. // "TWEET_ID" or "IMAGE_NAME"
  226. const imagesHistoryBy = LS.getItem("ujs-images-history-by", "IMAGE_NAME");
  227. // With "TWEET_ID" downloading of 1 image of 4 will mark all 4 images as "already downloaded"
  228. // on the next time when the tweet will appear.
  229. // "IMAGE_NAME" will count each image of a tweet, but it will take more data to store.
  230.  
  231.  
  232. // ---------------------------------------------------------------------------------------------------------------------
  233. // ---------------------------------------------------------------------------------------------------------------------
  234. // --- Script runner --- //
  235.  
  236. (function starter(feats) {
  237. const {once, onChangeImmediate, onChange} = feats;
  238.  
  239. once();
  240. onChangeImmediate();
  241. const onChangeThrottled = throttle(onChange, 250);
  242. onChangeThrottled();
  243.  
  244. const targetNode = document.querySelector("body");
  245. const observerOptions = {
  246. subtree: true,
  247. childList: true,
  248. };
  249. const observer = new MutationObserver(callback);
  250. observer.observe(targetNode, observerOptions);
  251.  
  252. function callback(mutationList, observer) {
  253. verbose && console.log(mutationList);
  254. onChangeImmediate();
  255. onChangeThrottled();
  256. }
  257. })({
  258. once: execFeaturesOnce,
  259. onChangeImmediate: execFeaturesImmediately,
  260. onChange: execFeatures
  261. });
  262.  
  263. // ---------------------------------------------------------------------------------------------------------------------
  264. // ---------------------------------------------------------------------------------------------------------------------
  265. // --- Twitter Specific code --- //
  266.  
  267.  
  268. const downloadedImages = new LS("ujs-twitter-downloaded-images-names");
  269. const downloadedImageTweetIds = new LS("ujs-twitter-downloaded-image-tweet-ids");
  270. const downloadedVideoTweetIds = new LS("ujs-twitter-downloaded-video-tweet-ids");
  271.  
  272. // --- Twitter.Features --- //
  273. function hoistFeatures() {
  274. class Features {
  275. static goFromMobileToMainSite() {
  276. if (location.href.startsWith("https://mobile.twitter.com/")) {
  277. location.href = location.href.replace("https://mobile.twitter.com/", "https://twitter.com/");
  278. }
  279. // TODO: add #redirected, remove by timer // to prevent a potential infinity loop
  280. }
  281. static _ImageHistory = class {
  282. static getImageNameFromUrl(url) {
  283. const _url = new URL(url);
  284. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  285. return filename.match(/^[^\.]+/)[0]; // remove extension
  286. }
  287. static isDownloaded({id, url}) {
  288. if (imagesHistoryBy === "TWEET_ID") {
  289. return downloadedImageTweetIds.hasItem(id);
  290. } else if (imagesHistoryBy === "IMAGE_NAME") {
  291. const name = Features._ImageHistory.getImageNameFromUrl(url);
  292. return downloadedImages.hasItem(name);
  293. }
  294. }
  295. static async markDownloaded({id, url}) {
  296. if (imagesHistoryBy === "TWEET_ID") {
  297. await downloadedImageTweetIds.pushItem(id);
  298. } else if (imagesHistoryBy === "IMAGE_NAME") {
  299. const name = Features._ImageHistory.getImageNameFromUrl(url);
  300. await downloadedImages.pushItem(name);
  301. }
  302. }
  303. }
  304. static async imagesHandler(preventBlinking) {
  305. verbose && console.log("[ujs-cns][imagesHandler]");
  306. const images = document.querySelectorAll("img");
  307. for (const img of images) {
  308.  
  309. if (img.width < 150 || img.dataset.handled) {
  310. continue;
  311. }
  312. verbose && console.log(img, img.width);
  313.  
  314. img.dataset.handled = "true";
  315.  
  316. const btn = document.createElement("div");
  317. btn.classList.add("ujs-btn-download");
  318. btn.dataset.url = img.src;
  319.  
  320. btn.addEventListener("click", Features._imageClickHandler);
  321.  
  322. let anchor = getNearestElementByType(img, "a");
  323. // if an image is _opened_ "https://twitter.com/UserName/status/1234567890123456789/photo/1" [fake-url]
  324. if (!anchor) {
  325. anchor = img.parentNode;
  326. }
  327. anchor.append(btn);
  328. if (preventBlinking) {
  329. Features._preventBlinking(btn);
  330. }
  331.  
  332. const downloaded = Features._ImageHistory.isDownloaded({
  333. id: Tweet.of(btn).id,
  334. url: btn.dataset.url
  335. });
  336. if (downloaded) {
  337. btn.classList.add("ujs-already-downloaded");
  338. }
  339. }
  340. }
  341. static hasBlinkListenerWeakSet;
  342. static _preventBlinking(clickBtnElem) {
  343. const weakSet = Features.hasBlinkListenerWeakSet || (Features.hasBlinkListenerWeakSet = new WeakSet());
  344. let wrapper;
  345. clickBtnElem.addEventListener("mouseenter", () => {
  346. if (!weakSet.has(clickBtnElem)) {
  347. wrapper = Features._preventBlinkingHandler(clickBtnElem);
  348. weakSet.add(clickBtnElem);
  349. }
  350. });
  351. clickBtnElem.addEventListener("mouseleave", () => {
  352. if (wrapper.observer && wrapper.observer.disconnect) { // Just in case
  353. weakSet.delete(clickBtnElem);
  354. wrapper.observer.disconnect();
  355. }
  356. });
  357. }
  358. static _preventBlinkingHandler(clickBtnElem) {
  359. let targetNode = clickBtnElem.closest("[aria-labelledby]");
  360. if (!targetNode) {
  361. return;
  362. }
  363. let config = {attributes: true, subtree: true, attributeOldValue: true};
  364. const wrapper = {};
  365. wrapper.observer = new MutationObserver(callback);
  366. wrapper.observer.observe(targetNode, config);
  367. function callback(mutationsList, observer) {
  368. for (const mutation of mutationsList) {
  369. if (mutation.type === "attributes" && mutation.attributeName === "class") {
  370. if (mutation.target.classList.contains("ujs-btn-download")) {
  371. return;
  372. }
  373. // Don't allow to change classList
  374. mutation.target.className = mutation.oldValue;
  375. // Recreate, to prevent an infinity loop
  376. wrapper.observer.disconnect();
  377. wrapper.observer = new MutationObserver(callback);
  378. wrapper.observer.observe(targetNode, config);
  379. }
  380. }
  381. }
  382. return wrapper;
  383. }
  384. static async _imageClickHandler(event) {
  385. event.preventDefault();
  386. event.stopImmediatePropagation();
  387.  
  388. const btn = event.currentTarget;
  389. const url = handleImgUrl(btn.dataset.url);
  390. verbose && console.log(url);
  391.  
  392. function handleImgUrl(url) {
  393. const urlObj = new URL(url);
  394. urlObj.searchParams.set("name", "orig");
  395. return urlObj.toString();
  396. }
  397.  
  398. const {id, author} = Tweet.of(btn);
  399. verbose && console.log(id, author);
  400.  
  401. async function safeFetchResource(url) {
  402. let fallbackUsed = false;
  403. retry:
  404. while (true) {
  405. try {
  406. return await fetchResource(url);
  407. } catch (e) {
  408. if (fallbackUsed) {
  409. throw "Fallback URL failed";
  410. }
  411. const _url = new URL(url);
  412. _url.searchParams.set("name", "4096x4096");
  413. url = _url.href;
  414. verbose && console.warn("[safeFetchResource] Fallback URL:", url);
  415. fallbackUsed = true;
  416. continue retry;
  417. }
  418. }
  419.  
  420. }
  421.  
  422. btn.classList.add("ujs-downloading");
  423. const {blob, lastModifiedDate, extension, name} = await safeFetchResource(url);
  424.  
  425. const filename = `[twitter] ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
  426. download(blob, filename, url);
  427.  
  428. const downloaded = btn.classList.contains("already-downloaded");
  429. if (!downloaded) {
  430. await Features._ImageHistory.markDownloaded({id, url});
  431. }
  432. btn.classList.remove("ujs-downloading");
  433. btn.classList.add("ujs-downloaded");
  434. }
  435.  
  436.  
  437. static async videoHandler(preventBlinking) {
  438. const videos = document.querySelectorAll("video");
  439.  
  440. for (const vid of videos) {
  441. if (vid.dataset.handled) {
  442. continue;
  443. }
  444. verbose && console.log(vid);
  445. vid.dataset.handled = "true";
  446.  
  447. const btn = document.createElement("div");
  448. btn.classList.add("ujs-btn-download");
  449. btn.classList.add("ujs-video");
  450. btn.addEventListener("click", Features._videoClickHandler);
  451.  
  452. let elem = vid.parentNode.parentNode.parentNode;
  453. elem.after(btn);
  454. if (preventBlinking) {
  455. Features._preventBlinking(btn);
  456. }
  457.  
  458. const id = Tweet.of(btn).id;
  459. const downloaded = downloadedVideoTweetIds.hasItem(id);
  460. if (downloaded) {
  461. btn.classList.add("ujs-already-downloaded");
  462. }
  463. }
  464. }
  465. static async _videoClickHandler(event) {
  466. event.preventDefault();
  467. event.stopImmediatePropagation();
  468.  
  469. const btn = event.currentTarget;
  470. const {id, author} = Tweet.of(btn);
  471. const video = await API.getVideoInfo(id); // {bitrate, content_type, url}
  472. verbose && console.log(video);
  473.  
  474. btn.classList.add("ujs-downloading");
  475. const url = video.url;
  476. const {blob, lastModifiedDate, extension, name} = await fetchResource(url);
  477.  
  478. const filename = `[twitter] ${author}—${lastModifiedDate}—${id}—${name}.${extension}`;
  479. download(blob, filename, url);
  480.  
  481. const downloaded = btn.classList.contains("ujs-already-downloaded");
  482. if (!downloaded) {
  483. await downloadedVideoTweetIds.pushItem(id);
  484. }
  485. btn.classList.remove("ujs-downloading");
  486. btn.classList.add("ujs-downloaded");
  487. }
  488.  
  489.  
  490. static addRequiredCSS() {
  491. addCSS(getUserScriptCSS());
  492. }
  493.  
  494. // it depends of `directLinks()` use only it after `directLinks()`
  495. static handleTitle(title) {
  496. if (!I18N.QUOTES) { // Unsupported lang, no QUOTES, ON_TWITTER, TWITTER constants
  497. return;
  498. }
  499. // if not a opened tweet
  500. if (!location.href.match(/twitter\.com\/[^\/]+\/status\/\d+/)) {
  501. return;
  502. }
  503.  
  504. let titleText = title || document.title;
  505. if (titleText === Features.lastHandledTitle) {
  506. return;
  507. }
  508. Features.originalTitle = titleText;
  509.  
  510. const [OPEN_QUOTE, CLOSE_QUOTE] = I18N.QUOTES;
  511. const urlsToReplace = [
  512. ...titleText.matchAll(new RegExp(`https:\\/\\/t\\.co\\/[^ ${CLOSE_QUOTE}]+`, "g"))
  513. ].map(el => el[0]);
  514. // the last one may be the URL to the tweet // or to an embedded shared URL
  515.  
  516. const map = new Map();
  517. const anchors = document.querySelectorAll(`a[data-redirect^="https://t.co/"]`);
  518. for (const anchor of anchors) {
  519. if (urlsToReplace.includes(anchor.dataset.redirect)) {
  520. map.set(anchor.dataset.redirect, anchor.href);
  521. }
  522. }
  523.  
  524. const lastUrl = urlsToReplace.slice(-1)[0];
  525. let lastUrlIsAttachment = false;
  526. let attachmentDescription = "";
  527. if (!map.has(lastUrl)) {
  528. const a = document.querySelector(`a[href="${lastUrl}?amp=1"]`);
  529. if (a) {
  530. lastUrlIsAttachment = true;
  531. attachmentDescription = document.querySelectorAll(`a[href="${lastUrl}?amp=1"]`)[1].innerText;
  532. attachmentDescription = attachmentDescription.replaceAll("\n", " — ");
  533. }
  534. }
  535.  
  536.  
  537. for (const [key, value] of map.entries()) {
  538. titleText = titleText.replaceAll(key, value + ` (${key})`);
  539. }
  540.  
  541. titleText = titleText.replace(new RegExp(`${I18N.ON_TWITTER}(?= ${OPEN_QUOTE})`), ":");
  542. titleText = titleText.replace(new RegExp(`(?<=${CLOSE_QUOTE}) \\\/ ${I18N.TWITTER}$`), "");
  543. if (!lastUrlIsAttachment) {
  544. const regExp = new RegExp(`(?<short> https:\\/\\/t\\.co\\/.{6,14})${CLOSE_QUOTE}$`);
  545. titleText = titleText.replace(regExp, (match, p1, p2, offset, string) => `${CLOSE_QUOTE} ${p1}`);
  546. } else {
  547. titleText = titleText.replace(lastUrl, `${lastUrl} (${attachmentDescription})`);
  548. }
  549. document.title = titleText; // Note: some characters will be removed automatically (`\n`, extra spaces)
  550. Features.lastHandledTitle = document.title;
  551. }
  552. static lastHandledTitle = "";
  553. static originalTitle = "";
  554.  
  555. static directLinks() {
  556. const anchors = xpathAll(`.//a[@dir="ltr" and child::span and not(@data-handled)]`);
  557. for (const anchor of anchors) {
  558. const redirectUrl = new URL(anchor.href);
  559. anchor.dataset.redirect = redirectUrl.origin + redirectUrl.pathname; // remove "?amp=1"
  560. anchor.dataset.handled = "true";
  561.  
  562. const nodes = xpathAll(`./span[text() != "…"]|./text()`, anchor);
  563. const url = nodes.map(node => node.textContent).join("");
  564. anchor.href = url;
  565. anchor.rel = "nofollow noopener noreferrer";
  566. }
  567. if (anchors.length) {
  568. Features.handleTitle(Features.originalTitle);
  569. }
  570. }
  571.  
  572. // Do NOT throttle it
  573. static expandSpoilers() {
  574. const main = document.querySelector("main[role=main]");
  575. if (!main) {
  576. return;
  577. }
  578. if (!I18N.YES_VIEW_PROFILE) { // Unsupported lang, no YES_VIEW_PROFILE, SHOW_NUDITY, VIEW constants
  579. return;
  580. }
  581.  
  582. const a = main.querySelectorAll("[data-testid=primaryColumn] [role=button]");
  583. if (a) {
  584. const elems = [...a];
  585. const button = elems.find(el => el.textContent === I18N.YES_VIEW_PROFILE);
  586. if (button) {
  587. button.click();
  588. }
  589. // "Content warning: Nudity"
  590. // "The Tweet author flagged this Tweet as showing sensitive content.""
  591. // "Show"
  592. const buttonShow = elems.find(el => el.textContent === I18N.SHOW_NUDITY);
  593. if (buttonShow) {
  594. //const verifing = a.previousSibling.textContent.includes("Nudity"); // todo?
  595. //if (verifing) {
  596. buttonShow.click();
  597. //}
  598. }
  599. }
  600. // todo: expand spoiler commentary in photo view mode (.../photo/1)
  601. const b = main.querySelectorAll("article [role=presentation] div[role=button]");
  602. if (b) {
  603. const elems = [...b];
  604. const buttons = elems.filter(el => el.textContent === I18N.VIEW);
  605. if (buttons.length) {
  606. buttons.forEach(el => el.click());
  607. }
  608. }
  609. }
  610.  
  611. static hideSignUpSection() { // "New to Twitter?"
  612. if (!I18N.SIGNUP) {// Unsupported lang, no SIGNUP constant
  613. return;
  614. }
  615. const elem = document.querySelector(`section[aria-label="${I18N.SIGNUP}"][role=region]`);
  616. if (elem) {
  617. elem.parentNode.classList.add("ujs-hidden");
  618. }
  619. }
  620.  
  621. // Call it once.
  622. // "Don’t miss what’s happening" if you are not logged in.
  623. // It looks that `#layers` is used only for this bar.
  624. static hideSignUpBottomBarAndMessages(doNotPlayVideosAutomatically) {
  625. if (doNotPlayVideosAutomatically) {
  626. addCSS(`
  627. #layers > div:nth-child(1) {
  628. display: none;
  629. }
  630. `);
  631. } else {
  632. addCSS(`
  633. #layers > div:nth-child(1) {
  634. height: 1px;
  635. opacity: 0;
  636. }
  637. `);
  638. }
  639. }
  640.  
  641. // "Trends for you"
  642. static hideTrends() {
  643. if (!I18N.TRENDS) { // Unsupported lang, no TRENDS constant
  644. return;
  645. }
  646. addCSS(`
  647. [aria-label="${I18N.TRENDS}"]
  648. {
  649. display: none;
  650. }
  651. `);
  652. }
  653. static highlightVisitedLinks() {
  654. addCSS(`
  655. a:visited {
  656. color: darkorange;
  657. }
  658. `);
  659. }
  660.  
  661. // Hides "TOPICS TO FOLLOW" only in the right column, NOT in timeline.
  662. // Use it once. To prevent blinking.
  663. static hideTopicsToFollowInstantly() {
  664. if (!I18N.TOPICS_TO_FOLLOW) { // Unsupported lang, no TOPICS_TO_FOLLOW constant
  665. return;
  666. }
  667. addCSS(`
  668. div[aria-label="${I18N.TOPICS_TO_FOLLOW}"] {
  669. display: none;
  670. }
  671. `);
  672. }
  673. // Hides container and "separator line"
  674. static hideTopicsToFollow() {
  675. if (!I18N.TOPICS_TO_FOLLOW) { // Unsupported lang, no TOPICS_TO_FOLLOW constant
  676. return;
  677. }
  678. const elem = xpath(`.//section[@role="region" and child::div[@aria-label="${I18N.TOPICS_TO_FOLLOW}"]]/../..`);
  679. if (!elem) {
  680. return;
  681. }
  682. elem.classList.add("ujs-hidden");
  683.  
  684. elem.previousSibling.classList.add("ujs-hidden"); // a "separator line" (empty element of "TRENDS", for example)
  685. // in fact it's a hack // todo rework // may hide "You might like" section [bug]
  686. }
  687.  
  688. // todo split to two methods
  689. // todo fix it, currently it works questionably
  690. // not tested with non eng langs
  691. static footerHandled = false;
  692. static hideAndMoveFooter() { // "Terms of Service Privacy Policy Cookie Policy"
  693. let footer = document.querySelector(`main[role=main] nav[aria-label=${I18N.FOOTER}][role=navigation]`);
  694. const nav = document.querySelector("nav[aria-label=Primary][role=navigation]"); // I18N."Primary" [?]
  695.  
  696. if (footer) {
  697. footer = footer.parentNode;
  698. const separatorLine = footer.previousSibling;
  699.  
  700. if (Features.footerHandled) {
  701. footer.remove();
  702. separatorLine.remove();
  703. return;
  704. }
  705.  
  706. nav.append(separatorLine);
  707. nav.append(footer);
  708. footer.classList.add("ujs-show-on-hover");
  709. separatorLine.classList.add("ujs-show-on-hover");
  710.  
  711. Features.footerHandled = true;
  712. }
  713. }
  714. }
  715. return Features;
  716. }
  717.  
  718. // --- Twitter.RequiredCSS --- //
  719. function getUserScriptCSS() {
  720. const labelText = I18N.IMAGE || "Image";
  721. // By default the scroll is showed all time, since <html style="overflow-y: scroll;>,
  722. // so it works — no need to use `getScrollbarWidth` function from SO (13382516).
  723. const scrollbarWidth = window.innerWidth - document.body.offsetWidth;
  724. const css = `
  725. .ujs-hidden {
  726. display: none;
  727. }
  728. .ujs-no-scroll {
  729. overflow-y: hidden;
  730. }
  731. .ujs-scroll-initial {
  732. overflow-y: initial!important;
  733. }
  734. .ujs-scrollbar-width-margin-right {
  735. margin-right: ${scrollbarWidth}px;
  736. }
  737. .ujs-show-on-hover:hover {
  738. opacity: 1;
  739. transition: opacity 1s ease-out 0.1s;
  740. }
  741. .ujs-show-on-hover {
  742. opacity: 0;
  743. transition: opacity 0.5s ease-out;
  744. }
  745. .ujs-btn-download {
  746. cursor: pointer;
  747. top: 0.5em;
  748. left: 0.5em;
  749. width: 33px;
  750. height: 33px;
  751. background: #e0245e; /*red*/
  752. opacity: 0;
  753. position: absolute;
  754. border-radius: 0.3em;
  755. background-image: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  756. }
  757. article[role=article]:hover .ujs-btn-download {
  758. opacity: 1;
  759. }
  760. div[aria-label="${labelText}"]:hover .ujs-btn-download {
  761. opacity: 1;
  762. }
  763. .ujs-btn-download.ujs-downloaded {
  764. background: #4caf50; /*green*/
  765. background-image: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  766. opacity: 1;
  767. }
  768. .ujs-btn-download.ujs-video {
  769. left: calc(0.5em + 33px + 3px);
  770. }
  771. article[role=article]:hover .ujs-already-downloaded:not(.ujs-downloaded) {
  772. background: #1da1f2; /*blue*/
  773. background-image: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  774. }
  775. div[aria-label="${labelText}"]:hover .ujs-already-downloaded:not(.ujs-downloaded) {
  776. background: #1da1f2; /*blue*/
  777. background-image: linear-gradient(to top, rgba(0,0,0,0.15), rgba(0,0,0,0.05));
  778. }
  779. /* -------------------------------------------------------- */
  780. /* Shadow the button on hover, active and while downloading */
  781. .ujs-btn-download:hover {
  782. background-image: linear-gradient(to top, rgba(0,0,0,0.25), rgba(0,0,0,0.05));
  783. }
  784. .ujs-btn-download:active {
  785. background-image: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.25));
  786. }
  787. .ujs-btn-download.ujs-downloading {
  788. background-image: linear-gradient(to top, rgba(0,0,0,0.45), rgba(0,0,0,0.15));
  789. }
  790. article[role=article]:hover .ujs-already-downloaded:not(.ujs-downloaded):hover {
  791. background-image: linear-gradient(to top, rgba(0,0,0,0.25), rgba(0,0,0,0.05));
  792. }
  793. article[role=article]:hover .ujs-already-downloaded:not(.ujs-downloaded):active {
  794. background-image: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.25));
  795. }
  796. article[role=article]:hover .ujs-already-downloaded:not(.ujs-downloaded).ujs-downloading {
  797. background-image: linear-gradient(to top, rgba(0,0,0,0.45), rgba(0,0,0,0.15));
  798. }
  799. div[aria-label="${labelText}"]:hover .ujs-already-downloaded:not(.ujs-downloaded):hover {
  800. background-image: linear-gradient(to top, rgba(0,0,0,0.25), rgba(0,0,0,0.05));
  801. }
  802. div[aria-label="${labelText}"]:hover .ujs-already-downloaded:not(.ujs-downloaded):active {
  803. background-image: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.25));
  804. }
  805. div[aria-label="${labelText}"]:hover .ujs-already-downloaded:not(.ujs-downloaded).ujs-downloading {
  806. background-image: linear-gradient(to top, rgba(0,0,0,0.45), rgba(0,0,0,0.15));
  807. }
  808. /* -------------------------------------------------------- */
  809. `;
  810. return css.replaceAll(" ".repeat(8), "");
  811. }
  812.  
  813. /*
  814. Features depend on:
  815.  
  816. addRequiredCSS: IMAGE
  817.  
  818. expandSpoilers: YES_VIEW_PROFILE, SHOW_NUDITY, VIEW
  819. handleTitle: QUOTES, ON_TWITTER, TWITTER
  820. hideSignUpSection: SIGNUP
  821. hideTrends: TRENDS
  822. hideTopicsToFollowInstantly: TOPICS_TO_FOLLOW,
  823. hideTopicsToFollow: TOPICS_TO_FOLLOW,
  824.  
  825. [unused]
  826. hideAndMoveFooter: FOOTER
  827. */
  828.  
  829. // --- Twitter.LangConstants --- //
  830. function getLanguageConstants() { //todo: "de", "fr"
  831. const defaultQuotes = [`"`, `"`];
  832.  
  833. const SUPPORTED_LANGUAGES = ["en", "ru", "es", "zh", "ja", ];
  834. // texts
  835. const VIEW = ["View", "Посмотреть", "Ver", "查看", "表示", ];
  836. const YES_VIEW_PROFILE = ["Yes, view profile", "Да, посмотреть профиль", "Sí, ver perfil", "是,查看个人资料", "プロフィールを表示する", ];
  837. const SHOW_NUDITY = ["Show", "Показать", "Mostrar", "显示", "表示", ];
  838. // aria-label texts
  839. const IMAGE = ["Image", "Изображение", "Imagen", "图像", "画像", ];
  840. const SIGNUP = ["Sign up", "Зарегистрироваться", "Regístrate", "注册", "アカウント作成", ];
  841. const TRENDS = ["Timeline: Trending now", "Лента: Актуальные темы", "Cronología: Tendencias del momento", "时间线:当前趋势", "タイムライン: トレンド", ];
  842. const TOPICS_TO_FOLLOW = ["Timeline: ", "Лента: ", "Cronología: ", "时间线:", /*[1]*/ "タイムライン: ", /*[1]*/ ];
  843. const WHO_TO_FOLLOW = ["Who to follow", "Кого читать", "A quién seguir", "推荐关注", "おすすめユーザー" ];
  844. const FOOTER = ["Footer", "Нижний колонтитул", "Pie de página", "页脚", "フッター", ];
  845. // *1 — it's a suggestion, need to recheck. But I can't find a page where I can check it. Was it deleted?
  846. // document.title "{AUTHOR}{ON_TWITTER} {QUOTES[0]}{TEXT}{QUOTES[1]} / {TWITTER}"
  847. const QUOTES = [defaultQuotes, [`«`, `»`], defaultQuotes, defaultQuotes, [`「`, `」`], ];
  848. const ON_TWITTER = [" on Twitter:", " в Твиттере:", " en Twitter:", " 在 Twitter:", "さんはTwitterを使っています", ];
  849. const TWITTER = ["Twitter", "Твиттер", "Twitter", "Twitter", "Twitter", ];
  850. const lang = document.querySelector("html").getAttribute("lang");
  851. const langIndex = SUPPORTED_LANGUAGES.indexOf(lang);
  852.  
  853. return {
  854. SUPPORTED_LANGUAGES,
  855. VIEW: VIEW[langIndex],
  856. YES_VIEW_PROFILE: YES_VIEW_PROFILE[langIndex],
  857. SIGNUP: SIGNUP[langIndex],
  858. TRENDS: TRENDS[langIndex],
  859. TOPICS_TO_FOLLOW: TOPICS_TO_FOLLOW[langIndex],
  860. WHO_TO_FOLLOW: WHO_TO_FOLLOW[langIndex],
  861. FOOTER: FOOTER[langIndex],
  862. QUOTES: QUOTES[langIndex],
  863. ON_TWITTER: ON_TWITTER[langIndex],
  864. TWITTER: TWITTER[langIndex],
  865. IMAGE: IMAGE[langIndex],
  866. SHOW_NUDITY: SHOW_NUDITY[langIndex],
  867. }
  868. }
  869.  
  870. // --- Twitter.Tweet --- //
  871. function hoistTweet() {
  872. class Tweet {
  873. constructor(elem) {
  874. this.elem = elem;
  875. this.url = Tweet.getUrl(elem);
  876. }
  877. static of(innerElem) {
  878. const elem = getParentWithSiblingDataset(innerElem, "testid", "tweet");
  879. if (!elem) { // opened image
  880. verbose && console.log("no-tweet elem");
  881. }
  882. return new Tweet(elem);
  883. }
  884. static getUrl(elem) {
  885. if (!elem) { // if opened image
  886. return location.href;
  887. }
  888.  
  889. const tweetAnchor = [...elem.querySelectorAll("a")].find(el => {
  890. return el.childNodes[0]?.nodeName === "TIME";
  891. });
  892.  
  893. if (tweetAnchor) {
  894. return tweetAnchor.href;
  895. }
  896. // else if selected tweet
  897. return location.href;
  898. }
  899.  
  900. get author() {
  901. return this.url.match(/(?<=twitter\.com\/).+?(?=\/)/)?.[0];
  902. }
  903. get id() {
  904. return this.url.match(/(?<=\/status\/)\d+/)?.[0];
  905. }
  906. }
  907. return Tweet;
  908. }
  909.  
  910. // --- Twitter.API --- //
  911. function hoistAPI() {
  912. class API {
  913. static guestToken = getCookie("gt");
  914. static csrfToken = getCookie("ct0"); // todo: lazy — not available at the first run
  915. // Guest/Suspended account Bearer token
  916. static guestAuthorization = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
  917.  
  918. static async _requestBearerToken() {
  919. const scriptSrc = [...document.querySelectorAll("script")]
  920. .find(el => el.src.match(/https:\/\/abs\.twimg\.com\/responsive-web\/client-web\/main[\w\d\.]*\.js/)).src;
  921.  
  922. let text;
  923. try {
  924. text = await (await fetch(scriptSrc)).text();
  925. } catch (e) {
  926. console.error(e, scriptSrc);
  927. throw e;
  928. }
  929.  
  930. const authorizationKey = text.match(/(?<=")AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D.+?(?=")/)[0];
  931. const authorization = `Bearer ${authorizationKey}`;
  932.  
  933. return authorization;
  934. }
  935.  
  936. static async getAuthorization() {
  937. if (!API.authorization) {
  938. API.authorization = await API._requestBearerToken();
  939. }
  940. return API.authorization;
  941. }
  942.  
  943. // @return {bitrate, content_type, url}
  944. static async getVideoInfo(tweetId) {
  945. // Hm... it always is the same. Even for a logged user.
  946. // const authorization = API.guestToken ? API.guestAuthorization : await API.getAuthorization();
  947. const authorization = API.guestAuthorization;
  948.  
  949. // for debug
  950. verbose && sessionStorage.setItem("guestAuthorization", API.guestAuthorization);
  951. verbose && sessionStorage.setItem("authorization", API.authorization);
  952. verbose && sessionStorage.setItem("x-csrf-token", API.csrfToken);
  953. verbose && sessionStorage.setItem("x-guest-token", API.guestToken);
  954.  
  955. // const url = new URL(`https://api.twitter.com/2/timeline/conversation/${tweetId}.json`); // only for suspended/anon
  956. const url = new URL(`https://twitter.com/i/api/2/timeline/conversation/${tweetId}.json`);
  957. url.searchParams.set("tweet_mode", "extended");
  958.  
  959. const headers = new Headers({
  960. authorization,
  961. "x-csrf-token": API.csrfToken,
  962. });
  963. if (API.guestToken) {
  964. headers.append("x-guest-token", API.guestToken);
  965. } else { // may be skipped
  966. headers.append("x-twitter-active-user", "yes");
  967. headers.append("x-twitter-auth-type", "OAuth2Session");
  968. }
  969.  
  970. const _url = url.toString();
  971. let json;
  972. try {
  973. const response = await fetch(_url, {headers});
  974. json = await response.json();
  975. } catch (e) {
  976. console.error(e, _url);
  977. throw e;
  978. }
  979.  
  980. verbose && console.warn(JSON.stringify(json, null, " "));
  981. // 429 - [{code: 88, message: "Rate limit exceeded"}] — for suspended accounts
  982.  
  983.  
  984. const tweetData = json.globalObjects.tweets[tweetId];
  985. const videoVariants = tweetData.extended_entities.media[0].video_info.variants;
  986. verbose && console.log(videoVariants);
  987.  
  988.  
  989. const video = videoVariants
  990. .filter(el => el.bitrate !== undefined) // if content_type: "application/x-mpegURL" // .m3u8
  991. .reduce((acc, cur) => cur.bitrate > acc.bitrate ? cur : acc);
  992. return video;
  993. }
  994. }
  995. return API;
  996. }
  997.  
  998. // ---------------------------------------------------------------------------------------------------------------------
  999. // ---------------------------------------------------------------------------------------------------------------------
  1000. // --- Common Utils --- //
  1001.  
  1002. // --- LocalStorage util class --- //
  1003. function hoistLS(settings = {}) {
  1004. const {
  1005. verbose, // debug "messages" in the document.title
  1006. } = settings;
  1007. class LS {
  1008. constructor(name) {
  1009. this.name = name;
  1010. }
  1011. getItem(defaultValue) {
  1012. return LS.getItem(this.name, defaultValue);
  1013. }
  1014. setItem(value) {
  1015. LS.setItem(this.name, value);
  1016. }
  1017. removeItem() {
  1018. LS.removeItem(this.name);
  1019. }
  1020. async pushItem(value) { // array method
  1021. await LS.pushItem(this.name, value);
  1022. }
  1023. async popItem(value) { // array method
  1024. await LS.popItem(this.name, value);
  1025. }
  1026. hasItem(value) { // array method
  1027. return LS.hasItem(this.name, value);
  1028. }
  1029.  
  1030. static getItem(name, defaultValue) {
  1031. const value = localStorage.getItem(name);
  1032. if (value === undefined) {
  1033. return undefined;
  1034. }
  1035. if (value === null) { // when there is no such item
  1036. LS.setItem(name, defaultValue);
  1037. return defaultValue;
  1038. }
  1039. return JSON.parse(value);
  1040. }
  1041. static setItem(name, value) {
  1042. localStorage.setItem(name, JSON.stringify(value));
  1043. }
  1044. static removeItem(name) {
  1045. localStorage.removeItem(name);
  1046. }
  1047. static async pushItem(name, value) {
  1048. const array = LS.getItem(name, []);
  1049. array.push(value);
  1050. LS.setItem(name, array);
  1051.  
  1052. //sanity check
  1053. await sleep(50);
  1054. if (!LS.hasItem(name, value)) {
  1055. if (verbose) {
  1056. document.title = "🟥" + document.title;
  1057. }
  1058. await LS.pushItem(name, value);
  1059. }
  1060. }
  1061. static async popItem(name, value) { // remove from an array
  1062. const array = LS.getItem(name, []);
  1063. if (array.indexOf(value) !== -1) {
  1064. array.splice(array.indexOf(value), 1);
  1065. LS.setItem(name, array);
  1066.  
  1067. //sanity check
  1068. await sleep(50);
  1069. if (LS.hasItem(name, value)) {
  1070. if (verbose) {
  1071. document.title = "🟨" + document.title;
  1072. }
  1073. await LS.popItem(name, value);
  1074. }
  1075. }
  1076. }
  1077. static hasItem(name, value) { // has in array
  1078. const array = LS.getItem(name, []);
  1079. return array.indexOf(value) !== -1;
  1080. }
  1081. }
  1082. return LS;
  1083. }
  1084.  
  1085. // --- Just groups them in a function for the convenient code looking --- //
  1086. function getUtils({verbose}) {
  1087. function sleep(time) {
  1088. return new Promise(resolve => setTimeout(resolve, time));
  1089. }
  1090.  
  1091. async function fetchResource(url) {
  1092. try {
  1093. const response = await fetch(url, {
  1094. cache: "force-cache",
  1095. });
  1096. const lastModifiedDateSeconds = response.headers.get("last-modified");
  1097. const contentType = response.headers.get("content-type");
  1098.  
  1099. const lastModifiedDate = dateToDayDateString(lastModifiedDateSeconds);
  1100. const extension = extensionFromMime(contentType);
  1101. const blob = await response.blob();
  1102.  
  1103. // https://pbs.twimg.com/media/AbcdEFgijKL01_9?format=jpg&name=orig -> AbcdEFgijKL01_9
  1104. // https://pbs.twimg.com/ext_tw_video_thumb/1234567890123456789/pu/img/Ab1cd2345EFgijKL.jpg?name=orig -> Ab1cd2345EFgijKL.jpg
  1105. // https://video.twimg.com/ext_tw_video/1234567890123456789/pu/vid/946x720/Ab1cd2345EFgijKL.mp4?tag=10 -> Ab1cd2345EFgijKL.mp4
  1106. const _url = new URL(url);
  1107. const {filename} = (_url.origin + _url.pathname).match(/(?<filename>[^\/]+$)/).groups;
  1108.  
  1109. const {name} = filename.match(/(?<name>^[^\.]+)/).groups;
  1110. return {blob, lastModifiedDate, contentType, extension, name};
  1111. } catch (error) {
  1112. verbose && console.error("[fetchResource]", url, error);
  1113. throw error;
  1114. }
  1115. }
  1116.  
  1117. function extensionFromMime(mimeType) {
  1118. let extension = mimeType.match(/(?<=\/).+/)[0];
  1119. extension = extension === "jpeg" ? "jpg" : extension;
  1120. return extension;
  1121. }
  1122.  
  1123. // the original download url will be posted as hash of the blob url, so you can check it in the download manager's history
  1124. function download(blob, name, url) {
  1125. const anchor = document.createElement("a");
  1126. anchor.setAttribute("download", name || "");
  1127. const blobUrl = URL.createObjectURL(blob);
  1128. anchor.href = blobUrl + (url ? ("#" + url) : "");
  1129. anchor.click();
  1130. setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
  1131. }
  1132.  
  1133. // "Sun, 10 Jan 2021 22:22:22 GMT" -> "2021.01.10"
  1134. function dateToDayDateString(dateValue, utc = true) {
  1135. const _date = new Date(dateValue);
  1136. function pad(str) {
  1137. return str.toString().padStart(2, "0");
  1138. }
  1139. const _utc = utc ? "UTC" : "";
  1140. const year = _date[`get${_utc}FullYear`]();
  1141. const month = _date[`get${_utc}Month`]() + 1;
  1142. const date = _date[`get${_utc}Date`]();
  1143.  
  1144. return year + "." + pad(month) + "." + pad(date);
  1145. }
  1146.  
  1147.  
  1148. function addCSS(css) {
  1149. const styleElem = document.createElement("style");
  1150. styleElem.textContent = css;
  1151. document.body.append(styleElem);
  1152. return styleElem;
  1153. }
  1154.  
  1155.  
  1156. function getCookie(name) {
  1157. verbose && console.log(document.cookie);
  1158. const regExp = new RegExp(`(?<=${name}=)[^;]+`);
  1159. return document.cookie.match(regExp)?.[0];
  1160. }
  1161.  
  1162. function throttle(runnable, time = 50) {
  1163. let waiting = false;
  1164. let queued = false;
  1165. let context;
  1166. let args;
  1167.  
  1168. return function() {
  1169. if (!waiting) {
  1170. waiting = true;
  1171. setTimeout(function() {
  1172. if (queued) {
  1173. runnable.apply(context, args);
  1174. context = args = undefined;
  1175. }
  1176. waiting = queued = false;
  1177. }, time);
  1178. return runnable.apply(this, arguments);
  1179. } else {
  1180. queued = true;
  1181. context = this;
  1182. args = arguments;
  1183. }
  1184. }
  1185. }
  1186. function throttleWithResult(func, time = 50) {
  1187. let waiting = false;
  1188. let args;
  1189. let context;
  1190. let timeout;
  1191. let promise;
  1192.  
  1193. return async function() {
  1194. if (!waiting) {
  1195. waiting = true;
  1196. timeout = new Promise(async resolve => {
  1197. await sleep(time);
  1198. waiting = false;
  1199. resolve();
  1200. });
  1201. return func.apply(this, arguments);
  1202. } else {
  1203. args = arguments;
  1204. context = this;
  1205. }
  1206.  
  1207. if (!promise) {
  1208. promise = new Promise(async resolve => {
  1209. await timeout;
  1210. const result = func.apply(context, args);
  1211. args = context = promise = undefined;
  1212. resolve(result);
  1213. });
  1214. }
  1215. return promise;
  1216. }
  1217. }
  1218.  
  1219.  
  1220. function xpath(path, node = document) {
  1221. let xPathResult = document.evaluate(path, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1222. return xPathResult.singleNodeValue;
  1223. }
  1224. function xpathAll(path, node = document) {
  1225. let xPathResult = document.evaluate(path, node, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  1226. const nodes = [];
  1227. try {
  1228. let node = xPathResult.iterateNext();
  1229.  
  1230. while (node) {
  1231. nodes.push(node);
  1232. node = xPathResult.iterateNext();
  1233. }
  1234. return nodes;
  1235. }
  1236. catch (e) {
  1237. // todo need investigate it
  1238. console.error(e); // "The document has mutated since the result was returned."
  1239. return [];
  1240. }
  1241. }
  1242.  
  1243.  
  1244. function getNearestElementByType(elem, type) {
  1245. const parent = elem.parentNode;
  1246. if (parent === document) {
  1247. return null;
  1248. }
  1249. if (parent.nodeName === type.toUpperCase()) {
  1250. return parent;
  1251. }
  1252. return getNearestElementByType(parent, type);
  1253. }
  1254. function getParentWithSiblingDataset(node, name, value) {
  1255. const parent = node.parentNode;
  1256. if (parent === document) {
  1257. return null;
  1258. }
  1259. // console.log(parent, parent.childNodes);
  1260. const elem = [...parent.childNodes].find(el => {
  1261. if (el.dataset?.[name] === value) {
  1262. return true;
  1263. }
  1264. });
  1265. if (!elem) {
  1266. return getParentWithSiblingDataset(parent, name, value);
  1267. }
  1268. return parent;
  1269. }
  1270.  
  1271. return {
  1272. sleep, fetchResource, extensionFromMime, download, dateToDayDateString,
  1273. addCSS,
  1274. getCookie,
  1275. throttle, throttleWithResult,
  1276. xpath, xpathAll,
  1277. getNearestElementByType, getParentWithSiblingDataset,
  1278. }
  1279. }
  1280.  
  1281.  
  1282. // ---------------------------------------------------------------------------------------------------------------------
  1283. // ---------------------------------------------------------------------------------------------------------------------