Peach: Local-first video metadata scraper and media manager.
fix: 独立包更新备份迁移数据库并支持回滚
longmeidao41984fe425ac
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 5e1993988..c42dfc851 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -8,6 +8,7 @@- Peach 维护安装策略与进度:下载校验后在程序同卷暂存,用户确认重启,复制出来的包内助手等待原托盘退出,再切换完整目录;失败保留或恢复旧目录。配置、数据库与媒体不作为更新包内容写入。- 已核对 [Velopack Windows 文档](https://docs.velopack.io/packaging/operating-systems/windows) 和 [WinSparkle 文档](https://winsparkle.org/):前者要求其安装目录与包格式,后者要求 appcast 并使用原生更新界面;现有 GitHub 产物为 PyInstaller ZIP,进度在 Web 显示,因此复用现有托盘进程与目录替换协议,未引入额外安装框架。- Web 复用 Fieldset、Progress、confirmModal;状态由 `standalone-update.json` 保存。下载按字节计量,解压按文件数计量,替换使用阶段进度;服务重启期间保留等待状态,恢复连接后核对版本。+- 新版有待应用迁移时,重启安装复用 `migrate upgrade --yes`,先保存 SQLite 备份;迁移或启动失败时恢复数据库与程序。数据库备份位于用户数据根的 `state/update-backups/`。JAV 默认封面(官方封面/预览图)与默认大小(大图/小图)独立保存,复用 localStorage、共享 Switch 和既有 `/cover`、`/poster` 接口,不新增依赖。`frontend/src/jav-artwork.ts` 负责作品身份、偏好恢复与缺图回退;首页、接着看、实体作品、详情推荐、Mix 静止与翻图、播放队列共用封面选择。小图保留所选来源,设置换图保留播放和滚动位置。diff --git a/src/peach/standalone_update.py b/src/peach/standalone_update.pyindex 2c3e07a7e..af142b4d4 100644--- a/src/peach/standalone_update.py+++ b/src/peach/standalone_update.py@@ -6,6 +6,7 @@ import jsonimport osfrom pathlib import Path, PurePosixPathimport shutil+import sqlite3import subprocessimport sysimport threading@@ -17,7 +18,7 @@ import httpxfrom filelock import FileLock, Timeoutfrom . import distribution, release_updates-from .config import STATE_DIR+from .config import STATE_DIR, DATABASE_PATHfrom .fsutil import atomic_write_textfrom .windows_update import replace_with_retry@@ -174,6 +175,36 @@ def poll(tray) -> None:tray._action_lock.release()+def migrate_database(stage: Path, data: dict) -> Path | None:+ from .migrations import plan, sqlite_backup+ if not DATABASE_PATH.is_file():+ return None+ _, pending = plan(DATABASE_PATH, stage / "_internal" / "migrations")+ if not pending:+ return None+ backup = STATE_DIR / "update-backups" / data["id"] / "ledger.db"+ sqlite_backup(DATABASE_PATH, backup)+ write(data, database_backup=str(backup), state="installing", progress=10, message="正在更新本地数据库")+ environment = dict(os.environ, PYINSTALLER_RESET_ENVIRONMENT="1")+ with (backup.parent / "migration.log").open("wb") as log:+ result = subprocess.run([str(stage / "Peach.exe"), "migrate", "upgrade", "--yes", "--db", str(DATABASE_PATH)],+ cwd=str(stage), env=environment, stdout=log, stderr=log, stdin=subprocess.DEVNULL,+ timeout=180, check=False, creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)+ if result.returncode:+ raise RuntimeError("数据库更新失败")+ return backup+++def restore_database(data: dict) -> None:+ backup = STATE_DIR / "update-backups" / data["id"] / "ledger.db"+ if not backup.is_file():+ return+ with sqlite3.connect(backup.as_uri() + "?mode=ro", uri=True) as source, sqlite3.connect(DATABASE_PATH) as destination:+ source.backup(destination)+ if destination.execute("PRAGMA integrity_check").fetchone()[0] != "ok":+ raise RuntimeError("数据库恢复检查失败")++def apply(manifest: Path, wait_pid: int) -> int:"""复制出来的助手等待原托盘正常退出,再在同一卷上切换两个目录。"""from .windows_restart import process_alive, start_tray, find_tray_windows, post_stop@@ -198,6 +229,7 @@ def apply(manifest: Path, wait_pid: int) -> int:if time.monotonic() > deadline:raise TimeoutError("托盘尚未退出,安装已取消")time.sleep(.25)+ migrate_database(stage, data)write(data, state="installing", progress=20, message="正在保留旧版本")replace_with_retry(target, backup)moved = True@@ -229,13 +261,18 @@ def apply(manifest: Path, wait_pid: int) -> int:post_stop(window.handle)replace_with_retry(target, transaction / "failed")replace_with_retry(backup, target)+ restore_database(data)start_tray(target / "Peach.exe")message = f"更新失败,已恢复旧版本:{exc}"except Exception as rollback:message = f"更新失败,回滚未完成:{rollback}"else:message = f"更新未安装:{exc}"- if not process_alive(wait_pid):- start_tray(target / "Peach.exe")+ try:+ restore_database(data)+ if not process_alive(wait_pid):+ start_tray(target / "Peach.exe")+ except Exception as rollback:+ message = f"更新失败,数据库恢复未完成:{rollback}"write(data, state="error", progress=0, message=message)return 1diff --git a/tests/test_standalone_update.py b/tests/test_standalone_update.pyindex 158f6a432..887019430 100644--- a/tests/test_standalone_update.py+++ b/tests/test_standalone_update.py@@ -4,6 +4,7 @@ import hashlibfrom contextlib import nullcontextfrom pathlib import Pathimport tempfile+import sqlite3import unittestfrom unittest.mock import Mock, patchimport zipfile@@ -20,6 +21,8 @@ class StandaloneUpdateTests(unittest.TestCase):self.state.mkdir()patcher = patch.object(update, "STATE_DIR", self.state)patcher.start(); self.addCleanup(patcher.stop)+ patcher = patch.object(update, "DATABASE_PATH", self.root / "ledger.db")+ patcher.start(); self.addCleanup(patcher.stop)def archive(self, names):archive = self.root / "package.zip"@@ -109,3 +112,20 @@ class StandaloneUpdateTests(unittest.TestCase):self.assertEqual(update.public()["state"], "error")start.assert_called_once_with(target / "Peach.exe")self.assertTrue(self.state.is_dir())++ def test_migration_failure_can_restore_the_sqlite_backup(self):+ with sqlite3.connect(update.DATABASE_PATH) as connection:+ connection.execute("CREATE TABLE fixture(value TEXT)")+ connection.execute("INSERT INTO fixture VALUES ('original')")+ data = {"id":"migration-fixture"}+ def failed_migration(*args, **kwargs):+ with sqlite3.connect(update.DATABASE_PATH) as connection:+ connection.execute("UPDATE fixture SET value='changed'")+ return Mock(returncode=1)+ with patch("peach.migrations.plan",return_value=([],[object()])), patch.object(+ update.subprocess,"run",side_effect=failed_migration):+ with self.assertRaises(RuntimeError):+ update.migrate_database(self.root,data)+ update.restore_database(data)+ with sqlite3.connect(update.DATABASE_PATH) as connection:+ self.assertEqual(connection.execute("SELECT value FROM fixture").fetchone()[0],"original")