【Mod】Twitter Media Downloader

Save Video/Photo by One-Click.

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