Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(desktop): 分离完整安装包与按需工具更新

longmeidao8584f1c1b3d4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 64b658695..4d3b42801 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -142,18 +142,21 @@ jobs:
- name: 构建独立目录包与安装包
shell: pwsh
run: '& ./scripts/build_windows.ps1 -Installer -CloudflaredPath "$env:RUNNER_TEMP/cloudflared.exe" -FFmpegPath "$env:RUNNER_TEMP/ffmpeg-build/ffmpeg" -UntruncPath "$env:RUNNER_TEMP/untrunc-build/untrunc"'
- - name: 压缩完整程序目录
+ - name: 生成完整包、应用更新包与工具包
shell: pwsh
run: |
New-Item -ItemType Directory -Path release | Out-Null
- Compress-Archive -Path dist/Peach -DestinationPath 'release/Peach-${{ steps.version.outputs.version }}-windows-x64.zip'
+ python scripts/package_windows_release.py --source dist/Peach --output release --version '${{ steps.version.outputs.version }}'
+ if ($LASTEXITCODE -ne 0) { throw '发行包拆分失败' }
Copy-Item 'dist/Peach-${{ steps.version.outputs.version }}-windows-x64-setup.exe' release/
Copy-Item dist/ffmpeg-corresponding-source.zip release/
Copy-Item dist/untrunc-corresponding-source.zip release/
Copy-Item scripts/smoke_desktop.py release/smoke_desktop.py
Copy-Item scripts/smoke_update_tasks.py release/smoke_update_tasks.py
+ Copy-Item scripts/smoke_split_update.py release/smoke_split_update.py
python scripts/changelog.py --notes '${{ steps.version.outputs.version }}' --to release/RELEASE_NOTES.md
if ($LASTEXITCODE -ne 0) { throw 'CHANGELOG.md 缺这一版的一节,不发没有说明的版本' }
+ Add-Content -LiteralPath release/RELEASE_NOTES.md -Value (Get-Content -Raw -Encoding utf8 release/DOWNLOADS.md) -Encoding utf8
- uses: actions/upload-artifact@v7
with:
name: desktop-candidate
@@ -179,6 +182,13 @@ jobs:
Expand-Archive -Path 'Peach-${{ needs.windows.outputs.version }}-windows-x64.zip' -DestinationPath candidate
python smoke_desktop.py candidate/Peach/Peach.exe
if ($LASTEXITCODE -ne 0) { throw '制品验收失败' }
+ - name: 从应用更新包与独立工具包重建并验证运行
+ shell: pwsh
+ run: |
+ python smoke_split_update.py --version '${{ needs.windows.outputs.version }}' --destination split-candidate
+ if ($LASTEXITCODE -ne 0) { throw '拆分制品与完整包不一致' }
+ python smoke_desktop.py split-candidate/Peach/Peach.exe
+ if ($LASTEXITCODE -ne 0) { throw '拆分制品运行验收失败' }
- name: 静默安装、验收并卸载安装包
shell: pwsh
run: |
diff --git a/README.en.md b/README.en.md
index bf97b4ed2..6893d52a1 100644
--- a/README.en.md
+++ b/README.en.md
@@ -105,8 +105,8 @@ The original screenshots are lossless 3840×2160 PNGs; click to view them. You c
### Windows
1. Download one of the two packages from [Releases](https://github.com/peach-mitao/peach/releases):
- - Installer `Peach-<version>-windows-x64-setup.exe`: double-click to install and choose an installation folder. No administrator rights needed; Peach appears in the Start menu and can be uninstalled from Windows Settings.
- - Portable `Peach-<version>-windows-x64.zip`: right-click it, choose "Extract All", then double-click `Peach.exe` inside.
+ - Full installer `Peach-<version>-windows-x64-setup.exe`: recommended for first-time installation. Double-click to install and choose an installation folder. No administrator rights needed; Peach appears in the Start menu and can be uninstalled from Windows Settings.
+ - Full portable package `Peach-<version>-windows-x64.zip`: right-click it, choose "Extract All", then double-click `Peach.exe` inside.
2. Your browser opens the first-run setup page.
3. Pick your media folders and who may access Peach, then start the scan.
@@ -114,6 +114,8 @@ If you already have a library but see first-run setup, choose **使用已有数
Windows standalone builds can check for and download updates under **应用与维护** in Configuration. Confirm a restart to install a downloaded update. Automatic checks and downloads are off by default and can be enabled there.
+Routine updates use `Peach-<version>-windows-x64-update.zip` and reuse verified installed tools. The updater downloads separate `tools-*.zip` bundles only when tools are missing, damaged or changed. The application update ZIP is for Peach's updater; use a full package for first-time installation. Older updaters download a full package on their first upgrade, then support tool reuse. Older releases that only provide a full package remain supported by the updater.
+
Downloading an update leaves tasks running. Installing an update saves progress and pauses scraping and preview generation; collection requests made during installation wait for it to finish. After installation finishes or is cancelled, a running Peach service resumes the tasks automatically. If Peach has exited, it resumes unfinished library metadata, local previews, timeline thumbnails and cover tasks on the next launch, reusing completed results. Turning thumbnail collection off explicitly keeps it stopped.
Both the Windows installer and portable ZIP include FFmpeg, ffprobe and untrunc for transcoding, thumbnails and MP4 index recovery. Corresponding source is available in the same Release; the tools directory contains licenses and build notes. See [Windows test build](docs/TESTING_DESKTOP.md). The test package is not code-signed yet. If Windows says "Windows protected your PC", make sure the file came from this project's Releases, then choose "More info → Run anyway".
diff --git a/README.md b/README.md
index 0a37e275e..d71396812 100644
--- a/README.md
+++ b/README.md
@@ -104,8 +104,8 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
### Windows
1. 从 [Releases](https://github.com/peach-mitao/peach/releases) 下载其中一种:
- - 安装包 `Peach-<版本>-windows-x64-setup.exe`:双击安装,可选择安装目录,不需要管理员权限,开始菜单里有 Peach,可以在系统设置里卸载。
- - 免安装包 `Peach-<版本>-windows-x64.zip`:右键「全部解压」,双击里面的 `Peach.exe`。
+ - 完整安装包 `Peach-<版本>-windows-x64-setup.exe`:首次安装推荐。双击安装,可选择安装目录,不需要管理员权限,开始菜单里有 Peach,可以在系统设置里卸载。
+ - 完整免安装包 `Peach-<版本>-windows-x64.zip`:右键「全部解压」,双击里面的 `Peach.exe`。
2. 浏览器会打开首次设置页。
3. 选好媒体文件夹和谁能访问,开始扫描。
@@ -113,6 +113,8 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
Windows 独立包可在配置页「应用与维护」检查并下载更新;下载完成后确认重启安装。自动检查与下载默认关闭,可在同一处开启。
+日常更新使用 `Peach-<版本>-windows-x64-update.zip`,复用已安装工具;只有工具缺失、损坏或版本变化时,更新器才另外下载对应的 `tools-*.zip`。应用更新包供 Peach 更新器使用,首次安装请选择完整包。旧版更新器首次升级仍下载完整包,之后支持工具复用;仅提供完整包的历史版本也可通过应用内更新。
+
下载更新不会停止任务。应用内重启安装和安装包覆盖安装会保存采集进度、暂停刮削与抽帧;安装期间发起的采集任务会等待安装完成。安装完成或取消后,仍在运行的 Peach 会自动续跑;如果 Peach 已退出,则在下次启动时恢复未完成的馆藏资料、本地预览、时间轴缩略图和封面任务,复用已完成结果。主动关闭缩略图采集则不恢复。
Windows 安装包和免安装包均携带 FFmpeg、ffprobe、untrunc,转码、缩略图和缺索引 MP4 修复可直接使用。对应源码随同一 Release 提供,工具目录包含许可证和构建说明,见 [Windows 测试版](docs/TESTING_DESKTOP.md)。测试包还没有代码签名。Windows 提示「已保护你的电脑」时,确认文件来自本项目的 Release,再点「更多信息 → 仍要运行」。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 6f38a5602..83df79383 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -215,7 +215,7 @@ OneJAV、Free JAV Torrent 只给种子链接。这类条目经索引器同源的
- `job_recovery` 保存馆藏处理范围、阶段、指定影片、时间轴密度、单部封面、关注、订阅和想要资料的请求;服务启动或安装结束后只领取未完成记录。暂停任务复用任务中心的同一行,已完成、失败和主动停止的任务不循环重试。馆藏预览在产物登记后保存影片检查点,元数据检查点跟随候选 CSV 成功落盘;未取得结果的项目不记完成。时间轴复用已有索引判定。恢复领取和新任务起跑共用安装闸门,数据仍留在本机 state 目录,不引入 ledger 迁移。
- 自动更新设置用 APScheduler(见「必须复用」表的定时轮询)、共享 HTTPX 发行查询、filelock 与原子 JSON 写入,安装走 `standalone_update`。按 [interval trigger](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/interval.html) 每分钟查是否到期,本机持久时间与文件锁协调多个服务;关闭、6/24/168 小时间隔与源码下载限制归 Peach。默认关闭,下载只准备安装,重启仍需确认;设置存 state 目录的 `automatic-updates.json`。
-- 版本与资产信息用 GitHub Releases REST API(测试通道含预发布),查询与流式下载用项目 HTTPX,ZIP 解压用标准库,互斥用 FileLock。真实 Release 只读验过:只有已上传完整独立包的发布才进更新,查询不下载也不安装。
+- 版本与资产信息用 [GitHub Releases REST API](https://docs.github.com/en/rest/releases/assets)(测试通道含预发布),查询与流式下载用项目 HTTPX,ZIP 解压用标准库,互斥用 FileLock。只有已上传完整独立包的发布才进更新,优先选择 `*-update.zip`,历史完整 ZIP 保留原名供旧客户端更新。`package_windows_release.py` 从同一构建目录生成完整包、应用更新包与 FFmpeg、untrunc、cloudflared 工具包;更新包内清单固定工具文件哈希、工具包大小与 SHA-256,运行时只复用校验相符的文件,按需下载不符的工具。工具包路径限于对应工具目录,补齐后再次校验并沿用同卷暂存与目录回滚。复用已有 HTTPX、hashlib、zipfile、copy2,无新增依赖;不引入 Velopack 的包格式或二进制差分机制。隔离回归用实际生成的 ZIP 验证工具复用、独立补下载与失败保留现有安装,不使用真实 ledger。
- 安装策略与进度归 Peach:下载校验后在程序同卷暂存,用户确认重启,复制出来的包内助手等原托盘退出再切换完整目录;失败保留或恢复旧目录。配置、数据库与媒体不进更新包。
- 不用 [Velopack](https://docs.velopack.io/packaging/operating-systems/windows)(要求其安装目录与包格式)与 [WinSparkle](https://winsparkle.org/)(要求 appcast 与原生更新界面):产物是 PyInstaller ZIP、进度在 Web 显示,沿用托盘进程与目录替换协议。
- Web 复用 Fieldset、Progress、confirmModal;状态由 `standalone-update.json` 保存。下载按字节计量,解压按文件数计量,替换使用阶段进度;服务重启期间保留等待状态,恢复连接后核对版本。
diff --git a/docs/STATUS.md b/docs/STATUS.md
index e48eebdd4..04b63c2ec 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -38,7 +38,7 @@
- [标签归一](reference-snapshots/tag-vocabulary-audit.md)
- 种子 `2026-10-17.1`:1,199 实体、13 撤销(ADR-0106);`0047` 已应用。
- STRM/ISO、目录读取策略、预览开关与 Video.js 10 已部署。
-- Windows 工具候选构建与 EXE 冒烟通过;未发布,安装/卸载未验证。
+- Windows 包构建通过;未发布,安装/卸载未验证。
- 推送发现开:本地 watch 加 CloudDrive 云端前缀 `/115open→B:`、`/Pikpak→A:`;关注每 60 分钟轮询;自动更新关闭。
- Cloudflare 公网入口默认关,配置页启停前须设密码;临时链接写状态文件,命名隧道限源码部署、令牌存设置文件;整站 `noindex` 与 `/robots.txt`。
- FC2PPV-DB、JAVten、被拦的 minnano-av 经本机 Chrome 取页(ADR-0065),profile 在 `secrets/browser/`。
diff --git a/docs/TESTING_DESKTOP.md b/docs/TESTING_DESKTOP.md
index 790e57821..43b74910c 100644
--- a/docs/TESTING_DESKTOP.md
+++ b/docs/TESTING_DESKTOP.md
@@ -50,7 +50,7 @@ Windows 第一次询问防火墙权限时,只勾选「专用网络」。
## 播放与 FFmpeg
-安装包和免安装 ZIP 均包含 FFmpeg 与 ffprobe,位于程序目录的 `tools\ffmpeg\bin`。转码、媒体信息探测与缩略图可直接使用,无需安装系统工具或设置 PATH。应用更新同时更新随包工具。
+完整安装包和完整免安装 ZIP 均包含 FFmpeg 与 ffprobe,位于程序目录的 `tools\ffmpeg\bin`。转码、媒体信息探测与缩略图可直接使用,无需安装系统工具或设置 PATH。应用更新包 `*-update.zip` 由 Peach 更新器使用,按文件 SHA-256 校验并复用已安装工具,仅下载缺失、损坏或版本变化的工具包。首次安装须使用完整包;`tools-*.zip` 由更新器按需处理。
缺索引 MP4 修复使用随包的 `tools\untrunc\untrunc.exe`,需要同编码参数的完整片作为参照。该工具与其兼容的 FFmpeg 库独立构建,按 GPL-2.0-or-later 分发;完整对应源码制品为同一 Release 中的 `untrunc-corresponding-source.zip`。显式 `PEACH_UNTRUNC` 优先于随包工具,其后查数据目录与 PATH。
diff --git a/frontend/e2e/configuration-layout.test.ts b/frontend/e2e/configuration-layout.test.ts
index 0debbbf83..35a8f3ef3 100644
--- a/frontend/e2e/configuration-layout.test.ts
+++ b/frontend/e2e/configuration-layout.test.ts
@@ -8,6 +8,28 @@ describe('配置表单与行间距', () => {
before(async () => { browser = await launch() });
after(async () => { await browser?.close() });
for (const viewport of VIEWPORTS) {
+ it(`${viewport.name}:应用更新包说明和体积不越出视口`, async () => {
+ const opened = await visit(browser, '/settings/library?section=' + encodeURIComponent('应用与维护'), viewport);
+ const { page } = opened;
+ try {
+ await page.route('**/api/configuration', async route => {
+ const data = await (await route.fetch()).json();
+ await route.fulfill({ json: { ...data, updates: { ...data.updates, installation: '独立测试包',
+ state: 'available', latest_version: '1.0.0', message: '有新版本可下载。', package_kind: 'update',
+ asset_size: 12 * 1048576, release_url: 'https://github.com/peach-mitao/peach/releases/tag/v1.0.0' },
+ update_job: { state: 'idle', progress: 0 } } });
+ });
+ await page.reload();
+ const region = page.getByRole('region', { name: '检查更新', exact: true });
+ await region.getByText('应用更新包 · 12.0 MB', { exact: true }).waitFor();
+ assert.ok((await region.innerText()).includes('工具缺失、损坏或版本变化时会另行下载'));
+ assert.equal(await region.getByRole('link', { name: '完整安装包', exact: true }).count(), 0);
+ await settle(page);
+ assert.ok((await layout(page)).scrollWidth <= viewport.width + 1);
+ await region.screenshot({ path: `../build/update-download-${viewport.name}.png` });
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close() }
+ });
it(`${viewport.name}:挂载目录的代理流量保护可切换且不越出视口`, async () => {
const opened = await visit(browser, '/settings/library?section=' + encodeURIComponent('这台电脑'), viewport);
const { page } = opened;
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index bb8907e09..5be503135 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -219,6 +219,8 @@ export interface ReleaseState {
message: string;
release_url: string;
checked_at?: number;
+ package_kind?: 'update' | 'full';
+ asset_size?: number;
}
export interface UpdateJob {
diff --git a/frontend/src/react/settings/release-updates.tsx b/frontend/src/react/settings/release-updates.tsx
index b3843ccf2..3540e3baa 100644
--- a/frontend/src/react/settings/release-updates.tsx
+++ b/frontend/src/react/settings/release-updates.tsx
@@ -14,7 +14,7 @@ import { ErrorText, ExternalLink, Fact, FactList, Footer, Help, Section, Stack }
import { busyProps, useAction } from './use-action';
const ACTIVE = new Set(['downloading', 'verifying', 'extracting', 'preparing', 'restarting', 'installing']);
-const STOPS = [65, 67, 90];
+const STOPS = [65, 75, 90];
const MAX_FAILURES = 120;
export function ReleaseUpdates({ initial, initialJob }: { initial: ReleaseState; initialJob?: UpdateJob | undefined }) {
@@ -92,7 +92,14 @@ export function ReleaseUpdates({ initial, initialJob }: { initial: ReleaseState;
<Fact term="安装方式">{data.installation}</Fact>
<Fact term="更新通道">{data.channel}</Fact>
<Fact term="最新版本">{data.latest_version || (data.state === 'unchecked' ? '尚未检查' : '未取得')}</Fact>
+ {data.package_kind ? <Fact term="下载内容">
+ {data.package_kind === 'update' ? '应用更新包' : '应用与工具'}
+ {data.asset_size ? ` · ${(data.asset_size / 1048576).toFixed(1)} MB` : ''}
+ </Fact> : null}
</FactList>
+ {data.package_kind === 'update'
+ ? <Help>应用更新包复用已安装工具;工具缺失、损坏或版本变化时会另行下载所需工具包。</Help>
+ : data.package_kind === 'full' ? <Help>本次更新包含媒体工具。</Help> : null}
{/* 还没检查过时「最新版本」那一行已经写着「尚未检查」,下面不再说一遍。 */}
{data.state === 'unchecked' && !data.checked_at && !error && job.state === 'idle' ? null : <Stack divided>
{data.checked_at ? <Help>检查于 {new Date(data.checked_at * 1000).toLocaleString()}</Help> : null}
diff --git a/frontend/test/react/maintenance-settings.test.tsx b/frontend/test/react/maintenance-settings.test.tsx
index f13a44553..7755f6d9c 100644
--- a/frontend/test/react/maintenance-settings.test.tsx
+++ b/frontend/test/react/maintenance-settings.test.tsx
@@ -73,6 +73,15 @@ describe('自动更新', () => {
});
describe('检查更新', () => {
+ it('标明应用更新包体积和工具补下载条件', async () => {
+ const host = await mount(<ReleaseUpdates initial={{ ...release, state: 'available', latest_version: '1.0.0',
+ package_kind: 'update', asset_size: 12 * 1048576 }} />);
+ expect(host.textContent).toContain('应用更新包 · 12.0 MB');
+ expect(host.textContent).toContain('工具缺失、损坏或版本变化时会另行下载所需工具包');
+ expect(host.textContent).not.toContain('首次安装');
+ expect([...host.querySelectorAll('a')].some((a) => a.textContent === '完整安装包')).toBe(false);
+ });
+
it('还没检查过时「尚未检查」只在最新版本那一行出现一次', async () => {
vi.stubGlobal('fetch', fetchMock(200, { state: 'idle', progress: 0 }));
const host = await mount(<ReleaseUpdates initial={release} />);
diff --git a/scripts/package_windows_release.py b/scripts/package_windows_release.py
new file mode 100644
index 000000000..fa7c8176f
--- /dev/null
+++ b/scripts/package_windows_release.py
@@ -0,0 +1,87 @@
+"""生成完整免安装包、应用更新包及按工具拆分的 ZIP。"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import sys
+import zipfile
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+from peach.update_packages import MANIFEST, TOOL_PATHS, digest, read_manifest
+
+
+def archive(destination: Path, root: Path, files: list[Path], manifest: dict | None = None) -> None:
+ with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as package:
+ for path in files:
+ if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
+ raise ValueError("发行目录包含链接或越界文件")
+ package.write(path, "Peach/" + path.relative_to(root).as_posix())
+ if manifest is not None:
+ package.writestr("Peach/" + MANIFEST, json.dumps(manifest, ensure_ascii=False, sort_keys=True))
+
+
+def package(root: Path, output: Path, version: str) -> dict:
+ import re
+ if not re.fullmatch(r"\d+\.\d+\.\d+", version):
+ raise ValueError("发行版本无效")
+ root, output = root.resolve(), output.resolve()
+ if output.is_relative_to(root):
+ raise ValueError("发行输出目录须位于程序目录外")
+ if not (root / "Peach.exe").is_file() or not (root / "_internal/standalone.txt").is_file():
+ raise ValueError("发行目录不是独立 Windows 包")
+ output.mkdir(parents=True, exist_ok=True)
+ files = sorted(path for path in root.rglob("*") if path.is_file())
+ if any(path.name == MANIFEST for path in files):
+ raise ValueError("完整程序目录中包含更新清单")
+ tools = {}
+ tool_files: set[Path] = set()
+ for tool, (prefix, required) in TOOL_PATHS.items():
+ selected = [path for path in files if (path.is_relative_to(root / prefix) if prefix
+ else path.relative_to(root).as_posix() in required)]
+ names = {path.relative_to(root).as_posix(): digest(path) for path in selected}
+ expected = {f"{prefix}/{name}" if prefix else name for name in required}
+ if not expected.issubset(names):
+ raise ValueError(f"发行目录缺少 {tool} 工具与分发材料")
+ name = f"Peach-{version}-windows-x64-tools-{tool}.zip"
+ archive(output / name, root, selected)
+ tools[tool] = {"files": names, "asset": {"name": name, "size": (output / name).stat().st_size,
+ "sha256": digest(output / name)}}
+ tool_files.update(selected)
+ manifest = {"format": 1, "version": version, "tools": tools}
+ # 用运行时的同一判据验证生成结果,不在完整包内留下更新专用文件。
+ import tempfile
+ with tempfile.TemporaryDirectory() as temp:
+ check = Path(temp).resolve()
+ (check / MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
+ read_manifest(check, version)
+ archive(output / f"Peach-{version}-windows-x64.zip", root, files)
+ archive(output / f"Peach-{version}-windows-x64-update.zip", root,
+ [path for path in files if path not in tool_files], manifest)
+ (output / "DOWNLOADS.md").write_text(
+ "\n## 下载选择\n\n"
+ "| 文件 | 用途 | 媒体工具 |\n| --- | --- | --- |\n"
+ f"| `Peach-{version}-windows-x64-setup.exe` | 首次安装,推荐 | 包含 FFmpeg、ffprobe、untrunc |\n"
+ f"| `Peach-{version}-windows-x64.zip` | 完整免安装包,解压后运行 | 包含 FFmpeg、ffprobe、untrunc |\n"
+ f"| `Peach-{version}-windows-x64-update.zip` | 已安装用户的应用更新包,由 Peach 更新器使用 | 复用本机工具 |\n"
+ f"| `Peach-{version}-windows-x64-tools-*.zip` | 更新器按需下载的工具包 | 按工具分别打包 |\n\n"
+ "已有 Peach 请在「配置 → 应用与维护」检查更新。更新器校验并复用已安装工具,"
+ "仅在工具缺失、损坏或版本变化时下载相应工具包。应用更新包不能单独用于首次安装。"
+ "旧版更新器首次升级仍下载完整包,之后支持工具复用。\n",
+ encoding="utf-8")
+ return manifest
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--version", required=True)
+ args = parser.parse_args()
+ manifest = package(args.source, args.output, args.version)
+ print(json.dumps({"version": manifest["version"], "tools": list(manifest["tools"])}))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/smoke_split_update.py b/scripts/smoke_split_update.py
new file mode 100644
index 000000000..e2c270f9d
--- /dev/null
+++ b/scripts/smoke_split_update.py
@@ -0,0 +1,68 @@
+"""仅用发行制品重建应用更新目录,并核对它与完整包逐文件一致。"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path, PurePosixPath
+import zipfile
+
+
+def inventory(package: zipfile.ZipFile) -> dict[str, str]:
+ result = {}
+ for entry in package.infolist():
+ if entry.is_dir():
+ continue
+ parts = PurePosixPath(entry.filename).parts
+ if (not parts or parts[0] != "Peach" or ".." in parts or "\\" in entry.filename
+ or ":" in entry.filename or entry.filename.startswith("/")
+ or (entry.external_attr >> 16) & 0o170000 == 0o120000
+ or entry.filename.casefold() in {name.casefold() for name in result}):
+ raise ValueError("发行 ZIP 包含无效路径")
+ with package.open(entry) as source:
+ result[entry.filename] = hashlib.file_digest(source, "sha256").hexdigest()
+ return result
+
+
+def verify(root: Path, version: str, destination: Path) -> dict:
+ prefix = f"Peach-{version}-windows-x64"
+ if destination.exists():
+ raise ValueError("制品验收目录须不存在")
+ with zipfile.ZipFile(root / f"{prefix}-update.zip") as thin, zipfile.ZipFile(root / f"{prefix}.zip") as full:
+ expected = inventory(full)
+ actual = inventory(thin)
+ manifest = json.loads(thin.read("Peach/update-manifest.json"))
+ del actual["Peach/update-manifest.json"]
+ if manifest["version"] != version or manifest["format"] != 1:
+ raise ValueError("发行更新清单版本无效")
+ tools = []
+ for tool, bundle in manifest["tools"].items():
+ name = f"{prefix}-tools-{tool}.zip"
+ if bundle["asset"]["name"] != name:
+ raise ValueError("发行工具包名无效")
+ path = root / name
+ with path.open("rb") as source:
+ if path.stat().st_size != bundle["asset"]["size"] or hashlib.file_digest(source, "sha256").hexdigest() != bundle["asset"]["sha256"]:
+ raise ValueError("发行工具包校验失败")
+ with zipfile.ZipFile(path) as package:
+ files = inventory(package)
+ if files != {"Peach/" + name: value for name, value in bundle["files"].items()} or set(actual) & set(files):
+ raise ValueError("发行工具文件清单不符或重复")
+ actual.update(files)
+ tools.append(path)
+ if actual != expected:
+ raise ValueError("应用更新包与工具包不能重建完整程序")
+ thin.extractall(destination)
+ for path in tools:
+ with zipfile.ZipFile(path) as package:
+ package.extractall(destination)
+ return {"files": len(expected), "tools": len(tools), "application": str(destination / "Peach/Peach.exe")}
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, default=Path.cwd())
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--destination", type=Path, required=True)
+ args = parser.parse_args()
+ print(json.dumps(verify(args.root.resolve(), args.version, args.destination.resolve()), ensure_ascii=False))
diff --git a/src/peach/release_updates.py b/src/peach/release_updates.py
index 48b5400bf..9a3628546 100644
--- a/src/peach/release_updates.py
+++ b/src/peach/release_updates.py
@@ -7,6 +7,7 @@ import httpx
from . import __version__, distribution
from .http import HttpRequest, HttpxTransport
+from .update_packages import TOOL_PATHS
RELEASES_URL = "https://github.com/peach-mitao/peach/releases"
API_URL = "https://api.github.com/repos/peach-mitao/peach/releases?per_page=100"
@@ -45,14 +46,17 @@ def check(*, transport=None) -> dict:
continue
tag = row["tag_name"]
assets = row.get("assets") or []
- expected = f"Peach-{tag.removeprefix('v')}-windows-x64.zip"
- if not any(isinstance(a, dict) and a.get("name") == expected and a.get("state") == "uploaded" for a in assets):
+ prefix = f"Peach-{tag.removeprefix('v')}-windows-x64"
+ uploaded = {a.get("name"): a for a in assets if isinstance(a, dict) and a.get("state") == "uploaded"}
+ full = uploaded.get(prefix + ".zip")
+ if full is None:
continue
- asset = next(a for a in assets if a.get("name") == expected and a.get("state") == "uploaded")
- releases.append((version, tag, asset))
+ complete_tools = all(prefix + f"-tools-{tool}.zip" in uploaded for tool in TOOL_PATHS)
+ asset = uploaded.get(prefix + "-update.zip", full) if complete_tools else full
+ releases.append((version, tag, asset, full))
if not releases:
return dict(result, state="empty", message="暂未找到可下载的测试版。")
- version, tag, asset = max(releases, key=lambda item: item[0])
+ version, tag, asset, full = max(releases, key=lambda item: item[0])
current = _version(result["current_version"])
if current is None:
raise ValueError("current version required")
@@ -61,6 +65,7 @@ def check(*, transport=None) -> dict:
return dict(result, latest_version=tag.removeprefix("v"), state=state, message=message,
asset_url=f"{RELEASES_URL}/download/{tag}/{asset['name']}",
asset_size=asset.get("size", 0), asset_digest=asset.get("digest"),
+ package_kind="update" if asset is not full else "full",
release_url=f"{RELEASES_URL}/tag/{tag}")
except (OSError, ValueError, TypeError, TimeoutError, httpx.HTTPError):
return dict(result, state="error", message="未能取得版本信息,请重试。")
diff --git a/src/peach/standalone_update.py b/src/peach/standalone_update.py
index 57e8f1042..5fcf95926 100644
--- a/src/peach/standalone_update.py
+++ b/src/peach/standalone_update.py
@@ -18,7 +18,7 @@ import zipfile
import httpx
from filelock import FileLock, Timeout
-from . import __version__, desktop_installer, distribution, release_updates, settings_file
+from . import __version__, desktop_installer, distribution, release_updates, settings_file, update_packages
from .fsutil import atomic_write_text
from .windows_update import replace_with_retry
from . import update_tasks
@@ -73,7 +73,7 @@ def public() -> dict:
"state", "progress", "message", "downloaded", "total", "version", "updated_at"}}
-def extract(archive: Path, destination: Path, progress) -> Path:
+def extract(archive: Path, destination: Path, progress, *, tool_files: set[str] | None = None) -> Path:
destination = destination.resolve()
with zipfile.ZipFile(archive) as package:
entries = package.infolist()
@@ -86,6 +86,8 @@ def extract(archive: Path, destination: Path, progress) -> Path:
if (not parts or parts[0] != "Peach" or "\\" in name or ":" in name
or ".." in parts or name.startswith("/") or (item.external_attr >> 16) & 0o170000 == 0o120000):
raise ValueError("更新包含无效路径")
+ if tool_files is not None and (item.is_dir() or "/".join(parts[1:]) not in tool_files):
+ raise ValueError("工具包包含清单外的文件")
target = destination.joinpath(*parts).resolve()
key = str(target).casefold()
if not target.is_relative_to(destination) or key in seen:
@@ -94,11 +96,63 @@ def extract(archive: Path, destination: Path, progress) -> Path:
package.extract(item, destination)
progress(index + 1, len(entries))
root = destination / "Peach"
- if not (root / "Peach.exe").is_file() or not (root / "_internal" / "standalone.txt").is_file():
+ if tool_files is None and (not (root / "Peach.exe").is_file() or not (root / "_internal" / "standalone.txt").is_file()):
raise ValueError("更新包不是独立 Windows 版本")
return root
+def download(url: str, archive: Path, size: int, digest: str, progress) -> None:
+ checksum = hashlib.sha256()
+ received = 0
+ with httpx.Client(follow_redirects=True, timeout=30) as client, client.stream("GET", url) as response:
+ response.raise_for_status()
+ with archive.open("wb") as output:
+ for chunk in response.iter_bytes(256 * 1024):
+ received += len(chunk)
+ if received > size:
+ raise ValueError("下载体积与发布记录不符")
+ output.write(chunk)
+ checksum.update(chunk)
+ progress(received)
+ if received != size or checksum.hexdigest() != digest:
+ raise ValueError("更新包校验失败,请重新下载")
+
+
+def prepare_tools(stage: Path, target: Path, transaction: Path, release: dict, data: dict) -> None:
+ manifest = update_packages.read_manifest(stage, release["latest_version"])
+ missing = []
+ for tool, bundle in manifest["tools"].items():
+ if update_packages.matches(target, bundle["files"]):
+ for name in bundle["files"]:
+ destination = update_packages.checked_path(stage, name)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(update_packages.checked_path(target, name), destination)
+ else:
+ missing.append((tool, bundle))
+ total = data["total"] + sum(bundle["asset"]["size"] for _, bundle in missing)
+ write(data, total=total)
+ for index, (tool, bundle) in enumerate(missing):
+ asset = bundle["asset"]
+ archive = transaction / f"tools-{tool}.zip"
+ received = data["downloaded"]
+ write(data, state="downloading", message=f"正在下载 {tool} 工具包")
+ download(release["asset_url"].rsplit("/", 1)[0] + "/" + asset["name"], archive,
+ asset["size"], asset["sha256"],
+ lambda count, start=received, step=index, size=asset["size"]: write(
+ data, downloaded=start + count, progress=75 + round((step + count / size) / len(missing) * 13)))
+ write(data, state="verifying", message=f"正在校验 {tool} 工具包")
+ extracted = extract(archive, transaction / f"tool-{tool}", lambda *_: None, tool_files=set(bundle["files"]))
+ if not update_packages.matches(extracted, bundle["files"]):
+ raise ValueError(f"{tool} 工具包文件校验失败")
+ for name in bundle["files"]:
+ destination = update_packages.checked_path(stage, name)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(update_packages.checked_path(extracted, name), destination)
+ for tool, bundle in manifest["tools"].items():
+ if not update_packages.matches(stage, bundle["files"]):
+ raise ValueError(f"{tool} 工具复用校验失败")
+
+
def prepare(data: dict, lock: FileLock) -> None:
try:
release = release_updates.check()
@@ -118,26 +172,18 @@ def prepare(data: dict, lock: FileLock) -> None:
write(data, transaction=str(transaction), target=str(target), version=release["latest_version"],
total=total, downloaded=0, message="正在下载", state="downloading")
archive = transaction / "package.zip"
- checksum = hashlib.sha256()
- received = 0
- with httpx.Client(follow_redirects=True, timeout=30) as client, client.stream("GET", release["asset_url"]) as response:
- response.raise_for_status()
- with archive.open("wb") as output:
- for chunk in response.iter_bytes(256 * 1024):
- received += len(chunk)
- if received > total:
- raise ValueError("下载体积与发布记录不符")
- output.write(chunk); checksum.update(chunk)
- write(data, downloaded=received, progress=round(received / total * 65, 1))
+ download(release["asset_url"], archive, total, digest[7:],
+ lambda count: write(data, downloaded=count, progress=round(count / total * 65, 1)))
write(data, state="verifying", progress=66, message="正在校验")
- if received != total or checksum.hexdigest() != digest[7:]:
- raise ValueError("更新包校验失败,请重新下载")
write(data, state="extracting", message="正在解压")
- stage = extract(archive, transaction / "stage", lambda done, count: write(data, progress=67 + round(done / count * 20)))
+ stage = extract(archive, transaction / "stage", lambda done, count: write(data, progress=67 + round(done / count * 8)))
from .buildinfo import read_build_info
info = read_build_info(stage / "_internal")
if not info or info.version != release["latest_version"]:
raise ValueError("包内版本与发布版本不符")
+ if release.get("package_kind") == "update":
+ write(data, state="preparing", message="正在复用和校验已安装工具")
+ prepare_tools(stage, target, transaction, release, data)
write(data, state="preparing", progress=90, message="正在准备安装")
desktop_installer.carry_uninstaller(target, stage)
# 助手从自己的目录运行,正式目录与暂存目录都不会被它的 DLL 句柄占用。
diff --git a/src/peach/update_packages.py b/src/peach/update_packages.py
new file mode 100644
index 000000000..a7ae2c5fe
--- /dev/null
+++ b/src/peach/update_packages.py
@@ -0,0 +1,71 @@
+"""独立更新包的工具清单与本机文件校验。"""
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path, PurePosixPath
+import re
+
+MANIFEST = "update-manifest.json"
+TOOL_PATHS = {
+ "ffmpeg": ("tools/ffmpeg", {"bin/ffmpeg.exe", "bin/ffprobe.exe", "manifest.json", "LICENSE.txt", "NOTICE.md", "buildconf.txt"}),
+ "untrunc": ("tools/untrunc", {"untrunc.exe", "manifest.json", "LICENSE.txt", "NOTICE.md", "buildconf.txt"}),
+ "cloudflared": ("", {"cloudflared.exe", "cloudflared-manifest.json"}),
+}
+
+
+def digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def checked_path(root: Path, name: str) -> Path:
+ parts = PurePosixPath(name).parts
+ if (not parts or "\\" in name or ":" in name or ".." in parts or any(part.endswith((".", " ")) for part in parts)
+ or name.startswith("/") or PurePosixPath(name).as_posix() != name):
+ raise ValueError("工具清单路径无效")
+ path = root.joinpath(*parts)
+ if not path.resolve().is_relative_to(root.resolve()) or any(
+ parent.is_symlink() for parent in (path, *path.parents) if parent != root.parent):
+ raise ValueError("工具清单路径越界或包含链接")
+ return path
+
+
+def matches(root: Path, files: dict[str, str]) -> bool:
+ try:
+ return all((path := checked_path(root, name)).is_file() and digest(path) == expected
+ for name, expected in files.items())
+ except (OSError, ValueError):
+ return False
+
+
+def read_manifest(stage: Path, version: str) -> dict:
+ manifest = json.loads((stage / MANIFEST).read_text(encoding="utf-8"))
+ if (not isinstance(manifest, dict) or manifest.get("format") != 1 or manifest.get("version") != version
+ or not isinstance(manifest.get("tools"), dict)
+ or set(manifest.get("tools", {})) != set(TOOL_PATHS)):
+ raise ValueError("更新包工具清单无效")
+ all_names: set[str] = set()
+ for tool, bundle in manifest["tools"].items():
+ if not isinstance(bundle, dict):
+ raise ValueError("更新包工具清单无效")
+ prefix, required = TOOL_PATHS[tool]
+ files = bundle.get("files")
+ if not isinstance(files, dict) or not files or len(files) > 2000:
+ raise ValueError("更新包工具文件清单无效")
+ expected_names = {f"{prefix}/{name}" if prefix else name for name in required}
+ if not expected_names.issubset(files):
+ raise ValueError("更新包工具清单缺少必需文件")
+ for name, expected in files.items():
+ checked_path(stage, name)
+ if ((prefix and not name.startswith(prefix + "/")) or (not prefix and name not in required)
+ or not isinstance(expected, str) or not re.fullmatch(r"[0-9a-f]{64}", expected)
+ or name.casefold() in all_names):
+ raise ValueError("更新包工具文件清单无效")
+ all_names.add(name.casefold())
+ asset = bundle.get("asset", {})
+ if (not isinstance(asset, dict) or asset.get("name") != f"Peach-{version}-windows-x64-tools-{tool}.zip"
+ or not isinstance(asset.get("size"), int) or not 0 < asset["size"] <= 512 * 1024 * 1024
+ or not isinstance(asset.get("sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", asset["sha256"])):
+ raise ValueError("更新包工具下载信息无效")
+ return manifest
diff --git a/tests/test_release_updates.py b/tests/test_release_updates.py
index e7e00bf3a..e4b65c79a 100644
--- a/tests/test_release_updates.py
+++ b/tests/test_release_updates.py
@@ -34,6 +34,24 @@ class ReleaseUpdateTests(unittest.TestCase):
self.assertEqual(self.check([release("0.8.0")])["state"], "ahead")
self.assertEqual(self.check([])["state"], "empty")
+ def test_prefers_app_update_when_all_tool_assets_are_uploaded(self):
+ row = release("1.0.0")
+ row["assets"] += [
+ {"name": "Peach-1.0.0-windows-x64-update.zip", "state": "uploaded", "size": 123, "digest": "sha256:" + "a" * 64},
+ {"name": "Peach-1.0.0-windows-x64-setup.exe", "state": "uploaded"},
+ ]
+ self.assertEqual(self.check([row])["package_kind"], "full")
+ row["assets"] += [{"name": f"Peach-1.0.0-windows-x64-tools-{tool}.zip", "state": "uploaded"}
+ for tool in ("ffmpeg", "untrunc", "cloudflared")]
+ result = self.check([row])
+ self.assertEqual(result["package_kind"], "update")
+ self.assertTrue(result["asset_url"].endswith("-update.zip"))
+ self.assertEqual(result["asset_size"], 123)
+ row["assets"][1]["state"] = "new"
+ self.assertEqual(self.check([row])["package_kind"], "full")
+ row["assets"].pop(0)
+ self.assertEqual(self.check([row])["state"], "empty")
+
def test_failures_do_not_claim_current_or_keep_a_latest_version(self):
self.assertEqual(self.check({}, status=429)["state"], "error")
self.assertEqual(self.check({})["state"], "error")
diff --git a/tests/test_standalone_update.py b/tests/test_standalone_update.py
index 46b62a13f..20c5b2dbd 100644
--- a/tests/test_standalone_update.py
+++ b/tests/test_standalone_update.py
@@ -2,6 +2,7 @@
import json
import hashlib
import os
+import shutil
from contextlib import nullcontext
from pathlib import Path
import tempfile
@@ -10,7 +11,12 @@ import unittest
from unittest.mock import Mock, patch
import zipfile
+import httpx
+
from peach import settings_file, standalone_update as update
+from peach import update_packages
+from scripts.package_windows_release import package as package_release
+from scripts.smoke_split_update import verify as verify_split
from support.ledger import fresh_ledger
@@ -151,6 +157,111 @@ class StandaloneUpdateTests(unittest.TestCase):
launch.assert_not_called()
lock.release.assert_called_once()
+ def release_fixture(self):
+ source = self.root / "dist/Peach"
+ (source / "_internal").mkdir(parents=True)
+ (source / "Peach.exe").write_bytes(b"new application")
+ (source / "_internal/standalone.txt").touch()
+ (source / "_internal/build-info.json").write_text(
+ json.dumps({"version": "1.0.0", "commit": None, "built_at": "fixture"}), encoding="utf-8")
+ for prefix, required in update_packages.TOOL_PATHS.values():
+ for name in required | ({"bin/codec.dll"} if prefix == "tools/ffmpeg" else set()):
+ path = source / prefix / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes((prefix + name).encode())
+ output = self.root / "release"
+ manifest = package_release(source, output, "1.0.0")
+ target = self.root / "installed"
+ shutil.copytree(source, target)
+ (target / "Peach.exe").write_bytes(b"old application")
+ (target / "unins000.exe").write_bytes(b"uninstaller")
+ archive = output / "Peach-1.0.0-windows-x64-update.zip"
+ release = dict(state="available", latest_version="1.0.0", asset_size=archive.stat().st_size,
+ asset_digest="sha256:" + update_packages.digest(archive),
+ asset_url="https://github.com/peach-mitao/peach/releases/download/v1.0.0/" + archive.name,
+ package_kind="update")
+ return source, output, manifest, target, archive, release
+
+ def prepare_fixture(self, target, output, release, *, corrupt=None):
+ requests = []
+ def response(request):
+ name = request.url.path.rsplit("/", 1)[1]
+ requests.append(name)
+ content = (output / name).read_bytes()
+ return httpx.Response(200, content=b"corrupt" if name == corrupt else content)
+ client_type = update.httpx.Client
+ lock = Mock()
+ with patch.object(update.sys, "executable", str(target / "Peach.exe")), patch.object(
+ update.release_updates, "check", return_value=release), patch.object(
+ update.httpx, "Client", side_effect=lambda **kwargs: client_type(
+ **kwargs, transport=update.httpx.MockTransport(response))):
+ update.prepare({"id": "split-fixture"}, lock)
+ lock.release.assert_called_once()
+ return update.read(), requests
+
+ def test_split_package_preserves_complete_install_and_reuses_verified_tools_without_download(self):
+ source, output, manifest, target, archive, release = self.release_fixture()
+ rebuilt = self.root / "rebuilt"
+ report = verify_split(output, "1.0.0", rebuilt)
+ self.assertEqual(report["tools"], 3)
+ self.assertEqual((rebuilt / "Peach/Peach.exe").read_bytes(), (source / "Peach.exe").read_bytes())
+ with zipfile.ZipFile(archive) as thin, zipfile.ZipFile(output / "Peach-1.0.0-windows-x64.zip") as full:
+ self.assertNotIn("Peach/tools/ffmpeg/bin/ffmpeg.exe", thin.namelist())
+ self.assertNotIn("Peach/cloudflared.exe", thin.namelist())
+ self.assertIn("Peach/tools/ffmpeg/bin/ffmpeg.exe", full.namelist())
+ self.assertNotIn("Peach/" + update_packages.MANIFEST, full.namelist())
+ state, requests = self.prepare_fixture(target, output, release)
+ self.assertEqual(state["state"], "ready", state)
+ self.assertEqual(requests, [archive.name])
+ self.assertEqual(state["downloaded"], state["total"])
+ for bundle in manifest["tools"].values():
+ self.assertTrue(update_packages.matches(Path(state["stage"]), bundle["files"]))
+ self.assertEqual((Path(state["stage"]) / "unins000.exe").read_bytes(), b"uninstaller")
+ self.assertEqual((target / "Peach.exe").read_bytes(), b"old application")
+
+ def test_only_missing_or_different_tools_are_downloaded_and_verified(self):
+ source, output, manifest, target, archive, release = self.release_fixture()
+ (target / "tools/ffmpeg/bin/codec.dll").write_bytes(b"different version")
+ (target / "cloudflared.exe").unlink()
+ state, requests = self.prepare_fixture(target, output, release)
+ self.assertEqual(state["state"], "ready", state)
+ self.assertEqual(set(requests), {archive.name, manifest["tools"]["ffmpeg"]["asset"]["name"],
+ manifest["tools"]["cloudflared"]["asset"]["name"]})
+ self.assertEqual(state["downloaded"], state["total"])
+ for bundle in manifest["tools"].values():
+ self.assertTrue(update_packages.matches(Path(state["stage"]), bundle["files"]))
+ self.assertEqual((target / "tools/ffmpeg/bin/codec.dll").read_bytes(), b"different version")
+
+ def test_corrupt_tool_download_leaves_the_installed_program_and_tools_untouched(self):
+ source, output, manifest, target, archive, release = self.release_fixture()
+ binary = target / "tools/ffmpeg/bin/ffmpeg.exe"
+ binary.write_bytes(b"old version")
+ state, _ = self.prepare_fixture(target, output, release, corrupt=manifest["tools"]["ffmpeg"]["asset"]["name"])
+ self.assertEqual(state["state"], "error")
+ self.assertIn("校验失败", state["message"])
+ self.assertEqual(binary.read_bytes(), b"old version")
+ self.assertEqual((target / "Peach.exe").read_bytes(), b"old application")
+
+ def test_manifest_rejects_path_escape_tool_scope_collision_and_incomplete_tools(self):
+ source, output, manifest, target, archive, release = self.release_fixture()
+ for name in ("../escape.exe", "tools/ffmpeg/../../Peach.exe", "Peach.exe", "tools/untrunc/untrunc.exe",
+ "tools/ffmpeg/bin/FFMPEG.exe"):
+ with self.subTest(name=name):
+ invalid = json.loads(json.dumps(manifest))
+ invalid["tools"]["ffmpeg"]["files"][name] = "a" * 64
+ (source / update_packages.MANIFEST).write_text(json.dumps(invalid), encoding="utf-8")
+ with self.assertRaises(ValueError):
+ update_packages.read_manifest(source, "1.0.0")
+ del manifest["tools"]["untrunc"]
+ (source / update_packages.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
+ with self.assertRaises(ValueError):
+ update_packages.read_manifest(source, "1.0.0")
+
+ def test_tool_archive_cannot_replace_application_files(self):
+ archive = self.archive(["Peach/tools/ffmpeg/bin/ffmpeg.exe", "Peach/Peach.exe"])
+ with self.assertRaisesRegex(ValueError, "清单外"):
+ update.extract(archive, self.root / "tool-stage", Mock(), tool_files={"tools/ffmpeg/bin/ffmpeg.exe"})
+
def test_install_failure_restores_program_directory_and_preserves_data(self):
target = self.root / "app"; target.mkdir()
(target / "Peach.exe").write_text("old")
diff --git a/web/dist/peach-app.js b/web/dist/peach-app.js
index eaf336915..8b25b660d 100644
--- a/web/dist/peach-app.js
+++ b/web/dist/peach-app.js
@@ -70014,7 +70014,7 @@ var GW = /* @__PURE__ */ new Set([
"installing"
]), GNe = [
65,
- 67,
+ 75,
90
], KW = 120;
function KNe({ initial: e, initialJob: t }) {
@@ -70086,8 +70086,13 @@ function KNe({ initial: e, initialJob: t }) {
/* @__PURE__ */ (0, C.jsx)(RA, {
term: "最新版本",
children: n.latest_version || (n.state === "unchecked" ? "尚未检查" : "未取得")
- })
+ }),
+ n.package_kind ? /* @__PURE__ */ (0, C.jsxs)(RA, {
+ term: "下载内容",
+ children: [n.package_kind === "update" ? "应用更新包" : "应用与工具", n.asset_size ? ` · ${(n.asset_size / 1048576).toFixed(1)} MB` : ""]
+ }) : null
] }),
+ n.package_kind === "update" ? /* @__PURE__ */ (0, C.jsx)(NA, { children: "应用更新包复用已安装工具;工具缺失、损坏或版本变化时会另行下载所需工具包。" }) : n.package_kind === "full" ? /* @__PURE__ */ (0, C.jsx)(NA, { children: "本次更新包含媒体工具。" }) : null,
n.state === "unchecked" && !n.checked_at && !g && i.state === "idle" ? null : /* @__PURE__ */ (0, C.jsxs)(jA, {
divided: !0,
children: [