Skip to content

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

feat(extension): 明确浏览器扩展职责并精简架构

XiaoYouChR765d1e6513fd
diff --git a/browser_extension/app/public/catch-script/media-download-overlay.js b/browser_extension/app/public/catch-script/media-download-overlay.js
deleted file mode 100644
index 374dd769..00000000
--- a/browser_extension/app/public/catch-script/media-download-overlay.js
+++ /dev/null
@@ -1,262 +0,0 @@
-(function installGhostDownloaderMediaButton() {
- if (window.GhostDownloaderMediaButton?.installed) { return; }
- if (!globalThis.chrome?.runtime?.sendMessage) { return; }
-
- const host = document.createElement("div");
- const root = host.attachShadow({ mode: "open" });
- let resetTimer = 0;
- let updateQueued = false;
- let enabled = false;
-
- host.id = "ghostDownloaderMediaDownload";
- Object.assign(host.style, {
- display: "none",
- left: "0",
- position: "fixed",
- top: "0",
- zIndex: "1000000000",
- });
-
- root.innerHTML = `
- <style>
- :host {
- font: 13px/18px "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
- }
- button {
- align-items: center;
- background: rgba(255, 255, 255, 0.96);
- border: 1px solid #d1d1d1;
- border-radius: 4px;
- box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18), 0 1px 4px rgba(0, 0, 0, 0.12);
- color: #242424;
- cursor: pointer;
- display: inline-flex;
- font: inherit;
- font-weight: 600;
- gap: 6px;
- min-height: 32px;
- padding: 6px 10px;
- white-space: nowrap;
- }
- button:hover {
- background: #f5f5f5;
- }
- button:active {
- background: #e0e0e0;
- }
- button:disabled {
- cursor: default;
- opacity: 0.78;
- }
- .icon {
- width: 16px;
- height: 16px;
- flex: none;
- }
- .status {
- color: #0f6cbd;
- }
- .error {
- color: #b10e1c;
- }
- </style>
- <button type="button" title="发送当前媒体到 Ghost Downloader">
- <svg class="icon" viewBox="0 0 20 20" aria-hidden="true">
- <path fill="currentColor" d="M10 2.5a.75.75 0 0 1 .75.75v7.69l2.72-2.72a.75.75 0 1 1 1.06 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 0 1 1.06-1.06l2.72 2.72V3.25A.75.75 0 0 1 10 2.5Zm-5.25 11a.75.75 0 0 1 .75.75v1.25h9v-1.25a.75.75 0 0 1 1.5 0v2a.75.75 0 0 1-.75.75H4.75A.75.75 0 0 1 4 16.25v-2a.75.75 0 0 1 .75-.75Z"/>
- </svg>
- <span class="label">下载此媒体</span>
- <span class="status"></span>
- </button>
- `;
-
- const button = root.querySelector("button");
- const label = root.querySelector(".label");
- const status = root.querySelector(".status");
-
- function mediaRect(media) {
- const rect = media.getBoundingClientRect();
- if (rect.width < 120 || rect.height < 80 || rect.bottom <= 0 || rect.right <= 0 || rect.top >= innerHeight || rect.left >= innerWidth) {
- return null;
- }
- return rect;
- }
-
- // Digit slots: playing (1e9) beats readyState (1e6) beats viewport area, so the user's
- // active video always wins over a paused full-screen poster.
- function mediaScore(media, rect) {
- const playing = !media.paused && !media.ended ? 1_000_000_000 : 0;
- return playing + media.readyState * 1_000_000 + rect.width * rect.height;
- }
-
- function findActiveMedia() {
- let selected = null;
- for (const media of document.querySelectorAll("video")) {
- const rect = mediaRect(media);
- if (!rect) { continue; }
- const score = mediaScore(media, rect);
- if (!selected || score > selected.score) {
- selected = { media, rect, score };
- }
- }
- return selected;
- }
-
- function updatePosition() {
- updateQueued = false;
- if (!enabled) {
- host.style.display = "none";
- return;
- }
- const selected = findActiveMedia();
- if (!selected) {
- host.style.display = "none";
- return;
- }
-
- host.style.display = "block";
- const gap = 8;
- const buttonWidth = host.offsetWidth || 112;
- const buttonHeight = host.offsetHeight || 32;
- let left = selected.rect.right + gap;
- let top = selected.rect.top;
-
- if (left + buttonWidth > innerWidth - gap) {
- left = Math.min(innerWidth - buttonWidth - gap, Math.max(gap, selected.rect.right - buttonWidth));
- top = selected.rect.top - buttonHeight - gap;
- }
- if (top < gap && selected.rect.left - buttonWidth - gap >= gap) {
- left = selected.rect.left - buttonWidth - gap;
- top = selected.rect.top;
- }
- if (top < gap) {
- top = selected.rect.bottom + gap;
- }
-
- host.style.left = `${Math.max(gap, Math.min(left, innerWidth - buttonWidth - gap))}px`;
- host.style.top = `${Math.max(gap, Math.min(top, innerHeight - buttonHeight - gap))}px`;
- }
-
- function enableOverlay() {
- enabled = true;
- if (document.documentElement && !host.isConnected) {
- document.documentElement.appendChild(host);
- }
- scheduleUpdate();
- }
-
- function disableOverlay() {
- enabled = false;
- host.style.display = "none";
- host.remove();
- }
-
- function scheduleUpdate() {
- if (updateQueued) { return; }
- updateQueued = true;
- requestAnimationFrame(updatePosition);
- }
-
- function setStatus(text, failed = false) {
- status.textContent = text;
- status.className = failed ? "status error" : "status";
- clearTimeout(resetTimer);
- if (text && !failed) {
- // Matches TERMINAL_RESET_MS in controller.ts so toast fade and button re-enable line up.
- resetTimer = setTimeout(() => { status.textContent = ""; }, 1600);
- }
- }
-
- let downloadInFlight = false;
- async function downloadMedia() {
- // Double-click would otherwise re-fire within the toast window before the auto-reset.
- if (downloadInFlight) { return; }
- const media = findActiveMedia()?.media;
- if (!media) {
- setStatus("未检测到媒体", true);
- return;
- }
-
- const pageMedia = window.__gd3PageMedia;
- if (!pageMedia?.resolveForElement) {
- setStatus("扩展未就绪", true);
- return;
- }
-
- downloadInFlight = true;
- button.disabled = true;
- label.textContent = "正在解析";
- setStatus("");
-
- // Mirror controller state on the button so the user sees a "waiting" beat instead of staring at "正在解析".
- const onState = (next) => {
- if (next === "waiting") { label.textContent = "等待资源…"; }
- else if (next === "resolving" || next === "dispatched") { label.textContent = "正在发送"; }
- };
-
- try {
- const resolution = await pageMedia.resolveForElement(media, {
- poster: media.poster || "",
- title: document.title,
- }, onState);
- if (!resolution || resolution.kind === "refused") {
- // resolveForElement already moved the session to 'refused'; flipping to 'failed' would misreport why.
- setStatus(resolution?.message || "未能定位媒体", true);
- return;
- }
- if (resolution.kind !== "selection") {
- setStatus("未能定位媒体", true);
- return;
- }
- const result = await chrome.runtime.sendMessage({
- type: "page_download_media",
- selection: resolution.selection,
- href: location.href,
- title: document.title,
- });
- const ok = Boolean(result?.ok);
- setStatus(ok ? "已发送" : result?.message || "发送失败", !ok);
- pageMedia.markDispatchResult?.(media, ok, result?.message || "");
- } catch (error) {
- const message = error instanceof Error ? error.message : "发送失败";
- setStatus(message, true);
- pageMedia.markDispatchResult?.(media, false, message);
- } finally {
- label.textContent = "下载此媒体";
- button.disabled = false;
- downloadInFlight = false;
- scheduleUpdate();
- }
- }
-
- button.addEventListener("click", (event) => {
- event.preventDefault();
- event.stopPropagation();
- void downloadMedia();
- });
-
- addEventListener("resize", scheduleUpdate, { passive: true });
- addEventListener("scroll", scheduleUpdate, { passive: true });
- document.addEventListener("play", scheduleUpdate, true);
- document.addEventListener("pause", scheduleUpdate, true);
- document.addEventListener("loadedmetadata", scheduleUpdate, true);
- setInterval(scheduleUpdate, 1000);
-
- chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
- if (message?.type !== "media_download_overlay_set_enabled") { return; }
- Boolean(message.enabled) ? enableOverlay() : disableOverlay();
- sendResponse({ ok: true });
- });
-
- chrome.runtime.sendMessage({ type: "page_media_overlay_state" }, (result) => {
- const lastError = chrome.runtime.lastError;
- if (!lastError && result?.enabled === false) {
- disableOverlay();
- return;
- }
- enableOverlay();
- });
-
- window.GhostDownloaderMediaButton = {
- installed: true,
- };
-})();
diff --git a/browser_extension/app/public/catch-script/mse-attribution.js b/browser_extension/app/public/catch-script/mse-attribution.js
deleted file mode 100644
index 3650ff78..00000000
--- a/browser_extension/app/public/catch-script/mse-attribution.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Ghost Downloader — MSE attribution probe.
- * Proxy layout derived from cat-catch (catch-script/catch.js); upstream is GPL-3.0.
- * We post tagged messages to the ISOLATED-world controller instead of capturing buffers.
- */
-(function installGhostDownloaderMseAttribution() {
- if (window.__gd3MseAttributionInstalled) { return; }
- window.__gd3MseAttributionInstalled = true;
-
- const SIGNAL_KEY = "__gd3MediaSignal";
- const mediaSourceIdByInstance = new WeakMap();
- let mediaSourceCounter = 0;
-
- function post(payload) {
- try {
- window.postMessage({ [SIGNAL_KEY]: true, ...payload }, "*");
- } catch {
- // Detached frame.
- }
- }
-
- function mediaSourceId(mediaSource) {
- let id = mediaSourceIdByInstance.get(mediaSource);
- if (id == null) {
- mediaSourceCounter += 1;
- id = `ms-${mediaSourceCounter}`;
- mediaSourceIdByInstance.set(mediaSource, id);
- }
- return id;
- }
-
- // Record blob URL → MediaSource so the controller can correlate <video>.src to a MS.
- if (typeof window.URL?.createObjectURL === "function" && typeof window.MediaSource !== "undefined") {
- const originalCreateObjectUrl = window.URL.createObjectURL;
- window.URL.createObjectURL = function patchedCreateObjectURL(source) {
- const url = originalCreateObjectUrl.call(this, source);
- if (source instanceof MediaSource) {
- post({ kind: "mse_objecturl", mediaSourceId: mediaSourceId(source), objectUrl: url });
- }
- return url;
- };
- }
-
- if (typeof window.MediaSource !== "undefined") {
- const originalAddSourceBuffer = MediaSource.prototype.addSourceBuffer;
- MediaSource.prototype.addSourceBuffer = function patchedAddSourceBuffer(mimeType) {
- const sourceBuffer = originalAddSourceBuffer.apply(this, arguments);
- const msId = mediaSourceId(this);
- post({ kind: "mse_source_buffer_added", mediaSourceId: msId, mimeType });
- try {
- const originalAppendBuffer = sourceBuffer.appendBuffer;
- sourceBuffer.appendBuffer = function patchedAppendBuffer(data) {
- const byteLength = data?.byteLength ?? 0;
- post({ kind: "mse_buffer_appended", mediaSourceId: msId, mimeType, byteLength });
- return originalAppendBuffer.apply(this, arguments);
- };
- } catch {
- // Frozen SourceBuffer prototype on some players.
- }
- return sourceBuffer;
- };
- }
-
- if (typeof window.fetch === "function") {
- const originalFetch = window.fetch;
- window.fetch = function patchedFetch(input) {
- const url = typeof input === "string"
- ? input
- : input instanceof Request
- ? input.url
- : String(input ?? "");
- const promise = originalFetch.apply(this, arguments);
- promise.then((response) => {
- try {
- post({
- kind: "fetch_completed",
- url: response?.url || url,
- status: response?.status ?? 0,
- contentType: response?.headers?.get?.("content-type") ?? "",
- contentLength: Number(response?.headers?.get?.("content-length") ?? 0),
- });
- } catch {
- // Opaque response.
- }
- }).catch(() => {});
- return promise;
- };
- }
-
- try {
- const originalOpen = XMLHttpRequest.prototype.open;
- const originalSend = XMLHttpRequest.prototype.send;
- XMLHttpRequest.prototype.open = function patchedOpen(method, url) {
- this.__gd3Url = String(url);
- return originalOpen.apply(this, arguments);
- };
- XMLHttpRequest.prototype.send = function patchedSend() {
- const xhr = this;
- const url = xhr.__gd3Url || "";
- xhr.addEventListener("loadend", () => {
- try {
- post({
- kind: "xhr_completed",
- url,
- status: xhr.status ?? 0,
- contentType: xhr.getResponseHeader?.("content-type") ?? "",
- contentLength: Number(xhr.getResponseHeader?.("content-length") ?? 0),
- });
- } catch { /* opaque response */ }
- });
- return originalSend.apply(this, arguments);
- };
- } catch {
- // Frozen XHR prototype on some players.
- }
-
- post({ kind: "attribution_ready" });
-})();
diff --git a/browser_extension/app/public/manifest.json b/browser_extension/app/public/manifest.json
index 99fff379..8e7362bb 100644
--- a/browser_extension/app/public/manifest.json
+++ b/browser_extension/app/public/manifest.json
@@ -34,7 +34,7 @@
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
- "js": ["catch-script/mse-attribution.js"],
+ "js": ["page-media-probe.js"],
"run_at": "document_start",
"all_frames": true,
"world": "MAIN"
@@ -47,7 +47,7 @@
},
{
"matches": ["http://*/*", "https://*/*"],
- "js": ["catch-script/media-download-overlay.js"],
+ "js": ["page-media-overlay.js"],
"run_at": "document_idle",
"all_frames": true
}
diff --git a/browser_extension/app/scripts/build.mjs b/browser_extension/app/scripts/build.mjs
index 6f458f44..e1adf603 100644
--- a/browser_extension/app/scripts/build.mjs
+++ b/browser_extension/app/scripts/build.mjs
@@ -96,6 +96,26 @@ for (const [target, config] of Object.entries(buildTargets)) {
outfile: path.resolve(config.outDir, "content-script.js"),
});
+ // GD3's own page-media probe (MAIN world) and overlay (ISOLATED world). Authored in TS
+ // under src/page-media — kept out of the vendored catch-script/ directory on purpose.
+ await esbuild({
+ entryPoints: [path.resolve(appRoot, "src/page-media/mse-probe.ts")],
+ bundle: true,
+ format: "iife",
+ target: config.runtimeTarget,
+ platform: "browser",
+ outfile: path.resolve(config.outDir, "page-media-probe.js"),
+ });
+
+ await esbuild({
+ entryPoints: [path.resolve(appRoot, "src/page-media/overlay.ts")],
+ bundle: true,
+ format: "iife",
+ target: config.runtimeTarget,
+ platform: "browser",
+ outfile: path.resolve(config.outDir, "page-media-overlay.js"),
+ });
+
await mkdir(config.outDir, { recursive: true });
await cp(catchScriptDir, path.resolve(config.outDir, "catch-script"), { recursive: true });
await cp(upstreamContentScript, path.resolve(config.outDir, "cat-catch-content-script.js"));
diff --git a/browser_extension/app/src/background.ts b/browser_extension/app/src/background.ts
index 5b0c9649..ed80ac22 100644
--- a/browser_extension/app/src/background.ts
+++ b/browser_extension/app/src/background.ts
@@ -1,10 +1,10 @@
import type {
- AdvancedFeatureKey,
DesktopRequestResult,
GenericTaskSummary,
PopupStatePayload,
PopupView,
} from "./shared/types";
+import type {PopupCommand} from "./shared/popup-protocol";
import {createDesktopBridge} from "./background/desktop-bridge";
import {createFeatureBridge} from "./background/feature-bridge";
import {createMediaBridge} from "./background/media-bridge";
@@ -41,7 +41,7 @@ async function injectMediaDownloadOverlay(tabId: number) {
try {
await chrome.scripting.executeScript({
- files: ["catch-script/media-download-overlay.js"],
+ files: ["page-media-overlay.js"],
injectImmediately: false,
target: { tabId, allFrames: true },
});
@@ -241,6 +241,73 @@ if (supportsDownloadDeterminingFilename()) {
});
}
+// The typed receiver half of the popup command seam (shared/popup-protocol.ts): one
+// exhaustive switch over the command union. Each case narrows the command to its own shape
+// (no cast); the never-typed default makes a missing case a compile error.
+async function handlePopupCommand(command: PopupCommand): Promise<PopupStatePayload | DesktopRequestResult> {
+ switch (command.type) {
+ case "popup_get_state":
+ return buildPopupState({
+ preferredTabId: typeof command.tabId === "number" ? command.tabId : null,
+ currentView: command.view,
+ });
+ case "popup_set_token":
+ await desktopBridge.setToken(command.token.trim());
+ return buildPopupState({ currentView: command.view });
+ case "popup_set_server_url":
+ await desktopBridge.setServerUrl(command.serverUrl);
+ return buildPopupState({ currentView: command.view });
+ case "popup_refresh_connection":
+ await desktopBridge.connect(true);
+ return buildPopupState({ currentView: command.view });
+ case "popup_set_intercept_downloads":
+ interceptDownloads = command.enabled;
+ await chrome.storage.local.set({ [INTERCEPT_DOWNLOADS_KEY]: interceptDownloads });
+ return buildPopupState({ currentView: command.view });
+ case "popup_set_media_download_overlay":
+ await updateMediaDownloadOverlay(command.enabled);
+ return buildPopupState({ currentView: command.view });
+ case "popup_set_media_index":
+ await mediaBridge.setMediaIndex(command.tabId, command.index);
+ return buildPopupState({ currentView: "advanced" });
+ case "popup_request_pairing":
+ void desktopBridge.requestPairing().catch(() => {
+ // The bridge snapshot carries the user-facing pairing failure message.
+ });
+ return { ok: true, message: "请确认配对" };
+ case "popup_task_action":
+ try {
+ return await desktopBridge.sendRequest<DesktopRequestResult>({
+ type: "task_action",
+ taskId: command.taskId,
+ action: command.action,
+ });
+ } catch (error) {
+ return { ok: false, message: error instanceof Error ? error.message : "任务操作失败" };
+ }
+ case "popup_send_resource":
+ return resourceBridge.sendResource(command.resourceId);
+ case "popup_merge_resources":
+ return resourceBridge.mergeResources(command.resourceIds);
+ case "popup_toggle_feature":
+ try {
+ const infoMessage = await featureBridge.toggleFeature(command.feature, command.tabId);
+ return { ok: true, message: infoMessage };
+ } catch (error) {
+ return { ok: false, message: error instanceof Error ? error.message : "功能切换失败" };
+ }
+ default:
+ return unknownPopupCommand(command);
+ }
+}
+
+// Reached only by a popup_ message whose type is not a known command. The `never` parameter
+// makes the switch above exhaustive at compile time; at runtime it returns a structured
+// error instead of throwing, so the caller still gets a response.
+function unknownPopupCommand(command: never): DesktopRequestResult {
+ return { ok: false, message: `未知命令: ${(command as { type?: string }).type ?? ""}` };
+}
+
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!message || typeof message !== "object") {
return;
@@ -268,87 +335,6 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true;
}
- if (message.type === "popup_get_state") {
- return reply(sendResponse, buildPopupState({
- preferredTabId: typeof message.tabId === "number" ? message.tabId : null,
- currentView: message.view as PopupView | undefined,
- }));
- }
-
- if (message.type === "popup_set_token") {
- return reply(sendResponse, (async () => {
- await desktopBridge.setToken(String(message.token ?? "").trim());
- return buildPopupState({ currentView: message.view as PopupView | undefined });
- })());
- }
-
- if (message.type === "popup_set_server_url") {
- return reply(sendResponse, (async () => {
- await desktopBridge.setServerUrl(String(message.serverUrl ?? ""));
- return buildPopupState({ currentView: message.view as PopupView | undefined });
- })());
- }
-
- if (message.type === "popup_refresh_connection") {
- return reply(sendResponse, (async () => {
- await desktopBridge.connect(true);
- return buildPopupState({ currentView: message.view as PopupView | undefined });
- })());
- }
-
- if (message.type === "popup_request_pairing") {
- void desktopBridge.requestPairing().catch(() => {
- // The bridge snapshot carries the user-facing pairing failure message.
- });
- sendResponse({ ok: true, message: "请确认配对" });
- return true;
- }
-
- if (message.type === "popup_set_intercept_downloads") {
- return reply(sendResponse, (async () => {
- interceptDownloads = Boolean(message.enabled);
- await chrome.storage.local.set({ [INTERCEPT_DOWNLOADS_KEY]: interceptDownloads });
- return buildPopupState({ currentView: message.view as PopupView | undefined });
- })());
- }
-
- if (message.type === "popup_set_media_download_overlay") {
- return reply(sendResponse, (async () => {
- await updateMediaDownloadOverlay(Boolean(message.enabled));
- return buildPopupState({ currentView: message.view as PopupView | undefined });
- })());
- }
-
- if (message.type === "popup_task_action") {
- return reply(sendResponse, (async () => {
- try {
- return await desktopBridge.sendRequest<DesktopRequestResult>({
- type: "task_action",
- taskId: message.taskId,
- action: message.action,
- });
- } catch (error) {
- return {
- ok: false,
- message: error instanceof Error ? error.message : "任务操作失败",
- };
- }
- })());
- }
-
- if (message.type === "popup_send_resource") {
- return reply(sendResponse, resourceBridge.sendResource(String(message.resourceId ?? "")));
- }
-
- if (message.type === "popup_merge_resources") {
- return reply(sendResponse, (async () => {
- const resourceIds = Array.isArray(message.resourceIds)
- ? message.resourceIds.map((value: unknown) => String(value ?? "")).filter(Boolean)
- : [];
- return resourceBridge.mergeResources(resourceIds);
- })());
- }
-
if (message.type === "page_download_media") {
return reply(sendResponse, resourceBridge.downloadPageMedia(sender, {
selection: message.selection,
@@ -362,33 +348,12 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return;
}
- if (message.type === "popup_toggle_feature") {
- return reply(sendResponse, (async () => {
- const tabId = typeof message.tabId === "number" ? message.tabId : null;
- if (tabId == null) {
- return { ok: false, message: "当前没有可操作的标签页" };
- }
- try {
- const infoMessage = await featureBridge.toggleFeature(message.feature as AdvancedFeatureKey, tabId);
- return { ok: true, message: infoMessage };
- } catch (error) {
- return {
- ok: false,
- message: error instanceof Error ? error.message : "功能切换失败",
- };
- }
- })());
+ // popup_ messages come only from the extension's own popup (the page world uses
+ // page_download_media / bridge_page_command). handlePopupCommand answers unknown types
+ // with a structured error, so the prefix is the whole guard.
+ if (message.type.startsWith("popup_")) {
+ return reply(sendResponse, handlePopupCommand(message as PopupCommand));
}
-
- if (message.type === "popup_set_media_index") {
- return reply(sendResponse, (async () => {
- await mediaBridge.setMediaIndex(Number(message.tabId ?? 0), Number(message.index ?? -1));
- return buildPopupState({
- currentView: "advanced",
- });
- })());
- }
-
});
void initialize();
diff --git a/browser_extension/app/src/background/download-spec.ts b/browser_extension/app/src/background/download-spec.ts
new file mode 100644
index 00000000..eab4d316
--- /dev/null
+++ b/browser_extension/app/src/background/download-spec.ts
@@ -0,0 +1,112 @@
+import type {CapturedResource} from "../shared/types";
+import {fileExtension, filenameFromUrl} from "../shared/utils";
+
+// 下载规格 (Download Spec) 的权威。Per ADR-0001, the extension — not the desktop — decides
+// the filename/size/supportsRange for a browser-sourced task, because only the browser has
+// the page context (title/poster) and the media's real response. This module is that
+// authority: pure functions turning a captured 资源 (Resource) into the spec the desktop
+// trusts. The two exported entry points are the test surface; the helpers stay internal.
+
+export interface DownloadSpec {
+ url: string;
+ headers: Record<string, string>;
+ filename: string;
+ size: number;
+ supportsRange: boolean;
+}
+
+// Minimal shape resolveCapturedFilename reads; CapturePayload (cat-catch addMedia path)
+// structurally satisfies it.
+export interface CapturedFilenameInput {
+ url: string;
+ filename?: string;
+ mime?: string;
+ ext?: string;
+}
+
+const MIME_EXTENSIONS: Record<string, string> = {
+ "application/dash+xml": "mpd",
+ "application/mpegurl": "m3u8",
+ "application/vnd.apple.mpegurl": "m3u8",
+ "application/x-mpegurl": "m3u8",
+ "audio/aac": "aac",
+ "audio/flac": "flac",
+ "audio/mp4": "m4a",
+ "audio/mpeg": "mp3",
+ "audio/ogg": "ogg",
+ "audio/wav": "wav",
+ "audio/webm": "webm",
+ "video/mp2t": "ts",
+ "video/mp4": "mp4",
+ "video/quicktime": "mov",
+ "video/webm": "webm",
+ "video/x-flv": "flv",
+ "video/x-m4v": "m4v",
+ "video/x-ms-wmv": "wmv",
+};
+
+function cleanFilename(value?: string): string {
+ return (value ?? "")
+ .trim()
+ .replace(/[<>:"/\\|?*\x00-\x1f]+/g, " ")
+ .replace(/\s+/g, " ")
+ .replace(/[. ]+$/g, "")
+ .trim()
+ .slice(0, 160);
+}
+
+function extensionFromMime(mime?: string): string {
+ const type = mime?.split(";")[0]?.trim().toLowerCase() ?? "";
+ return MIME_EXTENSIONS[type] ?? "";
+}
+
+function filenameWithExtension(baseName: string, extension: string): string {
+ const trimmedBaseName = cleanFilename(baseName) || "resource";
+ const normalizedExt = extension.trim().replace(/^\./, "").toLowerCase();
+ if (!normalizedExt) {
+ return trimmedBaseName;
+ }
+ if (fileExtension(trimmedBaseName) === normalizedExt) {
+ return trimmedBaseName;
+ }
+ return `${trimmedBaseName}.${normalizedExt}`;
+}
+
+// Capture-time name for a resource discovered via cat-catch's addMedia path.
+export function resolveCapturedFilename(payload: CapturedFilenameInput): string {
+ const ext = payload.ext?.trim() || extensionFromMime(payload.mime);
+ const explicit = cleanFilename(payload.filename);
+ if (explicit) {
+ return ext && !fileExtension(explicit) ? filenameWithExtension(explicit, ext) : explicit;
+ }
+
+ const fromUrl = cleanFilename(filenameFromUrl(payload.url));
+ if (fromUrl) {
+ return ext ? filenameWithExtension(fromUrl, ext) : fromUrl;
+ }
+
+ return ext ? filenameWithExtension("resource", ext) : "resource";
+}
+
+// The final filename in the spec handed to the desktop; prefers the page title.
+export function filenameForDesktop(resource: CapturedResource): string {
+ const urlFilename = filenameFromUrl(resource.url);
+ const current = cleanFilename(resource.filename || urlFilename);
+ const extension = fileExtension(current)
+ || fileExtension(urlFilename)
+ || extensionFromMime(resource.mime);
+ const title = cleanFilename(resource.pageTitle);
+ const baseName = title || current || "resource";
+ return filenameWithExtension(baseName, extension);
+}
+
+// 资源 → 下载规格. The canonical single-resource handoff spec.
+export function buildDownloadSpec(resource: CapturedResource): DownloadSpec {
+ return {
+ url: resource.url,
+ headers: resource.requestHeaders,
+ filename: filenameForDesktop(resource),
+ size: resource.size,
+ supportsRange: resource.supportsRange,
+ };
+}
diff --git a/browser_extension/app/src/background/resource-bridge.ts b/browser_extension/app/src/background/resource-bridge.ts
index fc648f17..797cd086 100644
--- a/browser_extension/app/src/background/resource-bridge.ts
+++ b/browser_extension/app/src/background/resource-bridge.ts
@@ -19,6 +19,7 @@ import {
RESOURCE_LIMIT,
} from "./constants";
import {bridgeStorageSet, findTab, loadFromBridgeStorage, openActionPopup, queryTabs,} from "./chrome-helpers";
+import {buildDownloadSpec, filenameForDesktop, resolveCapturedFilename} from "./download-spec";
type HeaderSnapshot = {
url: string;
@@ -81,27 +82,6 @@ const HEADER_WHITELIST = new Set([
"priority",
]);
-const MIME_EXTENSIONS: Record<string, string> = {
- "application/dash+xml": "mpd",
- "application/mpegurl": "m3u8",
- "application/vnd.apple.mpegurl": "m3u8",
- "application/x-mpegurl": "m3u8",
- "audio/aac": "aac",
- "audio/flac": "flac",
- "audio/mp4": "m4a",
- "audio/mpeg": "mp3",
- "audio/ogg": "ogg",
- "audio/wav": "wav",
- "audio/webm": "webm",
- "video/mp2t": "ts",
- "video/mp4": "mp4",
- "video/quicktime": "mov",
- "video/webm": "webm",
- "video/x-flv": "flv",
- "video/x-m4v": "m4v",
- "video/x-ms-wmv": "wmv",
-};
-
export function createResourceBridge(options: {
sendDesktopRequest: DesktopRequestSender;
}) {
@@ -385,59 +365,6 @@ export function createResourceBridge(options: {
return null;
}
- function filenameWithExtension(baseName: string, extension: string): string {
- const trimmedBaseName = cleanFilename(baseName) || "resource";
- const normalizedExt = extension.trim().replace(/^\./, "").toLowerCase();
- if (!normalizedExt) {
- return trimmedBaseName;
- }
- if (fileExtension(trimmedBaseName) === normalizedExt) {
- return trimmedBaseName;
- }
- return `${trimmedBaseName}.${normalizedExt}`;
- }
-
- function cleanFilename(value?: string): string {
- return (value ?? "")
- .trim()
- .replace(/[<>:"/\\|?*\x00-\x1f]+/g, " ")
- .replace(/\s+/g, " ")
- .replace(/[. ]+$/g, "")
- .trim()
- .slice(0, 160);
- }
-
- function extensionFromMime(mime?: string): string {
- const type = mime?.split(";")[0]?.trim().toLowerCase() ?? "";
- return MIME_EXTENSIONS[type] ?? "";
- }
-
- function resolveBridgeFilename(payload: CapturePayload): string {
- const ext = payload.ext?.trim() || extensionFromMime(payload.mime);
- const explicit = cleanFilename(payload.filename);
- if (explicit) {
- return ext && !fileExtension(explicit) ? filenameWithExtension(explicit, ext) : explicit;
- }
-
- const fromUrl = cleanFilename(filenameFromUrl(payload.url));
- if (fromUrl) {
- return ext ? filenameWithExtension(fromUrl, ext) : fromUrl;
- }
-
- return ext ? filenameWithExtension("resource", ext) : "resource";
- }
-
- function filenameForDesktop(resource: CapturedResource): string {
- const urlFilename = filenameFromUrl(resource.url);
- const current = cleanFilename(resource.filename || urlFilename);
- const extension = fileExtension(current)
- || fileExtension(urlFilename)
- || extensionFromMime(resource.mime);
- const title = cleanFilename(resource.pageTitle);
- const baseName = title || current || "resource";
- return filenameWithExtension(baseName, extension);
- }
-
async function resolveBridgeResourceTabId(sender: chrome.runtime.MessageSender, href?: string): Promise<number | null> {
if (sender.tab?.id) {
await setLastActiveTab(sender.tab.id);
@@ -733,7 +660,7 @@ export function createResourceBridge(options: {
const tab = await findTab(tabId);
cacheResourceFor(payload.url, tabId, tab, payload.href ?? tab?.url ?? "", {
- filename: resolveBridgeFilename(payload),
+ filename: resolveCapturedFilename(payload),
mime: payload.mime?.toLowerCase() || mimeFromUrl(payload.url),
size: 0,
supportsRange: false,
@@ -831,19 +758,13 @@ export function createResourceBridge(options: {
}
async function sendHttpResourceToDesktop(resource: CapturedResource): Promise<DesktopRequestResult> {
- const filename = filenameForDesktop(resource);
+ const spec = buildDownloadSpec(resource);
try {
const result = await options.sendDesktopRequest<DesktopRequestResult>({
type: "create_task",
source: "resource",
- title: filename,
- payload: {
- url: resource.url,
- headers: resource.requestHeaders,
- filename,
- size: resource.size,
- supportsRange: resource.supportsRange,
- },
+ title: spec.filename,
+ payload: spec,
});
if (result.ok) {
diff --git a/browser_extension/app/src/page-media/controller.ts b/browser_extension/app/src/page-media/controller.ts
index 6f48d178..9ffc36eb 100644
--- a/browser_extension/app/src/page-media/controller.ts
+++ b/browser_extension/app/src/page-media/controller.ts
@@ -2,19 +2,19 @@ import {isCatCatchMedia} from "../shared/cat-catch";
import {fileExtension, filenameFromUrl, mimeFromUrl} from "../shared/utils";
import {AttributionLedger} from "./attribution-ledger";
-import {createDefaultRegistry, StrategyRegistry} from "./strategy-registry";
-import type {AttributedUrlMatch, MediaStrategy, SessionSnapshot, ResolveContext, ResolveHints} from "./strategy";
+import {pickStrategy} from "./strategy-registry";
+import {isMediaSignal} from "./signals";
+import type {AttributedUrlView, MediaStrategy, SessionSnapshot, ResolveContext, ResolveHints} from "./strategy";
import type {
AttributionTier,
MseAttributionSignal,
Resolution,
VideoSession,
VideoSessionFormKind,
- VideoSessionResource,
+ AttributedUrlMeta,
VideoSessionState,
} from "./types";
-const SIGNAL_KEY = "__gd3MediaSignal";
const LOG_PREFIX = "[GD3 Media]";
const VIDEO_ID_QUERY_KEYS = ["__vid", "v", "modal_id", "video_id", "id", "bvid", "aid"];
// Budget from the FIRST Pending — not per re-eval.
@@ -22,7 +22,6 @@ const WAIT_FOR_TIMEOUT_MS = 8000;
// Matches the overlay status toast — auto-reset and toast fade on the same clock.
const TERMINAL_RESET_MS = 1600;
-type RawSignal = MseAttributionSignal & { [SIGNAL_KEY]?: true };
type ResolveStateListener = (state: VideoSessionState, reason: string) => void;
// mse_buffer_appended usually follows fetch_completed within tens of ms; slow CPUs stretch.
@@ -90,20 +89,17 @@ function safeResolveOf(strategy: MediaStrategy, ctx: ResolveContext): Resolution
}
function sessionSnapshot(session: VideoSession): SessionSnapshot {
- const resources: SessionSnapshot["resources"] = Object.freeze(
- [...session.resources.entries()].map(([url, meta]) => Object.freeze({
+ const attributedUrls: SessionSnapshot["attributedUrls"] = Object.freeze(
+ [...session.attributedUrls.entries()].map(([url, meta]) => Object.freeze({
url,
contentType: meta.contentType,
capturedAt: meta.capturedAt,
})),
);
return Object.freeze({
- id: session.id,
- state: session.state,
formKind: session.formKind,
lastBoundAt: session.lastBoundAt,
- resources,
- discriminators: session.discriminators,
+ attributedUrls,
});
}
@@ -116,7 +112,6 @@ class PageMediaController {
private readonly mediaSourceIdByObjectUrl = new Map<string, string>();
private readonly transientResolveListener = new WeakMap<HTMLMediaElement, ResolveStateListener>();
private readonly ledger = new AttributionLedger();
- private readonly registry: StrategyRegistry = createDefaultRegistry();
private mutationObserver: MutationObserver | null = null;
private performanceObserver: PerformanceObserver | null = null;
private lastBoundSession: VideoSession | null = null;
@@ -137,7 +132,7 @@ class PageMediaController {
this.performanceObserver = new PerformanceObserver(this.onResourceTimingEntries);
this.performanceObserver.observe({ type: "resource", buffered: true });
} catch {
- // mse-attribution.js covers attribution if PerformanceObserver throws.
+ // mse-probe.ts covers attribution if PerformanceObserver throws.
}
window.addEventListener("message", this.onMessage);
@@ -236,7 +231,7 @@ class PageMediaController {
state: "inert",
startedAt: performance.now(),
lastBoundAt: 0,
- resources: new Map(),
+ attributedUrls: new Map(),
mimeTypes: new Set(),
mediaSourceIds: new Set(),
discriminators: new Set(),
@@ -292,11 +287,11 @@ class PageMediaController {
let inheritedContentType = "";
for (const session of this.sessionsById.values()) {
if (session.id === newSession.id) { continue; }
- const meta = session.resources.get(url);
+ const meta = session.attributedUrls.get(url);
if (meta) { oldSession = session; inheritedContentType = meta.contentType; break; }
}
- const meta: VideoSessionResource = {
+ const meta: AttributedUrlMeta = {
contentType: trackMime || inheritedContentType,
capturedAt: performance.now(),
tier: "mse",
@@ -304,17 +299,17 @@ class PageMediaController {
};
if (oldSession) {
- oldSession.resources.delete(url);
- // Only locked resources contribute to discriminators (see recordAttribution).
+ oldSession.attributedUrls.delete(url);
+ // Only locked attributed URLs contribute to discriminators (see recordAttribution).
const recomputed = new Set<string>();
- for (const [remainingUrl, remainingMeta] of oldSession.resources) {
+ for (const [remainingUrl, remainingMeta] of oldSession.attributedUrls) {
if (!remainingMeta.lockedByMse) { continue; }
for (const d of urlDiscriminators(remainingUrl)) { recomputed.add(d); }
}
oldSession.discriminators = recomputed;
}
- newSession.resources.set(url, meta);
+ newSession.attributedUrls.set(url, meta);
for (const d of urlDiscriminators(url)) { newSession.discriminators.add(d); }
this.notifyResolveListener(newSession, newSession.state, "url-handover");
@@ -345,16 +340,16 @@ class PageMediaController {
const ledgerEntry = this.ledger.lookup(entry.url);
if (ledgerEntry?.lockedByMse) {
const owner = this.sessionsById.get(ledgerEntry.sessionId);
- const meta = owner?.resources.get(entry.url);
+ const meta = owner?.attributedUrls.get(entry.url);
if (meta) { this.upgradeTrackMime(meta, sourceBufferMime); }
continue;
}
const claim = this.ledger.claim(entry.url, session.id, "mse", now, true);
if (claim.moved || claim.ownerId === session.id) {
- if (!session.resources.has(entry.url)) {
+ if (!session.attributedUrls.has(entry.url)) {
this.handoverUrl(entry.url, session, sourceBufferMime);
} else {
- const meta = session.resources.get(entry.url);
+ const meta = session.attributedUrls.get(entry.url);
if (meta) { this.upgradeTrackMime(meta, sourceBufferMime); }
for (const d of urlDiscriminators(entry.url)) { session.discriminators.add(d); }
}
@@ -368,24 +363,20 @@ class PageMediaController {
// SourceBuffer mime (with `codecs=...`) is always more specific than the container mime
// it would overwrite, so once it's in place we leave it.
- private upgradeTrackMime(meta: VideoSessionResource, sourceBufferMime: string): void {
+ private upgradeTrackMime(meta: AttributedUrlMeta, sourceBufferMime: string): void {
if (!sourceBufferMime) { return; }
if (meta.contentType.includes("codecs")) { return; }
meta.contentType = sourceBufferMime;
}
private onMessage = (event: MessageEvent): void => {
- const data = event.data as RawSignal | null;
- if (!data || typeof data !== "object" || data[SIGNAL_KEY] !== true) { return; }
- this.onSignal(data);
+ if (isMediaSignal(event.data)) {
+ this.onSignal(event.data);
+ }
};
private onSignal(signal: MseAttributionSignal): void {
switch (signal.kind) {
- case "attribution_ready":
- console.log(`${LOG_PREFIX} mse-attribution probe online`);
- return;
-
case "mse_objecturl": {
this.mediaSourceIdByObjectUrl.set(signal.objectUrl, signal.mediaSourceId);
for (const session of this.sessionsById.values()) {
@@ -415,8 +406,7 @@ class PageMediaController {
this.correlateBufferAppend(signal.mediaSourceId, signal.mimeType);
return;
- case "fetch_completed":
- case "xhr_completed":
+ case "request_completed":
this.recordFetch(signal.url, signal.contentType);
this.attributeFetch(signal.url, signal.contentType);
return;
@@ -435,7 +425,7 @@ class PageMediaController {
const existingEntry = this.ledger.lookup(url);
if (existingEntry?.lockedByMse) {
const owner = this.sessionsById.get(existingEntry.sessionId);
- if (owner && !owner.resources.has(url)) {
+ if (owner && !owner.attributedUrls.has(url)) {
this.recordAttribution(owner, url, contentType, "mse", true);
}
return;
@@ -446,7 +436,7 @@ class PageMediaController {
console.log(`${LOG_PREFIX} orphan resource`, { url, contentType });
return;
}
- if (session.resources.has(url)) { return; }
+ if (session.attributedUrls.has(url)) { return; }
this.attribute(session, url, contentType, tier, false);
}
@@ -482,12 +472,12 @@ class PageMediaController {
const claim = this.ledger.claim(url, session.id, tier, performance.now(), locked);
const ownerSession = claim.ownerId === session.id ? session : this.sessionsById.get(claim.ownerId);
if (!ownerSession) { return; }
- if (ownerSession.resources.has(url)) { return; }
+ if (ownerSession.attributedUrls.has(url)) { return; }
this.recordAttribution(ownerSession, url, contentType, tier, locked || claim.ownerId !== session.id);
}
private recordAttribution(session: VideoSession, url: string, contentType: string, tier: AttributionTier, locked: boolean): void {
- session.resources.set(url, {
+ session.attributedUrls.set(url, {
contentType,
capturedAt: performance.now(),
tier,
@@ -504,7 +494,7 @@ class PageMediaController {
} else {
this.notifyResolveListener(session, session.state, `attributed ${url}`);
}
- console.log(`${LOG_PREFIX} ${session.id} += ${url}`, { hint: contentType, count: session.resources.size, tier, locked, state: session.state });
+ console.log(`${LOG_PREFIX} ${session.id} += ${url}`, { hint: contentType, count: session.attributedUrls.size, tier, locked, state: session.state });
}
private isMediaUrl(url: string, contentType: string): boolean {
@@ -525,7 +515,7 @@ class PageMediaController {
// Re-arm so the user can click again without reloading.
setTimeout(() => {
if (session.state === next) {
- this.transition(session, session.resources.size > 0 ? "ready" : "armed", "terminal-reset");
+ this.transition(session, session.attributedUrls.size > 0 ? "ready" : "armed", "terminal-reset");
}
}, TERMINAL_RESET_MS);
}
@@ -539,10 +529,10 @@ class PageMediaController {
try { listener(state, reason); } catch { /* swallow */ }
}
- resourcesFor(element: HTMLMediaElement | null): string[] {
+ attributedUrlsFor(element: HTMLMediaElement | null): string[] {
if (!element) { return []; }
const session = this.sessionsByElement.get(element);
- return session ? [...session.resources.keys()] : [];
+ return session ? [...session.attributedUrls.keys()] : [];
}
async resolveForElement(
@@ -558,13 +548,12 @@ class PageMediaController {
return { kind: "refused", message: "未识别媒体来源" };
}
const pageUrl = new URL(location.href);
- const strategy: MediaStrategy = this.registry.pick(pageUrl);
+ const strategy: MediaStrategy = pickStrategy(pageUrl);
const buildCtx = (): ResolveContext => ({
clicked: sessionSnapshot(session),
pageUrl,
hints,
- now: performance.now(),
findUrlsByDiscriminator: (discriminator) => this.lookupByDiscriminator(discriminator),
});
@@ -611,16 +600,15 @@ class PageMediaController {
// Douyin uses this to reach across sessions for a prefetched URL claimed by a sibling
// before the new <video> existed.
- private lookupByDiscriminator(discriminator: string): ReadonlyArray<AttributedUrlMatch> {
- const matches: AttributedUrlMatch[] = [];
+ private lookupByDiscriminator(discriminator: string): ReadonlyArray<AttributedUrlView> {
+ const matches: AttributedUrlView[] = [];
for (const session of this.sessionsById.values()) {
- for (const [url, meta] of session.resources) {
+ for (const [url, meta] of session.attributedUrls) {
if (urlDiscriminators(url).has(discriminator)) {
matches.push({
url,
contentType: meta.contentType,
capturedAt: meta.capturedAt,
- lockedByMse: meta.lockedByMse,
});
}
}
@@ -649,7 +637,7 @@ class PageMediaController {
declare global {
interface Window {
__gd3PageMedia?: {
- resourcesForElement(element: HTMLMediaElement | null): string[];
+ attributedUrlsForElement(element: HTMLMediaElement | null): string[];
resolveForElement(
element: HTMLMediaElement | null,
hints: ResolveHints,
@@ -667,7 +655,7 @@ export function startPageMediaController(): void {
controllerInstance = new PageMediaController();
controllerInstance.start();
window.__gd3PageMedia = {
- resourcesForElement: (element) => controllerInstance?.resourcesFor(element) ?? [],
+ attributedUrlsForElement: (element) => controllerInstance?.attributedUrlsFor(element) ?? [],
resolveForElement: (element, hints, onStateChange) =>
controllerInstance?.resolveForElement(element, hints, onStateChange) ?? Promise.resolve({ kind: "refused" as const, message: "controller not ready" }),
markDispatchResult: (element, ok, message) =>
diff --git a/browser_extension/app/src/page-media/mse-probe.ts b/browser_extension/app/src/page-media/mse-probe.ts
new file mode 100644
index 00000000..9be435dd
--- /dev/null
+++ b/browser_extension/app/src/page-media/mse-probe.ts
@@ -0,0 +1,115 @@
+/*
+ * Ghost Downloader — MSE attribution probe (MAIN world).
+ * Proxy layout derived from cat-catch (catch-script/catch.js); upstream is GPL-3.0.
+ * We post tagged, typed signals to the ISOLATED-world controller instead of capturing
+ * buffers. Built as a standalone IIFE bundle (see scripts/build.mjs).
+ */
+import {postMediaSignal} from "./signals";
+
+declare global {
+ interface Window {
+ __gd3MseAttributionInstalled?: boolean;
+ }
+}
+
+type GhostXMLHttpRequest = XMLHttpRequest & { __gd3Url?: string };
+
+(function installGhostDownloaderMseAttribution() {
+ if (window.__gd3MseAttributionInstalled) { return; }
+ window.__gd3MseAttributionInstalled = true;
+
+ const mediaSourceIdByInstance = new WeakMap<MediaSource, string>();
+ let mediaSourceCounter = 0;
+
+ function mediaSourceId(mediaSource: MediaSource): string {
+ let id = mediaSourceIdByInstance.get(mediaSource);
+ if (id == null) {
+ mediaSourceCounter += 1;
+ id = `ms-${mediaSourceCounter}`;
+ mediaSourceIdByInstance.set(mediaSource, id);
+ }
+ return id;
+ }
+
+ // Record blob URL → MediaSource so the controller can correlate <video>.src to a MS.
+ if (typeof window.URL?.createObjectURL === "function" && typeof window.MediaSource !== "undefined") {
+ const originalCreateObjectUrl = window.URL.createObjectURL;
+ window.URL.createObjectURL = function patchedCreateObjectURL(source: Blob | MediaSource): string {
+ const url = originalCreateObjectUrl(source);
+ if (source instanceof MediaSource) {
+ postMediaSignal({ kind: "mse_objecturl", mediaSourceId: mediaSourceId(source), objectUrl: url });
+ }
+ return url;
+ };
+ }
+
+ if (typeof window.MediaSource !== "undefined") {
+ const originalAddSourceBuffer = MediaSource.prototype.addSourceBuffer;
+ MediaSource.prototype.addSourceBuffer = function patchedAddSourceBuffer(this: MediaSource, mimeType: string): SourceBuffer {
+ const sourceBuffer = originalAddSourceBuffer.call(this, mimeType);
+ const msId = mediaSourceId(this);
+ postMediaSignal({ kind: "mse_source_buffer_added", mediaSourceId: msId, mimeType });
+ try {
+ const originalAppendBuffer = sourceBuffer.appendBuffer;
+ sourceBuffer.appendBuffer = function patchedAppendBuffer(this: SourceBuffer, data: BufferSource): void {
+ postMediaSignal({ kind: "mse_buffer_appended", mediaSourceId: msId, mimeType });
+ return originalAppendBuffer.call(this, data);
+ };
+ } catch {
+ // Frozen SourceBuffer prototype on some players.
+ }
+ return sourceBuffer;
+ };
+ }
+
+ if (typeof window.fetch === "function") {
+ const originalFetch = window.fetch;
+ window.fetch = function patchedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const url = typeof input === "string"
+ ? input
+ : input instanceof Request
+ ? input.url
+ : String(input ?? "");
+ const promise = originalFetch(input, init);
+ promise.then((response) => {
+ try {
+ postMediaSignal({
+ kind: "request_completed",
+ url: response?.url || url,
+ contentType: response?.headers?.get?.("content-type") ?? "",
+ });
+ } catch {
+ // Opaque response.
+ }
+ }).catch(() => {});
+ return promise;
+ };
+ }
+
+ try {
+ const originalOpen = XMLHttpRequest.prototype.open;
+ const originalSend = XMLHttpRequest.prototype.send;
+ XMLHttpRequest.prototype.open = function patchedOpen(this: GhostXMLHttpRequest, method: string, url: string | URL, ...rest: unknown[]): void {
+ this.__gd3Url = String(url);
+ return (originalOpen as (...args: unknown[]) => void).apply(this, [method, url, ...rest]);
+ };
+ XMLHttpRequest.prototype.send = function patchedSend(this: GhostXMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {
+ const xhr = this;
+ const url = xhr.__gd3Url || "";
+ xhr.addEventListener("loadend", () => {
+ try {
+ postMediaSignal({
+ kind: "request_completed",
+ url,
+ contentType: xhr.getResponseHeader?.("content-type") ?? "",
+ });
+ } catch {
+ // Opaque response.
+ }
+ });
+ return originalSend.call(this, body);
+ };
+ } catch {
+ // Frozen XHR prototype on some players.
+ }
+})();
diff --git a/browser_extension/app/src/page-media/overlay.ts b/browser_extension/app/src/page-media/overlay.ts
new file mode 100644
index 00000000..ba84b079
--- /dev/null
+++ b/browser_extension/app/src/page-media/overlay.ts
@@ -0,0 +1,277 @@
+/*
+ * Ghost Downloader — "download this media" overlay (ISOLATED world).
+ * A floating button that locates the active <video> and asks the page-media controller
+ * (window.__gd3PageMedia) to resolve the right stream, then hands it to the background.
+ * Built as a standalone IIFE bundle (see scripts/build.mjs).
+ */
+import type {VideoSessionState} from "./types";
+
+declare global {
+ interface Window {
+ GhostDownloaderMediaButton?: { installed: boolean };
+ }
+}
+
+type ActiveMedia = { media: HTMLVideoElement; rect: DOMRect; score: number };
+
+(function installGhostDownloaderMediaButton() {
+ if (window.GhostDownloaderMediaButton?.installed) { return; }
+ if (!globalThis.chrome?.runtime?.sendMessage) { return; }
+
+ const host = document.createElement("div");
+ const root = host.attachShadow({ mode: "open" });
+ let resetTimer = 0;
+ let updateQueued = false;
+ let enabled = false;
+
+ host.id = "ghostDownloaderMediaDownload";
+ Object.assign(host.style, {
+ display: "none",
+ left: "0",
+ position: "fixed",
+ top: "0",
+ zIndex: "1000000000",
+ });
+
+ root.innerHTML = `
+ <style>
+ :host {
+ font: 13px/18px "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
+ }
+ button {
+ align-items: center;
+ background: rgba(255, 255, 255, 0.96);
+ border: 1px solid #d1d1d1;
+ border-radius: 4px;
+ box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18), 0 1px 4px rgba(0, 0, 0, 0.12);
+ color: #242424;
+ cursor: pointer;
+ display: inline-flex;
+ font: inherit;
+ font-weight: 600;
+ gap: 6px;
+ min-height: 32px;
+ padding: 6px 10px;
+ white-space: nowrap;
+ }
+ button:hover {
+ background: #f5f5f5;
+ }
+ button:active {
+ background: #e0e0e0;
+ }
+ button:disabled {
+ cursor: default;
+ opacity: 0.78;
+ }
+ .icon {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ }
+ .status {
+ color: #0f6cbd;
+ }
+ .error {
+ color: #b10e1c;
+ }
+ </style>
+ <button type="button" title="发送当前媒体到 Ghost Downloader">
+ <svg class="icon" viewBox="0 0 20 20" aria-hidden="true">
+ <path fill="currentColor" d="M10 2.5a.75.75 0 0 1 .75.75v7.69l2.72-2.72a.75.75 0 1 1 1.06 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 0 1 1.06-1.06l2.72 2.72V3.25A.75.75 0 0 1 10 2.5Zm-5.25 11a.75.75 0 0 1 .75.75v1.25h9v-1.25a.75.75 0 0 1 1.5 0v2a.75.75 0 0 1-.75.75H4.75A.75.75 0 0 1 4 16.25v-2a.75.75 0 0 1 .75-.75Z"/>
+ </svg>
+ <span class="label">下载此媒体</span>
+ <span class="status"></span>
+ </button>
+ `;
+
+ const button = root.querySelector("button")!;
+ const label = root.querySelector(".label")!;
+ const status = root.querySelector(".status")!;
+
+ function mediaRect(media: HTMLVideoElement): DOMRect | null {
+ const rect = media.getBoundingClientRect();
+ if (rect.width < 120 || rect.height < 80 || rect.bottom <= 0 || rect.right <= 0 || rect.top >= innerHeight || rect.left >= innerWidth) {
+ return null;
+ }
+ return rect;
+ }
+
+ // Digit slots: playing (1e9) beats readyState (1e6) beats viewport area, so the user's
+ // active video always wins over a paused full-screen poster.
+ function mediaScore(media: HTMLVideoElement, rect: DOMRect): number {
+ const playing = !media.paused && !media.ended ? 1_000_000_000 : 0;
+ return playing + media.readyState * 1_000_000 + rect.width * rect.height;
+ }
+
+ function findActiveMedia(): ActiveMedia | null {
+ let selected: ActiveMedia | null = null;
+ for (const media of Array.from(document.querySelectorAll<HTMLVideoElement>("video"))) {
+ const rect = mediaRect(media);
+ if (!rect) { continue; }
+ const score = mediaScore(media, rect);
+ if (!selected || score > selected.score) {
+ selected = { media, rect, score };
+ }
+ }
+ return selected;
+ }
+
+ function updatePosition(): void {
+ updateQueued = false;
+ if (!enabled) {
+ host.style.display = "none";
+ return;
+ }
+ const selected = findActiveMedia();
+ if (!selected) {
+ host.style.display = "none";
+ return;
+ }
+
+ host.style.display = "block";
+ const gap = 8;
+ const buttonWidth = host.offsetWidth || 112;
+ const buttonHeight = host.offsetHeight || 32;
+ let left = selected.rect.right + gap;
+ let top = selected.rect.top;
+
+ if (left + buttonWidth > innerWidth - gap) {
+ left = Math.min(innerWidth - buttonWidth - gap, Math.max(gap, selected.rect.right - buttonWidth));
+ top = selected.rect.top - buttonHeight - gap;
+ }
+ if (top < gap && selected.rect.left - buttonWidth - gap >= gap) {
+ left = selected.rect.left - buttonWidth - gap;
+ top = selected.rect.top;
+ }
+ if (top < gap) {
+ top = selected.rect.bottom + gap;
+ }
+
+ host.style.left = `${Math.max(gap, Math.min(left, innerWidth - buttonWidth - gap))}px`;
+ host.style.top = `${Math.max(gap, Math.min(top, innerHeight - buttonHeight - gap))}px`;
+ }
+
+ function enableOverlay(): void {
+ enabled = true;
+ if (document.documentElement && !host.isConnected) {
+ document.documentElement.appendChild(host);
+ }
+ scheduleUpdate();
+ }
+
+ function disableOverlay(): void {
+ enabled = false;
+ host.style.display = "none";
+ host.remove();
+ }
+
+ function scheduleUpdate(): void {
+ if (updateQueued) { return; }
+ updateQueued = true;
+ requestAnimationFrame(updatePosition);
+ }
+
+ function setStatus(text: string, failed = false): void {
+ status.textContent = text;
+ status.className = failed ? "status error" : "status";
+ clearTimeout(resetTimer);
+ if (text && !failed) {
+ // Matches TERMINAL_RESET_MS in controller.ts so toast fade and button re-enable line up.
+ resetTimer = window.setTimeout(() => { status.textContent = ""; }, 1600);
+ }
+ }
+
+ let downloadInFlight = false;
+ async function downloadMedia(): Promise<void> {
+ // Double-click would otherwise re-fire within the toast window before the auto-reset.
+ if (downloadInFlight) { return; }
+ const media = findActiveMedia()?.media;
+ if (!media) {
+ setStatus("未检测到媒体", true);
+ return;
+ }
+
+ const pageMedia = window.__gd3PageMedia;
+ if (!pageMedia?.resolveForElement) {
+ setStatus("扩展未就绪", true);
+ return;
+ }
+
+ downloadInFlight = true;
+ (button as HTMLButtonElement).disabled = true;
+ label.textContent = "正在解析";
+ setStatus("");
+
+ // Mirror controller state on the button so the user sees a "waiting" beat instead of staring at "正在解析".
+ const onState = (next: VideoSessionState) => {
+ if (next === "waiting") { label.textContent = "等待资源…"; }
+ else if (next === "resolving" || next === "dispatched") { label.textContent = "正在发送"; }
+ };
+
+ try {
+ const resolution = await pageMedia.resolveForElement(media, {
+ poster: media.poster || "",
+ }, onState);
+ if (!resolution || resolution.kind === "refused") {
+ // resolveForElement already moved the session to 'refused'; flipping to 'failed' would misreport why.
+ setStatus(resolution?.message || "未能定位媒体", true);
+ return;
+ }
+ if (resolution.kind !== "selection") {
+ setStatus("未能定位媒体", true);
+ return;
+ }
+ const result = await chrome.runtime.sendMessage({
+ type: "page_download_media",
+ selection: resolution.selection,
+ href: location.href,
+ title: document.title,
+ });
+ const ok = Boolean(result?.ok);
+ setStatus(ok ? "已发送" : result?.message || "发送失败", !ok);
+ pageMedia.markDispatchResult?.(media, ok, result?.message || "");
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "发送失败";
+ setStatus(message, true);
+ pageMedia.markDispatchResult?.(media, false, message);
+ } finally {
+ label.textContent = "下载此媒体";
+ (button as HTMLButtonElement).disabled = false;
+ downloadInFlight = false;
+ scheduleUpdate();
+ }
+ }
+
+ button.addEventListener("click", (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void downloadMedia();
+ });
+
+ addEventListener("resize", scheduleUpdate, { passive: true });
+ addEventListener("scroll", scheduleUpdate, { passive: true });
+ document.addEventListener("play", scheduleUpdate, true);
+ document.addEventListener("pause", scheduleUpdate, true);
+ document.addEventListener("loadedmetadata", scheduleUpdate, true);
+ setInterval(scheduleUpdate, 1000);
+
+ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
+ if (message?.type !== "media_download_overlay_set_enabled") { return; }
+ Boolean(message.enabled) ? enableOverlay() : disableOverlay();
+ sendResponse({ ok: true });
+ });
+
+ chrome.runtime.sendMessage({ type: "page_media_overlay_state" }, (result) => {
+ const lastError = chrome.runtime.lastError;
+ if (!lastError && result?.enabled === false) {
+ disableOverlay();
+ return;
+ }
+ enableOverlay();
+ });
+
+ window.GhostDownloaderMediaButton = {
+ installed: true,
+ };
+})();
diff --git a/browser_extension/app/src/page-media/signals.ts b/browser_extension/app/src/page-media/signals.ts
new file mode 100644
index 00000000..527a94d1
--- /dev/null
+++ b/browser_extension/app/src/page-media/signals.ts
@@ -0,0 +1,28 @@
+import type {MseAttributionSignal} from "./types";
+
+// The typed contract for the MAIN-world probe → ISOLATED-world controller channel. Both
+// ends import this file: the probe posts via postMediaSignal, the controller guards with
+// isMediaSignal. The signal shapes live in MseAttributionSignal (./types). The probe and
+// controller are bundled separately, so each carries its own copy of the key — they agree
+// on the string, not on a shared runtime object.
+
+export const MEDIA_SIGNAL_KEY = "__gd3MediaSignal";
+
+type TaggedSignal = MseAttributionSignal & { [MEDIA_SIGNAL_KEY]?: true };
+
+// MAIN world → ISOLATED world. Swallows the throw a detached frame raises.
+export function postMediaSignal(signal: MseAttributionSignal): void {
+ try {
+ window.postMessage({ [MEDIA_SIGNAL_KEY]: true, ...signal }, "*");
+ } catch {
+ // Detached frame.
+ }
+}
+
+export function isMediaSignal(data: unknown): data is MseAttributionSignal {
+ return (
+ typeof data === "object"
+ && data !== null
+ && (data as TaggedSignal)[MEDIA_SIGNAL_KEY] === true
+ );
+}
diff --git a/browser_extension/app/src/page-media/strategies/douyin.ts b/browser_extension/app/src/page-media/strategies/douyin.ts
index 0ecf6801..2e211ecb 100644
--- a/browser_extension/app/src/page-media/strategies/douyin.ts
+++ b/browser_extension/app/src/page-media/strategies/douyin.ts
@@ -1,5 +1,5 @@
import {douyinKindOf, hostEndsWith} from "../url-classify";
-import {newestBy, postBindResources} from "../strategy";
+import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
import type {MediaStrategy, ResolveContext} from "../strategy";
import type {Resolution} from "../types";
@@ -14,25 +14,20 @@ export class DouyinStrategy implements MediaStrategy {
}
resolve(ctx: ResolveContext): Resolution {
- const post = postBindResources(ctx.clicked).filter((r) => hostEndsWith(r.url, "douyinvod.com"));
+ const post = postBindAttributedUrls(ctx.clicked).filter((r) => hostEndsWith(r.url, "douyinvod.com"));
if (ctx.clicked.formKind === "muxed") {
- const muxed = newestBy(post.filter((r) => douyinKindOf(r.url) === "muxed"), (r) => r.capturedAt);
+ const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed") ?? this.findByModalId(ctx, "muxed");
if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed.url, formKind: "muxed" } };
- }
- const fromModalId = this.findByModalId(ctx, "muxed");
- if (fromModalId) {
- return { kind: "selection", selection: { kind: "single", url: fromModalId, formKind: "muxed" } };
+ return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "muxed" } };
}
return { kind: "pending", reason: "等待 Douyin 单 MP4 URL" };
}
if (ctx.clicked.formKind === "dash") {
- const video = newestBy(post.filter((r) => douyinKindOf(r.url) === "video"), (r) => r.capturedAt);
- const audio = newestBy(post.filter((r) => douyinKindOf(r.url) === "audio"), (r) => r.capturedAt);
- if (video && audio) {
- return { kind: "selection", selection: { kind: "merge", video: video.url, audio: audio.url } };
+ const pair = selectMergePair(post, douyinKindOf);
+ if (pair) {
+ return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
}
return { kind: "pending", reason: "等待 Douyin 音视频分轨齐全" };
}
@@ -45,14 +40,13 @@ export class DouyinStrategy implements MediaStrategy {
}
return { kind: "pending", reason: "等待嗅探到当前视频资源" };
}
- const muxed = newestBy(post.filter((r) => douyinKindOf(r.url) === "muxed"), (r) => r.capturedAt);
+ const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed");
if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed.url, formKind: "unknown" } };
+ return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "unknown" } };
}
- const video = newestBy(post.filter((r) => douyinKindOf(r.url) === "video"), (r) => r.capturedAt);
- const audio = newestBy(post.filter((r) => douyinKindOf(r.url) === "audio"), (r) => r.capturedAt);
- if (video && audio) {
- return { kind: "selection", selection: { kind: "merge", video: video.url, audio: audio.url } };
+ const pair = selectMergePair(post, douyinKindOf);
+ if (pair) {
+ return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
}
return { kind: "refused", message: "无法判定 Douyin 当前媒体形态,请在资源嗅探页选择" };
}
@@ -63,7 +57,6 @@ export class DouyinStrategy implements MediaStrategy {
const modalId = ctx.pageUrl.searchParams.get("modal_id");
if (!modalId || modalId.length < 4) { return undefined; }
const matches = ctx.findUrlsByDiscriminator(`__vid=${modalId}`);
- const filtered = matches.filter((m) => douyinKindOf(m.url) === kind);
- return newestBy(filtered, (m) => m.capturedAt)?.url;
+ 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 aeba8ecd..6c1acca9 100644
--- a/browser_extension/app/src/page-media/strategies/generic.ts
+++ b/browser_extension/app/src/page-media/strategies/generic.ts
@@ -1,5 +1,5 @@
import {classifyTrackRole, isDashSegmentUrl, isStreamUrl, stripRangeParams} from "../url-classify";
-import {newestBy, postBindResources} from "../strategy";
+import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
import type {MediaStrategy, ResolveContext} from "../strategy";
import type {Resolution} from "../types";
@@ -12,26 +12,25 @@ export class GenericStrategy implements MediaStrategy {
}
resolve(ctx: ResolveContext): Resolution {
- const post = postBindResources(ctx.clicked);
+ const post = postBindAttributedUrls(ctx.clicked);
- const stream = newestBy(post.filter((r) => isStreamUrl(r.url, r.contentType)), (r) => r.capturedAt);
+ const stream = newestMatching(post, isStreamUrl);
if (stream) {
- return { kind: "selection", selection: { kind: "stream", url: stream.url } };
+ return { kind: "selection", selection: { kind: "stream", url: stream } };
}
if (ctx.clicked.formKind === "muxed") {
- const muxed = newestBy(post.filter((r) => !isDashSegmentUrl(r.url)), (r) => r.capturedAt);
+ const muxed = newestMatching(post, (url) => !isDashSegmentUrl(url));
if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed.url), formKind: "muxed" } };
+ return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "muxed" } };
}
return { kind: "pending", reason: "等待嗅探到当前视频资源" };
}
if (ctx.clicked.formKind === "dash") {
- const video = newestBy(post.filter((r) => classifyTrackRole(r.url, r.contentType) === "video"), (r) => r.capturedAt);
- const audio = newestBy(post.filter((r) => classifyTrackRole(r.url, r.contentType) === "audio"), (r) => r.capturedAt);
- if (video && audio) {
- return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(video.url), audio: stripRangeParams(audio.url) } };
+ 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: "等待音视频分轨齐全" };
}
diff --git a/browser_extension/app/src/page-media/strategies/x.ts b/browser_extension/app/src/page-media/strategies/x.ts
index 9134b420..45f37197 100644
--- a/browser_extension/app/src/page-media/strategies/x.ts
+++ b/browser_extension/app/src/page-media/strategies/x.ts
@@ -1,5 +1,5 @@
import {hostEndsWith, isStreamUrl} from "../url-classify";
-import {newestBy, postBindResources} from "../strategy";
+import {newestMatching, postBindAttributedUrls} from "../strategy";
import type {MediaStrategy, ResolveContext} from "../strategy";
import type {Resolution} from "../types";
@@ -32,7 +32,7 @@ export class XStrategy implements MediaStrategy {
resolve(ctx: ResolveContext): Resolution {
const posterMediaId = mediaIdOf(ctx.hints.poster ?? "");
- const allStreams = postBindResources(ctx.clicked).filter((r) =>
+ const allStreams = postBindAttributedUrls(ctx.clicked).filter((r) =>
hostEndsWith(r.url, "video.twimg.com")
&& isStreamUrl(r.url, r.contentType),
);
@@ -41,10 +41,9 @@ export class XStrategy implements MediaStrategy {
? allStreams.filter((r) => mediaIdOf(r.url) === posterMediaId)
: allStreams;
- const masters = candidates.filter((r) => isMasterTwitterPlaylist(r.url));
- const pick = newestBy(masters, (r) => r.capturedAt);
+ const pick = newestMatching(candidates, (url) => isMasterTwitterPlaylist(url));
if (pick) {
- return { kind: "selection", selection: { kind: "stream", url: pick.url } };
+ return { kind: "selection", selection: { kind: "stream", url: pick } };
}
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
index 312a1a46..4ccf4013 100644
--- a/browser_extension/app/src/page-media/strategy-registry.ts
+++ b/browser_extension/app/src/page-media/strategy-registry.ts
@@ -4,23 +4,13 @@ import {XStrategy} from "./strategies/x";
import type {MediaStrategy} from "./strategy";
-export class StrategyRegistry {
- private readonly strategies: MediaStrategy[] = [];
+// Order matters: GenericStrategy is the fallback (matches() always true), so it stays last.
+const STRATEGIES: readonly MediaStrategy[] = [
+ new DouyinStrategy(),
+ new XStrategy(),
+ new GenericStrategy(),
+];
- register(strategy: MediaStrategy): void {
- this.strategies.push(strategy);
- }
-
- // Relies on GenericStrategy being registered last (matches() always true).
- pick(pageUrl: URL): MediaStrategy {
- return this.strategies.find((strategy) => strategy.matches(pageUrl))!;
- }
-}
-
-export function createDefaultRegistry(): StrategyRegistry {
- const registry = new StrategyRegistry();
- registry.register(new DouyinStrategy());
- registry.register(new XStrategy());
- registry.register(new GenericStrategy());
- return registry;
+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 be4fd2ee..57c06ea9 100644
--- a/browser_extension/app/src/page-media/strategy.ts
+++ b/browser_extension/app/src/page-media/strategy.ts
@@ -1,29 +1,22 @@
-import type {Resolution, VideoSessionFormKind, VideoSessionState} from "./types";
+import type {Resolution, VideoSessionFormKind} from "./types";
+
+// One attributed URL as the strategies see it — also the element type of
+// SessionSnapshot.attributedUrls and of findUrlsByDiscriminator's 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.
export type SessionSnapshot = {
- readonly id: string;
- readonly state: VideoSessionState;
readonly formKind: VideoSessionFormKind;
readonly lastBoundAt: number;
- readonly resources: ReadonlyArray<{
- readonly url: string;
- readonly contentType: string;
- readonly capturedAt: number;
- }>;
- readonly discriminators: ReadonlySet<string>;
+ readonly attributedUrls: ReadonlyArray<AttributedUrlView>;
};
export type ResolveHints = {
readonly poster: string;
- readonly title: string;
-};
-
-export type AttributedUrlMatch = {
- readonly url: string;
- readonly contentType: string;
- readonly capturedAt: number;
- readonly lockedByMse: boolean;
};
// findUrlsByDiscriminator is the escape hatch for Douyin's prefetch case where the URL
@@ -32,8 +25,7 @@ export type ResolveContext = {
readonly clicked: SessionSnapshot;
readonly pageUrl: URL;
readonly hints: ResolveHints;
- readonly now: number;
- findUrlsByDiscriminator(discriminator: string): ReadonlyArray<AttributedUrlMatch>;
+ findUrlsByDiscriminator(discriminator: string): ReadonlyArray<AttributedUrlView>;
};
export interface MediaStrategy {
@@ -43,9 +35,9 @@ export interface MediaStrategy {
}
// Belt-and-suspenders against pre-bind leakage that survived the ledger.
-export function postBindResources(view: SessionSnapshot): SessionSnapshot["resources"] {
- if (view.lastBoundAt <= 0) { return view.resources; }
- return view.resources.filter((r) => r.capturedAt >= view.lastBoundAt);
+export function postBindAttributedUrls(view: SessionSnapshot): SessionSnapshot["attributedUrls"] {
+ if (view.lastBoundAt <= 0) { return view.attributedUrls; }
+ return view.attributedUrls.filter((r) => r.capturedAt >= view.lastBoundAt);
}
export function newestBy<T>(items: ReadonlyArray<T>, key: (item: T) => number): T | undefined {
@@ -58,3 +50,23 @@ export function newestBy<T>(items: ReadonlyArray<T>, key: (item: T) => number):
}
return best;
}
+
+// 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.
+export function newestMatching(
+ urls: SessionSnapshot["attributedUrls"],
+ predicate: (url: string, contentType: string) => boolean,
+): string | undefined {
+ return newestBy(urls.filter((entry) => predicate(entry.url, entry.contentType)), (entry) => entry.capturedAt)?.url;
+}
+
+// The freshest video + audio track for a DASH merge, or null if either side is missing.
+// The caller decides whether to strip range params off the returned URLs.
+export function selectMergePair(
+ urls: SessionSnapshot["attributedUrls"],
+ classify: (url: string, contentType: string) => string,
+): { video: string; audio: string } | null {
+ const video = newestMatching(urls, (url, contentType) => classify(url, contentType) === "video");
+ const audio = newestMatching(urls, (url, contentType) => classify(url, contentType) === "audio");
+ return video && audio ? { video, audio } : null;
+}
diff --git a/browser_extension/app/src/page-media/types.ts b/browser_extension/app/src/page-media/types.ts
index 76a8e947..675fad2f 100644
--- a/browser_extension/app/src/page-media/types.ts
+++ b/browser_extension/app/src/page-media/types.ts
@@ -13,7 +13,8 @@ export type VideoSessionFormKind = "muxed" | "dash" | "unknown";
export type AttributionTier = 0 | 1 | 2 | 3 | "mse";
-export type VideoSessionResource = {
+// Metadata about one 归属 URL (Attributed URL) within a session; the URL itself is the map key.
+export type AttributedUrlMeta = {
contentType: string;
capturedAt: number;
tier: AttributionTier;
@@ -21,12 +22,10 @@ export type VideoSessionResource = {
};
export type MseAttributionSignal =
- | { kind: "attribution_ready" }
| { kind: "mse_objecturl"; mediaSourceId: string; objectUrl: string }
| { kind: "mse_source_buffer_added"; mediaSourceId: string; mimeType: string }
- | { kind: "mse_buffer_appended"; mediaSourceId: string; mimeType: string; byteLength: number }
- | { kind: "fetch_completed"; url: string; status: number; contentType: string; contentLength: number }
- | { kind: "xhr_completed"; url: string; status: number; contentType: string; contentLength: number };
+ | { kind: "mse_buffer_appended"; mediaSourceId: string; mimeType: string }
+ | { kind: "request_completed"; url: string; contentType: string };
export type VideoSession = {
id: string;
@@ -36,7 +35,7 @@ export type VideoSession = {
startedAt: number;
// performance.now() at bindBlobToMediaSource; strategies filter capturedAt > lastBoundAt.
lastBoundAt: number;
- resources: Map<string, VideoSessionResource>;
+ attributedUrls: Map<string, AttributedUrlMeta>;
mimeTypes: Set<string>;
mediaSourceIds: Set<string>;
discriminators: Set<string>;
diff --git a/browser_extension/app/src/popup/hooks/usePopupBridge.ts b/browser_extension/app/src/popup/hooks/usePopupBridge.ts
index d4058dce..aceb4729 100644
--- a/browser_extension/app/src/popup/hooks/usePopupBridge.ts
+++ b/browser_extension/app/src/popup/hooks/usePopupBridge.ts
@@ -12,6 +12,7 @@ import type {
TaskAction,
} from "../../shared/types";
import {sortTasks} from "../../shared/utils";
+import type {ActionCommand, PopupCommand, StateCommand} from "../../shared/popup-protocol";
const REFRESH_INTERVAL_MS = 1000;
const FLASH_TIMEOUT_MS = 2800;
@@ -100,8 +101,14 @@ function errorMessageOr(error: unknown, fallback: string) {
return error instanceof Error ? error.message : fallback;
}
-async function sendDesktopCommand(message: unknown, fallback: string) {
- const result = await sendRuntimeMessage<DesktopRequestResult>(message);
+function dispatch(command: StateCommand): Promise<PopupStatePayload>;
+function dispatch(command: ActionCommand): Promise<DesktopRequestResult>;
+function dispatch(command: PopupCommand): Promise<PopupStatePayload | DesktopRequestResult> {
+ return sendRuntimeMessage<PopupStatePayload | DesktopRequestResult>(command);
+}
+
+async function sendDesktopCommand(command: ActionCommand, fallback: string): Promise<DesktopRequestResult> {
+ const result = await dispatch(command);
if (!result.ok) {
throw new Error(result.message || fallback);
}
@@ -207,7 +214,7 @@ export function usePopupBridge(activeView: PopupView) {
}
refreshPromiseRef.current = (async () => {
- const next = await sendRuntimeMessage<PopupStatePayload>({
+ const next = await dispatch({
type: "popup_get_state",
view: requestView(view),
});
@@ -259,22 +266,14 @@ export function usePopupBridge(activeView: PopupView) {
updateBusyState(setBusyFeatureKeys, feature, active);
}, []);
- const requestPopupState = useCallback(
- (message: Record<string, unknown>) =>
- sendRuntimeMessage<PopupStatePayload>({
- ...message,
- view: requestView(activeViewRef.current),
- }),
- [requestView],
- );
-
const saveToken = useCallback(
async (value: string) => {
setIsSavingToken(true);
try {
- const next = await requestPopupState({
+ const next = await dispatch({
type: "popup_set_token",
token: value.trim(),
+ view: requestView(activeViewRef.current),
});
applyPopupState(next);
setFlash(
@@ -291,16 +290,17 @@ export function usePopupBridge(activeView: PopupView) {
}
}
},
- [applyPopupState, requestPopupState, setFlash],
+ [applyPopupState, requestView, setFlash],
);
const saveServerUrl = useCallback(
async (value: string) => {
setIsSavingServerUrl(true);
try {
- const next = await requestPopupState({
+ const next = await dispatch({
type: "popup_set_server_url",
serverUrl: value,
+ view: requestView(activeViewRef.current),
});
applyPopupState(next);
setFlash(
@@ -317,14 +317,15 @@ export function usePopupBridge(activeView: PopupView) {
}
}
},
- [applyPopupState, requestPopupState, setFlash],
+ [applyPopupState, requestView, setFlash],
);
const refreshConnection = useCallback(async () => {
setIsRefreshingConnection(true);
try {
- const next = await requestPopupState({
+ const next = await dispatch({
type: "popup_refresh_connection",
+ view: requestView(activeViewRef.current),
});
applyPopupState(next);
setFlash(next.connectionMessage, next.connectionState === "connected" ? "success" : "neutral");
@@ -337,12 +338,12 @@ export function usePopupBridge(activeView: PopupView) {
setIsRefreshingConnection(false);
}
}
- }, [applyPopupState, requestPopupState, setFlash]);
+ }, [applyPopupState, requestView, setFlash]);
const requestPairing = useCallback(async () => {
setIsRequestingPairing(true);
try {
- const result = await sendRuntimeMessage<DesktopRequestResult>({
+ const result = await dispatch({
type: "popup_request_pairing",
});
if (!result.ok) {
@@ -367,9 +368,10 @@ export function usePopupBridge(activeView: PopupView) {
async (enabled: boolean) => {
setIsUpdatingIntercept(true);
try {
- const next = await requestPopupState({
+ const next = await dispatch({
type: "popup_set_intercept_downloads",
enabled,
+ view: requestView(activeViewRef.current),
});
applyPopupState(next);
} catch (error) {
@@ -380,16 +382,17 @@ export function usePopupBridge(activeView: PopupView) {
}
}
},
- [applyPopupState, requestPopupState, setFlash],
+ [applyPopupState, requestView, setFlash],
);
const setMediaDownloadOverlay = useCallback(
async (enabled: boolean) => {
setIsUpdatingMediaDownloadOverlay(true);
try {
- const next = await requestPopupState({
+ const next = await dispatch({
type: "popup_set_media_download_overlay",
enabled,
+ view: requestView(activeViewRef.current),
});
applyPopupState(next);
} catch (error) {
@@ -400,7 +403,7 @@ export function usePopupBridge(activeView: PopupView) {
}
}
},
- [applyPopupState, requestPopupState, setFlash],
+ [applyPopupState, requestView, setFlash],
);
const performTaskAction = useCallback(
@@ -466,7 +469,8 @@ export function usePopupBridge(activeView: PopupView) {
const toggleFeature = useCallback(
async (feature: AdvancedFeatureKey) => {
- if (payload.tabId == null) {
+ const tabId = payload.tabId;
+ if (tabId == null) {
setFlash("当前没有可操作的标签页", "error");
return;
}
@@ -475,7 +479,7 @@ export function usePopupBridge(activeView: PopupView) {
const result = await sendDesktopCommand({
type: "popup_toggle_feature",
feature,
- tabId: payload.tabId,
+ tabId,
}, "功能切换失败");
await refreshState(activeViewRef.current);
setFlash(result.message || "功能状态已更新", "success");
@@ -495,7 +499,7 @@ export function usePopupBridge(activeView: PopupView) {
return;
}
try {
- const next = await sendRuntimeMessage<PopupStatePayload>({
+ const next = await dispatch({
type: "popup_set_media_index",
tabId,
index,
diff --git a/browser_extension/app/src/shared/popup-protocol.ts b/browser_extension/app/src/shared/popup-protocol.ts
new file mode 100644
index 00000000..f2782909
--- /dev/null
+++ b/browser_extension/app/src/shared/popup-protocol.ts
@@ -0,0 +1,30 @@
+import type {
+ AdvancedFeatureKey,
+ PopupView,
+ TaskAction,
+} from "./types";
+
+// The typed seam between the popup and the service worker. Both ends import PopupCommand:
+// the popup builds one and dispatches it; the service worker dispatches it through a single
+// exhaustive switch. Commands split by result family — a StateCommand mutates then reprojects
+// the popup state, an ActionCommand is a one-shot that returns a DesktopRequestResult. The
+// family is encoded in the type, so the result type follows from the command with no per-
+// command result map to keep in sync.
+
+export type StateCommand =
+ | { type: "popup_get_state"; view: PopupView; tabId?: number | null }
+ | { type: "popup_set_token"; view: PopupView; token: string }
+ | { type: "popup_set_server_url"; view: PopupView; serverUrl: string }
+ | { type: "popup_refresh_connection"; view: PopupView }
+ | { type: "popup_set_intercept_downloads"; view: PopupView; enabled: boolean }
+ | { type: "popup_set_media_download_overlay"; view: PopupView; enabled: boolean }
+ | { type: "popup_set_media_index"; tabId: number; index: number };
+
+export type ActionCommand =
+ | { type: "popup_request_pairing" }
+ | { type: "popup_task_action"; taskId: string; action: TaskAction }
+ | { type: "popup_send_resource"; resourceId: string }
+ | { type: "popup_merge_resources"; resourceIds: string[] }
+ | { type: "popup_toggle_feature"; feature: AdvancedFeatureKey; tabId: number };
+
+export type PopupCommand = StateCommand | ActionCommand;