Skip to content

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

feat(browser-extension): 完成后打开、自动唤醒桌面端、Firefox 兼容

XiaoYouChRb22c8867d10a
diff --git a/browser_extension/app/src/background.ts b/browser_extension/app/src/background.ts
index 7b131d6a..68dc3d68 100644
--- a/browser_extension/app/src/background.ts
+++ b/browser_extension/app/src/background.ts
@@ -49,8 +49,24 @@ async function sendTaskOrEnqueue<T extends CommandResult>(payload: Record<string
return { ok: true, message: "桌面端未连接,任务已排队" } as T;
}
+const openWhenDoneIds = new Set<string>();
+
+function onTaskSnapshotChanged(tasks: TaskSummary[]): void {
+ updateIconForTasks(tasks);
+ for (const task of tasks) {
+ if (task.status === "completed" && openWhenDoneIds.has(task.taskId)) {
+ openWhenDoneIds.delete(task.taskId);
+ void desktopBridge.sendRequest({
+ type: "task_action",
+ taskId: task.taskId,
+ action: "open_file",
+ });
+ }
+ }
+}
+
const desktopBridge = createDesktopBridge({
- onTaskSnapshotChanged: updateIconForTasks,
+ onTaskSnapshotChanged,
onConnected: () => void flushQueue(),
});
const resourceBridge = createResourceBridge({
@@ -146,7 +162,7 @@ async function buildPopupState(options: {
serverUrl: desktopState.serverUrl,
shouldTakeDownloads,
isMediaButtonEnabled,
- tasks: desktopState.tasks,
+ tasks: desktopState.tasks.map((t) => ({ ...t, shouldOpenWhenDone: openWhenDoneIds.has(t.taskId) })),
taskCounters: buildTaskCounters(desktopState.tasks),
tabId: activeTabId,
featureStates: featureBridge.createFeatureStateMap(activeTabId),
@@ -295,6 +311,7 @@ chrome.webRequest.onResponseStarted.addListener(
let bypassNextDownload = false;
let bypassTimer = 0;
+let autoLaunchPending = false;
async function takeBrowserDownload(
downloadItem: chrome.downloads.DownloadItem,
@@ -317,6 +334,8 @@ async function takeBrowserDownload(
if (totalBytes >= 0 && totalBytes < minTakeSizeKB * 1024) { return; }
}
+ const wasReady = desktopBridge.isReady();
+
try {
await cancelDownload(downloadItem.id);
if (options.eraseFromHistory) {
@@ -326,6 +345,10 @@ async function takeBrowserDownload(
// Cleanup failed but the browser will still finish the download as fallback.
}
+ if (!wasReady) {
+ autoLaunchPending = true;
+ }
+
await resourceBridge.routeBrowserDownload(downloadItem);
}
@@ -380,6 +403,14 @@ async function runPopupCommand(command: PopupCommand): Promise<PopupState | Comm
});
return { ok: true, message: "请确认配对" };
case "popup_task_action":
+ if (command.action === "open_when_done") {
+ if (openWhenDoneIds.has(command.taskId)) {
+ openWhenDoneIds.delete(command.taskId);
+ } else {
+ openWhenDoneIds.add(command.taskId);
+ }
+ return { ok: true };
+ }
try {
return await desktopBridge.sendRequest<CommandResult>({
type: "task_action",
@@ -500,6 +531,13 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return;
}
+ if (message.type === "popup_mounted") {
+ const shouldLaunch = autoLaunchPending;
+ autoLaunchPending = false;
+ sendResponse({ autoLaunch: shouldLaunch });
+ return;
+ }
+
if (message.type === "page_media_button_state") {
sendResponse({ enabled: isMediaButtonEnabled });
return;
diff --git a/browser_extension/app/src/popup/App.tsx b/browser_extension/app/src/popup/App.tsx
index c5d77985..0247bbe7 100644
--- a/browser_extension/app/src/popup/App.tsx
+++ b/browser_extension/app/src/popup/App.tsx
@@ -1,5 +1,5 @@
import {makeStyles} from "@fluentui/react-components";
-import {useState} from "react";
+import {useEffect, useState} from "react";
import type {PopupView, ThemePreference} from "../shared/types";
import {AdvancedPage} from "./pages/AdvancedPage";
@@ -40,6 +40,15 @@ export function App({
const [currentView, setCurrentView] = useState<PopupView>("tasks");
const bridge = usePopupBridge(currentView);
+ useEffect(() => {
+ chrome.runtime.sendMessage({ type: "popup_mounted" }, (response) => {
+ void chrome.runtime.lastError;
+ if (response?.autoLaunch) {
+ launchDesktop();
+ }
+ });
+ }, []);
+
return (
<div className={styles.root}>
<Header
diff --git a/browser_extension/app/src/popup/components/TaskCard.tsx b/browser_extension/app/src/popup/components/TaskCard.tsx
index 4e6a39ae..0f73affe 100644
--- a/browser_extension/app/src/popup/components/TaskCard.tsx
+++ b/browser_extension/app/src/popup/components/TaskCard.tsx
@@ -1,4 +1,4 @@
-import {Avatar, Button, Caption1, Card, makeStyles, ProgressBar} from "@fluentui/react-components";
+import {Avatar, Button, Caption1, Card, makeStyles, ProgressBar, tokens} from "@fluentui/react-components";
import {
ArrowClockwiseRegular,
DismissRegular,
@@ -42,6 +42,16 @@ const useStyles = makeStyles({
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
+ cursor: "default",
+ },
+ metaClickable: {
+ cursor: "pointer",
+ "&:hover": {
+ textDecoration: "underline",
+ },
+ },
+ openWhenDone: {
+ color: tokens.colorBrandForeground1,
},
actions: {
display: "flex",
@@ -65,6 +75,10 @@ function metaText(task: TaskSummary): string {
? formatBytes(task.receivedBytes)
: "";
+ if (task.shouldOpenWhenDone && task.status !== "completed") {
+ return ["完成后打开", sizePart].filter(Boolean).join(" · ");
+ }
+
switch (task.status) {
case "running":
return [formatTaskMetric(task), sizePart].filter(Boolean).join(" · ");
@@ -106,10 +120,15 @@ export function TaskCard({
const TaskIcon = visualIcon(visual.kind);
const isCompleted = task.status === "completed";
const isRunning = task.status === "running";
+ const isActive = isRunning || task.status === "waiting";
const isPausedOrFailed = task.status === "paused" || task.status === "failed" || task.status === "waiting";
const showProgress = !isCompleted;
const progressValue = task.status === "waiting" ? undefined : Math.max(0, Math.min(100, task.progress)) / 100;
+ const metaClassName = isActive
+ ? `${styles.meta} ${styles.metaClickable}${task.shouldOpenWhenDone ? ` ${styles.openWhenDone}` : ""}`
+ : styles.meta;
+
return (
<Card appearance="filled-alternative" className={styles.root}>
<div className={styles.row}>
@@ -123,7 +142,12 @@ export function TaskCard({
<div className={styles.body}>
<div className={styles.title}>{task.name}</div>
- <Caption1 className={styles.meta}>{metaText(task)}</Caption1>
+ <Caption1
+ className={metaClassName}
+ onClick={isActive ? () => onAction("open_when_done") : undefined}
+ >
+ {metaText(task)}
+ </Caption1>
</div>
<div className={styles.actions}>
diff --git a/browser_extension/app/src/popup/launch-desktop.ts b/browser_extension/app/src/popup/launch-desktop.ts
index fba05689..49d13378 100644
--- a/browser_extension/app/src/popup/launch-desktop.ts
+++ b/browser_extension/app/src/popup/launch-desktop.ts
@@ -1,7 +1,3 @@
export function launchDesktop(): void {
- const frame = document.createElement("iframe");
- frame.style.display = "none";
- frame.src = "ghostdownloader://launch";
- document.body.appendChild(frame);
- setTimeout(() => frame.remove(), 2000);
+ window.location.href = "ghostdownloader://launch";
}
diff --git a/browser_extension/app/src/popup/usePopupBridge.ts b/browser_extension/app/src/popup/usePopupBridge.ts
index 6881d472..38a8aeba 100644
--- a/browser_extension/app/src/popup/usePopupBridge.ts
+++ b/browser_extension/app/src/popup/usePopupBridge.ts
@@ -404,7 +404,9 @@ export function usePopupBridge(activeView: PopupView) {
action,
}, "任务操作失败");
await refreshState(activeViewRef.current);
- showToast("任务操作已发送", "success");
+ if (action !== "open_when_done") {
+ showToast("任务操作已发送", "success");
+ }
} catch (error) {
showToast(errorMessageOr(error, "任务操作失败"), "error");
} finally {
diff --git a/browser_extension/app/src/shared/types.ts b/browser_extension/app/src/shared/types.ts
index 8a7e5294..fdbb4a77 100644
--- a/browser_extension/app/src/shared/types.ts
+++ b/browser_extension/app/src/shared/types.ts
@@ -1,5 +1,5 @@
export type PopupView = "tasks" | "resources" | "images" | "advanced" | "settings";
-export type TaskAction = "toggle_pause" | "redownload" | "open_file" | "open_folder" | "cancel";
+export type TaskAction = "toggle_pause" | "redownload" | "open_file" | "open_folder" | "cancel" | "open_when_done";
export type MediaAction =
| "toggle_play"
| "set_speed"
@@ -44,6 +44,7 @@ export interface TaskSummary {
canPause: boolean;
canOpenFile: boolean;
canOpenFolder: boolean;
+ shouldOpenWhenDone: boolean;
fileExt: string;
packName: string;
}