[editVersion]Twitter 媒体下载

一键保存视频/图片

目前为 2025-02-25 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name [editVersion]Twitter/X Media Downloader
  3. // @name:ja [editVersion]Twitter/X Media Downloader
  4. // @name:zh-cn [editVersion]Twitter 媒体下载
  5. // @name:zh-tw [editVersion]Twitter 媒體下載
  6. // @description Save Video/Photo by One-Click.
  7. // @description:ja ワンクリックで動画・画像を保存する。
  8. // @description:zh-cn 一键保存视频/图片
  9. // @description:zh-tw 一鍵保存視頻/圖片
  10. // @version 2.0.1
  11. // @author AMANE
  12. // @namespace none
  13. // @match https://twitter.com/*
  14. // @match https://x.com/*
  15. // @match https://mobile.twitter.com/*
  16. // @grant GM_registerMenuCommand
  17. // @grant GM_setValue
  18. // @grant GM_getValue
  19. // @grant GM_download
  20. // @compatible Chrome
  21. // @compatible Firefox
  22. // @license MIT
  23. // ==/UserScript==
  24. /* jshint esversion: 8 */
  25.  
  26. // tag_ppEdit
  27.  
  28. function timestampToYMDHMS(timestamp) {
  29. const date = new Date(timestamp);
  30. const year = date.getUTCFullYear();
  31. const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); // 月份是从0開始的
  32. const day = ('0' + date.getUTCDate()).slice(-2);
  33. const hours = ('0' + date.getUTCHours()).slice(-2);
  34. const minutes = ('0' + date.getUTCMinutes()).slice(-2);
  35. const seconds = ('0' + date.getUTCSeconds()).slice(-2);
  36.  
  37. return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  38. }
  39.  
  40. const filename = 'twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}';
  41.  
  42. let divWidth = 700;
  43. let divHeight = 700;
  44. let timeOffset = 8 * 60 * 60 * 1000;
  45. let reversePreViewLeftRight = true
  46. let imageSize = ["small", "medium", "Orig"]
  47. let imageSizeIndex = 1;
  48.  
  49. // tag_ppEdit
  50. let previewDiv = document.createElement("div");
  51.  
  52. previewDiv.id = "helloTwitterMedia";
  53. previewDiv.style.position = "fixed";
  54. previewDiv.style.backgroundColor = "white";
  55. previewDiv.style.border = "1px solid #ccc";
  56. previewDiv.style.display = "none";
  57.  
  58. let previewImg = document.createElement("img");
  59. previewImg.id = "previewImg";
  60. previewImg.style.maxWidth = "100%";
  61. previewImg.style.maxHeight = "100%";
  62. previewDiv.appendChild(previewImg);
  63.  
  64. const TMD = (function () {
  65. let lang, host, history, show_sensitive, is_tweetdeck;
  66. return {
  67. init: async function () {
  68. GM_registerMenuCommand((this.language[navigator.language] || this.language.en).settings, this.settings);
  69. lang = this.language[document.querySelector('html').lang] || this.language.en;
  70. host = location.hostname;
  71. is_tweetdeck = host.indexOf('tweetdeck') >= 0;
  72. history = this.storage_obsolete();
  73. if (history.length) {
  74. this.storage(history);
  75. this.storage_obsolete(true);
  76. } else history = await this.storage();
  77. show_sensitive = GM_getValue('show_sensitive', false);
  78. document.head.insertAdjacentHTML('beforeend', '<style>' + this.css + (show_sensitive ? this.css_ss : '') + '</style>');
  79. let observer = new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(node => this.detect(node))));
  80. observer.observe(document.body, {childList: true, subtree: true});
  81. // preview
  82. divWidth = GM_getValue('previewWidth', 700);
  83. divHeight = GM_getValue('previewHeight', 700);
  84. previewDiv.style.width = divWidth + "px";
  85. previewDiv.style.height = divHeight + "px";
  86. document.body.appendChild(previewDiv);
  87.  
  88. function movePreviewDiv(clientX, clientY, divWidth, divHeight) {
  89. const previewDiv = document.getElementById("helloTwitterMedia");
  90.  
  91. // 获取窗口的宽度和高度
  92. const windowWidth = window.innerWidth;
  93. const windowHeight = window.innerHeight;
  94.  
  95. // 左右上下超出的距离
  96. let leftOutLen = clientX - divWidth;
  97. let topOutLen = clientY - divHeight;
  98. let rightOutLen = windowWidth - clientX - divWidth;
  99. let bottomOutLen = windowHeight - clientY - divHeight;
  100.  
  101. let targetLeft = leftOutLen < rightOutLen ? clientX + 10 : clientX - divWidth - 10;
  102. let targetTop = topOutLen < bottomOutLen ? clientY + 10 : clientY - divHeight - 10;
  103. // 上下和左右只能调一个 , 否则鼠标会和窗口重叠 , 鉴于一般窗口都是宽的 , 那么只调整上下
  104. targetTop = targetTop < 0 ? 0 : targetTop;
  105. let maxTop = windowHeight - divHeight;
  106. targetTop = targetTop > maxTop ? maxTop : targetTop;
  107.  
  108. previewDiv.style.left = targetLeft + "px";
  109. previewDiv.style.top = targetTop + "px";
  110. }
  111.  
  112. let lastNode;
  113. let lastTime = Date.now();
  114.  
  115. document.addEventListener("mousemove", function (event) {
  116. // 100fps
  117. if (Date.now() - lastTime < 10) {
  118. return;
  119. }
  120. lastTime = Date.now();
  121. let node = event.target;
  122. let nodeSrc = node.src;
  123. if (nodeSrc == null || !nodeSrc.includes("pbs.twimg.com/media")) {
  124. previewDiv.style.display = "none";
  125. return;
  126. }
  127. if (node !== lastNode) {
  128. // // 网上搜了,总共四种 &name=small 、 &name=medium 、 &name=Large 、 &name=Orig
  129. previewImg.src = event.target.src
  130. .replace("name=small", "name=" + imageSize[imageSizeIndex]);
  131. }
  132. previewDiv.style.display = "block";
  133. console.log("[documentNode] mousemove ")
  134. lastNode = node;
  135. movePreviewDiv(event.clientX, event.clientY, divWidth, divHeight);
  136. });
  137.  
  138. },
  139. detect: function (node) {
  140. let article = node.tagName == 'ARTICLE' && node || node.tagName == 'DIV' && (node.querySelector('article') || node.closest('article'));
  141. if (article) this.addButtonTo(article);
  142. let listitems = node.tagName == 'LI' && node.getAttribute('role') == 'listitem' && [node] || node.tagName == 'DIV' && node.querySelectorAll('li[role="listitem"]');
  143. if (listitems) this.addButtonToMedia(listitems);
  144. },
  145. addButtonTo: function (article) {
  146. if (article.dataset.detected) return;
  147. article.dataset.detected = 'true';
  148. let media_selector = [
  149. 'a[href*="/photo/1"]',
  150. 'div[role="progressbar"]',
  151. 'button[data-testid="playButton"]',
  152. 'a[href="/settings/content_you_see"]', //hidden content
  153. 'div.media-image-container', // for tweetdeck
  154. 'div.media-preview-container', // for tweetdeck
  155. 'div[aria-labelledby]>div:first-child>div[role="button"][tabindex="0"]' //for audio (experimental)
  156. ];
  157. let media = article.querySelector(media_selector.join(','));
  158. if (media) {
  159. let status_id = article.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift();
  160. let btn_group = article.querySelector('div[role="group"]:last-of-type, ul.tweet-actions, ul.tweet-detail-actions');
  161. let btn_share = Array.from(btn_group.querySelectorAll(':scope>div>div, li.tweet-action-item>a, li.tweet-detail-action-item>a')).pop().parentNode;
  162. let btn_down = btn_share.cloneNode(true);
  163. btn_down.querySelector('button').removeAttribute('disabled');
  164. if (is_tweetdeck) {
  165. btn_down.firstElementChild.innerHTML = '<svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' + this.svg + '</svg>';
  166. btn_down.firstElementChild.removeAttribute('rel');
  167. btn_down.classList.replace("pull-left", "pull-right");
  168. } else {
  169. btn_down.querySelector('svg').innerHTML = this.svg;
  170. }
  171. let is_exist = history.indexOf(status_id) >= 0;
  172. this.status(btn_down, 'tmd-down');
  173. this.status(btn_down, is_exist ? 'completed' : 'download', is_exist ? lang.completed : lang.download);
  174. btn_group.insertBefore(btn_down, btn_share.nextSibling);
  175. btn_down.onclick = () => this.click(btn_down, status_id, is_exist);
  176. if (show_sensitive) {
  177. let btn_show = article.querySelector('div[aria-labelledby] div[role="button"][tabindex="0"]:not([data-testid]) > div[dir] > span > span');
  178. if (btn_show) btn_show.click();
  179. }
  180. }
  181. let imgs = article.querySelectorAll('a[href*="/photo/"]');
  182. if (imgs.length > 1) {
  183. let status_id = article.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift();
  184. let btn_group = article.querySelector('div[role="group"]:last-of-type');
  185. let btn_share = Array.from(btn_group.querySelectorAll(':scope>div>div')).pop().parentNode;
  186. imgs.forEach(img => {
  187. let index = img.href.split('/status/').pop().split('/').pop();
  188. let is_exist = history.indexOf(status_id) >= 0;
  189. let btn_down = document.createElement('div');
  190. btn_down.innerHTML = '<div><div><svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' + this.svg + '</svg></div></div>';
  191. btn_down.classList.add('tmd-down', 'tmd-img');
  192. this.status(btn_down, 'download');
  193. img.parentNode.appendChild(btn_down);
  194. btn_down.onclick = e => {
  195. e.preventDefault();
  196. this.click(btn_down, status_id, is_exist, index);
  197. }
  198. });
  199. }
  200. },
  201. addButtonToMedia: function (listitems) {
  202. listitems.forEach(li => {
  203. if (li.dataset.detected) return;
  204. li.dataset.detected = 'true';
  205. let status_id = li.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift();
  206. let is_exist = history.indexOf(status_id) >= 0;
  207. let btn_down = document.createElement('div');
  208. btn_down.innerHTML = '<div><div><svg viewBox="0 0 24 24" style="width: 18px; height: 18px;">' + this.svg + '</svg></div></div>';
  209. btn_down.classList.add('tmd-down', 'tmd-media');
  210. this.status(btn_down, is_exist ? 'completed' : 'download', is_exist ? lang.completed : lang.download);
  211. li.appendChild(btn_down);
  212. btn_down.onclick = () => this.click(btn_down, status_id, is_exist);
  213. });
  214. },
  215. click: async function (btn, status_id, is_exist, index) {
  216.  
  217. // tag_ppEdit001
  218. console.log(" 当前的推文id ", status_id)
  219. // 喜欢推文的接口
  220. let favoriteResult = await this.favoriteTweet(status_id, "lI07N6Otwv1PhnEgXILM7A");
  221. let res = this.displayFavoriteResult(favoriteResult, status_id);
  222. if (res == null || !res) {
  223. console.log(" 已经like过了 , 不下载 ")
  224. history.push(status_id);
  225. await this.storage(status_id);
  226. this.status(btn, 'completed', lang.completed);
  227. return;
  228. }
  229.  
  230. if (btn.classList.contains('loading')) return;
  231. this.status(btn, 'loading');
  232. let out = (await GM_getValue('filename', filename)).split('\n').join('');
  233. let save_history = await GM_getValue('save_history', true);
  234. let json = await this.fetchJson(status_id);
  235. let tweet = json.legacy;
  236. let user = json.core.user_results.result.legacy;
  237. let invalid_chars = {
  238. '\\': '\',
  239. '\/': '/',
  240. '\|': '|',
  241. '<': '<',
  242. '>': '>',
  243. ':': ':',
  244. '*': '*',
  245. '?': '?',
  246. '"': '"',
  247. '\u200b': '',
  248. '\u200c': '',
  249. '\u200d': '',
  250. '\u2060': '',
  251. '\ufeff': '',
  252. '🔞': ''
  253. };
  254. let datetime = out.match(/{date-time(-local)?:[^{}]+}/) ? out.match(/{date-time(?:-local)?:([^{}]+)}/)[1].replace(/[\\/|<>*?:"]/g, v => invalid_chars[v]) : 'YYYYMMDD-hhmmss';
  255. let info = {};
  256. info['status-id'] = status_id;
  257. info['user-name'] = user.name.replace(/([\\/|*?:"]|[\u200b-\u200d\u2060\ufeff]|🔞)/g, v => invalid_chars[v]);
  258. info['user-id'] = user.screen_name;
  259. info['date-time'] = this.formatDate(tweet.created_at, datetime);
  260. info['date-time-local'] = this.formatDate(tweet.created_at, datetime, true);
  261. info['full-text'] = tweet.full_text.split('\n').join(' ').replace(/\s*https:\/\/t\.co\/\w+/g, '').replace(/[\\/|<>*?:"]|[\u200b-\u200d\u2060\ufeff]/g, v => invalid_chars[v]);
  262. let medias = tweet.extended_entities && tweet.extended_entities.media;
  263. if (index) medias = [medias[index - 1]];
  264. if (medias.length > 0) {
  265. let tasks = medias.length;
  266. let tasks_result = [];
  267. medias.forEach((media, i) => {
  268. info.url = media.type == 'photo' ? media.media_url_https + ':orig' : media.video_info.variants.filter(n => n.content_type == 'video/mp4').sort((a, b) => b.bitrate - a.bitrate)[0].url;
  269. info.file = info.url.split('/').pop().split(/[:?]/).shift();
  270. info['file-name'] = info.file.split('.').shift();
  271. info['file-ext'] = info.file.split('.').pop();
  272. info['file-type'] = media.type.replace('animated_', '');
  273. info.out = (out.replace(/\.?{file-ext}/, '') + ((medias.length > 1 || index) && !out.match('{file-name}') ? '-' + (index ? index : i) : '') + '.{file-ext}').replace(/{([^{}:]+)(:[^{}]+)?}/g, (match, name) => info[name]);
  274. this.downloader.add({
  275. url: info.url,
  276. name: info.out,
  277. onload: () => {
  278. tasks -= 1;
  279. tasks_result.push(((medias.length > 1 || index) ? (index ? index : i + 1) + ': ' : '') + lang.completed);
  280. this.status(btn, null, tasks_result.sort().join('\n'));
  281. if (tasks === 0) {
  282. this.status(btn, 'completed', lang.completed);
  283. if (save_history && !is_exist) {
  284. history.push(status_id);
  285. this.storage(status_id);
  286. }
  287. }
  288. },
  289. onerror: result => {
  290. tasks = -1;
  291. tasks_result.push((medias.length > 1 ? i + 1 + ': ' : '') + result.details.current);
  292. this.status(btn, 'failed', tasks_result.sort().join('\n'));
  293. }
  294. });
  295. });
  296. } else {
  297. this.status(btn, 'failed', 'MEDIA_NOT_FOUND');
  298. }
  299. },
  300. status: function (btn, css, title, style) {
  301. if (css) {
  302. btn.classList.remove('download', 'completed', 'loading', 'failed');
  303. btn.classList.add(css);
  304. }
  305. if (title) btn.title = title;
  306. if (style) btn.style.cssText = style;
  307. },
  308. settings: async function () {
  309. const $element = (parent, tag, style, content, css) => {
  310. let el = document.createElement(tag);
  311. if (style) el.style.cssText = style;
  312. if (typeof content !== 'undefined') {
  313. if (tag == 'input') {
  314. if (content == 'checkbox') el.type = content;
  315. else el.value = content;
  316. } else el.innerHTML = content;
  317. }
  318. if (css) css.split(' ').forEach(c => el.classList.add(c));
  319. parent.appendChild(el);
  320. return el;
  321. };
  322. let wapper = $element(document.body, 'div', 'position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: #0009; z-index: 10;');
  323. let wapper_close;
  324. wapper.onmousedown = e => {
  325. wapper_close = e.target == wapper;
  326. };
  327. wapper.onmouseup = e => {
  328. if (wapper_close && e.target == wapper) wapper.remove();
  329. };
  330. let dialog = $element(wapper, 'div', '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;');
  331. let title = $element(dialog, 'h3', 'margin: 10px 20px;', lang.dialog.title);
  332. let options = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;');
  333. let save_history_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.save_history);
  334. let save_history_input = $element(save_history_label, 'input', 'float: left;', 'checkbox');
  335. let widthHeightDiv = $element(options, 'div', 'margin: 1px 2px;', lang.dialog.width + "," + lang.dialog.height);
  336. let preview_width_input = $element(widthHeightDiv, 'input', 'float: right;', GM_getValue('previewWidth'));
  337. let preview_height_input = $element(widthHeightDiv, 'input', 'float: right;', GM_getValue('previewHeight'));
  338. save_history_input.checked = await GM_getValue('save_history', true);
  339. save_history_input.onchange = () => {
  340. GM_setValue('save_history', save_history_input.checked);
  341. }
  342. preview_width_input.onchange = () => {
  343. let newPreviewWidth = preview_width_input.value;
  344. console.log(" 预览宽度变化 : ", newPreviewWidth);
  345. GM_setValue('previewWidth', newPreviewWidth);
  346. divWidth = newPreviewWidth;
  347. previewDiv.style.width = newPreviewWidth + "px";
  348. }
  349. preview_height_input.onchange = () => {
  350. let newPreviewHeight = preview_height_input.value;
  351. console.log(" 预览高度变化 : ", newPreviewHeight);
  352. GM_setValue('previewHeight', newPreviewHeight);
  353. divHeight = newPreviewHeight;
  354. previewDiv.style.height = newPreviewHeight + "px";
  355. }
  356. let clear_history = $element(save_history_label, 'label', 'display: inline-block; margin: 0 10px; color: blue;', lang.dialog.clear_history);
  357. clear_history.onclick = () => {
  358. if (confirm(lang.dialog.clear_confirm)) {
  359. history = [];
  360. GM_setValue('download_history', []);
  361. }
  362. };
  363. let show_sensitive_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.show_sensitive);
  364. let show_sensitive_input = $element(show_sensitive_label, 'input', 'float: left;', 'checkbox');
  365. show_sensitive_input.checked = await GM_getValue('show_sensitive', false);
  366. show_sensitive_input.onchange = () => {
  367. show_sensitive = show_sensitive_input.checked;
  368. GM_setValue('show_sensitive', show_sensitive);
  369. };
  370. let filename_div = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;');
  371. let filename_label = $element(filename_div, 'label', 'display: block; margin: 10px 15px;', lang.dialog.pattern);
  372. let filename_input = $element(filename_label, 'textarea', 'display: block; min-width: 500px; max-width: 500px; min-height: 100px; font-size: inherit; background: white; color: black;', await GM_getValue('filename', filename));
  373. let filename_tags = $element(filename_div, 'label', 'display: table; margin: 10px;', `
  374. <span class="tmd-tag" title="user name">{user-name}</span>
  375. <span class="tmd-tag" title="The user name after @ sign.">{user-id}</span>
  376. <span class="tmd-tag" title="example: 1234567890987654321">{status-id}</span>
  377. <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>
  378. <span class="tmd-tag" title="Text content in tweet.">{full-text}</span>
  379. <span class="tmd-tag" title="Type of &#34;video&#34; or &#34;photo&#34; or &#34;gif&#34;.">{file-type}</span>
  380. <span class="tmd-tag" title="Original filename from URL.">{file-name}</span>
  381. `);
  382. filename_input.selectionStart = filename_input.value.length;
  383. filename_tags.querySelectorAll('.tmd-tag').forEach(tag => {
  384. tag.onclick = () => {
  385. let ss = filename_input.selectionStart;
  386. let se = filename_input.selectionEnd;
  387. filename_input.value = filename_input.value.substring(0, ss) + tag.innerText + filename_input.value.substring(se);
  388. filename_input.selectionStart = ss + tag.innerText.length;
  389. filename_input.selectionEnd = ss + tag.innerText.length;
  390. filename_input.focus();
  391. };
  392. });
  393. let btn_save = $element(title, 'label', 'float: right;', lang.dialog.save, 'tmd-btn');
  394. btn_save.onclick = async () => {
  395. await GM_setValue('filename', filename_input.value);
  396. wapper.remove();
  397. };
  398. },
  399. fetchJson: async function (status_id) {
  400. let base_url = `https://${host}/i/api/graphql/NmCeCgkVlsRGS1cAwqtgmw/TweetDetail`;
  401. let variables = {
  402. "focalTweetId": status_id,
  403. "with_rux_injections": false,
  404. "includePromotedContent": true,
  405. "withCommunity": true,
  406. "withQuickPromoteEligibilityTweetFields": true,
  407. "withBirdwatchNotes": true,
  408. "withVoice": true,
  409. "withV2Timeline": true
  410. };
  411. let features = {
  412. "rweb_lists_timeline_redesign_enabled": true,
  413. "responsive_web_graphql_exclude_directive_enabled": true,
  414. "verified_phone_label_enabled": false,
  415. "creator_subscriptions_tweet_preview_api_enabled": true,
  416. "responsive_web_graphql_timeline_navigation_enabled": true,
  417. "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
  418. "tweetypie_unmention_optimization_enabled": true,
  419. "responsive_web_edit_tweet_api_enabled": true,
  420. "graphql_is_translatable_rweb_tweet_is_translatable_enabled": true,
  421. "view_counts_everywhere_api_enabled": true,
  422. "longform_notetweets_consumption_enabled": true,
  423. "responsive_web_twitter_article_tweet_consumption_enabled": false,
  424. "tweet_awards_web_tipping_enabled": false,
  425. "freedom_of_speech_not_reach_fetch_enabled": true,
  426. "standardized_nudges_misinfo": true,
  427. "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": true,
  428. "longform_notetweets_rich_text_read_enabled": true,
  429. "longform_notetweets_inline_media_enabled": true,
  430. "responsive_web_media_download_video_enabled": false,
  431. "responsive_web_enhance_cards_enabled": false
  432. };
  433. let url = encodeURI(`${base_url}?variables=${JSON.stringify(variables)}&features=${JSON.stringify(features)}`);
  434. let cookies = this.getCookie();
  435. let headers = {
  436. 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  437. 'x-twitter-active-user': 'yes',
  438. 'x-twitter-client-language': cookies.lang,
  439. 'x-csrf-token': cookies.ct0
  440. };
  441. if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt;
  442. let tweet_detail = await fetch(url, {headers: headers}).then(result => result.json());
  443. let tweet_entrie = tweet_detail.data.threaded_conversation_with_injections_v2.instructions[0].entries.find(n => n.entryId == `tweet-${status_id}`);
  444. let tweet_result = tweet_entrie.content.itemContent.tweet_results.result;
  445. return tweet_result.tweet || tweet_result;
  446. },
  447. // tag_ppEdit
  448. favoriteTweet: async function (tweet_id, queryId) {
  449. let base_url = `https://${host}/i/api/graphql/${queryId}/FavoriteTweet`;
  450. let variables = {
  451. "tweet_id": tweet_id
  452. };
  453. // let queryId = "lI07N6Otwv1PhnEgXILM7A";
  454. let body = JSON.stringify({
  455. variables: variables,
  456. queryId: queryId
  457. });
  458. let cookies = this.getCookie();
  459. let headers = {
  460. 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  461. 'x-twitter-active-user': 'yes',
  462. 'x-twitter-client-language': cookies.lang,
  463. 'x-csrf-token': cookies.ct0,
  464. 'content-type': 'application/json' // 添加 content-type 头
  465. };
  466. if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt;
  467.  
  468. try {
  469. let response = await fetch(base_url, {
  470. method: 'POST',
  471. headers: headers,
  472. body: body
  473. });
  474. let result = await response.json();
  475. console.log("Favorite Tweet Response:", result);
  476. return result;
  477. } catch (error) {
  478. console.error("Error favoriting tweet:", error);
  479. return null;
  480. }
  481. },
  482.  
  483. // tag_ppEdit
  484. displayFavoriteResult: function (result, status_id) {
  485. let favoriteDiv = document.getElementById('favorite-result');
  486. if (!favoriteDiv) {
  487. favoriteDiv = document.createElement('div');
  488. favoriteDiv.id = 'favorite-result';
  489. favoriteDiv.style.position = 'fixed';
  490. // favoriteDiv.style.top = '10px';
  491. // favoriteDiv.style.left = '10px';
  492. favoriteDiv.style.top = '2px';
  493. favoriteDiv.style.left = '2px';
  494. favoriteDiv.style.backgroundColor = '#fff';
  495. // favoriteDiv.style.padding = '10px';
  496. favoriteDiv.style.border = '1px solid #ccc';
  497. favoriteDiv.style.zIndex = '1000';
  498. favoriteDiv.style.color = "black";
  499. favoriteDiv.style.fontSize = "10px";
  500. document.body.appendChild(favoriteDiv);
  501. }
  502. let data = {};
  503. data.result = result;
  504. data.time = timestampToYMDHMS(Date.now() + timeOffset);
  505. data.status_id = status_id;
  506. favoriteDiv.innerHTML = result ? JSON.stringify(data, null, 2) : 'Failed to favorite tweet';
  507. return result.data != null && result.data.favorite_tweet != null && result.data.favorite_tweet === 'Done';
  508. },
  509. getCookie: function (name) {
  510. let cookies = {};
  511. document.cookie.split(';').filter(n => n.indexOf('=') > 0).forEach(n => {
  512. n.replace(/^([^=]+)=(.+)$/, (match, name, value) => {
  513. cookies[name.trim()] = value.trim();
  514. });
  515. });
  516. return name ? cookies[name] : cookies;
  517. },
  518. storage: async function (value) {
  519. let data = await GM_getValue('download_history', []);
  520. let data_length = data.length;
  521. if (value) {
  522. if (Array.isArray(value)) data = data.concat(value);
  523. else if (data.indexOf(value) < 0) data.push(value);
  524. } else return data;
  525. if (data.length > data_length) GM_setValue('download_history', data);
  526. },
  527. storage_obsolete: function (is_remove) {
  528. let data = JSON.parse(localStorage.getItem('history') || '[]');
  529. if (is_remove) localStorage.removeItem('history');
  530. else return data;
  531. },
  532. formatDate: function (i, o, tz) {
  533. let d = new Date(i);
  534. if (tz) d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
  535. let m = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
  536. let v = {
  537. YYYY: d.getUTCFullYear().toString(),
  538. YY: d.getUTCFullYear().toString(),
  539. MM: d.getUTCMonth() + 1,
  540. MMM: m[d.getUTCMonth()],
  541. DD: d.getUTCDate(),
  542. hh: d.getUTCHours(),
  543. mm: d.getUTCMinutes(),
  544. ss: d.getUTCSeconds(),
  545. h2: d.getUTCHours() % 12,
  546. ap: d.getUTCHours() < 12 ? 'AM' : 'PM'
  547. };
  548. return o.replace(/(YY(YY)?|MMM?|DD|hh|mm|ss|h2|ap)/g, n => ('0' + v[n]).substr(-n.length));
  549. },
  550. downloader: (function () {
  551. let tasks = [], thread = 0, max_thread = 2, retry = 0, max_retry = 2, failed = 0, notifier,
  552. has_failed = false;
  553. return {
  554. add: function (task) {
  555. tasks.push(task);
  556. if (thread < max_thread) {
  557. thread += 1;
  558. this.next();
  559. } else this.update();
  560. },
  561. next: async function () {
  562. let task = tasks.shift();
  563. await this.start(task);
  564. if (tasks.length > 0 && thread <= max_thread) this.next();
  565. else thread -= 1;
  566. this.update();
  567. },
  568. start: function (task) {
  569. this.update();
  570. return new Promise(resolve => {
  571. GM_download({
  572. url: task.url,
  573. name: task.name,
  574. onload: result => {
  575. task.onload();
  576. resolve();
  577. },
  578. onerror: result => {
  579. this.retry(task, result);
  580. resolve();
  581. },
  582. ontimeout: result => {
  583. this.retry(task, result);
  584. resolve();
  585. }
  586. });
  587. });
  588. },
  589. retry: function (task, result) {
  590. retry += 1;
  591. if (retry == 3) max_thread = 1;
  592. if (task.retry && task.retry >= max_retry ||
  593. result.details && result.details.current == 'USER_CANCELED') {
  594. task.onerror(result);
  595. failed += 1;
  596. } else {
  597. if (max_thread == 1) task.retry = (task.retry || 0) + 1;
  598. this.add(task);
  599. }
  600. },
  601. update: function () {
  602. if (!notifier) {
  603. notifier = document.createElement('div');
  604. notifier.title = 'Twitter Media Downloader';
  605. notifier.classList.add('tmd-notifier');
  606. notifier.innerHTML = '<label>0</label>|<label>0</label>';
  607. document.body.appendChild(notifier);
  608. }
  609. if (failed > 0 && !has_failed) {
  610. has_failed = true;
  611. notifier.innerHTML += '|';
  612. let clear = document.createElement('label');
  613. notifier.appendChild(clear);
  614. clear.onclick = () => {
  615. notifier.innerHTML = '<label>0</label>|<label>0</label>';
  616. failed = 0;
  617. has_failed = false;
  618. this.update();
  619. };
  620. }
  621. notifier.firstChild.innerText = thread;
  622. notifier.firstChild.nextElementSibling.innerText = tasks.length;
  623. if (failed > 0) notifier.lastChild.innerText = failed;
  624. if (thread > 0 || tasks.length > 0 || failed > 0) notifier.classList.add('running');
  625. else notifier.classList.remove('running');
  626. }
  627. };
  628. })(),
  629. language: {
  630. en: {
  631. download: 'Download',
  632. completed: 'Download Completed',
  633. settings: 'Settings',
  634. dialog: {
  635. title: 'Download Settings',
  636. save: 'Save',
  637. width: "width",
  638. height: "height",
  639. save_history: 'Remember download history',
  640. clear_history: '(Clear)',
  641. clear_confirm: 'Clear download history?',
  642. show_sensitive: 'Always show sensitive content',
  643. pattern: 'File Name Pattern'
  644. }
  645. },
  646. ja: {
  647. download: 'ダウンロード',
  648. completed: 'ダウンロード完了',
  649. settings: '設定',
  650. dialog: {
  651. title: 'ダウンロード設定',
  652. save: '保存',
  653. width: "width",
  654. height: "height",
  655. save_history: 'ダウンロード履歴を保存する',
  656. clear_history: '(クリア)',
  657. clear_confirm: 'ダウンロード履歴を削除する?',
  658. show_sensitive: 'センシティブな内容を常に表示する',
  659. pattern: 'ファイル名パターン'
  660. }
  661. },
  662. zh: {
  663. download: '下载',
  664. completed: '下载完成',
  665. settings: '设置',
  666. dialog: {
  667. title: '下载设置',
  668. save: '保存',
  669. width: "width",
  670. height: "height",
  671. save_history: '保存下载记录',
  672. clear_history: '(清除)',
  673. clear_confirm: '确认要清除下载记录?',
  674. show_sensitive: '自动显示敏感的内容',
  675. pattern: '文件名格式'
  676. }
  677. },
  678. 'zh-Hant': {
  679. download: '下載',
  680. completed: '下載完成',
  681. settings: '設置',
  682. dialog: {
  683. title: '下載設置',
  684. save: '保存',
  685. width: "width",
  686. height: "height",
  687. save_history: '保存下載記錄',
  688. clear_history: '(清除)',
  689. clear_confirm: '確認要清除下載記錄?',
  690. show_sensitive: '自動顯示敏感的内容',
  691. pattern: '文件名規則'
  692. }
  693. }
  694. },
  695. css: `
  696. .tmd-down {margin-left: 12px; order: 99;}
  697. .tmd-down:hover > div > div > div > div {color: rgba(29, 161, 242, 1.0);}
  698. .tmd-down:hover > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.1);}
  699. .tmd-down:active > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.2);}
  700. .tmd-down:hover svg {color: rgba(29, 161, 242, 1.0);}
  701. .tmd-down:hover div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.1);}
  702. .tmd-down:active div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.2);}
  703. .tmd-down.tmd-media {position: absolute; right: 0;}
  704. .tmd-down.tmd-media > div {display: flex; border-radius: 99px; margin: 2px;}
  705. .tmd-down.tmd-media > div > div {display: flex; margin: 6px; color: #fff;}
  706. .tmd-down.tmd-media:hover > div {background-color: rgba(255,255,255, 0.6);}
  707. .tmd-down.tmd-media:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  708. .tmd-down.tmd-media:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  709. .tmd-down g {display: none;}
  710. .tmd-down.download g.download, .tmd-down.completed g.completed, .tmd-down.loading g.loading,.tmd-down.failed g.failed {display: unset;}
  711. .tmd-down.loading svg {animation: spin 1s linear infinite;}
  712. @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}}
  713. .tmd-btn {display: inline-block; background-color: #1DA1F2; color: #FFFFFF; padding: 0 20px; border-radius: 99px;}
  714. .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;}
  715. .tmd-btn:hover {background-color: rgba(29, 161, 242, 0.9);}
  716. .tmd-tag:hover {background-color: rgba(29, 161, 242, 0.1);}
  717. .tmd-notifier {display: none; position: fixed; left: 16px; bottom: 16px; color: #000; background: #fff; border: 1px solid #ccc; border-radius: 8px; padding: 4px;}
  718. .tmd-notifier.running {display: flex; align-items: center;}
  719. .tmd-notifier label {display: inline-flex; align-items: center; margin: 0 8px;}
  720. .tmd-notifier label:before {content: " "; width: 32px; height: 16px; background-position: center; background-repeat: no-repeat;}
  721. .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>");}
  722. .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>");}
  723. .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>")}
  724. .tmd-down.tmd-img {position: absolute; right: 0; bottom: 0; display: none !important;}
  725. .tmd-down.tmd-img > div {display: flex; border-radius: 99px; margin: 2px; background-color: rgba(255,255,255, 0.6);}
  726. .tmd-down.tmd-img > div > div {display: flex; margin: 6px; color: #fff !important;}
  727. .tmd-down.tmd-img:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  728. .tmd-down.tmd-img:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  729. :hover > .tmd-down.tmd-img, .tmd-img.loading, .tmd-img.completed, .tmd-img.failed {display: block !important;}
  730. .tweet-detail-action-item {width: 20% !important;}
  731. `,
  732. css_ss: `
  733. /* show sensitive in media tab */
  734. li[role="listitem"]>div>div>div>div:not(:last-child) {filter: none;}
  735. li[role="listitem"]>div>div>div>div+div:last-child {display: none;}
  736. `,
  737. svg: `
  738. <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>
  739. <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>
  740. <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>
  741. <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>
  742. `
  743. };
  744. })();
  745.  
  746. TMD.init();
  747.