Peach: Local-first video metadata scraper and media manager.
refactor: remove legacy web server
Peach local maintenance9f09e68c0c48
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex a168cae9f..8b8fbd7a8 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -21,6 +21,7 @@ This is durable operating knowledge, not a per-session transcript.## Operations- Main command: `peach serve|migrate` after editable installation.+- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.- Long-running inventory helpers are under `scripts/`; their scheduled tasks use `R:\peach-app\.venv\Scripts\python.exe`. They use absolute data paths and may be interrupted/restarted where their own locking contract allows it.- Check ports 80, 8900 and 9999 before starting or switching services.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 8b0e2a37f..e53f6afc7 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,7 +4,7 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 58508; health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 51308; health mode is `fastapi`.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.@@ -15,17 +15,18 @@ Runtime PIDs are observations, not configuration; always re-check them.## Verified code state-- FastAPI serves home, legacy-compatible JSON, standard Range/HEAD media, thumbnails, posters, avatars and logos.-- Default ledger connections in the compatibility query layer are read-only; activity/play/feedback writes are explicit.+- FastAPI serves home, stable JSON contract, standard Range/HEAD media, thumbnails, posters, avatars and logos.+- The old `BaseHTTPRequestHandler`, dynamic legacy loader and automatic schema repair path are deleted. Default contract reads are read-only; activity/play/feedback writes are explicit.- FFmpeg/ffprobe are Peach-managed under `R:\peach-data\tools\ffmpeg`; resolver order is environment, managed bundle, then PATH. Active code has no Stash private binary fallback.- `R:\peach-data` now separates `database/generated/sources/state/secrets/logs/archive/inbox/tools`; the old empty root Inbox and old Resources/Tools compatibility surface are removed.-- 24 isolated tests passed under Python 3.14 after the real migration and FFmpeg decoupling.+- 21 isolated contract tests passed under Python 3.14 after removing three legacy-server-only tests with the deleted server.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check`.- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.- Restarted production port 80 passed health, home, 24,980-item all-source list, 2,552-item local list and one-byte `206 Partial Content` Range smoke checks.+- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.## Next work-1. Extract the remaining query/write functions from `compat_web.py`, then delete that compatibility module.-2. Route the remaining `scripts/ledger.py` Stash import through the centralized adapter and formalize entity provenance.+1. Route the remaining `scripts/ledger.py` Stash import through the centralized adapter and formalize entity provenance.+2. Split `web_contract.py` globals into explicit repository/application objects before enabling multiple workers.3. Implement the first real online-source and AI provider adapters behind the existing boundaries.diff --git a/docs/adr/0001-fastapi-modular-monolith.md b/docs/adr/0001-fastapi-modular-monolith.mdindex 1d67f7ff5..f72161e69 100644--- a/docs/adr/0001-fastapi-modular-monolith.md+++ b/docs/adr/0001-fastapi-modular-monolith.md@@ -10,8 +10,9 @@ Peach 已有可运行的旧 Web 服务,数据查询和写入函数大体独立## 决策- 后端渐进迁移到 FastAPI;前端与后端在代码职责上拆分,但继续单进程、单体部署。-- 第一阶段先提供 `/healthz` 与现有 `/api/*` JSON 兼容入口;第二阶段已补齐首页、标准媒体响应、- 缩略图和 preview/logo 路由。旧实现仅以 `src/peach/compat_web.py` 形式保留到生产切换完成。+- 第一阶段先提供 `/healthz` 与现有 `/api/*` JSON 入口;第二阶段已补齐首页、标准媒体响应、+ 缩略图和 preview/logo 路由。生产切换完成后,查询/写入 contract 已抽到+ `src/peach/web_contract.py`,旧 `BaseHTTPRequestHandler` 服务与动态加载器均已删除。- 不引入微服务、PostgreSQL、React 重写或完整账号系统。- Uvicorn 只允许单 worker,直到进程内缓存、写锁和后台任务状态移出全局变量。- schema 升级必须由显式迁移器完成;应用导入和健康检查不得自动改真实数据库。@@ -24,5 +25,5 @@ Peach 已有可运行的旧 Web 服务,数据查询和写入函数大体独立## 后果-迁移期会同时存在 legacy JSON adapter 与 FastAPI 入口,但每一步都可独立验证和回退。JSON、-媒体 Range、页面和双视口已通过;生产切换前仍需真实迁移备份、端口切换与 mDNS/回退演练。+FastAPI 现在是唯一 Web 入口;JSON contract、媒体 Range、页面和双视口保持兼容。进程内缓存与+写锁仍要求单 worker,后续可继续把 contract 拆为显式 repository/application 对象。diff --git a/src/peach/api.py b/src/peach/api.pyindex ac7cb41b6..dcafbe364 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -4,9 +4,9 @@ from typing import Anyfrom fastapi import Body, FastAPI, Requestfrom fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response+from . import web_contractfrom .config import PeachSettingsfrom .ffmpeg import FFmpegResolver-from .legacy_web import load_legacyfrom .media import FilesystemMediaService, MediaNotFound, MediaUnavailablefrom .previews import PreviewService, PreviewUnavailablefrom .repository import LedgerRepository@@ -30,7 +30,8 @@ def _authorized(request: Request, token: str, args: dict[str, str]) -> bool:def create_app(settings: PeachSettings | None = None) -> FastAPI:settings = settings or PeachSettings()- legacy = load_legacy(settings.legacy_module_path, settings.db_path, settings.token)+ web_contract.DB = str(settings.db_path)+ web_contract.cache_bust()repository = LedgerRepository(settings.db_path)resolver = FFmpegResolver(settings.ffmpeg_root)media_service = FilesystemMediaService(@@ -48,7 +49,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:openapi_url="/openapi.json" if settings.docs_enabled else None,)app.state.settings = settings- app.state.legacy = legacy+ app.state.web_contract = web_contractapp.state.repository = repositoryapp.state.media_service = media_serviceapp.state.preview_service = preview_service@@ -88,7 +89,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:@app.api_route("/favicon.svg", methods=["GET", "HEAD"])def favicon():- response = Response(legacy.FAVICON, media_type="image/svg+xml")+ response = Response(web_contract.FAVICON, media_type="image/svg+xml")response.headers["Cache-Control"] = "no-store"return response@@ -167,7 +168,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- return legacy.dispatch_api_get(f"/api/{route}", args)+ return web_contract.dispatch_api_get(f"/api/{route}", args)except KeyError:return JSONResponse({"error": "not found"}, status_code=404)except (TypeError, ValueError) as exc:@@ -181,7 +182,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- return legacy.dispatch_api_post(f"/api/{route}", body)+ return web_contract.dispatch_api_post(f"/api/{route}", body)except KeyError:return JSONResponse({"error": "not found"}, status_code=404)except (TypeError, ValueError) as exc:diff --git a/src/peach/config.py b/src/peach/config.pyindex c381eb3ff..f3d74f50d 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -24,7 +24,6 @@ class PeachSettings:db_path: Path = DATABASE_PATHpage_path: Path = PROJECT_ROOT / "web" / "index.html"token: str = ""- legacy_module_path: Path = Path(__file__).with_name("compat_web.py")docs_enabled: bool = Falseallowed_media_roots: tuple[Path, ...] = (Path(r"R:\media"), Path("B:/"), Path("A:/"))snapshot_root: Path = GENERATED_DIR / "snapshots"diff --git a/src/peach/legacy_web.py b/src/peach/legacy_web.pydeleted file mode 100644index b6e5c4a3d..000000000--- a/src/peach/legacy_web.py+++ /dev/null@@ -1,18 +0,0 @@-"""过渡加载器。--FastAPI 第一阶段复用已经验证的 q_*/w_* 数据函数;业务函数完成抽包后删除本模块。-"""-from importlib.util import module_from_spec, spec_from_file_location-from pathlib import Path-from types import ModuleType---def load_legacy(path: Path, db_path: Path, token: str = "") -> ModuleType:- spec = spec_from_file_location("peach_legacy_web", path)- if spec is None or spec.loader is None:- raise RuntimeError(f"无法加载旧 Web 模块:{path}")- module = module_from_spec(spec)- spec.loader.exec_module(module)- module.DB = str(db_path)- module.TOKEN = token- return modulediff --git a/src/peach/compat_web.py b/src/peach/web_contract.pysimilarity index 56%rename from src/peach/compat_web.pyrename to src/peach/web_contract.pyindex 8c70dcb31..d48c65e1a 100644--- a/src/peach/compat_web.py+++ b/src/peach/web_contract.py@@ -1,74 +1,22 @@-#!/usr/bin/env python3-# -*- coding: utf-8 -*-+"""Stable JSON contract used by the FastAPI application.++Database reads are read-only by default. Writes are limited to explicit activity and+feedback functions; schema changes belong to the migration runner."""-局域网最小壳 —— 能播 + 埋点 + 反馈。+from __future__ import annotations-为什么这个要先做(见《项目进度总览》判断 #18/#19):- 整套涌现推荐的燃料是消费数据,而消费数据只能从带埋点的播放器里来。- Stash 里 2,551 个 scene 只有 5 个有播放记录 —— 反馈闭环是空的,- 且只要消费还发生在 PotPlayer / 双击文件,它就会永远是空的。+import os+import re+import sqlite3+import threading+import time+from pathlib import Path-数据源是 ledger.db(唯一真相源),不是 Stash —— 因为 Stash 只索引了本地 2,552 个,-ledger 有全部 24,980 个(本地 + 115 + PikPak)。+from .config import DATABASE_PATH-边界:- · 只绑局域网,带 token;Stash 仍只绑 127.0.0.1,本服务不碰它- · 不上传任何东西到第三方,没有一个出网请求- · 反馈只写 ledger 的列,可改可撤- · **成本感知**:PikPak 是计费流量,界面显式标出,默认过滤掉-用法:- python -m peach.compat_web 默认 0.0.0.0:8899- python -m peach.compat_web --port 8899 --token 自定义口令-"""-import os, re, sys, json, time, html, hmac, sqlite3, mimetypes, threading, subprocess, urllib.parse-from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler-from http.cookies import SimpleCookie-from pathlib import Path+DB = str(DATABASE_PATH)-from peach.config import FFMPEG_DIR-from peach.ffmpeg import FFmpegResolver--DB = r"R:\peach-data\database\ledger.db"-HERE = os.path.dirname(os.path.abspath(__file__))-PAGE = os.path.join(os.path.dirname(os.path.dirname(HERE)), "web", "index.html")-SNAP_ROOT = r"R:\peach-data\generated\snapshots"-LOGO_ROOT = r"R:\peach-data\generated\logos"-AVA_ROOT = r"R:\peach-data\generated\avatars"-POSTER_ROOT = r"R:\peach-data\generated\posters"-_FFMPEG_RESOLVER = FFmpegResolver(FFMPEG_DIR)-_FFMPEG_CHOICE = _FFMPEG_RESOLVER.ffmpeg()-_FFPROBE_CHOICE = _FFMPEG_RESOLVER.ffprobe()-FFMPEG = str(_FFMPEG_CHOICE.path) if _FFMPEG_CHOICE else ""-FFPROBE = str(_FFPROBE_CHOICE.path) if _FFPROBE_CHOICE else ""--# 导入模块时绝不能解析进程级 sys.argv:Uvicorn 等宿主也使用 --host/--port。-# 旧服务仍从 main() 显式读取同样的参数,现有启动命令保持兼容。-PORT = 80-TOKEN = "" # 空 = 不校验,默认单用户本地自托管-MDNS_NAME = "peach" # → peach.local-HOST = "0.0.0.0"--def configure_cli(argv=None):- global PORT, TOKEN, MDNS_NAME, HOST- args = list(sys.argv[1:] if argv is None else argv)-- def option(name, default, cast=str):- if name not in args:- return default- pos = args.index(name)- if pos + 1 >= len(args):- raise SystemExit(f"{name} 缺少参数")- return cast(args[pos + 1])-- PORT = option("--port", 80, int)- TOKEN = option("--token", "")- MDNS_NAME = option("--name", "peach")- HOST = option("--host", "0.0.0.0")- return PORT, TOKEN, MDNS_NAME, HOST--# 允许直接串流的根目录 —— 除此之外一律拒绝,防目录穿越-ALLOW_ROOTS = [r"R:\\", r"B:\\", r"A:\\"]COST = {"local": "free", "115": "free", "pikpak": "metered", "online": "metered"}FAVICON = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0B0B0D"/><defs><linearGradient id="pg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FF9A76"/><stop offset="1" stop-color="#F2557B"/></linearGradient></defs><path d="M16 28c-5.7 0-9.7-3.6-9.7-8.6 0-4.3 2.8-7.6 6.5-7.6 1.4 0 2.4.5 3.2 1.1.8-.6 1.8-1.1 3.2-1.1 3.7 0 6.5 3.3 6.5 7.6C25.7 24.4 21.7 28 16 28z" fill="url(#pg)"/><path d="M16 13.4V27" stroke="#0B0B0D" stroke-width="1.1" opacity=".3" stroke-linecap="round"/><path d="M17.1 11.7c.6-2.8 2.8-4.6 5.6-4.8-.2 2.8-2.2 4.7-5.6 4.8z" fill="#5FB95F"/><path d="M16 11.9c0-1.9.5-3.4 1.5-4.5" stroke="#8A5A3B" stroke-width="1.5" stroke-linecap="round" fill="none"/></svg>')@@ -99,39 +47,6 @@ def db(write=False):c.row_factory = sqlite3.Rowreturn c-def ensure_columns():- """仅供旧库兼容/测试;生产启动不再自动调用。"""- c = db(write=True)- have = {r[1] for r in c.execute("PRAGMA table_info(asset)")}- for col, decl in (("feedback", "TEXT"), # dislike / seen (见方案 §5.4)- ("disposal", "TEXT"), # pending 待删- ("leave_ratio", "REAL"), # 离开位置 / 时长 —— 信息量最大的单个数字- ("play_seconds", "REAL"), # 累计观看秒数- ("feedback_at", "REAL"),- ("seek_count", "INTEGER"), # 拖动次数 —— 快进判断- ("max_reached", "REAL")): # 到达过的最远位置比值- if col not in have:- c.execute(f"ALTER TABLE asset ADD COLUMN {col} {decl}")- c.commit(); c.close()---def check_schema():- required = {"studio", "feedback", "disposal", "leave_ratio", "play_seconds",- "feedback_at", "seek_count", "max_reached"}- c = db()- try:- have = {r[1] for r in c.execute("PRAGMA table_info(asset)")}- finally:- c.close()- missing = sorted(required - have)- if missing:- raise SystemExit("ledger schema 缺列:" + ", ".join(missing)- + ";请先运行 peach migrate status/upgrade")--def allowed(p):- ap = os.path.abspath(p)- return any(ap.upper().startswith(r.replace("\\\\", "\\").upper()) for r in ALLOW_ROOTS)-# ────────────────────────────── 查询 ──────────────────────────────def q_items(args):@@ -548,7 +463,7 @@ def w_feedback(body):def dispatch_api_get(path, args):- """旧 HTTP 服务与 FastAPI 兼容入口共用的 JSON 路由表。"""+ """Dispatch the stable JSON read contract used by the current web client."""if path == "/api/items":return q_items(args)if path == "/api/item":@@ -577,339 +492,3 @@ def dispatch_api_post(path, body):if path == "/api/feedback":return w_feedback(body)raise KeyError(path)--# ────────────────────────────── HTTP ──────────────────────────────--class H(BaseHTTPRequestHandler):- protocol_version = "HTTP/1.1"- def log_message(self, *a): pass- def handle_one_request(self):- try:- super().handle_one_request()- except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):- self.close_connection = True-- def _auth(self, qs):- if not TOKEN: # 没设口令就不校验- return True- supplied = qs.get("t", [None])[0]- if supplied is not None and hmac.compare_digest(str(supplied), TOKEN):- return True- supplied = self.headers.get("X-Token")- if supplied is not None and hmac.compare_digest(str(supplied), TOKEN):- return True- # Cookie 必须按字段解析;直接做子串匹配会把 notok=<口令>、- # tok=<口令>extra 也误当成已登录。- cookie = SimpleCookie()- try:- cookie.load(self.headers.get("Cookie") or "")- supplied = cookie.get("tok").value if cookie.get("tok") else None- except Exception:- supplied = None- return supplied is not None and hmac.compare_digest(str(supplied), TOKEN)-- def _send(self, code, body=b"", ctype="application/json; charset=utf-8", extra=None):- self.send_response(code)- self.send_header("Content-Type", ctype)- self.send_header("Content-Length", str(len(body)))- # HTML 也必须 no-store —— 上一版给页面发了 max-age=86400,- # 改完前端刷新还是旧版,白查半天- cacheable = (ctype.startswith(("image/", "video/", "font/"))- and "svg" not in ctype) # favicon 要能立刻更新- self.send_header("Cache-Control", "max-age=86400" if cacheable else "no-store")- for k, v in (extra or {}).items():- self.send_header(k, v)- self.end_headers()- if body and self.command != "HEAD":- self.wfile.write(body)-- def _json(self, obj, code=200):- self._send(code, json.dumps(obj, ensure_ascii=False).encode())-- def do_GET(self):- u = urllib.parse.urlparse(self.path)- qs = urllib.parse.parse_qs(u.query)- p = u.path-- if p == "/":- if not self._auth(qs):- return self._send(401, "需要 ?t=口令".encode(), "text/plain; charset=utf-8")- with open(PAGE, "rb") as f:- body = f.read()- extra = ({"Set-Cookie": f"tok={TOKEN}; Path=/; Max-Age=31536000; SameSite=Lax; HttpOnly"}- if TOKEN else None)- return self._send(200, body, "text/html; charset=utf-8", extra)-- if p == "/favicon.svg":- return self._send(200, FAVICON.encode(), "image/svg+xml")- if not self._auth(qs):- return self._json({"error": "unauthorized"}, 401)-- if p.startswith("/api/"):- try:- return self._json(dispatch_api_get(p, {k: v[0] for k, v in qs.items()}))- except KeyError:- pass- if p == "/favicon.svg":- return self._send(200, FAVICON.encode(), "image/svg+xml")- if p == "/poster":- return self._poster(int(qs["id"][0]), int(qs.get("c", ["4"])[0]))- if p == "/avatar":- return self._avatar(int(qs["id"][0]))- if p == "/logo":- return self._logo(qs.get("studio", [""])[0])- if p == "/thumb":- return self._file_by_id(int(qs["id"][0]), thumb=True)- if p == "/stream":- return self._file_by_id(int(qs["id"][0]), thumb=False)- return self._json({"error": "not found"}, 404)-- def do_POST(self):- u = urllib.parse.urlparse(self.path)- qs = urllib.parse.parse_qs(u.query)- if not self._auth(qs):- return self._json({"error": "unauthorized"}, 401)- n = int(self.headers.get("Content-Length", 0))- try:- body = json.loads(self.rfile.read(n) or b"{}")- except Exception:- return self._json({"error": "bad json"}, 400)- try:- return self._json(dispatch_api_post(u.path, body))- except KeyError:- return self._json({"error": "not found"}, 404)- except Exception as e:- return self._json({"error": f"{type(e).__name__}: {e}"}, 500)-- def _avatar(self, aid):- """头像:从接触印相里裁**最亮的那一格**。-- 上一版固定裁中心格,遇到黑场就是个纯黑圆 —— 用户报的「还是有黑的」。- 现在按 [中心, 左上, 正中偏后, 右上, 左下] 顺序试,用 ffprobe 的 signalstats- 读平均亮度(YAVG),第一个够亮的就用;全都暗就用最亮的那个。裁完缓存。"""- os.makedirs(AVA_ROOT, exist_ok=True)- dst = os.path.join(AVA_ROOT, str(aid) + ".jpg")- if not os.path.exists(dst):- c = db()- r = c.execute("SELECT snapshot_path FROM asset WHERE id=?", (aid,)).fetchone()- c.close()- src = r["snapshot_path"] if r else None- if not src or not os.path.exists(src):- return self._send(404, b"", "text/plain")- best, best_y = None, -1.0- for col, row in ((1, 1), (0, 0), (1, 2), (2, 0), (0, 2), (2, 2)):- tmp = dst + f".{col}{row}.jpg"- try:- subprocess.run(- [FFMPEG, "-y", "-v", "error", "-i", src,- "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},"- "scale=160:160:force_original_aspect_ratio=increase,crop=160:160",- "-q:v", "4", tmp], capture_output=True, timeout=25)- if not os.path.exists(tmp):- continue- # 把这一格缩成 1x1 灰度,读出那一个字节 = 平均亮度。- # 不用 ffprobe 的 movie= 滤镜 —— Windows 盘符里的冒号会被当成参数分隔符。- raw = subprocess.run(- [FFMPEG, "-v", "error", "-i", tmp, "-vf", "scale=1:1",- "-f", "rawvideo", "-pix_fmt", "gray", "-"],- capture_output=True, timeout=20).stdout- y = float(raw[0]) if raw else 0.0- except Exception:- continue- if y > best_y:- if best and os.path.exists(best):- try: os.remove(best)- except Exception: pass- best, best_y = tmp, y- elif os.path.exists(tmp):- try: os.remove(tmp)- except Exception: pass- if best_y >= 60: # 够亮就不再试了- break- if not best or best_y < 12: # 全是黑场,别放一个黑圆上去- if best and os.path.exists(best):- try: os.remove(best)- except Exception: pass- return self._send(404, b"", "text/plain")- try:- os.replace(best, dst)- except Exception:- return self._send(404, b"", "text/plain")- if not os.path.exists(dst):- return self._send(404, b"", "text/plain")- with open(dst, "rb") as f:- return self._send(200, f.read(), "image/jpeg")-- def _poster(self, aid, cell):- """预览图:从接触印相裁出**单独一格**,保持原始宽高比。-- 前端框体固定 16:9,这张图用 object-fit:contain 放进去 —— 竖屏留黑边,- 既不拉伸也不把网格撑变形。上一版按素材比例改 tile 高度,竖屏直接把整行撑爆。"""- cell = max(0, min(8, cell))- col, row = cell % 3, cell // 3- os.makedirs(POSTER_ROOT, exist_ok=True)- dst = os.path.join(POSTER_ROOT, f"{aid}_{cell}.jpg")- if not os.path.exists(dst):- c = db()- r = c.execute("SELECT snapshot_path FROM asset WHERE id=?", (aid,)).fetchone()- c.close()- src = r["snapshot_path"] if r else None- if not src or not os.path.exists(src):- return self._send(404, b"", "text/plain")- try:- subprocess.run(- [FFMPEG, "-y", "-v", "error", "-i", src,- "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},"- "scale='min(640,iw)':-2",- "-q:v", "4", dst], capture_output=True, timeout=25)- except Exception:- return self._send(404, b"", "text/plain")- if not os.path.exists(dst):- return self._send(404, b"", "text/plain")- with open(dst, "rb") as f:- return self._send(200, f.read(), "image/jpeg")-- def _logo(self, studio):- """厂牌官网图标(已抓到本地,服务时不出网)。没有就 404,前端自动退回预览图裁切。"""- if not studio:- return self._send(404, b"", "text/plain")- nm = re.sub(r"[^A-Za-z0-9_-]", "_", studio)[:60]- cand = [os.path.join(LOGO_ROOT, nm + ".img")]- # 大小写不敏感兜底(库里 Faleno / FALENO 都有)- try:- low = nm.lower()- for f in os.listdir(LOGO_ROOT):- if f.lower() == low + ".img":- cand.append(os.path.join(LOGO_ROOT, f))- except Exception:- pass- for path in cand:- if os.path.exists(path):- ct = "image/x-icon"- try:- ct = open(path + ".ct", encoding="utf-8").read().strip() or ct- except Exception:- pass- with open(path, "rb") as f:- return self._send(200, f.read(), ct.split(";")[0])- return self._send(404, b"", "text/plain")-- # ── 按 id 取文件;路径不出网,且限制在白名单根目录内 ──- def _file_by_id(self, aid, thumb):- c = db()- r = c.execute("SELECT path,snapshot_path FROM asset WHERE id=?", (aid,)).fetchone()- c.close()- if not r:- return self._json({"error": "no such id"}, 404)- path = r["snapshot_path"] if thumb else r["path"]- if not path or not allowed(path) or not os.path.exists(path):- return self._json({"error": "unavailable"}, 404)- ctype = mimetypes.guess_type(path)[0] or "application/octet-stream"- size = os.path.getsize(path)- rng = self.headers.get("Range")- start, end = 0, size - 1- if rng:- m = re.match(r"bytes=(\d*)-(\d*)", rng)- if m:- if m.group(1): start = int(m.group(1))- if m.group(2): end = int(m.group(2))- end = min(end, size - 1)- length = max(end - start + 1, 0)- code = 206 if rng else 200- self.send_response(code)- self.send_header("Content-Type", ctype)- self.send_header("Accept-Ranges", "bytes")- self.send_header("Content-Length", str(length))- if rng:- self.send_header("Content-Range", f"bytes {start}-{end}/{size}")- self.send_header("Cache-Control", "max-age=86400" if thumb else "no-store")- self.end_headers()- if self.command == "HEAD":- return- try:- with open(path, "rb") as f:- f.seek(start)- left = length- while left > 0:- chunk = f.read(min(262144, left))- if not chunk: break- self.wfile.write(chunk); left -= len(chunk)- except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):- pass # 播放器 seek / 关标签页会中断流,属正常,不刷栈---# ── mDNS:发布 peach.local,全设备免配置访问 ────────────────────-# Mac / iOS / iPadOS 原生支持 .local;Windows 10+ 内置;Android 部分版本支持。-# 名字、访问口令、域名三者统一:Peach / peach / peach.local-_zc = None-def publish_mdns(ip, port, name):- """注册 A 记录 name.local → ip。失败不影响服务本身。"""- global _zc- try:- from zeroconf import Zeroconf, ServiceInfo- import socket as _s- _zc = Zeroconf()- info = ServiceInfo(- "_http._tcp.local.",- f"{name}._http._tcp.local.",- addresses=[_s.inet_aton(ip)],- port=port,- properties={"path": "/"},- server=f"{name}.local.",- )- _zc.register_service(info, allow_name_change=True)- return True- except Exception as e:- print(f" (mDNS 发布失败,不影响用 IP 访问:{type(e).__name__}: {e})")- return False--def lan_ip():- import socket- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- try:- s.connect(("223.5.5.5", 80)); return s.getsockname()[0]- except Exception:- return "127.0.0.1"- finally:- s.close()--def main(argv=None):- global PORT- configure_cli(argv)- check_schema()- srv = None- for port in ([PORT] + ([8899] if PORT != 8899 else [])):- try:- srv = ThreadingHTTPServer((HOST, port), H)- PORT = port- break- except OSError as e:- print(f" 端口 {port} 绑定失败({e}),换下一个")- if srv is None:- raise SystemExit("没有可用端口")-- ip = lan_ip()- ok = publish_mdns(ip, PORT, MDNS_NAME)- suffix = "" if PORT == 80 else f":{PORT}"- q = f"?t={TOKEN}" if TOKEN else ""- print("Peach · 蜜桃 已启动")- if ok:- print(f" 域名 http://{MDNS_NAME}.local{suffix}/{q} ← 手机/平板/Mac 直接用这个")- print(f" 局域网 http://{ip}{suffix}/{q}")- print(f" 本机 http://127.0.0.1{suffix}/{q}")- print(f" 账本 {DB}")- print(" Ctrl+C 停止")- try:- srv.serve_forever()- except KeyboardInterrupt:- print("\n已停止")- finally:- if _zc:- try:- _zc.unregister_all_services(); _zc.close()- except Exception:- pass---if __name__ == "__main__":- main()diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex ef5ad89f2..26ef55e40 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -85,6 +85,14 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):async def test_auth_and_items_contract(self):denied = await self.client.get("/api/items")self.assertEqual(denied.status_code, 401)+ wrong_cookie = await self.client.get(+ "/api/items", headers={"Cookie": "notok=secret"}+ )+ self.assertEqual(wrong_cookie.status_code, 401)+ cookie = await self.client.get(+ "/api/items?loc=local&limit=10", headers={"Cookie": "tok=secret"}+ )+ self.assertEqual(cookie.status_code, 200)response = await self.client.get("/api/items?t=secret&loc=local&limit=10")self.assertEqual(response.status_code, 200)data = response.json()diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex dfcb2c275..2e2100c0b 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -1,14 +1,9 @@-import importlib.utilimport sqlite3import tempfileimport unittestfrom pathlib import Path--MODULE_PATH = Path(__file__).resolve().parents[1] / "src" / "peach" / "compat_web.py"-SPEC = importlib.util.spec_from_file_location("rm_web", MODULE_PATH)-rm_web = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(rm_web)+from peach import web_contract as rm_webBASE_SCHEMA = """@@ -35,6 +30,13 @@ CREATE TABLE asset(o_count INTEGER,snapshot_path TEXT,first_seen TEXT,+ feedback TEXT,+ disposal TEXT,+ leave_ratio REAL,+ play_seconds REAL,+ feedback_at REAL,+ seek_count INTEGER,+ max_reached REAL,UNIQUE(location, path));CREATE TABLE asset_tag(@@ -75,7 +77,7 @@ class WebDataTests(unittest.TestCase):con.close()self.old_db = rm_web.DBrm_web.DB = self.db_path- rm_web.ensure_columns()+ rm_web.cache_bust()def tearDown(self):rm_web.DB = self.old_db@@ -88,14 +90,6 @@ class WebDataTests(unittest.TestCase):con.close()return row- def test_ensure_columns_is_idempotent(self):- rm_web.ensure_columns()- con = sqlite3.connect(self.db_path)- columns = {row[1] for row in con.execute("PRAGMA table_info(asset)")}- con.close()- self.assertTrue({"feedback", "disposal", "leave_ratio", "play_seconds",- "feedback_at", "seek_count", "max_reached"} <= columns)-def test_default_database_connection_is_readonly(self):con = rm_web.db()with self.assertRaises(sqlite3.OperationalError):@@ -127,32 +121,5 @@ class WebDataTests(unittest.TestCase):self.assertIsNone(rm_web.w_feedback({"id": 1, "kind": "dislike"})["feedback"])self.assertEqual(self.row()["disposal"], "pending")--class AuthTests(unittest.TestCase):- def setUp(self):- self.old_token = rm_web.TOKEN- rm_web.TOKEN = "secret"- self.handler = rm_web.H.__new__(rm_web.H)-- def tearDown(self):- rm_web.TOKEN = self.old_token-- def check(self, cookie="", header=None, query=None):- self.handler.headers = {"Cookie": cookie}- if header is not None:- self.handler.headers["X-Token"] = header- return self.handler._auth(query or {})-- def test_cookie_name_and_value_must_match_exactly(self):- self.assertTrue(self.check(cookie="tok=secret"))- self.assertFalse(self.check(cookie="notok=secret"))- self.assertFalse(self.check(cookie="tok=secretextra"))-- def test_query_and_header_tokens(self):- self.assertTrue(self.check(query={"t": ["secret"]}))- self.assertTrue(self.check(header="secret"))- self.assertFalse(self.check(header="wrong"))--if __name__ == "__main__":unittest.main()