Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: refine photo details and source reveal

longmeidaob09569c3a2fd
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 7b78b7bca..63c1cba68 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -37,6 +37,7 @@
## 本批修正与验证
- 0.7.13 让关注观看页复用资料页的“视频/图片”媒体 Tab,并在 URL 中保留图片视图;混合更新会同时进入两个视图,点开后默认落到当前媒体类型,待解析的外部文件页继续保留在默认视频视图。普通 Mix、分卷、播放列表与关注多视频合集统一为“左侧媒体、右侧详情、媒体下方切换队列”,不再让队列占用详情栏。接口继续使用既有 `media_kind`/`media_items`,没有新增依赖、迁移或真实 ledger 写入。Windows `follow` 412 项、正式全量 1185 项通过,分别 1/13 项按平台跳过;临时数据库浏览器实测关注页有视频 220、图片 13,1440×900 和 390×844 均无横向溢出;2 项关注合集与 29 项普通 Mix 都保持右侧详情、下方队列,控制台 0 错误。集成后生产网页资源已直接生效:真实关注页显示视频 220、图片 13,图片视图返回 13 张卡片;2 视频合集右侧保留 Sarah MFF Long 详情、队列紧接媒体下方。OpenSSL 以项目 CA、`peach-win.local` SNI 与主机名严格校验返回 `Verify return code: 0 (ok)`,HTTPS `/healthz` 正常且 HTTPS 脚本包含新 Tab。服务进程没有中断,故健康检查版本仍为 0.7.12;未写真实 ledger。
+- 0.7.13 将照片灯箱的详情入口收成单独的 30×30 圆形 `i`,去掉文字按钮;详情打开后点击面板和入口以外的位置会先收起提示,不误关整个灯箱;不足 1 MB 的图片大小改用 KB,避免显示成 `0 MB`。Windows 的“在资源管理器中显示”从 `explorer /select` 改为原生 `SHOpenFolderAndSelectItems`,完整路径仍只由服务端按 asset id 查询,不送到浏览器。临时文件实测接口返回成功,资源管理器窗口地址确认为目标文件所在目录;临时数据库在 1280×800 与 390×844 下实测图标水平、垂直中心偏差均为 0 px,手机详情面板为 360 px、无横向溢出,点图片区域可关闭提示,控制台错误为 0。变基到最新 master 后 Windows 正式全量 1186 项通过,13 项按平台跳过。用户确认截图中的图片均为已删除广告,本批未恢复图片、未把这些缺失文件判为代码故障,也未写真实 ledger。
- 0.7.12 修复艺人/厂牌资料页从深链或刷新进入时只看 URL 参数、因此漏掉 JAV 三种版式按钮的问题:页面现在从实际返回作品的 `is_jav` 推断资料页能力,并只给 JAV 卡片应用封面比例。照片查看器的缩放加减号改用本地 SVG,桌面和手机实测按钮与图标水平、垂直中心偏差均为 0 px;新增图片详情,显示文件名、来源和大小,切换图片时同步更新,并复用既有 `/api/reveal` 按 asset id 在资源管理器定位,客户端仍不接收或提交原始路径。照片 DTO 只新增安全的 `location`,没有迁移或真实 ledger 写入。Windows `catalog` 402 项、正式全量 1183 项通过,13 项按平台跳过;1440×900 下资料页三种版式按钮均可见,390×844 下详情面板 360 px 且位于 390 px 视口内,两端均无横向溢出和控制台错误。生产托盘已受控重启且继续使用原 0.7.11 EXE,80/443 由新子进程接管;HTTP 与项目 CA 严格 HTTPS `/healthz` 均返回 0.7.12、writer、非只读。生产资料页实测三种版式按钮均可见;真实 115 图片详情显示文件名、来源、大小和 asset id 定位入口,1280 px 与 390×844 下均无横向溢出,缩放图标中心偏差为 0 px。未点击生产定位按钮,未写真实 ledger。
- 0.7.11 将管理画像入口统一命名为“口味”;资源同步不再占用独立管理页,改为统计页末尾,旧 `/resource-sync` 深链自动替换为 `/stats#resource-sync`。同步配置按 Vercel 表单卡重排:主信息在上层,安全说明和 36px 次级操作放在带分隔线的底栏;扫描结果共用一套 12px 外框与内部 1px 分隔线,来源、汇总和确认操作不再各自嵌套卡片或压住边缘。按钮具备明确 hover/focus 和原位旋转忙碌态;窄屏规则提高到组件作用域,避免被后置基础规则覆盖。Windows 正式全量 1181 项通过、13 项按平台跳过。临时数据库的 1280×720 浏览器实测结果为三列来源、两列汇总、底栏按钮完全位于 1176px 外框内;390×844 下来源与汇总均为单列,外框 358px、底栏 356px、按钮 324×36,文档与视口同为 390px,无横向溢出。
- 0.7.11 正式 EXE 已替换为 SHA-256 `FCD54E557D9FE36FE3D3B0FFC50E486701CA5B990334A280F203691BF94EC9B0`,上版备份为 `dist/Peach/Peach.pre-0.7.11-20260829-004620.exe`;打包入口在临时 ledger 上确认 22 个迁移、0 待处理。80/443 均由新进程恢复,OpenSSL 以项目 CA、`peach-win.local` SNI 与主机名严格校验返回 `Verify return code: 0 (ok)`,固定到实际监听地址后的 `/healthz` 返回 0.7.11、writer、非只读,`/stats` 与旧 `/resource-sync` 均为 200。生产浏览器实测管理栏只有“口味”且无独立资源同步入口;1280×720 下配置卡 1166px、底栏 1164px、按钮 102×36,390×844 下卡片 348px、底栏 346px、按钮 314×36、无横向溢出和控制台错误;旧链接原位进入 `/stats#resource-sync`。未点击扫描、未执行同步应用。停止旧 SQLite 连接时主文件 SHA-256 由 `27F540B8F6B296F544EA2B250D159C0D7A2DFA6F59FA962F20AAE4CB2B63A8E3` 变为 `14F30D85F33631B74E99D9E1F48BBA090F57CD1D12AD3804AD47C2CC00FB8F60`,时间点与停服一致且重启后 WAL 为 0 字节,符合关闭连接时的 WAL 回写;只读复核为 `integrity_check=ok`、外键违规 0,asset 81555、follow_source 14、follow_item 1551、entity 8177。
diff --git a/src/peach/api.py b/src/peach/api.py
index f8bd260e9..0d2d5f5f6 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -5,7 +5,6 @@ import hashlib
import logging
import os
import re
-import subprocess
import uuid
import httpx
from concurrent.futures import ThreadPoolExecutor
@@ -44,7 +43,7 @@ from .media import (
from .mdns import create_mdns_publisher
from .platform import (
is_unmapped,
- reveal_command,
+ reveal_path,
root_online,
translate_ledger_path,
)
@@ -886,12 +885,9 @@ def create_app(
return JSONResponse(
{"error": "file missing", "location": asset.location},
status_code=410)
- command = reveal_command(target)
- if command is None:
- return JSONResponse({"error": "unsupported platform"}, status_code=501)
try:
- # explorer 成功时也返回 1,所以不能用 check=True 判成败。
- subprocess.Popen(command, close_fds=True)
+ if not reveal_path(target):
+ return JSONResponse({"error": "unsupported platform"}, status_code=501)
except OSError as error:
LOGGER.warning("reveal failed for asset %s: %s", asset_id, error)
return JSONResponse({"error": "reveal failed"}, status_code=500)
diff --git a/src/peach/platform.py b/src/peach/platform.py
index ccd6b769d..b95c83b1d 100644
--- a/src/peach/platform.py
+++ b/src/peach/platform.py
@@ -12,6 +12,7 @@ Windows 上运行,账本因此保持单一路径口径。
"""
from __future__ import annotations
+import ctypes
import logging
import os
import subprocess
@@ -235,16 +236,57 @@ def media_root_status(roots) -> tuple[dict[str, object], ...]:
return tuple(status)
-def reveal_command(path: Path) -> list[str] | None:
- """在文件管理器里定位这个文件的 argv;本平台不支持时返回 None。
+def _windows_reveal(path: Path) -> None:
+ """用 Shell 原生接口打开父目录并选中文件。
- 做成纯函数是为了能在没有桌面的环境里测:真正 spawn 的那一步只有一行。
- `explorer` 要求 `/select,<路径>` 整体是**一个**参数,逗号后不能断开,所以
- 必须用列表传参而不是拼字符串——顺带也就没有引号注入的余地。
+ `explorer /select` 只负责发起导航;现代 Explorer 已有多个窗口/标签时,新打开的
+ 正确目录可能留在旧「文档」窗口后面。`SHOpenFolderAndSelectItems` 是 Windows 为
+ 「在资源管理器中显示」提供的原生接口,直接接收完整 PIDL,不再依赖命令行解析。
"""
- target = os.fspath(path)
+ from ctypes import wintypes
+
+ ole32 = ctypes.WinDLL("ole32")
+ shell32 = ctypes.WinDLL("shell32")
+ ole32.CoInitializeEx.argtypes = [ctypes.c_void_p, wintypes.DWORD]
+ ole32.CoInitializeEx.restype = ctypes.c_long
+ ole32.CoUninitialize.argtypes = []
+ ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
+ shell32.SHParseDisplayName.argtypes = [
+ wintypes.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p),
+ wintypes.DWORD, ctypes.c_void_p,
+ ]
+ shell32.SHParseDisplayName.restype = ctypes.c_long
+ shell32.SHOpenFolderAndSelectItems.argtypes = [
+ ctypes.c_void_p, wintypes.UINT, ctypes.c_void_p, wintypes.DWORD,
+ ]
+ shell32.SHOpenFolderAndSelectItems.restype = ctypes.c_long
+
+ initialized = ole32.CoInitializeEx(None, 0x2) in (0, 1)
+ pidl = ctypes.c_void_p()
+ try:
+ parsed = shell32.SHParseDisplayName(
+ os.fspath(path), None, ctypes.byref(pidl), 0, None,
+ )
+ if parsed < 0 or not pidl.value:
+ raise OSError(f"SHParseDisplayName failed: 0x{parsed & 0xffffffff:08x}")
+ opened = shell32.SHOpenFolderAndSelectItems(pidl, 0, None, 0)
+ if opened < 0:
+ raise OSError(
+ f"SHOpenFolderAndSelectItems failed: 0x{opened & 0xffffffff:08x}"
+ )
+ finally:
+ if pidl.value:
+ ole32.CoTaskMemFree(pidl)
+ if initialized:
+ ole32.CoUninitialize()
+
+
+def reveal_path(path: Path) -> bool:
+ """在本机文件管理器中定位文件;不支持的平台返回 False。"""
if os.name == "nt":
- return ["explorer", f"/select,{target}"]
+ _windows_reveal(path)
+ return True
if sys.platform == "darwin":
- return ["open", "-R", target]
- return None
+ subprocess.Popen(["open", "-R", os.fspath(path)], close_fds=True)
+ return True
+ return False
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index aafa57a3f..066b20404 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -979,16 +979,13 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
async def test_photo_detail_reveal_resolves_the_asset_id_on_the_server(self):
source = self._seed_photo()
headers = {"X-Token": "secret"}
- command = ["file-manager", "select-source"]
- with (patch("peach.api.reveal_command", return_value=command) as resolve,
- patch("peach.api.subprocess.Popen") as launch):
+ with patch("peach.api.reveal_path", return_value=True) as reveal:
response = await self.client.post(
"/api/reveal", headers=headers,
json={"id": 9, "path": "C:/client-must-not-control-this"},
)
self.assertEqual(response.status_code, 200)
- resolve.assert_called_once_with(source)
- launch.assert_called_once_with(command, close_fds=True)
+ reveal.assert_called_once_with(source)
async def test_photo_thumbnail_is_generated_once_and_cached(self):
source = self._seed_photo()
diff --git a/tests/test_platform.py b/tests/test_platform.py
index 7dccbc739..0efa1a0f1 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -12,7 +12,8 @@ from peach.platform import (
is_windows_path,
mount_share,
mount_share_command,
- reveal_command,
+ _windows_reveal,
+ reveal_path,
root_online,
share_credentials_command,
share_credentials_present,
@@ -137,25 +138,49 @@ class OfflineModeTests(unittest.TestCase):
self.assertEqual([row["online"] for row in status], [True, False])
-class RevealCommandTests(unittest.TestCase):
- """在文件管理器里定位源文件的 argv。"""
-
- def test_windows_selects_the_file_in_one_argument(self):
- with patch("peach.platform.os.name", "nt"):
- command = reveal_command(Path(r"B:\创作者 b\c,d.mp4"))
- # explorer 要求 `/select,<路径>` 整体是一个参数:拆开或加引号都会
- # 变成「打开我的文档」。含空格和逗号的真实路径必须原样落在同一个参数里。
- self.assertEqual(command, ["explorer", r"/select,B:\创作者 b\c,d.mp4"])
+class RevealPathTests(unittest.TestCase):
+ """在文件管理器里定位源文件。"""
+
+ @unittest.skipUnless(os.name == "nt", "Windows Shell API only")
+ def test_windows_uses_the_native_shell_selection_api(self):
+ ole32, shell32 = Mock(), Mock()
+ ole32.CoInitializeEx.return_value = 0
+
+ def parse(_path, _bind, output, _attributes, _read_attributes):
+ output._obj.value = 1234
+ return 0
+
+ shell32.SHParseDisplayName.side_effect = parse
+ shell32.SHOpenFolderAndSelectItems.return_value = 0
+ with patch("peach.platform.ctypes.WinDLL",
+ side_effect=lambda name: ole32 if name == "ole32" else shell32):
+ _windows_reveal(Path(r"B:\创作者 a\c,d.mp4"))
+ self.assertEqual(shell32.SHParseDisplayName.call_args.args[0],
+ r"B:\创作者 a\c,d.mp4")
+ self.assertEqual(shell32.SHOpenFolderAndSelectItems.call_args.args[1:],
+ (0, None, 0))
+ ole32.CoTaskMemFree.assert_called_once()
+ ole32.CoUninitialize.assert_called_once_with()
+
+ def test_windows_reveal_delegates_to_the_native_shell(self):
+ source = Path(r"B:\创作者 a\c,d.mp4")
+ with (patch("peach.platform.os.name", "nt"),
+ patch("peach.platform._windows_reveal") as reveal):
+ self.assertTrue(reveal_path(source))
+ reveal.assert_called_once_with(source)
def test_macos_reveals_in_finder(self):
- with patch("peach.platform.os.name", "posix"), patch("peach.platform.sys.platform", "darwin"):
- self.assertEqual(
- reveal_command(Path("/Volumes/RESOURCES/media/a.mp4")),
- ["open", "-R", "/Volumes/RESOURCES/media/a.mp4"])
-
- def test_unsupported_platform_returns_none_instead_of_guessing(self):
- with patch("peach.platform.os.name", "posix"), patch("peach.platform.sys.platform", "linux"):
- self.assertIsNone(reveal_command(Path("/srv/a.mp4")))
+ source = Path("/Volumes/RESOURCES/media/a.mp4")
+ with (patch("peach.platform.os.name", "posix"),
+ patch("peach.platform.sys.platform", "darwin"),
+ patch("peach.platform.subprocess.Popen") as launch):
+ self.assertTrue(reveal_path(source))
+ launch.assert_called_once_with(["open", "-R", str(source)], close_fds=True)
+
+ def test_unsupported_platform_returns_false_instead_of_guessing(self):
+ with (patch("peach.platform.os.name", "posix"),
+ patch("peach.platform.sys.platform", "linux")):
+ self.assertFalse(reveal_path(Path("/srv/a.mp4")))
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 6c3fd0f8d..1ac6b1dd6 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -1512,12 +1512,18 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(".photozoom button svg{width:15px;height:15px;display:block;")
def test_lightbox_photo_detail_reveals_by_asset_id_without_leaking_a_path(self):
- self.assertPageContains('<button class="photodetailtoggle" type="button"')
+ self.assertPageContains('aria-label="图片详情" title="图片详情">${icon(\'info\')}</button>')
+ self.assertPageLacks("${icon('info')}<span>图片详情</span>",
+ "详情入口只显示圆圈 i,不再加文字按钮外框")
self.assertPageContains('<aside class="photodetail" aria-label="图片详情" hidden>')
self.assertPageContains("LOC[item.location]||item.location||'来源未知'")
+ self.assertPageContains("size<1024*1024?`${Math.max(1,Math.round(size/1024))} KB`")
self.assertPageContains("reveal.dataset.photoReveal=String(item.id)")
self.assertPageContains("revealSource(Number(reveal.dataset.photoReveal),status)")
+ self.assertPageContains("const dismissOutside=target=>{if(panel.hidden||toggle.contains(target)||panel.contains(target))return false")
+ self.assertPageContains("if(detail.dismissOutside(e.target))return")
self.assertPageContains(".photodetail[hidden]{display:none}")
+ self.assertPageContains(".photodetailtoggle{justify-self:start;width:30px;height:30px;display:grid;place-items:center")
self.assertPageLacks("item.path", "图片详情不能取得或渲染 ledger 绝对路径")
def test_lightbox_remeasures_when_the_window_resizes(self):
diff --git a/web/app.css b/web/app.css
index 633a58546..faf505f5d 100644
--- a/web/app.css
+++ b/web/app.css
@@ -405,10 +405,10 @@ body.photolight-open{overflow:hidden}
.photobar{position:relative;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;
padding:0 14px;min-height:30px}
.photocount{text-align:center;color:rgba(255,255,255,.72);font-size:var(--fs-xs)}
-.photodetailtoggle{justify-self:start;height:30px;display:flex;align-items:center;gap:6px;border:0;padding:0 8px;
- border-radius:var(--control-radius);background:transparent;color:rgba(255,255,255,.72);cursor:pointer}
+.photodetailtoggle{justify-self:start;width:30px;height:30px;display:grid;place-items:center;border:0;padding:0;
+ border-radius:50%;background:transparent;color:rgba(255,255,255,.72);cursor:pointer}
.photodetailtoggle:hover,.photodetailtoggle[aria-expanded="true"]{background:rgba(255,255,255,.12);color:#fff}
-.photodetailtoggle svg{width:16px;height:16px;display:block;stroke:currentColor;fill:none;stroke-width:2}
+.photodetailtoggle svg{width:20px;height:20px;display:block;stroke:currentColor;fill:none;stroke-width:2}
.photozoom{justify-self:end;display:flex;align-items:center;gap:8px;color:rgba(255,255,255,.72)}
.photozoom button{width:24px;height:24px;display:grid;place-items:center;border:0;border-radius:50%;
padding:0;background:rgba(255,255,255,.12);color:#fff;cursor:pointer}
@@ -430,7 +430,7 @@ body.photolight-open{overflow:hidden}
.photodetail>button svg{width:16px;height:16px;display:block;stroke:currentColor;fill:none;stroke-width:2}
.photodetail .srcstate{color:rgba(255,255,255,.62)}
@media (max-width:640px){.photozoom input{width:72px}.photozoom b{display:none}
- .photodetailtoggle span{display:none}.photodetailtoggle{padding:0 7px}.photodetail{bottom:96px}}
+ .photodetail{bottom:96px}}
.photolight .photostrip{width:100%;height:72px;padding:0 12px}
.photolight .photostrip .swiper-slide{width:auto;height:72px;opacity:.5;cursor:pointer;border-radius:6px;overflow:hidden}
.photolight .photostrip .swiper-slide img{height:100%;width:auto;display:block;object-fit:cover}
diff --git a/web/app.js b/web/app.js
index 15b9ef546..058fe214f 100644
--- a/web/app.js
+++ b/web/app.js
@@ -3015,6 +3015,8 @@ function wirePhotoZoom(box, main){
/* 图片详情只展示安全元数据,定位仍只把 asset id 交给服务端。绝不能为了显示路径把
ledger 的本机绝对路径送进浏览器。 */
+const fmtPhotoSize=raw=>{const size=Number(raw)||0;if(!size)return'大小未知';
+ return size<1024*1024?`${Math.max(1,Math.round(size/1024))} KB`:fmtSize(size)};
function wirePhotoDetail(box,items,index){
const toggle=box.querySelector('.photodetailtoggle');
const panel=box.querySelector('.photodetail');
@@ -3025,14 +3027,16 @@ function wirePhotoDetail(box,items,index){
const paint=at=>{
const item=items[at];if(!item)return;
title.textContent=item.name||'未命名图片';
- meta.textContent=[LOC[item.location]||item.location||'来源未知',
- Number(item.size)>0?fmtSize(Number(item.size)):'大小未知'].join(' · ');
+ meta.textContent=[LOC[item.location]||item.location||'来源未知',fmtPhotoSize(item.size)].join(' · ');
reveal.dataset.photoReveal=String(item.id);status.textContent='';
};
- toggle.onclick=()=>{const open=panel.hidden;panel.hidden=!open;
- toggle.setAttribute('aria-expanded',String(open))};
+ const dismiss=()=>{panel.hidden=true;toggle.setAttribute('aria-expanded','false')};
+ const dismissOutside=target=>{if(panel.hidden||toggle.contains(target)||panel.contains(target))return false;
+ dismiss();return true};
+ toggle.onclick=()=>{if(panel.hidden){panel.hidden=false;toggle.setAttribute('aria-expanded','true')}
+ else dismiss()};
reveal.onclick=()=>revealSource(Number(reveal.dataset.photoReveal),status);
- paint(index);return {paint};
+ paint(index);return {paint,dismiss,dismissOutside,isOpen:()=>!panel.hidden};
}
function closePhotoLightbox(){
@@ -3059,7 +3063,8 @@ async function openPhotoLightbox(index){
<button class="photonav back" type="button" aria-label="上一张">${icon('chevron-left')}</button>
<button class="photonav fwd" type="button" aria-label="下一张">${icon('chevron-left')}</button></div>
<div class="photobar">
- <button class="photodetailtoggle" type="button" aria-expanded="false">${icon('info')}<span>图片详情</span></button>
+ <button class="photodetailtoggle" type="button" aria-expanded="false"
+ aria-label="图片详情" title="图片详情">${icon('info')}</button>
<div class="photocount mono" aria-live="polite">${index+1} / ${items.length}</div>
<div class="photozoom">
<button type="button" data-zoom-step="-1" aria-label="缩小">${icon('minus')}</button>
@@ -3097,7 +3102,9 @@ async function openPhotoLightbox(index){
activeLightbox={box,main,strip,resize,zoomBar,detail};
box.querySelector('.photoclose').onclick=closePhotoLightbox;
// 只在背景本身上关闭:点图片、缩略图条和翻页按钮都不该退出。
- box.addEventListener('click',e=>{if(e.target===box)closePhotoLightbox()});
+ box.addEventListener('click',e=>{
+ if(detail.dismissOutside(e.target))return;
+ if(e.target===box)closePhotoLightbox()});
document.addEventListener('keydown',photoLightKeys);
}