Peach: Local-first video metadata scraper and media manager.
feat: add a macOS menu bar item, and give portrait cards one uniform ratio
Peach local maintenance41f42d391af3
diff --git a/src/peach/tray.py b/src/peach/tray.pyindex 6450534a7..0b783c489 100644--- a/src/peach/tray.py+++ b/src/peach/tray.py@@ -20,7 +20,14 @@ from .versioning import VersionManagerDEFAULT_LAN_ADDRESS = "192.168.50.162"-OPEN_URL = "https://peach.local/"+#: macOS 菜单栏项拉起的端口。80/443 在 macOS 上要 root,开发机不该为一个菜单栏图标+#: 去要管理员权限;本机 CA 的那套 TLS 材料也是给 Windows 生产实例签的。+MACOS_PORT = 8900+#: 单击菜单栏/托盘图标打开的地址。Windows 生产实例有本机 CA 的 HTTPS 和 80/443;+#: macOS 是开发环境,走非特权端口的 HTTP。+OPEN_URL = (+ f"http://127.0.0.1:{MACOS_PORT}/" if sys.platform == "darwin" else "https://peach.local/"+)def enable_hidpi() -> str:@@ -62,15 +69,37 @@ class AlreadyRunning(RuntimeError):class SingleInstance:- """A process-lifetime Windows file lock for the interactive tray."""+ """交互式托盘/菜单栏项的进程级单实例锁。"""def __init__(self, path: Path) -> None:self.path = pathself._handle = Nonedef acquire(self) -> None:- if os.name != "nt":- return+ """进程生命周期内的单实例锁。++ Windows 用 `msvcrt.locking`,POSIX 用 `fcntl.flock`——两者都在进程退出时由+ 内核释放,所以强杀之后不会留下一把解不开的锁。没有这层保护的话,菜单栏里会+ 出现两个 Peach,各自再拉起一份服务去抢同一个端口。+ """+ if os.name == "nt":+ self._acquire_windows()+ else:+ self._acquire_posix()++ def _acquire_posix(self) -> None:+ import fcntl++ self.path.parent.mkdir(parents=True, exist_ok=True)+ handle = self.path.open("a+b")+ try:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError as exc:+ handle.close()+ raise AlreadyRunning("Peach tray is already running") from exc+ self._handle = handle++ def _acquire_windows(self) -> None:import msvcrtself.path.parent.mkdir(parents=True, exist_ok=True)@@ -199,25 +228,49 @@ class ServiceManager:return self.wait_until_ready()+#: venv 里放可执行文件的目录与后缀。Windows 是 `Scripts\\peach.exe`,POSIX 是 `bin/peach`。+_BIN_DIR = "Scripts" if os.name == "nt" else "bin"+_EXECUTABLE = "peach.exe" if os.name == "nt" else "peach"++def _peach_executable() -> Path:if getattr(sys, "frozen", False):# 打包出来的托盘不是可移动的独立发行版:它仍然把服务进程的所有权交给项目 venv,# 因为 one-file bootloader 在本 Python 构建上再拉起一个 one-file 进程并不安全。# 逐级向上找 .venv,而不是写死 parents[2]——换个输出目录就不该整套失效。for parent in Path(sys.executable).resolve().parents:- managed = parent / ".venv" / "Scripts" / "peach.exe"+ managed = parent / ".venv" / _BIN_DIR / _EXECUTABLEif managed.is_file():return managed- sibling = Path(sys.executable).with_name("peach.exe")+ sibling = Path(sys.executable).with_name(_EXECUTABLE)if sibling.is_file():return sibling- candidate = PROJECT_ROOT / ".venv" / "Scripts" / "peach.exe"+ candidate = PROJECT_ROOT / ".venv" / _BIN_DIR / _EXECUTABLEif candidate.is_file():return candidate- raise FileNotFoundError("peach.exe is missing; reinstall the editable project")+ raise FileNotFoundError(f"{_EXECUTABLE} is missing; reinstall the editable project")+++def build_macos_service_specs() -> tuple[ServiceSpec, ...]:+ """macOS 只起一个非特权端口的 HTTP 服务。++ 不钉 `--mdns-address`:这台机器会换网络,钉死等于换个 Wi-Fi 就打不开+ (见 `peach.mdns` 的地址复查)。+ """+ peach = str(_peach_executable())+ return (+ ServiceSpec(+ "http",+ f"http://127.0.0.1:{MACOS_PORT}/healthz",+ (peach, "serve", "--host", "0.0.0.0", "--port", str(MACOS_PORT)),+ True,+ ),+ )def build_service_specs(lan_address: str | None = None) -> tuple[ServiceSpec, ...]:+ if sys.platform == "darwin":+ return build_macos_service_specs()address = lan_address or os.environ.get("PEACH_LAN_ADDRESS", DEFAULT_LAN_ADDRESS)peach = str(_peach_executable())cert_dir = SECRETS_DIR / "tls"@@ -246,14 +299,41 @@ def build_service_specs(lan_address: str | None = None) -> tuple[ServiceSpec, ..)-def create_icon(size: int = 64) -> Image.Image:- """Load the shared square Peach brand asset at tray resolution."""+def create_icon(size: int = 64, *, template: bool = False) -> Image.Image:+ """Load the shared square Peach brand asset at tray resolution.++ `template=True` 返回只有形状的单色版本:macOS 菜单栏图标必须是 template image,+ 由系统按浅色/深色菜单栏自己反色。彩色图标不会跟着变——浅色菜单栏下那颗桃子会+ 糊成一团。形状取自原图的 alpha 通道,颜色一律置黑。+ """resource = Path(getattr(sys, "_MEIPASS", PROJECT_ROOT)) / "resources" / "peach-logo.png"if not resource.is_file():resource = PROJECT_ROOT / "resources" / "peach-logo.png"if not resource.is_file():raise FileNotFoundError(f"Peach logo is missing: {resource}")- return Image.open(resource).convert("RGBA").resize((size, size), Image.Resampling.LANCZOS)+ image = Image.open(resource).convert("RGBA").resize((size, size), Image.Resampling.LANCZOS)+ if not template:+ return image+ black = Image.new("RGBA", image.size, (0, 0, 0, 0))+ black.putalpha(image.getchannel("A"))+ return black+++def apply_macos_template(icon) -> bool:+ """把菜单栏图标标成 template image。++ pystray 的 darwin 后端只做 `setImage_`,不调 `setTemplate_`,所以默认不会跟着+ 系统外观反色。这里在图标已经创建之后补上;拿不到底层 NSImage 就安静跳过——+ 菜单栏项本身仍然可用,只是不会自动反色。+ """+ if sys.platform != "darwin":+ return False+ image = getattr(icon, "_icon_image", None)+ setter = getattr(image, "setTemplate_", None)+ if setter is None:+ return False+ setter(True)+ return Truedef show_message(title: str, message: str, *, error: bool = False) -> None:@@ -281,7 +361,8 @@ class PeachTray:)self.icon = pystray.Icon("Peach",- create_icon(),+ # macOS 菜单栏要单色 template image,Windows 托盘要彩色品牌图。+ create_icon(template=sys.platform == "darwin"),"Peach · 蜜桃",pystray.Menu(pystray.MenuItem("打开 Peach", self.open, default=True),@@ -319,7 +400,9 @@ class PeachTray:def open_logs(self, _icon=None, _item=None) -> None:LOG_DIR.mkdir(parents=True, exist_ok=True)if os.name == "nt":- os.startfile(LOG_DIR)+ os.startfile(LOG_DIR) # type: ignore[attr-defined]+ elif sys.platform == "darwin":+ subprocess.run(["open", str(LOG_DIR)], check=False)def check_updates(self, icon=None, _item=None) -> None:if not self._update_lock.acquire(blocking=False):@@ -351,6 +434,8 @@ class PeachTray:def _setup(self, icon) -> None:icon.visible = True+ # 必须等图标真的创建出来才拿得到底层 NSImage,所以放在 setup 里而不是构造时。+ apply_macos_template(icon)if self._startup_warning:icon.notify(self._startup_warning, "Peach")diff --git a/tests/test_tray.py b/tests/test_tray.pyindex a07c6d5e9..3749ff064 100644--- a/tests/test_tray.py+++ b/tests/test_tray.py@@ -1,4 +1,5 @@import os+import sysimport tempfileimport threadingimport time@@ -8,7 +9,7 @@ from unittest.mock import Mock, patchfrom peach.tray import (AlreadyRunning, PeachTray, ServiceManager, ServiceSpec, SingleInstance,- create_icon, enable_hidpi,+ apply_macos_template, build_service_specs, create_icon, enable_hidpi,)from peach.versioning import UpdateResult, VersionSnapshot@@ -84,10 +85,8 @@ class TrayTests(unittest.TestCase):self.assertEqual(icon.notify.call_count, 2)icon.update_menu.assert_called_once()- @unittest.skipUnless(- os.name == "nt", "DPI 声明与单实例锁是 Windows 托盘专属能力"- )- def test_single_instance_rejects_second_windows_lock(self):+ def test_single_instance_rejects_a_second_holder(self):+ """两个菜单栏项会各自再拉起一份服务去抢同一个端口,必须挡住。"""with tempfile.TemporaryDirectory() as directory:path = Path(directory) / "tray.lock"first = SingleInstance(path)@@ -100,5 +99,34 @@ class TrayTests(unittest.TestCase):first.close()[email protected](sys.platform == "darwin", "菜单栏图标与服务规格是 macOS 专属")+class MacMenuBarTests(unittest.TestCase):+ def test_template_icon_is_a_black_silhouette(self):+ """macOS 菜单栏图标必须是 template image:彩色图不会跟着浅色/深色反色。"""+ colored = create_icon(32)+ template = create_icon(32, template=True)+ self.assertEqual(template.size, colored.size)+ self.assertEqual(template.getchannel("A").tobytes(), colored.getchannel("A").tobytes())+ opaque = [p for p in template.convert("RGBA").getdata() if p[3] > 0]+ self.assertTrue(opaque, "模板图不该整张透明")+ self.assertTrue(all(p[:3] == (0, 0, 0) for p in opaque), "模板图的颜色必须全黑")++ def test_service_spec_avoids_privileged_ports_and_a_pinned_address(self):+ """80/443 在 macOS 上要 root;地址钉死等于换个 Wi-Fi 就打不开。"""+ specs = build_service_specs()+ self.assertEqual(len(specs), 1)+ command = specs[0].command+ self.assertIn("--port", command)+ self.assertGreater(int(command[command.index("--port") + 1]), 1024)+ self.assertNotIn("--mdns-address", command)+ self.assertNotIn("--ssl-certfile", command)+++class TemplateHookTests(unittest.TestCase):+ def test_apply_template_is_a_no_op_without_a_backing_nsimage(self):+ """拿不到底层 NSImage 就安静跳过:菜单栏项本身仍然可用。"""+ self.assertFalse(apply_macos_template(Mock(spec=[])))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 9250cce07..e6af3153d 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -572,13 +572,17 @@ class WebUiSourceTests(unittest.TestCase):def test_creator_name_is_single_line_and_ellipsized(self):self.assertPageContains('.meta .who{color:var(--tungsten);min-width:0;max-width:100%;display:inline-block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap')- def test_only_portrait_cards_use_media_ratio(self):- """竖屏按实际宽高,其余固定比例——否则横屏卡片会在一列里高低不齐。+ def test_every_card_kind_has_one_fixed_ratio(self):+ """三类卡片各自一个固定比例,卡片之间不能高低不齐。- JAV 封面是第三种情况:大图只留右侧正封、宽度不变高度拉长,小图和预览图- 保持 16:9,判据是当前版式而不是媒体本身,所以它有自己的分支。+ 竖屏曾经按每条视频的实际宽高算,素材从 0.5 到 0.9 都有,竖屏条和竖屏网格+ 因此参差不齐。这段代码写下后一直没生效(`.pic` 写死 16/9),接上+ `--card-ratio` 才暴露出来。比例不同的用 contain 上下留黑边。"""self.assertPageContains("const ar=(it.ctx_orient==='竖屏'||cls==='scard')")+ self.assertPageContains("const PORTRAIT_RATIO=9/16;")+ self.assertPageContains(" ? PORTRAIT_RATIO")+ self.assertPageLacks("Math.min(0.9,Math.max(0.5,it.width/it.height))")self.assertPageContains("(jav&&layout==='big'?COVER_FRONT_RATIO:16/9)")def test_portrait_strip_sits_on_a_row_boundary_without_borrowing_extra_items(self):diff --git a/web/app.js b/web/app.jsindex 848b914f5..96a5b41e4 100644--- a/web/app.js+++ b/web/app.js@@ -363,6 +363,10 @@ const COVER_FRAME=`onload="const r=this.naturalWidth/this.naturalHeight;this.dat只在容器比图片更「竖」时才会横向裁,容器一旦宽过 1.48 就变成纵向裁、整张封套原样铺满——这正是「大图」以前只是撑满画布、没取到右侧的原因。 */const COVER_FRONT_RATIO=0.7;+/* 竖屏一律用同一个比例,不按每条视频的实际宽高。竖屏素材从 0.5 到 0.9 都有,+ 按各自比例渲染会让竖屏条和竖屏网格高低不齐;比例不同的用 contain 上下留黑边+ (`.poster` 本来就是 contain + 黑底)。 */+const PORTRAIT_RATIO=9/16;function coverImage(it,layout){const src=`/cover?code=${encodeURIComponent(it.code||'')}`;// 人脸只做纵向微调:人物在画面里的高低差别很大,写死的纵向位置会把一部分@@ -379,7 +383,7 @@ function cardHtml(it,cls){/* 卡片比例。这个值以前算出来就没人用过——`.pic` 一直写死 16/9,于是 JAV 的两种版式看起来一模一样。现在写进 `--card-ratio`,由 CSS 消费。 */const ar=(it.ctx_orient==='竖屏'||cls==='scard')- ? ((it.width&&it.height)?Math.min(0.9,Math.max(0.5,it.width/it.height)):9/16)+ ? PORTRAIT_RATIO/* 大图只留右侧正封,宽度不变、高度拉长;小图和预览图保持 16:9。没有封面的那些也跟着拉长:一行里高矮混排会把网格撕成锯齿状,缺封面的用 16:9 预览图上下留黑边即可(`.poster` 本来就是 contain + 黑底)。 */