(Mod)Twitter Media Downloader

Save Video/Photo by One-Click.【Mod】1.修改下载文件名格式

2024-04-08 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name (Mod)Twitter Media Downloader
  3. // @name:ja (Mod)Twitter Media Downloader
  4. // @name:zh-cn (Mod)Twitter 媒体下载
  5. // @name:zh-tw (Mod)Twitter 媒體下載
  6. // @description Save Video/Photo by One-Click.【Mod】1.修改下载文件名格式
  7. // @description:ja ワンクリックで動画?画像を保存する。
  8. // @description:zh-cn 一键保存视频/图片
  9. // @description:zh-tw 一鍵保存視頻/圖片
  10. // @version 1.27-Mod-20240408
  11. // @author AMANE【Mod by heckles】
  12. // @namespace none
  13. // @match https://twitter.com/*
  14. // @match https://mobile.twitter.com/*
  15. // @grant GM_registerMenuCommand
  16. // @grant GM_setValue
  17. // @grant GM_getValue
  18. // @grant GM_download
  19. // @compatible Chrome
  20. // @compatible Firefox
  21. // @license MIT
  22. // ==/UserScript==
  23. /* jshint esversion: 8 */
  24.  
  25. /**
  26. * 生成推特文件名格式
  27. *
  28. * 该文件名格式用于标识推特用户、发布日期时间、状态ID和文件类型。
  29. * 它采用特定的字符串模板,通过替换模板中的占位符来生成最终的文件名。
  30. *
  31. * @param {string} userName 用户名
  32. * @param {number} userId 用户ID
  33. * @param {string} dateTime 发布的日期和时间,应为符合特定格式的字符串
  34. * @param {string} statusId 状态ID,即推文的唯一标识符
  35. * @param {string} fileType 文件类型,如jpg、png等
  36. * @returns {string} 根据提供的参数生成的推特文件名
  37. */
  38. const filename =
  39. // "twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}";
  40. "{date-time}_twitter_{user-name}(@{user-id})_{status-id}_{file-type}";
  41. /**
  42. * TMD 是一个封装了各种功能的自执行函数,用于实现语言环境配置、存储管理、敏感内容显示控制等。
  43. * */
  44. const TMD = (function () {
  45. let lang, host, history, show_sensitive, is_tweetdeck;
  46. // 返回一个包含各种功能的方法的对象
  47. return {
  48. /**
  49. * 初始化函数,负责设置语言、检测环境、初始化存储及设置界面样式等。
  50. * */
  51. init: async function () {
  52. // 注册右键菜单命令,根据用户语言设置显示的文本
  53. GM_registerMenuCommand(
  54. (this.language[navigator.language] || this.language.en).settings,
  55. this.settings
  56. );
  57. lang =
  58. this.language[document.querySelector("html").lang] || this.language.en; // 设置当前语言
  59. host = location.hostname; // 获取当前域名
  60. is_tweetdeck = host.indexOf("tweetdeck") >= 0; // 检查是否在TweetDeck环境中
  61. history = this.storage_obsolete(); // 试图从旧存储中获取历史记录
  62.  
  63. // 如果存在历史记录,则使用旧存储机制,否则使用新的存储机制
  64. if (history.length) {
  65. this.storage(history);
  66. this.storage_obsolete(true);
  67. } else history = await this.storage(); // 异步获取存储的历史记录
  68.  
  69. show_sensitive = GM_getValue("show_sensitive", false); // 获取是否显示敏感内容的设置
  70. // 动态插入样式表,根据是否显示敏感内容决定是否应用额外的样式
  71. document.head.insertAdjacentHTML(
  72. "beforeend",
  73. "<style>" + this.css + (show_sensitive ? this.css_ss : "") + "</style>"
  74. );
  75.  
  76. // 使用MutationObserver监听文档变动,以实时处理新增节点
  77. let observer = new MutationObserver((ms) =>
  78. ms.forEach((m) => m.addedNodes.forEach((node) => this.detect(node)))
  79. );
  80. observer.observe(document.body, { childList: true, subtree: true }); // 启动观察者
  81. },
  82. /**
  83. * 检测给定的节点,并根据其类型添加相应的按钮。
  84. * @param {HTMLElement} node - 需要进行检测的DOM节点。
  85. */
  86. detect: function (node) {
  87. // 检查当前节点或其子节点或最近的祖先节点是否为ARTICLE标签,如果是,则为该文章节点添加按钮
  88. let article =
  89. (node.tagName == "ARTICLE" && node) ||
  90. (node.tagName == "DIV" &&
  91. (node.querySelector("article") || node.closest("article")));
  92. if (article) this.addButtonTo(article);
  93.  
  94. // 检查当前节点是否为LI标签且其角色为listitem,或如果当前节点为DIV标签则查找所有的li[role="listitem"]子节点,若是,则为这些媒体列表项添加按钮
  95. let listitems =
  96. (node.tagName == "LI" &&
  97. node.getAttribute("role") == "listitem" && [node]) ||
  98. (node.tagName == "DIV" && node.querySelectorAll('li[role="listitem"]'));
  99. if (listitems) this.addButtonToMedia(listitems);
  100. },
  101. /**
  102. * 向指定的文章中添加下载按钮。
  103. * @param {HTMLElement} article - 需要添加按钮的文章元素。
  104. */
  105. addButtonTo: function (article) {
  106. // 如果已经检测到,则不再重复添加
  107. if (article.dataset.detected) return;
  108. article.dataset.detected = "true";
  109.  
  110. // 定义用于选择媒体元素的选择器
  111. let media_selector = [
  112. 'a[href*="/photo/1"]',
  113. 'div[role="progressbar"]',
  114. 'div[data-testid="playButton"]',
  115. 'a[href="/settings/content_you_see"]', // 隐藏的内容
  116. "div.media-image-container", // 用于TweetDeck
  117. "div.media-preview-container", // 用于TweetDeck
  118. 'div[aria-labelledby]>div:first-child>div[role="button"][tabindex="0"]', // 音频(实验性)
  119. ];
  120.  
  121. // 尝试根据选择器找到媒体元素
  122. let media = article.querySelector(media_selector.join(","));
  123.  
  124. if (media) {
  125. // 从文章中提取状态ID
  126. let status_id = article
  127. .querySelector('a[href*="/status/"]')
  128. .href.split("/status/")
  129. .pop()
  130. .split("/")
  131. .shift();
  132.  
  133. // 查找按钮组或者操作列表
  134. let btn_group = article.querySelector(
  135. 'div[role="group"]:last-of-type, ul.tweet-actions, ul.tweet-detail-actions'
  136. );
  137.  
  138. // 在按钮组中找到分享按钮的父节点
  139. let btn_share = Array.from(
  140. btn_group.querySelectorAll(
  141. ":scope>div>div, li.tweet-action-item>a, li.tweet-detail-action-item>a"
  142. )
  143. ).pop().parentNode;
  144.  
  145. // 克隆分享按钮并创建下载按钮
  146. let btn_down = btn_share.cloneNode(true);
  147.  
  148. // 根据是否在TweetDeck中,对按钮进行不同的设置
  149. if (is_tweetdeck) {
  150. btn_down.firstElementChild.innerHTML =
  151. '<svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' +
  152. this.svg +
  153. "</svg>";
  154. btn_down.firstElementChild.removeAttribute("rel");
  155. btn_down.classList.replace("pull-left", "pull-right");
  156. } else {
  157. btn_down.querySelector("svg").innerHTML = this.svg;
  158. }
  159.  
  160. // 检查是否已经下载
  161. let is_exist = history.indexOf(status_id) >= 0;
  162.  
  163. // 设置按钮状态
  164. this.status(btn_down, "tmd-down");
  165. this.status(
  166. btn_down,
  167. is_exist ? "completed" : "download",
  168. is_exist ? lang.completed : lang.download
  169. );
  170.  
  171. // 在按钮组中插入下载按钮
  172. btn_group.insertBefore(btn_down, btn_share.nextSibling);
  173.  
  174. // 绑定点击事件
  175. btn_down.onclick = () => this.click(btn_down, status_id, is_exist);
  176.  
  177. // 如果显示敏感内容,自动点击显示按钮
  178. if (show_sensitive) {
  179. let btn_show = article.querySelector(
  180. 'div[aria-labelledby] div[role="button"][tabindex="0"]:not([data-testid]) > div[dir] > span > span'
  181. );
  182. if (btn_show) btn_show.click();
  183. }
  184. }
  185.  
  186. // 处理文章中的多张图片
  187. let imgs = article.querySelectorAll('a[href*="/photo/"]');
  188. if (imgs.length > 1) {
  189. let status_id = article
  190. .querySelector('a[href*="/status/"]')
  191. .href.split("/status/")
  192. .pop()
  193. .split("/")
  194. .shift();
  195. let btn_group = article.querySelector('div[role="group"]:last-of-type');
  196. let btn_share = Array.from(
  197. btn_group.querySelectorAll(":scope>div>div")
  198. ).pop().parentNode;
  199.  
  200. imgs.forEach((img) => {
  201. // 为每张图片生成独立的下载按钮
  202. let index = img.href.split("/status/").pop().split("/").pop();
  203. let is_exist = history.indexOf(status_id) >= 0;
  204. let btn_down = document.createElement("div");
  205. btn_down.innerHTML =
  206. '<div><div><svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' +
  207. this.svg +
  208. "</svg></div></div>";
  209. btn_down.classList.add("tmd-down", "tmd-img");
  210. this.status(btn_down, "download");
  211. img.parentNode.appendChild(btn_down);
  212.  
  213. // 绑定点击事件,防止默认行为
  214. btn_down.onclick = (e) => {
  215. e.preventDefault();
  216. this.click(btn_down, status_id, is_exist, index);
  217. };
  218. });
  219. }
  220. },
  221. /**
  222. * 为媒体列表项添加下载按钮
  223. * @param {Array} listitems - 包含媒体信息的列表项数组
  224. */
  225. addButtonToMedia: function (listitems) {
  226. listitems.forEach((li) => {
  227. // 跳过已经检测过的列表项
  228. if (li.dataset.detected) return;
  229. li.dataset.detected = "true";
  230.  
  231. // 提取状态ID
  232. let status_id = li
  233. .querySelector('a[href*="/status/"]')
  234. .href.split("/status/")
  235. .pop()
  236. .split("/")
  237. .shift();
  238.  
  239. // 检查历史记录中是否已存在该状态ID
  240. let is_exist = history.indexOf(status_id) >= 0;
  241.  
  242. // 创建下载按钮
  243. let btn_down = document.createElement("div");
  244. btn_down.innerHTML =
  245. '<div><div><svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' +
  246. this.svg +
  247. "</svg></div></div>";
  248. btn_down.classList.add("tmd-down", "tmd-media");
  249.  
  250. // 设置按钮状态
  251. this.status(
  252. btn_down,
  253. is_exist ? "completed" : "download",
  254. is_exist ? lang.completed : lang.download
  255. );
  256.  
  257. // 将按钮添加到列表项中
  258. li.appendChild(btn_down);
  259.  
  260. // 设置按钮点击事件处理函数
  261. btn_down.onclick = () => this.click(btn_down, status_id, is_exist);
  262. });
  263. },
  264. /**
  265. * 处理下载按钮点击事件
  266. * @param {Object} btn - 被点击的按钮对象
  267. * @param {String} status_id - 媒体的状态ID
  268. * @param {Boolean} is_exist - 指示该媒体是否已存在于历史记录中
  269. */
  270. click: async function (btn, status_id, is_exist, index) {
  271. // 如果按钮处于加载状态,则不进行任何操作
  272. if (btn.classList.contains("loading")) return;
  273.  
  274. // 设置按钮为加载状态
  275. this.status(btn, "loading");
  276.  
  277. // 读取并处理文件名和保存历史记录的设置
  278. let out = (await GM_getValue("filename", filename)).split("\n").join("");
  279. let save_history = await GM_getValue("save_history", true);
  280.  
  281. // 获取媒体的详细信息
  282. let json = await this.fetchJson(status_id);
  283. let tweet = json.legacy;
  284. let user = json.core.user_results.result.legacy;
  285.  
  286. // 定义并处理文件名中不允许出现的字符
  287. let invalid_chars = {
  288. "\\": "\",
  289. "/": "/",
  290. "|": "|",
  291. "<": "<",
  292. ">": ">",
  293. ":": ":",
  294. "*": "*",
  295. "?": "?",
  296. '"': """,
  297. "\u200b": "",
  298. "\u200c": "",
  299. "\u200d": "",
  300. "\u2060": "",
  301. "\ufeff": "",
  302. "🔞": "",
  303. };
  304.  
  305. // 处理输出文件名中的日期和时间部分
  306. let datetime = out.match(/{date-time(-local)?:[^{}]+}/)
  307. ? out
  308. .match(/{date-time(?:-local)?:([^{}]+)}/)[1]
  309. .replace(/[\\/|<>*?:"]/g, (v) => invalid_chars[v])
  310. // : "YYYYMMDD-hhmmss";
  311. : "YYYY-MM-DD hh-mm-ss";
  312.  
  313. // 准备下载信息
  314. let info = {};
  315. info["status-id"] = status_id;
  316. info["user-name"] = user.name.replace(
  317. /([\\/|*?:"]|[\u200b-\u200d\u2060\ufeff]|🔞)/g,
  318. (v) => invalid_chars[v]
  319. );
  320. info["user-id"] = user.screen_name;
  321. info["date-time"] = this.formatDate(tweet.created_at, datetime);
  322. info["date-time-local"] = this.formatDate(
  323. tweet.created_at,
  324. datetime,
  325. true
  326. );
  327. info["full-text"] = tweet.full_text
  328. .split("\n")
  329. .join(" ")
  330. .replace(/\s*https:\/\/t\.co\/\w+/g, "")
  331. .replace(
  332. /[\\/|<>*?:"]|[\u200b-\u200d\u2060\ufeff]/g,
  333. (v) => invalid_chars[v]
  334. );
  335.  
  336. // 处理媒体文件下载
  337. let medias = tweet.extended_entities && tweet.extended_entities.media;
  338. if (index) medias = [medias[index - 1]];
  339.  
  340. if (medias.length > 0) {
  341. let tasks = medias.length;
  342. let tasks_result = [];
  343. medias.forEach((media, i) => {
  344. // 准备每个媒体文件的下载信息
  345. info.url =
  346. media.type == "photo"
  347. ? media.media_url_https + ":orig"
  348. : media.video_info.variants
  349. .filter((n) => n.content_type == "video/mp4")
  350. .sort((a, b) => b.bitrate - a.bitrate)[0].url;
  351. info.file = info.url.split("/").pop().split(/[:?]/).shift();
  352. info["file-name"] = info.file.split(".").shift();
  353. info["file-ext"] = info.file.split(".").pop();
  354. info["file-type"] = media.type.replace("animated_", "");
  355. info.out = (
  356. out.replace(/\.?{file-ext}/, "") +
  357. ((medias.length > 1 || index) && !out.match("{file-name}")
  358. ? "-" + (index ? index - 1 : i)
  359. : "") +
  360. ".{file-ext}"
  361. ).replace(/{([^{}:]+)(:[^{}]+)?}/g, (match, name) => info[name]);
  362.  
  363. // 添加下载任务
  364. this.downloader.add({
  365. url: info.url,
  366. name: info.out,
  367. onload: () => {
  368. tasks -= 1;
  369. tasks_result.push(
  370. (medias.length > 1 || index
  371. ? (index ? index : i + 1) + ": "
  372. : "") + lang.completed
  373. );
  374. this.status(btn, null, tasks_result.sort().join("\n"));
  375. if (tasks === 0) {
  376. this.status(btn, "completed", lang.completed);
  377. if (save_history && !is_exist) {
  378. history.push(status_id);
  379. this.storage(status_id);
  380. }
  381. }
  382. },
  383. onerror: (result) => {
  384. tasks = -1;
  385. tasks_result.push(
  386. (medias.length > 1 ? i + 1 + ": " : "") + result.details.current
  387. );
  388. this.status(btn, "failed", tasks_result.sort().join("\n"));
  389. },
  390. });
  391. });
  392. } else {
  393. // 如果未找到媒体文件,则设置按钮状态为失败
  394. this.status(btn, "failed", "MEDIA_NOT_FOUND");
  395. }
  396. },
  397. /**
  398. * 更新按钮状态。
  399. * @param {HTMLElement} btn - 要更新状态的按钮元素。
  400. * @param {string} css - 要添加的CSS类(可选)。
  401. * @param {string} title - 按钮的标题(可选)。
  402. * @param {string} style - 要应用的内联样式(可选)。
  403. */
  404. status: function (btn, css, title, style) {
  405. // 如果提供了CSS类,则移除旧的类并添加新的类
  406. if (css) {
  407. btn.classList.remove("download", "completed", "loading", "failed");
  408. btn.classList.add(css);
  409. }
  410. // 如果提供了标题,则更新按钮标题
  411. if (title) btn.title = title;
  412. // 如果提供了样式,则更新按钮的内联样式
  413. if (style) btn.style.cssText = style;
  414. },
  415.  
  416. /**
  417. * 弹出设置对话框。
  418. */
  419. settings: async function () {
  420. // 创建元素的工具函数
  421. const $element = (parent, tag, style, content, css) => {
  422. let el = document.createElement(tag);
  423. if (style) el.style.cssText = style;
  424. if (typeof content !== "undefined") {
  425. if (tag == "input") {
  426. if (content == "checkbox") el.type = content;
  427. else el.value = content;
  428. } else el.innerHTML = content;
  429. }
  430. if (css) css.split(" ").forEach((c) => el.classList.add(c));
  431. parent.appendChild(el);
  432. return el;
  433. };
  434.  
  435. // 创建设置对话框的容器和基本样式
  436. let wapper = $element(
  437. document.body,
  438. "div",
  439. "position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: #0009; z-index: 10;"
  440. );
  441. // 处理关闭设置对话框的逻辑
  442. let wapper_close;
  443. wapper.onmousedown = (e) => {
  444. wapper_close = e.target == wapper;
  445. };
  446. wapper.onmouseup = (e) => {
  447. if (wapper_close && e.target == wapper) wapper.remove();
  448. };
  449.  
  450. // 创建并设置对话框内容,包括标题、选项等
  451. let dialog = $element(
  452. wapper,
  453. "div",
  454. "position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); width: fit-content; width: -moz-fit-content; background-color: #f3f3f3; border: 1px solid #ccc; border-radius: 10px; color: black;"
  455. );
  456. let title = $element(
  457. dialog,
  458. "h3",
  459. "margin: 10px 20px;",
  460. lang.dialog.title
  461. );
  462. let options = $element(
  463. dialog,
  464. "div",
  465. "margin: 10px; border: 1px solid #ccc; border-radius: 5px;"
  466. );
  467.  
  468. // 保存历史记录的设置
  469. let save_history_label = $element(
  470. options,
  471. "label",
  472. "display: block; margin: 10px;",
  473. lang.dialog.save_history
  474. );
  475. let save_history_input = $element(
  476. save_history_label,
  477. "input",
  478. "float: left;",
  479. "checkbox"
  480. );
  481. save_history_input.checked = await GM_getValue("save_history", true);
  482. save_history_input.onchange = () => {
  483. GM_setValue("save_history", save_history_input.checked);
  484. };
  485.  
  486. // 清除历史记录的按钮和逻辑
  487. let clear_history = $element(
  488. save_history_label,
  489. "label",
  490. "display: inline-block; margin: 0 10px; color: blue;",
  491. lang.dialog.clear_history
  492. );
  493. clear_history.onclick = () => {
  494. if (confirm(lang.dialog.clear_confirm)) {
  495. history = [];
  496. GM_setValue("download_history", []);
  497. }
  498. };
  499.  
  500. // 显示敏感内容的设置
  501. let show_sensitive_label = $element(
  502. options,
  503. "label",
  504. "display: block; margin: 10px;",
  505. lang.dialog.show_sensitive
  506. );
  507. let show_sensitive_input = $element(
  508. show_sensitive_label,
  509. "input",
  510. "float: left;",
  511. "checkbox"
  512. );
  513. show_sensitive_input.checked = await GM_getValue("show_sensitive", false);
  514. show_sensitive_input.onchange = () => {
  515. show_sensitive = show_sensitive_input.checked;
  516. GM_setValue("show_sensitive", show_sensitive);
  517. };
  518.  
  519. // 文件名模式设置
  520. let filename_div = $element(
  521. dialog,
  522. "div",
  523. "margin: 10px; border: 1px solid #ccc; border-radius: 5px;"
  524. );
  525. let filename_label = $element(
  526. filename_div,
  527. "label",
  528. "display: block; margin: 10px 15px;",
  529. lang.dialog.pattern
  530. );
  531. let filename_input = $element(
  532. filename_label,
  533. "textarea",
  534. "display: block; min-width: 500px; max-width: 500px; min-height: 100px; font-size: inherit; background: white; color: black;",
  535. await GM_getValue("filename", filename)
  536. );
  537. let filename_tags = $element(
  538. filename_div,
  539. "label",
  540. "display: table; margin: 10px;",
  541. `
  542. <span class="tmd-tag" title="user name">{user-name}</span>
  543. <span class="tmd-tag" title="The user name after @ sign.">{user-id}</span>
  544. <span class="tmd-tag" title="example: 1234567890987654321">{status-id}</span>
  545. <span class="tmd-tag" title="{date-time} : Posted time in UTC.\n{date-time-local} : Your local time zone.\n\nDefault:\nYYYYMMDD-hhmmss => 20201231-235959\n\nExample of custom:\n{date-time:DD-MMM-YY hh.mm} => 31-DEC-21 23.59">{date-time}</span><br>
  546. <span class="tmd-tag" title="Text content in tweet.">{full-text}</span>
  547. <span class="tmd-tag" title="Type of &#34;video&#34; or &#34;photo&#34; or &#34;gif&#34;.">{file-type}</span>
  548. <span class="tmd-tag" title="Original filename from URL.">{file-name}</span>
  549. `
  550. );
  551. filename_input.selectionStart = filename_input.value.length;
  552. filename_tags.querySelectorAll(".tmd-tag").forEach((tag) => {
  553. tag.onclick = () => {
  554. let ss = filename_input.selectionStart;
  555. let se = filename_input.selectionEnd;
  556. filename_input.value =
  557. filename_input.value.substring(0, ss) +
  558. tag.innerText +
  559. filename_input.value.substring(se);
  560. filename_input.selectionStart = ss + tag.innerText.length;
  561. filename_input.selectionEnd = ss + tag.innerText.length;
  562. filename_input.focus();
  563. };
  564. });
  565.  
  566. // 保存设置的按钮及其逻辑
  567. let btn_save = $element(
  568. title,
  569. "label",
  570. "float: right;",
  571. lang.dialog.save,
  572. "tmd-btn"
  573. );
  574. btn_save.onclick = async () => {
  575. await GM_setValue("filename", filename_input.value);
  576. wapper.remove();
  577. };
  578. },
  579. /**
  580. * 异步获取指定状态ID的JSON数据
  581. * @param {string} status_id - 待查询的状态ID
  582. * @returns {Promise<Object>} 返回一个Promise对象,包含指定推文的详细信息
  583. */
  584. fetchJson: async function (status_id) {
  585. // 定义基础URL
  586. let base_url = `https://${host}/i/api/graphql/NmCeCgkVlsRGS1cAwqtgmw/TweetDetail`;
  587. // 定义查询变量
  588. let variables = {
  589. focalTweetId: status_id,
  590. with_rux_injections: false,
  591. includePromotedContent: true,
  592. withCommunity: true,
  593. withQuickPromoteEligibilityTweetFields: true,
  594. withBirdwatchNotes: true,
  595. withVoice: true,
  596. withV2Timeline: true,
  597. };
  598. // 定义功能特性
  599. let features = {
  600. // 各种功能特性的启用或禁用状态
  601. };
  602. // 构建完整查询URL
  603. let url = encodeURI(
  604. `${base_url}?variables=${JSON.stringify(
  605. variables
  606. )}&features=${JSON.stringify(features)}`
  607. );
  608. // 获取当前页面的cookies
  609. let cookies = this.getCookie();
  610. // 定义请求头
  611. let headers = {
  612. authorization:
  613. "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
  614. "x-twitter-active-user": "yes",
  615. "x-twitter-client-language": cookies.lang,
  616. "x-csrf-token": cookies.ct0,
  617. };
  618. // 如果存在guest token,则添加到请求头
  619. if (cookies.ct0.length == 32) headers["x-guest-token"] = cookies.gt;
  620. // 发起网络请求并处理响应
  621. let tweet_detail = await fetch(url, { headers: headers }).then((result) =>
  622. result.json()
  623. );
  624. // 解析推文详细信息
  625. let tweet_entrie =
  626. tweet_detail.data.threaded_conversation_with_injections_v2.instructions[0].entries.find(
  627. (n) => n.entryId == `tweet-${status_id}`
  628. );
  629. let tweet_result = tweet_entrie.content.itemContent.tweet_results.result;
  630. // 返回推文信息
  631. return tweet_result.tweet || tweet_result;
  632. },
  633.  
  634. /**
  635. * 获取指定名称的cookie值
  636. * @param {string} [name] - 需要获取的cookie名称,可选,默认为获取所有cookie
  637. * @returns {Object|string} 如果指定了name,则返回该cookie的值;否则返回所有cookie的对象
  638. */
  639. getCookie: function (name) {
  640. let cookies = {};
  641. // 解析document.cookie获取所有cookie
  642. document.cookie
  643. .split(";")
  644. .filter((n) => n.indexOf("=") > 0)
  645. .forEach((n) => {
  646. n.replace(/^([^=]+)=(.+)$/, (match, name, value) => {
  647. cookies[name.trim()] = value.trim();
  648. });
  649. });
  650. // 返回指定或所有cookie
  651. return name ? cookies[name] : cookies;
  652. },
  653.  
  654. /**
  655. * 异步存储数据到本地存储(如GM_setValue)
  656. * @param {*} value - 需要存储的数据,可以是任意类型。如果为数组,则会合并到历史数据中;如果为其他类型且历史数据中不存在,则会添加到数据数组中。
  657. * @returns {Promise<void>} 不返回任何内容
  658. */
  659. storage: async function (value) {
  660. let data = await GM_getValue("download_history", []); // 获取历史数据,默认为空数组
  661. let data_length = data.length;
  662. // 如果提供了value参数,则进行数据处理
  663. if (value) {
  664. // 如果value是数组,则合并到历史数据中
  665. if (Array.isArray(value)) data = data.concat(value);
  666. // 如果value不是数组且在历史数据中不存在,则添加到数据数组中
  667. else if (data.indexOf(value) < 0) data.push(value);
  668. } else return data; // 如果未提供value参数,则直接返回历史数据
  669. // 如果数据有更新,则保存到本地存储
  670. if (data.length > data_length) GM_setValue("download_history", data);
  671. },
  672. /**
  673. * 检查并处理本地存储中的历史记录是否过时
  674. * @param {boolean} is_remove - 是否移除过时的历史记录
  675. * @returns {Array} - 如果不移除历史记录,则返回历史记录数组;否则无返回值
  676. */
  677. storage_obsolete: function (is_remove) {
  678. // 从本地存储获取历史记录,如果不存在则初始化为空数组
  679. let data = JSON.parse(localStorage.getItem("history") || "[]");
  680. // 如果is_remove为true,则移除本地存储中的历史记录
  681. if (is_remove) localStorage.removeItem("history");
  682. else return data;
  683. },
  684.  
  685. /**
  686. * 格式化日期字符串
  687. * @param {Date} i - 输入的日期对象
  688. * @param {string} o - 日期格式字符串
  689. * @param {boolean} tz - 是否考虑时区
  690. * @returns {string} - 格式化后的日期字符串
  691. */
  692. formatDate: function (i, o, tz) {
  693. // 创建日期对象
  694. let d = new Date(i);
  695. // 如果需要考虑时区,则调整日期对象到UTC时区
  696. if (tz) d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
  697. // 月份的缩写数组
  698. let m = [
  699. "JAN",
  700. "FEB",
  701. "MAR",
  702. "APR",
  703. "MAY",
  704. "JUN",
  705. "JUL",
  706. "AUG",
  707. "SEP",
  708. "OCT",
  709. "NOV",
  710. "DEC",
  711. ];
  712. // 用于替换日期格式字符串中的各种元素的对象
  713. let v = {
  714. YYYY: d.getUTCFullYear().toString(),
  715. YY: d.getUTCFullYear().toString(),
  716. MM: d.getUTCMonth() + 1,
  717. MMM: m[d.getUTCMonth()],
  718. DD: d.getUTCDate(),
  719. hh: d.getUTCHours(),
  720. mm: d.getUTCMinutes(),
  721. ss: d.getUTCSeconds(),
  722. h2: d.getUTCHours() % 12,
  723. ap: d.getUTCHours() < 12 ? "AM" : "PM",
  724. };
  725. // 使用正则表达式和替换规则格式化日期字符串
  726. return o.replace(/(YY(YY)?|MMM?|DD|hh|mm|ss|h2|ap)/g, (n) =>
  727. ("0" + v[n]).substr(-n.length)
  728. );
  729. },
  730. // 定义一个下载器对象
  731. downloader: (function () {
  732. // 初始化下载器相关变量
  733. let tasks = [],
  734. thread = 0,
  735. max_thread = 2,
  736. retry = 0,
  737. max_retry = 2,
  738. failed = 0,
  739. notifier,
  740. has_failed = false;
  741. // 返回一个具有下载管理功能的对象
  742. return {
  743. // 添加一个下载任务到队列
  744. add: function (task) {
  745. tasks.push(task);
  746. // 如果当前线程数小于最大线程数,则启动下一个任务
  747. if (thread < max_thread) {
  748. thread += 1;
  749. this.next();
  750. } else this.update();
  751. },
  752. // 异步执行下一个下载任务
  753. next: async function () {
  754. let task = tasks.shift();
  755. await this.start(task);
  756. // 如果还有任务且当前线程数未达到最大值,继续执行下一个任务
  757. if (tasks.length > 0 && thread <= max_thread) this.next();
  758. else thread -= 1;
  759. this.update();
  760. },
  761. // 开始下载指定任务
  762. start: function (task) {
  763. this.update();
  764. return new Promise((resolve) => {
  765. GM_download({
  766. url: task.url,
  767. name: task.name,
  768. onload: (result) => {
  769. task.onload();
  770. resolve();
  771. },
  772. onerror: (result) => {
  773. this.retry(task, result);
  774. resolve();
  775. },
  776. ontimeout: (result) => {
  777. this.retry(task, result);
  778. resolve();
  779. },
  780. });
  781. });
  782. },
  783. // 处理下载失败的情况,尝试重试或报告错误
  784. retry: function (task, result) {
  785. retry += 1;
  786. // 如果达到最大重试次数,将最大线程数降至1
  787. if (retry == 3) max_thread = 1;
  788. if (
  789. (task.retry && task.retry >= max_retry) ||
  790. (result.details && result.details.current == "USER_CANCELED")
  791. ) {
  792. task.onerror(result);
  793. failed += 1;
  794. } else {
  795. // 如果最大线程数为1,则增加重试次数
  796. if (max_thread == 1) task.retry = (task.retry || 0) + 1;
  797. this.add(task);
  798. }
  799. },
  800. // 更新下载器的状态信息
  801. update: function () {
  802. // 初始化或更新下载状态通知器
  803. if (!notifier) {
  804. notifier = document.createElement("div");
  805. notifier.title = "Twitter Media Downloader";
  806. notifier.classList.add("tmd-notifier");
  807. notifier.innerHTML = "<label>0</label>|<label>0</label>";
  808. document.body.appendChild(notifier);
  809. }
  810. // 更新失败任务的提示,并提供清除选项
  811. if (failed > 0 && !has_failed) {
  812. has_failed = true;
  813. notifier.innerHTML += "|";
  814. let clear = document.createElement("label");
  815. notifier.appendChild(clear);
  816. clear.onclick = () => {
  817. notifier.innerHTML = "<label>0</label>|<label>0</label>";
  818. failed = 0;
  819. has_failed = false;
  820. this.update();
  821. };
  822. }
  823. // 更新通知器中的下载进度和状态
  824. notifier.firstChild.innerText = thread;
  825. notifier.firstChild.nextElementSibling.innerText = tasks.length;
  826. if (failed > 0) notifier.lastChild.innerText = failed;
  827. if (thread > 0 || tasks.length > 0 || failed > 0)
  828. notifier.classList.add("running");
  829. else notifier.classList.remove("running");
  830. },
  831. };
  832. })(),
  833. // 定义支持的语言及其相关文本
  834. language: {
  835. en: {
  836. download: "Download",
  837. completed: "Download Completed",
  838. settings: "Settings",
  839. dialog: {
  840. title: "Download Settings",
  841. save: "Save",
  842. save_history: "Remember download history",
  843. clear_history: "(Clear)",
  844. clear_confirm: "Clear download history?",
  845. show_sensitive: "Always show sensitive content",
  846. pattern: "File Name Pattern",
  847. },
  848. },
  849. ja: {
  850. download: "ダウンロード",
  851. completed: "ダウンロード完了",
  852. settings: "設定",
  853. dialog: {
  854. title: "ダウンロード設定",
  855. save: "保存",
  856. save_history: "ダウンロード履歴を保存する",
  857. clear_history: "(クリア)",
  858. clear_confirm: "ダウンロード履歴を削除する?",
  859. show_sensitive: "センシティブな内容を常に表示する",
  860. pattern: "ファイル名パターン",
  861. },
  862. },
  863. zh: {
  864. download: "下载",
  865. completed: "下载完成",
  866. settings: "设置",
  867. dialog: {
  868. title: "下载设置",
  869. save: "保存",
  870. save_history: "保存下载记录",
  871. clear_history: "(清除)",
  872. clear_confirm: "确认要清除下载记录?",
  873. show_sensitive: "自动显示敏感的内容",
  874. pattern: "文件名格式",
  875. },
  876. },
  877. "zh-Hant": {
  878. download: "下載",
  879. completed: "下載完成",
  880. settings: "設置",
  881. dialog: {
  882. title: "下載設置",
  883. save: "保存",
  884. save_history: "保存下載記錄",
  885. clear_history: "(清除)",
  886. clear_confirm: "確認要清除下載記錄?",
  887. show_sensitive: "自動顯示敏感的内容",
  888. pattern: "文件名規則",
  889. },
  890. },
  891. },
  892. css: `
  893. .tmd-down {margin-left: 12px; order: 99;}
  894. .tmd-down:hover > div > div > div > div {color: rgba(29, 161, 242, 1.0);}
  895. .tmd-down:hover > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.1);}
  896. .tmd-down:active > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.2);}
  897. .tmd-down:hover svg {color: rgba(29, 161, 242, 1.0);}
  898. .tmd-down:hover div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.1);}
  899. .tmd-down:active div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.2);}
  900. .tmd-down.tmd-media {position: absolute; right: 0;}
  901. .tmd-down.tmd-media > div {display: flex; border-radius: 99px; margin: 2px;}
  902. .tmd-down.tmd-media > div > div {display: flex; margin: 6px; color: #fff;}
  903. .tmd-down.tmd-media:hover > div {background-color: rgba(255,255,255, 0.6);}
  904. .tmd-down.tmd-media:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  905. .tmd-down.tmd-media:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  906. .tmd-down g {display: none;}
  907. .tmd-down.download g.download, .tmd-down.completed g.completed, .tmd-down.loading g.loading,.tmd-down.failed g.failed {display: unset;}
  908. .tmd-down.loading svg {animation: spin 1s linear infinite;}
  909. @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}}
  910. .tmd-btn {display: inline-block; background-color: #1DA1F2; color: #FFFFFF; padding: 0 20px; border-radius: 99px;}
  911. .tmd-tag {display: inline-block; background-color: #FFFFFF; color: #1DA1F2; padding: 0 10px; border-radius: 10px; border: 1px solid #1DA1F2; font-weight: bold; margin: 5px;}
  912. .tmd-btn:hover {background-color: rgba(29, 161, 242, 0.9);}
  913. .tmd-tag:hover {background-color: rgba(29, 161, 242, 0.1);}
  914. .tmd-notifier {display: none; position: fixed; left: 16px; bottom: 16px; color: #000; background: #fff; border: 1px solid #ccc; border-radius: 8px; padding: 4px;}
  915. .tmd-notifier.running {display: flex; align-items: center;}
  916. .tmd-notifier label {display: inline-flex; align-items: center; margin: 0 8px;}
  917. .tmd-notifier label:before {content: " "; width: 32px; height: 16px; background-position: center; background-repeat: no-repeat;}
  918. .tmd-notifier label:nth-child(1):before {background-image:url("data:image/svg+xml;charset=utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2216%22 height=%2216%22 viewBox=%220 0 24 24%22><path d=%22M3,14 v5 q0,2 2,2 h14 q2,0 2,-2 v-5 M7,10 l4,4 q1,1 2,0 l4,-4 M12,3 v11%22 fill=%22none%22 stroke=%22%23666%22 stroke-width=%222%22 stroke-linecap=%22round%22 /></svg>");}
  919. .tmd-notifier label:nth-child(2):before {background-image:url("data:image/svg+xml;charset=utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2216%22 height=%2216%22 viewBox=%220 0 24 24%22><path d=%22M12,2 a1,1 0 0 1 0,20 a1,1 0 0 1 0,-20 M12,5 v7 h6%22 fill=%22none%22 stroke=%22%23999%22 stroke-width=%222%22 stroke-linejoin=%22round%22 stroke-linecap=%22round%22 /></svg>");}
  920. .tmd-notifier label:nth-child(3):before {background-image:url("data:image/svg+xml;charset=utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2216%22 height=%2216%22 viewBox=%220 0 24 24%22><path d=%22M12,0 a2,2 0 0 0 0,24 a2,2 0 0 0 0,-24%22 fill=%22%23f66%22 stroke=%22none%22 /><path d=%22M14.5,5 a1,1 0 0 0 -5,0 l0.5,9 a1,1 0 0 0 4,0 z M12,17 a2,2 0 0 0 0,5 a2,2 0 0 0 0,-5%22 fill=%22%23fff%22 stroke=%22none%22 /></svg>");}
  921. .tmd-down.tmd-img {position: absolute; right: 0; bottom: 0; display: none !important;}
  922. .tmd-down.tmd-img > div {display: flex; border-radius: 99px; margin: 2px; background-color: rgba(255,255,255, 0.6);}
  923. .tmd-down.tmd-img > div > div {display: flex; margin: 6px; color: #fff !important;}
  924. .tmd-down.tmd-img:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  925. .tmd-down.tmd-img:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  926. :hover > .tmd-down.tmd-img, .tmd-img.loading, .tmd-img.completed, .tmd-img.failed {display: block !important;}
  927. .tweet-detail-action-item {width: 20% !important;}
  928. `,
  929. css_ss: `
  930. /* show sensitive in media tab */
  931. li[role="listitem"]>div>div>div>div:not(:last-child) {filter: none;}
  932. li[role="listitem"]>div>div>div>div+div:last-child {display: none;}
  933. `,
  934. svg: `
  935. <g class="download"><path d="M3,14 v5 q0,2 2,2 h14 q2,0 2,-2 v-5 M7,10 l4,4 q1,1 2,0 l4,-4 M12,3 v11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></g>
  936. <g class="completed"><path d="M3,14 v5 q0,2 2,2 h14 q2,0 2,-2 v-5 M7,10 l3,4 q1,1 2,0 l8,-11" fill="none" stroke="#1DA1F2" stroke-width="2" stroke-linecap="round" /></g>
  937. <g class="loading"><circle cx="12" cy="12" r="10" fill="none" stroke="#1DA1F2" stroke-width="4" opacity="0.4" /><path d="M12,2 a10,10 0 0 1 10,10" fill="none" stroke="#1DA1F2" stroke-width="4" stroke-linecap="round" /></g>
  938. <g class="failed"><circle cx="12" cy="12" r="11" fill="#f33" stroke="currentColor" stroke-width="2" opacity="0.8" /><path d="M14,5 a1,1 0 0 0 -4,0 l0.5,9.5 a1.5,1.5 0 0 0 3,0 z M12,17 a2,2 0 0 0 0,4 a2,2 0 0 0 0,-4" fill="#fff" stroke="none" /></g>
  939. `,
  940. };
  941. })();
  942.  
  943. TMD.init();