[editVersion]Twitter 媒体下载

一键保存视频/图片

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

QingJ © 2025

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