twitter-media-downloader.user.js
· 29 KiB · JavaScript
Ham
// ==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 = `<path fill="currentColor" d="${ICON_PATHS[state] || ICON_PATHS.download}"></path>`;
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 = `
<header><strong>X 媒体批量下载</strong><button type="button" class="tmd-collapse" aria-label="收起">−</button></header>
<div class="tmd-panel-body">
<div class="tmd-batch-count">正在扫描已加载媒体…</div>
<button type="button" class="tmd-batch-download" disabled>下载已加载媒体</button>
<div class="tmd-batch-status" role="status">不会自动滚动页面;滚动加载更多后会继续收集。</div>
</div>`;
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 });
})();
| 1 | // ==UserScript== |
| 2 | // @name Twitter/X Media Downloader (Maintained) |
| 3 | // @namespace community.twitter-media-downloader |
| 4 | // @version 1.28.0 |
| 5 | // @description Download original photos and the highest-bitrate MP4 from posts; batch download media already loaded on a profile's Media page. |
| 6 | // @author AMANE (original); community-maintained fork |
| 7 | // @license MIT |
| 8 | // @copyright 2021 AMANE; community-maintained modifications |
| 9 | // @match https://x.com/* |
| 10 | // @match https://www.x.com/* |
| 11 | // @match https://twitter.com/* |
| 12 | // @match https://mobile.twitter.com/* |
| 13 | // @match https://mobile.x.com/* |
| 14 | // @grant GM_download |
| 15 | // @grant GM_getValue |
| 16 | // @grant GM_setValue |
| 17 | // @grant GM_registerMenuCommand |
| 18 | // @connect pbs.twimg.com |
| 19 | // @connect video.twimg.com |
| 20 | // @connect x.com |
| 21 | // @connect twitter.com |
| 22 | // ==/UserScript== |
| 23 | |
| 24 | /* |
| 25 | * Community-maintained fork of AMANE's Twitter Media Downloader. |
| 26 | * Upstream: https://greasyfork.org/scripts/423001-twitter-media-downloader |
| 27 | * |
| 28 | * The upstream script is MIT-licensed. This fork keeps the attribution and |
| 29 | * license while repairing the TweetDetail timeline parser and adding a batch |
| 30 | * panel for media cards already discovered on a profile's /media page. |
| 31 | * |
| 32 | * MIT License |
| 33 | * Copyright (c) 2021 AMANE |
| 34 | * |
| 35 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 36 | * of this software and associated documentation files (the "Software"), to |
| 37 | * deal in the Software without restriction, including without limitation the |
| 38 | * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or |
| 39 | * sell copies of the Software, and to permit persons to whom the Software is |
| 40 | * furnished to do so, subject to the following conditions: |
| 41 | * |
| 42 | * The above copyright notice and this permission notice shall be included in |
| 43 | * all copies or substantial portions of the Software. |
| 44 | * |
| 45 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 46 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 47 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 48 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 49 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 50 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 51 | * IN THE SOFTWARE. |
| 52 | */ |
| 53 | |
| 54 | (function () { |
| 55 | 'use strict'; |
| 56 | |
| 57 | const VERSION = '1.28.0'; |
| 58 | // Operation ID observed in X's current TweetDetail request on 2026-10-21. |
| 59 | // X rotates internal GraphQL operation IDs; update this when the endpoint changes. |
| 60 | const TWEET_DETAIL_OPERATION = '3BlMtudy4N-d78ch7zTLZQ'; |
| 61 | const BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA'; |
| 62 | const DEFAULT_FILENAME = 'twitter_{user-name}(@{user-id})_{date-time}_{status-id}_{file-type}'; |
| 63 | const HISTORY_KEY = 'tmd_download_history_v128'; |
| 64 | const FILENAME_KEY = 'tmd_filename_v128'; |
| 65 | const PANEL_ID = 'tmd-batch-panel'; |
| 66 | const MAX_MEDIA_PER_POST = 16; |
| 67 | const DOWNLOAD_GAP_MS = 350; |
| 68 | const discoveredPosts = new Map(); |
| 69 | let panelStatus; |
| 70 | let panelCount; |
| 71 | let panelButton; |
| 72 | let batchState = null; |
| 73 | const completedBatchPosts = new Set(); |
| 74 | |
| 75 | const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); |
| 76 | |
| 77 | function readCookie(name) { |
| 78 | const part = document.cookie.split('; ').find((item) => item.startsWith(`${name}=`)); |
| 79 | return part ? decodeURIComponent(part.slice(name.length + 1)) : ''; |
| 80 | } |
| 81 | |
| 82 | function sanitizeFilename(value) { |
| 83 | return String(value || '') |
| 84 | .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_') |
| 85 | .replace(/[. ]+$/g, '') |
| 86 | .trim() |
| 87 | .slice(0, 160) || 'twitter-media'; |
| 88 | } |
| 89 | |
| 90 | function getStatusId(href) { |
| 91 | try { |
| 92 | return new URL(href, location.href).pathname.match(/\/status\/(\d+)/)?.[1] || ''; |
| 93 | } catch { |
| 94 | return ''; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | function getTweetEntry(response, statusId) { |
| 99 | const instructions = response?.data?.threaded_conversation_with_injections_v2?.instructions; |
| 100 | if (!Array.isArray(instructions)) { |
| 101 | throw new Error('TweetDetail 响应中没有 instructions;X 可能已更改接口结构。'); |
| 102 | } |
| 103 | |
| 104 | // X may prepend TimelineClearCache (without entries) before TimelineAddEntries. |
| 105 | // Never assume instructions[0] contains the timeline entries. |
| 106 | const entries = instructions.flatMap((instruction) => |
| 107 | Array.isArray(instruction?.entries) ? instruction.entries : [] |
| 108 | ); |
| 109 | const entry = entries.find((item) => item?.entryId === `tweet-${statusId}`); |
| 110 | if (!entry) { |
| 111 | throw new Error(`TweetDetail 响应中找不到推文 ${statusId}。`); |
| 112 | } |
| 113 | |
| 114 | const result = entry?.content?.itemContent?.tweet_results?.result; |
| 115 | if (!result) { |
| 116 | throw new Error('找到推文条目,但 tweet_results.result 不存在;X 可能已更改字段结构。'); |
| 117 | } |
| 118 | return result.tweet || result; |
| 119 | } |
| 120 | |
| 121 | async function fetchTweet(statusId) { |
| 122 | const variables = { |
| 123 | focalTweetId: statusId, |
| 124 | with_rux_injections: false, |
| 125 | includePromotedContent: true, |
| 126 | withCommunity: true, |
| 127 | withQuickPromoteEligibilityTweetFields: true, |
| 128 | withBirdwatchNotes: true, |
| 129 | withVoice: true, |
| 130 | withV2Timeline: true, |
| 131 | }; |
| 132 | const features = { |
| 133 | rweb_lists_timeline_redesign_enabled: true, |
| 134 | responsive_web_graphql_exclude_directive_enabled: true, |
| 135 | verified_phone_label_enabled: false, |
| 136 | creator_subscriptions_tweet_preview_api_enabled: true, |
| 137 | responsive_web_graphql_timeline_navigation_enabled: true, |
| 138 | responsive_web_graphql_skip_user_profile_image_extensions_enabled: false, |
| 139 | tweetypie_unmention_optimization_enabled: true, |
| 140 | responsive_web_edit_tweet_api_enabled: true, |
| 141 | graphql_is_translatable_rweb_tweet_is_translatable_enabled: true, |
| 142 | view_counts_everywhere_api_enabled: true, |
| 143 | longform_notetweets_consumption_enabled: true, |
| 144 | responsive_web_twitter_article_tweet_consumption_enabled: false, |
| 145 | tweet_awards_web_tipping_enabled: false, |
| 146 | freedom_of_speech_not_reach_fetch_enabled: true, |
| 147 | standardized_nudges_misinfo: true, |
| 148 | tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true, |
| 149 | longform_notetweets_rich_text_read_enabled: true, |
| 150 | longform_notetweets_inline_media_enabled: true, |
| 151 | responsive_web_media_download_video_enabled: false, |
| 152 | responsive_web_enhance_cards_enabled: false, |
| 153 | }; |
| 154 | |
| 155 | const url = new URL(`/i/api/graphql/${TWEET_DETAIL_OPERATION}/TweetDetail`, location.origin); |
| 156 | url.searchParams.set('variables', JSON.stringify(variables)); |
| 157 | url.searchParams.set('features', JSON.stringify(features)); |
| 158 | |
| 159 | const csrfToken = readCookie('ct0'); |
| 160 | const headers = { |
| 161 | authorization: `Bearer ${BEARER_TOKEN}`, |
| 162 | 'x-twitter-active-user': 'yes', |
| 163 | 'x-twitter-client-language': readCookie('lang') || document.documentElement.lang || 'en', |
| 164 | }; |
| 165 | if (csrfToken) headers['x-csrf-token'] = csrfToken; |
| 166 | const guestToken = readCookie('gt'); |
| 167 | if (guestToken) headers['x-guest-token'] = guestToken; |
| 168 | |
| 169 | const response = await fetch(url, { headers, credentials: 'same-origin' }); |
| 170 | const body = await response.text(); |
| 171 | let json; |
| 172 | try { |
| 173 | json = JSON.parse(body); |
| 174 | } catch { |
| 175 | throw new Error(`TweetDetail 返回了非 JSON 内容(HTTP ${response.status})。`); |
| 176 | } |
| 177 | if (!response.ok) { |
| 178 | const apiMessage = json?.errors?.map((error) => error.message).filter(Boolean).join('; '); |
| 179 | throw new Error(`TweetDetail 请求失败(HTTP ${response.status})${apiMessage ? `:${apiMessage}` : ''}`); |
| 180 | } |
| 181 | return getTweetEntry(json, statusId); |
| 182 | } |
| 183 | |
| 184 | function getMedia(tweet) { |
| 185 | const media = tweet?.legacy?.extended_entities?.media |
| 186 | || tweet?.extended_entities?.media |
| 187 | || tweet?.legacy?.entities?.media |
| 188 | || []; |
| 189 | if (!Array.isArray(media) || !media.length) { |
| 190 | throw new Error('该推文没有可下载的媒体,或媒体字段未返回。'); |
| 191 | } |
| 192 | return media.slice(0, MAX_MEDIA_PER_POST); |
| 193 | } |
| 194 | |
| 195 | function userInfo(tweet) { |
| 196 | const result = tweet?.core?.user_results?.result || {}; |
| 197 | // Newer TweetDetail responses use User.core; older responses used User.legacy. |
| 198 | const user = result.legacy || result.core || result; |
| 199 | return { |
| 200 | name: user.name || user.screen_name || 'twitter-user', |
| 201 | handle: user.screen_name || 'unknown', |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | function buildMediaUrl(media) { |
| 206 | if (media.type === 'photo') { |
| 207 | if (!media.media_url_https) throw new Error('图片媒体没有 media_url_https。'); |
| 208 | return { url: `${media.media_url_https}:orig`, extension: 'jpg', type: 'photo' }; |
| 209 | } |
| 210 | |
| 211 | const variants = media.video_info?.variants; |
| 212 | if (!Array.isArray(variants)) throw new Error(`媒体类型 ${media.type || 'unknown'} 没有视频变体。`); |
| 213 | const mp4s = variants |
| 214 | .filter((variant) => variant?.content_type === 'video/mp4' && variant.url) |
| 215 | .sort((a, b) => (b.bitrate || 0) - (a.bitrate || 0)); |
| 216 | if (!mp4s.length) throw new Error('没有找到可下载的 MP4 变体。'); |
| 217 | return { url: mp4s[0].url, extension: 'mp4', type: media.type === 'animated_gif' ? 'gif' : 'video' }; |
| 218 | } |
| 219 | |
| 220 | async function buildDownloadItems(statusId, tweet) { |
| 221 | const legacy = tweet.legacy || tweet; |
| 222 | const user = userInfo(tweet); |
| 223 | const mediaList = getMedia(tweet); |
| 224 | const pattern = await GM_getValue(FILENAME_KEY, DEFAULT_FILENAME); |
| 225 | return mediaList.map((media, index) => { |
| 226 | const item = buildMediaUrl(media); |
| 227 | const sequence = mediaList.length > 1 ? `-${String(index + 1).padStart(2, '0')}` : ''; |
| 228 | const values = { |
| 229 | 'user-name': user.name, |
| 230 | 'user-id': user.handle, |
| 231 | 'date-time': formatTimestamp(legacy.created_at), |
| 232 | 'status-id': statusId, |
| 233 | 'file-type': item.type, |
| 234 | 'file-name': item.url.split('/').pop().split(/[?:]/)[0], |
| 235 | }; |
| 236 | const baseName = pattern.replace(/\{([^{}]+)\}/g, (match, key) => values[key] ?? match); |
| 237 | return { ...item, statusId, filename: `${sanitizeFilename(baseName)}${sequence}.${item.extension}` }; |
| 238 | }); |
| 239 | } |
| 240 | |
| 241 | async function downloadFile(url, filename) { |
| 242 | if (typeof GM_download !== 'function') throw new Error('GM_download 不可用,请检查用户脚本管理器权限。'); |
| 243 | return new Promise((resolve, reject) => { |
| 244 | GM_download({ |
| 245 | url, |
| 246 | name: filename, |
| 247 | saveAs: false, |
| 248 | timeout: 60000, |
| 249 | onload: resolve, |
| 250 | onerror: (error) => reject(new Error(error?.error || error?.details?.current || '下载失败')), |
| 251 | ontimeout: () => reject(new Error('下载超时')), |
| 252 | }); |
| 253 | }); |
| 254 | } |
| 255 | |
| 256 | function formatTimestamp(dateString) { |
| 257 | const date = new Date(dateString); |
| 258 | if (Number.isNaN(date.getTime())) return new Date().toISOString().replace(/[-:TZ.]/g, '').slice(0, 14); |
| 259 | return date.toISOString().replace(/[-:TZ.]/g, '').slice(0, 14); |
| 260 | } |
| 261 | |
| 262 | async function downloadStatus(statusId, onProgress) { |
| 263 | const tweet = await fetchTweet(statusId); |
| 264 | const items = await buildDownloadItems(statusId, tweet); |
| 265 | const history = await GM_getValue(HISTORY_KEY, []); |
| 266 | const results = []; |
| 267 | let succeeded = 0; |
| 268 | |
| 269 | for (let index = 0; index < items.length; index += 1) { |
| 270 | const item = items[index]; |
| 271 | onProgress?.({ index: index + 1, total: items.length, filename: item.filename }); |
| 272 | try { |
| 273 | await downloadFile(item.url, item.filename); |
| 274 | succeeded += 1; |
| 275 | results.push({ filename: item.filename, url: item.url, success: true }); |
| 276 | } catch (error) { |
| 277 | results.push({ filename: item.filename, url: item.url, success: false, error: error.message }); |
| 278 | } |
| 279 | if (index < items.length - 1) await sleep(DOWNLOAD_GAP_MS); |
| 280 | } |
| 281 | |
| 282 | if (succeeded === items.length && !history.includes(statusId)) { |
| 283 | history.push(statusId); |
| 284 | await GM_setValue(HISTORY_KEY, history); |
| 285 | } |
| 286 | return { tweet, results, succeeded, failed: items.length - succeeded }; |
| 287 | } |
| 288 | |
| 289 | const ICON_PATHS = { |
| 290 | download: 'M5 20h14v-2H5v2zm7-18a1 1 0 0 0-1 1v8H7l5 5 5-5h-4V3a1 1 0 0 0-1-1z', |
| 291 | completed: 'M9 16.2 4.8 12l-1.4 1.4L9 19l12-12-1.4-1.4z', |
| 292 | 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', |
| 293 | loading: 'M12 2a10 10 0 1 0 10 10h-2a8 8 0 1 1-8-8V2zm1-1v6l5-3-5-3z', |
| 294 | }; |
| 295 | |
| 296 | function setButtonState(button, state, title) { |
| 297 | button.dataset.state = state; |
| 298 | const label = title || ({ download: '下载此推文媒体', loading: '正在下载…', completed: '下载完成(仍可再次点击)', failed: '下载失败;点击重试' }[state]); |
| 299 | let svg = button.querySelector('svg'); |
| 300 | if (!svg) { |
| 301 | svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); |
| 302 | svg.setAttribute('viewBox', '0 0 24 24'); |
| 303 | button.append(svg); |
| 304 | } |
| 305 | svg.innerHTML = `<path fill="currentColor" d="${ICON_PATHS[state] || ICON_PATHS.download}"></path>`; |
| 306 | button.title = label; |
| 307 | button.setAttribute('aria-label', label); |
| 308 | button.setAttribute('role', 'button'); |
| 309 | if (!button.hasAttribute('tabindex')) button.tabIndex = 0; |
| 310 | button.setAttribute('aria-disabled', state === 'loading' ? 'true' : 'false'); |
| 311 | } |
| 312 | |
| 313 | async function runSingleDownload(button, statusId) { |
| 314 | if (button.dataset.state === 'loading') return; |
| 315 | setButtonState(button, 'loading'); |
| 316 | try { |
| 317 | const result = await downloadStatus(statusId, ({ index, total, filename }) => { |
| 318 | button.title = `正在下载 ${index}/${total}:${filename}`; |
| 319 | }); |
| 320 | if (result.failed) { |
| 321 | const failed = result.results.filter((item) => !item.success).map((item) => `${item.filename}: ${item.error}`).join('\n'); |
| 322 | setButtonState(button, 'failed', failed || '部分媒体下载失败;点击重试'); |
| 323 | } else { |
| 324 | setButtonState(button, 'completed'); |
| 325 | } |
| 326 | } catch (error) { |
| 327 | console.error('[Twitter Media Downloader]', error); |
| 328 | setButtonState(button, 'failed', error.message || '下载失败;点击重试'); |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | function isMediaArticle(article) { |
| 333 | return Boolean(article.querySelector( |
| 334 | 'a[href*="/photo/"], [data-testid="tweetPhoto"], [data-testid="videoPlayer"], video, div[role="progressbar"], div[data-testid="playButton"]' |
| 335 | )); |
| 336 | } |
| 337 | |
| 338 | function addTweetButton(article) { |
| 339 | if (!(article instanceof HTMLElement) || article.dataset.tmdButton === 'true' || !isMediaArticle(article)) return; |
| 340 | const statusLink = article.querySelector('a[href*="/status/"]'); |
| 341 | const actionGroup = article.querySelector('div[role="group"]'); |
| 342 | const statusId = statusLink && getStatusId(statusLink.href); |
| 343 | if (!statusId || !actionGroup) return; |
| 344 | |
| 345 | const originalAction = Array.from(actionGroup.querySelectorAll(':scope > div > div')).pop()?.parentNode; |
| 346 | const button = originalAction?.cloneNode(true) || document.createElement('button'); |
| 347 | button.classList.add('tmd-maintained-button'); |
| 348 | button.removeAttribute('id'); |
| 349 | button.removeAttribute('data-testid'); |
| 350 | button.querySelectorAll('[data-testid]').forEach((node) => node.removeAttribute('data-testid')); |
| 351 | setButtonState(button, 'download'); |
| 352 | const activate = (event) => { |
| 353 | event.preventDefault(); |
| 354 | event.stopPropagation(); |
| 355 | runSingleDownload(button, statusId); |
| 356 | }; |
| 357 | button.addEventListener('click', activate); |
| 358 | button.addEventListener('keydown', (event) => { |
| 359 | if (event.key === 'Enter' || event.key === ' ') activate(event); |
| 360 | }); |
| 361 | actionGroup.append(button); |
| 362 | article.dataset.tmdButton = 'true'; |
| 363 | } |
| 364 | |
| 365 | function queuePostForBatch(statusId) { |
| 366 | const state = batchState; |
| 367 | if (!state?.active || state.queuedPosts.has(statusId) || completedBatchPosts.has(statusId)) return; |
| 368 | state.queuedPosts.add(statusId); |
| 369 | state.postQueue.push(statusId); |
| 370 | } |
| 371 | |
| 372 | function updateBatchPanel() { |
| 373 | if (!panelCount || !panelButton) return; |
| 374 | const eligiblePosts = Array.from(discoveredPosts.keys()).filter((id) => !completedBatchPosts.has(id)); |
| 375 | panelCount.textContent = batchState?.active |
| 376 | ? `已发现 ${discoveredPosts.size} 条推文,已识别 ${batchState.scheduledFiles} 个媒体文件` |
| 377 | : `已发现 ${discoveredPosts.size} 条媒体推文(已加载)`; |
| 378 | if (batchState?.active) { |
| 379 | panelButton.disabled = false; |
| 380 | panelButton.textContent = batchState.paused ? '继续下载' : '暂停下载'; |
| 381 | const queuedPosts = batchState.postQueue.length; |
| 382 | const queuedFiles = batchState.mediaQueue.length; |
| 383 | const running = batchState.currentMedia ? `;当前文件:${batchState.currentMedia.filename}` : batchState.currentPost ? `;正在读取推文 ${batchState.currentPost}` : ''; |
| 384 | const pauseLabel = batchState.paused && batchState.currentMedia ? '正在暂停(当前文件完成后停止)' : batchState.paused ? '已暂停' : '下载中'; |
| 385 | panelStatus.textContent = `${pauseLabel}:待读取推文 ${queuedPosts} 条,待下载媒体 ${queuedFiles} 个,成功 ${batchState.succeeded},失败 ${batchState.failed}${running}`; |
| 386 | } else { |
| 387 | panelButton.disabled = eligiblePosts.length === 0; |
| 388 | panelButton.textContent = eligiblePosts.length |
| 389 | ? '下载已加载媒体' |
| 390 | : discoveredPosts.size ? '已下载当前媒体' : '等待媒体加载'; |
| 391 | if (panelStatus && !batchState?.finished) panelStatus.textContent = '不会自动滚动页面;滚动加载更多后会继续收集。'; |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | function collectLoadedMediaPosts() { |
| 396 | const anchors = document.querySelectorAll('main a[href*="/status/"]'); |
| 397 | for (const anchor of anchors) { |
| 398 | const href = anchor.href || ''; |
| 399 | if (!/\/status\/\d+\/(?:photo|video)\/\d+/i.test(href)) continue; |
| 400 | const statusId = getStatusId(href); |
| 401 | if (statusId && !discoveredPosts.has(statusId)) { |
| 402 | discoveredPosts.set(statusId, true); |
| 403 | queuePostForBatch(statusId); |
| 404 | } |
| 405 | } |
| 406 | updateBatchPanel(); |
| 407 | return Array.from(discoveredPosts.keys()); |
| 408 | } |
| 409 | |
| 410 | function createBatchPanel() { |
| 411 | if (!/\/media\/?$/.test(location.pathname) || document.getElementById(PANEL_ID)) return; |
| 412 | const panel = document.createElement('section'); |
| 413 | panel.id = PANEL_ID; |
| 414 | panel.innerHTML = ` |
| 415 | <header><strong>X 媒体批量下载</strong><button type="button" class="tmd-collapse" aria-label="收起">−</button></header> |
| 416 | <div class="tmd-panel-body"> |
| 417 | <div class="tmd-batch-count">正在扫描已加载媒体…</div> |
| 418 | <button type="button" class="tmd-batch-download" disabled>下载已加载媒体</button> |
| 419 | <div class="tmd-batch-status" role="status">不会自动滚动页面;滚动加载更多后会继续收集。</div> |
| 420 | </div>`; |
| 421 | document.body.append(panel); |
| 422 | panelCount = panel.querySelector('.tmd-batch-count'); |
| 423 | panelStatus = panel.querySelector('.tmd-batch-status'); |
| 424 | panelButton = panel.querySelector('.tmd-batch-download'); |
| 425 | panel.querySelector('.tmd-collapse').addEventListener('click', () => { |
| 426 | panel.classList.toggle('collapsed'); |
| 427 | panel.querySelector('.tmd-collapse').textContent = panel.classList.contains('collapsed') ? '+' : '−'; |
| 428 | }); |
| 429 | panelButton.addEventListener('click', handleBatchButton); |
| 430 | collectLoadedMediaPosts(); |
| 431 | } |
| 432 | |
| 433 | function safeText(value) { |
| 434 | return String(value || '').replace(/[\r\n\t]+/g, ' ').trim(); |
| 435 | } |
| 436 | |
| 437 | function batchFolderName() { |
| 438 | const handle = location.pathname.split('/').filter(Boolean)[0] || 'X'; |
| 439 | const runId = Math.random().toString(36).slice(2, 6); |
| 440 | return sanitizeFilename(`${handle}_media_${formatTimestamp(new Date().toISOString())}_${runId}`); |
| 441 | } |
| 442 | |
| 443 | function createBatchInfoBlob(state) { |
| 444 | const lines = [ |
| 445 | 'Twitter/X Media Downloader — batch report', |
| 446 | `Profile: ${location.origin}/${state.handle}/media`, |
| 447 | `Started: ${state.startedAt}`, |
| 448 | `Finished: ${new Date().toLocaleString()}`, |
| 449 | `Posts initially queued: ${state.discoveredCountAtStart} (newly discovered posts during the run are included)`, |
| 450 | `Files succeeded: ${state.succeeded}`, |
| 451 | `Files failed: ${state.failed}`, |
| 452 | '', |
| 453 | 'Results:', |
| 454 | ]; |
| 455 | state.results.forEach((item) => { |
| 456 | lines.push(`- ${item.success ? 'SUCCESS' : 'FAILED'}: ${safeText(item.filename || item.statusId)}`); |
| 457 | if (item.statusId) lines.push(` Post: https://x.com/${state.handle}/status/${item.statusId}`); |
| 458 | if (item.url) lines.push(` Media URL: ${item.url}`); |
| 459 | if (item.error) lines.push(` Error: ${safeText(item.error)}`); |
| 460 | }); |
| 461 | return new Blob([`\uFEFF${lines.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }); |
| 462 | } |
| 463 | |
| 464 | async function startBatchDownload() { |
| 465 | collectLoadedMediaPosts(); |
| 466 | const eligible = Array.from(discoveredPosts.keys()).filter((id) => !completedBatchPosts.has(id)); |
| 467 | if (!eligible.length) return; |
| 468 | const handle = location.pathname.split('/').filter(Boolean)[0] || 'X'; |
| 469 | batchState = { |
| 470 | active: true, |
| 471 | paused: false, |
| 472 | pumping: false, |
| 473 | handle, |
| 474 | folder: batchFolderName(), |
| 475 | startedAt: new Date().toLocaleString(), |
| 476 | discoveredCountAtStart: eligible.length, |
| 477 | postQueue: [], |
| 478 | queuedPosts: new Set(), |
| 479 | mediaQueue: [], |
| 480 | queuedMedia: new Set(), |
| 481 | postProgress: new Map(), |
| 482 | currentPost: '', |
| 483 | currentMedia: null, |
| 484 | succeeded: 0, |
| 485 | failed: 0, |
| 486 | scheduledFiles: 0, |
| 487 | results: [], |
| 488 | finished: false, |
| 489 | }; |
| 490 | eligible.forEach(queuePostForBatch); |
| 491 | updateBatchPanel(); |
| 492 | void pumpBatch(batchState); |
| 493 | } |
| 494 | |
| 495 | function handleBatchButton() { |
| 496 | if (!batchState?.active) { |
| 497 | void startBatchDownload(); |
| 498 | return; |
| 499 | } |
| 500 | if (!batchState.paused) { |
| 501 | batchState.paused = true; |
| 502 | panelStatus.textContent = batchState.currentMedia |
| 503 | ? `正在暂停:当前文件完成后暂停,后续文件不会启动。` |
| 504 | : '已暂停;继续后会处理剩余媒体及暂停期间新发现的推文。'; |
| 505 | updateBatchPanel(); |
| 506 | return; |
| 507 | } |
| 508 | batchState.paused = false; |
| 509 | updateBatchPanel(); |
| 510 | void pumpBatch(batchState); |
| 511 | } |
| 512 | |
| 513 | async function finishBatch(state) { |
| 514 | if (state.finished) return; |
| 515 | state.finished = true; |
| 516 | try { |
| 517 | await downloadFile(createBatchInfoBlob(state), `${state.folder}/info.txt`); |
| 518 | state.infoSaved = true; |
| 519 | } catch (error) { |
| 520 | state.infoSaved = false; |
| 521 | console.warn('[Twitter Media Downloader] info.txt download failed', error); |
| 522 | } |
| 523 | if (batchState === state) { |
| 524 | panelStatus.textContent = `完成:成功 ${state.succeeded} 个媒体,失败 ${state.failed} 个;${state.infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`; |
| 525 | updateBatchPanel(); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | async function pumpBatch(state) { |
| 530 | if (!state?.active || state.paused || state.pumping) return; |
| 531 | state.pumping = true; |
| 532 | try { |
| 533 | while (state.active && !state.paused) { |
| 534 | if (state.mediaQueue.length) { |
| 535 | const item = state.mediaQueue.shift(); |
| 536 | state.currentMedia = item; |
| 537 | updateBatchPanel(); |
| 538 | let success = false; |
| 539 | let errorMessage = ''; |
| 540 | try { |
| 541 | await downloadFile(item.url, `${state.folder}/${item.filename}`); |
| 542 | success = true; |
| 543 | state.succeeded += 1; |
| 544 | } catch (error) { |
| 545 | errorMessage = error.message || '下载失败'; |
| 546 | state.failed += 1; |
| 547 | } |
| 548 | state.results.push({ statusId: item.statusId, filename: item.filename, url: item.url, success, error: errorMessage }); |
| 549 | const progress = state.postProgress.get(item.statusId); |
| 550 | if (progress) { |
| 551 | progress.remaining -= 1; |
| 552 | if (!success) progress.failed = true; |
| 553 | if (progress.remaining === 0 && !progress.failed) completedBatchPosts.add(item.statusId); |
| 554 | } |
| 555 | state.currentMedia = null; |
| 556 | updateBatchPanel(); |
| 557 | await sleep(DOWNLOAD_GAP_MS); |
| 558 | continue; |
| 559 | } |
| 560 | |
| 561 | if (state.postQueue.length) { |
| 562 | const statusId = state.postQueue.shift(); |
| 563 | state.currentPost = statusId; |
| 564 | updateBatchPanel(); |
| 565 | try { |
| 566 | const tweet = await fetchTweet(statusId); |
| 567 | const items = await buildDownloadItems(statusId, tweet); |
| 568 | const freshItems = items.filter((item) => { |
| 569 | if (state.queuedMedia.has(item.url)) return false; |
| 570 | state.queuedMedia.add(item.url); |
| 571 | return true; |
| 572 | }); |
| 573 | if (!freshItems.length) { |
| 574 | completedBatchPosts.add(statusId); |
| 575 | state.results.push({ statusId, filename: '', success: true, error: '重复媒体,已跳过' }); |
| 576 | } else { |
| 577 | state.postProgress.set(statusId, { remaining: freshItems.length, failed: false }); |
| 578 | state.scheduledFiles += freshItems.length; |
| 579 | state.mediaQueue.push(...freshItems); |
| 580 | } |
| 581 | } catch (error) { |
| 582 | state.failed += 1; |
| 583 | state.results.push({ statusId, filename: '', success: false, error: error.message || '读取推文失败' }); |
| 584 | console.warn('[Twitter Media Downloader] batch post failed', statusId, error); |
| 585 | } |
| 586 | state.currentPost = ''; |
| 587 | updateBatchPanel(); |
| 588 | continue; |
| 589 | } |
| 590 | |
| 591 | state.active = false; |
| 592 | } |
| 593 | } finally { |
| 594 | state.pumping = false; |
| 595 | if (state.active && !state.paused && (state.postQueue.length || state.mediaQueue.length)) { |
| 596 | void pumpBatch(state); |
| 597 | } else if (!state.active) { |
| 598 | await finishBatch(state); |
| 599 | } |
| 600 | updateBatchPanel(); |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | function installStyles() { |
| 605 | if (document.getElementById('tmd-maintained-style')) return; |
| 606 | const style = document.createElement('style'); |
| 607 | style.id = 'tmd-maintained-style'; |
| 608 | style.textContent = ` |
| 609 | #${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:285px;color:#202124;background:var(--background-primary,#fff); |
| 610 | border:1px solid #d9dde3;border-radius:12px;box-shadow:0 4px 18px #0002;font:14px/1.5 system-ui,sans-serif} |
| 611 | #${PANEL_ID} header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border-bottom:1px solid #eee} |
| 612 | #${PANEL_ID} button{font:inherit;cursor:pointer}#${PANEL_ID} .tmd-collapse{border:0;background:transparent;font-size:20px;color:#666} |
| 613 | #${PANEL_ID} .tmd-panel-body{padding:11px 12px 12px}#${PANEL_ID} .tmd-batch-count{margin-bottom:9px;color:#536471} |
| 614 | #${PANEL_ID} .tmd-batch-download{width:100%;padding:8px;border:0;border-radius:999px;background:#1d9bf0;color:white;font-weight:700} |
| 615 | #${PANEL_ID} .tmd-batch-download:hover{background:#1a8cd8}#${PANEL_ID} .tmd-batch-download:disabled{opacity:.55;cursor:default} |
| 616 | #${PANEL_ID} .tmd-batch-status{min-height:20px;margin-top:8px;color:#536471;font-size:12px} |
| 617 | #${PANEL_ID}.collapsed{width:auto}#${PANEL_ID}.collapsed .tmd-panel-body{display:none} |
| 618 | .tmd-maintained-button{display:inline-flex!important;align-items:center;justify-content:center;width:34px;height:34px;margin-left:4px;padding:0; |
| 619 | color:rgb(83,100,113);background:transparent;border:0;border-radius:999px;cursor:pointer} |
| 620 | .tmd-maintained-button:hover{color:rgb(29,155,240);background:rgba(29,155,240,.1)} |
| 621 | .tmd-maintained-button svg{display:block;width:18px;height:18px;fill:currentColor} |
| 622 | .tmd-maintained-button[data-state="completed"]{color:rgb(29,155,240)} |
| 623 | .tmd-maintained-button[data-state="failed"]{color:rgb(244,33,46)} |
| 624 | .tmd-maintained-button[data-state="loading"] svg{animation:tmd-spin 1s linear infinite} |
| 625 | @keyframes tmd-spin{to{transform:rotate(360deg)}}`; |
| 626 | document.head.append(style); |
| 627 | } |
| 628 | |
| 629 | function installSettings() { |
| 630 | if (typeof GM_registerMenuCommand !== 'function') return; |
| 631 | GM_registerMenuCommand('下载设置:文件名格式', async () => { |
| 632 | const current = await GM_getValue(FILENAME_KEY, DEFAULT_FILENAME); |
| 633 | const next = window.prompt('文件名格式,可用 {user-name} {user-id} {date-time} {status-id} {file-type} {file-name}', current); |
| 634 | if (next !== null && next.trim()) await GM_setValue(FILENAME_KEY, next.trim()); |
| 635 | }); |
| 636 | GM_registerMenuCommand(`Twitter Media Downloader ${VERSION}`, () => { |
| 637 | window.alert('AMANE 原脚本的社区维护版。支持单条下载及媒体页已加载内容批量下载。'); |
| 638 | }); |
| 639 | } |
| 640 | |
| 641 | function scanPage() { |
| 642 | const isMediaPage = /\/media\/?$/.test(location.pathname); |
| 643 | const panel = document.getElementById(PANEL_ID); |
| 644 | if (!isMediaPage && panel && !batchState?.active) { |
| 645 | panel.remove(); |
| 646 | panelCount = null; |
| 647 | panelStatus = null; |
| 648 | panelButton = null; |
| 649 | discoveredPosts.clear(); |
| 650 | } |
| 651 | document.querySelectorAll('article').forEach(addTweetButton); |
| 652 | if (isMediaPage) { |
| 653 | if (!document.getElementById(PANEL_ID)) createBatchPanel(); |
| 654 | collectLoadedMediaPosts(); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | function start() { |
| 659 | installStyles(); |
| 660 | installSettings(); |
| 661 | createBatchPanel(); |
| 662 | scanPage(); |
| 663 | let scanTimer; |
| 664 | const observer = new MutationObserver(() => { |
| 665 | window.clearTimeout(scanTimer); |
| 666 | scanTimer = window.setTimeout(() => { |
| 667 | scanPage(); |
| 668 | if (!document.getElementById(PANEL_ID)) createBatchPanel(); |
| 669 | }, 120); |
| 670 | }); |
| 671 | observer.observe(document.body, { childList: true, subtree: true }); |
| 672 | } |
| 673 | |
| 674 | if (document.body) start(); |
| 675 | else document.addEventListener('DOMContentLoaded', start, { once: true }); |
| 676 | })(); |
| 677 |