[editVersion]Twitter Media Downloader[2504fix]

Save Video/Photo by One-Click.

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