The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(meta): 修复 Facebook/Instagram 视频下载
XiaoYouChRc535ba55dca8
diff --git a/app/models/pack.py b/app/models/pack.pyindex 09b1ff64..32ccc7e5 100644--- a/app/models/pack.py+++ b/app/models/pack.py@@ -150,8 +150,8 @@ class BinaryRuntime:def isNewer(self, installed: str, latest: str) -> bool:if not installed or not latest:return False- v1 = QVersionNumber.fromString(installed.lstrip("vV"))- v2 = QVersionNumber.fromString(latest.lstrip("vV"))+ v1 = QVersionNumber.fromString(installed.lstrip("vVn"))+ v2 = QVersionNumber.fromString(latest.lstrip("vVn"))return v2 > v1def delete(self) -> None:diff --git a/browser_extension/app/src/background.ts b/browser_extension/app/src/background.tsindex b823b3b1..a9bea581 100644--- a/browser_extension/app/src/background.ts+++ b/browser_extension/app/src/background.ts@@ -628,6 +628,12 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {return;}+ if (message.type === "request_tab_video_resources") {+ const tabId = sender.tab?.id;+ sendResponse({ urls: tabId ? resourceBridge.videoResourcesByTab(tabId) : [] });+ return true;+ }+if (message.type === "page_poster" && message.posterUrl && sender.tab?.id) {resourceBridge.enrichTabPoster(sender.tab.id, String(message.posterUrl));return;diff --git a/browser_extension/app/src/background/resource-bridge.ts b/browser_extension/app/src/background/resource-bridge.tsindex 89ad4846..de471c3e 100644--- a/browser_extension/app/src/background/resource-bridge.ts+++ b/browser_extension/app/src/background/resource-bridge.ts@@ -529,7 +529,9 @@ export function createResourceBridge(options: {}const snapshot = cache.headerSnapshotByUrl(url);- const headers: Record<string, string> = { ...(snapshot?.headers ?? {}) };+ const headers: Record<string, string> = {+ ...(snapshot?.headers ?? cache.headersForPage(url)),+ };const referer = headers.referer || fallbackPageUrl;if (referer) { headers.referer = referer; }const synthesized: Resource = {@@ -721,6 +723,12 @@ export function createResourceBridge(options: {cache.setHeaderSnapshot(details.url, headers, details.tabId > 0 ? details.tabId : lastActiveTabId, supportsRange);}+ function videoResourcesByTab(tabId: number): Array<{ url: string; mime: string; capturedAt: number }> {+ return cache.resourcesForTab(tabId)+ .filter((r) => isCatCatchMedia(fileExtension(filenameFromUrl(r.url)), r.mime))+ .map((r) => ({ url: r.url, mime: r.mime, capturedAt: r.capturedAt }));+ }+return {buildPopupStateData,captureNetworkResource,@@ -743,5 +751,6 @@ export function createResourceBridge(options: {mergeResources,sendResource,setLastActiveTab,+ videoResourcesByTab,};}diff --git a/browser_extension/app/src/page-media/attribution/attribution.ts b/browser_extension/app/src/page-media/attribution/attribution.tsindex e3a0c9e4..b2bb5571 100644--- a/browser_extension/app/src/page-media/attribution/attribution.ts+++ b/browser_extension/app/src/page-media/attribution/attribution.ts@@ -1,6 +1,6 @@import {isCatCatchMedia} from "../../shared/cat-catch";import {fileExtension, filenameFromUrl, mimeFromUrl} from "../../shared/utils";-import {instagramAssetId, isInstagramCdnUrl} from "../resolution/url-classify";+import {fbCdnDuration, instagramAssetId, isInstagramCdnUrl, urlIdHints} from "../resolution/url-classify";import {AttributionLedger} from "./attribution-ledger";import {selectMediaForPage} from "../resolution/strategy";@@ -17,7 +17,6 @@ import type {} from "../types";const LOG_PREFIX = "[GD Media]";-const VIDEO_ID_QUERY_KEYS = ["__vid", "v", "modal_id", "video_id", "id", "bvid", "aid"];// Budget from the FIRST Pending — not per re-eval.const WAIT_FOR_TIMEOUT_MS = 8000;// Matches the download-button status toast — auto-reset and toast fade on the same clock.@@ -29,38 +28,6 @@ type ResolveStateListener = (state: VideoSessionState, reason: string) => void;const FETCH_BUFFER_CORRELATION_MS = 2500;const RECENT_FETCHES_CAP = 16;-function looksLikeVideoIdSegment(segment: string): boolean {- if (segment.length < 10) { return false; }- if (!/^[A-Za-z0-9_-]+$/.test(segment)) { return false; }- let longestRun = 0;- for (const run of segment.split(/[-_]+/)) {- if (run.length > longestRun) { longestRun = run.length; }- }- return longestRun >= 10;-}--function urlIdHints(url: string): Set<string> {- const result = new Set<string>();- let parsed: URL;- try {- parsed = new URL(url);- } catch {- return result;- }- for (const segment of parsed.pathname.split("/")) {- if (looksLikeVideoIdSegment(segment)) { result.add(segment); }- }- for (const key of VIDEO_ID_QUERY_KEYS) {- const value = parsed.searchParams.get(key);- if (value && value.length >= 4) { result.add(`${key}=${value}`); }- }- if (isInstagramCdnUrl(url)) {- const assetId = instagramAssetId(url);- if (assetId) { result.add(`xpv_asset_id=${assetId}`); }- }- return result;-}-function toFormKind(mimeTypes: Set<string>): VideoSessionFormKind {if (mimeTypes.size === 0) { return "unknown"; }@@ -169,14 +136,14 @@ class MediaAttribution {element.addEventListener("emptied", () => this.onMediaEmptied(element));const initialSrc = element.currentSrc || element.src || "";- if (initialSrc) {+ if (initialSrc || element.srcObject) {this.openSessionFor(element);}}private onMediaLoadStart(element: HTMLMediaElement): void {const src = element.currentSrc || element.src || "";- if (!src) { return; }+ if (!src && !element.srcObject) { return; }const existing = this.sessionsByElement.get(element);if (!existing) {this.openSessionFor(element);@@ -192,7 +159,7 @@ class MediaAttribution {let session = this.sessionsByElement.get(element);if (!session) {const src = element.currentSrc || element.src || "";- if (!src) { return; }+ if (!src && !element.srcObject) { return; }session = this.openSessionFor(element);}this.transition(session, "armed", "loadedmetadata");@@ -488,8 +455,6 @@ class MediaAttribution {}}- // Provisional — recordAttribution will refuse to add prefetch URLs to- // lastBoundSession.idHints so they don't poison tier-1 for the next session.if (this.lastBoundSession && this.sessionsById.has(this.lastBoundSession.id)) {return { session: this.lastBoundSession, tier: 2 };}@@ -582,6 +547,11 @@ class MediaAttribution {if (!session) {return { kind: "refused", message: chrome.i18n.getMessage("errorMediaSourceUnrecognized") };}++ if (session.attributedUrls.size === 0) {+ await this.fetchUrlsFromBackground(session);+ }+const pageUrl = new URL(location.href);const findUrlsByIdHint: FindUrlsByIdHint = (idHint) => this.lookupByIdHint(idHint);@@ -650,6 +620,56 @@ class MediaAttribution {return matches;}+ // Worker-based MediaSourceHandle bypasses the MSE probe — the probe only patches+ // main-thread MediaSource/fetch/XHR. Combine two fallback sources:+ // 1. Background's webRequest captures (URLs the player already fetched)+ // 2. Page's embedded JSON data (all quality levels from the DASH manifest)+ private async fetchUrlsFromBackground(session: VideoSession): Promise<void> {+ const element = session.elementRef.deref();+ const videoDuration = element instanceof HTMLVideoElement && Number.isFinite(element.duration) ? element.duration : 0;+ const now = performance.now();++ const addUrl = (url: string, mime: string, capturedAt: number): void => {+ if (session.attributedUrls.has(url)) { return; }+ const urlDuration = fbCdnDuration(url);+ if (videoDuration > 0 && urlDuration > 0 && Math.abs(videoDuration - urlDuration) > 2) { return; }+ session.attributedUrls.set(url, { contentType: mime, capturedAt, tier: 0, lockedByMse: false });+ };++ try {+ const response = await chrome.runtime.sendMessage({ type: "request_tab_video_resources" });+ if (Array.isArray(response?.urls)) {+ for (const entry of response.urls) { addUrl(entry.url, entry.mime || "", entry.capturedAt || now); }+ }+ } catch { /* Extension context invalidated. */ }++ // Page's embedded JSON often contains higher-quality DASH representation URLs that+ // the adaptive player hasn't fetched yet.+ for (const url of this.parseFbCdnUrlsFromPage()) { addUrl(url, "", now); }++ if (session.attributedUrls.size > 0) {+ console.log(`${LOG_PREFIX} ${session.id} populated ${session.attributedUrls.size} url(s) from background`);+ }+ }++ private parseFbCdnUrlsFromPage(): string[] {+ const results: string[] = [];+ for (const script of document.querySelectorAll<HTMLScriptElement>('script[type="application/json"]')) {+ const text = script.textContent;+ if (!text || !text.includes("fbcdn")) { continue; }+ const regex = /https?:(?:\\\/){2}[^"]*\.fbcdn\.net[^"]*\.mp4\?(?:[^"\\]|\\u[0-9a-fA-F]{4}|\\[/\\])*/g;+ let m;+ while ((m = regex.exec(text)) !== null) {+ const url = m[0]+ .replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))+ .replace(/\\\//g, "/")+ .replace(/&/g, "&");+ if (isInstagramCdnUrl(url)) { results.push(url); }+ }+ }+ return results;+ }+private applyResolutionToState(session: VideoSession, resolution: Resolution): void {if (resolution.kind === "selection") {this.transition(session, "resolving", "selection-dispatch");diff --git a/browser_extension/app/src/page-media/resolution/strategies/instagram.ts b/browser_extension/app/src/page-media/resolution/strategies/instagram.tsindex 18051382..8b3468d9 100644--- a/browser_extension/app/src/page-media/resolution/strategies/instagram.ts+++ b/browser_extension/app/src/page-media/resolution/strategies/instagram.ts@@ -1,13 +1,55 @@-import {instagramAssetId, instagramKindOf, isInstagramCdnUrl, stripRangeParams} from "../url-classify";-import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";-import type {FindUrlsByIdHint, ResolveContext} from "../strategy";+import {fbCdnBitrate, instagramAssetId, instagramKindOf, isInstagramCdnUrl, stripRangeParams} from "../url-classify";+import {postBindAttributedUrls} from "../strategy";+import type {AttributedUrlView, FindUrlsByIdHint, ResolveContext} from "../strategy";import type {Resolution} from "../../types";-export function selectInstagram(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {+function selectBestPair(+ urls: ReadonlyArray<AttributedUrlView>,+): { video: string; audio: string } | null {+ let bestVideo: { url: string; bitrate: number } | null = null;+ let bestAudio: { url: string; bitrate: number } | null = null;+ for (const entry of urls) {+ const kind = instagramKindOf(entry.url);+ const bitrate = fbCdnBitrate(entry.url);+ if (kind === "video" && (!bestVideo || bitrate > bestVideo.bitrate)) {+ bestVideo = { url: entry.url, bitrate };+ } else if (kind === "audio" && (!bestAudio || bitrate > bestAudio.bitrate)) {+ bestAudio = { url: entry.url, bitrate };+ }+ }+ return bestVideo && bestAudio ? { video: bestVideo.url, audio: bestAudio.url } : null;+}++// Group by xpv_asset_id, try each group by segment count (the actively playing video+// has the most fetched segments), then by highest video bitrate as tiebreaker.+function matchPairByAssetId(+ post: ReadonlyArray<AttributedUrlView>,+): { video: string; audio: string } | null {+ const byAsset = new Map<string, AttributedUrlView[]>();+ for (const entry of post) {+ const id = instagramAssetId(entry.url);+ if (!id) { continue; }+ let group = byAsset.get(id);+ if (!group) { group = []; byAsset.set(id, group); }+ group.push(entry);+ }+ if (byAsset.size <= 1) { return selectBestPair(post); }+ const maxVideoBitrate = (urls: ReadonlyArray<AttributedUrlView>) =>+ urls.reduce((max, e) => Math.max(max, instagramKindOf(e.url) === "video" ? fbCdnBitrate(e.url) : 0), 0);+ const groups = [...byAsset.values()].sort((a, b) =>+ b.length - a.length || maxVideoBitrate(b) - maxVideoBitrate(a));+ for (const group of groups) {+ const pair = selectBestPair(group);+ if (pair) { return pair; }+ }+ return null;+}++export function selectMeta(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {const post = postBindAttributedUrls(ctx.clicked).filter((r) => isInstagramCdnUrl(r.url));if (ctx.clicked.formKind === "dash") {- const pair = selectMergePair(post, instagramKindOf) ?? findPairByAssetId(post, findUrlsByIdHint);+ const pair = matchPairByAssetId(post) ?? findPairByAssetId(post, findUrlsByIdHint);if (pair) {return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };}@@ -17,7 +59,7 @@ export function selectInstagram(ctx: ResolveContext, findUrlsByIdHint: FindUrlsBif (post.length === 0) {return { kind: "pending", reason: chrome.i18n.getMessage("waitingForVideoResource") };}- const pair = selectMergePair(post, instagramKindOf);+ const pair = matchPairByAssetId(post);if (pair) {return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };}@@ -38,7 +80,5 @@ function findPairByAssetId(}if (!assetId) { return null; }const matches = findUrlsByIdHint(`xpv_asset_id=${assetId}`);- const video = newestMatching(matches, (url) => instagramKindOf(url) === "video");- const audio = newestMatching(matches, (url) => instagramKindOf(url) === "audio");- return video && audio ? { video, audio } : null;+ return selectBestPair(matches);}diff --git a/browser_extension/app/src/page-media/resolution/strategy.ts b/browser_extension/app/src/page-media/resolution/strategy.tsindex e0091192..d3321074 100644--- a/browser_extension/app/src/page-media/resolution/strategy.ts+++ b/browser_extension/app/src/page-media/resolution/strategy.ts@@ -1,6 +1,6 @@import {selectDouyin} from "./strategies/douyin";import {selectGeneric} from "./strategies/generic";-import {selectInstagram} from "./strategies/instagram";+import {selectMeta} from "./strategies/instagram";import {selectX} from "./strategies/x";import {selectYouTube} from "./strategies/youtube";import type {Resolution, VideoSessionFormKind} from "../types";@@ -45,8 +45,10 @@ export function selectMediaForPage(ctx: ResolveContext, findUrlsByIdHint: FindUrif (host === "www.douyin.com" || host.endsWith(".douyin.com")) {return selectDouyin(ctx, findUrlsByIdHint);}- if (host === "www.instagram.com" || host.endsWith(".instagram.com")) {- return selectInstagram(ctx, findUrlsByIdHint);+ // Instagram and Facebook share the same CDN format (fbcdn.net, efg/vencode_tag/xpv_asset_id).+ if (host === "www.instagram.com" || host.endsWith(".instagram.com")+ || host === "www.facebook.com" || host.endsWith(".facebook.com")) {+ return selectMeta(ctx, findUrlsByIdHint);}if (host === "youtube.com" || host.endsWith(".youtube.com") || host === "youtu.be") {return selectYouTube(ctx);diff --git a/browser_extension/app/src/page-media/resolution/url-classify.ts b/browser_extension/app/src/page-media/resolution/url-classify.tsindex 782ba62d..cbe5904b 100644--- a/browser_extension/app/src/page-media/resolution/url-classify.ts+++ b/browser_extension/app/src/page-media/resolution/url-classify.ts@@ -83,6 +83,20 @@ export function instagramAssetId(url: string): string {return "";}+export function fbCdnBitrate(url: string): number {+ const efg = parseEfg(url);+ if (!efg || typeof efg !== "object") { return 0; }+ const br = (efg as Record<string, unknown>).bitrate;+ return typeof br === "number" && br > 0 ? br : 0;+}++export function fbCdnDuration(url: string): number {+ const efg = parseEfg(url);+ if (!efg || typeof efg !== "object") { return 0; }+ const dur = (efg as Record<string, unknown>).duration_s;+ return typeof dur === "number" && dur > 0 ? dur : 0;+}+export function instagramKindOf(url: string): "video" | "audio" | "" {const tag = instagramVencodeTag(url);if (!tag) { return ""; }@@ -91,6 +105,40 @@ export function instagramKindOf(url: string): "video" | "audio" | "" {return "";}+const VIDEO_ID_QUERY_KEYS = ["__vid", "v", "modal_id", "video_id", "id", "bvid", "aid"];++function looksLikeVideoIdSegment(segment: string): boolean {+ if (segment.length < 10) { return false; }+ if (!/^[A-Za-z0-9_-]+$/.test(segment)) { return false; }+ let longestRun = 0;+ for (const run of segment.split(/[-_]+/)) {+ if (run.length > longestRun) { longestRun = run.length; }+ }+ return longestRun >= 10;+}++export function urlIdHints(url: string): Set<string> {+ const result = new Set<string>();+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return result;+ }+ for (const segment of parsed.pathname.split("/")) {+ if (looksLikeVideoIdSegment(segment)) { result.add(segment); }+ }+ for (const key of VIDEO_ID_QUERY_KEYS) {+ const value = parsed.searchParams.get(key);+ if (value && value.length >= 4) { result.add(`${key}=${value}`); }+ }+ if (isInstagramCdnUrl(url)) {+ const assetId = instagramAssetId(url);+ if (assetId) { result.add(`xpv_asset_id=${assetId}`); }+ }+ return result;+}+export function classifyTrackRole(url: string, contentType: string): TrackRole {const douyin = douyinKindOf(url);if (douyin === "muxed") { return "muxed"; }diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 2e734e3c..a1357c47 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -89,6 +89,11 @@ class FFmpegRuntime(BinaryRuntime):path = self.path()if not path:return ""+ versionFile = Path(ffmpegConfig.installFolder.value) / "VERSION"+ if versionFile.is_file():+ tag = versionFile.read_text().strip()+ if tag:+ return tagprocess = await asyncio.create_subprocess_exec(path, "-version",stdin=asyncio.subprocess.DEVNULL,diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 64e24114..817ea911 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -61,7 +61,8 @@ class HttpParser(TaskParser):name = toSafeFilename(options.name, fallback=f"file_{time_ns()}")fileSize = options.size if options.size > 0 else SpecialFileSize.UNKNOWNcanUseRangeRequests = options.canUseRangeRequests- else:++ if fileSize == SpecialFileSize.UNKNOWN:emulation = toEmulation(options.clientProfile or cfg.clientProfile.value,options.sourceUserAgent,@@ -143,44 +144,46 @@ class HttpParser(TaskParser):if fileSize == SpecialFileSize.UNKNOWN and fbStatus == 416:fileSize = rangeTotal(fbHeaders)- cd = responseHeaders.get("content-disposition", "")- if cd:- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- paramDict = {k.lower(): v for k, v in params}- name = unquote(collapse_rfc2231_value(- paramDict.get("filename") or paramDict.get("filename*") or ""- )).strip("\"' ")-- if not name and "content-location" in responseHeaders:- cl = responseHeaders["content-location"]- name = unquote(urlparse(cl).path.split("/")[-1])-- if not name:- queryParams = parse_qs(urlparse(finalUrl).query)- rcd = queryParams.get("response-content-disposition", [""])[0]- if "filename=" in rcd.lower():- m = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)- if m:- name = unquote(m.group(1)).strip("\"' ")-- if not name:- path = urlparse(finalUrl).path- if path and "/" in path:- cleanPath = path.split(";")[0]- name = unquote(cleanPath.split("/")[-1])-- contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()- standardExt = guess_extension(contentType) if contentType else ""- standardExt = standardExt or ""-if not name:- name = f"file_{time_ns()}{standardExt}"- elif "." not in name and standardExt:- name = f"{name}{standardExt}"+ cd = responseHeaders.get("content-disposition", "")+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {k.lower(): v for k, v in params}+ name = unquote(collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ )).strip("\"' ")++ if not name and "content-location" in responseHeaders:+ cl = responseHeaders["content-location"]+ name = unquote(urlparse(cl).path.split("/")[-1])++ if not name:+ queryParams = parse_qs(urlparse(finalUrl).query)+ rcd = queryParams.get("response-content-disposition", [""])[0]+ if "filename=" in rcd.lower():+ m = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)+ if m:+ name = unquote(m.group(1)).strip("\"' ")++ if not name:+ path = urlparse(finalUrl).path+ if path and "/" in path:+ cleanPath = path.split(";")[0]+ name = unquote(cleanPath.split("/")[-1])++ contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()+ standardExt = guess_extension(contentType) if contentType else ""+ standardExt = standardExt or ""++ if not name:+ name = f"file_{time_ns()}{standardExt}"+ elif "." not in name and standardExt:+ name = f"{name}{standardExt}"++ name = toSafeFilename(name, fallback=f"file_{time_ns()}")- name = toSafeFilename(name, fallback=f"file_{time_ns()}")lastModified = responseHeaders.get("last-modified", "")finally:client.close()