// ==UserScript== // @name Twitter/X Media Downloader (Maintained) // @namespace community.twitter-media-downloader // @version 1.28.0 // @description Download original photos and the highest-bitrate MP4 from posts; batch download media already loaded on a profile's Media page. // @author AMANE (original); community-maintained fork // @license MIT // @copyright 2021 AMANE; community-maintained modifications // @match https://x.com/* // @match https://www.x.com/* // @match https://twitter.com/* // @match https://mobile.twitter.com/* // @match https://mobile.x.com/* // @grant GM_download // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @connect pbs.twimg.com // @connect video.twimg.com // @connect x.com // @connect twitter.com // ==/UserScript== /* * Community-maintained fork of AMANE's Twitter Media Downloader. * Upstream: https://greasyfork.org/scripts/423001-twitter-media-downloader * * The upstream script is MIT-licensed. This fork keeps the attribution and * license while repairing the TweetDetail timeline parser and adding a batch * panel for media cards already discovered on a profile's /media page. * * MIT License * Copyright (c) 2021 AMANE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ (function () { 'use strict'; const VERSION = '1.28.0'; // Operation ID observed in X's current TweetDetail request on 2026-10-21. // X rotates internal GraphQL operation IDs; update this when the endpoint changes. const TWEET_DETAIL_OPERATION = '3BlMtudy4N-d78ch7zTLZQ'; const BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA'; const DEFAULT_FILENAME = 'twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}'; const HISTORY_KEY = 'tmd_download_history_v128'; const FILENAME_KEY = 'tmd_filename_v128'; const PANEL_ID = 'tmd-batch-panel'; const MAX_MEDIA_PER_POST = 16; const DOWNLOAD_GAP_MS = 350; const discoveredPosts = new Map(); let panelStatus; let panelCount; let panelButton; let batchState = null; const completedBatchPosts = new Set(); const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); function readCookie(name) { const part = document.cookie.split('; ').find((item) => item.startsWith(`${name}=`)); return part ? decodeURIComponent(part.slice(name.length + 1)) : ''; } function sanitizeFilename(value) { return String(value || '') .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_') .replace(/[. ]+$/g, '') .trim() .slice(0, 160) || 'twitter-media'; } function getStatusId(href) { try { return new URL(href, location.href).pathname.match(/\/status\/(\d+)/)?.[1] || ''; } catch { return ''; } } function getTweetEntry(response, statusId) { const instructions = response?.data?.threaded_conversation_with_injections_v2?.instructions; if (!Array.isArray(instructions)) { throw new Error('TweetDetail 响应中没有 instructions;X 可能已更改接口结构。'); } // X may prepend TimelineClearCache (without entries) before TimelineAddEntries. // Never assume instructions[0] contains the timeline entries. const entries = instructions.flatMap((instruction) => Array.isArray(instruction?.entries) ? instruction.entries : [] ); const entry = entries.find((item) => item?.entryId === `tweet-${statusId}`); if (!entry) { throw new Error(`TweetDetail 响应中找不到推文 ${statusId}。`); } const result = entry?.content?.itemContent?.tweet_results?.result; if (!result) { throw new Error('找到推文条目,但 tweet_results.result 不存在;X 可能已更改字段结构。'); } return result.tweet || result; } async function fetchTweet(statusId) { const variables = { focalTweetId: statusId, with_rux_injections: false, includePromotedContent: true, withCommunity: true, withQuickPromoteEligibilityTweetFields: true, withBirdwatchNotes: true, withVoice: true, withV2Timeline: true, }; const features = { rweb_lists_timeline_redesign_enabled: true, responsive_web_graphql_exclude_directive_enabled: true, verified_phone_label_enabled: false, creator_subscriptions_tweet_preview_api_enabled: true, responsive_web_graphql_timeline_navigation_enabled: true, responsive_web_graphql_skip_user_profile_image_extensions_enabled: false, tweetypie_unmention_optimization_enabled: true, responsive_web_edit_tweet_api_enabled: true, graphql_is_translatable_rweb_tweet_is_translatable_enabled: true, view_counts_everywhere_api_enabled: true, longform_notetweets_consumption_enabled: true, responsive_web_twitter_article_tweet_consumption_enabled: false, tweet_awards_web_tipping_enabled: false, freedom_of_speech_not_reach_fetch_enabled: true, standardized_nudges_misinfo: true, tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true, longform_notetweets_rich_text_read_enabled: true, longform_notetweets_inline_media_enabled: true, responsive_web_media_download_video_enabled: false, responsive_web_enhance_cards_enabled: false, }; const url = new URL(`/i/api/graphql/${TWEET_DETAIL_OPERATION}/TweetDetail`, location.origin); url.searchParams.set('variables', JSON.stringify(variables)); url.searchParams.set('features', JSON.stringify(features)); const csrfToken = readCookie('ct0'); const headers = { authorization: `Bearer ${BEARER_TOKEN}`, 'x-twitter-active-user': 'yes', 'x-twitter-client-language': readCookie('lang') || document.documentElement.lang || 'en', }; if (csrfToken) headers['x-csrf-token'] = csrfToken; const guestToken = readCookie('gt'); if (guestToken) headers['x-guest-token'] = guestToken; const response = await fetch(url, { headers, credentials: 'same-origin' }); const body = await response.text(); let json; try { json = JSON.parse(body); } catch { throw new Error(`TweetDetail 返回了非 JSON 内容(HTTP ${response.status})。`); } if (!response.ok) { const apiMessage = json?.errors?.map((error) => error.message).filter(Boolean).join('; '); throw new Error(`TweetDetail 请求失败(HTTP ${response.status})${apiMessage ? `:${apiMessage}` : ''}`); } return getTweetEntry(json, statusId); } function getMedia(tweet) { const media = tweet?.legacy?.extended_entities?.media || tweet?.extended_entities?.media || tweet?.legacy?.entities?.media || []; if (!Array.isArray(media) || !media.length) { throw new Error('该推文没有可下载的媒体,或媒体字段未返回。'); } return media.slice(0, MAX_MEDIA_PER_POST); } function userInfo(tweet) { const result = tweet?.core?.user_results?.result || {}; // Newer TweetDetail responses use User.core; older responses used User.legacy. const user = result.legacy || result.core || result; return { name: user.name || user.screen_name || 'twitter-user', handle: user.screen_name || 'unknown', }; } function buildMediaUrl(media) { if (media.type === 'photo') { if (!media.media_url_https) throw new Error('图片媒体没有 media_url_https。'); return { url: `${media.media_url_https}:orig`, extension: 'jpg', type: 'photo' }; } const variants = media.video_info?.variants; if (!Array.isArray(variants)) throw new Error(`媒体类型 ${media.type || 'unknown'} 没有视频变体。`); const mp4s = variants .filter((variant) => variant?.content_type === 'video/mp4' && variant.url) .sort((a, b) => (b.bitrate || 0) - (a.bitrate || 0)); if (!mp4s.length) throw new Error('没有找到可下载的 MP4 变体。'); return { url: mp4s[0].url, extension: 'mp4', type: media.type === 'animated_gif' ? 'gif' : 'video' }; } async function buildDownloadItems(statusId, tweet) { const legacy = tweet.legacy || tweet; const user = userInfo(tweet); const mediaList = getMedia(tweet); const pattern = await GM_getValue(FILENAME_KEY, DEFAULT_FILENAME); return mediaList.map((media, index) => { const item = buildMediaUrl(media); const sequence = mediaList.length > 1 ? `-${String(index + 1).padStart(2, '0')}` : ''; const values = { 'user-name': user.name, 'user-id': user.handle, 'date-time': formatTimestamp(legacy.created_at), 'status-id': statusId, 'file-type': item.type, 'file-name': item.url.split('/').pop().split(/[?:]/)[0], }; const baseName = pattern.replace(/\{([^{}]+)\}/g, (match, key) => values[key] ?? match); return { ...item, statusId, filename: `${sanitizeFilename(baseName)}${sequence}.${item.extension}` }; }); } async function downloadFile(url, filename) { if (typeof GM_download !== 'function') throw new Error('GM_download 不可用,请检查用户脚本管理器权限。'); return new Promise((resolve, reject) => { GM_download({ url, name: filename, saveAs: false, timeout: 60000, onload: resolve, onerror: (error) => reject(new Error(error?.error || error?.details?.current || '下载失败')), ontimeout: () => reject(new Error('下载超时')), }); }); } function formatTimestamp(dateString) { const date = new Date(dateString); if (Number.isNaN(date.getTime())) return new Date().toISOString().replace(/[-:TZ.]/g, '').slice(0, 14); return date.toISOString().replace(/[-:TZ.]/g, '').slice(0, 14); } async function downloadStatus(statusId, onProgress) { const tweet = await fetchTweet(statusId); const items = await buildDownloadItems(statusId, tweet); const history = await GM_getValue(HISTORY_KEY, []); const results = []; let succeeded = 0; for (let index = 0; index < items.length; index += 1) { const item = items[index]; onProgress?.({ index: index + 1, total: items.length, filename: item.filename }); try { await downloadFile(item.url, item.filename); succeeded += 1; results.push({ filename: item.filename, url: item.url, success: true }); } catch (error) { results.push({ filename: item.filename, url: item.url, success: false, error: error.message }); } if (index < items.length - 1) await sleep(DOWNLOAD_GAP_MS); } if (succeeded === items.length && !history.includes(statusId)) { history.push(statusId); await GM_setValue(HISTORY_KEY, history); } return { tweet, results, succeeded, failed: items.length - succeeded }; } const ICON_PATHS = { download: 'M5 20h14v-2H5v2zm7-18a1 1 0 0 0-1 1v8H7l5 5 5-5h-4V3a1 1 0 0 0-1-1z', completed: 'M9 16.2 4.8 12l-1.4 1.4L9 19l12-12-1.4-1.4z', failed: 'M19 6.4 17.6 5 12 10.6 6.4 5 5 6.4 10.6 12 5 17.6 6.4 19 12 13.4 17.6 19 19 17.6 13.4 12z', loading: 'M12 2a10 10 0 1 0 10 10h-2a8 8 0 1 1-8-8V2zm1-1v6l5-3-5-3z', }; function setButtonState(button, state, title) { button.dataset.state = state; const label = title || ({ download: '下载此推文媒体', loading: '正在下载…', completed: '下载完成(仍可再次点击)', failed: '下载失败;点击重试' }[state]); let svg = button.querySelector('svg'); if (!svg) { svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); button.append(svg); } svg.innerHTML = ``; button.title = label; button.setAttribute('aria-label', label); button.setAttribute('role', 'button'); if (!button.hasAttribute('tabindex')) button.tabIndex = 0; button.setAttribute('aria-disabled', state === 'loading' ? 'true' : 'false'); } async function runSingleDownload(button, statusId) { if (button.dataset.state === 'loading') return; setButtonState(button, 'loading'); try { const result = await downloadStatus(statusId, ({ index, total, filename }) => { button.title = `正在下载 ${index}/${total}:${filename}`; }); if (result.failed) { const failed = result.results.filter((item) => !item.success).map((item) => `${item.filename}: ${item.error}`).join('\n'); setButtonState(button, 'failed', failed || '部分媒体下载失败;点击重试'); } else { setButtonState(button, 'completed'); } } catch (error) { console.error('[Twitter Media Downloader]', error); setButtonState(button, 'failed', error.message || '下载失败;点击重试'); } } function isMediaArticle(article) { return Boolean(article.querySelector( 'a[href*="/photo/"], [data-testid="tweetPhoto"], [data-testid="videoPlayer"], video, div[role="progressbar"], div[data-testid="playButton"]' )); } function addTweetButton(article) { if (!(article instanceof HTMLElement) || article.dataset.tmdButton === 'true' || !isMediaArticle(article)) return; const statusLink = article.querySelector('a[href*="/status/"]'); const actionGroup = article.querySelector('div[role="group"]'); const statusId = statusLink && getStatusId(statusLink.href); if (!statusId || !actionGroup) return; const originalAction = Array.from(actionGroup.querySelectorAll(':scope > div > div')).pop()?.parentNode; const button = originalAction?.cloneNode(true) || document.createElement('button'); button.classList.add('tmd-maintained-button'); button.removeAttribute('id'); button.removeAttribute('data-testid'); button.querySelectorAll('[data-testid]').forEach((node) => node.removeAttribute('data-testid')); setButtonState(button, 'download'); const activate = (event) => { event.preventDefault(); event.stopPropagation(); runSingleDownload(button, statusId); }; button.addEventListener('click', activate); button.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') activate(event); }); actionGroup.append(button); article.dataset.tmdButton = 'true'; } function queuePostForBatch(statusId) { const state = batchState; if (!state?.active || state.queuedPosts.has(statusId) || completedBatchPosts.has(statusId)) return; state.queuedPosts.add(statusId); state.postQueue.push(statusId); } function updateBatchPanel() { if (!panelCount || !panelButton) return; const eligiblePosts = Array.from(discoveredPosts.keys()).filter((id) => !completedBatchPosts.has(id)); panelCount.textContent = batchState?.active ? `已发现 ${discoveredPosts.size} 条推文,已识别 ${batchState.scheduledFiles} 个媒体文件` : `已发现 ${discoveredPosts.size} 条媒体推文(已加载)`; if (batchState?.active) { panelButton.disabled = false; panelButton.textContent = batchState.paused ? '继续下载' : '暂停下载'; const queuedPosts = batchState.postQueue.length; const queuedFiles = batchState.mediaQueue.length; const running = batchState.currentMedia ? `;当前文件:${batchState.currentMedia.filename}` : batchState.currentPost ? `;正在读取推文 ${batchState.currentPost}` : ''; const pauseLabel = batchState.paused && batchState.currentMedia ? '正在暂停(当前文件完成后停止)' : batchState.paused ? '已暂停' : '下载中'; panelStatus.textContent = `${pauseLabel}:待读取推文 ${queuedPosts} 条,待下载媒体 ${queuedFiles} 个,成功 ${batchState.succeeded},失败 ${batchState.failed}${running}`; } else { panelButton.disabled = eligiblePosts.length === 0; panelButton.textContent = eligiblePosts.length ? '下载已加载媒体' : discoveredPosts.size ? '已下载当前媒体' : '等待媒体加载'; if (panelStatus && !batchState?.finished) panelStatus.textContent = '不会自动滚动页面;滚动加载更多后会继续收集。'; } } function collectLoadedMediaPosts() { const anchors = document.querySelectorAll('main a[href*="/status/"]'); for (const anchor of anchors) { const href = anchor.href || ''; if (!/\/status\/\d+\/(?:photo|video)\/\d+/i.test(href)) continue; const statusId = getStatusId(href); if (statusId && !discoveredPosts.has(statusId)) { discoveredPosts.set(statusId, true); queuePostForBatch(statusId); } } updateBatchPanel(); return Array.from(discoveredPosts.keys()); } function createBatchPanel() { if (!/\/media\/?$/.test(location.pathname) || document.getElementById(PANEL_ID)) return; const panel = document.createElement('section'); panel.id = PANEL_ID; panel.innerHTML = `
X 媒体批量下载
正在扫描已加载媒体…
不会自动滚动页面;滚动加载更多后会继续收集。
`; document.body.append(panel); panelCount = panel.querySelector('.tmd-batch-count'); panelStatus = panel.querySelector('.tmd-batch-status'); panelButton = panel.querySelector('.tmd-batch-download'); panel.querySelector('.tmd-collapse').addEventListener('click', () => { panel.classList.toggle('collapsed'); panel.querySelector('.tmd-collapse').textContent = panel.classList.contains('collapsed') ? '+' : '−'; }); panelButton.addEventListener('click', handleBatchButton); collectLoadedMediaPosts(); } function safeText(value) { return String(value || '').replace(/[\r\n\t]+/g, ' ').trim(); } function batchFolderName() { const handle = location.pathname.split('/').filter(Boolean)[0] || 'X'; const runId = Math.random().toString(36).slice(2, 6); return sanitizeFilename(`${handle}_media_${formatTimestamp(new Date().toISOString())}_${runId}`); } function createBatchInfoBlob(state) { const lines = [ 'Twitter/X Media Downloader — batch report', `Profile: ${location.origin}/${state.handle}/media`, `Started: ${state.startedAt}`, `Finished: ${new Date().toLocaleString()}`, `Posts initially queued: ${state.discoveredCountAtStart} (newly discovered posts during the run are included)`, `Files succeeded: ${state.succeeded}`, `Files failed: ${state.failed}`, '', 'Results:', ]; state.results.forEach((item) => { lines.push(`- ${item.success ? 'SUCCESS' : 'FAILED'}: ${safeText(item.filename || item.statusId)}`); if (item.statusId) lines.push(` Post: https://x.com/${state.handle}/status/${item.statusId}`); if (item.url) lines.push(` Media URL: ${item.url}`); if (item.error) lines.push(` Error: ${safeText(item.error)}`); }); return new Blob([`\uFEFF${lines.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }); } async function startBatchDownload() { collectLoadedMediaPosts(); const eligible = Array.from(discoveredPosts.keys()).filter((id) => !completedBatchPosts.has(id)); if (!eligible.length) return; const handle = location.pathname.split('/').filter(Boolean)[0] || 'X'; batchState = { active: true, paused: false, pumping: false, handle, folder: batchFolderName(), startedAt: new Date().toLocaleString(), discoveredCountAtStart: eligible.length, postQueue: [], queuedPosts: new Set(), mediaQueue: [], queuedMedia: new Set(), postProgress: new Map(), currentPost: '', currentMedia: null, succeeded: 0, failed: 0, scheduledFiles: 0, results: [], finished: false, }; eligible.forEach(queuePostForBatch); updateBatchPanel(); void pumpBatch(batchState); } function handleBatchButton() { if (!batchState?.active) { void startBatchDownload(); return; } if (!batchState.paused) { batchState.paused = true; panelStatus.textContent = batchState.currentMedia ? `正在暂停:当前文件完成后暂停,后续文件不会启动。` : '已暂停;继续后会处理剩余媒体及暂停期间新发现的推文。'; updateBatchPanel(); return; } batchState.paused = false; updateBatchPanel(); void pumpBatch(batchState); } async function finishBatch(state) { if (state.finished) return; state.finished = true; try { await downloadFile(createBatchInfoBlob(state), `${state.folder}/info.txt`); state.infoSaved = true; } catch (error) { state.infoSaved = false; console.warn('[Twitter Media Downloader] info.txt download failed', error); } if (batchState === state) { panelStatus.textContent = `完成:成功 ${state.succeeded} 个媒体,失败 ${state.failed} 个;${state.infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`; updateBatchPanel(); } } async function pumpBatch(state) { if (!state?.active || state.paused || state.pumping) return; state.pumping = true; try { while (state.active && !state.paused) { if (state.mediaQueue.length) { const item = state.mediaQueue.shift(); state.currentMedia = item; updateBatchPanel(); let success = false; let errorMessage = ''; try { await downloadFile(item.url, `${state.folder}/${item.filename}`); success = true; state.succeeded += 1; } catch (error) { errorMessage = error.message || '下载失败'; state.failed += 1; } state.results.push({ statusId: item.statusId, filename: item.filename, url: item.url, success, error: errorMessage }); const progress = state.postProgress.get(item.statusId); if (progress) { progress.remaining -= 1; if (!success) progress.failed = true; if (progress.remaining === 0 && !progress.failed) completedBatchPosts.add(item.statusId); } state.currentMedia = null; updateBatchPanel(); await sleep(DOWNLOAD_GAP_MS); continue; } if (state.postQueue.length) { const statusId = state.postQueue.shift(); state.currentPost = statusId; updateBatchPanel(); try { const tweet = await fetchTweet(statusId); const items = await buildDownloadItems(statusId, tweet); const freshItems = items.filter((item) => { if (state.queuedMedia.has(item.url)) return false; state.queuedMedia.add(item.url); return true; }); if (!freshItems.length) { completedBatchPosts.add(statusId); state.results.push({ statusId, filename: '', success: true, error: '重复媒体,已跳过' }); } else { state.postProgress.set(statusId, { remaining: freshItems.length, failed: false }); state.scheduledFiles += freshItems.length; state.mediaQueue.push(...freshItems); } } catch (error) { state.failed += 1; state.results.push({ statusId, filename: '', success: false, error: error.message || '读取推文失败' }); console.warn('[Twitter Media Downloader] batch post failed', statusId, error); } state.currentPost = ''; updateBatchPanel(); continue; } state.active = false; } } finally { state.pumping = false; if (state.active && !state.paused && (state.postQueue.length || state.mediaQueue.length)) { void pumpBatch(state); } else if (!state.active) { await finishBatch(state); } updateBatchPanel(); } } function installStyles() { if (document.getElementById('tmd-maintained-style')) return; const style = document.createElement('style'); style.id = 'tmd-maintained-style'; style.textContent = ` #${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:285px;color:#202124;background:var(--background-primary,#fff); border:1px solid #d9dde3;border-radius:12px;box-shadow:0 4px 18px #0002;font:14px/1.5 system-ui,sans-serif} #${PANEL_ID} header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border-bottom:1px solid #eee} #${PANEL_ID} button{font:inherit;cursor:pointer}#${PANEL_ID} .tmd-collapse{border:0;background:transparent;font-size:20px;color:#666} #${PANEL_ID} .tmd-panel-body{padding:11px 12px 12px}#${PANEL_ID} .tmd-batch-count{margin-bottom:9px;color:#536471} #${PANEL_ID} .tmd-batch-download{width:100%;padding:8px;border:0;border-radius:999px;background:#1d9bf0;color:white;font-weight:700} #${PANEL_ID} .tmd-batch-download:hover{background:#1a8cd8}#${PANEL_ID} .tmd-batch-download:disabled{opacity:.55;cursor:default} #${PANEL_ID} .tmd-batch-status{min-height:20px;margin-top:8px;color:#536471;font-size:12px} #${PANEL_ID}.collapsed{width:auto}#${PANEL_ID}.collapsed .tmd-panel-body{display:none} .tmd-maintained-button{display:inline-flex!important;align-items:center;justify-content:center;width:34px;height:34px;margin-left:4px;padding:0; color:rgb(83,100,113);background:transparent;border:0;border-radius:999px;cursor:pointer} .tmd-maintained-button:hover{color:rgb(29,155,240);background:rgba(29,155,240,.1)} .tmd-maintained-button svg{display:block;width:18px;height:18px;fill:currentColor} .tmd-maintained-button[data-state="completed"]{color:rgb(29,155,240)} .tmd-maintained-button[data-state="failed"]{color:rgb(244,33,46)} .tmd-maintained-button[data-state="loading"] svg{animation:tmd-spin 1s linear infinite} @keyframes tmd-spin{to{transform:rotate(360deg)}}`; document.head.append(style); } function installSettings() { if (typeof GM_registerMenuCommand !== 'function') return; GM_registerMenuCommand('下载设置:文件名格式', async () => { const current = await GM_getValue(FILENAME_KEY, DEFAULT_FILENAME); const next = window.prompt('文件名格式,可用 {user-name} {user-id} {date-time} {status-id} {file-type} {file-name}', current); if (next !== null && next.trim()) await GM_setValue(FILENAME_KEY, next.trim()); }); GM_registerMenuCommand(`Twitter Media Downloader ${VERSION}`, () => { window.alert('AMANE 原脚本的社区维护版。支持单条下载及媒体页已加载内容批量下载。'); }); } function scanPage() { const isMediaPage = /\/media\/?$/.test(location.pathname); const panel = document.getElementById(PANEL_ID); if (!isMediaPage && panel && !batchState?.active) { panel.remove(); panelCount = null; panelStatus = null; panelButton = null; discoveredPosts.clear(); } document.querySelectorAll('article').forEach(addTweetButton); if (isMediaPage) { if (!document.getElementById(PANEL_ID)) createBatchPanel(); collectLoadedMediaPosts(); } } function start() { installStyles(); installSettings(); createBatchPanel(); scanPage(); let scanTimer; const observer = new MutationObserver(() => { window.clearTimeout(scanTimer); scanTimer = window.setTimeout(() => { scanPage(); if (!document.getElementById(PANEL_ID)) createBatchPanel(); }, 120); }); observer.observe(document.body, { childList: true, subtree: true }); } if (document.body) start(); else document.addEventListener('DOMContentLoaded', start, { once: true }); })();