Peach: Local-first video metadata scraper and media manager.
fix: use native Windows mDNS and refine immersive actions
Peach local maintenancef8c7bde54bdc
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 6792c7fa2..de3cbc542 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -21,7 +21,7 @@ This is durable operating knowledge, not a per-session transcript.## Operations- Main command: `peach serve|migrate` after editable installation.-- `peach serve` 默认发布 `peach.local`;使用 `--no-mdns` 可关闭。mDNS 注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。+- `peach serve` 默认发布 `peach.local`;使用 `--no-mdns` 可关闭。Windows 走系统 DNS-SD (`DnsServiceRegister`),其他平台走 zeroconf;mDNS 注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。health 的 `mdns_backend` 必须与运行态一致,不能只凭 `mdns` 字符串判断可用。- TLS 仅在同时提供 `--ssl-certfile` 和 `--ssl-keyfile` 时启用;`.local` 使用本地 CA,不使用 Let's Encrypt,证书和私钥留在 `R:\peach-data\secrets`。- 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.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex bb715c340..66adcc7c2 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -5,7 +5,7 @@ Last verified: 2026-08-14## Runtime- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 52476; health mode is `fastapi`.-- mDNS publisher: `peach.local` is published on `192.168.50.162` as HTTP, but an actual LAN client could not resolve it. Use `http://192.168.50.162/` until the client/router multicast path is fixed; no firewall/router change was made.+- mDNS root cause was the Python zeroconf responder failing to answer while several Windows applications shared UDP 5353, even though health incorrectly reported registration. Windows now uses the native DNS-SD API; LAN-client verification is pending the production restart below. No firewall or router rule was changed.- 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.@@ -31,12 +31,13 @@ Runtime PIDs are observations, not configuration; always re-check them.- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.-- 43 isolated tests and tracked-script static compilation passed under Python 3.14.+- 45 isolated tests and tracked-script static compilation passed under Python 3.14.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.- 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, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.- Optional SSL is supported with an explicit certificate/key pair. Production remains HTTP until a trusted local certificate is supplied.+- Immersive-mode actions now use optically centered 60 px controls with visible `不喜欢` / `看过` / `高潮` labels; the orgasm count is a corner badge and the watched state changes to `已看`.- The original Peach process could not see CloudDrive `A:`/`B:` even though CloudDrive was running. After confirming zero copy tasks and no I/O, CloudDrive and Peach were restarted in the same execution context. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks. Drive-letter visibility differs by Windows token, so the HTTP stream check is the authoritative service test.## Batch jobsdiff --git a/docs/adr/0004-network-and-profile-boundary.md b/docs/adr/0004-network-and-profile-boundary.mdindex f1764efae..05b5b78a7 100644--- a/docs/adr/0004-network-and-profile-boundary.md+++ b/docs/adr/0004-network-and-profile-boundary.md@@ -9,7 +9,7 @@- online 资产、追更和外部数据源是正式能力,不再受“绝不出网”旧约束;每个 connector 必须显式授权、控频、标注来源与保留策略。- schema 预留 `app_user`/`profile`,当前只创建本地默认身份,不开放注册、密码找回、公共会话或复杂 RBAC。- 远程访问以后可选择 VPN/Tunnel,或 DDNS + 反向代理 + HTTPS;应用本身不直接裸露公网端口。-- 局域网服务由 FastAPI 生命周期发布 `peach.local` mDNS;可用 `--no-mdns` 关闭,不再依赖旧 HTTP server。+- 局域网服务由 FastAPI 生命周期发布 `peach.local` mDNS;可用 `--no-mdns` 关闭,不再依赖旧 HTTP server。Windows 使用系统 `DnsServiceRegister` DNS-SD 后端,避免 Python zeroconf 与 CrossPaste/PikPak/Steam 等多个 UDP 5353 使用者竞争;其他平台保留 zeroconf 后端。- Uvicorn 支持显式证书/私钥的本机 TLS。`.local` 不能申请公开受信的 Let's Encrypt 证书;局域网需要 TLS 时使用受各客户端信任的本地 CA(如 mkcert),证书材料只放 `R:\peach-data\secrets`。- 公网启用前必须完成强口令/身份、TLS、反代可信头、CSRF/速率限制、secret storage、审计与备份恢复验收。diff --git a/src/peach/api.py b/src/peach/api.pyindex 36b447d81..9efcbed23 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -11,7 +11,7 @@ from . import web_contractfrom .config import PeachSettingsfrom .ffmpeg import FFmpegResolverfrom .media import FilesystemMediaService, MediaNotFound, MediaUnavailable-from .mdns import MdnsPublisher+from .mdns import create_mdns_publisherfrom .previews import PreviewService, PreviewUnavailablefrom .providers import OpenCodeGoClient, ProviderUnavailable, default_registryfrom .repository import LedgerRepository@@ -48,7 +48,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:repository, resolver, settings.snapshot_root, settings.poster_root,settings.avatar_root, settings.logo_root, settings.legacy_snapshot_roots,)- mdns = MdnsPublisher(+ mdns = create_mdns_publisher(settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled) if settings.mdns_enabled else Noneproviders = default_registry()@@ -102,6 +102,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:"db": "available" if settings.db_path.is_file() else "missing","ffmpeg": ffmpeg.source if ffmpeg else "unavailable","mdns": mdns.status if mdns is not None else "disabled",+ "mdns_backend": mdns.backend if mdns is not None else None,"mdns_address": mdns.address if mdns is not None else None,"scheme": "https" if settings.tls_enabled else "http"}diff --git a/src/peach/mdns.py b/src/peach/mdns.pyindex f72841e95..0596221b2 100644--- a/src/peach/mdns.py+++ b/src/peach/mdns.py@@ -1,13 +1,25 @@from __future__ import annotations+import ctypes+import osimport socket+import threadingfrom collections.abc import Callable+from ctypes import wintypesfrom zeroconf import ServiceInfo, ZeroconfHTTP_SERVICE_TYPE = "_http._tcp.local."HTTPS_SERVICE_TYPE = "_https._tcp.local."+DNS_REQUEST_PENDING = 9506+++def _normalized_name(name: str) -> str:+ normalized = name.strip().lower().removesuffix(".local")+ if not normalized or any(ch not in "abcdefghijklmnopqrstuvwxyz0123456789-" for ch in normalized):+ raise ValueError("mDNS name must contain only letters, digits, and hyphens")+ return normalizeddef lan_ipv4() -> str:@@ -21,6 +33,8 @@ def lan_ipv4() -> str:class MdnsPublisher:+ backend = "zeroconf"+def __init__(self,name: str,@@ -28,10 +42,7 @@ class MdnsPublisher:secure: bool = False,address_resolver: Callable[[], str] = lan_ipv4,) -> None:- normalized = name.strip().lower().removesuffix(".local")- if not normalized or any(ch not in "abcdefghijklmnopqrstuvwxyz0123456789-" for ch in normalized):- raise ValueError("mDNS name must contain only letters, digits, and hyphens")- self.name = normalized+ self.name = _normalized_name(name)self.port = portself.secure = secureself._address_resolver = address_resolver@@ -80,3 +91,144 @@ class MdnsPublisher:self._info = Noneself.address = Noneself.status = "stopped"+++_REGISTER_COMPLETE = getattr(ctypes, "WINFUNCTYPE", ctypes.CFUNCTYPE)(+ None, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p,+)+++class _DnsServiceRegisterRequest(ctypes.Structure):+ _fields_ = [+ ("Version", wintypes.ULONG),+ ("InterfaceIndex", wintypes.ULONG),+ ("pServiceInstance", ctypes.c_void_p),+ ("pRegisterCompletionCallback", _REGISTER_COMPLETE),+ ("pQueryContext", ctypes.c_void_p),+ ("hCredentials", wintypes.HANDLE),+ ("unicastEnabled", wintypes.BOOL),+ ]+++def _load_dnsapi():+ dnsapi = ctypes.WinDLL("dnsapi", use_last_error=True)+ dnsapi.DnsServiceConstructInstance.argtypes = [+ wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(wintypes.ULONG),+ ctypes.c_void_p, wintypes.WORD, wintypes.WORD, wintypes.WORD,+ wintypes.DWORD, ctypes.POINTER(wintypes.LPCWSTR),+ ctypes.POINTER(wintypes.LPCWSTR),+ ]+ dnsapi.DnsServiceConstructInstance.restype = ctypes.c_void_p+ dnsapi.DnsServiceRegister.argtypes = [+ ctypes.POINTER(_DnsServiceRegisterRequest), ctypes.c_void_p,+ ]+ dnsapi.DnsServiceRegister.restype = wintypes.DWORD+ dnsapi.DnsServiceDeRegister.argtypes = [+ ctypes.POINTER(_DnsServiceRegisterRequest), ctypes.c_void_p,+ ]+ dnsapi.DnsServiceDeRegister.restype = wintypes.DWORD+ dnsapi.DnsServiceFreeInstance.argtypes = [ctypes.c_void_p]+ dnsapi.DnsServiceFreeInstance.restype = None+ return dnsapi+++class WindowsMdnsPublisher:+ """Advertise through Windows DNS-SD instead of competing for UDP 5353."""++ backend = "windows-dns-sd"++ def __init__(+ self,+ name: str,+ port: int,+ secure: bool = False,+ address_resolver: Callable[[], str] = lan_ipv4,+ dnsapi_factory: Callable[[], object] = _load_dnsapi,+ ) -> None:+ self.name = _normalized_name(name)+ self.port = port+ self.secure = secure+ self._address_resolver = address_resolver+ self._dnsapi_factory = dnsapi_factory+ self._dnsapi = None+ self._instance: int | None = None+ self._request: _DnsServiceRegisterRequest | None = None+ self._callback = None+ self._event = threading.Event()+ self._callback_status: int | None = None+ self.address: str | None = None+ self.status = "pending"++ @property+ def hostname(self) -> str:+ return f"{self.name}.local"++ def start(self) -> None:+ if self._request is not None:+ return+ address = self._address_resolver()+ dnsapi = self._dnsapi_factory()+ service = "_https._tcp.local" if self.secure else "_http._tcp.local"+ instance_name = f"{self.name}.{service}"+ ip4 = wintypes.ULONG.from_buffer_copy(socket.inet_aton(address))+ keys = (wintypes.LPCWSTR * 2)("path", "scheme")+ values = (wintypes.LPCWSTR * 2)("/", "https" if self.secure else "http")+ instance = dnsapi.DnsServiceConstructInstance(+ instance_name, self.hostname, ctypes.byref(ip4), None, self.port,+ 0, 0, 2, keys, values,+ )+ if not instance:+ raise OSError(ctypes.get_last_error(), "DnsServiceConstructInstance failed")++ self._event.clear()+ self._callback_status = None++ @_REGISTER_COMPLETE+ def completed(status, _context, callback_instance):+ self._callback_status = int(status)+ if callback_instance:+ dnsapi.DnsServiceFreeInstance(callback_instance)+ self._event.set()++ request = _DnsServiceRegisterRequest(+ 1, 0, instance, completed, None, None, False,+ )+ result = int(dnsapi.DnsServiceRegister(ctypes.byref(request), None))+ if result != DNS_REQUEST_PENDING:+ dnsapi.DnsServiceFreeInstance(instance)+ raise OSError(result, "DnsServiceRegister failed")+ if not self._event.wait(5) or self._callback_status != 0:+ dnsapi.DnsServiceDeRegister(ctypes.byref(request), None)+ dnsapi.DnsServiceFreeInstance(instance)+ raise OSError(self._callback_status or result, "mDNS registration did not complete")+ self._dnsapi = dnsapi+ self._instance = instance+ self._request = request+ self._callback = completed+ self.address = address+ self.status = self.hostname++ def stop(self) -> None:+ if self._request is None or self._dnsapi is None:+ return+ self._event.clear()+ try:+ result = int(self._dnsapi.DnsServiceDeRegister(+ ctypes.byref(self._request), None,+ ))+ if result == DNS_REQUEST_PENDING:+ self._event.wait(5)+ finally:+ if self._instance:+ self._dnsapi.DnsServiceFreeInstance(self._instance)+ self._dnsapi = None+ self._instance = None+ self._request = None+ self._callback = None+ self.address = None+ self.status = "stopped"+++def create_mdns_publisher(name: str, port: int, secure: bool = False):+ publisher_type = WindowsMdnsPublisher if os.name == "nt" else MdnsPublisher+ return publisher_type(name, port, secure=secure)diff --git a/tests/test_mdns.py b/tests/test_mdns.pyindex b0da0b606..6240d5986 100644--- a/tests/test_mdns.py+++ b/tests/test_mdns.py@@ -1,7 +1,10 @@import unittestfrom unittest.mock import patch-from peach.mdns import MdnsPublisher+from peach.mdns import (+ DNS_REQUEST_PENDING, MdnsPublisher, WindowsMdnsPublisher,+ create_mdns_publisher,+)class MdnsPublisherTests(unittest.TestCase):@@ -35,6 +38,42 @@ class MdnsPublisherTests(unittest.TestCase):with self.assertRaises(ValueError):MdnsPublisher("bad name", 80)+ def test_windows_native_registration_lifecycle(self):+ class Function:+ def __init__(self, action=None, result=None):+ self.action = action+ self.result = result++ def __call__(self, *args):+ return self.action(*args) if self.action else self.result++ class DnsApi:+ def __init__(self):+ self.DnsServiceConstructInstance = Function(result=123)+ self.DnsServiceFreeInstance = Function()+ self.DnsServiceRegister = Function(self._complete)+ self.DnsServiceDeRegister = Function(self._complete)++ @staticmethod+ def _complete(request_pointer, _cancel):+ request_pointer._obj.pRegisterCompletionCallback(0, None, None)+ return DNS_REQUEST_PENDING++ dnsapi = DnsApi()+ publisher = WindowsMdnsPublisher(+ "peach", 80, address_resolver=lambda: "192.0.2.10",+ dnsapi_factory=lambda: dnsapi,+ )+ publisher.start()+ self.assertEqual(publisher.status, "peach.local")+ self.assertEqual(publisher.backend, "windows-dns-sd")+ publisher.stop()+ self.assertEqual(publisher.status, "stopped")++ @patch("peach.mdns.os.name", "nt")+ def test_factory_uses_windows_native_backend(self):+ self.assertIsInstance(create_mdns_publisher("peach", 80), WindowsMdnsPublisher)+if __name__ == "__main__":unittest.main()diff --git a/web/index.html b/web/index.htmlindex 5d9fe3bed..b7a0e6c91 100644--- a/web/index.html+++ b/web/index.html@@ -390,13 +390,23 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位.tok video.slide-dn{transform:translateY(8%);opacity:0}.tokui{position:absolute;inset:auto 0 0 0;padding:18px 20px 26px;color:#F3ECE2;background:linear-gradient(transparent,rgba(0,0,0,.84));pointer-events:none}-.tokbtns{position:absolute;right:15px;bottom:106px;display:flex;flex-direction:column;gap:11px}-.tokbtns button{width:52px;height:52px;border-radius:50%;border:1px solid rgba(255,255,255,.26);- background:rgba(0,0,0,.45);color:#F3ECE2;cursor:pointer;- display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px}-.tokbtns svg{width:22px;height:22px;stroke:currentColor;fill:none;stroke-width:1.8;+.tokbtns{position:absolute;right:max(14px,env(safe-area-inset-right));bottom:106px;+ display:flex;flex-direction:column;align-items:center;gap:12px}+.tokbtns button{position:relative;width:60px;height:60px;padding:7px 4px 6px;border-radius:50%;+ border:1px solid rgba(255,255,255,.28);background:rgba(12,12,14,.58);color:#F3ECE2;+ box-shadow:0 8px 28px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.06);+ backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);cursor:pointer;+ display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;+ transition:transform .14s,border-color .14s,background .14s}+.tokbtns button:hover{transform:scale(1.05);border-color:rgba(255,255,255,.5)}+.tokbtns button:active{transform:scale(.96)}+.tokbtns button:focus-visible{outline:2px solid var(--tungsten);outline-offset:3px}+.tokbtns svg{display:block;width:23px;height:23px;flex:none;stroke:currentColor;fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}-.tokbtns b{font-size:10px;font-family:"Cascadia Mono",monospace}+.toklabel{font-size:9px;font-weight:650;line-height:1;letter-spacing:.04em;white-space:nowrap}+.tokcount{position:absolute;top:3px;right:3px;min-width:16px;height:16px;padding:0 4px;+ border-radius:999px;background:var(--tungsten);color:#17110A;border:2px solid #111;+ display:grid;place-items:center;font:700 9px/1 "Cascadia Mono",monospace}/* 进度条 */.tokbar{position:absolute;left:0;right:0;bottom:0;height:4px;background:rgba(255,255,255,.16);cursor:pointer;z-index:3}@@ -477,9 +487,9 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位<div class="tokhint mono">滚轮 / ↑↓ 切换 · Esc 退出 · 横竖屏混流</div><button class="tokclose" id="tokClose">退出</button><div class="tokbtns">- <button id="tokDislike" title="不合口味"><svg viewBox="0 0 24 24"><path d="M17 14V3H7l-3 8v3h5l-1 5 5-5z" transform="rotate(180 12 12)"/></svg></button>- <button id="tokSeen" title="看过了"><svg viewBox="0 0 24 24"><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg></button>- <button id="tokO" title="记一次高潮"><svg viewBox="0 0 24 24"><path d="M12 21s-7-4.6-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 11c0 5.4-7 10-7 10z"/></svg><b id="tokOn">0</b></button>+ <button id="tokDislike" title="标为不喜欢" aria-label="标为不喜欢"><svg viewBox="0 0 24 24"><path d="M17 14V3H7l-3 8v3h5l-1 5 5-5z" transform="rotate(180 12 12)"/></svg><span class="toklabel">不喜欢</span></button>+ <button id="tokSeen" title="标为看过" aria-label="标为看过"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="m8.5 12 2.3 2.3 4.9-5"/></svg><span class="toklabel">看过</span></button>+ <button id="tokO" title="记一次高潮" aria-label="记一次高潮"><svg viewBox="0 0 24 24"><path d="M12 21s-7-4.6-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 11c0 5.4-7 10-7 10z"/></svg><span class="toklabel">高潮</span><b class="tokcount" id="tokOn">0</b></button></div><div class="tokbar" id="tokBar"><i id="tokProg"></i></div><div class="tokui"><div id="tokTitle" style="font-size:14px;margin-bottom:5px"></div>@@ -1101,6 +1111,7 @@ async function tokShow(dir){const d=v.duration||0; if(d)v.currentTime=d*((e.clientX-r.left)/r.width)};$('#tokDislike').setAttribute('aria-pressed',full.feedback==='dislike');$('#tokSeen').setAttribute('aria-pressed',full.feedback==='seen');+ $('#tokSeen .toklabel').textContent=full.feedback==='seen'?'已看':'看过';$('#tokOn').textContent=full.o_count||0;api('/api/play',{method:'POST',body:JSON.stringify({id:it.id})});wireTelemetry(it,v,{});@@ -1141,6 +1152,7 @@ $('#tok').addEventListener('touchend',e=>{const dy=ty-e.changedTouches[0].clientconst r=await api('/api/feedback',{method:'POST',body:JSON.stringify({id:it.id,kind})});$('#tokDislike').setAttribute('aria-pressed',r.feedback==='dislike');$('#tokSeen').setAttribute('aria-pressed',r.feedback==='seen');+ $('#tokSeen .toklabel').textContent=r.feedback==='seen'?'已看':'看过';$('#tokOn').textContent=r.o_count||0;if(kind==='dislike'&&r.feedback==='dislike')setTimeout(()=>tokNext(1),260)}});