The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(cli): 设置里可安装命令行工具 ghd
XiaoYouChRf76bd48b1599
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex f4c6158a..20b3ab2e 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -183,6 +183,14 @@ jobs:cmake --build build-updater --config ReleaseCopy-Item build-updater/Release/updater.exe dist/Ghost-Downloader-3.dist/+ - name: Build ghd+ shell: pwsh+ run: |+ cmake -B build-ghd -G "Visual Studio 17 2022" -A x64 tools/ghd+ cmake --build build-ghd --config Release+ New-Item -ItemType Directory -Force dist/Ghost-Downloader-3.dist/bin+ Copy-Item build-ghd/Release/ghd.exe dist/Ghost-Downloader-3.dist/bin/+- name: Download HDiffPatchshell: pwshrun: |diff --git a/app/i18n.py b/app/i18n.pyindex 952406bc..7c4e9377 100644--- a/app/i18n.py+++ b/app/i18n.py@@ -28,6 +28,8 @@ N("TaskErrors", "{name} 未安装,请在设置中安装")N("TaskErrors", "无法获取版本信息")N("TaskErrors", "校验失败")N("TaskErrors", "当前平台无可用更新")+N("TaskErrors", "{path} 已被其他文件占用")+N("TaskErrors", "未获得管理员授权")N("TaskErrors", "DMG 中未找到 .app")N("TaskErrors", "端口 {port} 被占用,请更换端口")diff --git a/app/platform/cli_install.py b/app/platform/cli_install.pynew file mode 100644index 00000000..6eb8ac15--- /dev/null+++ b/app/platform/cli_install.py@@ -0,0 +1,82 @@+from __future__ import annotations++import asyncio+import shlex+import sys+from pathlib import Path++from app.config.paths import EXECUTABLE_DIR, EXECUTABLE_PATH+from app.models.task import TaskError++LINK_PATH = Path("/usr/local/bin/ghd") if sys.platform == "darwin" else Path.home() / ".local/bin/ghd"+BIN_FOLDER = str(EXECUTABLE_DIR / "bin")+++def isInstalled() -> bool:+ if sys.platform == "win32":+ return BIN_FOLDER.lower() in (entry.lower() for entry in loadUserPath()[0].split(";"))+ return LINK_PATH.is_symlink() and LINK_PATH.resolve() == EXECUTABLE_PATH.resolve()+++async def install() -> None:+ if sys.platform == "win32":+ path, kind = loadUserPath()+ if not isInstalled():+ await asyncio.to_thread(saveUserPath, ";".join(entry for entry in (path, BIN_FOLDER) if entry), kind)+ return+ if LINK_PATH.exists() and not LINK_PATH.is_symlink():+ raise TaskError("{path} 已被其他文件占用", path=LINK_PATH)+ try:+ LINK_PATH.parent.mkdir(parents=True, exist_ok=True)+ LINK_PATH.unlink(missing_ok=True)+ LINK_PATH.symlink_to(EXECUTABLE_PATH)+ except PermissionError:+ if sys.platform != "darwin":+ raise+ await runAsAdministrator(f"mkdir -p {shlex.quote(str(LINK_PATH.parent))} && "+ f"ln -sfn {shlex.quote(str(EXECUTABLE_PATH))} {shlex.quote(str(LINK_PATH))}")+++async def delete() -> None:+ if sys.platform == "win32":+ path, kind = loadUserPath()+ entries = [entry for entry in path.split(";") if entry.lower() != BIN_FOLDER.lower()]+ await asyncio.to_thread(saveUserPath, ";".join(entries), kind)+ return+ if not LINK_PATH.is_symlink():+ return+ try:+ LINK_PATH.unlink()+ except PermissionError:+ if sys.platform != "darwin":+ raise+ await runAsAdministrator(f"rm -f {shlex.quote(str(LINK_PATH))}")+++async def runAsAdministrator(command: str) -> None:+ script = command.replace("\\", "\\\\").replace('"', '\\"')+ process = await asyncio.create_subprocess_exec(+ "osascript", "-e", f'do shell script "{script}" with administrator privileges',+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,+ )+ if await process.wait() != 0:+ raise TaskError("未获得管理员授权")+++def loadUserPath() -> tuple[str, int]:+ import winreg+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:+ try:+ return winreg.QueryValueEx(key, "Path")+ except FileNotFoundError:+ return "", winreg.REG_EXPAND_SZ+++def saveUserPath(path: str, kind: int) -> None:+ import winreg+ import win32con+ import win32gui+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) as key:+ winreg.SetValueEx(key, "Path", 0, kind, path)+ win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment",+ win32con.SMTO_ABORTIFHUNG, 5000)diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.pyindex 361ceb47..f16fa83f 100644--- a/app/view/pages/setting_page.py+++ b/app/view/pages/setting_page.py@@ -16,7 +16,6 @@ from app.view.components.scroll_area import FastScrollAreafrom app.config.cfg import cfg, LANGUAGE_TEXTSfrom app.i18n import toLocalizedErrorfrom app.models.task import toTaskError-from app.platform.android import IS_ANDROIDfrom app.services.port_listener import ListenStatusfrom app.config.constants import (AUTHOR, AUTHOR_URL, CHROME_WEBSTORE_URL, EDGE_ADDONS_URL,@@ -327,26 +326,26 @@ class SettingPage(FastScrollArea):self.tr("当前为用户模式,数据保存在: {0}").format(APP_DATA_DIR),)+ self.commandLineToolCard = PushSettingCard(+ "", FluentIcon.COMMAND_PROMPT, self.tr("命令行工具"),+ self.tr("安装后可在终端中使用 ghd 命令添加和管理任务"),+ )+ self._refreshCommandLineToolCard()softwareCards = [SwitchSettingCard(FluentIcon.UPDATE, self.tr("在应用程序启动时检查更新"),self.tr("新版本将更稳定,并具有更多功能"),cfg.shouldCheckUpdateAtStartup),self.autoRunCard,- ]- if not IS_ANDROID:- softwareCards.append(- ComboBoxSettingCard(- cfg.closeMode, FluentIcon.POWER_BUTTON,- self.tr("关闭主窗口时"),- self.tr("设置关闭主窗口后程序继续在后台运行还是退出"),- texts=[self.tr("关闭时询问"), self.tr("继续在后台运行"), self.tr("退出程序")],- ),- )- softwareCards.append(+ self.commandLineToolCard,+ ComboBoxSettingCard(+ cfg.closeMode, FluentIcon.POWER_BUTTON,+ self.tr("关闭主窗口时"),+ self.tr("设置关闭主窗口后程序继续在后台运行还是退出"),+ texts=[self.tr("关闭时询问"), self.tr("继续在后台运行"), self.tr("退出程序")],+ ),ClipboardSettingCard(self._featureService.packs),- )- if not IS_ANDROID:- softwareCards.append(self.migrateCard)+ self.migrateCard,+ ]self.softwareGroup.addSettingCards(softwareCards)self.feedbackCard = PrimaryPushSettingCard(@@ -408,12 +407,12 @@ class SettingPage(FastScrollArea):if sys.platform != "darwin":self.urlSchemeCard.checkedChanged.connect(self._onUrlSchemeChanged)self.autoRunCard.checkedChanged.connect(self._onRunAtLoginChanged)+ self.commandLineToolCard.clicked.connect(self._onCommandLineToolClicked)self.packInfoCard.clicked.connect(self._onPackInfoClicked)self.aboutCard.clicked.connect(self._onAboutCardClicked)self.feedbackCard.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(FEEDBACK_URL)))self.openLogButton.clicked.connect(self._onOpenLogClicked)- if not IS_ANDROID:- self.migrateCard.clicked.connect(self._onMigrateClicked)+ self.migrateCard.clicked.connect(self._onMigrateClicked)def _onDownloadFolderChanged(self, path: str) -> None:cfg.set(cfg.downloadFolder, path)@@ -500,6 +499,38 @@ class SettingPage(FastScrollArea):from app.platform.run_at_login import setRunAtLoginsetRunAtLogin(enabled)+ def _refreshCommandLineToolCard(self) -> None:+ from app.platform import cli_install+ self.commandLineToolCard.button.setEnabled(True)+ self.commandLineToolCard.button.setText(+ self.tr("卸载") if cli_install.isInstalled() else self.tr("安装"))++ def _onCommandLineToolClicked(self) -> None:+ from app.platform import cli_install+ work = cli_install.delete() if cli_install.isInstalled() else cli_install.install()+ self.commandLineToolCard.button.setEnabled(False)+ self._coroutineRunner.submit(work, done=self._onCommandLineToolDone, failed=self._onCommandLineToolFailed)++ def _onCommandLineToolDone(self, _) -> None:+ from app.platform import cli_install+ self._refreshCommandLineToolCard()+ if not cli_install.isInstalled():+ InfoBar.success(self.tr("已卸载命令行工具"), "", duration=2000,+ position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window())+ return+ content = self.tr("新打开的终端即可使用 ghd")+ if sys.platform == "linux":+ content = self.tr("新打开的终端即可使用 ghd;若提示找不到命令,请将 ~/.local/bin 添加到 PATH")+ InfoBar.success(self.tr("已安装命令行工具"), content, duration=5000,+ position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window())++ def _onCommandLineToolFailed(self, error) -> None:+ from app.platform import cli_install+ self._refreshCommandLineToolCard()+ title = self.tr("卸载命令行工具失败") if cli_install.isInstalled() else self.tr("安装命令行工具失败")+ InfoBar.error(title, toLocalizedError(toTaskError(error)),+ duration=5000, position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window())+def _onMigrateClicked(self) -> None:from app.config.paths import isPortable, migrate, PORTABLE_DIR, USER_DATA_DIRdiff --git a/docs/adr/0021-windows-command-line-tool-is-a-forwarding-exe.md b/docs/adr/0021-windows-command-line-tool-is-a-forwarding-exe.mdnew file mode 100644index 00000000..6c6bd03c--- /dev/null+++ b/docs/adr/0021-windows-command-line-tool-is-a-forwarding-exe.md@@ -0,0 +1,28 @@+# Windows 的 Command Line Tool 是一个转发 exe++Windows 上 PATH 里只放 `{app}\bin`,里面只有一个 C 写的 console 程序 `ghd.exe`:找到上一级的 `Ghost-Downloader-3.exe`,+在命令行最前面插入 `ghd` 后原样转交命令行和 std 句柄,等它退出并返回它的退出码,不含任何其他逻辑。+这是 Git for Windows `cmd\git.exe` 的做法。macOS 和 Linux 用指向可执行文件的 symlink。++转发 exe 解决两件事:++- **PATH 污染**:App Dir 里的 libcrypto、libssl、Qt6*.dll 不能进入其他程序的 DLL 搜索路径;Git 以 OpenSSL 冲突为由拒绝了把 App Dir 放进 PATH。+- **主程序是 GUI 子系统**(`--windows-console-mode=attach`):shell 不等 GUI 程序退出,也拿不到它的退出码,而退出码是 `ghd` 输出契约的一部分。+ 转发 exe 是 console 程序,shell 等的是它。(尚待 Windows 实测确认)++## Considered Options++- **App Dir 直接进 PATH**:上面两件事都没解决,命令名也只能是 `Ghost-Downloader-3`。+- **把主程序复制或硬链接到 `bin\`**:Nuitka standalone 从 exe 所在目录加载 DLL,放进 `bin\` 无法启动;且仍是 GUI 子系统。+- **再用 Nuitka 编一个 console 版客户端**:要再带一份 Python 和 Qt 运行时。+- **`.cmd` shim**(VS Code 的 `bin\code.cmd`):cmd.exe 的参数解析无法被可靠转义(BatBadBut,CVE-2024-24576),而 URL 里的 `&`、`%` 正是 `ghd` 的核心输入。+- **`.ps1` shim**:只在 PowerShell 里可用,受执行策略限制。+- **App Paths 注册表**:只有 ShellExecute 查它,cmd 和 PowerShell 不查。+- **并入 `updater.exe`,按 argv[0] 分派**:两个程序职责无关。++## Consequences++- Windows 构建多一步 MSVC 编译,结构与 `tools/updater` 相同;转发 exe 随 App Dir 一起被 Updater 替换,Portable 模式同样可用。+- 转发 exe 显式把 std 句柄交给主程序,不依赖 Nuitka `attach` 模式继承管道。+- 插入的 `ghd` 标明这是子命令;argv[0] 不能改,打包版靠它定位自身。+- Uninstaller 用 `[Code]` 从用户 PATH 删去 `{app}\bin`,两端补 `;` 匹配首尾条目。diff --git a/scripts/Ghost-Downloader-3.iss b/scripts/Ghost-Downloader-3.issindex d9cdb805..18a8f5ec 100644--- a/scripts/Ghost-Downloader-3.iss+++ b/scripts/Ghost-Downloader-3.iss@@ -32,6 +32,7 @@ ArchitecturesInstallIn64BitMode=x64compatibleDisableProgramGroupPage=yesLicenseFile=LICENSEPrivilegesRequired=lowest+ChangesEnvironment=yesPrivilegesRequiredOverridesAllowed=dialogOutputDir=distOutputBaseFilename=Ghost-Downloader-v{#MyAppVersion}-Windows-Setup@@ -82,3 +83,19 @@ Type: filesandordirs; Name: "{localappdata}\GhostDownloader"[Run]Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent++[Code]+procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);+var+ Path, Entry: string;+ Index: Integer;+begin+ if CurUninstallStep <> usUninstall then Exit;+ if not RegQueryStringValue(HKCU, 'Environment', 'Path', Path) then Exit;+ Entry := ';' + ExpandConstant('{app}\bin') + ';';+ Path := ';' + Path + ';';+ Index := Pos(Lowercase(Entry), Lowercase(Path));+ if Index = 0 then Exit;+ Delete(Path, Index, Length(Entry) - 1);+ RegWriteExpandStringValue(HKCU, 'Environment', 'Path', Copy(Path, 2, Length(Path) - 2));+end;diff --git a/tools/ghd/CMakeLists.txt b/tools/ghd/CMakeLists.txtnew file mode 100644index 00000000..714e3e10--- /dev/null+++ b/tools/ghd/CMakeLists.txt@@ -0,0 +1,7 @@+cmake_minimum_required(VERSION 3.20)+project(ghd C)++set(CMAKE_C_STANDARD 11)++add_executable(ghd ghd.c)+set_property(TARGET ghd PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded")diff --git a/tools/ghd/ghd.c b/tools/ghd/ghd.cnew file mode 100644index 00000000..356a67d2--- /dev/null+++ b/tools/ghd/ghd.c@@ -0,0 +1,48 @@+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#include <wchar.h>++#define COMMAND_LINE_MAX 32768++static const char UNAVAILABLE[] =+ "{\"error\": {\"code\": \"instanceUnavailable\", \"message\": \"Cannot start Ghost-Downloader-3.exe next to the bin folder.\"}}\n";++static const wchar_t *skipProgram(const wchar_t *commandLine) {+ if (*commandLine == L'"') {+ commandLine = wcschr(commandLine + 1, L'"');+ commandLine = commandLine ? commandLine + 1 : L"";+ } else {+ while (*commandLine && *commandLine != L' ' && *commandLine != L'\t') commandLine++;+ }+ while (*commandLine == L' ' || *commandLine == L'\t') commandLine++;+ return commandLine;+}++int wmain(void) {+ wchar_t program[MAX_PATH];+ DWORD length = GetModuleFileNameW(NULL, program, MAX_PATH);+ if (length == 0 || length == MAX_PATH) return 1;+ for (int i = 0; i < 2; i++) *wcsrchr(program, L'\\') = L'\0';+ wcscat_s(program, MAX_PATH, L"\\Ghost-Downloader-3.exe");++ static wchar_t commandLine[COMMAND_LINE_MAX];+ if (_snwprintf_s(commandLine, COMMAND_LINE_MAX, _TRUNCATE, L"\"%ls\" ghd %ls", program,+ skipProgram(GetCommandLineW())) < 0) return 2;++ STARTUPINFOW startup = {sizeof(startup)};+ startup.dwFlags = STARTF_USESTDHANDLES;+ startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);+ startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);+ startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);+ PROCESS_INFORMATION process;+ if (!CreateProcessW(program, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process)) {+ DWORD written;+ WriteFile(startup.hStdOutput, UNAVAILABLE, sizeof(UNAVAILABLE) - 1, &written, NULL);+ return 1;+ }++ DWORD exitCode = 1;+ WaitForSingleObject(process.hProcess, INFINITE);+ GetExitCodeProcess(process.hProcess, &exitCode);+ return (int)exitCode;+}