Skip to content

The only downloader you need. 下载器的集大成者。

refactor(extension): 压平策略层为 hostname 分发 + 纯 resolver

XiaoYouChR1dafc53a25b5
diff --git a/browser_extension/app/src/page-media/controller.ts b/browser_extension/app/src/page-media/controller.ts
index 7acabe0a..406b4a53 100644
--- a/browser_extension/app/src/page-media/controller.ts
+++ b/browser_extension/app/src/page-media/controller.ts
@@ -2,9 +2,9 @@ import {isCatCatchMedia} from "../shared/cat-catch";
import {fileExtension, filenameFromUrl, mimeFromUrl} from "../shared/utils";
import {AttributionLedger} from "./attribution-ledger";
-import {pickStrategy} from "./strategy-registry";
+import {resolveForPage} from "./strategy";
import {isMediaSignal} from "./signals";
-import type {AttributedUrlView, MediaStrategy, SessionSnapshot, ResolveContext, ResolveHints} from "./strategy";
+import type {AttributedUrlView, FindUrlsByIdHint, SessionSnapshot, ResolveContext, ResolveHints} from "./strategy";
import type {
AttributionTier,
MseAttributionSignal,
@@ -76,14 +76,13 @@ function toFormKind(mimeTypes: Set<string>): VideoSessionFormKind {
return hasVideo && hasAudio ? "dash" : "unknown";
}
-// Per-site strategies are extension points; bubbling their exceptions to the overlay
-// would crash the click pipeline.
-function tryResolve(strategy: MediaStrategy, ctx: ResolveContext): Resolution {
+// A per-site resolver bubbling its exception to the overlay would crash the click pipeline.
+function tryResolve(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {
try {
- return strategy.resolve(ctx);
+ return resolveForPage(ctx, findUrlsByIdHint);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`${LOG_PREFIX} strategy "${strategy.id}" threw`, error);
+ console.error(`${LOG_PREFIX} resolver for ${ctx.pageUrl.hostname} threw`, error);
return { kind: "refused", message: `策略异常: ${message}` };
}
}
@@ -548,16 +547,15 @@ class PageMediaController {
return { kind: "refused", message: "未识别媒体来源" };
}
const pageUrl = new URL(location.href);
- const strategy: MediaStrategy = pickStrategy(pageUrl);
+ const findUrlsByIdHint: FindUrlsByIdHint = (idHint) => this.lookupByIdHint(idHint);
const buildCtx = (): ResolveContext => ({
clicked: toSessionSnapshot(session),
pageUrl,
hints,
- findUrlsByIdHint: (idHint) => this.lookupByIdHint(idHint),
});
- const initial = tryResolve(strategy, buildCtx());
+ const initial = tryResolve(buildCtx(), findUrlsByIdHint);
if (initial.kind !== "pending") {
this.applyResolutionToState(session, initial);
return initial;
@@ -584,7 +582,7 @@ class PageMediaController {
finish({ kind: "refused", message: reason });
return;
}
- const next = tryResolve(strategy, buildCtx());
+ const next = tryResolve(buildCtx(), findUrlsByIdHint);
if (next.kind === "pending") {
lastPendingReason = next.reason;
return;
diff --git a/browser_extension/app/src/page-media/strategies/douyin.ts b/browser_extension/app/src/page-media/strategies/douyin.ts
index 1a840c16..5962c368 100644
--- a/browser_extension/app/src/page-media/strategies/douyin.ts
+++ b/browser_extension/app/src/page-media/strategies/douyin.ts
@@ -1,62 +1,54 @@
import {douyinKindOf, hostEndsWith} from "../url-classify";
import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
-import type {MediaStrategy, ResolveContext} from "../strategy";
+import type {FindUrlsByIdHint, ResolveContext} from "../strategy";
import type {Resolution} from "../types";
// Until the next reel's MSE binds and correlation locks the URL, the prefetched URL is
// still provisionally owned by the previous reel's session. modal_id is what survives
// that window.
-export class DouyinStrategy implements MediaStrategy {
- readonly id = "douyin";
+export function resolveDouyin(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {
+ const post = postBindAttributedUrls(ctx.clicked).filter((r) => hostEndsWith(r.url, "douyinvod.com"));
- matches(pageUrl: URL): boolean {
- return pageUrl.hostname === "www.douyin.com" || pageUrl.hostname.endsWith(".douyin.com");
- }
-
- resolve(ctx: ResolveContext): Resolution {
- const post = postBindAttributedUrls(ctx.clicked).filter((r) => hostEndsWith(r.url, "douyinvod.com"));
-
- if (ctx.clicked.formKind === "muxed") {
- const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed") ?? this.findByModalId(ctx, "muxed");
- if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "muxed" } };
- }
- return { kind: "pending", reason: "等待 Douyin 单 MP4 URL" };
- }
-
- if (ctx.clicked.formKind === "dash") {
- const pair = selectMergePair(post, douyinKindOf);
- if (pair) {
- return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
- }
- return { kind: "pending", reason: "等待 Douyin 音视频分轨齐全" };
- }
-
- // formKind unknown — MSE hasn't reported yet.
- if (post.length === 0) {
- const fromModalId = this.findByModalId(ctx, "muxed");
- if (fromModalId) {
- return { kind: "selection", selection: { kind: "single", url: fromModalId, formKind: "unknown" } };
- }
- return { kind: "pending", reason: "等待嗅探到当前视频资源" };
- }
- const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed");
+ if (ctx.clicked.formKind === "muxed") {
+ const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed") ?? findByModalId(ctx, findUrlsByIdHint, "muxed");
if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "unknown" } };
+ return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "muxed" } };
}
+ return { kind: "pending", reason: "等待 Douyin 单 MP4 URL" };
+ }
+
+ if (ctx.clicked.formKind === "dash") {
const pair = selectMergePair(post, douyinKindOf);
if (pair) {
return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
}
- return { kind: "refused", message: "无法判定 Douyin 当前媒体形态,请在资源嗅探页选择" };
+ return { kind: "pending", reason: "等待 Douyin 音视频分轨齐全" };
}
- // Ledger query crosses session boundaries — that's what lets us pick the prefetched
- // URL even when it's still provisionally owned by the previous reel.
- private findByModalId(ctx: ResolveContext, kind: "muxed" | "video" | "audio"): string | undefined {
- const modalId = ctx.pageUrl.searchParams.get("modal_id");
- if (!modalId || modalId.length < 4) { return undefined; }
- const matches = ctx.findUrlsByIdHint(`__vid=${modalId}`);
- return newestMatching(matches, (url) => douyinKindOf(url) === kind);
+ // formKind unknown — MSE hasn't reported yet.
+ if (post.length === 0) {
+ const fromModalId = findByModalId(ctx, findUrlsByIdHint, "muxed");
+ if (fromModalId) {
+ return { kind: "selection", selection: { kind: "single", url: fromModalId, formKind: "unknown" } };
+ }
+ return { kind: "pending", reason: "等待嗅探到当前视频资源" };
+ }
+ const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed");
+ if (muxed) {
+ return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "unknown" } };
}
+ const pair = selectMergePair(post, douyinKindOf);
+ if (pair) {
+ return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
+ }
+ return { kind: "refused", message: "无法判定 Douyin 当前媒体形态,请在资源嗅探页选择" };
+}
+
+// Ledger query crosses session boundaries — that's what lets us pick the prefetched
+// URL even when it's still provisionally owned by the previous reel.
+function findByModalId(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint, kind: "muxed" | "video" | "audio"): string | undefined {
+ const modalId = ctx.pageUrl.searchParams.get("modal_id");
+ if (!modalId || modalId.length < 4) { return undefined; }
+ const matches = findUrlsByIdHint(`__vid=${modalId}`);
+ return newestMatching(matches, (url) => douyinKindOf(url) === kind);
}
diff --git a/browser_extension/app/src/page-media/strategies/generic.ts b/browser_extension/app/src/page-media/strategies/generic.ts
index 6c1acca9..17955f0c 100644
--- a/browser_extension/app/src/page-media/strategies/generic.ts
+++ b/browser_extension/app/src/page-media/strategies/generic.ts
@@ -1,51 +1,43 @@
import {classifyTrackRole, isDashSegmentUrl, isStreamUrl, stripRangeParams} from "../url-classify";
import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
-import type {MediaStrategy, ResolveContext} from "../strategy";
+import type {ResolveContext} from "../strategy";
import type {Resolution} from "../types";
-// Fallback; matches() always true, so it must be registered last.
-export class GenericStrategy implements MediaStrategy {
- readonly id = "generic";
+// Fallback resolver — runs when no per-site resolver matches the hostname.
+export function resolveGeneric(ctx: ResolveContext): Resolution {
+ const post = postBindAttributedUrls(ctx.clicked);
- matches(_pageUrl: URL): boolean {
- return true;
+ const stream = newestMatching(post, isStreamUrl);
+ if (stream) {
+ return { kind: "selection", selection: { kind: "stream", url: stream } };
}
- resolve(ctx: ResolveContext): Resolution {
- const post = postBindAttributedUrls(ctx.clicked);
-
- const stream = newestMatching(post, isStreamUrl);
- if (stream) {
- return { kind: "selection", selection: { kind: "stream", url: stream } };
+ if (ctx.clicked.formKind === "muxed") {
+ const muxed = newestMatching(post, (url) => !isDashSegmentUrl(url));
+ if (muxed) {
+ return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "muxed" } };
}
+ return { kind: "pending", reason: "等待嗅探到当前视频资源" };
+ }
- if (ctx.clicked.formKind === "muxed") {
- const muxed = newestMatching(post, (url) => !isDashSegmentUrl(url));
- if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "muxed" } };
- }
- return { kind: "pending", reason: "等待嗅探到当前视频资源" };
+ if (ctx.clicked.formKind === "dash") {
+ const pair = selectMergePair(post, classifyTrackRole);
+ if (pair) {
+ return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };
}
+ return { kind: "pending", reason: "等待音视频分轨齐全" };
+ }
- if (ctx.clicked.formKind === "dash") {
- const pair = selectMergePair(post, classifyTrackRole);
- if (pair) {
- return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };
- }
+ if (post.length === 0) {
+ return { kind: "pending", reason: "等待嗅探到当前视频资源" };
+ }
+ if (post.length === 1) {
+ const only = post[0];
+ if (isDashSegmentUrl(only.url)) {
+ // The sibling track may still be in flight pre-MSE-ack.
return { kind: "pending", reason: "等待音视频分轨齐全" };
}
-
- if (post.length === 0) {
- return { kind: "pending", reason: "等待嗅探到当前视频资源" };
- }
- if (post.length === 1) {
- const only = post[0];
- if (isDashSegmentUrl(only.url)) {
- // The sibling track may still be in flight pre-MSE-ack.
- return { kind: "pending", reason: "等待音视频分轨齐全" };
- }
- return { kind: "selection", selection: { kind: "single", url: stripRangeParams(only.url), formKind: "unknown" } };
- }
- return { kind: "refused", message: "找到多个媒体资源,请在资源嗅探页选择" };
+ return { kind: "selection", selection: { kind: "single", url: stripRangeParams(only.url), formKind: "unknown" } };
}
+ return { kind: "refused", message: "找到多个媒体资源,请在资源嗅探页选择" };
}
diff --git a/browser_extension/app/src/page-media/strategies/x.ts b/browser_extension/app/src/page-media/strategies/x.ts
index 45f37197..8361ed61 100644
--- a/browser_extension/app/src/page-media/strategies/x.ts
+++ b/browser_extension/app/src/page-media/strategies/x.ts
@@ -1,6 +1,6 @@
import {hostEndsWith, isStreamUrl} from "../url-classify";
import {newestMatching, postBindAttributedUrls} from "../strategy";
-import type {MediaStrategy, ResolveContext} from "../strategy";
+import type {ResolveContext} from "../strategy";
import type {Resolution} from "../types";
const TWITTER_MEDIA_ID = /\/(?:amplify_video(?:_thumb)?|ext_tw_video|tweet_video)\/(\d+)\//i;
@@ -23,29 +23,21 @@ function isMasterTwitterPlaylist(url: string): boolean {
// Master m3u8 only — variants are single-track and dropping one would give silent video.
// posterMediaId pins to this tweet so adjacent tweets' streams don't leak in.
-export class XStrategy implements MediaStrategy {
- readonly id = "x";
-
- matches(pageUrl: URL): boolean {
- return pageUrl.hostname === "x.com" || pageUrl.hostname.endsWith(".x.com");
+export function resolveX(ctx: ResolveContext): Resolution {
+ const posterMediaId = mediaIdOf(ctx.hints.poster ?? "");
+ const allStreams = postBindAttributedUrls(ctx.clicked).filter((r) =>
+ hostEndsWith(r.url, "video.twimg.com")
+ && isStreamUrl(r.url, r.contentType),
+ );
+
+ const candidates = posterMediaId
+ ? allStreams.filter((r) => mediaIdOf(r.url) === posterMediaId)
+ : allStreams;
+
+ const pick = newestMatching(candidates, (url) => isMasterTwitterPlaylist(url));
+ if (pick) {
+ return { kind: "selection", selection: { kind: "stream", url: pick } };
}
- resolve(ctx: ResolveContext): Resolution {
- const posterMediaId = mediaIdOf(ctx.hints.poster ?? "");
- const allStreams = postBindAttributedUrls(ctx.clicked).filter((r) =>
- hostEndsWith(r.url, "video.twimg.com")
- && isStreamUrl(r.url, r.contentType),
- );
-
- const candidates = posterMediaId
- ? allStreams.filter((r) => mediaIdOf(r.url) === posterMediaId)
- : allStreams;
-
- const pick = newestMatching(candidates, (url) => isMasterTwitterPlaylist(url));
- if (pick) {
- return { kind: "selection", selection: { kind: "stream", url: pick } };
- }
-
- return { kind: "pending", reason: "等待 X 主播放清单" };
- }
+ return { kind: "pending", reason: "等待 X 主播放清单" };
}
diff --git a/browser_extension/app/src/page-media/strategy-registry.ts b/browser_extension/app/src/page-media/strategy-registry.ts
deleted file mode 100644
index 4ccf4013..00000000
--- a/browser_extension/app/src/page-media/strategy-registry.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import {DouyinStrategy} from "./strategies/douyin";
-import {GenericStrategy} from "./strategies/generic";
-import {XStrategy} from "./strategies/x";
-
-import type {MediaStrategy} from "./strategy";
-
-// Order matters: GenericStrategy is the fallback (matches() always true), so it stays last.
-const STRATEGIES: readonly MediaStrategy[] = [
- new DouyinStrategy(),
- new XStrategy(),
- new GenericStrategy(),
-];
-
-export function pickStrategy(pageUrl: URL): MediaStrategy {
- return STRATEGIES.find((strategy) => strategy.matches(pageUrl))!;
-}
diff --git a/browser_extension/app/src/page-media/strategy.ts b/browser_extension/app/src/page-media/strategy.ts
index 72dc049a..89c9fa1f 100644
--- a/browser_extension/app/src/page-media/strategy.ts
+++ b/browser_extension/app/src/page-media/strategy.ts
@@ -1,14 +1,17 @@
+import {resolveDouyin} from "./strategies/douyin";
+import {resolveGeneric} from "./strategies/generic";
+import {resolveX} from "./strategies/x";
import type {Resolution, VideoSessionFormKind} from "./types";
-// One attributed URL as the strategies see it — also the element type of
-// SessionSnapshot.attributedUrls and of findUrlsByIdHint's return.
+// One attributed URL as the resolvers see it — also the element type of
+// SessionSnapshot.attributedUrls and of a FindUrlsByIdHint return.
export type AttributedUrlView = {
readonly url: string;
readonly contentType: string;
readonly capturedAt: number;
};
-// Strategies see only this — they MUST NOT reach back into the controller.
+// Resolvers see only this — they MUST NOT reach back into the controller.
export type SessionSnapshot = {
readonly formKind: VideoSessionFormKind;
readonly lastBoundAt: number;
@@ -19,19 +22,28 @@ export type ResolveHints = {
readonly poster: string;
};
-// findUrlsByIdHint is the escape hatch for Douyin's prefetch case where the URL
-// is provisionally owned by v-1 but carries v-2's __vid.
export type ResolveContext = {
readonly clicked: SessionSnapshot;
readonly pageUrl: URL;
readonly hints: ResolveHints;
- findUrlsByIdHint(idHint: string): ReadonlyArray<AttributedUrlView>;
};
-export interface MediaStrategy {
- readonly id: string;
- matches(pageUrl: URL): boolean;
- resolve(ctx: ResolveContext): Resolution;
+// Cross-session ledger lookup. It is Douyin's escape hatch for the prefetch case where the
+// URL is provisionally owned by v-1 but carries v-2's __vid — so only Douyin's resolver
+// gets it, instead of leaking the capability into every resolver's context.
+export type FindUrlsByIdHint = (idHint: string) => ReadonlyArray<AttributedUrlView>;
+
+// The whole dispatch: pick the resolver by hostname, Generic being the fallback. Resolvers
+// are pure functions of the context; Douyin alone also takes the ledger lookup.
+export function resolveForPage(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {
+ const host = ctx.pageUrl.hostname;
+ if (host === "x.com" || host.endsWith(".x.com")) {
+ return resolveX(ctx);
+ }
+ if (host === "www.douyin.com" || host.endsWith(".douyin.com")) {
+ return resolveDouyin(ctx, findUrlsByIdHint);
+ }
+ return resolveGeneric(ctx);
}
// Belt-and-suspenders against pre-bind leakage that survived the ledger.
@@ -52,7 +64,7 @@ export function newestBy<T>(items: ReadonlyArray<T>, key: (item: T) => number):
}
// The freshest attributed URL whose url/contentType matches — the shared shape behind every
-// "pick the newest stream / muxed / track" line the strategies used to spell out by hand.
+// "pick the newest stream / muxed / track" line the resolvers used to spell out by hand.
export function newestMatching(
urls: SessionSnapshot["attributedUrls"],
predicate: (url: string, contentType: string) => boolean,