Twitter Media Downloader

Save Video/Photo by One-Click.

Ekde 2021/05/06. Vidu La ĝisdata versio.

  1. // ==UserScript==
  2. // @name Twitter Media Downloader
  3. // @name:ja Twitter Media Downloader
  4. // @name:zh-cn Twitter 媒体下载
  5. // @name:zh-tw Twitter 媒體下載
  6. // @description Save Video/Photo by One-Click.
  7. // @description:ja ワンクリックで動画・画像を保存する。
  8. // @description:zh-cn 一键保存视频/图片
  9. // @description:zh-tw 一鍵保存視頻/圖片
  10. // @version 0.81
  11. // @author AMANE
  12. // @namespace none
  13. // @match https://twitter.com/*
  14. // @grant GM_registerMenuCommand
  15. // @grant GM_setValue
  16. // @grant GM_getValue
  17. // @grant GM_download
  18. // @compatible chrome
  19. // @compatible firefox
  20. // @compatible Tampermonkey
  21. // ==/UserScript==
  22. /* jshint esversion: 8 */
  23.  
  24. const filename = 'twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}';
  25.  
  26. const language = {
  27. en: {download: 'Download', completed: 'Download Completed', settings: 'Settings', dialog: {title: 'Download Settings', save: 'Save', record: 'Remember Download History', clear: '(Clear)', confirm: 'Clear download history?', pattern: 'File Name Pattern'}},
  28. ja: {download: 'ダウンロード', completed: 'ダウンロード完了', settings: '設定', dialog: {title: 'ダウンロード設定', save: '保存', record: 'ダウンロード履歴を保存する', clear: '(クリア)', confirm: 'ダウンロード履歴を削除する?', pattern: 'ファイル名パターン'}},
  29. zh: {download: '下载', completed: '下载完成', settings: '设置', dialog: {title: '下载设置', save: '保存', record: '保存下载记录', clear: '(清除)', confirm: '确认要清除下载记录?', pattern: '文件名格式'}},
  30. 'zh-Hant': {download: '下載', completed: '下載完成', settings: '設置', dialog: {title: '下載設置', save: '保存', record: '保存下載記錄', clear: '(清除)', confirm: '確認要清除下載記錄?', pattern: '文件名規則'}},
  31. };
  32.  
  33. const svg = `
  34. <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>
  35. <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>
  36. <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>
  37. <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>
  38. `;
  39.  
  40. const css = `
  41. .tmd-down > div > div > div:nth-child(2) {display: none}
  42. .tmd-down:hover > div > div {color: rgba(29, 161, 242, 1.0);}
  43. .tmd-down:hover > div > div > div > div {background-color: rgba(29, 161, 242, 0.1);}
  44. .tmd-down:active > div > div > div > div {background-color: rgba(29, 161, 242, 0.2);}
  45. .tmd-down.loading svg {animation: spin 1s linear infinite;}
  46. .tmd-down g {display: none;}
  47. .tmd-down.download g.download, .tmd-down.completed g.completed, .tmd-down.loading g.loading,.tmd-down.failed g.failed {display: unset;}
  48. @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}}
  49. .tmd-btn {display: inline-block; background-color: #1DA1F2; color: #FFFFFF; padding: 0 20px; border-radius: 99px;}
  50. .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;}
  51. .tmd-btn:hover {background-color: rgba(29, 161, 242, 0.9);}
  52. .tmd-tag:hover {background-color: rgba(29, 161, 242, 0.1);}
  53. `;
  54.  
  55. const TMD = (function () {
  56. let lang, history;
  57. return {
  58. init: function () {
  59. GM_registerMenuCommand((language[navigator.language] || language.en).settings, this.settings);
  60. document.head.insertAdjacentHTML('beforeend', '<style>' + css + '</style>');
  61. lang = language[document.querySelector('html').lang] || language.en;
  62. history = this.storage('history');
  63. },
  64. inject: function (article) {
  65. let media_selector = [
  66. 'a[href*="/photo/1"]',
  67. 'div[role="progressbar"]',
  68. 'div[data-testid="playButton"]',
  69. 'a[href="/settings/safety"]'
  70. ];
  71. let media = article.querySelector(media_selector.join(','));
  72. if (!media || article.dataset.injected) return;
  73. article.dataset.injected = 'true';
  74. let status_id = article.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift();
  75. let group = article.querySelector('div[role="group"]');
  76. let btn = group.querySelector(':scope>:first-child').cloneNode(true);
  77. btn.querySelector('svg').innerHTML = svg;
  78. let is_exist = history.indexOf(status_id) >= 0;
  79. this.status(btn, 'tmd-down');
  80. this.status(btn, is_exist ? 'completed' : 'download', is_exist ? lang.completed : lang.download);
  81. group.appendChild(btn);
  82. btn.onclick = () => this.click(btn, status_id, is_exist);
  83. },
  84. click: async function (btn, status_id, is_exist) {
  85. if (btn.classList.contains('loading')) return;
  86. this.status(btn, 'loading');
  87. let out = (await GM_getValue('filename', filename)).split('\n').join('');
  88. let record = await GM_getValue('record', true);
  89. let json = await this.fetchJson(status_id);
  90. let tweet = json.globalObjects.tweets[status_id];
  91. let user = json.globalObjects.users[tweet.user_id_str];
  92. let invalid_chars = {'\\': '\', '\/': '/', '\|': '|', '<': '<', '>': '>', ':': ':', '*': '*', '?': '?', '"': '"', '🔞': ''};
  93. let info = {};
  94. info['status-id'] = status_id;
  95. info['user-name'] = user.name.replace(/([\\\/\|\*\?:"]|🔞)/g, v => invalid_chars[v]);
  96. info['user-id'] = user.screen_name;
  97. info['date-time'] = this.formatDate(tweet.created_at, 'YYYYMMDD-hhmmss');
  98. info['full-text'] = tweet.full_text.split('\n').join(' ').replace(/\s*https:\/\/t\.co\/\w+/g, '').replace(/[\\\/\|<>\*\?:"]/g, v => invalid_chars[v]);
  99. let medias = tweet.extended_entities && tweet.extended_entities.media;
  100. if (medias.length > 0) {
  101. let tasks = medias.length;
  102. let tasks_result = [];
  103. medias.forEach((media, i) => {
  104. info.url = media.type == 'photo' ? media.media_url + ':orig' : media.video_info.variants.filter(n => n.content_type == 'video/mp4').sort((a, b) => b.bitrate - a.bitrate)[0].url;
  105. info.file = info.url.split('/').pop().split(/[:?]/).shift();
  106. info['file-name'] = info.file.split('.').shift();
  107. info['file-ext'] = info.file.split('.').pop();
  108. info['file-type'] = media.type.replace('animated_', '');
  109. info.out = (out.replace(/\.?{file-ext}/, '') + (medias.length > 1 && !out.match('{file-name}') ? '-' + i : '') + '.{file-ext}').replace(/{([^{}]+)}/g, (match, name) => info[name]);
  110. this.downloader.add({
  111. url: info.url,
  112. name: info.out,
  113. onload: () => {
  114. tasks -= 1;
  115. tasks_result.push((medias.length > 1 ? i + 1 + ': ' : '') + lang.completed);
  116. this.status(btn, null, tasks_result.sort().join('\n'));
  117. if (tasks === 0) {
  118. this.status(btn, 'completed', lang.completed);
  119. if (record && !is_exist) {
  120. history.push(status_id);
  121. this.storage('history', status_id);
  122. }
  123. }
  124. },
  125. onerror: result => {
  126. tasks = -1;
  127. tasks_result.push((medias.length > 1 ? i + 1 + ': ' : '') + result.details.current);
  128. this.status(btn, 'failed', tasks_result.sort().join('\n'));
  129. }
  130. });
  131. });
  132. } else {
  133. this.status(btn, 'failed', 'MEDIA_NOT_FOUND');
  134. }
  135. },
  136. status: function (btn, css, title, style) {
  137. if (css) {
  138. btn.classList.remove('download', 'completed', 'loading', 'failed');
  139. btn.classList.add(css);
  140. }
  141. if (title) btn.title = title;
  142. if (style) btn.style.cssText = style;
  143. },
  144. settings: async function () {
  145. const $element = (parent, tag, style, content, css) => {
  146. let el = document.createElement(tag);
  147. if (style) el.style.cssText = style;
  148. if (typeof content !== 'undefined') {
  149. if (tag == 'input') {
  150. if (content == 'checkbox') el.type = content;
  151. else el.value = content;
  152. } else el.innerHTML = content;
  153. }
  154. if (css) css.split(' ').forEach(c => el.classList.add(c));
  155. parent.appendChild(el);
  156. return el;
  157. };
  158. let wapper = $element(document.body, 'div', 'position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: #0009; z-index: 10;');
  159. let wapper_close;
  160. wapper.onmousedown = e => {
  161. wapper_close = e.target == wapper;
  162. };
  163. wapper.onmouseup = e => {
  164. if (wapper_close && e.target == wapper) wapper.remove();
  165. };
  166. 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;');
  167. let title = $element(dialog, 'h3', 'margin: 10px 20px;', lang.dialog.title);
  168. let options = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;');
  169. let record_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.record);
  170. let record_input = $element(record_label, 'input', 'float: left;', 'checkbox');
  171. record_input.checked = await GM_getValue('history', true);
  172. record_input.onchange = () => GM_setValue('history', record_input.checked);
  173. let record_clear = $element(record_label, 'label', 'margin: 10px; color: blue;', lang.dialog.clear);
  174. record_clear.onclick = () => {
  175. if (confirm(lang.dialog.confirm)) {
  176. history = [];
  177. localStorage.removeItem('history');
  178. }
  179. };
  180. let filename_div = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;');
  181. let filename_label = $element(filename_div, 'label', 'display: block; margin: 10px 15px;', lang.dialog.pattern);
  182. let filename_input = $element(filename_label, 'textarea', 'display: block; min-width: 500px; max-width: 500px; min-height: 100px; font-size: inherit;', await GM_getValue('filename', filename));
  183. let filename_tags = $element(filename_div, 'label', 'display: table; margin: 10px;', `
  184. <span class="tmd-tag" title="user name">{user-name}</span>
  185. <span class="tmd-tag" title="The user name after @ sign.">{user-id}</span>
  186. <span class="tmd-tag" title="example: 1234567890987654321">{status-id}</span>
  187. <span class="tmd-tag" title="YYYYMMDD-hhmmss\nexample: 20201231-235959">{date-time}</span><br>
  188. <span class="tmd-tag" title="Type of &#34;video&#34; or &#34;photo&#34; or &#34;gif&#34;.">{file-type}</span>
  189. <span class="tmd-tag" title="Original filename from URL.">{file-name}</span>
  190. <span class="tmd-tag" title="Unnecessary. Will be added automatically.">{file-ext}</span>
  191. `);
  192. filename_input.selectionStart = filename_input.value.length;
  193. filename_tags.querySelectorAll('.tmd-tag').forEach(tag => {
  194. tag.onclick = () => {
  195. let ss = filename_input.selectionStart;
  196. let se = filename_input.selectionEnd;
  197. filename_input.value = filename_input.value.substring(0, ss) + tag.innerText + filename_input.value.substring(se);
  198. filename_input.selectionStart = ss + tag.innerText.length;
  199. filename_input.selectionEnd = ss + tag.innerText.length;
  200. filename_input.focus();
  201. };
  202. });
  203. let btn_save = $element(title, 'label', 'float: right;', lang.dialog.save, 'tmd-btn');
  204. btn_save.onclick = async () => {
  205. await GM_setValue('filename', filename_input.value);
  206. wapper.remove();
  207. };
  208. },
  209. fetchJson: async function (status_id) {
  210. let url = 'https://twitter.com/i/api/2/timeline/conversation/' + status_id + '.json?tweet_mode=extended&include_entities=false&include_user_entities=false';
  211. let cookies = this.getCookie();
  212. let headers = {
  213. 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  214. 'x-twitter-active-user': 'yes',
  215. 'x-twitter-client-language': cookies.lang,
  216. 'x-csrf-token': cookies.ct0
  217. };
  218. if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt;
  219. return await fetch(url, {headers: headers}).then(result => result.json());
  220. },
  221. getCookie: function (name) {
  222. let cookies = {};
  223. document.cookie.split(';').filter(n => n.indexOf('=') > 0).forEach(n => {
  224. n.replace(/^([^=]+)=(.+)$/, (match, name, value) => {
  225. cookies[name.trim()] = value.trim();
  226. });
  227. });
  228. return name ? cookies[name] : cookies;
  229. },
  230. storage: function (name, value) {
  231. let data = JSON.parse(localStorage.getItem(name) || '[]');
  232. if (value) data.push(value);
  233. else return data;
  234. localStorage.setItem(name, JSON.stringify(data));
  235. },
  236. formatDate: function (i, o) {
  237. let d = new Date(i);
  238. let v = {
  239. YYYY: d.getUTCFullYear().toString(),
  240. YY: d.getUTCFullYear().toString(),
  241. MM: '0' + (d.getUTCMonth() + 1),
  242. DD: '0' + d.getUTCDate(),
  243. hh: '0' + d.getUTCHours(),
  244. mm: '0' + d.getUTCMinutes(),
  245. ss: '0' + d.getUTCSeconds()
  246. };
  247. return o.replace(/(YY(YY)?|MM|DD|hh|mm|ss)/g, n => v[n].substr(-n.length));
  248. },
  249. downloader: (function () {
  250. let tasks = [], thread = 0, max_thread = 2, retry = 0, max_retry = 2;
  251. return {
  252. add: function (task) {
  253. tasks.push(task);
  254. if (thread < max_thread) {
  255. thread += 1;
  256. this.next();
  257. }
  258. },
  259. next: async function () {
  260. let task = tasks.shift();
  261. await this.start(task);
  262. if (tasks.length > 0 && thread <= max_thread) this.next();
  263. else thread -= 1;
  264. },
  265. start: function (task) {
  266. return new Promise(resolve => {
  267. GM_download({
  268. url: task.url,
  269. name: task.name,
  270. onload: result => {
  271. task.onload();
  272. resolve();
  273. },
  274. onerror: result => {
  275. this.retry(task, result);
  276. resolve();
  277. },
  278. ontimeout: result => {
  279. this.retry(task, result);
  280. resolve();
  281. }
  282. });
  283. });
  284. },
  285. retry: function (task, result) {
  286. retry += 1;
  287. if (retry == 3) max_thread = 1;
  288. if (task.retry && task.retry >= max_retry ||
  289. result.details && result.details.current == 'USER_CANCELED') {
  290. task.onerror(result);
  291. } else {
  292. if (max_thread == 1) task.retry = (task.retry || 0) + 1;
  293. this.add(task);
  294. }
  295. }
  296. };
  297. })()
  298. };
  299. })();
  300.  
  301. (function () {
  302. TMD.init();
  303. new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(node => {
  304. let article = node.tagName == 'DIV' && (node.querySelector('article') || node.closest('article'));
  305. if (article) TMD.inject(article);
  306. }))).observe(document.body, {childList: true, subtree: true});
  307. })();