The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(Notice): 整理通知接线并优化任务弹窗标题与详情文案
XiaoYouChR4caf2bbb1354
diff --git a/GLOSSARY.md b/GLOSSARY.mdindex 99b333e5..b6c9ca3a 100644--- a/GLOSSARY.md+++ b/GLOSSARY.md@@ -259,6 +259,9 @@ _Avoid_: 用绑定端口或任务句柄推断是否在监听**Clipboard Listener**:剪贴板监听器。监控剪贴板变化,把其中符合 Passive Capture 的链接通知出去。+**Notifier**:+桌面端用户告知的统一入口。负责按用户设置派发 Notice、跟踪新建任务的 Task Popup 并在结束时原地替换为结果提示,以及在主窗口不在屏幕上时以 Popup 承载 Request。+**Category**:下载分类和目标目录规则。将文件扩展名匹配到分类并解析下载目录。任务未指定分类时按扩展名自动匹配;未分类指用户明确不分类,或自动匹配不到任何分类。diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.pyindex da31efaa..2c63db47 100644--- a/Ghost-Downloader-3.py+++ b/Ghost-Downloader-3.py@@ -4,17 +4,13 @@ import osimport sysimport tracebackfrom contextlib import suppress-from dataclasses import replacefrom typing import TYPE_CHECKINGfrom app.config.paths import APP_DATA_DIRif TYPE_CHECKING:- from desktop_notifier.common import Notification- from app.models.task import Taskfrom app.platform.application import Applicationfrom app.platform.instance import PrimaryInstance- from app.services.browser_service import PairRequestdef _exceptionHook(exceptionType, value, tb):@@ -66,7 +62,7 @@ def setupEnvironment() -> None:def startApp(application: Application, primaryInstance: PrimaryInstance, isSilent: bool = False) -> None:from PySide6.QtGui import QIcon- from app.config.cfg import NoticeStyle, TaskPopupPlace, cfg+ from app.config.cfg import cfgfrom app.view.dialogs.name_conflict import NameConflictPromptfrom app.view.shell.clipboard_listener import ClipboardListenerfrom app.signal_bus import signalBus@@ -244,114 +240,29 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilenspeedMeter.speedChanged.connect(lambda _: setLauncherProgress(taskService.overallProgress()))from app.platform.desktop_notification import (- PopupNotifier, PopupStack, SystemNotifier, buildClipboardRequest,- buildDiskSpaceInsufficient, buildPairRequest, buildParseFailed, buildTaskCompleted, buildTaskFailed,- createDoNotDisturb, toFileIcon,+ buildClipboardRequest, buildPairRequest, buildParseFailed,)- systemNotifier = SystemNotifier(coroutineRunner.submit)- sendTo = {NoticeStyle.SYSTEM: systemNotifier.send, NoticeStyle.OFF: lambda _: None}- popupStack: PopupStack | None = None- popupNotifier: PopupNotifier | None = None- if NoticeStyle.POPUP in cfg.noticeStyle.options:- doNotDisturb = createDoNotDisturb()- popupStack = PopupStack(doNotDisturb)- popupNotifier = PopupNotifier(popupStack)- sendTo[NoticeStyle.POPUP] = popupNotifier.send- # 先于 onAboutToQuit 连接,engine.stop() 期间再来的 Notice 会被忽略- application.aboutToQuit.connect(doNotDisturb.close)- application.aboutToQuit.connect(popupStack.clear)-- def windowIsAway() -> bool:- return window is None or not window.isVisible() or window.isMinimized()-- def onUrlsDetected(urls: list[str]) -> None:- if not cfg.isClipboardRequestEnabled.value or not windowIsAway() or popupNotifier is None:- show().addUrls(urls)- return- popupNotifier.send(buildClipboardRequest(urls, lambda: show().addUrls(urls)), "clipboard")-- def onPairRequestChanged(request: PairRequest | None) -> None:- if request is None or not windowIsAway() or popupNotifier is None:- if popupStack is not None:- popupStack.close("pair")- if request is not None:- show().onPairRequested(request)- return- popupNotifier.send(buildPairRequest(- request, lambda: browserService.approvePair(request.requestId),- lambda: browserService.rejectPair(request.requestId)), "pair")-- application.clipboardListener.urlsDetected.connect(onUrlsDetected)- browserService.pairRequestChanged.connect(onPairRequestChanged)- activate = signalBus.activationRequested.emit+ from app.view.shell.notifier import Notifier- def sendNotice(notification: Notification) -> None:- if not cfg.isNoticeSoundEnabled.value:- notification = replace(notification, sound=None)- sendTo[cfg.noticeStyle.value](notification)-- candidates: set[str] = set()-- def showTaskPopup(task: Task, minimized: bool) -> None:- if popupStack is None:- return- popupId = f"task:{task.taskId}"- if (popup := popupStack.popup(popupId)) is not None:- if minimized or not popup.isMinimized():- return- if popupStack.countShown("task:") >= 3:- return- popup.showNormal()- return- if not minimized and popupStack.countShown("task:") >= 3:- return- from app.view.shell.task_popup import TaskPopup- popup = TaskPopup(task, taskService, speedMeter.speedChanged)- popup.openOnTaskbar = minimized- popupStack.add(popup)-- def onTaskAdded(task: Task) -> None:- candidates.add(task.taskId)-- def onTaskStarted(task: Task) -> None:- if task.taskId not in candidates:- return- candidates.discard(task.taskId)- if (popupStack is None or cfg.noticeStyle.value != NoticeStyle.POPUP- or cfg.taskPopupPlace.value == TaskPopupPlace.OFF):- return- showTaskPopup(task, minimized=cfg.taskPopupPlace.value == TaskPopupPlace.TASKBAR)-- def onTaskRemoved(taskId: str) -> None:- candidates.discard(taskId)- if popupStack is not None:- popupStack.close(f"task:{taskId}")-- def onTaskCompleted(task: Task) -> None:- notice = buildTaskCompleted(task, toFileIcon(task.outputPath))- popupId = f"task:{task.taskId}"- if popupNotifier is not None and popupStack is not None and popupStack.has(popupId):- if not cfg.isNoticeSoundEnabled.value:- notice = replace(notice, sound=None)- popupNotifier.send(notice, popupId)- return- sendNotice(notice)-- def onTaskFailed(task: Task) -> None:- popupId = f"task:{task.taskId}"- if popupNotifier is not None and popupStack is not None and popupStack.has(popupId):- popupNotifier.send(buildTaskFailed(task, activate), popupId)-- if popupStack is not None:- taskService.taskAdded.connect(onTaskAdded)- taskService.taskStarted.connect(onTaskStarted)- taskService.taskRemoved.connect(onTaskRemoved)- taskService.taskFailed.connect(onTaskFailed)- signalBus.taskPopupRequested.connect(lambda task: showTaskPopup(task, minimized=False))- taskService.taskCompleted.connect(onTaskCompleted)- taskService.diskSpaceInsufficient.connect(- lambda free, needed: sendNotice(buildDiskSpaceInsufficient(free, needed, activate)))- engine.aria2RpcService.parseFailed.connect(lambda url, error: sendNotice(buildParseFailed(url, error, activate)))+ activate = signalBus.activationRequested.emit+ notifier = Notifier(+ taskService, speedMeter.speedChanged, coroutineRunner.submit, activate,+ isWindowAway=lambda: window is None or not window.isVisible() or window.isMinimized(),+ )+ signalBus.taskPopupRequested.connect(notifier.openTaskPopup)+ engine.aria2RpcService.parseFailed.connect(+ lambda url, error: notifier.send(buildParseFailed(url, error, activate)))+ application.clipboardListener.urlsDetected.connect(lambda urls: notifier.request(+ "clipboard",+ buildClipboardRequest(urls, lambda: show().addUrls(urls)) if cfg.isClipboardRequestEnabled.value else None,+ lambda: show().addUrls(urls),+ ))+ browserService.pairRequestChanged.connect(lambda req: notifier.request(+ "pair",+ buildPairRequest(req, lambda: browserService.approvePair(req.requestId),+ lambda: browserService.rejectPair(req.requestId)) if req else None,+ (lambda: show().onPairRequested(req)) if req else None,+ ))taskService.tasksAllCompleted.connect(emptyWorkingSetIfIdle)@@ -377,6 +288,7 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilenwith suppress(RuntimeError):application.aboutToQuit.disconnect(updateService.apply)+ application.aboutToQuit.connect(notifier.close)application.aboutToQuit.connect(engine.stop)application.aboutToQuit.connect(updateService.apply)application.aboutToQuit.connect(coroutineRunner.stop)diff --git a/app/i18n.py b/app/i18n.pyindex a01e4601..2547ec99 100644--- a/app/i18n.py+++ b/app/i18n.py@@ -39,6 +39,21 @@ def toLocalizedError(error) -> str:return text.format_map(error.params) if error.params else text+def toDurationText(seconds: int) -> str:+ from PySide6.QtCore import QCoreApplication+ if seconds < 60:+ return QCoreApplication.translate("TaskPopup", "{0} 秒").format(seconds)+ minutes, secs = divmod(seconds, 60)+ if seconds < 3600:+ if secs:+ return QCoreApplication.translate("TaskPopup", "{0} 分 {1} 秒").format(minutes, secs)+ return QCoreApplication.translate("TaskPopup", "{0} 分").format(minutes)+ hours, minutes = divmod(minutes, 60)+ if minutes:+ return QCoreApplication.translate("TaskPopup", "{0} 小时 {1} 分").format(hours, minutes)+ return QCoreApplication.translate("TaskPopup", "{0} 小时").format(hours)++N("TaskErrors", "进程异常退出({code}):{detail}")N("TaskErrors", "发生了意外错误:{detail}")N("TaskErrors", "不支持该链接")diff --git a/app/view/dialogs/task_drawer.py b/app/view/dialogs/task_drawer.pyindex ae6a3f5d..0828c1a7 100644--- a/app/view/dialogs/task_drawer.py+++ b/app/view/dialogs/task_drawer.py@@ -19,8 +19,8 @@ from qfluentwidgets.components.widgets.menu import TextEditMenufrom app.checksum import matchChecksumfrom app.config.cfg import cfg-from app.format import toReadableSize, toReadableTime-from app.i18n import toLocalizedError+from app.format import toReadableSize+from app.i18n import toDurationText, toLocalizedErrorfrom app.models.task import TaskStatusfrom app.platform.desktop import revealInFolderfrom app.view.components.category_settings import toCategoryName@@ -187,12 +187,16 @@ class HeaderCard(QWidget):def _toStatusText(self, speed: int, received: int) -> str:task = self._taskif task.status == TaskStatus.RUNNING:- parts = [f"{toReadableSize(speed)}/s"]+ if task.fileSize > 0 and speed > 0:+ remaining = toDurationText(int((task.fileSize - received) / speed))+ return self.tr("速度 {0}/s,已下载 {1} / {2},剩余 {3}").format(+ toReadableSize(speed), toReadableSize(received), toReadableSize(task.fileSize), remaining)if task.fileSize > 0:- parts.append(f"{toReadableSize(received)} / {toReadableSize(task.fileSize)}")- if speed > 0:- parts.append(toReadableTime(int((task.fileSize - received) / speed)))- return " · ".join(parts)+ return self.tr("正在计算速度,已下载 {0} / {1}").format(+ toReadableSize(received), toReadableSize(task.fileSize))+ if speed > 0:+ return self.tr("速度 {0}/s,已下载 {1}").format(toReadableSize(speed), toReadableSize(received))+ return self.tr("正在计算速度,已下载 {0}").format(toReadableSize(received))if task.status == TaskStatus.COMPLETED:return self.tr("做种中") if task.isSeeding else self.tr("已完成")if task.status == TaskStatus.FAILED:diff --git a/app/view/shell/notifier.py b/app/view/shell/notifier.pynew file mode 100644index 00000000..4e9abb9e--- /dev/null+++ b/app/view/shell/notifier.py@@ -0,0 +1,161 @@+from __future__ import annotations++from collections.abc import Callable, Coroutine+from dataclasses import replace+from typing import TYPE_CHECKING++from app.config.cfg import NoticeStyle, TaskPopupPlace, cfg+from app.platform.desktop_notification import (+ DoNotDisturb, PopupNotifier, PopupStack, SystemNotifier,+ buildDiskSpaceInsufficient, buildTaskCompleted, buildTaskFailed,+ createDoNotDisturb, toFileIcon,+)++if TYPE_CHECKING:+ from desktop_notifier.common import Notification++ from app.models.task import Task+ from app.services.task_service import TaskService+ from app.signal import Signal++MAX_SHOWN_TASK_POPUPS = 3+TASK_POPUP_PREFIX = "task:"+++class Notifier:+ def __init__(+ self,+ taskService: TaskService,+ speedChanged: Signal,+ submit: Callable[[Coroutine], object],+ activate: Callable[[], None],+ isWindowAway: Callable[[], bool],+ ) -> None:+ self._taskService = taskService+ self._speedChanged = speedChanged+ self._activate = activate+ self._isWindowAway = isWindowAway+ self._isClosed = False+ self._candidates: set[str] = set()++ systemNotifier = SystemNotifier(submit)+ self._sendTo: dict[NoticeStyle, Callable[[Notification], None]] = {+ NoticeStyle.SYSTEM: systemNotifier.send,+ NoticeStyle.OFF: lambda _: None,+ }+ self._doNotDisturb: DoNotDisturb | None = None+ self._popupStack: PopupStack | None = None+ self._popupNotifier: PopupNotifier | None = None+ if NoticeStyle.POPUP in cfg.noticeStyle.options:+ self._doNotDisturb = createDoNotDisturb()+ self._popupStack = PopupStack(self._doNotDisturb)+ self._popupNotifier = PopupNotifier(self._popupStack)+ self._sendTo[NoticeStyle.POPUP] = self._popupNotifier.send++ if self._popupStack is not None:+ taskService.taskAdded.connect(self._onTaskAdded)+ taskService.taskStarted.connect(self._onTaskStarted)+ taskService.taskRemoved.connect(self._onTaskRemoved)+ taskService.taskFailed.connect(self._onTaskFailed)+ taskService.taskCompleted.connect(self._onTaskCompleted)+ taskService.diskSpaceInsufficient.connect(self._onDiskSpaceInsufficient)++ def send(self, notification: Notification) -> None:+ if self._isClosed:+ return+ self._sendTo[cfg.noticeStyle.value](self._applySoundPolicy(notification))++ def request(+ self,+ requestId: str,+ notification: Notification | None,+ fallback: Callable[[], None] | None = None,+ ) -> None:+ if self._isClosed:+ return+ if notification is not None and self._popupNotifier is not None and self._isWindowAway():+ self._popupNotifier.send(notification, requestId)+ return+ if self._popupStack is not None:+ self._popupStack.close(requestId)+ if fallback is not None:+ fallback()++ def openTaskPopup(self, task: Task) -> None:+ self._openTaskPopup(task, minimized=False)++ def close(self) -> None:+ if self._isClosed:+ return+ self._isClosed = True+ self._candidates.clear()+ if self._popupStack is not None:+ self._taskService.taskAdded.disconnect(self._onTaskAdded)+ self._taskService.taskStarted.disconnect(self._onTaskStarted)+ self._taskService.taskRemoved.disconnect(self._onTaskRemoved)+ self._taskService.taskFailed.disconnect(self._onTaskFailed)+ self._taskService.taskCompleted.disconnect(self._onTaskCompleted)+ self._taskService.diskSpaceInsufficient.disconnect(self._onDiskSpaceInsufficient)+ if self._doNotDisturb is not None:+ self._doNotDisturb.close()+ if self._popupStack is not None:+ self._popupStack.clear()++ def _applySoundPolicy(self, notification: Notification) -> Notification:+ if not cfg.isNoticeSoundEnabled.value:+ return replace(notification, sound=None)+ return notification++ def _openTaskPopup(self, task: Task, minimized: bool) -> None:+ if self._isClosed or self._popupStack is None:+ return+ popupId = f"{TASK_POPUP_PREFIX}{task.taskId}"+ if (popup := self._popupStack.popup(popupId)) is not None:+ if minimized or not popup.isMinimized():+ return+ if self._popupStack.countShown(TASK_POPUP_PREFIX) >= MAX_SHOWN_TASK_POPUPS:+ return+ popup.showNormal()+ return+ if not minimized and self._popupStack.countShown(TASK_POPUP_PREFIX) >= MAX_SHOWN_TASK_POPUPS:+ return+ from app.view.shell.task_popup import TaskPopup+ popup = TaskPopup(task, self._taskService, self._speedChanged)+ popup.openOnTaskbar = minimized+ self._popupStack.add(popup)++ def _onTaskAdded(self, task: Task) -> None:+ self._candidates.add(task.taskId)++ def _onTaskStarted(self, task: Task) -> None:+ if task.taskId not in self._candidates:+ return+ self._candidates.discard(task.taskId)+ if cfg.noticeStyle.value != NoticeStyle.POPUP or cfg.taskPopupPlace.value == TaskPopupPlace.OFF:+ return+ self._openTaskPopup(task, minimized=cfg.taskPopupPlace.value == TaskPopupPlace.TASKBAR)++ def _onTaskRemoved(self, taskId: str) -> None:+ self._candidates.discard(taskId)+ if self._popupStack is not None:+ self._popupStack.close(f"{TASK_POPUP_PREFIX}{taskId}")++ def _onTaskCompleted(self, task: Task) -> None:+ if self._isClosed:+ return+ notice = buildTaskCompleted(task, toFileIcon(task.outputPath))+ popupId = f"{TASK_POPUP_PREFIX}{task.taskId}"+ if self._popupNotifier is not None and self._popupStack is not None and self._popupStack.has(popupId):+ self._popupNotifier.send(self._applySoundPolicy(notice), popupId)+ return+ self.send(notice)++ def _onTaskFailed(self, task: Task) -> None:+ if self._isClosed:+ return+ popupId = f"{TASK_POPUP_PREFIX}{task.taskId}"+ if self._popupNotifier is not None and self._popupStack is not None and self._popupStack.has(popupId):+ self._popupNotifier.send(buildTaskFailed(task, self._activate), popupId)++ def _onDiskSpaceInsufficient(self, free: int, needed: int) -> None:+ self.send(buildDiskSpaceInsufficient(free, needed, self._activate))diff --git a/app/view/shell/task_popup.py b/app/view/shell/task_popup.pyindex 00c2c9d0..8251f7e5 100644--- a/app/view/shell/task_popup.py+++ b/app/view/shell/task_popup.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport sysfrom typing import TYPE_CHECKING-from PySide6.QtCore import QCoreApplication, QFileInfo, Qt+from PySide6.QtCore import QFileInfo, Qtfrom PySide6.QtGui import QColorfrom PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QLabel, QSizePolicy, QVBoxLayoutfrom qfluentwidgets import (@@ -11,26 +11,13 @@ from qfluentwidgets import ()from app.format import toReadableSize+from app.i18n import toDurationTextfrom app.models.task import SpecialFileSize, TaskStatusfrom app.platform.desktop_notification import (FILE_ICON_SIZE, ICON_SPACING, PADDING, SPACING, TEXT_WIDTH, Popup,)-def toRemainingText(seconds: int) -> str:- if seconds < 60:- return QCoreApplication.translate("TaskPopup", "{0} 秒").format(seconds)- minutes, secs = divmod(seconds, 60)- if seconds < 3600:- if secs:- return QCoreApplication.translate("TaskPopup", "{0} 分 {1} 秒").format(minutes, secs)- return QCoreApplication.translate("TaskPopup", "{0} 分").format(minutes)- hours, minutes = divmod(minutes, 60)- if minutes:- return QCoreApplication.translate("TaskPopup", "{0} 小时 {1} 分").format(hours, minutes)- return QCoreApplication.translate("TaskPopup", "{0} 小时").format(hours)--if TYPE_CHECKING:from app.models.task import Taskfrom app.services.task_service import TaskService@@ -126,7 +113,7 @@ class TaskPopup(Popup):if task.status == TaskStatus.RUNNING and speed > 0 and task.fileSize > 0:remaining = int((task.fileSize - received) / speed)self.statusLabel.setText(self.tr("速度 {0}/s,剩余 {1}").format(- toReadableSize(speed), toRemainingText(remaining)))+ toReadableSize(speed), toDurationText(remaining)))elif task.status == TaskStatus.RUNNING and speed > 0:self.statusLabel.setText(self.tr("速度 {0}/s").format(toReadableSize(speed)))elif task.status == TaskStatus.RUNNING:@@ -141,9 +128,13 @@ class TaskPopup(Popup):else:self.sizeLabel.setText(self.tr("已下载 {0}").format(toReadableSize(received)))+ hasFileSize = task.fileSize > 0isPaused = task.status == TaskStatus.PAUSEDif isinstance(self.progressBar, ProgressBar):self.progressBar.setValue(int(progress))+ title = f"{int(progress)}% {task.name}" if hasFileSize else task.name+ if self.windowTitle() != title:+ self.setWindowTitle(title)if isPaused:self.progressBar.pause()else:@@ -153,8 +144,7 @@ class TaskPopup(Popup):if sys.platform == "win32":from app.platform.taskbar import setWindowsProgress- isKnown = isinstance(self.progressBar, ProgressBar)- setWindowsProgress(int(self.winId()), task.status, progress if isKnown else None)+ setWindowsProgress(int(self.winId()), task.status, progress if hasFileSize else None)def _onTaskPaused(self, task: Task) -> None:if task.taskId == self._task.taskId: