Greasy Fork 还支持 简体中文。

Twitter Click'n'Save

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

目前為 2022-08-06 提交的版本,檢視 最新版本

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