[editVersion]Twitter 媒体下载[2504fix]

一键保存视频/图片

  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.3
  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. 'content-type': 'application/json', // 添加 content-type 头
  367. 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  368. 'x-twitter-active-user': 'yes',
  369. 'x-twitter-client-language': cookies.lang,
  370. 'x-csrf-token': cookies.ct0
  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 widthHeightDiv = $element(options, 'div', 'margin: 1px 2px;background: white;', lang.dialog.width + "," + lang.dialog.height);
  436. let preview_height_input = $element(widthHeightDiv, 'input', 'float: right;background: white;', GM_getValue('previewHeight'));
  437. let preview_width_input = $element(widthHeightDiv, 'input', 'float: right;background: white;', GM_getValue('previewWidth'));
  438. let previewSetDiv = $element(options, 'div', 'margin: 1px 2px;', "preOnOff,previewOnSide(other is on center)");
  439. let previewSwitchDiv = $element(previewSetDiv, 'input', 'float: right;', "checkbox");
  440. let previewOnSideDiv = $element(previewSetDiv, 'input', 'float: right;', "checkbox");
  441.  
  442.  
  443. save_history_input.checked = await GM_getValue('save_history', true);
  444. save_history_input.onchange = () => {
  445. GM_setValue('save_history', save_history_input.checked);
  446. }
  447. preview_width_input.onchange = () => {
  448. let newPreviewWidth = preview_width_input.value;
  449. console.log(" 预览宽度变化 : ", newPreviewWidth);
  450. GM_setValue('previewWidth', newPreviewWidth);
  451. divWidth = newPreviewWidth;
  452. previewDiv.style.width = newPreviewWidth + "px";
  453. }
  454. preview_height_input.onchange = () => {
  455. let newPreviewHeight = preview_height_input.value;
  456. console.log(" 预览高度变化 : ", newPreviewHeight);
  457. GM_setValue('previewHeight', newPreviewHeight);
  458. divHeight = newPreviewHeight;
  459. previewDiv.style.height = newPreviewHeight + "px";
  460. }
  461. previewSwitchDiv.onchange = () => {
  462. previewSwitch = previewSwitchDiv.checked;
  463. console.log(" 是否开启预览 : ", previewSwitchDiv.checked);
  464. GM_setValue('previewSwitch', previewSwitch);
  465. };
  466. previewOnSideDiv.onchange = () => {
  467. previewOnSide = previewOnSideDiv.checked;
  468. console.log(" 预览框是在两侧还是在中央 : ", previewOnSideDiv.checked);
  469. GM_setValue('previewOnSide', previewOnSide);
  470. };
  471.  
  472. let clear_history = $element(save_history_label, 'label', 'display: inline-block; margin: 0 10px; color: blue;', lang.dialog.clear_history);
  473. clear_history.onclick = () => {
  474. if (confirm(lang.dialog.clear_confirm)) {
  475. history = [];
  476. GM_setValue('download_history', []);
  477. }
  478. };
  479. let show_sensitive_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.show_sensitive);
  480. let show_sensitive_input = $element(show_sensitive_label, 'input', 'float: left;', 'checkbox');
  481. show_sensitive_input.checked = await GM_getValue('show_sensitive', false);
  482. show_sensitive_input.onchange = () => {
  483. show_sensitive = show_sensitive_input.checked;
  484. GM_setValue('show_sensitive', show_sensitive);
  485. };
  486. let filename_div = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;');
  487. let filename_label = $element(filename_div, 'label', 'display: block; margin: 10px 15px;', lang.dialog.pattern);
  488. 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));
  489. let filename_tags = $element(filename_div, 'label', 'display: table; margin: 10px;', `
  490. <span class="tmd-tag" title="user name">{user-name}</span>
  491. <span class="tmd-tag" title="The user name after @ sign.">{user-id}</span>
  492. <span class="tmd-tag" title="example: 1234567890987654321">{status-id}</span>
  493. <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>
  494. <span class="tmd-tag" title="Text content in tweet.">{full-text}</span>
  495. <span class="tmd-tag" title="Type of &#34;video&#34; or &#34;photo&#34; or &#34;gif&#34;.">{file-type}</span>
  496. <span class="tmd-tag" title="Original filename from URL.">{file-name}</span>
  497. `);
  498. filename_input.selectionStart = filename_input.value.length;
  499. filename_tags.querySelectorAll('.tmd-tag').forEach(tag => {
  500. tag.onclick = () => {
  501. let ss = filename_input.selectionStart;
  502. let se = filename_input.selectionEnd;
  503. filename_input.value = filename_input.value.substring(0, ss) + tag.innerText + filename_input.value.substring(se);
  504. filename_input.selectionStart = ss + tag.innerText.length;
  505. filename_input.selectionEnd = ss + tag.innerText.length;
  506. filename_input.focus();
  507. };
  508. });
  509. let btn_save = $element(title, 'label', 'float: right;', lang.dialog.save, 'tmd-btn');
  510. btn_save.onclick = async () => {
  511. await GM_setValue('filename', filename_input.value);
  512. wapper.remove();
  513. };
  514. },
  515. fetchJson: async function (status_id) {
  516. let base_url = `https://${host}/i/api/graphql/2ICDjqPd81tulZcYrtpTuQ/TweetResultByRestId`;
  517. let variables = {
  518. // "focalTweetId":status_id,
  519. "tweetId": status_id,
  520. "with_rux_injections": false,
  521. "includePromotedContent": true,
  522. "withCommunity": true,
  523. "withQuickPromoteEligibilityTweetFields": true,
  524. "withBirdwatchNotes": true,
  525. "withVoice": true,
  526. "withV2Timeline": true
  527. };
  528. let features = {
  529. "articles_preview_enabled": true,
  530. "c9s_tweet_anatomy_moderator_badge_enabled": true,
  531. "communities_web_enable_tweet_community_results_fetch": false,
  532. "creator_subscriptions_quote_tweet_preview_enabled": false,
  533. "creator_subscriptions_tweet_preview_api_enabled": false,
  534. "freedom_of_speech_not_reach_fetch_enabled": true,
  535. "graphql_is_translatable_rweb_tweet_is_translatable_enabled": true,
  536. "longform_notetweets_consumption_enabled": false,
  537. "longform_notetweets_inline_media_enabled": true,
  538. "longform_notetweets_rich_text_read_enabled": false,
  539. "premium_content_api_read_enabled": false,
  540. "profile_label_improvements_pcf_label_in_post_enabled": true,
  541. "responsive_web_edit_tweet_api_enabled": false,
  542. "responsive_web_enhance_cards_enabled": false,
  543. "responsive_web_graphql_exclude_directive_enabled": false,
  544. "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
  545. "responsive_web_graphql_timeline_navigation_enabled": false,
  546. "responsive_web_grok_analysis_button_from_backend": false,
  547. "responsive_web_grok_analyze_button_fetch_trends_enabled": false,
  548. "responsive_web_grok_analyze_post_followups_enabled": false,
  549. "responsive_web_grok_image_annotation_enabled": false,
  550. "responsive_web_grok_share_attachment_enabled": false,
  551. "responsive_web_grok_show_grok_translated_post": false,
  552. "responsive_web_jetfuel_frame": false,
  553. "responsive_web_media_download_video_enabled": false,
  554. "responsive_web_twitter_article_tweet_consumption_enabled": true,
  555. "rweb_tipjar_consumption_enabled": true,
  556. "rweb_video_screen_enabled": false,
  557. "standardized_nudges_misinfo": true,
  558. "tweet_awards_web_tipping_enabled": false,
  559. "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": true,
  560. "tweetypie_unmention_optimization_enabled": false,
  561. "verified_phone_label_enabled": false,
  562. "view_counts_everywhere_api_enabled": true,
  563. };
  564. let url = encodeURI(`${base_url}?variables=${JSON.stringify(variables)}&features=${JSON.stringify(features)}`);
  565. let cookies = this.getCookie();
  566. let headers = {
  567. 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  568. 'x-twitter-active-user': 'yes',
  569. 'x-twitter-client-language': cookies.lang,
  570. 'x-csrf-token': cookies.ct0
  571. };
  572. if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt;
  573. let tweet_detail = await fetch(url, {headers: headers}).then(result => result.json());
  574. //let tweet_entrie = tweet_detail.data.threaded_conversation_with_injections_v2.instructions[0].entries.find(n => n.entryId == `tweet-${status_id}`);
  575. //let tweet_result = tweet_entrie.content.itemContent.tweet_results.result;
  576. let tweet_result = tweet_detail.data.tweetResult.result;
  577. return tweet_result.tweet || tweet_result;
  578. },
  579.  
  580. // tag_ppEdit
  581. displayFavoriteResult: function (result, status_id) {
  582. let favoriteDiv = document.getElementById('favorite-result');
  583. if (!favoriteDiv) {
  584. favoriteDiv = document.createElement('div');
  585. favoriteDiv.id = 'favorite-result';
  586. favoriteDiv.style.position = 'fixed';
  587. // favoriteDiv.style.top = '10px';
  588. // favoriteDiv.style.left = '10px';
  589. favoriteDiv.style.top = '2px';
  590. favoriteDiv.style.left = '2px';
  591. favoriteDiv.style.backgroundColor = '#fff';
  592. // favoriteDiv.style.padding = '10px';
  593. favoriteDiv.style.border = '1px solid #ccc';
  594. favoriteDiv.style.zIndex = '1000';
  595. favoriteDiv.style.color = "black";
  596. favoriteDiv.style.fontSize = "10px";
  597. document.body.appendChild(favoriteDiv);
  598. }
  599. let data = {};
  600. data.result = result;
  601. data.time = timestampToYMDHMS(Date.now() + timeOffset);
  602. data.status_id = status_id;
  603. favoriteDiv.innerHTML = result ? JSON.stringify(data, null, 2) : 'Failed to favorite tweet';
  604. return result != null && result.data != null && result.data.favorite_tweet != null && result.data.favorite_tweet === 'Done';
  605. },
  606.  
  607. displayFavoriteResult_simp: function (str) {
  608. let favoriteDiv = document.getElementById('favorite-result');
  609. if (!favoriteDiv) {
  610. favoriteDiv = document.createElement('div');
  611. favoriteDiv.id = 'favorite-result';
  612. favoriteDiv.style.position = 'fixed';
  613. // favoriteDiv.style.top = '10px';
  614. // favoriteDiv.style.left = '10px';
  615. favoriteDiv.style.top = '2px';
  616. favoriteDiv.style.left = '2px';
  617. favoriteDiv.style.backgroundColor = '#fff';
  618. // favoriteDiv.style.padding = '10px';
  619. favoriteDiv.style.border = '1px solid #ccc';
  620. favoriteDiv.style.zIndex = '1000';
  621. favoriteDiv.style.color = "black";
  622. favoriteDiv.style.fontSize = "10px";
  623. document.body.appendChild(favoriteDiv);
  624. }
  625. favoriteDiv.innerHTML = str;
  626. },
  627.  
  628. getCookie: function (name) {
  629. let cookies = {};
  630. document.cookie.split(';').filter(n => n.indexOf('=') > 0).forEach(n => {
  631. n.replace(/^([^=]+)=(.+)$/, (match, name, value) => {
  632. cookies[name.trim()] = value.trim();
  633. });
  634. });
  635. return name ? cookies[name] : cookies;
  636. },
  637. storage: async function (value) {
  638. let data = await GM_getValue('download_history', []);
  639. let data_length = data.length;
  640. if (value) {
  641. if (Array.isArray(value)) data = data.concat(value);
  642. else if (data.indexOf(value) < 0) data.push(value);
  643. } else return data;
  644. if (data.length > data_length) GM_setValue('download_history', data);
  645. },
  646. storage_obsolete: function (is_remove) {
  647. let data = JSON.parse(localStorage.getItem('history') || '[]');
  648. if (is_remove) localStorage.removeItem('history');
  649. else return data;
  650. },
  651. formatDate: function (i, o, tz) {
  652. let d = new Date(i);
  653. if (tz) d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
  654. let m = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
  655. let v = {
  656. YYYY: d.getUTCFullYear().toString(),
  657. YY: d.getUTCFullYear().toString(),
  658. MM: d.getUTCMonth() + 1,
  659. MMM: m[d.getUTCMonth()],
  660. DD: d.getUTCDate(),
  661. hh: d.getUTCHours(),
  662. mm: d.getUTCMinutes(),
  663. ss: d.getUTCSeconds(),
  664. h2: d.getUTCHours() % 12,
  665. ap: d.getUTCHours() < 12 ? 'AM' : 'PM'
  666. };
  667. return o.replace(/(YY(YY)?|MMM?|DD|hh|mm|ss|h2|ap)/g, n => ('0' + v[n]).substr(-n.length));
  668. },
  669. downloader: (function () {
  670. let tasks = [], thread = 0, max_thread = 2, retry = 0, max_retry = 2, failed = 0, notifier,
  671. has_failed = false;
  672. return {
  673. add: function (task) {
  674. tasks.push(task);
  675. if (thread < max_thread) {
  676. thread += 1;
  677. this.next();
  678. } else this.update();
  679. },
  680. next: async function () {
  681. let task = tasks.shift();
  682. await this.start(task);
  683. if (tasks.length > 0 && thread <= max_thread) this.next();
  684. else thread -= 1;
  685. this.update();
  686. },
  687. start: function (task) {
  688. this.update();
  689. return new Promise(resolve => {
  690. GM_download({
  691. url: task.url,
  692. name: task.name,
  693. onload: result => {
  694. task.onload();
  695. resolve();
  696. },
  697. onerror: result => {
  698. this.retry(task, result);
  699. resolve();
  700. },
  701. ontimeout: result => {
  702. this.retry(task, result);
  703. resolve();
  704. }
  705. });
  706. });
  707. },
  708. retry: function (task, result) {
  709. retry += 1;
  710. if (retry == 3) max_thread = 1;
  711. if (task.retry && task.retry >= max_retry ||
  712. result.details && result.details.current == 'USER_CANCELED') {
  713. task.onerror(result);
  714. failed += 1;
  715. } else {
  716. if (max_thread == 1) task.retry = (task.retry || 0) + 1;
  717. this.add(task);
  718. }
  719. },
  720. update: function () {
  721. if (!notifier) {
  722. notifier = document.createElement('div');
  723. notifier.title = 'Twitter Media Downloader';
  724. notifier.classList.add('tmd-notifier');
  725. notifier.innerHTML = '<label>0</label>|<label>0</label>';
  726. document.body.appendChild(notifier);
  727. }
  728. if (failed > 0 && !has_failed) {
  729. has_failed = true;
  730. notifier.innerHTML += '|';
  731. let clear = document.createElement('label');
  732. notifier.appendChild(clear);
  733. clear.onclick = () => {
  734. notifier.innerHTML = '<label>0</label>|<label>0</label>';
  735. failed = 0;
  736. has_failed = false;
  737. this.update();
  738. };
  739. }
  740. notifier.firstChild.innerText = thread;
  741. notifier.firstChild.nextElementSibling.innerText = tasks.length;
  742. if (failed > 0) notifier.lastChild.innerText = failed;
  743. if (thread > 0 || tasks.length > 0 || failed > 0) notifier.classList.add('running');
  744. else notifier.classList.remove('running');
  745. }
  746. };
  747. })(),
  748. language: {
  749. en: {
  750. download: 'Download',
  751. completed: 'Download Completed',
  752. settings: 'Settings',
  753. dialog: {
  754. title: 'Download Settings',
  755. save: 'Save',
  756. width: "width",
  757. height: "height",
  758. save_history: 'Remember download history',
  759. clear_history: '(Clear)',
  760. clear_confirm: 'Clear download history?',
  761. show_sensitive: 'Always show sensitive content',
  762. pattern: 'File Name Pattern'
  763. }
  764. },
  765. ja: {
  766. download: 'ダウンロード',
  767. completed: 'ダウンロード完了',
  768. settings: '設定',
  769. dialog: {
  770. title: 'ダウンロード設定',
  771. save: '保存',
  772. width: "width",
  773. height: "height",
  774. save_history: 'ダウンロード履歴を保存する',
  775. clear_history: '(クリア)',
  776. clear_confirm: 'ダウンロード履歴を削除する?',
  777. show_sensitive: 'センシティブな内容を常に表示する',
  778. pattern: 'ファイル名パターン'
  779. }
  780. },
  781. zh: {
  782. download: '下载',
  783. completed: '下载完成',
  784. settings: '设置',
  785. dialog: {
  786. title: '下载设置',
  787. save: '保存',
  788. width: "width",
  789. height: "height",
  790. save_history: '保存下载记录',
  791. clear_history: '(清除)',
  792. clear_confirm: '确认要清除下载记录?',
  793. show_sensitive: '自动显示敏感的内容',
  794. pattern: '文件名格式'
  795. }
  796. },
  797. 'zh-Hant': {
  798. download: '下載',
  799. completed: '下載完成',
  800. settings: '設置',
  801. dialog: {
  802. title: '下載設置',
  803. save: '保存',
  804. width: "width",
  805. height: "height",
  806. save_history: '保存下載記錄',
  807. clear_history: '(清除)',
  808. clear_confirm: '確認要清除下載記錄?',
  809. show_sensitive: '自動顯示敏感的内容',
  810. pattern: '文件名規則'
  811. }
  812. }
  813. },
  814. css: `
  815. .tmd-down {margin-left: 12px; order: 99;}
  816. .tmd-down:hover > div > div > div > div {color: rgba(29, 161, 242, 1.0);}
  817. .tmd-down:hover > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.1);}
  818. .tmd-down:active > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.2);}
  819. .tmd-down:hover svg {color: rgba(29, 161, 242, 1.0);}
  820. .tmd-down:hover div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.1);}
  821. .tmd-down:active div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.2);}
  822. .tmd-down.tmd-media {position: absolute; right: 0;}
  823. .tmd-down.tmd-media > div {display: flex; border-radius: 99px; margin: 2px;}
  824. .tmd-down.tmd-media > div > div {display: flex; margin: 6px; color: #fff;}
  825. .tmd-down.tmd-media:hover > div {background-color: rgba(255,255,255, 0.6);}
  826. .tmd-down.tmd-media:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  827. .tmd-down.tmd-media:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  828. .tmd-down g {display: none;}
  829. .tmd-down.download g.download, .tmd-down.completed g.completed, .tmd-down.loading g.loading,.tmd-down.failed g.failed {display: unset;}
  830. .tmd-down.loading svg {animation: spin 1s linear infinite;}
  831. @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}}
  832. .tmd-btn {display: inline-block; background-color: #1DA1F2; color: #FFFFFF; padding: 0 20px; border-radius: 99px;}
  833. .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;}
  834. .tmd-btn:hover {background-color: rgba(29, 161, 242, 0.9);}
  835. .tmd-tag:hover {background-color: rgba(29, 161, 242, 0.1);}
  836. .tmd-notifier {display: none; position: fixed; left: 16px; bottom: 16px; color: #000; background: #fff; border: 1px solid #ccc; border-radius: 8px; padding: 4px;}
  837. .tmd-notifier.running {display: flex; align-items: center;}
  838. .tmd-notifier label {display: inline-flex; align-items: center; margin: 0 8px;}
  839. .tmd-notifier label:before {content: " "; width: 32px; height: 16px; background-position: center; background-repeat: no-repeat;}
  840. .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>");}
  841. .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>");}
  842. .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>");}
  843. .tmd-down.tmd-img {position: absolute; right: 0; bottom: 0; display: none !important;}
  844. .tmd-down.tmd-img > div {display: flex; border-radius: 99px; margin: 2px; background-color: rgba(255,255,255, 0.6);}
  845. .tmd-down.tmd-img > div > div {display: flex; margin: 6px; color: #fff !important;}
  846. .tmd-down.tmd-img:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);}
  847. .tmd-down.tmd-img:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  848. :hover > .tmd-down.tmd-img, .tmd-img.loading, .tmd-img.completed, .tmd-img.failed {display: block !important;}
  849. .tweet-detail-action-item {width: 20% !important;}
  850. `,
  851. css_ss: `
  852. /* show sensitive in media tab */
  853. li[role="listitem"]>div>div>div>div:not(:last-child) {filter: none;}
  854. li[role="listitem"]>div>div>div>div+div:last-child {display: none;}
  855. `,
  856. svg: `
  857. <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>
  858. <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>
  859. <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>
  860. <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>
  861. `
  862. };
  863. })();
  864.  
  865. TMD.init();