// ==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 = `