The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(linux): 支持可写目录的应用内自更新
XiaoYouChR1c56859af8cb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex aabf3937..8256021a 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -624,9 +624,11 @@ jobs:- architecture: x86_64runner: ubuntu-22.04appimage_arch: x86_64+ hdiff_arch: linux64- architecture: arm64runner: ubuntu-24.04-armappimage_arch: aarch64+ hdiff_arch: linux_arm64runs-on: ${{ matrix.runner }}steps:- name: Checkout@@ -640,7 +642,7 @@ jobs:- name: Install dependenciesrun: |sudo apt-get update- sudo apt-get install -y desktop-file-utils libegl1-mesa-dev libzstd1+ sudo apt-get install -y cmake desktop-file-utils libegl1-mesa-dev libzstd1uv python install 3.13uv sync@@ -767,27 +769,59 @@ jobs:file "$APPIMAGE_FILE"+ - name: Build updater+ run: |+ cmake -B build-updater -DCMAKE_BUILD_TYPE=Release tools/updater+ cmake --build build-updater+ cp build-updater/updater dist/Ghost-Downloader-3.dist/++ - name: Download HDiffPatch+ run: |+ curl -fsSL "https://github.com/sisong/HDiffPatch/releases/download/v5.1.3/hdiffpatch_v5.1.3_bin_${{ matrix.hdiff_arch }}.zip" -o hdiffpatch.zip+ python3 -m zipfile -e hdiffpatch.zip hdiffpatch+ chmod +x "hdiffpatch/${{ matrix.hdiff_arch }}/hdiffz" "hdiffpatch/${{ matrix.hdiff_arch }}/hpatchz"+ cp "hdiffpatch/${{ matrix.hdiff_arch }}/hpatchz" dist/Ghost-Downloader-3.dist/+- name: Tar the contents of Ghost-Downloaderif: ${{ github.event.inputs.create_release == 'true' }}- shell: pwshrun: |- $distPath = "dist/Ghost-Downloader-3.dist"- $tarFile = "Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz"+ cp app/assets/logo.png dist/Ghost-Downloader-3.dist/logo.png+ TAR_FILE="Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz"+ echo "Creating tar.xz archive of dist/Ghost-Downloader-3.dist..."+ tar -cJf "$TAR_FILE" -C dist/Ghost-Downloader-3.dist .+ echo "Archive created at $TAR_FILE"- Copy-Item "app/assets/logo.png" "$distPath/logo.png"- Write-Output "Creating tar.xz archive of $distPath..."- tar -cJf $tarFile -C $distPath .- Write-Output "Archive created at $tarFile"+ - name: Generate patch+ if: ${{ needs.prepare.outputs.patch_base != '' }}+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ BASE_VER="${{ needs.prepare.outputs.patch_base }}"+ BASE_TAR="Ghost-Downloader-v${BASE_VER}-Linux-${{ matrix.architecture }}.tar.xz"+ if ! gh release view "v$BASE_VER" --json assets --jq '.assets[].name' | grep -Fxq "$BASE_TAR"; then+ echo "v$BASE_VER has no Linux-${{ matrix.architecture }} package, skipping patch"+ exit 0+ fi++ mkdir -p prev-download prev-dir+ gh release download "v$BASE_VER" -p "$BASE_TAR" -D prev-download/+ tar -xJf "prev-download/$BASE_TAR" -C prev-dir+ PATCH_FILE="patch-Linux-${{ matrix.architecture }}-${BASE_VER}-to-${{ env.VERSION }}.hdiff"+ "hdiffpatch/${{ matrix.hdiff_arch }}/hdiffz" -f prev-dir dist/Ghost-Downloader-3.dist "$PATCH_FILE"+ rm -rf prev-download prev-dir+ echo "PATCH_FILE=$PATCH_FILE" >> "$GITHUB_ENV"- name: Upload to releaseif: ${{ github.event.inputs.create_release == 'true' }}env:GH_TOKEN: ${{ github.token }}run: |- gh release upload "v${{ env.VERSION }}" \- "Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz" \- "dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.AppImage" \- --clobber+ FILES=(+ "Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.tar.xz"+ "dist/Ghost-Downloader-v${{ env.VERSION }}-Linux-${{ matrix.architecture }}.AppImage"+ )+ if [ -n "${PATCH_FILE:-}" ] && [ -f "$PATCH_FILE" ]; then FILES+=("$PATCH_FILE"); fi+ gh release upload "v${{ env.VERSION }}" "${FILES[@]}" --clobber- name: Upload artifactsif: ${{ github.event.inputs.create_release == 'false' }}diff --git a/app/config/paths.py b/app/config/paths.pyindex 80a57f51..d65c103a 100644--- a/app/config/paths.py+++ b/app/config/paths.py@@ -19,6 +19,8 @@ EXECUTABLE_DIR = (else Path("."))+APP_DIR = EXECUTABLE_DIR.parent.parent if sys.platform == "darwin" else EXECUTABLE_DIR+APP_DATA_DIR = (EXECUTABLE_DIR / "GhostDownloader"if (EXECUTABLE_DIR / "GhostDownloader").is_dir()diff --git a/app/services/update_service.py b/app/services/update_service.pyindex c52bbe12..5d11d04b 100644--- a/app/services/update_service.py+++ b/app/services/update_service.py@@ -17,7 +17,7 @@ from loguru import loggerfrom app.checksum import parseChecksum, toChecksumfrom app.config.constants import VERSION-from app.config.paths import APP_DATA_DIR, FEATURES_DIR, EXECUTABLE_DIR+from app.config.paths import APP_DATA_DIR, APP_DIR, EXECUTABLE_DIR, FEATURES_DIRfrom app.platform.android import IS_ANDROIDfrom app.platform.arch import BUILD_ARCH, MACHINE_ARCHfrom app.models.pack import PackManifest@@ -29,6 +29,7 @@ if TYPE_CHECKING:from app.services.coroutine_runner import CoroutineRunnerSTAGING_DIR = APP_DATA_DIR / "update_staging"+UPDATER_PATH = EXECUTABLE_DIR / ("updater.exe" if sys.platform == "win32" else "updater")OS_MAP = {"win32": "Windows", "darwin": "macOS", "linux": "Linux"}@@ -118,6 +119,17 @@ class UpdateService:def infoById(self, targetId: str) -> UpdateInfo | None:return self._infos.get(targetId)+ def canSelfUpdate(self) -> bool:+ if "__compiled__" not in globals() or not UPDATER_PATH.is_file():+ return False+ if sys.platform != "linux":+ return True+ return (+ "APPIMAGE" not in os.environ+ and os.access(APP_DIR, os.W_OK)+ and os.access(APP_DIR.parent, os.W_OK)+ )+def check(self) -> None:self._coroutineRunner.submit(self._check())@@ -283,17 +295,14 @@ class UpdateService:logger.info("Pack 更新已暂存: {}", packId)def _startUpdater(self) -> None:- updaterName = "updater.exe" if sys.platform == "win32" else "updater"- updaterPath = EXECUTABLE_DIR / updaterName- if not updaterPath.is_file():- logger.error("updater not found: {}", updaterPath)+ if not UPDATER_PATH.is_file():+ logger.error("updater not found: {}", UPDATER_PATH)return- appDir = EXECUTABLE_DIR.parent.parent if sys.platform == "darwin" else EXECUTABLE_DIRpatchPath = STAGING_DIR / "patch.hdiff"stagingNewDir = STAGING_DIR / "app_new"- args = [str(updaterPath), str(os.getpid()), str(appDir),+ args = [str(UPDATER_PATH), str(os.getpid()), str(APP_DIR),str(Path(sys.executable).resolve())]if patchPath.is_file():args.append(str(patchPath))diff --git a/app/startup.py b/app/startup.pyindex dbf38600..b84404ba 100644--- a/app/startup.py+++ b/app/startup.py@@ -84,11 +84,11 @@ def createEngine(application: Application) -> Engine:def deleteBackupDir() -> None:import shutil- import sys- from app.config.paths import EXECUTABLE_DIR+ from app.config.paths import APP_DIR- appDir = EXECUTABLE_DIR.parent.parent if sys.platform == "darwin" else EXECUTABLE_DIR- backupDir = appDir.parent / f"{appDir.name}_backup"+ if "__compiled__" not in globals():+ return+ backupDir = APP_DIR.parent / f"{APP_DIR.name}_backup"if backupDir.is_dir():shutil.rmtree(backupDir, ignore_errors=True)diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.pyindex e5a19db6..52095e46 100644--- a/app/view/windows/main_window.py+++ b/app/view/windows/main_window.py@@ -362,10 +362,10 @@ class MainWindow(MSFluentWindow):parent=self,)downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))- if sys.platform == "linux":- downloadButton.clicked.connect(lambda: (infoBar.close(), self._downloadBestAsset()))- else:+ if self._updateService.canSelfUpdate():downloadButton.clicked.connect(lambda: (infoBar.close(), self._updateService.download("app")))+ else:+ downloadButton.clicked.connect(lambda: (infoBar.close(), self._downloadBestAsset()))infoBar.addWidget(downloadButton)detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))detailButton.clicked.connect(self._showReleaseDetails)diff --git a/docs/adr/0037-linux-self-update-for-writable-dir-only.md b/docs/adr/0037-linux-self-update-for-writable-dir-only.mdnew file mode 100644index 00000000..fcae602a--- /dev/null+++ b/docs/adr/0037-linux-self-update-for-writable-dir-only.md@@ -0,0 +1,15 @@+# Linux 应用内自更新仅覆盖可写目录安装++Linux 官方发布仅保留 `.tar.xz`(配合 `scripts/install.sh` 或手动解压到用户目录)与 `.AppImage`,另有社区维护的 AUR 等系统包。我们在 `UpdateService.canSelfUpdate()` 中收口自更新能力判断:Linux 上仅当 `updater` 二进制存在、未处于 `APPIMAGE` 环境、且 `App Dir` 与其父目录均对当前用户可写时,才启用与 Windows / macOS 一致的应用内自更新(优先 HDiffPatch 目录增量 `Patch`,跨版本自动回退全量 `.tar.xz`);其余形态(`.AppImage`、只读系统目录、源码运行)统一回退到下载发布包。++## Considered Options++- **为 `.AppImage` 增加单文件原地替换**:需要在 `versions.json`、`UpdateService` 与 `updater.c` 各增加一条单文件分支,无法复用目录级 HDiffPatch 补丁,且用户选择 `.AppImage` 本身即偏好免安装单文件管理。+- **通过 `pkexec` 提权更新只读系统目录**:官方已停止发布 `.deb`,只读系统目录基本来自发行版包管理器(如 AUR),应用绕过包管理器强行覆写 `/usr` 会破坏包数据库;同时提权后在 Wayland/D-Bus 会话下重新拉起 GUI 进程极易丢失会话环境变量。+- **Linux 仅做全量 `.tar.xz` 自更新、不生成增量 `Patch`**:全量包约 70 MB,而目录增量 `Patch` 通常不足 10 MB;`UpdateService`、`updater.c` 与 `finalize` 已有完整的增量链路,接入 `hdiffz` / `hpatchz` 的额外维护成本极低。++## Consequences++- `build-ubuntu` 在 `Build .AppImage` 之后再编译并装入 `updater`、`hpatchz` 与 `logo.png`,保证 `.AppImage` 不夹带无效的更新器二进制,同时让 `hdiffz` 直接对齐 `.tar.xz` 内容。+- `Updater` 在 Linux 上保持单一职责,仅负责 `App Dir` 的 `Patch`、`Install`(优先 `renameat2(RENAME_EXCHANGE)` 原子交换,不支持时回退两步 `moveDir`)与重启,不触碰 XDG `.desktop` 与图标文件。+- 首次携带 `updater` 的版本发布前,旧版(如 `v4.5.11`)用户仍通过 `install.sh` 或手动覆盖升级;升入该版本后,后续版本即可直接在应用内完成自更新。diff --git a/tools/updater/updater.c b/tools/updater/updater.cindex ea993fef..31ea5f04 100644--- a/tools/updater/updater.c+++ b/tools/updater/updater.c@@ -3,6 +3,10 @@* Exit: 0 ok · 1 patch · 2 rename · 3 timeout · 4 launch · 5 args*/+#ifdef __linux__+ #define _GNU_SOURCE+#endif+#include <stdarg.h>#include <stdio.h>#include <stdlib.h>@@ -21,6 +25,7 @@#else#include <dirent.h>#include <errno.h>+ #include <fcntl.h>#include <ftw.h>#include <pwd.h>#include <signal.h>@@ -75,6 +80,10 @@ static void toDirname(pchar *path) {}static void openLog(const pchar *exeDir) {+ if (g_log) {+ fclose(g_log);+ g_log = NULL;+ }#ifdef _WIN32if (exeDir && exeDir[0]) {wsnprintf(g_logPath, PATH_BUF, L"%ls\\GhostDownloader", exeDir);@@ -442,7 +451,7 @@ static void installUninstaller(const wchar_t *appDir, const wchar_t *newDir) {FindClose(h);}#else-static int copyFile(const char *from, const char *to) {+static int copyFile(const char *from, const char *to, mode_t mode) {FILE *in = fopen(from, "rb");if (!in) return -1;FILE *out = fopen(to, "wb");@@ -460,8 +469,9 @@ static int copyFile(const char *from, const char *to) {}}if (ferror(in)) ok = 0;+ if (ok && fchmod(fileno(out), mode & 0777) != 0) ok = 0;fclose(in);- fclose(out);+ if (fclose(out) != 0) ok = 0;if (!ok) {remove(to);return -1;@@ -489,18 +499,32 @@ static int copyDir(const char *from, const char *to) {closedir(d);return -1;}- if (stat(fromChild, &st) != 0) {+ if (lstat(fromChild, &st) != 0) {closedir(d);return -1;}- if (S_ISDIR(st.st_mode)) {+ if (S_ISLNK(st.st_mode)) {+ char target[PATH_BUF];+ ssize_t linkLen = readlink(fromChild, target, sizeof(target) - 1);+ if (linkLen < 0 || (size_t)linkLen >= sizeof(target) - 1) {+ closedir(d);+ return -1;+ }+ target[linkLen] = '\0';+ if (symlink(target, toChild) != 0) {+ closedir(d);+ return -1;+ }+ } else if (S_ISDIR(st.st_mode)) {if (copyDir(fromChild, toChild) != 0) {closedir(d);return -1;}- } else if (copyFile(fromChild, toChild) != 0) {- closedir(d);- return -1;+ } else if (S_ISREG(st.st_mode)) {+ if (copyFile(fromChild, toChild, st.st_mode) != 0) {+ closedir(d);+ return -1;+ }}}closedir(d);@@ -532,6 +556,16 @@ static int moveDir(const pchar *from, const pchar *to) {return -1;#elseif (rename(from, to) == 0) return 0;+ if (errno == EXDEV) {+ logMsg("cross-device, copying \"" PFMT "\" -> \"" PFMT "\"", from, to);+ if (copyDir(from, to) != 0) {+ logMsg("copy failed");+ deleteDir(to);+ return -1;+ }+ deleteDir(from);+ return 0;+ }logMsg("rename \"" PFMT "\" -> \"" PFMT "\" failed: %s", from, to, strerror(errno));return -1;#endif@@ -597,6 +631,16 @@ static void restructureBundle(const char *appDir) {}#endif+#if defined(__APPLE__) || defined(__linux__)+static int swapDirs(const char *a, const char *b) {+#ifdef __APPLE__+ return renamex_np(a, b, RENAME_SWAP);+#else+ return renameat2(AT_FDCWD, a, AT_FDCWD, b, RENAME_EXCHANGE);+#endif+}+#endif+static int install(const pchar *appDir, const pchar *newDir,const pchar *backupDir, const pchar *exeDir) {if (!hasDir(newDir))@@ -633,9 +677,9 @@ static int install(const pchar *appDir, const pchar *newDir,#endifint swapOk = 0;-#ifdef __APPLE__- if (renamex_np(newDir, appDir, RENAME_SWAP) == 0) {- /* After SWAP, newDir holds the old tree. Leaving it there makes+#if defined(__APPLE__) || defined(__linux__)+ if (swapDirs(newDir, appDir) == 0) {+ /* After swap, newDir holds the old tree. Leaving it there makesthe next patch reuse it as New Dir. */if (rename(newDir, backupDir) != 0) {logMsg("rename old to backup failed (%s), deleting leftover", strerror(errno));@@ -643,7 +687,7 @@ static int install(const pchar *appDir, const pchar *newDir,}swapOk = 1;} else {- logMsg("renamex_np failed (%s), falling back", strerror(errno));+ logMsg("atomic swap failed (%s), falling back", strerror(errno));}#endifif (!swapOk) {@@ -995,8 +1039,10 @@ int main(int argc, char *argv[]) {}}+#ifdef _WIN32/* Windows cannot MoveFile a directory while updater.log is open inside it. */closeLog();+#endifif (patchFile && !isStagedDir) {#ifdef _WIN32_wremove(patchFile);@@ -1040,13 +1086,22 @@ int main(int argc, char *argv[]) {restructureBundle(appDir);#endif+#ifndef _WIN32+ /* Avoid passing a deleted Backup Dir as cwd when the old process started inside App Dir. */+ if (chdir(appDir) != 0)+ logMsg("chdir \"" PFMT "\" failed: %s", appDir, strerror(errno));+#endif+logMsg("starting " PFMT, appExe);if (startApp(appExe) != 0) {logMsg("start failed, rolling back");closeLog();- if (moveDir(appDir, newDir) == 0)- moveDir(backupDir, appDir);- deleteDir(newDir);+ if (hasDir(backupDir) && moveDir(appDir, newDir) == 0) {+ if (moveDir(backupDir, appDir) == 0)+ deleteDir(newDir);+ else+ moveDir(newDir, appDir);+ }return EXIT_LAUNCH_FAILED;}