Skip to content

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

feat(update): 支持 Android 补丁更新

XiaoYouChR2018dc6c6154
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 8256021a..501c3068 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1044,12 +1044,37 @@ jobs:
mv "$APK" "$DEST"
echo "APK_FILE=$DEST" >> "$GITHUB_ENV"
+ - name: Generate patch
+ if: ${{ needs.prepare.outputs.patch_base != '' && env.HAS_KEYSTORE == 'true' }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ BASE_VER="${{ needs.prepare.outputs.patch_base }}"
+ BASE_APK="Ghost-Downloader-v${BASE_VER}-Android-arm64-v8a.apk"
+ if ! gh release view "v$BASE_VER" --json assets --jq '.assets[].name' | grep -Fxq "$BASE_APK"; then
+ echo "v$BASE_VER has no Android-arm64 APK, skipping patch"
+ exit 0
+ fi
+
+ curl -fL "https://github.com/sisong/HDiffPatch/releases/download/v5.1.3/hdiffpatch_v5.1.3_bin_linux64.zip" -o hdiffpatch.zip
+ unzip -q hdiffpatch.zip -d hdiffpatch
+ chmod +x hdiffpatch/linux64/hdiffz
+
+ mkdir -p prev
+ gh release download "v$BASE_VER" -p "$BASE_APK" -D prev/
+
+ PATCH_FILE="patch-Android-arm64-${BASE_VER}-to-${{ needs.prepare.outputs.version }}.hdiff"
+ hdiffpatch/linux64/hdiffz -f -c-lzma2 "prev/$BASE_APK" "${{ env.APK_FILE }}" "$PATCH_FILE"
+ 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${{ needs.prepare.outputs.version }}" "${{ env.APK_FILE }}" --clobber
+ FILES=("${{ env.APK_FILE }}")
+ if [ -n "$PATCH_FILE" ] && [ -f "$PATCH_FILE" ]; then FILES+=("$PATCH_FILE"); fi
+ gh release upload "v${{ needs.prepare.outputs.version }}" "${FILES[@]}" --clobber
- name: Upload APK artifact
if: ${{ github.event.inputs.create_release == 'false' }}
@@ -1061,7 +1086,7 @@ jobs:
finalize:
needs: [prepare, build-windows, build-macos, build-ubuntu, build-android]
- if: ${{ always() && github.event.inputs.create_release == 'true' && needs.prepare.result == 'success' && !contains(fromJSON('["failure","cancelled"]'), needs.build-windows.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-macos.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-ubuntu.result) && (needs.build-windows.result == 'success' || needs.build-macos.result == 'success' || needs.build-ubuntu.result == 'success') }}
+ if: ${{ always() && github.event.inputs.create_release == 'true' && needs.prepare.result == 'success' && !contains(fromJSON('["failure","cancelled"]'), needs.build-windows.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-macos.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-ubuntu.result) && !contains(fromJSON('["failure","cancelled"]'), needs.build-android.result) && (needs.build-windows.result == 'success' || needs.build-macos.result == 'success' || needs.build-ubuntu.result == 'success' || needs.build-android.result == 'success') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
@@ -1100,16 +1125,19 @@ jobs:
h.update(chunk)
return h.hexdigest()
- platforms = [
- "Windows-x86_64", "Windows-arm64",
- "macOS-arm64", "macOS-x86_64",
- "Linux-x86_64", "Linux-arm64",
- ]
- full_ext = {"Windows": ".zip", "macOS": ".dmg", "Linux": ".tar.xz"}
+ full_suffix = {
+ "Windows-x86_64": "Windows-x86_64.zip",
+ "Windows-arm64": "Windows-arm64.zip",
+ "macOS-arm64": "macOS-arm64.dmg",
+ "macOS-x86_64": "macOS-x86_64.dmg",
+ "Linux-x86_64": "Linux-x86_64.tar.xz",
+ "Linux-arm64": "Linux-arm64.tar.xz",
+ "Android-arm64": "Android-arm64-v8a.apk",
+ }
patches = {}
full = {}
- for p in platforms:
+ for p, suffix_name in full_suffix.items():
for f in os.listdir(assets_dir):
if f.startswith(f"patch-{p}-") and f.endswith(".hdiff"):
path = os.path.join(assets_dir, f)
@@ -1118,8 +1146,7 @@ jobs:
patches[p] = {"from": from_ver, "file": f, "sha256": sha256of(path), "size": os.path.getsize(path)}
break
- ext = full_ext[p.split("-", 1)[0]]
- full_name = f"Ghost-Downloader-v{version}-{p}{ext}"
+ full_name = f"Ghost-Downloader-v{version}-{suffix_name}"
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)}
diff --git a/GLOSSARY.md b/GLOSSARY.md
index cb72cc9f..b3a8533b 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -318,7 +318,7 @@ Inno Setup 写在 App Dir 里的卸载程序与日志。
_Avoid_: setup、installer
**Patch**:
-一份目录级增量文件。
+一份应用增量文件:桌面端按目录生成,Android 按安装包生成。
_Avoid_: delta、diff
**Staging**:
@@ -338,7 +338,7 @@ _Avoid_: old、prev
_Avoid_: helper、installer
**Apply**:
-退出时把已就绪的更新交出去:Pack 暂存到 Features Dir,应用则启动 Updater。
+把已就绪的更新交出去:桌面端在退出时暂存 Pack 并启动 Updater,Android 调起系统安装器。
_Avoid_: install、commit
**Install**:
diff --git a/app/platform/android.py b/app/platform/android.py
index 57a682bd..0aad7ced 100644
--- a/app/platform/android.py
+++ b/app/platform/android.py
@@ -2,12 +2,55 @@ from __future__ import annotations
import sys
from functools import lru_cache
+from pathlib import Path
+
+from loguru import logger
IS_ANDROID = hasattr(sys, "getandroidapilevel")
+@lru_cache(maxsize=1)
+def application():
+ from java import jclass
+ return jclass("com.chaquo.python.Python").getPlatform().getApplication()
+
+
@lru_cache(maxsize=1)
def nativeLibraryDir() -> str:
+ return application().getApplicationInfo().nativeLibraryDir
+
+
+def isUnmeteredNetwork() -> bool:
+ try:
+ from java import jclass
+ cm = application().getSystemService(jclass("android.content.Context").CONNECTIVITY_SERVICE)
+ return cm is not None and cm.getActiveNetwork() is not None and not cm.isActiveNetworkMetered()
+ except Exception as e:
+ logger.debug("检查网络计费状态失败: {}", repr(e))
+ return False
+
+
+def patchApk(patchPath: Path, outputPath: Path) -> None:
from java import jclass
- activity = jclass("com.chaquo.python.Python").getPlatform().getApplication()
- return activity.getApplicationInfo().nativeLibraryDir
+ oldApk = application().getApplicationInfo().sourceDir
+ code = jclass("com.github.sisong.HPatch").patch(oldApk, str(patchPath), str(outputPath))
+ if code != 0:
+ raise RuntimeError(f"HPatch.patch failed ({code})")
+
+
+def installApk(apkPath: Path) -> bool:
+ try:
+ from java import jclass
+ app = application()
+ uri = jclass("androidx.core.content.FileProvider").getUriForFile(
+ app, f"{app.getPackageName()}.fileprovider", jclass("java.io.File")(str(apkPath)),
+ )
+ Intent = jclass("android.content.Intent")
+ intent = Intent(Intent.ACTION_VIEW)
+ intent.setDataAndType(uri, "application/vnd.android.package-archive")
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK)
+ app.startActivity(intent)
+ return True
+ except Exception as e:
+ logger.warning("启动 APK 安装失败: {}", repr(e))
+ return False
diff --git a/app/services/update_service.py b/app/services/update_service.py
index 5d11d04b..8edc9e5a 100644
--- a/app/services/update_service.py
+++ b/app/services/update_service.py
@@ -136,18 +136,29 @@ class UpdateService:
def download(self, targetId: str) -> None:
self._coroutineRunner.submit(self._download(targetId))
- def apply(self) -> None:
+ def apply(self) -> bool:
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()
+ if appInfo is None or appInfo.state != UpdateState.READY:
+ return False
+ if IS_ANDROID:
+ full = self._versionsData.get("app", {}).get("full", {}).get(f"Android-{MACHINE_ARCH}")
+ apkPath = STAGING_DIR / full["file"] if full and full.get("file") else None
+ if apkPath is None or not apkPath.is_file():
+ return False
+ from app.platform.android import installApk
+ return installApk(apkPath)
+ return self._startUpdater()
# ── Private ──
async def _check(self) -> None:
- self._emit("app", UpdateState.CHECKING, label=f"Ghost Downloader {VERSION}")
+ appInfo = self._infos.get("app")
+ if appInfo is not None and appInfo.state in (UpdateState.CHECKING, UpdateState.DOWNLOADING):
+ return
+ self._emit("app", UpdateState.CHECKING, label=f"Ghost Downloader {VERSION}", error=None)
data = await self._fetchVersions()
if data is None:
@@ -159,10 +170,25 @@ class UpdateService:
appData = data.get("app", {})
latestVersion = appData.get("version", "")
if latestVersion and isNewer(VERSION, latestVersion):
+ full = appData.get("full", {}).get(f"Android-{MACHINE_ARCH}") if IS_ANDROID else None
+ if IS_ANDROID and not full:
+ self._emit("app", UpdateState.IDLE)
+ return
+ apkPath = STAGING_DIR / full["file"] if full and full.get("file") and full.get("sha256") else None
+ if apkPath and apkPath.is_file():
+ if await toChecksum(apkPath, "sha256", lambda _: None) == parseChecksum(full["sha256"]):
+ self._emit("app", UpdateState.READY,
+ label=f"Ghost Downloader {latestVersion}",
+ latestVersion=latestVersion, progress=100)
+ return
+ apkPath.unlink(missing_ok=True)
self._emit("app", UpdateState.AVAILABLE,
- label=f"Ghost Downloader {latestVersion}",
- latestVersion=latestVersion)
+ label=f"Ghost Downloader {latestVersion}",
+ latestVersion=latestVersion)
else:
+ if IS_ANDROID:
+ for path in (*STAGING_DIR.glob("*.apk"), STAGING_DIR / "patch.hdiff"):
+ path.unlink(missing_ok=True)
self._emit("app", UpdateState.IDLE)
if IS_ANDROID:
@@ -193,15 +219,15 @@ class UpdateService:
try:
data, _ = await fetchJson(APP_REPO, "main", "versions.json")
return data
- except RuntimeError:
+ except (TaskError, RuntimeError):
return None
async def _download(self, targetId: str) -> None:
info = self._infos.get(targetId)
- if info is None or info.state != UpdateState.AVAILABLE:
+ if info is None or info.state not in (UpdateState.AVAILABLE, UpdateState.FAILED):
return
- self._emit(targetId, UpdateState.DOWNLOADING)
+ self._emit(targetId, UpdateState.DOWNLOADING, progress=0, error=None)
STAGING_DIR.mkdir(parents=True, exist_ok=True)
try:
@@ -217,27 +243,56 @@ class UpdateService:
appData = self._versionsData.get("app", {})
version = appData.get("version", "")
tag = f"v{version}"
- platformKey = f"{OS_MAP[sys.platform]}-{MACHINE_ARCH}"
+ platformKey = f"{'Android' if IS_ANDROID else OS_MAP[sys.platform]}-{MACHINE_ARCH}"
+ full = appData.get("full", {}).get(platformKey)
patches = appData.get("patches", {})
patch = patches.get(platformKey)
+ if IS_ANDROID:
+ for path in (*STAGING_DIR.glob("*.apk"), STAGING_DIR / "patch.hdiff"):
+ path.unlink(missing_ok=True)
+
if patch and patch.get("from") == VERSION and BUILD_ARCH == MACHINE_ARCH:
- sha = patch.get("sha256", "")
- outputPath = STAGING_DIR / "patch.hdiff"
+ patchPath = STAGING_DIR / "patch.hdiff"
+ patchSha = patch.get("sha256", "")
+ if not IS_ANDROID:
+ await fetchReleaseAsset(APP_REPO, tag, patch["file"], patchPath,
+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))
+
+ if not patchSha or await toChecksum(patchPath, "sha256", lambda _: None) != parseChecksum(patchSha):
+ patchPath.unlink(missing_ok=True)
+ self._emit("app", UpdateState.FAILED, error=TaskError("校验失败"))
+ return
+
+ self._emit("app", UpdateState.READY)
+ return
- await fetchReleaseAsset(APP_REPO, tag, patch["file"], outputPath,
- onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))
+ if full:
+ apkPath = STAGING_DIR / full["file"]
+ try:
+ from app.platform.android import patchApk
- if not sha or await toChecksum(outputPath, "sha256", lambda _: None) != parseChecksum(sha):
- outputPath.unlink(missing_ok=True)
- self._emit("app", UpdateState.FAILED, error=TaskError("校验失败"))
- return
+ await fetchReleaseAsset(APP_REPO, tag, patch["file"], patchPath,
+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))
+ if not patchSha or await toChecksum(patchPath, "sha256", lambda _: None) != parseChecksum(patchSha):
+ raise TaskError("校验失败")
- self._emit("app", UpdateState.READY)
- return
+ await asyncio.to_thread(patchApk, patchPath, apkPath)
+ patchPath.unlink(missing_ok=True)
+
+ fullSha = full.get("sha256", "")
+ if not fullSha or await toChecksum(apkPath, "sha256", lambda _: None) != parseChecksum(fullSha):
+ raise TaskError("校验失败")
+
+ self._emit("app", UpdateState.READY, progress=100)
+ return
+ except Exception as e:
+ logger.warning("Android 补丁更新失败,回退全量下载: {}", repr(e))
+ patchPath.unlink(missing_ok=True)
+ apkPath.unlink(missing_ok=True)
+ self._emit("app", UpdateState.DOWNLOADING, progress=0)
- full = appData.get("full", {}).get(platformKey)
if not full:
self._emit("app", UpdateState.FAILED, error=TaskError("当前平台无可用更新"))
return
@@ -253,6 +308,10 @@ class UpdateService:
self._emit("app", UpdateState.FAILED, error=TaskError("校验失败"))
return
+ if IS_ANDROID:
+ self._emit("app", UpdateState.READY, progress=100)
+ return
+
newDir = STAGING_DIR / "app_new"
if newDir.exists():
await asyncio.to_thread(shutil.rmtree, newDir)
@@ -294,10 +353,10 @@ class UpdateService:
zipPath.unlink()
logger.info("Pack 更新已暂存: {}", packId)
- def _startUpdater(self) -> None:
+ def _startUpdater(self) -> bool:
if not UPDATER_PATH.is_file():
logger.error("updater not found: {}", UPDATER_PATH)
- return
+ return False
patchPath = STAGING_DIR / "patch.hdiff"
stagingNewDir = STAGING_DIR / "app_new"
@@ -310,7 +369,7 @@ class UpdateService:
args.append(str(stagingNewDir))
else:
logger.error("no patch or newDir found for update")
- return
+ return False
kwargs = {}
if sys.platform == "win32":
@@ -320,6 +379,7 @@ class UpdateService:
subprocess.Popen(args, **kwargs)
logger.info("updater started")
+ return True
def _emit(self, targetId: str, state: UpdateState, **kwargs) -> None:
current = self._infos.get(targetId)
diff --git a/docs/adr/0038-android-patch-uses-hdiffpatch.md b/docs/adr/0038-android-patch-uses-hdiffpatch.md
new file mode 100644
index 00000000..de1669c4
--- /dev/null
+++ b/docs/adr/0038-android-patch-uses-hdiffpatch.md
@@ -0,0 +1,15 @@
+# Android 增量更新用 HDiffPatch 直接差分 APK,不用 ApkDiffPatch
+
+Android 补丁更新复用桌面端的 HDiffPatch(`hdiffz -f -c-lzma2` 配合官方 Android SDK 的 JNI `libhpatchz.so`),直接对 Gradle 签好名的发布 APK 做文件级差分,不采用 [ApkDiffPatch](https://github.com/sisong/ApkDiffPatch)。
+
+因为 `android/app/build.gradle.kts` 开启了 `jniLibs.useLegacyPackaging = true`,所有 `.so`(约 20.3 MiB)以 `DEFLATE` 存储且常规发版极少变动,而常规发版变动的 `classes.dex`、`resources.arsc`、`app.imy`、`requirements-common.imy` 全为 `STORE`(未压缩)。在真实发布包 `v4.5.8 -> v4.5.11`(整包 45.08 MiB)上实测,HDiffPatch 产出的补丁为 2.03 MiB(占整包 4.5%),与 `ApkDiffPatch`(2.03 MiB)几乎一致,且端侧 `libhpatchz.so` 仅 98.5 KB(已 16 KB 对齐、仅依赖 `libc.so`)、合成无需重压缩、无需改动 Gradle 的 APK v2/v3 签名链路。
+
+## Considered Options
+
+- **ApkDiffPatch v1.8.1(`ApkNormalized` + `apksigner` + `ZipDiff/ZipPatch`)**:仅在某次发版恰好升级较大 `.so`(如 `libkelpie.so`、`libffmpeg.so`)时可多省 1~2 MiB;但必须改造发版流程在 `ApkNormalized` 后重签,且 v1.8.1 不兼容 Android SDK `apksigner` v35/v36(Issue #96,PR #109 尚未合并),CI 需要锁死 `build-tools` v34,端侧合成还要重跑 zlib 压缩、耗时更高。
+- **sfpatcher**:无需重签且支持嵌套压缩包,但为闭源商业授权。
+
+## Consequences
+
+- 某次发版若升级了较大的 `DEFLATE` `.so`,该版本补丁会多出对应 `.so` 压缩后的体积(约 1~3 MiB),仍远小于整包。
+- `versions.json` 的 `app.patches` 在桌面端与 Android 保持相同的 4 字段结构,不新增 `baseSha256`;Android 合成后以 `app.full["Android-arm64"].sha256` 校验产物,任意失败自动回退全量下载。
diff --git a/tests/import_android_packs.py b/tests/import_android_packs.py
index b6da9390..3f3d2fd9 100644
--- a/tests/import_android_packs.py
+++ b/tests/import_android_packs.py
@@ -20,6 +20,11 @@ sys.path.insert(0, str(tree))
sys.path.insert(0, str(tree / "features"))
failures = {}
+for module in ("app.services.update_service",):
+ try:
+ importlib.import_module(module)
+ except Exception as e:
+ failures[module] = f"{type(e).__name__}: {e}"
for pack in packs:
for module in ("pack", "android"):
if not (tree / "features" / pack / f"{module}.py").exists():