Twitter Click'n'Save

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

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

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

QingJ © 2025

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