Skip to content

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

feat(update): delta 更新系统

XiaoYouChRbef53eb72e15
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index baaf886c..4628016f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -116,6 +116,22 @@ jobs:
(Get-Content scripts/Ghost-Downloader-3.iss) -replace 'APPLICATION_VERSION', '${{ needs.prepare.outputs.version }}' | Set-Content scripts/Ghost-Downloader-3.iss
uv run scripts/deploy.py
+ - name: Build updater
+ shell: pwsh
+ run: |
+ $arch = if ("${{ matrix.architecture }}" -eq "arm64") { "ARM64" } else { "x64" }
+ cmake -B build-updater -G "Visual Studio 17 2022" -A $arch tools/updater
+ cmake --build build-updater --config Release
+ Copy-Item build-updater/Release/updater.exe dist/Ghost-Downloader-3.dist/
+
+ - name: Download HDiffPatch
+ shell: pwsh
+ run: |
+ $hdiffArch = if ("${{ matrix.architecture }}" -eq "arm64") { "windows_arm64" } else { "windows64" }
+ Invoke-WebRequest -Uri "https://github.com/sisong/HDiffPatch/releases/download/v5.1.3/hdiffpatch_v5.1.3_bin_${hdiffArch}.zip" -OutFile hdiffpatch.zip
+ Expand-Archive hdiffpatch.zip -DestinationPath hdiffpatch
+ Copy-Item hdiffpatch/${hdiffArch}/hpatchz.exe dist/Ghost-Downloader-3.dist/
+
- name: Prepare For Sign
if: ${{ github.event.inputs.create_release == 'true' || github.event.inputs.sign_artifact == 'true' }}
run: |
@@ -170,15 +186,54 @@ jobs:
if: ${{ github.event.inputs.create_release == 'true' }}
shell: pwsh
run: |
- 7z a -tzip -mx=9 -m0=LZMA Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}.zip dist/Ghost-Downloader-3.dist/*
+ Push-Location dist/Ghost-Downloader-3.dist
+ 7z a -tzip -mx=9 -m0=LZMA "$env:GITHUB_WORKSPACE/Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}.zip" *
+ Pop-Location
mv dist/Ghost-Downloader-v${{ env.VERSION }}-Windows-Setup.exe dist/Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}-Setup.exe
+ - name: Generate delta patch
+ if: ${{ github.event.inputs.create_release == 'true' }}
+ shell: pwsh
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ $hdiffArch = if ("${{ matrix.architecture }}" -eq "arm64") { "windows_arm64" } else { "windows64" }
+ $prevTag = gh release list --limit 2 --json tagName --jq '.[1].tagName'
+ if (-not $prevTag) { Write-Output "No previous release, skipping delta"; exit 0 }
+ $prevVer = $prevTag -replace '^v', ''
+
+ New-Item -ItemType Directory -Path prev -Force
+ gh release download $prevTag -p "*Windows-${{ matrix.architecture }}.zip" -D prev/ 2>$null
+ $prevZip = Get-ChildItem prev/*.zip | Select-Object -First 1
+ if (-not $prevZip) { Write-Output "No previous asset for this architecture"; exit 0 }
+
+ New-Item -ItemType Directory -Path prev-extracted -Force
+ Push-Location prev-extracted
+ 7z x $prevZip.FullName
+ Pop-Location
+
+ if (Test-Path "prev-extracted/dist/Ghost-Downloader-3.dist") {
+ $oldDir = "prev-extracted/dist/Ghost-Downloader-3.dist"
+ } else {
+ $oldDir = "prev-extracted"
+ }
+
+ $patchFile = "patch-Windows-${{ matrix.architecture }}-${prevVer}-to-${{ env.VERSION }}.hdiff"
+ & "hdiffpatch/${hdiffArch}/hdiffz.exe" -f "$oldDir" dist/Ghost-Downloader-3.dist "$patchFile"
+ echo "PATCH_FILE=$patchFile" >> $env:GITHUB_ENV
+
- name: Upload to release
if: ${{ github.event.inputs.create_release == 'true' }}
env:
GH_TOKEN: ${{ github.token }}
+ shell: pwsh
run: |
- gh release upload "v${{ env.VERSION }}" "Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}.zip" "dist/Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}-Setup.exe" --clobber
+ $files = @(
+ "Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}.zip",
+ "dist/Ghost-Downloader-v${{ env.VERSION }}-Windows-${{ matrix.architecture }}-Setup.exe"
+ )
+ if ($env:PATCH_FILE -and (Test-Path $env:PATCH_FILE)) { $files += $env:PATCH_FILE }
+ gh release upload "v${{ env.VERSION }}" @files --clobber
- name: Upload artifacts
if: ${{ github.event.inputs.create_release == 'false' }}
@@ -235,6 +290,19 @@ jobs:
mv "app/assets/修复软件损坏" "dist/修复软件损坏"
chmod +x "dist/修复软件损坏"
+ - name: Build updater
+ run: |
+ cmake -B build-updater -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=${{ matrix.architecture }} tools/updater
+ cmake --build build-updater
+ cp build-updater/updater "dist/Ghost Downloader.app/Contents/MacOS/"
+
+ - name: Download HDiffPatch
+ run: |
+ curl -fL "https://github.com/sisong/HDiffPatch/releases/download/v5.1.3/hdiffpatch_v5.1.3_bin_macos.zip" -o hdiffpatch.zip
+ unzip -q hdiffpatch.zip
+ cp macos/hpatchz "dist/Ghost Downloader.app/Contents/MacOS/"
+ chmod +x "dist/Ghost Downloader.app/Contents/MacOS/hpatchz"
+
- name: Reinstall openssl libs
if: ${{ matrix.openssl_workaround == 'true' }}
run: |
@@ -271,12 +339,39 @@ jobs:
"$DMG_NAME" \
"$DMG_SOURCE_DIR"
+ - name: Generate delta patch
+ if: ${{ github.event.inputs.create_release == 'true' }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ chmod +x macos/hdiffz
+ PREV_TAG=$(gh release list --limit 2 --json tagName --jq '.[1].tagName')
+ if [ -z "$PREV_TAG" ]; then echo "No previous release, skipping delta"; exit 0; fi
+ PREV_VER=${PREV_TAG#v}
+
+ mkdir -p prev-download
+ gh release download "$PREV_TAG" -p "*macOS-${{ matrix.architecture }}.dmg" -D prev-download/ 2>/dev/null || true
+ PREV_DMG=$(ls prev-download/*.dmg 2>/dev/null | head -1)
+ if [ -z "$PREV_DMG" ]; then echo "No previous asset for this architecture"; exit 0; fi
+
+ mkdir -p prev-mount
+ hdiutil attach "$PREV_DMG" -mountpoint prev-mount -nobrowse -quiet
+ OLD_APP=$(find prev-mount -maxdepth 1 -name "*.app" | head -1)
+
+ PATCH_FILE="patch-macOS-${{ matrix.architecture }}-${PREV_VER}-to-${{ env.VERSION }}.hdiff"
+ macos/hdiffz -f "$OLD_APP" "dist/Ghost Downloader.app" "$PATCH_FILE"
+
+ hdiutil detach prev-mount -quiet
+ echo "PATCH_FILE=$PATCH_FILE" >> "$GITHUB_ENV"
+
- name: Upload to release
if: ${{ github.event.inputs.create_release == 'true' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
- gh release upload "v${{ env.VERSION }}" "Ghost-Downloader-v${{ env.VERSION }}-macOS-${{ matrix.architecture }}.dmg" --clobber
+ FILES=("Ghost-Downloader-v${{ env.VERSION }}-macOS-${{ matrix.architecture }}.dmg")
+ if [ -n "$PATCH_FILE" ] && [ -f "$PATCH_FILE" ]; then FILES+=("$PATCH_FILE"); fi
+ gh release upload "v${{ env.VERSION }}" "${FILES[@]}" --clobber
- name: Upload artifacts
if: ${{ github.event.inputs.create_release == 'false' }}
@@ -498,3 +593,119 @@ jobs:
name: Ghost-Downloader-v${{ needs.prepare.outputs.version }}-Android-arm64-v8a
path: ${{ env.APK_FILE }}
if-no-files-found: error
+
+ finalize:
+ needs: [prepare, build-windows, build-macos]
+ if: ${{ github.event.inputs.create_release == 'true' }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Set up uv
+ uses: astral-sh/setup-uv@v7
+
+ - name: Install Python
+ run: uv python install 3.11
+
+ - name: Generate versions.json
+ env:
+ GH_TOKEN: ${{ github.token }}
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ PREV_TAG=$(gh release list --repo ${{ github.repository }} --limit 2 --json tagName --jq '.[1].tagName' 2>/dev/null || echo "")
+ export PREV_VER=${PREV_TAG#v}
+
+ mkdir -p assets
+ gh release download "v${VERSION}" --repo ${{ github.repository }} -p "*.hdiff" -p "*.zip" -p "*.dmg" -D assets/ 2>/dev/null || true
+
+ uv run --no-project python3 << 'PYEOF'
+ import hashlib, json, os
+
+ version = os.environ["VERSION"]
+ prev_ver = os.environ.get("PREV_VER", "")
+ assets_dir = "assets"
+
+ def sha256of(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+ platforms = ["Windows-x86_64", "Windows-arm64", "macOS-arm64", "macOS-x86_64"]
+ patches = {}
+ full = {}
+
+ for p in platforms:
+ for f in os.listdir(assets_dir):
+ if f.startswith(f"patch-{p}-") and f.endswith(".hdiff"):
+ path = os.path.join(assets_dir, f)
+ patches[p] = {"from": prev_ver, "file": f, "sha256": sha256of(path), "size": os.path.getsize(path)}
+ break
+
+ ext = ".zip" if p.startswith("Windows") else ".dmg"
+ full_name = f"Ghost-Downloader-v{version}-{p}{ext}"
+ full_path = os.path.join(assets_dir, full_name)
+ if os.path.isfile(full_path):
+ full[p] = {"file": full_name, "sha256": sha256of(full_path), "size": os.path.getsize(full_path)}
+
+ data = {"app": {"version": version, "patches": patches, "full": full}, "packs": {}}
+
+ with open("versions.json", "w") as f:
+ json.dump(data, f, indent=2)
+ print(json.dumps(data, indent=2))
+ PYEOF
+
+ gh release upload "v${VERSION}" versions.json --repo ${{ github.repository }} --clobber
+
+ - name: Mirror to GitCode
+ env:
+ GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ if [ -z "$GITCODE_TOKEN" ]; then echo "No GITCODE_TOKEN, skipping mirror"; exit 0; fi
+
+ API="https://api.gitcode.com/api/v5"
+ REPO="XiaoYouChR/Ghost-Downloader-3"
+ TAG="v${VERSION}"
+ AUTH="access_token=${GITCODE_TOKEN}"
+
+ RELEASE=$(curl -sf "${API}/repos/${REPO}/releases/tags/${TAG}?${AUTH}" || echo "")
+ if [ -z "$RELEASE" ]; then
+ curl -sf -X POST "${API}/repos/${REPO}/releases?${AUTH}" \
+ -H "Content-Type: application/json" \
+ -d "{\"tag_name\":\"${TAG}\",\"name\":\"${TAG}\",\"body\":\"${TAG}\"}"
+ fi
+
+ curl -sf -X PATCH "${API}/repos/${REPO}/releases/${TAG}?${AUTH}" \
+ -H "Content-Type: application/json" \
+ -d '{"release_status":"latest"}'
+
+ upload_file() {
+ local file="$1"
+ local name=$(basename "$file")
+
+ local upload_info=$(curl -sf "${API}/repos/${REPO}/releases/${TAG}/upload_url?${AUTH}&file_name=${name}")
+ local url=$(echo "$upload_info" | jq -r '.url')
+ local content_type=$(echo "$upload_info" | jq -r '.headers["Content-Type"]')
+ local meta_project=$(echo "$upload_info" | jq -r '.headers["x-obs-meta-project-id"]')
+ local obs_acl=$(echo "$upload_info" | jq -r '.headers["x-obs-acl"]')
+ local obs_callback=$(echo "$upload_info" | jq -r '.headers["x-obs-callback"]')
+
+ curl -sf -X PUT "$url" \
+ -H "Content-Type: ${content_type}" \
+ -H "x-obs-meta-project-id: ${meta_project}" \
+ -H "x-obs-acl: ${obs_acl}" \
+ -H "x-obs-callback: ${obs_callback}" \
+ --data-binary "@${file}"
+
+ echo "uploaded: $name"
+ }
+
+ upload_file versions.json
+
+ for f in assets/patch-*.hdiff; do
+ [ -f "$f" ] && upload_file "$f"
+ done
+
+ for f in assets/Ghost-Downloader-v${VERSION}-*.zip assets/Ghost-Downloader-v${VERSION}-*.dmg; do
+ [ -f "$f" ] && upload_file "$f"
+ done
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index 5e775791..f3b61746 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -64,8 +64,10 @@ def setupEnvironment():
def startApp(application, isSilent=False):
+ import shutil
from PySide6.QtGui import QIcon
from app.config.cfg import cfg
+ from app.config.paths import executableDir
from app.services.clipboard_listener import ClipboardListener
from app.signal_bus import signalBus
from app.startup import loadEngine, createServices, loadPacks, startEngine, bindNotifications, checkUpdateAtStartup, stopEngine
@@ -86,9 +88,14 @@ def startApp(application, isSilent=False):
coroutineRunner, categoryService, speedMeter = loadEngine(application)
+ appDir = executableDir.parent.parent if sys.platform == "darwin" else executableDir
+ backupDir = appDir.parent / f"{appDir.name}_backup"
+ if backupDir.is_dir():
+ shutil.rmtree(backupDir, ignore_errors=True)
+
MainWindow.refreshThemeColor()
- featureService, taskService, browserService, aria2RpcServer = createServices(
+ featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService = createServices(
coroutineRunner, categoryService, speedMeter,
)
loadPacks(featureService, coroutineRunner, speedMeter)
@@ -109,7 +116,7 @@ def startApp(application, isSilent=False):
if cfg.isBrowserExtensionEnabled.value:
browserService.start() # 提前启动,OOBE 期间可完成扩展配对
- oobe = OobeWindow(browserService, coroutineRunner, featureService, taskService)
+ oobe = OobeWindow(browserService, coroutineRunner, featureService, runtimeStatusService)
browserService.pairRequested.connect(oobe.onPairRequested)
oobe.show()
@@ -123,11 +130,11 @@ def startApp(application, isSilent=False):
# Python GC 会在任意工作线程 delete,主线程定时器表悬空 → 闪退
oobe.deleteLater()
- window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan)
+ window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan, updateService)
window.setupPacks()
window.show()
else:
- window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan)
+ window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan, updateService)
if not isSilent:
from qfluentwidgets import SplashScreen
@@ -158,7 +165,7 @@ def startApp(application, isSilent=False):
def show() -> MainWindow:
nonlocal window
if window is None:
- window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan)
+ window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan, updateService)
window.setupPacks()
window.destroyed.connect(onWindowDestroyed)
window.show()
@@ -169,7 +176,7 @@ def startApp(application, isSilent=False):
def onBrowserDraft(tasks):
nonlocal window
if window is None:
- window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan)
+ window = MainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, plan, updateService)
window.setupPacks()
window.destroyed.connect(onWindowDestroyed)
window.addTasks(tasks)
@@ -228,9 +235,14 @@ def startApp(application, isSilent=False):
if isSilent:
emptyWorkingSetIfIdle()
- checkUpdateAtStartup(coroutineRunner, onUpdateAvailable=lambda release: show()._onUpdateAvailable(release))
+ from app.services.update_service import UpdateState
+ def onUpdateChanged(info):
+ if info.targetId == "app" and info.state == UpdateState.AVAILABLE:
+ show()._onUpdateAvailable(info)
+ updateService.changed.connect(onUpdateChanged)
+ checkUpdateAtStartup(updateService)
- application.aboutToQuit.connect(lambda: stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner))
+ application.aboutToQuit.connect(lambda: stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner, updateService))
if __name__ == "__main__":
diff --git a/android/main.py b/android/main.py
index 6e0cc6eb..e738bc8e 100644
--- a/android/main.py
+++ b/android/main.py
@@ -65,12 +65,12 @@ def startApp(application):
sys.excepthook = exceptionHook
coroutineRunner, categoryService, speedMeter = loadEngine(application)
- featureService, taskService, browserService, aria2RpcServer = createServices(
+ featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService = createServices(
coroutineRunner, categoryService, speedMeter,
)
loadPacks(featureService, coroutineRunner, speedMeter)
- mainWindow = MobileMainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner)
+ mainWindow = MobileMainWindow(taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, updateService)
mainWindow.show()
setupTouchScrolling(mainWindow)
@@ -116,7 +116,12 @@ def startApp(application):
keepAlive.holdFor(REASON_BROWSER)
browserService.start()
- checkUpdateAtStartup(coroutineRunner, onUpdateAvailable=mainWindow._onUpdateAvailable)
+ from app.services.update_service import UpdateState
+ def onUpdateChanged(info):
+ if info.targetId == "app" and info.state == UpdateState.AVAILABLE:
+ mainWindow._onUpdateAvailable(info)
+ updateService.changed.connect(onUpdateChanged)
+ checkUpdateAtStartup(updateService)
application.aboutToQuit.connect(lambda: stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner))
diff --git a/android/preview.py b/android/preview.py
index 5fb81f2f..1d7457f7 100644
--- a/android/preview.py
+++ b/android/preview.py
@@ -30,7 +30,7 @@ if __name__ == "__main__":
from app.startup import createServices, loadPacks, startEngine, stopEngine
coroutineRunner, categoryService, speedMeter = loadEngine(app)
- featureService, taskService, browserService, aria2RpcServer = createServices(
+ featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService = createServices(
coroutineRunner, categoryService, speedMeter,
)
loadPacks(featureService, coroutineRunner, speedMeter)
diff --git a/app/client.py b/app/client.py
index 042d9bae..64d2cf4f 100644
--- a/app/client.py
+++ b/app/client.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
import sys
from datetime import timedelta
+from pathlib import Path
from typing import TYPE_CHECKING
from loguru import logger
@@ -14,6 +15,7 @@ from wreq.redirect import Policy
from app.config.cfg import cfg, proxy
if TYPE_CHECKING:
+ from collections.abc import Callable
from wreq import ClientConfig
FALLBACK_PROFILE = "chrome"
@@ -156,6 +158,27 @@ def profileVersions(family: str) -> list[str]:
return [name for name, _ver, _profile in PROFILES_BY_FAMILY.get(family, [])]
+async def fetchFile(
+ url: str,
+ outputPath: Path,
+ onProgress: Callable[[float], None] | None = None,
+) -> None:
+ client = buildClient()
+ try:
+ async with client.stream("GET", url) as response:
+ response.raise_for_status()
+ total = int(response.headers.get("content-length", 0))
+ received = 0
+ with open(outputPath, "wb") as f:
+ async for chunk in response.aiter_bytes():
+ f.write(chunk)
+ received += len(chunk)
+ if onProgress and total:
+ onProgress(received / total * 100)
+ finally:
+ client.close()
+
+
def matchEmulation(userAgent: str, host: Platform) -> Emulation | None:
if not userAgent:
return None
diff --git a/features/disk_pack/task.py b/app/install.py
similarity index 75%
rename from features/disk_pack/task.py
rename to app/install.py
index 2db7f515..5b729d36 100644
--- a/features/disk_pack/task.py
+++ b/app/install.py
@@ -7,24 +7,25 @@ import sys
import tarfile
import zipfile
from dataclasses import dataclass, field
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from time import perf_counter
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
from app.models.task import Task, TaskError, TaskStep, TaskStatus
-from app.platform.filesystem import deletePath
+from app.platform.filesystem import deletePath, toPosixPath
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+ from app.models.task import TaskOptions
CHUNK_SIZE = 1 << 20
+ARCHIVE_SUFFIXES = (".zip", ".tar.gz")
-# Disabled: our own HTTP client doesn't set com.apple.quarantine, so for one-click
-# install this is a no-op. Kept (commented) in case a future install source is
-# quarantined (e.g. a user-supplied, browser-downloaded archive). To re-enable,
-# uncomment this plus the two call sites below and restore `import os` / suppress.
-# def removeQuarantine(path: Path) -> None:
-# if sys.platform != "darwin":
-# return
-# with suppress(OSError):
-# os.removexattr(str(path), "com.apple.quarantine")
+def isArchive(name: str) -> bool:
+ lower = name.lower()
+ return any(lower.endswith(suffix) for suffix in ARCHIVE_SUFFIXES)
@dataclass(kw_only=True, eq=False)
@@ -175,7 +176,6 @@ class InstallStep(TaskStep):
raise TaskError("解压后未找到可执行文件:{name}", name=name)
if sys.platform != "win32":
executable.chmod(executable.stat().st_mode | 0o755)
- # removeQuarantine(executable) # disabled — see removeQuarantine note
if self.shouldDeleteSource and archive is not None and archive.exists():
archive.unlink()
@@ -224,5 +224,77 @@ class BinaryInstallStep(TaskStep):
raise TaskError("下载的文件未找到:{path}", path=str(path))
if sys.platform != "win32":
path.chmod(path.stat().st_mode | 0o755)
- # removeQuarantine(path) # disabled — see removeQuarantine note
self.setStatus(TaskStatus.COMPLETED)
+
+
+async def createInstallTask(
+ delegate: Callable[[TaskOptions], Awaitable[Task]],
+ url: str,
+ outputFolder: Path,
+ name: str = "",
+ executableNames: tuple[str, ...] = (),
+ sha256Url: str = "",
+) -> InstallTask:
+ from app.models.task import TaskOptions
+
+ assetName = PurePosixPath(urlparse(url).path).name
+
+ download = await delegate(TaskOptions(url=url, outputFolder=outputFolder))
+ downloadStep = download.steps[0]
+
+ archive = isArchive(assetName)
+ if archive:
+ targetPath = toPosixPath(outputFolder / assetName)
+ else:
+ binaryName = executableNames[0] if executableNames else assetName
+ targetPath = toPosixPath(outputFolder / binaryName)
+ downloadStep.outputFile = targetPath
+
+ task = InstallTask(
+ name=name or assetName,
+ url=url,
+ packId="install",
+ fileSize=download.fileSize,
+ outputFolder=outputFolder,
+ installFolder=str(outputFolder),
+ )
+ stepIndex = 1
+ downloadStep.stepIndex = stepIndex
+ task.addStep(downloadStep)
+ stepIndex += 1
+
+ if sha256Url:
+ checksumDownload = await delegate(
+ TaskOptions(url=sha256Url, outputFolder=outputFolder)
+ )
+ checksumStep = checksumDownload.steps[0]
+ sha256Path = toPosixPath(outputFolder / PurePosixPath(urlparse(sha256Url).path).name)
+ checksumStep.outputFile = sha256Path
+ checksumStep.stepIndex = stepIndex
+ task.addStep(checksumStep)
+ stepIndex += 1
+ task.addStep(ChecksumStep(
+ stepIndex=stepIndex, targetFile=targetPath, sha256File=sha256Path,
+ ))
+ stepIndex += 1
+
+ if archive:
+ extractFolder = toPosixPath(outputFolder / ".extracting")
+ task.addStep(ExtractStep(
+ stepIndex=stepIndex,
+ archivePath=targetPath,
+ outputFolder=extractFolder,
+ archiveSize=download.fileSize,
+ ))
+ stepIndex += 1
+ task.addStep(InstallStep(
+ stepIndex=stepIndex,
+ sourceFolder=extractFolder,
+ installFolder=toPosixPath(outputFolder),
+ archivePath=targetPath,
+ executableNames=list(executableNames),
+ ))
+ else:
+ task.addStep(BinaryInstallStep(stepIndex=stepIndex, binaryPath=targetPath))
+
+ return task
diff --git a/app/models/serialization.py b/app/models/serialization.py
index f7dac3a4..e78af231 100644
--- a/app/models/serialization.py
+++ b/app/models/serialization.py
@@ -8,6 +8,17 @@ if TYPE_CHECKING:
from app.models.task import Task, TaskStep
+def _typeByName(registry: dict[str, type], typeName: str, fallback: type) -> type:
+ found = registry.get(typeName)
+ if found is not None:
+ return found
+ # 向后兼容:旧 tasks.jsonl 用裸类名(如 "BilibiliTask"),扫描 registry 匹配
+ for cls in registry.values():
+ if cls.__name__ == typeName:
+ return cls
+ return fallback
+
+
def toDict(obj: Any) -> Any:
from app.models.task import Task, TaskStep, TaskStatus
@@ -20,9 +31,10 @@ def toDict(obj: Any) -> Any:
f.name: toDict(getattr(obj, f.name))
for f in dataclass_fields(obj) if f.repr
}
+ cls = type(obj)
baseName = "TaskStep" if isinstance(obj, TaskStep) else "Task"
- if type(obj).__name__ != baseName:
- result["type"] = type(obj).__name__
+ if cls.__name__ != baseName:
+ result["type"] = f"{cls.__module__}.{cls.__name__}"
return result
if is_dataclass(obj):
return {
@@ -48,9 +60,9 @@ def fromDict(data: Any, cls: type) -> Any:
typeName = obj.pop("type", None)
if isinstance(typeName, str):
if issubclass(cls, TaskStep):
- targetCls = TaskStep._registry.get(typeName, cls)
+ targetCls = _typeByName(TaskStep._registry, typeName, cls)
elif issubclass(cls, Task):
- targetCls = Task._registry.get(typeName, cls)
+ targetCls = _typeByName(Task._registry, typeName, cls)
else:
targetCls = cls
else:
diff --git a/app/models/task.py b/app/models/task.py
index 5c3f1708..23d3ef17 100644
--- a/app/models/task.py
+++ b/app/models/task.py
@@ -86,13 +86,6 @@ class MergeTaskOptions(TaskOptions):
audio: ResourceTaskOptions | None = None
-@dataclass(frozen=True)
-class BinaryInstallOptions(TaskOptions):
- name: str = ""
- executableNames: tuple[str, ...] = ()
- sha256Url: str = ""
-
-
@dataclass(kw_only=True)
class TaskFile:
index: int
@@ -110,7 +103,7 @@ class TaskStep:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
- TaskStep._registry[cls.__name__] = cls
+ TaskStep._registry[f"{cls.__module__}.{cls.__name__}"] = cls
stepIndex: int
fileIndex: int | None = None
@@ -213,7 +206,7 @@ class Task:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
- Task._registry[cls.__name__] = cls
+ Task._registry[f"{cls.__module__}.{cls.__name__}"] = cls
name: str
url: str
diff --git a/app/platform/filesystem.py b/app/platform/filesystem.py
index a17bee15..b53d01b4 100644
--- a/app/platform/filesystem.py
+++ b/app/platform/filesystem.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import hashlib
import re
import shutil
import sys
@@ -94,6 +95,14 @@ def findExecutable(installFolder: Path, name: str, *subdirs: str) -> str:
return toPosixPath(found) if found else ""
+def matchChecksum(filePath: Path, expectedHex: str) -> bool:
+ digest = hashlib.sha256()
+ with filePath.open("rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ digest.update(chunk)
+ return digest.hexdigest().lower() == expectedHex.lower()
+
+
def deletePath(path: Path) -> None:
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path, ignore_errors=True)
diff --git a/app/services/feature_service.py b/app/services/feature_service.py
index 451daa76..b33e12ef 100644
--- a/app/services/feature_service.py
+++ b/app/services/feature_service.py
@@ -136,8 +136,7 @@ class FeatureService(QObject):
def _createRuntimeCard(self, runtime, parent):
from app.view.components.setting_cards import RuntimeCard
- return RuntimeCard(self._runtimeStatusService, self._coroutineRunner,
- self._taskService, runtime, parent)
+ return RuntimeCard(self._runtimeStatusService, runtime, parent)
# ── Aggregation ──
diff --git a/app/services/pack_loader.py b/app/services/pack_loader.py
index 1b3d72cf..9770a7ed 100644
--- a/app/services/pack_loader.py
+++ b/app/services/pack_loader.py
@@ -20,6 +20,8 @@ class PackManifest:
entryPath: Path
folder: Path
dependencies: tuple[str, ...]
+ version: str
+ gdMinVersion: str
@classmethod
def fromDir(cls, packDir: Path) -> PackManifest | None:
@@ -63,25 +65,49 @@ class PackManifest:
logger.warning("manifest dependencies 无效: {}", manifestPath)
return None
+ version = packSection.get("version", "")
+ if not isinstance(version, str):
+ version = ""
+
+ gdMinVersion = packSection.get("gdMinVersion", "")
+ if not isinstance(gdMinVersion, str):
+ gdMinVersion = ""
+
return cls(
name=packDir.name,
className=className,
entryPath=entryPath,
folder=packDir,
dependencies=tuple(deps),
+ version=version,
+ gdMinVersion=gdMinVersion,
)
def loadPacks(featuresDir: Path, services=None) -> list[FeaturePack]:
+ from PySide6.QtCore import QVersionNumber
+ from app.config.constants import VERSION
+
if not featuresDir.exists():
logger.warning("features 目录不存在: {}", featuresDir)
return []
- manifests = [
- m for p in sorted(featuresDir.iterdir())
- if p.is_dir() and not p.name.startswith(".")
- if (m := PackManifest.fromDir(p)) is not None
- ]
+ appVersion = QVersionNumber.fromString(VERSION)
+
+ manifests = []
+ for p in sorted(featuresDir.iterdir()):
+ if not p.is_dir() or p.name.startswith("."):
+ continue
+ m = PackManifest.fromDir(p)
+ if m is None:
+ continue
+ if m.gdMinVersion:
+ required = QVersionNumber.fromString(m.gdMinVersion)
+ if appVersion < required:
+ logger.warning("跳过 FeaturePack {}:需要 GD ≥ {},当前 {}", m.name, m.gdMinVersion, VERSION)
+ continue
+ manifests.append(m)
+
ordered = orderedByDependency(manifests)
return [pack for m in ordered if (pack := loadManifest(m, services)) is not None]
diff --git a/app/services/runtime_status.py b/app/services/runtime_status.py
index cb338706..b4b89e20 100644
--- a/app/services/runtime_status.py
+++ b/app/services/runtime_status.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
@@ -19,6 +20,7 @@ class RuntimeStatus:
latestVersion: str = ""
error: str = ""
isBusy: bool = False
+ isInstalling: bool = False
class RuntimeStatusService(QObject):
@@ -30,6 +32,7 @@ class RuntimeStatusService(QObject):
self._statuses: dict[str, RuntimeStatus] = {}
self._workIds: dict[str, str] = {}
self._runtimes: dict[str, BinaryRuntime] = {}
+ self._installingIds: set[str] = set()
def status(self, runtime: BinaryRuntime) -> RuntimeStatus:
status = self._statuses.get(runtime.runtimeId)
@@ -55,6 +58,52 @@ class RuntimeStatusService(QObject):
self._runtimes.pop(runtimeId, None)
self._probe(runtime)
+ def install(self, runtime: BinaryRuntime) -> None:
+ runtimeId = runtime.runtimeId
+ if runtimeId in self._installingIds:
+ return
+ workId = self._workIds.pop(runtimeId, None)
+ if workId:
+ self._coroutineRunner.cancel(workId)
+
+ self._installingIds.add(runtimeId)
+ self._runtimes[runtimeId] = runtime
+
+ status = RuntimeStatus(runtimeId, runtime.name, isInstalling=True)
+ self._statuses[runtimeId] = status
+ self.statusChanged.emit(status)
+
+ self._workIds[runtimeId] = self._coroutineRunner.submit(
+ self._runInstall(runtime),
+ done=self._onInstallFinished,
+ failed=self._onInstallFailed,
+ runtimeId=runtimeId,
+ )
+
+ async def _runInstall(self, runtime: BinaryRuntime) -> None:
+ from app.models.task import TaskStatus
+
+ task = await runtime.installTask()
+ task.setStatus(TaskStatus.RUNNING)
+ await task.run(lambda *a: None, lambda: asyncio.sleep(0))
+
+ def _onInstallFinished(self, _, runtimeId: str) -> None:
+ self._installingIds.discard(runtimeId)
+ self._workIds.pop(runtimeId, None)
+ runtime = self._runtimes.get(runtimeId)
+ if runtime:
+ self.invalidate(runtime)
+
+ def _onInstallFailed(self, error: str, runtimeId: str) -> None:
+ self._installingIds.discard(runtimeId)
+ self._workIds.pop(runtimeId, None)
+ self._runtimes.pop(runtimeId, None)
+ current = self._statuses.get(runtimeId)
+ if current:
+ status = replace(current, isInstalling=False, error=error)
+ self._statuses[runtimeId] = status
+ self.statusChanged.emit(status)
+
def _probe(self, runtime: BinaryRuntime) -> None:
runtimeId = runtime.runtimeId
path = runtime.path()
diff --git a/app/services/update_service.py b/app/services/update_service.py
new file mode 100644
index 00000000..ecb71d74
--- /dev/null
+++ b/app/services/update_service.py
@@ -0,0 +1,368 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import tarfile
+import zipfile
+from dataclasses import dataclass, replace
+from enum import auto, IntEnum
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from PySide6.QtCore import QObject, QVersionNumber, Signal
+from loguru import logger
+
+from app.client import buildClient, fetchFile
+from app.config.constants import VERSION
+from app.config.paths import APP_DATA_DIR, executableDir
+from app.platform.filesystem import matchChecksum
+from app.services.pack_loader import PackManifest
+
+if TYPE_CHECKING:
+ from app.services.coroutine_runner import CoroutineRunner
+
+STAGING_DIR = Path(APP_DATA_DIR) / "update_staging"
+
+SOURCES = {
+ "github": {
+ "api": "https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest",
+ "headers": {"accept": "application/vnd.github+json"},
+ },
+ "gitcode": {
+ "api": "https://gitcode.com/api/v5/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest",
+ "headers": {},
+ },
+}
+
+OS_MAP = {"win32": "Windows", "darwin": "macOS", "linux": "Linux"}
+MACHINE_MAP = {"AMD64": "x86_64", "x86_64": "x86_64", "aarch64": "arm64", "arm64": "arm64"}
+
+
+def buildPlatformKey() -> str:
+ return f"{OS_MAP[sys.platform]}-{MACHINE_MAP[platform.machine()]}"
+
+
+def isNewer(current: str, latest: str) -> bool:
+ v1 = QVersionNumber.fromString(current.lstrip("vV"))
+ v2 = QVersionNumber.fromString(latest.lstrip("vV"))
+ return v2 > v1
+
+
+def buildAssetUrl(source: str, version: str, assetName: str) -> str:
+ if source == "gitcode":
+ return f"https://gitcode.com/XiaoYouChR/Ghost-Downloader-3/releases/download/v{version}/{assetName}"
+ return f"https://github.com/XiaoYouChR/Ghost-Downloader-3/releases/download/v{version}/{assetName}"
+
+
+def extractZip(archivePath: Path, targetDir: Path) -> None:
+ with zipfile.ZipFile(archivePath) as zf:
+ zf.extractall(targetDir)
+
+
+def extractTarXz(archivePath: Path, targetDir: Path) -> None:
+ with tarfile.open(archivePath, "r:xz") as tf:
+ tf.extractall(targetDir)
+
+
+async def extractDmg(dmgPath: Path, targetDir: Path) -> None:
+ mountPoint = dmgPath.parent / "_dmg_mount"
+ mountPoint.mkdir(exist_ok=True)
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ "hdiutil", "attach", str(dmgPath), "-mountpoint", str(mountPoint),
+ "-nobrowse", "-quiet",
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
+ )
+ await proc.wait()
+ if proc.returncode != 0:
+ raise RuntimeError(f"hdiutil attach failed ({proc.returncode})")
+
+ apps = [p for p in mountPoint.iterdir() if p.suffix == ".app"]
+ if not apps:
+ raise RuntimeError("DMG 中未找到 .app")
+
+ await asyncio.to_thread(shutil.copytree, apps[0], targetDir)
+ finally:
+ await asyncio.create_subprocess_exec(
+ "hdiutil", "detach", str(mountPoint), "-quiet",
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
+ )
+ if mountPoint.exists():
+ mountPoint.rmdir()
+
+
+def installPendingPacks(featuresDir: Path) -> None:
+ if not featuresDir.exists():
+ return
+ for pending in featuresDir.glob("*_pending"):
+ packId = pending.name.removesuffix("_pending")
+ target = featuresDir / packId
+ if target.exists():
+ shutil.rmtree(target)
+ pending.rename(target)
+ logger.info("已应用 Pack 更新: {}", packId)
+
+
+class UpdateState(IntEnum):
+ IDLE = auto()
+ CHECKING = auto()
+ AVAILABLE = auto()
+ DOWNLOADING = auto()
+ READY = auto()
+ FAILED = auto()
+
+
+@dataclass(frozen=True)
+class UpdateInfo:
+ targetId: str
+ label: str
+ currentVersion: str
+ latestVersion: str
+ state: UpdateState = UpdateState.IDLE
+ progress: float = 0
+ error: str = ""
+
+
+class UpdateService(QObject):
+ changed = Signal(object)
+
+ def __init__(self, coroutineRunner: CoroutineRunner, parent=None):
+ super().__init__(parent)
+ self._coroutineRunner = coroutineRunner
+ self._infos: dict[str, UpdateInfo] = {}
+ self._source = ""
+ self._versionsData: dict = {}
+
+ def check(self) -> None:
+ self._coroutineRunner.submit(self._check())
+
+ def download(self, targetId: str) -> None:
+ self._coroutineRunner.submit(self._download(targetId))
+
+ def apply(self) -> None:
+ for info in self._infos.values():
+ if info.state == UpdateState.READY and info.targetId != "app":
+ self._applyPack(info.targetId)
+ appInfo = self._infos.get("app")
+ if appInfo is not None and appInfo.state == UpdateState.READY:
+ self._startUpdater()
+
+ # ── Private ──
+
+ async def _check(self) -> None:
+ self._emit("app", UpdateState.CHECKING, label=f"Ghost Downloader {VERSION}")
+
+ data = await self._fetchVersions()
+ if data is None:
+ self._emit("app", UpdateState.FAILED, error="无法获取版本信息")
+ return
+ self._versionsData = data
+
+ appData = data.get("app", {})
+ latestVersion = appData.get("version", "")
+ if latestVersion and isNewer(VERSION, latestVersion):
+ self._emit("app", UpdateState.AVAILABLE,
+ label=f"Ghost Downloader {latestVersion}",
+ latestVersion=latestVersion)
+ else:
+ self._emit("app", UpdateState.IDLE)
+
+ packsData = data.get("packs", {})
+ featuresDir = executableDir / "features"
+ for packDir in sorted(featuresDir.iterdir()) if featuresDir.exists() else []:
+ if not packDir.is_dir() or packDir.name.startswith("."):
+ continue
+ manifest = PackManifest.fromDir(packDir)
+ if manifest is None or not manifest.version:
+ continue
+ remoteInfo = packsData.get(manifest.name)
+ if remoteInfo is None:
+ continue
+ remoteVersion = remoteInfo.get("version", "")
+ if remoteVersion and isNewer(manifest.version, remoteVersion):
+ remoteGdMin = remoteInfo.get("gdMinVersion", "")
+ if remoteGdMin and not isNewer(remoteGdMin, VERSION) and remoteGdMin != VERSION:
+ logger.debug("跳过 Pack 更新 {}:需要 GD ≥ {}", manifest.name, remoteGdMin)
+ continue
+ self._emit(manifest.name, UpdateState.AVAILABLE,
+ label=f"{manifest.name} {remoteVersion}",
+ currentVersion=manifest.version,
+ latestVersion=remoteVersion)
+
+ async def _fetchVersions(self) -> dict | None:
+ sources = [self._source] if self._source else list(SOURCES)
+ for sourceName in sources:
+ try:
+ source = SOURCES[sourceName]
+ client = buildClient(headers=source["headers"] or None, timeout=15)
+ try:
+ resp = await client.get(source["api"])
+ resp.raise_for_status()
+ data = await resp.json()
+ for asset in data.get("assets", []):
+ if asset.get("name") == "versions.json":
+ url = asset.get("browser_download_url", "")
+ if not url:
+ continue
+ response = await client.get(url)
+ response.raise_for_status()
+ result = await response.json()
+ self._source = sourceName
+ return result
+ finally:
+ client.close()
+ except Exception as e:
+ logger.debug("从 {} 获取版本信息失败: {}", sourceName, repr(e))
+ continue
+ return None
+
+ async def _download(self, targetId: str) -> None:
+ info = self._infos.get(targetId)
+ if info is None or info.state != UpdateState.AVAILABLE:
+ return
+
+ self._emit(targetId, UpdateState.DOWNLOADING)
+ STAGING_DIR.mkdir(parents=True, exist_ok=True)
+
+ try:
+ if targetId == "app":
+ await self._downloadApp(info)
+ else:
+ await self._downloadPack(targetId, info)
+ except Exception as e:
+ logger.opt(exception=e).error("下载更新失败: {}", targetId)
+ self._emit(targetId, UpdateState.FAILED, error=str(e))
+
+ async def _downloadApp(self, info: UpdateInfo) -> None:
+ appData = self._versionsData.get("app", {})
+ version = appData.get("version", "")
+ platformKey = buildPlatformKey()
+
+ patches = appData.get("patches", {})
+ patch = patches.get(platformKey)
+
+ if patch and patch.get("from") == VERSION:
+ url = buildAssetUrl(self._source, version, patch["file"])
+ sha = patch.get("sha256", "")
+ outputPath = STAGING_DIR / "patch.hdiff"
+
+ await fetchFile(url, outputPath,
+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))
+
+ if sha:
+ if not matchChecksum(outputPath, sha):
+ outputPath.unlink(missing_ok=True)
+ self._emit("app", UpdateState.FAILED, error="校验失败")
+ return
+
+ self._emit("app", UpdateState.READY)
+ return
+
+ full = appData.get("full", {}).get(platformKey)
+ if not full:
+ self._emit("app", UpdateState.FAILED, error="当前平台无可用更新")
+ return
+
+ archivePath = STAGING_DIR / full["file"]
+ sha = full.get("sha256", "")
+
+ await fetchFile(buildAssetUrl(self._source, version, full["file"]), archivePath,
+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))
+
+ if sha and not matchChecksum(archivePath, sha):
+ archivePath.unlink(missing_ok=True)
+ self._emit("app", UpdateState.FAILED, error="校验失败")
+ return
+
+ appDir = executableDir.parent.parent if sys.platform == "darwin" else executableDir
+ newDir = appDir.parent / f"{appDir.name}_new"
+ if newDir.exists():
+ await asyncio.to_thread(shutil.rmtree, newDir)
+
+ if sys.platform == "darwin":
+ await extractDmg(archivePath, newDir)
+ elif archivePath.suffix == ".xz":
+ await asyncio.to_thread(extractTarXz, archivePath, newDir)
+ else:
+ await asyncio.to_thread(extractZip, archivePath, newDir)
+
+ archivePath.unlink(missing_ok=True)
+ self._emit("app", UpdateState.READY)
+
+ async def _downloadPack(self, packId: str, info: UpdateInfo) -> None:
+ appVersion = self._versionsData.get("app", {}).get("version", "")
+ packData = self._versionsData.get("packs", {}).get(packId, {})
+ url = buildAssetUrl(self._source, appVersion, packData.get("file", f"{packId}-{info.latestVersion}.zip"))
+ outputPath = STAGING_DIR / f"{packId}.zip"
+
+ await fetchFile(url, outputPath, onProgress=lambda p: self._emit(packId, UpdateState.DOWNLOADING, progress=p))
+
+ expectedSha = packData.get("sha256", "")
+ if expectedSha and not matchChecksum(outputPath, expectedSha):
+ outputPath.unlink(missing_ok=True)
+ self._emit(packId, UpdateState.FAILED, error="校验失败")
+ return
+
+ self._emit(packId, UpdateState.READY)
+
+ def _applyPack(self, packId: str) -> None:
+ zipPath = STAGING_DIR / f"{packId}.zip"
+ if not zipPath.is_file():
+ return
+ pendingDir = executableDir / "features" / f"{packId}_pending"
+ pendingDir.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(zipPath) as zf:
+ zf.extractall(pendingDir)
+ zipPath.unlink()
+ logger.info("Pack 更新已暂存: {}", packId)
+
+ def _startUpdater(self) -> None:
+ updaterName = "updater.exe" if sys.platform == "win32" else "updater"
+ updaterPath = executableDir / updaterName
+ if not updaterPath.is_file():
+ logger.error("updater not found: {}", updaterPath)
+ return
+
+ appDir = executableDir.parent.parent if sys.platform == "darwin" else executableDir
+ patchPath = STAGING_DIR / "patch.hdiff"
+ newDir = appDir.parent / f"{appDir.name}_new"
+
+ args = [str(updaterPath), str(os.getpid()), str(appDir), sys.executable]
+ if patchPath.is_file():
+ args.append(str(patchPath))
+ elif not newDir.is_dir():
+ logger.error("no patch or newDir found for update")
+ return
+
+ kwargs = {}
+ if sys.platform == "win32":
+ kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
+ else:
+ kwargs["start_new_session"] = True
+
+ subprocess.Popen(args, **kwargs)
+ logger.info("updater started")
+
+ def _emit(self, targetId: str, state: UpdateState, **kwargs) -> None:
+ current = self._infos.get(targetId)
+ if current is None:
+ info = UpdateInfo(
+ targetId=targetId,
+ label=kwargs.get("label", targetId),
+ currentVersion=kwargs.get("currentVersion", VERSION if targetId == "app" else ""),
+ latestVersion=kwargs.get("latestVersion", ""),
+ state=state,
+ progress=kwargs.get("progress", 0),
+ error=kwargs.get("error", ""),
+ )
+ else:
+ info = replace(current, state=state, **{
+ k: v for k, v in kwargs.items()
+ if k in ("label", "currentVersion", "latestVersion", "progress", "error")
+ })
+ self._infos[targetId] = info
+ self.changed.emit(info)
diff --git a/app/startup.py b/app/startup.py
index 53bfb467..a7c7bffe 100644
--- a/app/startup.py
+++ b/app/startup.py
@@ -43,18 +43,24 @@ def createServices(coroutineRunner, categoryService, speedMeter):
from app.services.feature_service import FeatureService
from app.services.runtime_status import RuntimeStatusService
from app.services.task_service import TaskService
+ from app.services.update_service import UpdateService
taskService = TaskService(coroutineRunner, categoryService, speedMeter)
runtimeStatusService = RuntimeStatusService(coroutineRunner)
featureService = FeatureService(taskService, categoryService, coroutineRunner, runtimeStatusService)
browserService = BrowserService(coroutineRunner, taskService, parse=featureService.parse)
aria2RpcServer = Aria2RpcServer(coroutineRunner, parse=featureService.parse, addTask=taskService.add)
+ updateService = UpdateService(coroutineRunner)
- return featureService, taskService, browserService, aria2RpcServer
+ return featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService
def loadPacks(featureService, coroutineRunner, speedMeter):
from app.models.pack import PackConfig, PackServices
+ from app.services.update_service import installPendingPacks
+ from app.config.paths import executableDir
+
+ installPendingPacks(executableDir / "features")
services = PackServices(
coroutineRunner=coroutineRunner,
@@ -76,24 +82,20 @@ def bindNotifications(taskService, notifyCompleted, notifyDiskSpace):
taskService.diskSpaceInsufficient.connect(notifyDiskSpace)
-def checkUpdateAtStartup(coroutineRunner, onUpdateAvailable):
+def checkUpdateAtStartup(updateService):
from app.config.cfg import cfg
if not cfg.shouldCheckUpdateAtStartup.value:
return
- from app.update import fetchRelease, isOutdated
-
- def _onFetched(release):
- if isOutdated(release):
- onUpdateAvailable(release)
-
- coroutineRunner.submit(fetchRelease(), done=_onFetched)
+ updateService.check()
-def stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner):
+def stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner, updateService=None):
taskService.stop()
taskService.flush()
browserService.stop()
aria2RpcServer.stop()
featureService.deactivate(coroutineRunner)
taskService.flush()
+ if updateService is not None:
+ updateService.apply()
coroutineRunner.stop()
diff --git a/app/update.py b/app/update.py
index 5e70bc8f..3ab31429 100644
--- a/app/update.py
+++ b/app/update.py
@@ -3,16 +3,9 @@ from __future__ import annotations
import platform
import sys
from dataclasses import dataclass
-from typing import Any, TYPE_CHECKING
-
-if TYPE_CHECKING:
- from PySide6.QtWidgets import QWidget
-
-from PySide6.QtCore import QVersionNumber
+from typing import Any
from app.client import buildClient
-from app.config.cfg import cfg, proxy
-from app.config.constants import VERSION
RELEASE_API = "https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest"
@@ -85,12 +78,6 @@ async def fetchGitHubLatestTag(repo: str) -> str:
client.close()
-def isOutdated(release: Release) -> bool:
- current = QVersionNumber.fromString(VERSION.lstrip("vV"))
- latest = QVersionNumber.fromString(release.version.lstrip("vV"))
- return current < latest
-
-
def bestAsset(release: Release) -> ReleaseAsset | None:
best, bestScore = None, -1
for asset in release.assets:
@@ -160,40 +147,3 @@ def assetScore(name: str) -> int:
score += 50
return score
-
-
-def showReleaseDialog(release: Release, parent: QWidget, coroutineRunner, featureService, taskService) -> None:
- from app.view.dialogs.release_info import ReleaseInfoDialog
- dialog = ReleaseInfoDialog(release, parent)
- dialog.accepted.connect(lambda: addAssetTask(dialog.selectedAsset(), parent, coroutineRunner, featureService, taskService))
- dialog.open()
-
-
-def addBestAssetTask(release: Release, parent: QWidget, coroutineRunner, featureService, taskService) -> None:
- from qfluentwidgets import InfoBar, InfoBarPosition
- asset = bestAsset(release)
- if asset is None:
- InfoBar.warning(
- parent.tr("未找到适配的安装包"),
- parent.tr("请在版本详情中手动选择"),
- duration=3000, position=InfoBarPosition.BOTTOM_RIGHT, parent=parent,
- )
- showReleaseDialog(release, parent, coroutineRunner, featureService, taskService)
- return
- addAssetTask(asset, parent, coroutineRunner, featureService, taskService)
-
-
-def addAssetTask(asset: ReleaseAsset, parent: QWidget, coroutineRunner, featureService, taskService) -> None:
- from qfluentwidgets import InfoBar, InfoBarPosition
- from app.models.task import TaskOptions
- coroutineRunner.submit(
- featureService.parse(TaskOptions(url=asset.downloadUrl)),
- done=taskService.add,
- failed=lambda e: InfoBar.error(
- parent.tr("创建下载任务失败"), str(e),
- duration=3000, position=InfoBarPosition.BOTTOM_RIGHT, parent=parent,
- ),
- owner=parent,
- )
-
-
diff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.py
index 9bffa5f1..b2642f52 100644
--- a/app/view/cards/task_cards.py
+++ b/app/view/cards/task_cards.py
@@ -26,11 +26,12 @@ if TYPE_CHECKING:
from qfluentwidgets import MessageBoxBase
+
@dataclass(frozen=True)
class FieldSpec:
name: str
icon: FluentIcon
- formats: dict[TaskStatus | None, Callable]
+ formats: dict[TaskStatus | None, Callable[[Task, int, int], str | None]]
@dataclass(frozen=True)
diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.py
index 02327349..c3bc1214 100644
--- a/app/view/components/setting_cards.py
+++ b/app/view/components/setting_cards.py
@@ -2,7 +2,6 @@ from __future__ import annotations
from re import compile
from urllib.parse import urlsplit
-import weakref
from PySide6.QtCore import Qt, QEvent, QRectF, Signal
from PySide6.QtGui import QPainter, QPainterPath
@@ -797,13 +796,10 @@ class SelectFileCard(SettingCard):
class RuntimeCard(SettingCard):
- def __init__(self, runtimeStatusService, coroutineRunner, taskService,
- runtime, parent=None):
+ def __init__(self, runtimeStatusService, runtime, parent=None):
from app.models.pack import BinaryRuntime
self._runtimeStatusService = runtimeStatusService
- self._coroutineRunner = coroutineRunner
- self._taskService = taskService
self._runtime: BinaryRuntime = runtime
super().__init__(FluentIcon.INFO, runtime.name, self.tr("正在检测运行时..."), parent)
@@ -843,7 +839,7 @@ class RuntimeCard(SettingCard):
self._runtimeStatusService.refreshStatus(self._runtime)
def updateStatus(self, status) -> None:
- self.refreshButton.setEnabled(not status.isBusy)
+ self.refreshButton.setEnabled(not status.isBusy and not status.isInstalling)
isInstalled = bool(status.path)
isManaged = self._runtime.isAppManaged()
isUpdateAvailable = (
@@ -852,6 +848,12 @@ class RuntimeCard(SettingCard):
and (not status.version or self._runtime.isNewer(status.version, status.latestVersion))
)
+ if status.isInstalling:
+ self.setContent(self.tr("正在安装..."))
+ self.installButton.hide()
+ self.deleteButton.hide()
+ return
+
if status.isBusy:
self.setContent(self.tr("正在检测运行时..."))
self.installButton.hide()
@@ -896,43 +898,7 @@ class RuntimeCard(SettingCard):
self.updateStatus(status)
def _onInstallClicked(self) -> None:
- self.installButton.setEnabled(False)
- cardRef = weakref.ref(self)
- _taskService = self._taskService
-
- def onCreated(task) -> None:
- from shiboken6 import isValid
-
- _taskService.add(task)
- card = cardRef()
- if card is not None and isValid(card):
- card.installButton.setEnabled(True)
- InfoBar.success(
- self.tr("安装任务已创建"),
- self.tr("请前往任务页查看安装进度"),
- duration=3000,
- position=InfoBarPosition.TOP,
- parent=card.window(),
- )
-
- def onFailed(error: str) -> None:
- from shiboken6 import isValid
-
- card = cardRef()
- if card is not None and isValid(card):
- card._onInstallTaskFailed(error)
-
- self._coroutineRunner.submit(self._runtime.installTask(), done=onCreated, failed=onFailed)
-
- def _onInstallTaskFailed(self, error: str) -> None:
- self.installButton.setEnabled(True)
- InfoBar.error(
- self.tr("安装失败"),
- error,
- duration=-1,
- position=InfoBarPosition.TOP,
- parent=self.window(),
- )
+ self._runtimeStatusService.install(self._runtime)
def _onDeleteClicked(self) -> None:
from qfluentwidgets import MessageBox
diff --git a/app/view/mobile/window.py b/app/view/mobile/window.py
index 38e2d155..3e1cad3b 100644
--- a/app/view/mobile/window.py
+++ b/app/view/mobile/window.py
@@ -13,7 +13,7 @@ from app.config.cfg import cfg
from app.platform.android import clearShare, isStorageGranted, parseShare, requestStoragePermission
from app.platform.android_notification import isNotificationEnabled, requestNotificationPermission
from app.services.task_draft import TaskDraft
-from app.update import addBestAssetTask, showReleaseDialog
+from app.services.update_service import UpdateState
from app.view.dialogs.task_draft import TaskDraftDialog
from app.view.mobile.device import setupAccentColor
from app.view.mobile.navigation import BottomNavigationBar
@@ -25,7 +25,7 @@ TASK_PAGE_INDEX = 0
class MobileMainWindow(QWidget):
- def __init__(self, taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner):
+ def __init__(self, taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, updateService=None):
super().__init__(parent=None)
self._taskService = taskService
self._featureService = featureService
@@ -33,6 +33,7 @@ class MobileMainWindow(QWidget):
self._categoryService = categoryService
self._speedMeter = speedMeter
self._coroutineRunner = coroutineRunner
+ self._updateService = updateService
setupAccentColor()
self.stackedWidget = QStackedWidget(self)
@@ -199,13 +200,13 @@ class MobileMainWindow(QWidget):
return
self._draftDialog.showMask()
- def _onUpdateAvailable(self, release) -> None:
+ def _onUpdateAvailable(self, info) -> None:
from qfluentwidgets import PrimaryPushButton, PushButton
infoBar = InfoBar(
icon=FluentIcon.CLOUD,
title=self.tr("检测到新版本"),
- content=self.tr("最新版本: {0}").format(release.version),
+ content=self.tr("最新版本: {0}").format(info.latestVersion),
orient=Qt.Orientation.Vertical,
isClosable=True,
duration=-1,
@@ -213,13 +214,29 @@ class MobileMainWindow(QWidget):
parent=self,
)
downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))
- downloadButton.clicked.connect(lambda: addBestAssetTask(release, self, self._coroutineRunner, self._featureService, self._taskService))
+ downloadButton.clicked.connect(lambda: self._updateService.download("app"))
infoBar.addWidget(downloadButton)
detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))
- detailButton.clicked.connect(lambda: showReleaseDialog(release, self, self._coroutineRunner, self._featureService, self._taskService))
+ detailButton.clicked.connect(self._showReleaseDetails)
infoBar.addWidget(detailButton)
infoBar.show()
+ def _showReleaseDetails(self) -> None:
+ from app.models.task import TaskOptions
+ from app.update import fetchRelease
+ from app.view.dialogs.release_info import ReleaseInfoDialog
+
+ def onFetched(release):
+ dialog = ReleaseInfoDialog(release, self)
+ dialog.accepted.connect(lambda: self._coroutineRunner.submit(
+ self._featureService.parse(TaskOptions(url=dialog.selectedAsset().downloadUrl)),
+ done=self._taskService.add,
+ owner=self,
+ ))
+ dialog.open()
+
+ self._coroutineRunner.submit(fetchRelease(), done=onFetched, owner=self)
+
def alertException(self, message: str) -> None:
from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.py
index ab74e1f7..9fe6ef24 100644
--- a/app/view/pages/setting_page.py
+++ b/app/view/pages/setting_page.py
@@ -27,7 +27,7 @@ from app.view.components.setting_cards import (
HeadersPresetSettingCard, IdentitySettingCard, LineEditSettingCard,
PercentSpinBoxSettingCard, ProxySettingCard, SpinBoxSettingCard,
)
-from app.update import fetchRelease, isOutdated, showReleaseDialog
+from app.update import fetchRelease
from app.view.components.editors import FolderPicker
@@ -510,13 +510,25 @@ class SettingPage(ScrollArea):
)
def _onUpdateChecked(self, release) -> None:
- if not isOutdated(release):
+ from PySide6.QtCore import QVersionNumber
+ current = QVersionNumber.fromString(VERSION.lstrip("vV"))
+ latest = QVersionNumber.fromString(release.version.lstrip("vV"))
+ if current >= latest:
InfoBar.success(self.tr("当前已是最新版本"),
self.tr("当前版本 {0},最新版本 {1}").format(VERSION, release.version),
duration=3000, position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window())
return
- showReleaseDialog(release, self.window(), self._coroutineRunner, self._featureService, self._taskService)
+ from app.models.task import TaskOptions
+ from app.view.dialogs.release_info import ReleaseInfoDialog
+ parent = self.window()
+ dialog = ReleaseInfoDialog(release, parent)
+ dialog.accepted.connect(lambda: self._coroutineRunner.submit(
+ self._featureService.parse(TaskOptions(url=dialog.selectedAsset().downloadUrl)),
+ done=self._taskService.add,
+ owner=parent,
+ ))
+ dialog.open()
def _onUpdateCheckFailed(self, error: str) -> None:
InfoBar.error(self.tr("检查更新失败"), self.tr("无法获取最新版本信息"),
diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.py
index b3e97754..9d824c6b 100644
--- a/app/view/windows/main_window.py
+++ b/app/view/windows/main_window.py
@@ -16,7 +16,7 @@ from app.config.cfg import CloseMode, cfg
from app.config.constants import DONATE_URL, FEEDBACK_URL
from app.services.task_draft import TaskDraft
from app.signal_bus import signalBus
-from app.update import addBestAssetTask, showReleaseDialog
+from app.services.update_service import UpdateState
from app.view.pages.setting_page import SettingPage
from app.view.pages.task_page import TaskPage
@@ -75,6 +75,7 @@ class MainWindow(MSFluentWindow):
speedMeter: SpeedMeter,
coroutineRunner: CoroutineRunner,
plan,
+ updateService=None,
parent=None,
):
self._isGeometryRestored = False
@@ -89,6 +90,7 @@ class MainWindow(MSFluentWindow):
self._categoryService = categoryService
self._coroutineRunner = coroutineRunner
self._speedMeter = speedMeter
+ self._updateService = updateService
self._plan = plan
self.setMicaEffectEnabled(False)
if sys.platform != "darwin":
@@ -285,13 +287,13 @@ class MainWindow(MSFluentWindow):
else:
self._browserService.rejectPair(session, requestId)
- def _onUpdateAvailable(self, release) -> None:
+ def _onUpdateAvailable(self, info) -> None:
from qfluentwidgets import PrimaryPushButton, PushButton
infoBar = InfoBar(
icon=FluentIcon.CLOUD,
title=self.tr("检测到新版本"),
- content=self.tr("最新版本: {0}").format(release.version),
+ content=self.tr("最新版本: {0}").format(info.latestVersion),
orient=Qt.Orientation.Horizontal,
isClosable=True,
duration=-1,
@@ -299,16 +301,32 @@ class MainWindow(MSFluentWindow):
parent=self,
)
downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))
- downloadButton.clicked.connect(lambda: addBestAssetTask(release, self, self._coroutineRunner, self._featureService, self._taskService))
+ downloadButton.clicked.connect(lambda: self._updateService.download("app"))
infoBar.addWidget(downloadButton)
detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))
- detailButton.clicked.connect(lambda: showReleaseDialog(release, self, self._coroutineRunner, self._featureService, self._taskService))
+ detailButton.clicked.connect(self._showReleaseDetails)
infoBar.addWidget(detailButton)
sponsorButton = PushButton(FluentIcon.HEART, self.tr("请作者喝咖啡"))
sponsorButton.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(DONATE_URL)))
infoBar.addWidget(sponsorButton)
infoBar.show()
+ def _showReleaseDetails(self) -> None:
+ from app.models.task import TaskOptions
+ from app.update import fetchRelease
+ from app.view.dialogs.release_info import ReleaseInfoDialog
+
+ def onFetched(release):
+ dialog = ReleaseInfoDialog(release, self)
+ dialog.accepted.connect(lambda: self._coroutineRunner.submit(
+ self._featureService.parse(TaskOptions(url=dialog.selectedAsset().downloadUrl)),
+ done=self._taskService.add,
+ owner=self,
+ ))
+ dialog.open()
+
+ self._coroutineRunner.submit(fetchRelease(), done=onFetched, owner=self)
+
def alertException(self, message: str) -> None:
from qfluentwidgets import TransparentToolButton, ToolTipFilter
diff --git a/app/view/windows/oobe_window.py b/app/view/windows/oobe_window.py
index 2371ebce..83f22872 100644
--- a/app/view/windows/oobe_window.py
+++ b/app/view/windows/oobe_window.py
@@ -783,15 +783,14 @@ class OobeWindow(FluentWidget):
PAGE_COUNT = 6
def __init__(self, browserService, coroutineRunner, featureService,
- taskService, parent=None):
+ runtimeStatusService, parent=None):
super().__init__(parent=parent)
self._browserService = browserService
self._coroutineRunner = coroutineRunner
self._featureService = featureService
- self._taskService = taskService
+ self._runtimeStatusService = runtimeStatusService
self._currentIndex = 0
self._isFinished = False
- self._queuedRuntimeIds: set[str] = set()
self._initWidget()
self._initContent()
self._initLayout()
@@ -930,26 +929,10 @@ class OobeWindow(FluentWidget):
if not runtimes:
return
- from loguru import logger
-
- _taskService = self._taskService
-
- def onDone(task, name):
- _taskService.add(task)
-
- def onFailed(error, name):
- logger.error("OOBE 安装 {} 失败: {}", name, error)
-
for runtime in runtimes:
- if runtime.path() or runtime.runtimeId in self._queuedRuntimeIds:
+ if runtime.path():
continue
- self._queuedRuntimeIds.add(runtime.runtimeId)
- self._coroutineRunner.submit(
- runtime.installTask(),
- done=onDone,
- failed=onFailed,
- name=runtime.name,
- )
+ self._runtimeStatusService.install(runtime)
def _finish(self) -> None:
if self._isFinished:
diff --git a/features/bili_pack/manifest.toml b/features/bili_pack/manifest.toml
index a401ca6b..a36a640f 100644
--- a/features/bili_pack/manifest.toml
+++ b/features/bili_pack/manifest.toml
@@ -2,3 +2,5 @@
entry = "pack.py"
class = "BilibiliPack"
dependencies = ["http_pack", "ffmpeg_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/bittorrent_pack/manifest.toml b/features/bittorrent_pack/manifest.toml
index b7d7bed5..af3f0a07 100644
--- a/features/bittorrent_pack/manifest.toml
+++ b/features/bittorrent_pack/manifest.toml
@@ -2,3 +2,5 @@
entry = "pack.py"
class = "BitTorrentPack"
dependencies = []
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/disk_pack/error_catalog.py b/features/disk_pack/error_catalog.py
deleted file mode 100644
index aae10ed8..00000000
--- a/features/disk_pack/error_catalog.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from PySide6.QtCore import QT_TRANSLATE_NOOP as N
-
-N("TaskErrors", "压缩包包含不安全路径:{path}")
-N("TaskErrors", "压缩包未找到:{path}")
-N("TaskErrors", "不支持的压缩格式:{name}")
-N("TaskErrors", "解压后未找到可执行文件:{name}")
-N("TaskErrors", "无法读取校验文件:{path}")
-N("TaskErrors", "SHA256 校验失败:期望 {expected},实际 {actual}")
-N("TaskErrors", "下载的文件未找到:{path}")
diff --git a/features/disk_pack/manifest.toml b/features/disk_pack/manifest.toml
deleted file mode 100644
index de92ddba..00000000
--- a/features/disk_pack/manifest.toml
+++ /dev/null
@@ -1,3 +0,0 @@
-[pack]
-entry = "pack.py"
-class = "DiskPack"
diff --git a/features/disk_pack/pack.py b/features/disk_pack/pack.py
deleted file mode 100644
index 2fa6368b..00000000
--- a/features/disk_pack/pack.py
+++ /dev/null
@@ -1,98 +0,0 @@
-from __future__ import annotations
-
-from pathlib import PurePosixPath
-from urllib.parse import urlparse
-
-from app.models.pack import FeaturePack, TaskParser
-from app.models.task import BinaryInstallOptions, Task, TaskOptions
-from app.platform.filesystem import toPosixPath
-from .task import BinaryInstallStep, ChecksumStep, ExtractStep, InstallStep, InstallTask
-
-ARCHIVE_SUFFIXES = (".zip", ".tar.gz")
-
-
-def isArchive(name: str) -> bool:
- lower = name.lower()
- return any(lower.endswith(suffix) for suffix in ARCHIVE_SUFFIXES)
-
-
-def assetNameFromUrl(url: str) -> str:
- return PurePosixPath(urlparse(url).path).name
-
-
-class InstallParser(TaskParser):
- priority = 55
-
- def match(self, options: TaskOptions) -> bool:
- return isinstance(options, BinaryInstallOptions)
-
- async def parse(self, options: BinaryInstallOptions) -> Task:
- installFolder = options.outputFolder
- assetName = assetNameFromUrl(options.url)
-
- download = await self.delegate(
- TaskOptions(url=options.url, outputFolder=installFolder)
- )
- downloadStep = download.steps[0]
-
- archive = isArchive(assetName)
- if archive:
- targetPath = toPosixPath(installFolder / assetName)
- else:
- binaryName = options.executableNames[0] if options.executableNames else assetName
- targetPath = toPosixPath(installFolder / binaryName)
- downloadStep.outputFile = targetPath
-
- task = InstallTask(
- name=options.name or assetName,
- url=options.url,
- packId="disk",
- fileSize=download.fileSize,
- outputFolder=installFolder,
- installFolder=str(installFolder),
- )
- stepIndex = 1
- downloadStep.stepIndex = stepIndex
- task.addStep(downloadStep)
- stepIndex += 1
-
- if options.sha256Url:
- checksumDownload = await self.delegate(
- TaskOptions(url=options.sha256Url, outputFolder=installFolder)
- )
- checksumStep = checksumDownload.steps[0]
- sha256Path = toPosixPath(installFolder / assetNameFromUrl(options.sha256Url))
- checksumStep.outputFile = sha256Path
- checksumStep.stepIndex = stepIndex
- task.addStep(checksumStep)
- stepIndex += 1
- task.addStep(ChecksumStep(
- stepIndex=stepIndex, targetFile=targetPath, sha256File=sha256Path,
- ))
- stepIndex += 1
-
- if archive:
- extractFolder = toPosixPath(installFolder / ".extracting")
- task.addStep(ExtractStep(
- stepIndex=stepIndex,
- archivePath=targetPath,
- outputFolder=extractFolder,
- archiveSize=download.fileSize,
- ))
- stepIndex += 1
- task.addStep(InstallStep(
- stepIndex=stepIndex,
- sourceFolder=extractFolder,
- installFolder=toPosixPath(installFolder),
- archivePath=targetPath,
- executableNames=list(options.executableNames),
- ))
- else:
- task.addStep(BinaryInstallStep(stepIndex=stepIndex, binaryPath=targetPath))
-
- return task
-
-
-class DiskPack(FeaturePack):
- packId = "disk"
- parsers = [InstallParser]
diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.py
index 9c5d1b78..1fe719d5 100644
--- a/features/ed2k_pack/config.py
+++ b/features/ed2k_pack/config.py
@@ -101,7 +101,7 @@ class ED2kRuntime(BinaryRuntime):
async def installTask(self):
from app.models.task import TaskOptions
- from disk_pack.task import InstallTask
+ from app.install import InstallTask
from .task import ED2kInstallStep
assetName = _assetName()
diff --git a/features/ed2k_pack/manifest.toml b/features/ed2k_pack/manifest.toml
index 54bdc2ba..b2bb1795 100644
--- a/features/ed2k_pack/manifest.toml
+++ b/features/ed2k_pack/manifest.toml
@@ -1,4 +1,6 @@
[pack]
entry = "pack.py"
class = "ED2kPack"
-dependencies = ["disk_pack"]
+dependencies = []
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.py
index a1357c47..d65ba94a 100644
--- a/features/ffmpeg_pack/config.py
+++ b/features/ffmpeg_pack/config.py
@@ -117,7 +117,7 @@ class FFmpegRuntime(BinaryRuntime):
shutil.rmtree(folder)
async def installTask(self) -> Task:
- from app.models.task import BinaryInstallOptions
+ from app.install import createInstallTask
target = ffmpegAssetTarget()
extension = "zip" if sys.platform == "win32" else "tar.gz"
@@ -126,13 +126,14 @@ class FFmpegRuntime(BinaryRuntime):
("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32"
else ("ffmpeg", "ffprobe")
)
- return await self.parse(BinaryInstallOptions(
+ return await createInstallTask(
+ self.parse,
url=url,
outputFolder=Path(ffmpegConfig.installFolder.value),
name=f"FFmpeg 安装 ({target})",
executableNames=executableNames,
sha256Url=f"{url}.sha256",
- ))
+ )
ffmpegRuntime = FFmpegRuntime()
diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.toml
index 3576f5ed..19d6a611 100644
--- a/features/ffmpeg_pack/manifest.toml
+++ b/features/ffmpeg_pack/manifest.toml
@@ -1,4 +1,6 @@
[pack]
entry = "pack.py"
class = "FFmpegPack"
-dependencies = ["http_pack", "disk_pack"]
+dependencies = ["http_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/ftp_pack/manifest.toml b/features/ftp_pack/manifest.toml
index 7cf5abe0..96ce52f0 100644
--- a/features/ftp_pack/manifest.toml
+++ b/features/ftp_pack/manifest.toml
@@ -1,3 +1,5 @@
[pack]
entry = "pack.py"
class = "FtpPack"
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/github_pack/manifest.toml b/features/github_pack/manifest.toml
index 390da33b..6f6f25c5 100644
--- a/features/github_pack/manifest.toml
+++ b/features/github_pack/manifest.toml
@@ -2,3 +2,5 @@
entry = "pack.py"
class = "GitHubPack"
dependencies = ["http_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/http_pack/manifest.toml b/features/http_pack/manifest.toml
index d7cb4e26..a4525755 100644
--- a/features/http_pack/manifest.toml
+++ b/features/http_pack/manifest.toml
@@ -2,3 +2,5 @@
entry = "pack.py"
class = "HttpPack"
dependencies = []
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/huggingface_pack/manifest.toml b/features/huggingface_pack/manifest.toml
index 0e3e1e12..e5f01bad 100644
--- a/features/huggingface_pack/manifest.toml
+++ b/features/huggingface_pack/manifest.toml
@@ -2,3 +2,5 @@
entry = "pack.py"
class = "HuggingFacePack"
dependencies = ["http_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.py
index cfe7714d..eed711ff 100644
--- a/features/m3u8_pack/config.py
+++ b/features/m3u8_pack/config.py
@@ -188,14 +188,15 @@ class M3U8Runtime(BinaryRuntime):
url, tag = await self._fetchAssetUrl(target)
- from app.models.task import BinaryInstallOptions
+ from app.install import createInstallTask
binaryName = "N_m3u8DL-RE.exe" if sys.platform == "win32" else "N_m3u8DL-RE"
- return await self.parse(BinaryInstallOptions(
+ return await createInstallTask(
+ self.parse,
url=url,
outputFolder=Path(m3u8Config.installFolder.value),
name=f"N_m3u8DL-RE {tag} ({target})",
executableNames=(binaryName,),
- ))
+ )
async def _fetchAssetUrl(self, target: str) -> tuple[str, str]:
from app.client import buildClient
diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.toml
index f09ec6b5..02fa5f7e 100644
--- a/features/m3u8_pack/manifest.toml
+++ b/features/m3u8_pack/manifest.toml
@@ -1,4 +1,6 @@
[pack]
entry = "pack.py"
class = "M3U8Pack"
-dependencies = ["http_pack", "disk_pack", "ffmpeg_pack"]
+dependencies = ["http_pack", "ffmpeg_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
index 9b956e07..0602c4db 100644
--- a/features/yt_dlp_pack/config.py
+++ b/features/yt_dlp_pack/config.py
@@ -229,7 +229,7 @@ class YouTubeRuntime(BinaryRuntime):
async def installTask(self):
from app.config.cfg import cfg, currentHeaders
- from disk_pack.task import ExtractStep, InstallTask
+ from app.install import ExtractStep, InstallTask
from http_pack.task import HttpTaskStep
whlUrl, whlSize = await self._fetchWhlAsset()
@@ -264,7 +264,7 @@ class YouTubeRuntime(BinaryRuntime):
))
return task
- from disk_pack.task import BinaryInstallStep
+ from app.install import BinaryInstallStep
from app.models.task import TaskOptions
qjsBinaryName = "qjs.exe" if sys.platform == "win32" else "qjs"
diff --git a/features/yt_dlp_pack/manifest.toml b/features/yt_dlp_pack/manifest.toml
index e92cc737..e0fcd227 100644
--- a/features/yt_dlp_pack/manifest.toml
+++ b/features/yt_dlp_pack/manifest.toml
@@ -1,4 +1,6 @@
[pack]
entry = "pack.py"
class = "YouTubePack"
-dependencies = ["http_pack", "disk_pack", "ffmpeg_pack"]
+dependencies = ["http_pack", "ffmpeg_pack"]
+version = "1.0.0"
+gdMinVersion = "4.2.0"
diff --git a/tools/updater/CMakeLists.txt b/tools/updater/CMakeLists.txt
new file mode 100644
index 00000000..f5eeec25
--- /dev/null
+++ b/tools/updater/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.20)
+project(gd3-updater C)
+
+set(CMAKE_C_STANDARD 11)
+
+if(APPLE)
+ set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64")
+endif()
+
+add_executable(updater updater.c)
+
+if(WIN32)
+ set_property(TARGET updater PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded")
+ target_link_libraries(updater PRIVATE shell32)
+endif()
diff --git a/tools/updater/updater.c b/tools/updater/updater.c
new file mode 100644
index 00000000..37fb9057
--- /dev/null
+++ b/tools/updater/updater.c
@@ -0,0 +1,344 @@
+/*
+ * Usage: updater <appPID> <appDir> <appExe> [patchFile]
+ * Exit: 0 ok · 1 patch · 2 rename · 3 timeout · 4 launch · 5 args
+ */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+ #define WIN32_LEAN_AND_MEAN
+ #include <windows.h>
+ #include <shellapi.h>
+#else
+ #include <errno.h>
+ #include <ftw.h>
+ #include <signal.h>
+ #include <spawn.h>
+ #include <sys/wait.h>
+ #include <unistd.h>
+ extern char **environ;
+ #ifdef __APPLE__
+ #include <mach-o/dyld.h>
+ #endif
+#endif
+
+#define PATH_BUF 4096
+
+enum {
+ EXIT_OK = 0,
+ EXIT_PATCH_FAILED = 1,
+ EXIT_RENAME_FAILED= 2,
+ EXIT_WAIT_TIMEOUT = 3,
+ EXIT_LAUNCH_FAILED= 4,
+ EXIT_BAD_ARGS = 5,
+};
+
+static FILE *g_log;
+static char g_logPath[PATH_BUF];
+
+static void toDirname(char *path) {
+ char *sep = strrchr(path, '/');
+#ifdef _WIN32
+ char *bsep = strrchr(path, '\\');
+ if (bsep > sep) sep = bsep;
+#endif
+ if (sep) *sep = '\0';
+ else path[0] = '\0';
+}
+
+static void openLog(const char *appDir) {
+ strncpy(g_logPath, appDir, sizeof(g_logPath) - 1);
+ g_logPath[sizeof(g_logPath) - 1] = '\0';
+ toDirname(g_logPath);
+
+ size_t dirLen = strlen(g_logPath);
+ if (dirLen > 0)
+ snprintf(g_logPath + dirLen, sizeof(g_logPath) - dirLen, "%cupdater.log",
+#ifdef _WIN32
+ '\\');
+#else
+ '/');
+#endif
+ else
+ snprintf(g_logPath, sizeof(g_logPath), "updater.log");
+
+ g_log = fopen(g_logPath, "a");
+}
+
+static void logMsg(const char *fmt, ...) {
+ if (!g_log) return;
+
+ time_t now = time(NULL);
+ struct tm *t = localtime(&now);
+ fprintf(g_log, "%04d-%02d-%02d %02d:%02d:%02d ",
+ t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
+ t->tm_hour, t->tm_min, t->tm_sec);
+
+ va_list ap;
+ va_start(ap, fmt);
+ vfprintf(g_log, fmt, ap);
+ va_end(ap);
+
+ fputc('\n', g_log);
+ fflush(g_log);
+}
+
+static void closeLog(void) {
+ if (g_log) fclose(g_log);
+}
+
+static void findExeDir(char *buf, size_t len) {
+#ifdef _WIN32
+ GetModuleFileNameA(NULL, buf, (DWORD)len);
+#elif defined(__APPLE__)
+ uint32_t size = (uint32_t)len;
+ if (_NSGetExecutablePath(buf, &size) != 0) {
+ buf[0] = '\0';
+ return;
+ }
+#else
+ ssize_t n = readlink("/proc/self/exe", buf, len - 1);
+ if (n > 0)
+ buf[n] = '\0';
+ else {
+ buf[0] = '\0';
+ return;
+ }
+#endif
+ toDirname(buf);
+}
+
+#ifdef _WIN32
+static int waitForProcessExit(unsigned long pid, int timeoutMs) {
+ HANDLE h = OpenProcess(SYNCHRONIZE, FALSE, pid);
+ if (!h) return 0;
+ DWORD r = WaitForSingleObject(h, (DWORD)timeoutMs);
+ CloseHandle(h);
+ return (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED) ? 0 : -1;
+}
+#else
+static int waitForProcessExit(unsigned long pid, int timeoutMs) {
+ for (int elapsed = 0; elapsed < timeoutMs; elapsed += 100) {
+ if (kill((pid_t)pid, 0) != 0) return 0;
+ usleep(100 * 1000);
+ }
+ return -1;
+}
+#endif
+
+static int runHpatchz(const char *dir, const char *oldDir,
+ const char *patchFile, const char *newDir) {
+ char hpatchz[PATH_BUF];
+#ifdef _WIN32
+ snprintf(hpatchz, sizeof(hpatchz), "%s\\hpatchz.exe", dir);
+#else
+ snprintf(hpatchz, sizeof(hpatchz), "%s/hpatchz", dir);
+#endif
+
+ logMsg("running: %s -f \"%s\" \"%s\" \"%s\"", hpatchz, oldDir, patchFile, newDir);
+
+#ifdef _WIN32
+ char cmd[PATH_BUF * 2];
+ snprintf(cmd, sizeof(cmd), "\"%s\" -f \"%s\" \"%s\" \"%s\"",
+ hpatchz, oldDir, patchFile, newDir);
+
+ SECURITY_ATTRIBUTES sa = { .nLength = sizeof(sa), .bInheritHandle = TRUE };
+ HANDLE hLog = g_log
+ ? CreateFileA(g_logPath, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)
+ : INVALID_HANDLE_VALUE;
+
+ STARTUPINFOA si = { .cb = sizeof(si) };
+ if (hLog != INVALID_HANDLE_VALUE) {
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdOutput = hLog;
+ si.hStdError = hLog;
+ }
+
+ PROCESS_INFORMATION pi = {0};
+ if (!CreateProcessA(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
+ if (hLog != INVALID_HANDLE_VALUE) CloseHandle(hLog);
+ return -1;
+ }
+
+ WaitForSingleObject(pi.hProcess, INFINITE);
+ DWORD code = 1;
+ GetExitCodeProcess(pi.hProcess, &code);
+ CloseHandle(pi.hProcess);
+ CloseHandle(pi.hThread);
+ if (hLog != INVALID_HANDLE_VALUE) CloseHandle(hLog);
+ return code == 0 ? 0 : (int)code;
+
+#else
+ posix_spawn_file_actions_t actions;
+ posix_spawn_file_actions_init(&actions);
+ if (g_log) {
+ int fd = fileno(g_log);
+ posix_spawn_file_actions_adddup2(&actions, fd, STDOUT_FILENO);
+ posix_spawn_file_actions_adddup2(&actions, fd, STDERR_FILENO);
+ }
+
+ pid_t child;
+ char *argv[] = {hpatchz, "-f", (char *)oldDir, (char *)patchFile,
+ (char *)newDir, NULL};
+ int err = posix_spawn(&child, hpatchz, &actions, NULL, argv, environ);
+ posix_spawn_file_actions_destroy(&actions);
+ if (err != 0) return -1;
+
+ int status;
+ waitpid(child, &status, 0);
+ return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
+#endif
+}
+
+static int moveDir(const char *from, const char *to) {
+#ifdef _WIN32
+ for (int i = 0; i < 5; i++) {
+ if (MoveFileA(from, to)) return 0;
+ logMsg("rename \"%s\" -> \"%s\" failed (err=%lu), retry %d",
+ from, to, GetLastError(), i + 1);
+ Sleep(100u << i);
+ }
+ return -1;
+#else
+ if (rename(from, to) == 0) return 0;
+ logMsg("rename \"%s\" -> \"%s\" failed: %s", from, to, strerror(errno));
+ return -1;
+#endif
+}
+
+
+#ifdef _WIN32
+static void deleteDir(const char *dir) {
+ char buf[MAX_PATH + 2];
+ memset(buf, 0, sizeof(buf));
+ strncpy(buf, dir, MAX_PATH);
+
+ SHFILEOPSTRUCTA op = {0};
+ op.wFunc = FO_DELETE;
+ op.pFrom = buf;
+ op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
+ SHFileOperationA(&op);
+}
+#else
+static int deletePath(const char *path, const struct stat *sb, int t, struct FTW *f) {
+ (void)sb; (void)t; (void)f;
+ return remove(path);
+}
+
+static void deleteDir(const char *dir) {
+ nftw(dir, deletePath, 64, FTW_DEPTH | FTW_PHYS);
+}
+#endif
+
+static int startApp(const char *exe) {
+#ifdef _WIN32
+ char cmd[PATH_BUF];
+ snprintf(cmd, sizeof(cmd), "\"%s\"", exe);
+
+ STARTUPINFOA si = { .cb = sizeof(si) };
+ PROCESS_INFORMATION pi = {0};
+ if (!CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
+ return -1;
+
+ CloseHandle(pi.hProcess);
+ CloseHandle(pi.hThread);
+ return 0;
+#else
+ pid_t child;
+ char *argv[] = {(char *)exe, NULL};
+ return posix_spawn(&child, exe, NULL, NULL, argv, environ) == 0 ? 0 : -1;
+#endif
+}
+
+int main(int argc, char *argv[]) {
+ if (argc < 4 || argc > 5) {
+ fprintf(stderr, "usage: updater <appPID> <appDir> <appExe> [patchFile]\n");
+ return EXIT_BAD_ARGS;
+ }
+
+ unsigned long appPid = strtoul(argv[1], NULL, 10);
+ const char *appDir = argv[2];
+ const char *appExe = argv[3];
+ const char *patchFile = argc == 5 ? argv[4] : NULL;
+
+ char newDir[PATH_BUF], backupDir[PATH_BUF], updaterDir[PATH_BUF];
+ snprintf(newDir, sizeof(newDir), "%s_new", appDir);
+ snprintf(backupDir, sizeof(backupDir), "%s_backup", appDir);
+ findExeDir(updaterDir, sizeof(updaterDir));
+
+ openLog(appDir);
+ logMsg(" __________ __ ______ ____ ___ ________________");
+ logMsg(" / ____/ __ \\ / / / / __ \\/ __ \\/ |/_ __/ ____/ __ \\");
+ logMsg(" / / __/ / / / / / / / /_/ / / / / /| | / / / __/ / /_/ /");
+ logMsg("/ /_/ / /_/ / / /_/ / ____/ /_/ / ___ |/ / / /___/ _, _/");
+ logMsg("\\____/_____/ \\____/_/ /_____/_/ |_/_/ /_____/_/ |_|");
+ logMsg("pid=%lu appDir=\"%s\" exe=\"%s\" patch=\"%s\"",
+ appPid, appDir, appExe, patchFile ? patchFile : "(full)");
+
+ logMsg("waiting for app %lu ...", appPid);
+ if (waitForProcessExit(appPid, 30000) != 0) {
+ logMsg("timeout");
+ closeLog();
+ return EXIT_WAIT_TIMEOUT;
+ }
+ logMsg("app exited");
+
+ deleteDir(backupDir);
+
+ if (patchFile) {
+ deleteDir(newDir);
+ if (runHpatchz(updaterDir, appDir, patchFile, newDir) != 0) {
+ logMsg("hpatchz failed");
+ deleteDir(newDir);
+ closeLog();
+ return EXIT_PATCH_FAILED;
+ }
+ logMsg("patch applied");
+ }
+
+ int swapOk = 0;
+#ifdef __APPLE__
+ if (renamex_np(newDir, appDir, RENAME_SWAP) == 0) {
+ rename(newDir, backupDir);
+ swapOk = 1;
+ } else {
+ logMsg("renamex_np failed (%s), falling back", strerror(errno));
+ }
+#endif
+ if (!swapOk) {
+ if (moveDir(appDir, backupDir) != 0) {
+ deleteDir(newDir);
+ closeLog();
+ return EXIT_RENAME_FAILED;
+ }
+ if (moveDir(newDir, appDir) != 0) {
+ moveDir(backupDir, appDir);
+ deleteDir(newDir);
+ closeLog();
+ return EXIT_RENAME_FAILED;
+ }
+ }
+ logMsg("installed");
+
+ if (patchFile)
+ remove(patchFile);
+
+ logMsg("starting %s", appExe);
+ if (startApp(appExe) != 0) {
+ logMsg("start failed, rolling back");
+ if (moveDir(appDir, newDir) == 0)
+ moveDir(backupDir, appDir);
+ deleteDir(newDir);
+ closeLog();
+ return EXIT_LAUNCH_FAILED;
+ }
+
+ logMsg("ok");
+ closeLog();
+ return EXIT_OK;
+}