Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(desktop): 完全卸载清理设置备份与解压目录

longmeidaoe360abf9f599
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 82fef5451..b9bd0c876 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -8,7 +8,7 @@
本机配置页提供开机自启、静默启动和 Peach 代理。代理选择系统代理、直连或自定义;采集来源选择“Peach 代理”或“直接连接”,新采集使用保存的策略。
-独立 Windows 包的“卸载 Peach”先确认范围,再退出托盘、关闭其服务、移除自启和程序。默认保留数据;完全卸载删除配置及列出的数据库、缓存、凭据等直属目录,保留原始媒体和未列入的文件。外部数据目录、目录链接或媒体重叠须人工检查。源码安装先关闭自启并退出托盘,再按页面列出的路径手动移除;Git 工作区不自动删除。
+独立 Windows 包的“卸载 Peach”先确认范围,再退出托盘、关闭其服务、退出仍从程序目录运行的残留进程、移除自启和整个解压程序目录,删除重试三次后才报失败。默认保留数据;完全卸载删除配置、`config.toml.*` 设置备份及列出的数据库、缓存、凭据等直属目录,保留原始媒体和其它未列名文件。外部数据目录、目录链接或媒体重叠须人工检查。删除被占用而失败时,原因和失败路径写在临时目录的 `peach-uninstall.log`,弹窗会给出该日志位置。源码安装先关闭自启并退出托盘,再按页面列出的路径手动移除;Git 工作区不自动删除。
本地测试服务使用独立测试数据根,以 `peach serve --host 127.0.0.1 --port 18977 --no-mdns --no-auth`
启动;浏览器打开 `http://127.0.0.1:18977`。`--no-auth` 只影响这次进程,不读取或改写口令文件;
diff --git a/docs/REUSE.md b/docs/REUSE.md
index c3c8bae9c..69696ea8c 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -28,7 +28,7 @@
- Peach 代理复用 HTTPX 的 `trust_env`、`proxy` 与本机 CredentialStore;来源只选择公共策略或直接连接,地址不回传。单一旧代理可继承,多个地址需明确选择。
- 自启复用项目 Windows WScript.Shell 快捷方式和 macOS LaunchAgent;[微软原生文档](https://learn.microsoft.com/en-us/troubleshoot/windows-client/admin-development/create-desktop-shortcut-with-wsh)支持 TargetPath、Arguments 与 Save。Windows 自带 COM,无新增依赖;pylnk3 无需引入。临时中文路径的真实快捷方式读、写、移除通过。
-- 独立包卸载复用正常托盘退出和 Windows PowerShell 助手;计划限制程序标记、数据直属目录、媒体不重叠,助手拒绝目录链接。临时程序、数据、媒体与无关文件组成的真实输入验证只删除计划内容。源码树仅提供手动卸载说明。
+- 独立包卸载复用正常托盘退出和 Windows PowerShell 助手;计划限制程序标记、数据直属目录、媒体不重叠,助手拒绝目录链接。助手会退出仍从程序目录运行的进程并重试删除;完全卸载把 `config.toml.*` 视为设置备份。临时程序、被占用文件、历史设置备份、数据、媒体与无关文件组成的真实输入验证只删除计划内容和整个解压程序目录。源码树仅提供手动卸载说明。
- 扫描与采集统一挂在数据管理;首页进度 Banner 跳转同一入口。默认排序与方向使用浏览偏好,显式 URL 优先。
目录页进度横幅与数据管理卡片共用 `frontend/src/react/library-processing/` 那一份读取,读同一个 `LIBRARY_PROCESSING_KEY`,轮询由 TanStack Query 合成一份;启动只提交一次,状态查询接续托盘首次处理。首页在完成后收起,失败跳转数据管理;数据管理持续读取阶段与真实计数。Geist Banner 取证与 Peach 差异见 `docs/reference-snapshots/vercel-geist-library-banner.md`。
diff --git a/src/peach/desktop_uninstall.py b/src/peach/desktop_uninstall.py
index 2a452cf01..77f05b3b6 100644
--- a/src/peach/desktop_uninstall.py
+++ b/src/peach/desktop_uninstall.py
@@ -33,7 +33,13 @@ def plan(config, *, delete_data: bool, program: Path | None = None) -> dict:
for path in [target, *directories]:
if any(item.is_relative_to(path) or path.is_relative_to(item) for item in media):
raise ValueError("卸载目录与媒体目录重叠,请手动检查")
- files = [config.path.resolve(), root / "config.previous.toml", root / "config.pending.toml"] if delete_data else []
+ files: list[Path] = []
+ if delete_data:
+ # `config.toml.<说明>` 都是 Peach 设置备份;其它未列名文件继续保留。
+ generated = [config.path.resolve(), root / "config.previous.toml", root / "config.pending.toml"]
+ generated.extend(path.resolve() for path in root.glob("config.toml.*")
+ if path.is_file() or path.is_symlink())
+ files = sorted(set(generated), key=lambda path: os.path.normcase(str(path)))
return {"program": str(target), "data_root": str(root), "directories": [str(p) for p in directories],
"files": [str(p) for p in files], "delete_data": delete_data}
@@ -71,6 +77,7 @@ def request(config, delete_data: bool) -> dict:
# 系统助手从 stdin 接受数据,路径不拼进脚本文本;只清理计划中的目录。
+# `quiet` 只在测试里置真:跳过弹窗,错误改走日志文件。
_SCRIPT = r"""
$ErrorActionPreference = 'Stop'
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
@@ -79,35 +86,67 @@ $peachProgram = [IO.Path]::GetFullPath($peachJob.program)
$peachData = [IO.Path]::GetFullPath($peachJob.data_root)
if (-not (Test-Path -LiteralPath (Join-Path $peachProgram '_internal/standalone.txt'))) { exit 2 }
if ($peachProgram.Length -lt 4 -or $peachProgram -eq $env:USERPROFILE) { exit 2 }
-$peachProcess = Get-Process -Id $peachJob.pid -ErrorAction SilentlyContinue
+$peachProcess = if ($peachJob.pid) { Get-Process -Id $peachJob.pid -ErrorAction SilentlyContinue }
if ($peachProcess -and -not $peachProcess.WaitForExit(90000)) { exit 3 }
foreach ($peachPath in @($peachJob.directories) + @($peachJob.files)) {
if ([IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($peachPath)) -ne $peachData) { exit 2 }
}
+function Stop-PeachProgramProcesses {
+ # 托盘退出时被硬杀的服务会留下自己的子进程:扫描、转码用的可执行文件可能就在
+ # `_internal` 里。按镜像路径清场,只匹配程序目录前缀加一个分隔符,不误伤名字
+ # 相近的其它解压目录。
+ $peachStrays = @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
+ $_.Path -and $_.Path.StartsWith($peachProgram + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)
+ })
+ foreach ($peachStray in $peachStrays) {
+ Stop-Process -Id $peachStray.Id -Force -ErrorAction SilentlyContinue
+ }
+ foreach ($peachStray in $peachStrays) {
+ Wait-Process -Id $peachStray.Id -Timeout 10 -ErrorAction SilentlyContinue
+ }
+}
try {
function Test-PeachTree($peachNode) {
$peachItem = Get-Item -LiteralPath $peachNode -Force
- if ($peachItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Directory contains a link; manual cleanup required' }
+ if ($peachItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw ('卸载目标含有链接:' + $peachNode) }
if ($peachItem.PSIsContainer) {
foreach ($peachChild in Get-ChildItem -LiteralPath $peachNode -Force) { Test-PeachTree $peachChild.FullName }
}
}
+ Stop-PeachProgramProcesses
foreach ($peachPath in @($peachJob.directories) + @($peachJob.files) + @($peachProgram)) {
if (Test-Path -LiteralPath $peachPath) { Test-PeachTree $peachPath }
}
foreach ($peachPath in @($peachJob.directories) + @($peachJob.files) + @($peachProgram)) {
- if (Test-Path -LiteralPath $peachPath) {
- $peachItem = Get-Item -LiteralPath $peachPath -Force
- if ($peachItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Directory is a link' }
- Remove-Item -LiteralPath $peachPath -Recurse -Force
+ for ($peachAttempt = 3; $peachAttempt -gt 0; $peachAttempt--) {
+ if (-not (Test-Path -LiteralPath $peachPath)) { break }
+ try {
+ $peachItem = Get-Item -LiteralPath $peachPath -Force
+ if ($peachItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw ('卸载目标是链接:' + $peachPath) }
+ Remove-Item -LiteralPath $peachPath -Recurse -Force
+ break
+ } catch {
+ if ($peachAttempt -le 1) { throw ('删除失败:' + $peachPath + ':' + $_.Exception.Message) }
+ Stop-PeachProgramProcesses
+ Start-Sleep -Seconds 2
+ }
}
}
if ($peachJob.delete_data -and (Test-Path -LiteralPath $peachData) -and -not (Get-ChildItem -LiteralPath $peachData -Force | Select-Object -First 1)) {
Remove-Item -LiteralPath $peachData
}
} catch {
- [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null
- [System.Windows.Forms.MessageBox]::Show('卸载未完成,请手动检查:' + $peachProgram + [Environment]::NewLine + $peachData, 'Peach') | Out-Null
+ $peachReason = $_.Exception.Message
+ $peachLog = Join-Path ([IO.Path]::GetTempPath()) 'peach-uninstall.log'
+ $peachDetail = '原因:' + $peachReason
+ try {
+ Add-Content -LiteralPath $peachLog -Value ((Get-Date -Format s) + ' ' + $peachReason) -Encoding UTF8
+ $peachDetail += [Environment]::NewLine + '详情记录在 ' + $peachLog
+ } catch { }
+ if (-not $peachJob.quiet) {
+ [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null
+ [System.Windows.Forms.MessageBox]::Show('卸载未完成,请手动检查:' + [Environment]::NewLine + $peachProgram + [Environment]::NewLine + $peachData + [Environment]::NewLine + $peachDetail, 'Peach') | Out-Null
+ }
exit 1
}
"""
diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.py
index 48d456e30..5dc853ca0 100644
--- a/tests/test_desktop_settings.py
+++ b/tests/test_desktop_settings.py
@@ -3,8 +3,10 @@ import json
import base64
import ctypes
import os
+import shutil
import subprocess
import sys
+import threading
from pathlib import Path
import tempfile
from types import SimpleNamespace
@@ -65,9 +67,18 @@ class DesktopSettingsTests(unittest.TestCase):
def test_uninstall_plan_keeps_media_and_can_preserve_all_data(self):
keep = desktop_uninstall.plan(self.config, delete_data=False, program=self.program)
self.assertEqual(keep['directories'], [])
+ generated_backup = self.data / 'config.toml.before-access-fix-20260906-135757'
+ generated_backup.write_text('fixture')
+ manual_backup = self.data / 'config.toml.bak'
+ manual_backup.write_text('fixture')
+ unrelated = self.data / 'personal.txt'
+ unrelated.write_text('preserve')
full = desktop_uninstall.plan(self.config, delete_data=True, program=self.program)
self.assertEqual(len(full['directories']), len(settings_file.DIRECTORY_KEYS))
self.assertNotIn(str(self.root / 'media'), full['directories'])
+ self.assertIn(str(generated_backup), full['files'])
+ self.assertIn(str(manual_backup), full['files'])
+ self.assertNotIn(str(unrelated), full['files'])
def test_uninstall_refuses_media_overlap_external_storage_and_source_tree(self):
self.config.locations = {'local': (str(self.data / 'sources/media'),)}
@@ -332,6 +343,8 @@ class DesktopSettingsTests(unittest.TestCase):
path.mkdir()
(path / 'fixture.txt').write_text('fixture')
self.config.path.write_text('fixture')
+ generated_backup = self.data / 'config.toml.before-access-fix-20260906-135757'
+ generated_backup.write_text('fixture')
unrelated = self.data / 'personal.txt'
unrelated.write_text('preserve')
media = self.root / 'media'
@@ -346,5 +359,56 @@ class DesktopSettingsTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(self.program.exists())
self.assertFalse(self.config.path.exists())
+ self.assertFalse(generated_backup.exists())
self.assertTrue(unrelated.is_file())
self.assertTrue((media / 'video.mp4').is_file())
+
+ def _run_native_uninstall(self, job):
+ shell = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
+ return subprocess.run([str(shell), '-NoProfile', '-NonInteractive', '-EncodedCommand',
+ base64.b64encode(desktop_uninstall._SCRIPT.encode('utf-16-le')).decode('ascii')],
+ input=json.dumps(dict(job, pid=2147483647, quiet=True)).encode('utf-8'), capture_output=True,
+ timeout=30, creationflags=subprocess.CREATE_NO_WINDOW)
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 系统卸载助手')
+ def test_native_uninstall_kills_strays_running_from_the_program(self):
+ stray = self.program / 'Stray.exe'
+ shutil.copyfile(Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/cmd.exe', stray)
+ held = subprocess.Popen([str(stray), '/c', 'ping', '-n', '60', '127.0.0.1'],
+ creationflags=subprocess.CREATE_NO_WINDOW)
+ self.addCleanup(held.kill)
+ result = self._run_native_uninstall(
+ desktop_uninstall.plan(self.config, delete_data=False, program=self.program))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(self.program.exists())
+ self.assertTrue(self.root.exists(), '只删除 Peach 解压目录,不删除用户选择的父目录')
+ self.assertIsNotNone(held.poll())
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 系统卸载助手')
+ def test_native_uninstall_retries_until_the_file_is_released(self):
+ blocked = self.program / '_internal' / 'locked.bin'
+ blocked.write_text('fixture')
+ handle = blocked.open('rb')
+ self.addCleanup(handle.close)
+ timer = threading.Timer(1.0, handle.close)
+ timer.start()
+ self.addCleanup(timer.join)
+ result = self._run_native_uninstall(
+ desktop_uninstall.plan(self.config, delete_data=False, program=self.program))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(self.program.exists())
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 系统卸载助手')
+ def test_native_uninstall_names_the_blocked_file_in_the_error_log(self):
+ blocked = self.program / '_internal' / 'locked.bin'
+ blocked.write_text('fixture')
+ handle = blocked.open('rb')
+ self.addCleanup(handle.close)
+ log = Path(tempfile.gettempdir()) / 'peach-uninstall.log'
+ log.unlink(missing_ok=True)
+ self.addCleanup(log.unlink)
+ result = self._run_native_uninstall(
+ desktop_uninstall.plan(self.config, delete_data=False, program=self.program))
+ self.assertEqual(result.returncode, 1, result.stderr)
+ self.assertTrue(self.program.exists())
+ self.assertIn('locked.bin', log.read_text(encoding='utf-8'))