// ==UserScript== // @name [editVersion]Twitter Media Downloader[2504fix] // @name:ja [editVersion]Twitter Media Downloader[2504fix] // @name:zh-cn [editVersion]Twitter 媒体下载[2504fix] // @name:zh-tw [editVersion]Twitter 媒體下載[2504fix] // @description Save Video/Photo by One-Click. // @description:ja ワンクリックで動画・画像を保存する。 // @description:zh-cn 一键保存视频/图片 // @description:zh-tw 一鍵保存視頻/圖片 // @version 2.0.5.1 // @author AMANE // @namespace none // @match https://x.com/* // @match https://mobile.x.com/* // @grant GM_registerMenuCommand // @grant GM_setValue // @grant GM_getValue // @grant GM_download // @compatible Chrome // @compatible Firefox // @license MIT // @downloadURL https://update.greasyfork.cloud/scripts/528025/%5BeditVersion%5DTwitter%20Media%20Downloader%5B2504fix%5D.user.js // @updateURL https://update.greasyfork.cloud/scripts/528025/%5BeditVersion%5DTwitter%20Media%20Downloader%5B2504fix%5D.meta.js // ==/UserScript== /* jshint esversion: 8 */ const filename = 'twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}'; // tag_ppEdit function timestampToYMDHMS(timestamp) { const date = new Date(timestamp); const year = date.getUTCFullYear(); const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); // 月份是从0開始的 const day = ('0' + date.getUTCDate()).slice(-2); const hours = ('0' + date.getUTCHours()).slice(-2); const minutes = ('0' + date.getUTCMinutes()).slice(-2); const seconds = ('0' + date.getUTCSeconds()).slice(-2); return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; } let divWidth = 700; let divHeight = 700; let timeOffset = 8 * 60 * 60 * 1000; // let reversePreViewLeftRight = true let imageSizeKey = "name="; let imageSize = ["small", "medium", "Orig"] let imageSizeIndex = 1; // 就是让预览框偏向中间还是两侧,感觉两侧很多时候不点 , 而且中间的图片也就占1/3左右 , 放两侧还挺合适 let previewSwitch = true; let previewOnSide = true; // tag_ppEdit let previewDiv = document.createElement("div"); previewDiv.id = "helloTwitterMedia"; previewDiv.style.position = "fixed"; previewDiv.style.backgroundColor = "white"; previewDiv.style.border = "1px solid #ccc"; previewDiv.style.display = "none"; let previewImg = document.createElement("img"); previewImg.id = "previewImg"; previewImg.style.maxWidth = "100%"; previewImg.style.maxHeight = "100%"; previewDiv.appendChild(previewImg); const TMD = (function () { let lang, host, history, show_sensitive, is_tweetdeck; return { init: async function () { GM_registerMenuCommand((this.language[navigator.language] || this.language.en).settings, this.settings); lang = this.language[document.querySelector('html').lang] || this.language.en; host = location.hostname; is_tweetdeck = host.indexOf('tweetdeck') >= 0; history = this.storage_obsolete(); if (history.length) { this.storage(history); this.storage_obsolete(true); } else history = await this.storage(); show_sensitive = GM_getValue('show_sensitive', false); document.head.insertAdjacentHTML('beforeend', ''); let observer = new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(node => this.detect(node)))); observer.observe(document.body, {childList: true, subtree: true}); // tag_ppEdit_preview divWidth = GM_getValue('previewWidth', 700); divHeight = GM_getValue('previewHeight', 700); previewDiv.style.width = divWidth + "px"; previewDiv.style.height = divHeight + "px"; document.body.appendChild(previewDiv); previewSwitch = GM_getValue('previewSwitch', true); console.log(" 当前的预览开关 ", previewSwitch); previewOnSide = GM_getValue('previewOnSide', true); console.log(" 当前的预览位置 ", previewOnSide) let lastNode; let lastTime = Date.now(); document.addEventListener("mousemove", function (event) { if (!previewSwitch) { return; } // 100fps if (Date.now() - lastTime < 10) { return; } lastTime = Date.now(); let node = event.target; let nodeSrc = node.src; if (node !== lastNode) { console.log(" 鼠标焦点变化 ") if (nodeSrc == null || !nodeSrc.includes("pbs.twimg.com/media")) { previewDiv.style.display = "none"; } else { previewDiv.style.display = "block"; // // 网上搜了,总共四种 &name=small 、 &name=medium 、 &name=Large 、 &name=Orig previewImg.src = getNewUrl(event.target.src) } } lastNode = node; movePreviewDiv(event.clientX, event.clientY, divWidth, divHeight); }); function getNewUrl(url) { let index = url.indexOf(imageSizeKey); if (index < 0) { return url; } let i = index + imageSizeKey.length; if (url.substring(i, i + 5) === "small") { return url.substring(0, i) + "medium" + url.substring(i + 5); } let numArr = []; let numIndex = -1; for (; i < url.length; i++) { let c = url.charAt(i) - '0'; if (c >= 0 && c <= 9) { numArr[++numIndex] = 0; for (; i < url.length && (c = url.charAt(i)) >= '0' && url.charAt(i) <= '9'; i++) { numArr[numIndex] = numArr[numIndex] * 10 + (c - '0'); } if (numIndex === 1) { break; } } } if (numIndex <= 0) { console.log(" 宽高个数不够 "); return url; } else { // url = url.substring(0, index) + "name=" + (numArr[0] * 2) + "x" + (numArr[1] * 2) + url.substring(i); // 好像只能是固定的 4096*4096 url = url.substring(0, index) + "name=4096x4096" + url.substring(i); } return url; } function movePreviewDiv(clientX, clientY, divWidth, divHeight) { // 获取窗口的宽度和高度 const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; // 左右上下超出的距离 let leftOutLen = clientX - divWidth; let topOutLen = clientY - divHeight; let rightOutLen = windowWidth - clientX - divWidth; let bottomOutLen = windowHeight - clientY - divHeight; let isOnRight = (leftOutLen < rightOutLen) ^ previewOnSide; let targetLeft = isOnRight ? clientX + 10 : clientX - divWidth - 10; previewImg.style.float = isOnRight ? "left" : "right"; let targetTop = topOutLen < bottomOutLen ? clientY + 10 : clientY - divHeight - 10; // 上下和左右只能调一个 , 否则鼠标会和窗口重叠 , 鉴于一般窗口都是宽的 , 那么只调整上下 targetTop = targetTop < 0 ? 0 : targetTop; let maxTop = windowHeight - divHeight; targetTop = targetTop > maxTop ? maxTop : targetTop; previewDiv.style.left = targetLeft + "px"; previewDiv.style.top = targetTop + "px"; } }, detect: function (node) { let article = node.tagName == 'ARTICLE' && node || node.tagName == 'DIV' && (node.querySelector('article') || node.closest('article')); if (article) this.addButtonTo(article); let listitems = node.tagName == 'LI' && node.getAttribute('role') == 'listitem' && [node] || node.tagName == 'DIV' && node.querySelectorAll('li[role="listitem"]'); if (listitems) this.addButtonToMedia(listitems); }, addButtonTo: function (article) { if (article.dataset.detected) return; article.dataset.detected = 'true'; let media_selector = [ 'a[href*="/photo/1"]', 'div[role="progressbar"]', 'div[data-testid="playButton"]', 'a[href="/settings/content_you_see"]', //hidden content 'div.media-image-container', // for tweetdeck 'div.media-preview-container', // for tweetdeck 'div[aria-labelledby]>div:first-child>div[role="button"][tabindex="0"]' //for audio (experimental) ]; let media = article.querySelector(media_selector.join(',')); if (media) { let status_id = article.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift(); let btn_group = article.querySelector('div[role="group"]:last-of-type, ul.tweet-actions, ul.tweet-detail-actions'); let btn_share = Array.from(btn_group.querySelectorAll(':scope>div>div, li.tweet-action-item>a, li.tweet-detail-action-item>a')).pop().parentNode; let btn_down = btn_share.cloneNode(true); if (is_tweetdeck) { btn_down.firstElementChild.innerHTML = '' + this.svg + ''; btn_down.firstElementChild.removeAttribute('rel'); btn_down.classList.replace("pull-left", "pull-right"); } else { btn_down.querySelector('svg').innerHTML = this.svg; } let is_exist = history.indexOf(status_id) >= 0; this.status(btn_down, 'tmd-down'); this.status(btn_down, is_exist ? 'completed' : 'download', is_exist ? lang.completed : lang.download); btn_group.insertBefore(btn_down, btn_share.nextSibling); btn_down.onclick = () => this.click(btn_down, status_id, is_exist); if (show_sensitive) { let btn_show = article.querySelector('div[aria-labelledby] div[role="button"][tabindex="0"]:not([data-testid]) > div[dir] > span > span'); if (btn_show) btn_show.click(); } } let imgs = article.querySelectorAll('a[href*="/photo/"]'); if (imgs.length > 1) { let status_id = article.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift(); let btn_group = article.querySelector('div[role="group"]:last-of-type'); let btn_share = Array.from(btn_group.querySelectorAll(':scope>div>div')).pop().parentNode; imgs.forEach(img => { let index = img.href.split('/status/').pop().split('/').pop(); let is_exist = history.indexOf(status_id) >= 0; let btn_down = document.createElement('div'); btn_down.innerHTML = '
' + this.svg + '
'; btn_down.classList.add('tmd-down', 'tmd-img'); this.status(btn_down, 'download'); img.parentNode.appendChild(btn_down); btn_down.onclick = e => { e.preventDefault(); this.click(btn_down, status_id, is_exist, index); } }); } }, addButtonToMedia: function (listitems) { listitems.forEach(li => { if (li.dataset.detected) return; li.dataset.detected = 'true'; let status_id = li.querySelector('a[href*="/status/"]').href.split('/status/').pop().split('/').shift(); let is_exist = history.indexOf(status_id) >= 0; let btn_down = document.createElement('div'); btn_down.innerHTML = '
' + this.svg + '
'; btn_down.classList.add('tmd-down', 'tmd-media'); this.status(btn_down, is_exist ? 'completed' : 'download', is_exist ? lang.completed : lang.download); li.appendChild(btn_down); btn_down.onclick = () => this.click(btn_down, status_id, is_exist); }); }, click: async function (btn, status_id, is_exist, index) { // tag_ppEdit001 console.log(" 当前的推文id ", status_id) // 喜欢推文的接口 let favoriteResult = await this.favoriteTweet(status_id, "lI07N6Otwv1PhnEgXILM7A"); if (null == favoriteResult) { this.displayFavoriteResult_simp('http error while favorite twitter'); console.log('http error while favorite twitter') return; } let res = this.displayFavoriteResult(favoriteResult, status_id); if (res == null || !res) { console.log(" 已经like过了 , 不下载 ") history.push(status_id); await this.storage(status_id); this.status(btn, 'completed', lang.completed); return; } if (btn.classList.contains('loading')) return; this.status(btn, 'loading'); let out = (await GM_getValue('filename', filename)).split('\n').join(''); let save_history = await GM_getValue('save_history', true); let json = await this.fetchJson(status_id); let tweet = json.legacy; let user = json.core.user_results.result.legacy; let invalid_chars = { '\\': '\', '\/': '/', '\|': '|', '<': '<', '>': '>', ':': ':', '*': '*', '?': '?', '"': '"', '\u200b': '', '\u200c': '', '\u200d': '', '\u2060': '', '\ufeff': '', '🔞': '' }; let datetime = out.match(/{date-time(-local)?:[^{}]+}/) ? out.match(/{date-time(?:-local)?:([^{}]+)}/)[1].replace(/[\\/|<>*?:"]/g, v => invalid_chars[v]) : 'YYYYMMDD-hhmmss'; let info = {}; info['status-id'] = status_id; info['user-name'] = user.name.replace(/([\\/|*?:"]|[\u200b-\u200d\u2060\ufeff]|🔞)/g, v => invalid_chars[v]); info['user-id'] = user.screen_name; info['date-time'] = this.formatDate(tweet.created_at, datetime); info['date-time-local'] = this.formatDate(tweet.created_at, datetime, true); 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]); let medias = tweet.extended_entities && tweet.extended_entities.media; if (index) medias = [medias[index - 1]]; if (medias.length > 0) { let tasks = medias.length; let tasks_result = []; medias.forEach((media, i) => { 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; info.file = info.url.split('/').pop().split(/[:?]/).shift(); info['file-name'] = info.file.split('.').shift(); info['file-ext'] = info.file.split('.').pop(); info['file-type'] = media.type.replace('animated_', ''); 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]); this.downloader.add({ url: info.url, name: info.out, onload: () => { tasks -= 1; tasks_result.push(((medias.length > 1 || index) ? (index ? index : i + 1) + ': ' : '') + lang.completed); this.status(btn, null, tasks_result.sort().join('\n')); if (tasks === 0) { this.status(btn, 'completed', lang.completed); if (save_history && !is_exist) { history.push(status_id); this.storage(status_id); } } }, onerror: result => { tasks = -1; tasks_result.push((medias.length > 1 ? i + 1 + ': ' : '') + result.details.current); this.status(btn, 'failed', tasks_result.sort().join('\n')); } }); }); } else { this.status(btn, 'failed', 'MEDIA_NOT_FOUND'); } }, // tag_ppEdit , 有bug , 不知道为啥有时候会失败 , 404 favoriteTweet: async function (tweet_id, queryId) { let base_url = `https://${host}/i/api/graphql/${queryId}/FavoriteTweet`; let variables = { "tweet_id": tweet_id }; // let queryId = "lI07N6Otwv1PhnEgXILM7A"; let body = JSON.stringify({ variables: variables, queryId: queryId }); let cookies = this.getCookie(); let headers = { 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA', 'x-twitter-active-user': 'yes', 'x-twitter-client-language': cookies.lang, 'x-csrf-token': cookies.ct0, 'content-type': 'application/json' // 添加 content-type 头 }; if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt; try { let response = await fetch(base_url, { method: 'POST', headers: headers, body: body }); console.log("Favorite Tweet Response:", response); if (!response.ok) { console.error("Favorite Tweet Response --- HTTP error!"); return null; } let result = await response.json(); console.log("Favorite Tweet Response json:", result); return result; } catch (error) { console.error("Error favoriting tweet:", error); return null; } }, status: function (btn, css, title, style) { if (css) { btn.classList.remove('download', 'completed', 'loading', 'failed'); btn.classList.add(css); } if (title) btn.title = title; if (style) btn.style.cssText = style; }, settings: async function () { const $element = (parent, tag, style, content, css) => { let el = document.createElement(tag); if (style) el.style.cssText = style; if (typeof content !== 'undefined') { if (tag == 'input') { if (content == 'checkbox') el.type = content; else el.value = content; } else el.innerHTML = content; } if (css) css.split(' ').forEach(c => el.classList.add(c)); parent.appendChild(el); return el; }; let wapper = $element(document.body, 'div', 'position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: #0009; z-index: 10;'); let wapper_close; wapper.onmousedown = e => { wapper_close = e.target == wapper; }; wapper.onmouseup = e => { if (wapper_close && e.target == wapper) wapper.remove(); }; 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;'); let title = $element(dialog, 'h3', 'margin: 10px 20px;', lang.dialog.title); let options = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;'); let save_history_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.save_history); let save_history_input = $element(save_history_label, 'input', 'float: left;', 'checkbox'); save_history_input.checked = await GM_getValue('save_history', true); save_history_input.onchange = () => { GM_setValue('save_history', save_history_input.checked); } // tag_ppEdit let previewSetDiv = $element(options, 'div', 'margin: 1px 2px;', "preOnOff,previewOnSide(other is on center)"); let previewSwitchDiv = $element(previewSetDiv, 'input', 'float: right;', "checkbox"); let previewOnSideDiv = $element(previewSetDiv, 'input', 'float: right;', "checkbox"); save_history_input.checked = await GM_getValue('save_history', true); save_history_input.onchange = () => { GM_setValue('save_history', save_history_input.checked); } preview_width_input.onchange = () => { let newPreviewWidth = preview_width_input.value; console.log(" 预览宽度变化 : ", newPreviewWidth); GM_setValue('previewWidth', newPreviewWidth); divWidth = newPreviewWidth; previewDiv.style.width = newPreviewWidth + "px"; } preview_height_input.onchange = () => { let newPreviewHeight = preview_height_input.value; console.log(" 预览高度变化 : ", newPreviewHeight); GM_setValue('previewHeight', newPreviewHeight); divHeight = newPreviewHeight; previewDiv.style.height = newPreviewHeight + "px"; } previewSwitchDiv.onchange = () => { previewSwitch = previewSwitchDiv.checked; GM_setValue('previewSwitch', previewSwitch); }; previewOnSideDiv.onchange = () => { previewOnSide = previewOnSideDiv.checked; GM_setValue('previewOnSide', previewOnSide); }; let clear_history = $element(save_history_label, 'label', 'display: inline-block; margin: 0 10px; color: blue;', lang.dialog.clear_history); clear_history.onclick = () => { if (confirm(lang.dialog.clear_confirm)) { history = []; GM_setValue('download_history', []); } }; let show_sensitive_label = $element(options, 'label', 'display: block; margin: 10px;', lang.dialog.show_sensitive); let show_sensitive_input = $element(show_sensitive_label, 'input', 'float: left;', 'checkbox'); show_sensitive_input.checked = await GM_getValue('show_sensitive', false); show_sensitive_input.onchange = () => { show_sensitive = show_sensitive_input.checked; GM_setValue('show_sensitive', show_sensitive); }; let filename_div = $element(dialog, 'div', 'margin: 10px; border: 1px solid #ccc; border-radius: 5px;'); let filename_label = $element(filename_div, 'label', 'display: block; margin: 10px 15px;', lang.dialog.pattern); 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)); let filename_tags = $element(filename_div, 'label', 'display: table; margin: 10px;', ` {user-name} {user-id} {status-id} {date-time}
{full-text} {file-type} {file-name} `); filename_input.selectionStart = filename_input.value.length; filename_tags.querySelectorAll('.tmd-tag').forEach(tag => { tag.onclick = () => { let ss = filename_input.selectionStart; let se = filename_input.selectionEnd; filename_input.value = filename_input.value.substring(0, ss) + tag.innerText + filename_input.value.substring(se); filename_input.selectionStart = ss + tag.innerText.length; filename_input.selectionEnd = ss + tag.innerText.length; filename_input.focus(); }; }); let btn_save = $element(title, 'label', 'float: right;', lang.dialog.save, 'tmd-btn'); btn_save.onclick = async () => { await GM_setValue('filename', filename_input.value); wapper.remove(); }; }, fetchJson: async function (status_id) { let base_url = `https://${host}/i/api/graphql/2ICDjqPd81tulZcYrtpTuQ/TweetResultByRestId`; let variables = { // "focalTweetId":status_id, "tweetId": status_id, "with_rux_injections": false, "includePromotedContent": true, "withCommunity": true, "withQuickPromoteEligibilityTweetFields": true, "withBirdwatchNotes": true, "withVoice": true, "withV2Timeline": true }; let features = { "articles_preview_enabled": true, "c9s_tweet_anatomy_moderator_badge_enabled": true, "communities_web_enable_tweet_community_results_fetch": false, "creator_subscriptions_quote_tweet_preview_enabled": false, "creator_subscriptions_tweet_preview_api_enabled": false, "freedom_of_speech_not_reach_fetch_enabled": true, "graphql_is_translatable_rweb_tweet_is_translatable_enabled": true, "longform_notetweets_consumption_enabled": false, "longform_notetweets_inline_media_enabled": true, "longform_notetweets_rich_text_read_enabled": false, "premium_content_api_read_enabled": false, "profile_label_improvements_pcf_label_in_post_enabled": true, "responsive_web_edit_tweet_api_enabled": false, "responsive_web_enhance_cards_enabled": false, "responsive_web_graphql_exclude_directive_enabled": false, "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false, "responsive_web_graphql_timeline_navigation_enabled": false, "responsive_web_grok_analysis_button_from_backend": false, "responsive_web_grok_analyze_button_fetch_trends_enabled": false, "responsive_web_grok_analyze_post_followups_enabled": false, "responsive_web_grok_image_annotation_enabled": false, "responsive_web_grok_share_attachment_enabled": false, "responsive_web_grok_show_grok_translated_post": false, "responsive_web_jetfuel_frame": false, "responsive_web_media_download_video_enabled": false, "responsive_web_twitter_article_tweet_consumption_enabled": true, "rweb_tipjar_consumption_enabled": true, "rweb_video_screen_enabled": false, "standardized_nudges_misinfo": true, "tweet_awards_web_tipping_enabled": false, "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": true, "tweetypie_unmention_optimization_enabled": false, "verified_phone_label_enabled": false, "view_counts_everywhere_api_enabled": true, }; let url = encodeURI(`${base_url}?variables=${JSON.stringify(variables)}&features=${JSON.stringify(features)}`); let cookies = this.getCookie(); let headers = { 'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA', 'x-twitter-active-user': 'yes', 'x-twitter-client-language': cookies.lang, 'x-csrf-token': cookies.ct0 }; if (cookies.ct0.length == 32) headers['x-guest-token'] = cookies.gt; let tweet_detail = await fetch(url, {headers: headers}).then(result => result.json()); //let tweet_entrie = tweet_detail.data.threaded_conversation_with_injections_v2.instructions[0].entries.find(n => n.entryId == `tweet-${status_id}`); //let tweet_result = tweet_entrie.content.itemContent.tweet_results.result; let tweet_result = tweet_detail.data.tweetResult.result; return tweet_result.tweet || tweet_result; }, // tag_ppEdit displayFavoriteResult: function (result, status_id) { let favoriteDiv = document.getElementById('favorite-result'); if (!favoriteDiv) { favoriteDiv = document.createElement('div'); favoriteDiv.id = 'favorite-result'; favoriteDiv.style.position = 'fixed'; // favoriteDiv.style.top = '10px'; // favoriteDiv.style.left = '10px'; favoriteDiv.style.top = '2px'; favoriteDiv.style.left = '2px'; favoriteDiv.style.backgroundColor = '#fff'; // favoriteDiv.style.padding = '10px'; favoriteDiv.style.border = '1px solid #ccc'; favoriteDiv.style.zIndex = '1000'; favoriteDiv.style.color = "black"; favoriteDiv.style.fontSize = "10px"; document.body.appendChild(favoriteDiv); } let data = {}; data.result = result; data.time = timestampToYMDHMS(Date.now() + timeOffset); data.status_id = status_id; favoriteDiv.innerHTML = result ? JSON.stringify(data, null, 2) : 'Failed to favorite tweet'; return result != null && result.data != null && result.data.favorite_tweet != null && result.data.favorite_tweet === 'Done'; }, displayFavoriteResult_simp: function (str) { let favoriteDiv = document.getElementById('favorite-result'); if (!favoriteDiv) { favoriteDiv = document.createElement('div'); favoriteDiv.id = 'favorite-result'; favoriteDiv.style.position = 'fixed'; // favoriteDiv.style.top = '10px'; // favoriteDiv.style.left = '10px'; favoriteDiv.style.top = '2px'; favoriteDiv.style.left = '2px'; favoriteDiv.style.backgroundColor = '#fff'; // favoriteDiv.style.padding = '10px'; favoriteDiv.style.border = '1px solid #ccc'; favoriteDiv.style.zIndex = '1000'; favoriteDiv.style.color = "black"; favoriteDiv.style.fontSize = "10px"; document.body.appendChild(favoriteDiv); } favoriteDiv.innerHTML = str; }, getCookie: function (name) { let cookies = {}; document.cookie.split(';').filter(n => n.indexOf('=') > 0).forEach(n => { n.replace(/^([^=]+)=(.+)$/, (match, name, value) => { cookies[name.trim()] = value.trim(); }); }); return name ? cookies[name] : cookies; }, storage: async function (value) { let data = await GM_getValue('download_history', []); let data_length = data.length; if (value) { if (Array.isArray(value)) data = data.concat(value); else if (data.indexOf(value) < 0) data.push(value); } else return data; if (data.length > data_length) GM_setValue('download_history', data); }, storage_obsolete: function (is_remove) { let data = JSON.parse(localStorage.getItem('history') || '[]'); if (is_remove) localStorage.removeItem('history'); else return data; }, formatDate: function (i, o, tz) { let d = new Date(i); if (tz) d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); let m = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; let v = { YYYY: d.getUTCFullYear().toString(), YY: d.getUTCFullYear().toString(), MM: d.getUTCMonth() + 1, MMM: m[d.getUTCMonth()], DD: d.getUTCDate(), hh: d.getUTCHours(), mm: d.getUTCMinutes(), ss: d.getUTCSeconds(), h2: d.getUTCHours() % 12, ap: d.getUTCHours() < 12 ? 'AM' : 'PM' }; return o.replace(/(YY(YY)?|MMM?|DD|hh|mm|ss|h2|ap)/g, n => ('0' + v[n]).substr(-n.length)); }, downloader: (function () { let tasks = [], thread = 0, max_thread = 2, retry = 0, max_retry = 2, failed = 0, notifier, has_failed = false; return { add: function (task) { tasks.push(task); if (thread < max_thread) { thread += 1; this.next(); } else this.update(); }, next: async function () { let task = tasks.shift(); await this.start(task); if (tasks.length > 0 && thread <= max_thread) this.next(); else thread -= 1; this.update(); }, start: function (task) { this.update(); return new Promise(resolve => { GM_download({ url: task.url, name: task.name, onload: result => { task.onload(); resolve(); }, onerror: result => { this.retry(task, result); resolve(); }, ontimeout: result => { this.retry(task, result); resolve(); } }); }); }, retry: function (task, result) { retry += 1; if (retry == 3) max_thread = 1; if (task.retry && task.retry >= max_retry || result.details && result.details.current == 'USER_CANCELED') { task.onerror(result); failed += 1; } else { if (max_thread == 1) task.retry = (task.retry || 0) + 1; this.add(task); } }, update: function () { if (!notifier) { notifier = document.createElement('div'); notifier.title = 'Twitter Media Downloader'; notifier.classList.add('tmd-notifier'); notifier.innerHTML = '|'; document.body.appendChild(notifier); } if (failed > 0 && !has_failed) { has_failed = true; notifier.innerHTML += '|'; let clear = document.createElement('label'); notifier.appendChild(clear); clear.onclick = () => { notifier.innerHTML = '|'; failed = 0; has_failed = false; this.update(); }; } notifier.firstChild.innerText = thread; notifier.firstChild.nextElementSibling.innerText = tasks.length; if (failed > 0) notifier.lastChild.innerText = failed; if (thread > 0 || tasks.length > 0 || failed > 0) notifier.classList.add('running'); else notifier.classList.remove('running'); } }; })(), language: { en: { download: 'Download', completed: 'Download Completed', settings: 'Settings', dialog: { title: 'Download Settings', save: 'Save', save_history: 'Remember download history', clear_history: '(Clear)', clear_confirm: 'Clear download history?', show_sensitive: 'Always show sensitive content', pattern: 'File Name Pattern' } }, ja: { download: 'ダウンロード', completed: 'ダウンロード完了', settings: '設定', dialog: { title: 'ダウンロード設定', save: '保存', save_history: 'ダウンロード履歴を保存する', clear_history: '(クリア)', clear_confirm: 'ダウンロード履歴を削除する?', show_sensitive: 'センシティブな内容を常に表示する', pattern: 'ファイル名パターン' } }, zh: { download: '下载', completed: '下载完成', settings: '设置', dialog: { title: '下载设置', save: '保存', save_history: '保存下载记录', clear_history: '(清除)', clear_confirm: '确认要清除下载记录?', show_sensitive: '自动显示敏感的内容', pattern: '文件名格式' } }, 'zh-Hant': { download: '下載', completed: '下載完成', settings: '設置', dialog: { title: '下載設置', save: '保存', save_history: '保存下載記錄', clear_history: '(清除)', clear_confirm: '確認要清除下載記錄?', show_sensitive: '自動顯示敏感的内容', pattern: '文件名規則' } } }, css: ` .tmd-down {margin-left: 12px; order: 99;} .tmd-down:hover > div > div > div > div {color: rgba(29, 161, 242, 1.0);} .tmd-down:hover > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.1);} .tmd-down:active > div > div > div > div > div {background-color: rgba(29, 161, 242, 0.2);} .tmd-down:hover svg {color: rgba(29, 161, 242, 1.0);} .tmd-down:hover div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.1);} .tmd-down:active div:first-child:not(:last-child) {background-color: rgba(29, 161, 242, 0.2);} .tmd-down.tmd-media {position: absolute; right: 0;} .tmd-down.tmd-media > div {display: flex; border-radius: 99px; margin: 2px;} .tmd-down.tmd-media > div > div {display: flex; margin: 6px; color: #fff;} .tmd-down.tmd-media:hover > div {background-color: rgba(255,255,255, 0.6);} .tmd-down.tmd-media:hover > div > div {color: rgba(29, 161, 242, 1.0);} .tmd-down.tmd-media:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);} .tmd-down g {display: none;} .tmd-down.download g.download, .tmd-down.completed g.completed, .tmd-down.loading g.loading,.tmd-down.failed g.failed {display: unset;} .tmd-down.loading svg {animation: spin 1s linear infinite;} @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}} .tmd-btn {display: inline-block; background-color: #1DA1F2; color: #FFFFFF; padding: 0 20px; border-radius: 99px;} .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;} .tmd-btn:hover {background-color: rgba(29, 161, 242, 0.9);} .tmd-tag:hover {background-color: rgba(29, 161, 242, 0.1);} .tmd-notifier {display: none; position: fixed; left: 16px; bottom: 16px; color: #000; background: #fff; border: 1px solid #ccc; border-radius: 8px; padding: 4px;} .tmd-notifier.running {display: flex; align-items: center;} .tmd-notifier label {display: inline-flex; align-items: center; margin: 0 8px;} .tmd-notifier label:before {content: " "; width: 32px; height: 16px; background-position: center; background-repeat: no-repeat;} .tmd-notifier label:nth-child(1):before {background-image:url("data:image/svg+xml;charset=utf8,");} .tmd-notifier label:nth-child(2):before {background-image:url("data:image/svg+xml;charset=utf8,");} .tmd-notifier label:nth-child(3):before {background-image:url("data:image/svg+xml;charset=utf8,");} .tmd-down.tmd-img {position: absolute; right: 0; bottom: 0; display: none !important;} .tmd-down.tmd-img > div {display: flex; border-radius: 99px; margin: 2px; background-color: rgba(255,255,255, 0.6);} .tmd-down.tmd-img > div > div {display: flex; margin: 6px; color: #fff !important;} .tmd-down.tmd-img:not(:hover) > div > div {filter: drop-shadow(0 0 1px #000);} .tmd-down.tmd-img:hover > div > div {color: rgba(29, 161, 242, 1.0);} :hover > .tmd-down.tmd-img, .tmd-img.loading, .tmd-img.completed, .tmd-img.failed {display: block !important;} .tweet-detail-action-item {width: 20% !important;} `, css_ss: ` /* show sensitive in media tab */ li[role="listitem"]>div>div>div>div:not(:last-child) {filter: none;} li[role="listitem"]>div>div>div>div+div:last-child {display: none;} `, svg: ` ` }; })(); TMD.init();