The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat: 种子/M3U8 文件关联与打开
XiaoYouChR0448ccea8e41
diff --git a/app/assets/file_icons/build_icons.py b/app/assets/file_icons/build_icons.pynew file mode 100644index 00000000..4c93bb1b--- /dev/null+++ b/app/assets/file_icons/build_icons.py@@ -0,0 +1,84 @@+"""从 SVG 源重新生成各平台文件图标 (.png/.ico/.icns)。++图标按"预渲染并提交"策略管理: SVG 是唯一可编辑源, 改动后跑这个脚本重生成并提交产物。+ QT_QPA_PLATFORM=offscreen python3 app/assets/file_icons/build_icons.py+"""++import os+import struct+import subprocess+import tempfile+from pathlib import Path++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++from PySide6.QtCore import QBuffer, QByteArray, QRectF+from PySide6.QtGui import QColor, QGuiApplication, QImage, QPainter+from PySide6.QtSvg import QSvgRenderer++HERE = Path(__file__).resolve().parent+STEMS = ("torrent", "m3u8")+ICO_SIZES = (16, 24, 32, 48, 64, 128, 256)+ICNS_SIZES = (16, 32, 64, 128, 256, 512, 1024)+ICNS_NAMES = {+ 16: ("icon_16x16.png",), 32: ("[email protected]", "icon_32x32.png"),+ 64: ("[email protected]",), 128: ("icon_128x128.png",),+ 256: ("[email protected]", "icon_256x256.png"),+ 512: ("[email protected]", "icon_512x512.png"), 1024: ("[email protected]",),+}+++def renderPng(svgPath: Path, size: int) -> bytes:+ renderer = QSvgRenderer(str(svgPath))+ image = QImage(size, size, QImage.Format.Format_ARGB32)+ image.fill(QColor(0, 0, 0, 0))+ painter = QPainter(image)+ renderer.render(painter, QRectF(0, 0, size, size))+ painter.end()++ storage = QByteArray()+ buffer = QBuffer(storage)+ buffer.open(QBuffer.OpenModeFlag.WriteOnly)+ image.save(buffer, "PNG")+ buffer.close()+ return bytes(storage)+++def writeIco(pngBySize: dict[int, bytes], outPath: Path) -> None:+ sizes = sorted(pngBySize)+ header = struct.pack("<HHH", 0, 1, len(sizes))+ entries = b""+ blobs = b""+ offset = 6 + 16 * len(sizes)+ for size in sizes:+ data = pngBySize[size]+ edge = 0 if size >= 256 else size # ICO 用 0 表示 256+ entries += struct.pack("<BBBBHHII", edge, edge, 0, 0, 1, 32, len(data), offset)+ offset += len(data)+ blobs += data+ outPath.write_bytes(header + entries + blobs)+++def writeIcns(svgPath: Path, outPath: Path) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ iconset = Path(tmp) / "icon.iconset"+ iconset.mkdir()+ for size in ICNS_SIZES:+ data = renderPng(svgPath, size)+ for name in ICNS_NAMES[size]:+ (iconset / name).write_bytes(data)+ subprocess.run(["iconutil", "-c", "icns", str(iconset), "-o", str(outPath)], check=True)+++def main() -> None:+ QGuiApplication([])+ for stem in STEMS:+ svgPath = HERE / f"{stem}.svg"+ (HERE / f"{stem}.png").write_bytes(renderPng(svgPath, 256))+ writeIco({size: renderPng(svgPath, size) for size in ICO_SIZES}, HERE / f"{stem}.ico")+ writeIcns(svgPath, HERE / f"{stem}.icns")+ print(f"generated {stem}.png / {stem}.ico / {stem}.icns")+++if __name__ == "__main__":+ main()diff --git a/app/assets/file_icons/m3u8.icns b/app/assets/file_icons/m3u8.icnsnew file mode 100644index 00000000..54bedae7Binary files /dev/null and b/app/assets/file_icons/m3u8.icns differdiff --git a/app/assets/file_icons/m3u8.ico b/app/assets/file_icons/m3u8.iconew file mode 100644index 00000000..6cbd2f22Binary files /dev/null and b/app/assets/file_icons/m3u8.ico differdiff --git a/app/assets/file_icons/m3u8.png b/app/assets/file_icons/m3u8.pngnew file mode 100644index 00000000..3b1199b6Binary files /dev/null and b/app/assets/file_icons/m3u8.png differdiff --git a/app/assets/file_icons/m3u8.svg b/app/assets/file_icons/m3u8.svgnew file mode 100644index 00000000..bfd78f9f--- /dev/null+++ b/app/assets/file_icons/m3u8.svg@@ -0,0 +1,46 @@+<svg width="256" height="256" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="fold" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#B6BEE6"/>+ <stop offset="1" stop-color="#8E9BD0"/>+ </linearGradient>+ <linearGradient id="page" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#FFFFFF"/>+ <stop offset="1" stop-color="#F2F4FB"/>+ </linearGradient>+ <linearGradient id="ghost" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#DBE0F4"/>+ <stop offset="1" stop-color="#C6CDEC"/>+ </linearGradient>+ <linearGradient id="glyph" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#6E7AC6"/>+ <stop offset="1" stop-color="#343B68"/>+ </linearGradient>+ <filter id="sh" x="-25%" y="-25%" width="150%" height="150%">+ <feDropShadow dx="0" dy="5" stdDeviation="7" flood-color="#4A5286" flood-opacity="0.22"/>+ </filter>+ <filter id="glow" x="-40%" y="-40%" width="180%" height="180%">+ <feDropShadow dx="0" dy="3" stdDeviation="3.5" flood-color="#2A2F52" flood-opacity="0.38"/>+ </filter>+ </defs>++ <!-- document page with folded top-right corner -->+ <g filter="url(#sh)">+ <path d="M58 40 a14 14 0 0 1 14 -14 h92 l40 40 v150+ a14 14 0 0 1 -14 14 H72 a14 14 0 0 1 -14 -14 Z" fill="url(#page)"/>+ <path d="M164 26 L204 66 L174 66 a10 10 0 0 1 -10 -10 Z" fill="url(#fold)"/>+ </g>++ <!-- faint ghost watermark -->+ <g transform="translate(50 44) scale(6.5)" opacity="0.4">+ <path d="M12 2C8.13 2 5 5.13 5 9V14C5 14.55 4.55 15 4 15H3V17H4.1C4.54 18.7 6.08 20 7.9 20C8.36 20 8.81 19.92 9.22 19.78C10.05 20.54 11.08 21 12.2 21C13.25 21 14.23 20.57 15 19.91C15.7 20.58 16.65 21 17.7 21C19.52 21 21 19.52 21 17.7V9C21 5.13 17.87 2 14 2H12Z" fill="url(#ghost)"/>+ <circle cx="9" cy="9.5" r="1.35" fill="#8088BE"/>+ <circle cx="15" cy="9.5" r="1.35" fill="#8088BE"/>+ </g>++ <!-- play glyph -->+ <g filter="url(#glow)">+ <path d="M120 148 L120 190 L160 169 Z"+ fill="url(#glyph)" stroke="url(#glyph)" stroke-width="12" stroke-linejoin="round"/>+ </g>+</svg>diff --git a/app/assets/file_icons/torrent.icns b/app/assets/file_icons/torrent.icnsnew file mode 100644index 00000000..37bf82a8Binary files /dev/null and b/app/assets/file_icons/torrent.icns differdiff --git a/app/assets/file_icons/torrent.ico b/app/assets/file_icons/torrent.iconew file mode 100644index 00000000..a6cd59b5Binary files /dev/null and b/app/assets/file_icons/torrent.ico differdiff --git a/app/assets/file_icons/torrent.png b/app/assets/file_icons/torrent.pngnew file mode 100644index 00000000..477b0267Binary files /dev/null and b/app/assets/file_icons/torrent.png differdiff --git a/app/assets/file_icons/torrent.svg b/app/assets/file_icons/torrent.svgnew file mode 100644index 00000000..54720426--- /dev/null+++ b/app/assets/file_icons/torrent.svg@@ -0,0 +1,52 @@+<svg width="256" height="256" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="fold" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#B6BEE6"/>+ <stop offset="1" stop-color="#8E9BD0"/>+ </linearGradient>+ <linearGradient id="page" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#FFFFFF"/>+ <stop offset="1" stop-color="#F2F4FB"/>+ </linearGradient>+ <linearGradient id="ghost" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#DBE0F4"/>+ <stop offset="1" stop-color="#C6CDEC"/>+ </linearGradient>+ <linearGradient id="glyph" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#6E7AC6"/>+ <stop offset="1" stop-color="#343B68"/>+ </linearGradient>+ <linearGradient id="silver" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#F4F6FD"/>+ <stop offset="1" stop-color="#C2CAEA"/>+ </linearGradient>+ <filter id="sh" x="-25%" y="-25%" width="150%" height="150%">+ <feDropShadow dx="0" dy="5" stdDeviation="7" flood-color="#4A5286" flood-opacity="0.22"/>+ </filter>+ <filter id="glow" x="-40%" y="-40%" width="180%" height="180%">+ <feDropShadow dx="0" dy="3" stdDeviation="3.5" flood-color="#2A2F52" flood-opacity="0.38"/>+ </filter>+ </defs>++ <!-- document page with folded top-right corner -->+ <g filter="url(#sh)">+ <path d="M58 40 a14 14 0 0 1 14 -14 h92 l40 40 v150+ a14 14 0 0 1 -14 14 H72 a14 14 0 0 1 -14 -14 Z" fill="url(#page)"/>+ <path d="M164 26 L204 66 L174 66 a10 10 0 0 1 -10 -10 Z" fill="url(#fold)"/>+ </g>++ <!-- faint ghost watermark -->+ <g transform="translate(50 44) scale(6.5)" opacity="0.4">+ <path d="M12 2C8.13 2 5 5.13 5 9V14C5 14.55 4.55 15 4 15H3V17H4.1C4.54 18.7 6.08 20 7.9 20C8.36 20 8.81 19.92 9.22 19.78C10.05 20.54 11.08 21 12.2 21C13.25 21 14.23 20.57 15 19.91C15.7 20.58 16.65 21 17.7 21C19.52 21 21 19.52 21 17.7V9C21 5.13 17.87 2 14 2H12Z" fill="url(#ghost)"/>+ <circle cx="9" cy="9.5" r="1.35" fill="#8088BE"/>+ <circle cx="15" cy="9.5" r="1.35" fill="#8088BE"/>+ </g>++ <!-- magnet glyph: indigo horseshoe + silver tips -->+ <g filter="url(#glow)">+ <path d="M110 190 V152 a22 22 0 0 1 44 0 V190"+ fill="none" stroke="url(#glyph)" stroke-width="20" stroke-linecap="butt"/>+ <rect x="100" y="180" width="20" height="16" rx="2" fill="url(#silver)"/>+ <rect x="144" y="180" width="20" height="16" rx="2" fill="url(#silver)"/>+ </g>+</svg>diff --git a/app/bases/interfaces.py b/app/bases/interfaces.pyindex 9b001659..1f1d4c0f 100644--- a/app/bases/interfaces.py+++ b/app/bases/interfaces.py@@ -13,9 +13,11 @@ if TYPE_CHECKING:@dataclass(frozen=True)-class ImportSource:- label: str+class FileType:extensions: tuple[str, ...]+ displayName: str+ mimeType: str+ icon: strclass Worker:@@ -45,7 +47,7 @@ class FeaturePack:from app.view.components.cards import UniversalResultCardreturn UniversalResultCard(task, parent)- def importSources(self) -> list[ImportSource]:+ def fileTypes(self) -> list[FileType]:return []def setup(self, mainWindow: "MainWindow"):diff --git a/app/services/feature_service.py b/app/services/feature_service.pyindex bf742d1f..75d136d1 100644--- a/app/services/feature_service.py+++ b/app/services/feature_service.py@@ -7,7 +7,7 @@ from urllib.parse import urlparsefrom loguru import logger-from app.bases.interfaces import FeaturePack, ImportSource+from app.bases.interfaces import FeaturePack, FileTypefrom app.bases.models import Taskfrom app.supports.paths import executableDir@@ -264,14 +264,14 @@ class FeatureService:logger.opt(exception=e).error("获取 FeaturePack 对话框设置项失败 {}", packName)return cards- def importSources(self) -> list[ImportSource]:- sources = []+ def fileTypes(self) -> list[FileType]:+ types = []for packName, packInstance in self._sortedPacks():try:- sources.extend(packInstance.importSources())+ types.extend(packInstance.fileTypes())except Exception as e:- logger.opt(exception=e).error("获取 FeaturePack 导入项失败 {}", packName)- return sources+ logger.opt(exception=e).error("获取 FeaturePack 文件类型失败 {}", packName)+ return typesdef load(self, mainWindow: "MainWindow"):logger.info("开始加载 FeaturePacks")diff --git a/app/supports/application.py b/app/supports/application.pyindex d64f3926..4bacacb1 100644--- a/app/supports/application.py+++ b/app/supports/application.py@@ -1,11 +1,13 @@import sys+from pathlib import Pathfrom signal import signal, SIGINTfrom PySide6.QtCore import QSharedMemory, QEvent+from PySide6.QtGui import QFileOpenEventfrom PySide6.QtWidgets import QApplicationfrom loguru import logger-from app.supports.config import cfg+from app.supports.config import cfg, DESKTOP_ID, DESKTOP_OBJECT_PATHfrom app.supports.signal_bus import signalBusif sys.platform == "darwin":@@ -22,30 +24,35 @@ class SingletonApplication(QApplication):def __init__(self, argv: list[str], key: str):super().__init__(argv)self.key = key+ self._lockSingleInstance()- # cleanup (only needed for unix)try:- cleanupMemory = QSharedMemory(key)+ signal(SIGINT, self._onInterrupt)+ except Exception as e:+ logger.warning(f"Failed to register SIGINT handler: {e}")++ if sys.platform == "darwin":+ self._setDockIconVisible(cfg.showDockIcon.value, activate=False)+ cfg.showDockIcon.valueChanged.connect(lambda visible: self._setDockIconVisible(visible, activate=True))+ if sys.platform == "linux":+ self._listenOnDesktopBus()++ def _lockSingleInstance(self) -> None:+ # 清掉 unix 上崩溃残留的共享内存段+ try:+ cleanupMemory = QSharedMemory(self.key)if cleanupMemory.attach():cleanupMemory.detach()except Exception as e:logger.warning(f"Failed to cleanup shared memory: {e}")self.memory = QSharedMemory()- self.memory.setKey(key)-- if self.memory.attach():- if sys.platform == "win32":- import win32gui-- hWnd = win32gui.FindWindow(None, "Ghost Downloader")-- # 发送自定义信息唤醒窗口- # WM_CUSTOM = win32con.WM_USER + 1- # win32gui.SendMessage(hWnd, WM_CUSTOM, 0, 0)- win32gui.SendMessage(hWnd, 1024 + 1, 0, 0)- win32gui.SetForegroundWindow(hWnd)+ self.memory.setKey(self.key)+ if self.memory.attach(): # attach 成功即已有实例: 转交本次启动后自退+ if sys.platform in ("win32", "linux"):+ from app.supports.file_open import sendToRunningInstance+ sendToRunningInstance()sys.exit(-1)if not self.memory.create(1):@@ -60,14 +67,26 @@ class SingletonApplication(QApplication):logger.opt(exception=e).error("Failed to recover from shared memory error")raise RuntimeError(self.memory.errorString())+ def _unlockSingleInstance(self) -> None:try:- signal(SIGINT, self._handleInterruptSignal)+ if self.memory.isAttached():+ self.memory.detach()except Exception as e:- logger.warning(f"Failed to register SIGINT handler: {e}")+ logger.warning(f"Failed to cleanup shared memory: {e}")- if sys.platform == "darwin":- self._setDockIconVisible(cfg.showDockIcon.value, activate=False)- cfg.showDockIcon.valueChanged.connect(lambda visible: self._setDockIconVisible(visible, activate=True))+ def exec(self):+ try:+ return super().exec()+ finally:+ self._unlockSingleInstance()++ def quit(self):+ self._unlockSingleInstance()+ super().quit()++ def _onInterrupt(self, _signum, _frame):+ logger.error("KeyboardInterrupt, quitting application")+ self.quit()def _setDockIconVisible(self, visible: bool, activate: bool = False):if sys.platform != "darwin":@@ -83,32 +102,28 @@ class SingletonApplication(QApplication):if activate:app.activateIgnoringOtherApps_(True)- def _handleInterruptSignal(self, _signum, _frame):- logger.error("KeyboardInterrupt, quitting application")- self.quit()+ def _listenOnDesktopBus(self) -> None:+ from PySide6.QtDBus import QDBusConnection+ from app.supports.file_open import DesktopBusReceiver- # exit: cleanup shared memory- def exec(self):- try:- return super().exec()- finally:- try:- if self.memory.isAttached():- self.memory.detach()- except Exception as e:- logger.warning(f"Failed to cleanup shared memory on exit: {e}")-- def quit(self):- try:- if self.memory.isAttached():- self.memory.detach()- except Exception as e:- logger.warning(f"Failed to cleanup shared memory on quit: {e}")- super().quit()+ bus = QDBusConnection.sessionBus()+ if not bus.registerService(DESKTOP_ID):+ return+ self._dbusObject = DesktopBusReceiver()+ bus.registerObject(+ DESKTOP_OBJECT_PATH,+ self._dbusObject,+ QDBusConnection.RegisterOption.ExportAllSlots,+ )def event(self, e: QEvent) -> bool:- if sys.platform == "darwin":- if e.type() == QEvent.Type.ApplicationActivate:- signalBus.showMainWindow.emit()+ if isinstance(e, QFileOpenEvent):+ uri = e.url().toString() if not e.url().isEmpty() else Path(e.file()).as_uri()+ if uri:+ signalBus.openFileRequested.emit([uri])+ return True++ if sys.platform == "darwin" and e.type() == QEvent.Type.ApplicationActivate:+ signalBus.showMainWindow.emit()return super().event(e)diff --git a/app/supports/config.py b/app/supports/config.pyindex abf584d7..d0ee4c8b 100644--- a/app/supports/config.py+++ b/app/supports/config.py@@ -345,7 +345,10 @@ class Config(QConfig):YEAR = 2026AUTHOR = "XiaoYouChR"-VERSION = "3.10.1"+VERSION = "3.10"+# freedesktop 应用 id: D-Bus 总线名 + Linux .desktop/.service 文件名 (DBusActivatable 要求两者一致)+DESKTOP_ID = "io.github.xiaoyouchr.GhostDownloader"+DESKTOP_OBJECT_PATH = "/" + DESKTOP_ID.replace(".", "/") # D-Bus 对象路径: app id 点换斜杠LATEST_EXTENSION_VERSION = "1.4.0"AUTHOR_URL = "https://space.bilibili.com/437313511"FEEDBACK_URL = "https://github.com/XiaoYouChR/Ghost-Downloader-3/issues"diff --git a/app/supports/file_association.py b/app/supports/file_association.pynew file mode 100644index 00000000..5d2d59d3--- /dev/null+++ b/app/supports/file_association.py@@ -0,0 +1,180 @@+import subprocess+import sys+from pathlib import Path++from loguru import logger+from PySide6.QtCore import QCoreApplication++from app.bases.interfaces import FileType+from app.supports.config import DESKTOP_ID+from app.supports.paths import executableDir++if sys.platform == "win32":+ import winreg++DESKTOP_DIR = Path.home() / ".local/share/applications"+DBUS_SERVICE_DIR = Path.home() / ".local/share/dbus-1/services"+++def register(fileTypes: list[FileType]) -> None:+ if not fileTypes:+ return+ try:+ if sys.platform == "win32":+ _registerWindows(fileTypes)+ elif sys.platform == "linux":+ _applyLinuxAssociation(_linuxMimes() | {ft.mimeType for ft in fileTypes})+ except Exception as e:+ logger.opt(exception=e).error("注册文件关联失败")+++def unregister(fileTypes: list[FileType]) -> None:+ if not fileTypes:+ return+ try:+ if sys.platform == "win32":+ _unregisterWindows(fileTypes)+ elif sys.platform == "linux":+ _applyLinuxAssociation(_linuxMimes() - {ft.mimeType for ft in fileTypes})+ except Exception as e:+ logger.opt(exception=e).error("取消文件关联失败")+++def iconFile(name: str, extension: str) -> Path:+ return executableDir / "app" / "assets" / "file_icons" / f"{name}.{extension}"+++# Windows 文件关联写在 per-user 的 HKCU\Software\Classes, 免管理员权限++def _progId(extension: str) -> str:+ return f"GhostDownloader{extension}"+++def _registerWindows(fileTypes: list[FileType]) -> None:+ command = f'"{QCoreApplication.applicationFilePath().replace("/", chr(92))}" "%1"'+ for fileType in fileTypes:+ icon = str(iconFile(fileType.icon, "ico")).replace("/", "\\")+ for extension in fileType.extensions:+ progId = _progId(extension)+ _writeKey(rf"Software\Classes\{progId}", fileType.displayName)+ _writeKey(rf"Software\Classes\{progId}\DefaultIcon", icon)+ _writeKey(rf"Software\Classes\{progId}\shell\open\command", command)+ _writeKey(rf"Software\Classes\{extension}", progId)+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, rf"Software\Classes\{extension}\OpenWithProgids") as key:+ winreg.SetValueEx(key, progId, 0, winreg.REG_NONE, b"")+ _announceAssociationChange()+++def _unregisterWindows(fileTypes: list[FileType]) -> None:+ for fileType in fileTypes:+ for extension in fileType.extensions:+ progId = _progId(extension)+ _deleteTree(rf"Software\Classes\{progId}")+ _deleteValue(rf"Software\Classes\{extension}\OpenWithProgids", progId)+ # 默认值是别人时不要动, 只清掉确实是我们写的那个+ if _keyDefault(rf"Software\Classes\{extension}") == progId:+ _deleteValue(rf"Software\Classes\{extension}", "")+ _announceAssociationChange()+++def _writeKey(path: str, value: str) -> None:+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, path) as key:+ winreg.SetValueEx(key, "", 0, winreg.REG_SZ, value)+++def _keyDefault(path: str) -> str | None:+ try:+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as key:+ return winreg.QueryValueEx(key, "")[0]+ except FileNotFoundError:+ return None+++def _deleteValue(path: str, name: str) -> None:+ try:+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_SET_VALUE) as key:+ winreg.DeleteValue(key, name)+ except FileNotFoundError:+ pass+++def _deleteTree(path: str) -> None:+ try:+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_ALL_ACCESS) as key:+ while True:+ try:+ child = winreg.EnumKey(key, 0)+ except OSError:+ break+ _deleteTree(rf"{path}\{child}")+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, path)+ except FileNotFoundError:+ pass+++def _announceAssociationChange() -> None:+ import ctypes++ SHCNE_ASSOCCHANGED = 0x08000000+ ctypes.windll.shell32.SHChangeNotify(SHCNE_ASSOCCHANGED, 0, None, None)+++# Linux 文件关联写在 ~/.local/share 下的 .desktop + xdg-mime, 免 root++def _desktopPath() -> Path:+ return DESKTOP_DIR / f"{DESKTOP_ID}.desktop"+++def _linuxMimes() -> set[str]:+ path = _desktopPath()+ if not path.exists():+ return set()+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.startswith("MimeType="):+ return {mime for mime in line[len("MimeType="):].split(";") if mime}+ return set()+++def _applyLinuxAssociation(mimes: set[str]) -> None:+ path = _desktopPath()+ if not mimes:+ path.unlink(missing_ok=True)+ (DBUS_SERVICE_DIR / f"{DESKTOP_ID}.service").unlink(missing_ok=True)+ _refreshLinuxDatabases()+ return++ DESKTOP_DIR.mkdir(parents=True, exist_ok=True)+ DBUS_SERVICE_DIR.mkdir(parents=True, exist_ok=True)+ mimeLine = ";".join(sorted(mimes)) + ";"+ path.write_text(+ "[Desktop Entry]\n"+ "Type=Application\n"+ "Name=Ghost Downloader\n"+ f"Exec={QCoreApplication.applicationFilePath()} %F\n"+ "Icon=ghost-downloader\n"+ "Terminal=false\n"+ "Categories=Network;Utility;\n"+ "DBusActivatable=true\n"+ f"MimeType={mimeLine}\n",+ encoding="utf-8",+ )+ (DBUS_SERVICE_DIR / f"{DESKTOP_ID}.service").write_text(+ "[D-BUS Service]\n"+ f"Name={DESKTOP_ID}\n"+ f"Exec={QCoreApplication.applicationFilePath()}\n",+ encoding="utf-8",+ )+ _refreshLinuxDatabases()+ for mime in mimes:+ _run(["xdg-mime", "default", f"{DESKTOP_ID}.desktop", mime])+++def _refreshLinuxDatabases() -> None:+ _run(["update-desktop-database", str(DESKTOP_DIR)])+++def _run(args: list[str]) -> None:+ try:+ subprocess.run(args, check=False, capture_output=True)+ except FileNotFoundError:+ logger.warning("缺少命令, 跳过: {}", args[0])diff --git a/app/supports/file_open.py b/app/supports/file_open.pynew file mode 100644index 00000000..4e46c524--- /dev/null+++ b/app/supports/file_open.py@@ -0,0 +1,90 @@+"""跨实例打开文件的传输层: 第二个实例把本次启动交给运行中的实例 (sendToRunningInstance);+运行中的实例从 argv / WM_COPYDATA / D-Bus 收下, 归一成 file:// URI 经 signalBus 投递。+"""++import sys+from pathlib import Path++from app.supports.signal_bus import signalBus++COPYDATA_OPEN_FILES = 0x4744+++def fileUrisFromArgv(argv: list[str]) -> list[str]:+ # 归一成 file:// URI: 裸路径会被 featureService._toUrl 当成 http:// 而失效+ uris = []+ for arg in argv[1:]:+ if arg.startswith("-"):+ continue+ path = Path(arg)+ if path.is_file():+ uris.append(path.resolve().as_uri())+ return uris+++if sys.platform == "win32":+ import ctypes+ import win32gui+ from ctypes import wintypes++ WM_COPYDATA = 0x004A+ WM_USER_WAKE = 1024 + 1++ class _CopyDataStruct(ctypes.Structure):+ _fields_ = [+ ("dwData", ctypes.c_void_p),+ ("cbData", wintypes.DWORD),+ ("lpData", ctypes.c_void_p),+ ]++ def sendToRunningInstance() -> None:+ hWnd = win32gui.FindWindow(None, "Ghost Downloader")+ if not hWnd:+ return+ uris = fileUrisFromArgv(sys.argv)+ if uris:+ # WM_COPYDATA 要传结构体指针, 只能走 ctypes+ blob = "\n".join(uris).encode("utf-16-le") + b"\x00\x00"+ data = ctypes.create_string_buffer(blob, len(blob))+ payload = _CopyDataStruct(COPYDATA_OPEN_FILES, len(blob), ctypes.cast(data, ctypes.c_void_p))+ ctypes.windll.user32.SendMessageW(hWnd, WM_COPYDATA, 0, ctypes.byref(payload))+ else:+ win32gui.SendMessage(hWnd, WM_USER_WAKE, 0, 0)+ win32gui.SetForegroundWindow(hWnd)++ def fileUrisFromCopyData(lParam: int) -> list[str]:+ payload = _CopyDataStruct.from_address(lParam)+ if payload.dwData != COPYDATA_OPEN_FILES:+ return []+ raw = ctypes.string_at(payload.lpData, payload.cbData)+ return [line for line in raw.decode("utf-16-le").rstrip("\x00").split("\n") if line]+++if sys.platform == "linux":+ from PySide6.QtCore import QObject, Slot, ClassInfo++ from app.supports.config import DESKTOP_ID, DESKTOP_OBJECT_PATH++ @ClassInfo({"D-Bus Interface": "org.freedesktop.Application"})+ class DesktopBusReceiver(QObject):+ @Slot("QStringList", "QVariantMap")+ def Open(self, uris, platformData):+ uris = [uri for uri in uris if uri]+ if uris:+ signalBus.openFileRequested.emit(uris)++ @Slot("QVariantMap")+ def Activate(self, platformData):+ signalBus.showMainWindow.emit()++ def sendToRunningInstance() -> None:+ from PySide6.QtDBus import QDBusConnection, QDBusInterface++ uris = fileUrisFromArgv(sys.argv)+ interface = QDBusInterface(+ DESKTOP_ID, DESKTOP_OBJECT_PATH, "org.freedesktop.Application", QDBusConnection.sessionBus()+ )+ if uris:+ interface.call("Open", uris, {})+ else:+ interface.call("Activate", {})diff --git a/app/supports/signal_bus.py b/app/supports/signal_bus.pyindex 0716f019..16f2f758 100644--- a/app/supports/signal_bus.py+++ b/app/supports/signal_bus.py@@ -6,6 +6,7 @@ class SignalBus(QObject):catchException = Signal(str)showMainWindow = Signal()+ openFileRequested = Signal(list)signalBus = SignalBus()diff --git a/app/view/components/add_task_dialog.py b/app/view/components/add_task_dialog.pyindex a56a3b53..29399d17 100644--- a/app/view/components/add_task_dialog.py+++ b/app/view/components/add_task_dialog.py@@ -210,8 +210,8 @@ class AddTaskDialog(MessageBoxBase):for card in featureService.dialogCards(self.settingGroup):self.settingGroup.addCard(card)- self._importSources = featureService.importSources()- self.importButton.setVisible(bool(self._importSources))+ self._fileTypes = featureService.fileTypes()+ self.importButton.setVisible(bool(self._fileTypes))def _initLayout(self) -> None:self.headerLayout.addWidget(self.titleLabel)@@ -315,9 +315,12 @@ class AddTaskDialog(MessageBoxBase):return [line.strip() for line in text.splitlines() if line.strip()]def _onImportClicked(self) -> None:- allExtensions = [ext for source in self._importSources for ext in source.extensions]- nameFilters = [self.tr("所有可导入文件 ({0})").format(" ".join(allExtensions))]- nameFilters += [f"{source.label} ({' '.join(source.extensions)})" for source in self._importSources]+ globs = [f"*{ext}" for fileType in self._fileTypes for ext in fileType.extensions]+ nameFilters = [self.tr("所有可导入文件 ({0})").format(" ".join(globs))]+ nameFilters += [+ "{0} ({1})".format(fileType.displayName, " ".join(f"*{ext}" for ext in fileType.extensions))+ for fileType in self._fileTypes+ ]paths, _ = QFileDialog.getOpenFileNames(self, self.tr("导入文件"), "", ";;".join(nameFilters))if not paths:diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.pyindex 9dc23408..8b02921c 100644--- a/app/view/pages/setting_page.py+++ b/app/view/pages/setting_page.py@@ -12,7 +12,7 @@ from qfluentwidgets import RangeSettingCard, FluentIcon, SwitchSettingCard, Pushfrom app.services.browser_service import BrowserServicefrom app.supports.config import cfg, EDGE_ADDONS_URL, FIREFOX_ADDONS_URL, AUTHOR_URL, AUTHOR, YEAR, \- VERSION, FEEDBACK_URL+ VERSION, FEEDBACK_URL, DESKTOP_IDfrom app.supports.utils import openAppLogFolderfrom app.view.components.category_settings import CategoryRulesCardfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup@@ -502,30 +502,26 @@ class SettingPage(ScrollArea):f"/Users/{getpwuid(os.getuid()).pw_name}/Library/LaunchAgents/com.xiaoyouchr.ghostdownloader.plist")elif sys.platform == "linux":- from getpass import getuser+ autoStartDir = Path.home() / ".config/autostart"+ desktopFile = autoStartDir / f"{DESKTOP_ID}.desktop"+ legacyFile = autoStartDir / "gd3.desktop" # 旧版固定名, 迁移时一并清掉if value:- autoStartPath = Path(f"/home/{getuser()}/.config/autostart/")- if not autoStartPath.exists():- autoStartPath.mkdir(parents=True, exist_ok=True)-- with open(- f"/home/{getuser()}/.config/autostart/gd3.desktop",- "w",+ autoStartDir.mkdir(parents=True, exist_ok=True)+ desktopFile.write_text(+ "[Desktop Entry]\n"+ "Type=Application\n"+ f"Version={VERSION}\n"+ "Name=Ghost Downloader 3\n"+ "Comment=A multi-threading downloader with QThread based on PySide6\n"+ f'Exec="{QCoreApplication.applicationFilePath()}" --silence\n'+ "StartupNotify=false\n"+ "Terminal=false\n",encoding="utf-8",- ) as f:- _ = f"""[Desktop Entry]- Type=Application- Version={VERSION}- Name=Ghost Downloader 3- Comment=A multi-threading downloader with QThread based on PySide6- Exec="{QCoreApplication.applicationFilePath()}" --silence- StartupNotify=false- Terminal=false- """- f.write(_)- f.flush()+ )+ legacyFile.unlink(missing_ok=True)else:- os.remove(f"/home/{getuser()}/.config/autostart/gd3.desktop")+ desktopFile.unlink(missing_ok=True)+ legacyFile.unlink(missing_ok=True)else:InfoBar.warning(diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.pyindex ddfd5328..6bde2d27 100644--- a/app/view/windows/main_window.py+++ b/app/view/windows/main_window.py@@ -21,6 +21,7 @@ from app.supports.config import cfg, defaultHeaders, AUTHOR_URL, VERSION, FEEDBAfrom app.services.task_service import taskServicefrom app.supports.signal_bus import signalBusfrom app.supports.update import checkUpdate, UpdateState+from app.supports.file_open import fileUrisFromArgvfrom app.supports.utils import getProxies, bringWindowToTop, showMessageBox, deduplicateFilename, openAppLogFolderfrom app.view.components.add_task_dialog import AddTaskDialogfrom app.view.components.labels import IconBodyLabel@@ -76,6 +77,8 @@ class MainWindow(MSFluentWindow):self.tray.show()self.connectSignalToSlot()+ # argv 里的文件延到事件循环: 此时 featurePacks 已加载, 也不会在构造期卡死在模态框+ QTimer.singleShot(0, lambda: signalBus.openFileRequested.emit(fileUrisFromArgv(sys.argv)))self._updateClipboardListener()self._toggleTheme(cfg.customThemeMode.value, triggeredByUser=True)self.updateThemeColor()@@ -86,6 +89,7 @@ class MainWindow(MSFluentWindow):def connectSignalToSlot(self):signalBus.showMainWindow.connect(lambda: bringWindowToTop(self))signalBus.catchException.connect(self._onExceptionCaught)+ signalBus.openFileRequested.connect(self.onOpenFileRequested)cfg.enableClipboardListener.valueChanged.connect(self._updateClipboardListener)cfg.customThemeMode.valueChanged.connect(lambda value: self._toggleTheme(value, triggeredByUser=True)@@ -291,6 +295,12 @@ class MainWindow(MSFluentWindow):)self.addSubInterface(self.settingPage, FluentIcon.SETTING, self.tr("设置"), position=NavigationItemPosition.BOTTOM)+ def onOpenFileRequested(self, uris: list[str]):+ if not uris:+ return+ bringWindowToTop(self)+ self.showAddTaskDialog(urls=uris)+def showAddTaskDialog(self,triggeredByUser: bool = False,@@ -360,10 +370,17 @@ class MainWindow(MSFluentWindow):from ctypes.wintypes import MSGmsg = MSG.from_address(message.__int__())- # WIN_USER = 1024- if msg.message == 1024 + 1:+ if msg.message == 1024 + 1: # WM_USER+1: 第二实例的唤醒请求bringWindowToTop(self)return True, 0+ # Win11 不打 isWin10 的 acrylic 补丁, WM_COPYDATA 只能在基类这条路接收+ if msg.message == 0x004A:+ from app.supports.file_open import fileUrisFromCopyData+ uris = fileUrisFromCopyData(msg.lParam)+ if uris:+ signalBus.openFileRequested.emit(uris)+ bringWindowToTop(self)+ return True, 1return super().nativeEvent(eventType, message)@@ -511,6 +528,13 @@ if isWin10():elif msg.message == 1024 + 1:bringWindowToTop(self)return True, 0+ elif msg.message == 0x004A: # WM_COPYDATA: 第二实例转发来的待打开 URI+ from app.supports.file_open import fileUrisFromCopyData+ uris = fileUrisFromCopyData(msg.lParam)+ if uris:+ signalBus.openFileRequested.emit(uris)+ bringWindowToTop(self)+ return True, 1return FramelessWindow.nativeEvent(self, eventType, message)diff --git a/deploy.py b/deploy.pyindex 281c936a..0d7c142c 100644--- a/deploy.py+++ b/deploy.py@@ -1,3 +1,4 @@+import plistlibimport shutilimport subprocessimport sys@@ -6,6 +7,13 @@ from pathlib import Pathfrom app.supports.config import VERSION, YEAR, AUTHORFEATURES_ROOT = Path("features")+FILE_ICONS_DIR = Path("app/assets/file_icons")+# macOS 文件关联只能构建时烘进 Info.plist; 这份清单镜像各 pack 的 fileTypes(), 改 pack 时同步+MACOS_DOCUMENT_TYPES = [+ {"name": "种子文件", "extensions": ["torrent"], "icon": "torrent"},+ {"name": "M3U8 播放列表", "extensions": ["m3u8", "m3u"], "icon": "m3u8"},+ {"name": "DASH 清单", "extensions": ["mpd"], "icon": "m3u8"},+]FEATURE_PACK_BLACKLIST = {"jack_yao"}COMMON_INCLUDE_PACKAGES = ["urllib3",@@ -49,6 +57,8 @@ def build_args() -> list[str]:# '--show-memory' ,# '--show-progress' ,'--windows-icon-from-ico=app/assets/logo.ico',+ # 注册表 DefaultIcon 指向磁盘上的 .ico, 所以图标必须作为实体文件随包发出 (不能只进 qrc)+ '--include-data-dir=app/assets/file_icons=app/assets/file_icons','--company-name=XiaoYouChR','--product-name="Ghost Downloader"',f'--file-version={VERSION}',@@ -84,6 +94,8 @@ def build_args() -> list[str]:'--plugin-enable=pyside6',*build_include_args(),'--include-qt-plugins=platforms',+ # 文件关联的 D-Bus 激活接收器懒加载 QtDBus, 显式带上确保进包+ '--include-module=PySide6.QtDBus','--assume-yes-for-downloads',# '--show-memory',# '--show-progress',@@ -134,6 +146,34 @@ def copy_feature_packs() -> None:print(f"Copied FeaturePacks to {target_root}: {[source.name for source in feature_pack_sources]}")+def patch_macos_app() -> None:+ appBundle = Path("dist") / "Ghost-Downloader-3.app"+ plistPath = appBundle / "Contents" / "Info.plist"+ resourcesDir = appBundle / "Contents" / "Resources"+ resourcesDir.mkdir(parents=True, exist_ok=True)++ documentTypes = []+ for entry in MACOS_DOCUMENT_TYPES:+ shutil.copy(FILE_ICONS_DIR / f"{entry['icon']}.icns", resourcesDir / f"{entry['icon']}.icns")+ documentTypes.append(+ {+ "CFBundleTypeName": entry["name"],+ "CFBundleTypeRole": "Viewer",+ "CFBundleTypeExtensions": entry["extensions"],+ "CFBundleTypeIconFile": f"{entry['icon']}.icns",+ "LSHandlerRank": "Alternate",+ }+ )++ with open(plistPath, "rb") as f:+ plist = plistlib.load(f)+ plist["CFBundleDocumentTypes"] = documentTypes+ with open(plistPath, "wb") as f:+ plistlib.dump(plist, f)++ print(f"Patched Info.plist with {len(documentTypes)} document types")++def main() -> int:args = build_args()command = ' '.join(args)@@ -145,6 +185,9 @@ def main() -> int:copy_feature_packs()+ if sys.platform == "darwin":+ patch_macos_app()+return 0diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex 862e7b0c..8c805da8 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -1,3 +1,4 @@+import sysfrom typing import TYPE_CHECKINGfrom qfluentwidgets import (@@ -53,6 +54,7 @@ class BitTorrentConfig(PackConfig):saveMagnetTorrentFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())+ associateFileTypes = ConfigItem("BitTorrent", "AssociateFileTypes", False, BoolValidator())webTrackerSources = ConfigItem("BitTorrent","WebTrackerSources",@@ -228,6 +230,17 @@ class BitTorrentConfig(PackConfig):):self.bittorrentGroup.addSettingCard(card)+ # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示+ if sys.platform != "darwin":+ self.associateCard = SwitchSettingCard(+ FluentIcon.LINK,+ self.tr("关联 .torrent 文件"),+ self.tr("把 .torrent 文件的打开方式设为 Ghost Downloader"),+ self.associateFileTypes,+ self.bittorrentGroup,+ )+ self.bittorrentGroup.addSettingCard(self.associateCard)+settingPage.addSettingGroup(self.bittorrentGroup)diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex 674a26ac..3675a4bb 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -2,9 +2,10 @@ from urllib.parse import urlparsefrom loguru import logger-from app.bases.interfaces import FeaturePack, ImportSource+from app.bases.interfaces import FeaturePack, FileTypefrom app.bases.models import Taskfrom app.services.core_service import coreService+from app.supports import file_associationfrom .cards import BitTorrentResultCard, BTTaskCardfrom .config import bittorrentConfigfrom .loaders import loadLocalTorrent, resolve as _btResolve@@ -30,11 +31,21 @@ class BitTorrentPack(FeaturePack):config = bittorrentConfigdef setup(self, mainWindow):+ if bittorrentConfig.associateFileTypes.value:+ file_association.register(self.fileTypes())+ bittorrentConfig.associateFileTypes.valueChanged.connect(self._onAssociationToggled)+if webTrackerService.mergedTrackers():returncoreService.runCoroutine(webTrackerService.refresh(), self._onTrackersLoaded)+ def _onAssociationToggled(self, enabled: bool):+ if enabled:+ file_association.register(self.fileTypes())+ else:+ file_association.unregister(self.fileTypes())+def matches(self, url: str) -> bool:return _isTorrentUrl(url)@@ -47,8 +58,15 @@ class BitTorrentPack(FeaturePack):def resultCard(self, task, parent=None):return BitTorrentResultCard(task, parent)- def importSources(self):- return [ImportSource(label=self.tr("种子文件"), extensions=("*.torrent",))]+ def fileTypes(self):+ return [+ FileType(+ extensions=(".torrent",),+ displayName=self.tr("种子文件"),+ mimeType="application/x-bittorrent",+ icon="torrent",+ )+ ]def _onTrackersLoaded(self, result, error: str | None):if error:diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 031981e5..d61f697b 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -1,4 +1,5 @@import asyncio+import sysfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -157,6 +158,7 @@ class M3U8Config(PackConfig):liveRealTimeMerge = ConfigItem("M3U8", "LiveRealTimeMerge", False, BoolValidator())liveKeepSegments = ConfigItem("M3U8", "LiveKeepSegments", False, BoolValidator())livePipeMux = ConfigItem("M3U8", "LivePipeMux", False, BoolValidator())+ associateFileTypes = ConfigItem("M3U8", "AssociateFileTypes", False, BoolValidator())def setupSettings(self, settingPage: "SettingPage"):self.m3u8Group = CollapsibleSettingCardGroup(self.tr("流媒体下载"), "m3u8", settingPage.container)@@ -255,7 +257,6 @@ class M3U8Config(PackConfig):self.livePipeMux,self.m3u8Group,)-self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())for card in (@@ -276,6 +277,17 @@ class M3U8Config(PackConfig):):self.m3u8Group.addSettingCard(card)+ # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示+ if sys.platform != "darwin":+ self.associateCard = SwitchSettingCard(+ FluentIcon.LINK,+ self.tr("关联 M3U8/MPD 文件"),+ self.tr("把 .m3u8/.m3u/.mpd 文件的打开方式设为 Ghost Downloader"),+ self.associateFileTypes,+ self.m3u8Group,+ )+ self.m3u8Group.addSettingCard(self.associateCard)+settingPage.addSettingGroup(self.m3u8Group)self.runtimeCard.refreshStatus()diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 1c8dbc40..d76a9084 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -10,8 +10,9 @@ from urllib.request import url2pathnameimport niquests-from app.bases.interfaces import FeaturePack, ImportSource+from app.bases.interfaces import FeaturePack, FileTypefrom app.bases.models import Task+from app.supports import file_associationfrom app.supports.config import activeUserAgent, cfg, defaultHeadersfrom app.supports.utils import getProxies, splitCookies, toExecutable, toSafeFilenamefrom app.view.components.cards import UniversalTaskCard@@ -119,8 +120,21 @@ class M3U8Pack(FeaturePack):loweredUrl = url.lower()return ".m3u" in loweredUrl or ".mpd" in loweredUrl- def importSources(self):- return [ImportSource(label=self.tr("M3U8/MPD 清单"), extensions=("*.m3u8", "*.m3u", "*.mpd"))]+ def fileTypes(self):+ return [+ FileType(+ extensions=(".m3u8", ".m3u"),+ displayName=self.tr("M3U8 播放列表"),+ mimeType="application/vnd.apple.mpegurl",+ icon="m3u8",+ ),+ FileType(+ extensions=(".mpd",),+ displayName=self.tr("DASH 清单"),+ mimeType="application/dash+xml",+ icon="m3u8",+ ),+ ]def taskCard(self, task, parent=None):from disk_pack.task import InstallTask@@ -131,6 +145,17 @@ class M3U8Pack(FeaturePack):def resultCard(self, task, parent=None):return M3U8ResultCard(task, parent)+ def setup(self, mainWindow):+ if m3u8Config.associateFileTypes.value:+ file_association.register(self.fileTypes())+ m3u8Config.associateFileTypes.valueChanged.connect(self._onAssociationToggled)++ def _onAssociationToggled(self, enabled: bool):+ if enabled:+ file_association.register(self.fileTypes())+ else:+ file_association.unregister(self.fileTypes())+async def parse(self, payload: dict) -> Task:url = payload["url"].strip()rawHeaders = payload.get("headers")