Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: 完善测试包首启与本地空馆藏体验

longmeidao69b2d0ce1882
diff --git a/README.en.md b/README.en.md
index e4a583c49..f43bb0645 100644
--- a/README.en.md
+++ b/README.en.md
@@ -6,6 +6,8 @@
<p align="center">A personal library for media across your disks, mounted drives and followed sources.</p>
+The home page includes videos without thumbnails. Search suggestions come from the current library. An empty library keeps the people, studio and tag layout and offers actions to add content or sources.
+
<p align="center">
<a href="https://github.com/longmeidao/peach/releases">Download for Windows</a> ·
<a href="#quick-start">Quick start</a> ·
diff --git a/README.md b/README.md
index 43fb5fa7d..5a5d0752d 100644
--- a/README.md
+++ b/README.md
@@ -43,6 +43,8 @@ CloudDrive · 115 与 CloudDrive · PikPak 按本机文件夹接入;先在 Clo
右上角设置可控制打开本地作品和关注视频详情时是否自动播放。
+首页包含尚无缩略图的视频;搜索推荐仅来自当前馆藏。空馆藏保留头像、厂牌与标签布局,并提供添加内容与来源的入口。
+
人物头像和厂牌标识在大图、紧凑模式中允许适度放大;明显过小的图片居中,周围用同图模糊补底。小于 64 px 的展示区域保持普通图标样式。
设置中的「JAV 默认封面」可选官方封面或预览图,适用于首页、接着看、Mix、作品卡片和播放队列;缺图时使用另一种封面。「JAV 封面默认大小」可选大图或小图,两种大小都使用所选封面。偏好保存在当前浏览器。
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index dd1940d46..2956ab7af 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -1,6 +1,6 @@
# Peach 交接与长期工作约定
-本文件保存长期事实与规则;细节见技能、参考快照、专题文档与测试。
+长期约定;细节见技能与专题文档。
## 界面、媒体与复核的既定判据
@@ -73,7 +73,7 @@
## 参考产品证据登记
-- README 提交检查与参考取舍:[维护流程](README_MAINTENANCE.md)。
+- [Geist 控件](reference-snapshots/vercel-geist-controls-measured.md);[README 维护](README_MAINTENANCE.md)。
- 图 3、JavDB:`docs/REUSE.md`。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index 9c8065166..718868f27 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -4,6 +4,8 @@
## 已有骨架、尚未完成(6 项)
+- Windows 独立测试包的局域网访问与 mDNS:按用户要求先恢复本机访问,后续加入此功能;测试域名与开发环境隔离。首启页的局域网选项与当前测试包限制不一致,也在此项闭环。
+
本轮实施顺序(评审来源:[外部复评](https://chatgpt.com/c/6a9ad810-6148-83e9-95dd-6b58ef28e7ec),按当前源码核对;候选实现与生产验收分开):
- 运行与一致性:HTTP 只跳转 HTTPS;业务与调度由单一应用拥有;成功提交后失效缓存;缓存有界;可更新图片可复验;列表参数有上下界。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index a5e568e75..aecb10c0f 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -196,6 +196,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
| 局域网发现 | Python zeroconf | 服务生命周期和真实客户端验收 |
| 生成产物跨机同步 | Syncthing 2.1.x,Windows send-only → Mac receive-only | 目录划分、忽略规则、方向固定与「Mac 不发布正式产物」的边界 |
| Windows 托盘 | pystray 0.19.5(LGPLv3)、Pillow、Win32 Per-Monitor V2 DPI | Peach 服务归属、后台更新检查、菜单动作、品牌图标 |
+| Windows 文件夹选择与证书子进程 | 系统 IFileOpenDialog、SetThreadDpiAwarenessContext(Windows 10+)、Python 标准库 CREATE_NO_WINDOW | 选择器所在 PowerShell STA 线程设置 Per-Monitor V2 并恢复原上下文;OpenSSL 保留退出码与错误输出。没有新增依赖;托盘的进程 DPI 不会传给选择器子进程。 |
| macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 |
| 人脸取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.FaceDetectorYN` + opencv_zoo 定版模型 `face_detection_yunet_2023mar.onnx`(sha256 `8f2383e4…52fa4`,232 KB,放 `peach-data/tools/yunet/`,不进 Git);MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b` 的主脸聚类只作算法参考 | 头像/封面离线脚本共用 `peach.face_detect`,主脸选择、归一化焦点与 sidecar。**主脸不是最大的那张**:`main_face` 先筛掉分数落后最好那张 0.1 以上的框,再在剩下的里取最大。只按面积挑会被「大而勉强」的误检抢走(`performer-8218` 那张 600×1000 人像上,罩在胸口的框 0.427×0.313 分 0.798 压过 0.202×0.170 分 0.928 的脸,圆头像于是取景在胸口);只按分数挑会被背景里那张小而清晰的脸抢走(`performer-8540` 右上角 0.066×0.052 分 0.925)。954 张封面按这条重算,47 张换了主脸,每一张的新框分数都更高(`451HHH-029` 从画面中缝的 0.813 换到左上主体的 0.925)。**Haar 级联已不可用**:OpenCV 5 把它移出了 Python wheel(`cv2.CascadeClassifier` 不存在、`cv2/data/` 只剩 `__init__.py`),两个脚本一直抛 AttributeError,954 张封面 0 个 sidecar,取景从未生效。YuNet 同属 OpenCV,不是替代品,换掉的只是检出器这一层:Haar 在 512 张头像上检出 313、46 张封面上检出 24,YuNet 首轮 12 张封面检出 11,且带置信度,不必再靠位置规则丢假阳性。Pigo v1.4.6(MIT)512 张检出 488,但存在无脸误报且无 Python 部署优势,仍不引入。 |
| 115 文件清单 | `p115client==0.0.9.6.5.1`(MIT) | 只在显式 SHA-1 对账脚本中安装,Peach 负责 ledger 事务、备份与写入门槛 |
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 17e82b786..475bbb1ff 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -6,9 +6,11 @@
## 运行态
+- 测试包可本机访问,首页含无缩略图视频;mDNS 待办。
+
- JAV 封面、大小独立设置。
-- 导入或跳过后隐藏指南,折叠保留;浅色导航选中填灰;SFW 模式附说明。测试及桌面、手机预览通过。
+- 导入指南、浅色导航、SFW 说明已验收。
- 已恢复 41 张被封面覆盖的人像及焦点。封面禁止安装为头像,尺寸不符不套焦点;半脸场景已复现并修复。全量 3299、追加 2391、前端 77 项通过。
- 小图显示、资料骨架、官网图标、X 原色及自动播放开关已实现;桌面和手机预览通过,生产浏览器取证受客户端限制。请求共用 Chrome UA。
diff --git a/docs/reference-snapshots/vercel-geist-controls-measured.md b/docs/reference-snapshots/vercel-geist-controls-measured.md
index 46199d2fc..f977f7ea3 100644
--- a/docs/reference-snapshots/vercel-geist-controls-measured.md
+++ b/docs/reference-snapshots/vercel-geist-controls-measured.md
@@ -33,6 +33,8 @@ Peach 配置页的产品取值(根据用户于 2026-09-05 提出的间距要
## Peach 复用了什么
+2026-09-06 复核:官方 `https://vercel.com/geist/button` 明确导航使用 ButtonLink;首次设置完成页复用主站 `.geist-button.primary`,保持链接语义。`https://vercel.com/geist/label` 未给出「可选」专用颜色;Peach 自行采用已有 `--muted`、`--fs-sm` 与 400 字重,不宣称这是上游专用组件。密码输入与其他文本字段共用首启样式。官方正文可读取;IAB 与 Chrome 控制均返回 `js execution timed out`,本轮上游浏览器视觉实测未取得。
+
关注管理页(`web/css/22-followmanage.css`)据此:控件统一 32 px 高、14 px 字;
圆角取根变量的 **6 px** 而不是按钮的 4 px;默认按钮描边透明,只有主操作填色。
diff --git a/frontend/src/catalog-onboarding.ts b/frontend/src/catalog-onboarding.ts
new file mode 100644
index 000000000..642f25bc6
--- /dev/null
+++ b/frontend/src/catalog-onboarding.ts
@@ -0,0 +1,49 @@
+import { emptyStateHtml } from '@peach/legacy/ui';
+
+type Request = (url: string) => Promise<any>;
+const FILTERS = ['loc', 'creator', 'performer', 'studio', 'series', 'agency', 'tag', 'tag_match', 'len', 'dur_min', 'dur_max', 'orient', 'state', 'jav', 'thumb'];
+
+/** 空馆藏保留三个静止的身份、厂牌和标签占位,不宣称正在加载。 */
+export function emptyCatalogLayout(): { tiers: string; tags: string } {
+ const three = (html: string) => Array(3).fill(html).join('');
+ return {
+ tiers: '<div class="tier catalog-placeholder" aria-hidden="true">' + three('<span class="av"><span class="ring"></span><span class="nm">&nbsp;</span></span>')
+ + '</div><div class="tier catalog-placeholder" aria-hidden="true">' + three('<span class="brandpill"><span class="mk"></span><span class="placeholder-name">&nbsp;</span></span>') + '</div>',
+ tags: '<span class="catalog-placeholder placeholder-tags" aria-hidden="true">' + three('<span class="pill">&nbsp;</span>') + '</span>',
+ };
+}
+
+/** 推荐与当前列表共用筛选,并以实际搜索命中作为展示条件。 */
+export async function catalogSuggestions(state: Record<string, string>, request: Request): Promise<string[]> {
+ const params = new URLSearchParams();
+ for (const key of FILTERS) if (state[key]) params.set(key, state[key]);
+ const [facets, sample] = await Promise.all([
+ request('/api/facets?' + params), request('/api/items?' + params + '&limit=5'),
+ ]);
+ const candidates: string[] = [...new Set<string>([
+ ...(facets.creators || []), ...(facets.tagperformers || []), ...(facets.tags || []),
+ ].map(row => String(row.k || '')).concat((sample.items || []).map((row: { code?: string; name?: string }) => row.code || row.name || '')))]
+ .filter(value => value.length > 1).slice(0, 10);
+ const hits = await Promise.all(candidates.map(async value => {
+ const query = new URLSearchParams(params); query.set('q', value); query.set('limit', '1');
+ const result = await request('/api/items?' + query);
+ return result.total > 0 ? value : '';
+ }));
+ return hits.filter(Boolean);
+}
+
+/** 空馆藏、筛选无结果与资料尚未建立分别给出可执行入口。 */
+export function catalogEmptyHtml({ kind = 'catalog', filtered = false, jav = false, configurable = false, online = false } = {}): string {
+ const add = configurable ? '<a class="geist-button primary" href="/configuration">添加内容</a>' : '';
+ const follow = '<a class="geist-button" href="/follow-manage">添加来源</a>';
+ if (filtered || jav) return emptyStateHtml('search', jav ? '还没有符合条件的 JAV 作品' : '没有符合条件的内容',
+ jav ? '已扫描但尚未补充发行资料的视频可在全部内容中查看。' : '清除筛选或搜索条件后查看全部内容。',
+ { actions: '<a class="geist-button primary" href="/?loc=&thumb=0">查看全部内容</a>' });
+ if (kind !== 'catalog') {
+ const labels: Record<string, string> = { tags: '标签', performers: '艺人', creators: '创作者', studios: '厂牌', agencies: '事务所', series: '系列' };
+ return emptyStateHtml(kind === 'tags' ? 'tags' : 'user-round', '还没有' + (labels[kind] || '资料'),
+ online ? '添加关注来源并获取内容后,这里会显示对应标签。' : '添加内容并补充资料后,这里会显示对应信息。',
+ { actions: online ? follow : add + follow });
+ }
+ return emptyStateHtml('play', '还没有视频', '添加媒体文件夹或关注来源,开始建立你的馆藏。', { actions: add + follow });
+}
diff --git a/frontend/src/islands.ts b/frontend/src/islands.ts
index d8604884c..e80a4935c 100644
--- a/frontend/src/islands.ts
+++ b/frontend/src/islands.ts
@@ -31,6 +31,7 @@ export { refreshStore, storeNames } from './state';
export { watchJob, followJobProgress } from './jobs';
export { nativeImageFit, matchesFaceSource } from './native-image';
export { entitySkeletonHtml } from './entity-skeleton';
+export { catalogSuggestions, catalogEmptyHtml, emptyCatalogLayout } from './catalog-onboarding';
export { syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent } from './sidebar';
export { cleanupSkeletonHtml, cloudLocations, cloudPreferenceLocations, tasteHistoryGuideHtml, wireTasteHistoryGuide, TASTE_GUIDE_KEY } from './management';
export type { StoreName } from './state';
diff --git a/frontend/src/islands/configuration.tsx b/frontend/src/islands/configuration.tsx
index 64b5d8da6..b81d28e37 100644
--- a/frontend/src/islands/configuration.tsx
+++ b/frontend/src/islands/configuration.tsx
@@ -245,10 +245,10 @@ function ConfigurationForm({ data, receipt }: { data: ConfigurationData; receipt
if (saved) {
return (
<div class="configsaved" role="status">
- <Html html={noteHtml('配置已保存,Peach 正在重新启动。', { variant: 'success', label: '已保存' })} />
- <p class="confighelp">
- 几秒后自动打开新地址;没跳转就点 <a href={saved.url}>进入馆藏</a>。
- </p>
+ <div class="geist-note geist-note-success" role="note">
+ <svg aria-hidden="true" viewBox="0 0 24 24"><use href="#i-check" /></svg>
+ <p><span>配置已保存,Peach 正在重新启动。稍后自动跳转,或点击<a href={saved.url}>进入馆藏</a>。</span></p>
+ </div>
</div>
);
}
diff --git a/frontend/test/catalog-onboarding.test.ts b/frontend/test/catalog-onboarding.test.ts
new file mode 100644
index 000000000..4971456b4
--- /dev/null
+++ b/frontend/test/catalog-onboarding.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from 'vitest';
+import { catalogEmptyHtml, catalogSuggestions, emptyCatalogLayout } from '../src/catalog-onboarding';
+
+describe('当前馆藏推荐', () => {
+ it('空实例不显示示例词', async () => {
+ expect(await catalogSuggestions({}, async () => ({ items: [], tags: [] }))).toEqual([]);
+ });
+ it('少量内容也能推荐,且每条在当前筛选内有搜索命中', async () => {
+ const request = vi.fn(async (url: string) => {
+ const parsed = new URL(url, 'http://localhost');
+ expect(parsed.searchParams.get('jav')).toBe('1');
+ if (parsed.pathname === '/api/facets') return { tags: [{ k: '本机标签' }, { k: '失效词' }] };
+ if (!parsed.searchParams.has('q')) return { items: [{ name: '本机视频.mp4' }] };
+ return { total: parsed.searchParams.get('q') === '失效词' ? 0 : 1 };
+ });
+ expect(await catalogSuggestions({ jav: '1', q: '不会带入' }, request)).toEqual(['本机标签', '本机视频.mp4']);
+ });
+});
+
+describe('馆藏与资料空状态', () => {
+ it('空首页保留三个头像、厂商和标签的静止布局', () => {
+ const layout = emptyCatalogLayout();
+ expect(layout.tiers.match(/class="av"/g)).toHaveLength(3);
+ expect(layout.tiers.match(/class="brandpill"/g)).toHaveLength(3);
+ expect(layout.tags.match(/class="pill"/g)).toHaveLength(3);
+ expect(layout.tiers).not.toContain('aria-busy');
+ expect(layout.tiers).toContain('aria-hidden="true"');
+ });
+ it('空首页提供添加内容与来源的真实入口', () => {
+ const html = catalogEmptyHtml({ configurable: true });
+ expect(html).toContain('data-geist-empty-state');
+ expect(html).toContain('href="/configuration"');
+ expect(html).toContain('href="/follow-manage"');
+ expect(catalogEmptyHtml()).not.toContain('href="/configuration"');
+ });
+ it('JAV 与筛选无结果可查看未筛选内容', () => {
+ expect(catalogEmptyHtml({ jav: true })).toContain('尚未补充发行资料');
+ expect(catalogEmptyHtml({ filtered: true })).toContain('href="/?loc=&thumb=0"');
+ });
+ it('标签和各类实体没有资料时显示说明', () => {
+ for (const kind of ['tags', 'performers', 'creators', 'studios', 'agencies', 'series']) {
+ expect(catalogEmptyHtml({ kind })).toContain('data-geist-empty-state');
+ }
+ expect(catalogEmptyHtml({ kind: 'tags', online: true })).toContain('关注来源');
+ });
+});
diff --git a/frontend/test/configuration.test.tsx b/frontend/test/configuration.test.tsx
index ba1bafae3..14dbaca54 100644
--- a/frontend/test/configuration.test.tsx
+++ b/frontend/test/configuration.test.tsx
@@ -205,7 +205,9 @@ describe('保存', () => {
revision: 'rev-1', media_dirs: ['D:\\Media'], port: '9124', scan_now: false,
});
expect(receipt).toHaveBeenCalledWith('已保存配置');
- expect(el.querySelector('.geist-note-success')?.textContent).toContain('正在重新启动');
+ expect(el.querySelector('.geist-note-success')?.textContent).toContain('正在重新启动');
+ expect(el.querySelector('.geist-note-success a')?.previousSibling?.textContent).toMatch(/点击$/);
+ expect(el.querySelector('.configsaved > .confighelp')).toBeNull();
expect(el.querySelector<HTMLAnchorElement>('.configsaved a')?.getAttribute('href'))
.toBe('http://127.0.0.1:9124/');
expect(el.querySelector('form'), '保存后表单不再留在页面上').toBeNull();
diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.ts
index f5dc87719..500de049e 100644
--- a/frontend/test/stubs/legacy-ui.ts
+++ b/frontend/test/stubs/legacy-ui.ts
@@ -7,9 +7,10 @@ export const emptyStateHtml = (
iconName: string,
title: string,
description: string,
+ options: { actions?: string } = {},
): string => `<div class="emptystate" data-geist-empty-state role="status">`
+ `<div class="es-icon" data-icon="${iconName}"></div>`
- + `<div class="es-copy"><h3>${title}</h3><p>${description}</p></div></div>`;
+ + `<div class="es-copy"><h3>${title}</h3><p>${description}</p></div>${options.actions || ''}</div>`;
export const fieldsetTitle = (id: string, title: string): string =>
`<h3 class="geist-fieldset-title" id="${id}">${title}</h3>`;
diff --git a/src/peach/certs.py b/src/peach/certs.py
index f7ac600c4..0675c174c 100644
--- a/src/peach/certs.py
+++ b/src/peach/certs.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import ipaddress
import logging
+import os
import re
import shutil
import subprocess
@@ -63,6 +64,7 @@ def _openssl(*args: str, stdin: bytes | None = None) -> str:
# 显式给 encoding:text=True 会用平台默认编码,中文输出会静默丢成空 stdout。
text=stdin is None, encoding=None if stdin is not None else "utf-8",
errors=None if stdin is not None else "replace",
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
)
if result.returncode != 0:
detail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode(
diff --git a/src/peach/folder_picker.py b/src/peach/folder_picker.py
index 0ac77afe3..5a3231cad 100644
--- a/src/peach/folder_picker.py
+++ b/src/peach/folder_picker.py
@@ -89,6 +89,8 @@ namespace PeachPick {
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
public class FileOpenDialogRCW { }
public static class Picker {
+ [DllImport("user32.dll")]
+ static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
static extern IShellItem SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid interfaceId);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
@@ -111,6 +113,8 @@ namespace PeachPick {
}
}
public static string Pick(string title, string initial) {
+ var previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4));
+ try {
var dialog = (IFileOpenDialog)new FileOpenDialogRCW();
new System.Threading.Thread(() => Raise(title)).Start();
dialog.SetOptions(0x8 | 0x20 | 0x40);
@@ -126,6 +130,9 @@ namespace PeachPick {
string path;
picked.GetDisplayName(0x80058000, out path);
return path;
+ } finally {
+ if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi);
+ }
}
}
}
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index 24e3bf536..fc564e579 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -70,7 +70,7 @@ form{margin-top:32px}
.field{margin-top:24px}
.field>label,.field>.legend{display:block;margin:0 0 8px;font-weight:500;color:var(--ink)}
.req{color:var(--drop);margin-right:4px}
-input[type=text],input[type=number]{width:100%;height:var(--control-h);padding:0 12px;
+input[type=text],input[type=number],input[type=password]{width:100%;height:var(--control-h);padding:0 12px;
border:1px solid var(--line);border-radius:var(--control-radius);background:var(--ground);
color:var(--ink);font:inherit}
.affix{display:flex;align-items:center;height:var(--control-h);border:1px solid var(--line);
@@ -94,6 +94,8 @@ border-radius:var(--control-radius);color:var(--ink-2);cursor:pointer}
.switch label:has(input:focus-visible){outline:2px solid var(--tungsten);outline-offset:2px}
:focus-visible{outline:2px solid var(--tungsten);outline-offset:3px}
.help{margin:6px 0 0;color:var(--muted);font-size:var(--fs-sm)}
+.optional{margin-inline-start:8px;color:var(--muted);font-size:var(--fs-sm);font-weight:400}
+.field>label:not(:first-child){margin-top:24px}
/* 高级设置是 Geist Collapse:summary 是触发器,chevron 紧跟标题,与高度一样 200ms ease-in-out;
折叠体由 /js/ui-components.js 的 wireCollapse 接管。 */
details{margin-top:24px}
@@ -508,7 +510,7 @@ def setup_page(
fields.append(f'<details{opened}><summary><span>高级设置</span>{_CHEVRON_SVG}</summary>'
+ "".join(advanced) + "</details>")
access_error = str(errors.get("access_password", ""))
- fields.insert(1, '<div class="field"><label for="access-password">访问密码(可选)</label>'
+ fields.insert(1, '<div class="field"><label for="access-password">访问密码<span class="optional">可选</span></label>'
'<input id="access-password" name="access_password" type="password" maxlength="256" '
f'aria-invalid="{"true" if access_error else "false"}" '
'autocomplete="new-password" aria-describedby="access-help">'
@@ -533,7 +535,7 @@ def setup_page(
+ "".join(fields)
+ _check_html("scan_now", scan_text, checked=scan_now)
+ '<p class="help">扫描只读取文件名、大小和修改时间,不改动任何媒体文件。</p>'
- + '<section class="history-guide-choice"><h2>浏览器历史记录 <small>可选</small></h2>'
+ + '<section class="history-guide-choice"><h2>浏览器历史记录<span class="optional">可选</span></h2>'
+ _check_html("history_guide", "接下来导入浏览器历史记录", checked=values.get("history_guide") == "y")
+ '<p class="help">用于生成口味分析。完成设置后选择读取这台电脑,或导入其他设备的记录;也可稍后从「口味」进入。</p></section>'
+ '<button type="submit">完成设置</button></form>'
@@ -551,7 +553,7 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool, history_gui
scan = "首次扫描已排队。" if scan_requested else "你可以稍后在配置界面开始扫描。"
return _document("Peach · 设置完成",
'<h1>设置完成</h1><p class="lede">正在启动你的馆藏。' + scan + '</p>'
- f'<p><a href="{destination}">{destination_label}</a></p>'
+ f'<p><a class="geist-button primary" href="{destination}">{destination_label}</a></p>'
f'<meta http-equiv="refresh" content="8;url={destination}">'
+ runtime_facts_html(config))
ledger = (f"Peach 数据库已存在,没有动它:{tree.database}" if tree.ledger_existed
@@ -579,7 +581,7 @@ def setup_done_page(applied, *, windows: bool, scan_requested: bool, history_gui
f"{scan}"
"</ul>"
f"{mounts}"
- + f'<p><a href="{destination}">{destination_label}</a></p>'
+ + f'<p><a class="geist-button primary" href="{destination}">{destination_label}</a></p>'
+ runtime_facts_html(config)
)
return _document("Peach · 设置完成", body)
diff --git a/tests/test_access.py b/tests/test_access.py
index e08b64ce2..86fa7646f 100644
--- a/tests/test_access.py
+++ b/tests/test_access.py
@@ -118,7 +118,9 @@ class AccessTests(unittest.IsolatedAsyncioTestCase):
from peach import routes_pages, settings_file
config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.path.parent)})
html = routes_pages.setup_page(config, windows=True, values={"access_password": "sensitive-password"})
- self.assertIn("访问密码(可选)", html)
+ self.assertIn('访问密码<span class="optional">可选</span>', html)
+ self.assertIn('input[type=password]{width:100%;height:var(--control-h)', html)
+ self.assertIn('.optional{margin-inline-start:8px;color:var(--muted)', html)
form = html.split('<form method="post" action="/setup">', 1)[1]
self.assertLess(form.index('name="access_password"'), form.index("高级设置"))
self.assertNotIn("sensitive-password", html)
diff --git a/tests/test_certs.py b/tests/test_certs.py
index dce14e073..6be667c03 100644
--- a/tests/test_certs.py
+++ b/tests/test_certs.py
@@ -3,6 +3,7 @@ import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
+from unittest import mock
from peach.certs import (
CERT_DAYS,
@@ -27,6 +28,18 @@ def make_ca(tls_dir: Path) -> CertificateFiles:
class CertificateTests(unittest.TestCase):
+ def test_openssl_hides_its_windows_console_and_preserves_output(self):
+ from peach import certs
+ result = subprocess.CompletedProcess(['openssl'], 0, 'certificate output', '')
+ with mock.patch.object(certs.subprocess, 'run', return_value=result) as run:
+ self.assertEqual(certs._openssl('version'), 'certificate output')
+ expected = subprocess.CREATE_NO_WINDOW if certs.os.name == 'nt' else 0
+ self.assertEqual(run.call_args.kwargs['creationflags'], expected)
+ result.returncode, result.stderr = 1, 'test failure'
+ with mock.patch.object(certs.subprocess, 'run', return_value=result):
+ with self.assertRaisesRegex(RuntimeError, 'test failure'):
+ certs._openssl('version')
+
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.tls = Path(self._tmp.name) / "tls"
diff --git a/tests/test_configuration_sources.py b/tests/test_configuration_sources.py
index d0ebffa60..304e484f8 100644
--- a/tests/test_configuration_sources.py
+++ b/tests/test_configuration_sources.py
@@ -98,3 +98,9 @@ class MediaConfigurationTests(unittest.TestCase):
self.assertIn('/Volumes/115', html)
self.assertIn('peach scan configured', html)
self.assertNotIn('peach scan local', html)
+ self.assertIn('<a class="geist-button primary" href=', html)
+ with patch('peach.distribution.standalone', return_value=True):
+ packaged = setup_done_page(SimpleNamespace(config=config, tree=tree), windows=True,
+ scan_requested=False, history_guide=True)
+ self.assertIn('<a class="geist-button primary" href=', packaged)
+ self.assertIn('>导入浏览器历史记录</a>', packaged)
diff --git a/tests/test_folder_picker.py b/tests/test_folder_picker.py
index 0950dc90f..dbc0c6a1e 100644
--- a/tests/test_folder_picker.py
+++ b/tests/test_folder_picker.py
@@ -33,6 +33,9 @@ class CommandTests(unittest.TestCase):
self.assertIn("-STA", argv, "COM 对话框要求单线程套间")
self.assertEqual(argv[-2], "-EncodedCommand")
script = base64.b64decode(argv[-1]).decode("utf-16-le")
+ self.assertLess(script.index('SetThreadDpiAwarenessContext(new IntPtr(-4))'),
+ script.index('new FileOpenDialogRCW()'))
+ self.assertIn('SetThreadDpiAwarenessContext(previousDpi)', script)
self.assertIn('Guid("42f85136-db7e-439c-85f1-e4075d135fc8")', script, "IFileOpenDialog 的接口 ID")
self.assertIn("dialog.SetOptions(0x8 | 0x20 | 0x40)", script, "FOS_NOCHANGEDIR、FOS_PICKFOLDERS、FOS_FORCEFILESYSTEM")
self.assertNotIn("FolderBrowserDialog", script)
diff --git a/tests/test_scan.py b/tests/test_scan.py
index 95593669f..96cb05bd7 100644
--- a/tests/test_scan.py
+++ b/tests/test_scan.py
@@ -71,6 +71,16 @@ class WindowsShapeTests(_ScanCase):
for path in rows:
self.assertTrue(Path(path).is_file(), path)
+ def test_scanned_video_is_visible_without_a_thumbnail_filter(self):
+ from fastapi.testclient import TestClient
+ from peach.api import create_app
+ from peach.config import PeachSettings
+ self._scan(str(self.media), declared_roots={"local": (str(self.media),)}, windows=True)
+ with TestClient(create_app(PeachSettings(db_path=self.db, configured=True, token=""))) as client:
+ self.assertEqual(client.get('/api/items').json()['total'], 1)
+ self.assertEqual(client.get('/api/items?thumb=0').json()['total'], 1)
+ self.assertEqual(client.get('/api/items?thumb=1').json()['total'], 0)
+
def test_a_subdirectory_of_the_declared_root_is_accepted(self):
declared = {"local": (str(self.media),)}
result, _ = self._scan(str(self.media / "创作者"), declared_roots=declared, windows=True)
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index d6e303053..27c67cd8d 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -2620,7 +2620,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_search_active_index_resets_when_the_list_is_rebuilt(self):
# 列表重建后旧索引会指向不存在的行;输入和重新渲染都必须归零。
- self.assertPageContains("menu.hidden=false;searchActive=-1;")
+ self.assertPageContains("menu.hidden=!menu.innerHTML;searchActive=-1;")
self.assertPageContains("const refreshSearchMenu=()=>{searchActive=-1;")
def test_enter_uses_the_highlighted_option_before_the_suggestion(self):
@@ -4002,7 +4002,7 @@ class WebUiSourceTests(unittest.TestCase):
scope = self.page.split("const scope=facetParams.toString();", 1)[0]
self.assertIn("facetParams.set('state'", scope)
# 收窄到空时不能留下空带:实测已标记页上两排都没人,#tiers 仍占 28px。
- self.assertPageContains("$('#tiers').hidden=!(perfRow||studioRow);")
+ self.assertPageContains("$('#tiers').hidden=!(emptyLayout||perfRow||studioRow);")
self.assertPageContains(".tiers[hidden]{display:none}")
def test_collapsed_rail_is_divided_from_the_content_beside_it(self):
@@ -4140,7 +4140,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains('.playlistpage>header{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:16px}')
self.assertPageContains('.followfilters{position:relative;top:auto;z-index:1;height:auto;min-height:58px;margin:0 0 16px')
self.assertPageContains("emptyState('trash','回收站是空的','删掉的内容会先到这里;确认不再需要后再清空。')")
- self.assertPageContains("emptyState('search','没有符合条件的作品','调整筛选或搜索条件后再试。')")
+ self.assertPageContains("$('#grid').innerHTML=catalogEmptyHtml(")
+ self.assertPageContains("if(reset&&d.items.length)setGridCards(html)")
self.assertPageLacks('class="trashempty"')
def test_follow_fieldset_headers_share_one_control_height(self):
@@ -4315,10 +4316,10 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains(".resourcecardaction{position:absolute")
def test_search_suggestions_come_from_real_data_in_bulk(self):
- """写死的 6 个词翻两次就重复。顶部聚合只有几十条,也不够;索引接口一次给近千条。"""
+ """推荐取当前馆藏,并核对实际搜索命中。"""
self.assertPageContains("async function loadSearchPool()")
- self.assertPageContains("['performers','creators','tags'].map(")
- self.assertPageContains("`/api/index?kind=${kind}&limit=400`")
+ self.assertPageContains("await catalogSuggestions(state,api)")
+ self.assertPageContains("searchPoolCache=[]")
self.assertPageContains("Promise.all([loadSearchHistory(),loadSearchPool()])")
self.assertPageContains("[...searchPool()]")
@@ -4392,7 +4393,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_returning_home_from_any_surface_moves_the_highlight(self):
"""Logo、侧栏和沉浸关闭都必须清掉隐藏筛选,不能让 `/` 继续请求 JAV。"""
self.assertPageContains("function resetHomeState(){")
- self.assertPageContains("q:'',jav:'',thumb:'1'};")
+ self.assertPageContains("q:'',jav:'',thumb:'0'};")
self.assertPageContains("function openHome(scroll=false){")
self.assertPageContains("resetHomeState();route('/');$('#q').value='';disposeStage(false);showHomeSurfaces();")
self.assertPageContains("buildEdge();buildBars();load(true);")
@@ -5524,7 +5525,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageLacks("{k:'ads',label:'垃圾复核'}")
def test_search_placeholder_is_an_actionable_recommendation(self):
- self.assertPageContains("const SEARCH_HINTS=['Prestige','FC2','Sakura Misaki','丝袜','足交','ABW']")
+ self.assertPageLacks("const SEARCH_HINTS=")
+ self.assertPageContains("await catalogSuggestions(state,api)")
self.assertPageContains("$('#q').dataset.suggestion=searchSuggestion")
# 契约是「没有选中下拉项时,Enter 用当前推荐词」。下拉加了键盘导航后,
# 这个条件由 `!picked` 表达:没有高亮项时它就是 true,与旧的字面 true 等价。
diff --git a/web/app.js b/web/app.js
index 23e6c7e21..fe1174a80 100644
--- a/web/app.js
+++ b/web/app.js
@@ -5,7 +5,7 @@ import { javDisplayName, javTitleHtml } from './js/jav-title.js';
import { matchRoute, routeLabel } from './js/routes.js';
import { initMiddleTruncate } from './js/middle-truncate.js';
import { tagLabel } from './js/tags.js';
-import { syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent, cleanupSkeletonHtml, cloudLocations, cloudPreferenceLocations, tasteHistoryGuideHtml, wireTasteHistoryGuide, TASTE_GUIDE_KEY } from './dist/peach-ui.js';
+import { catalogSuggestions, catalogEmptyHtml, emptyCatalogLayout, syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent, cleanupSkeletonHtml, cloudLocations, cloudPreferenceLocations, tasteHistoryGuideHtml, wireTasteHistoryGuide, TASTE_GUIDE_KEY } from './dist/peach-ui.js';
import { javImageKind, normalizeJavImage, normalizeJavLayout, normalizeJavPreferences, syncJavImages, nativeImageFit, matchesFaceSource, entitySkeletonHtml } from './dist/peach-ui.js';
import {
attachOverlayScrollbar, breadcrumbHtml, checkboxHtml, closeAnchoredMenu, confirmModal, emptyStateHtml, fieldsetTitle,
@@ -594,6 +594,7 @@ const srcBadge=(loc,cost,cls)=>{const label=`${LOC[loc]||loc}${cost==='metered'?
/* 空态用 Vercel 的「icon tile + 标题 + 一句解释」结构。不放假动作按钮:
能执行的操作仍然留在各页自己的工具栏里,空态只负责解释为什么是空的。 */
const emptyState=emptyStateHtml;
+let runtimeConfigurable=null;
/* Toast:挂在 #toasts(body 直下)而不是 #stats 里——检查完会整页重画,
页内浮层会被冲掉,这里不会。对齐 Geist 的处方(取证见
@@ -712,12 +713,12 @@ function resolveSort(rawSort,rawDir,fallback=appSettings.defaultSort){
const initialCatalogUrl=(path=>isCatalogPath(path)||path==='/trash')(
decodeURIComponent(location.pathname));
const initialParam=key=>initialCatalogUrl?initialParams.get(key):null;
-state={loc:initialParams.get('loc')||'local,115',creator:initialParam('creator')||'',studio:initialParam('studio')||'',
+state={loc:initialParams.get('loc')??'local,115',creator:initialParam('creator')||'',studio:initialParam('studio')||'',
tag:cleanTagFilter(initialParam('tag')),len:initialParam('len')||'',dur_min:initialParam('dur_min')||'',dur_max:initialParam('dur_max')||'',
tag_match:initialParam('tag_match')==='any'?'any':'all',orient:initialParam('orient')||'',
state:ROUTE_STATES[decodeURIComponent(location.pathname)]||initialParam('state')||'',
...resolveSort(initialParam('sort'),initialParam('dir')),
- seed:initialParam('seed')||rollSeed(),q:initialParam('q')||'',jav:initialParam('jav')||'',thumb:'1'};
+ seed:initialParam('seed')||rollSeed(),q:initialParam('q')||'',jav:initialParam('jav')||'',thumb:initialParam('thumb')||'0'};
/* 脱盘的来源要从默认筛选里摘掉,否则首页照样按它筛,出来一屏点开就报脱盘的卡片。
只动默认值:地址栏里显式写了 `loc=` 就是用户自己选的,不替他改。
全部来源都脱盘时保持原样——清空筛选会变成「什么都不筛」,那比原状更糟。
@@ -749,7 +750,7 @@ let barsContext={type:'home',filters:state},detailReturnBarsContext=null;
function resetHomeState(){
state={loc:state.loc,creator:'',studio:'',tag:'',tag_match:'all',len:'',dur_min:'',dur_max:'',
orient:'',state:'',sort:appSettings.defaultSort,dir:defaultSortDir(appSettings.defaultSort),
- seed:rollSeed(),q:'',jav:'',thumb:'1'};
+ seed:rollSeed(),q:'',jav:'',thumb:'0'};
barsContext={type:'home',filters:state};detailReturnBarsContext=null;
barsDataCache=null;barsDataPromise=null;
}
@@ -2669,8 +2670,10 @@ async function buildBars(){
const perfRow=tops.performers.map(avHtml).join('');
const studioRow=tops.studios.map(bpHtml).join('');
const tier=html=>html?`<div class="tier">${html}</div>`:'';
- $('#tiers').innerHTML=tier(perfRow)+tier(studioRow);
- $('#tiers').hidden=!(perfRow||studioRow);
+ const emptyHome=context.type==='home'&&!javActive()&&!state.state&&!state.q&&!facetData.locations.some(row=>row.n>0);
+ const emptyLayout=emptyHome?emptyCatalogLayout():null;
+ $('#tiers').innerHTML=emptyLayout?emptyLayout.tiers+tier(emptyLayout.tags):tier(perfRow)+tier(studioRow);
+ $('#tiers').hidden=!(emptyLayout||perfRow||studioRow);
$('#tiers').removeAttribute('aria-busy');
$('#tiers').querySelectorAll('[data-entity-kind]').forEach(b=>b.onclick=()=>
openEntity(b.dataset.entityKind,b.dataset.entityName));
@@ -5712,7 +5715,8 @@ async function openIndex(kind,q,push=true,refine=false){
/* 公司格和人格在大图版式下要的形状不一样:竖幅是给脸留的,方标进去左右各被裁掉
一截。这一格里装的是什么,只有这里知道,所以在这里写进 DOM。 */
const cells=entityKind==='studio'||entityKind==='agency'?'company':'people';
- const body=people?`<div class="igrid" data-cells="${cells}" data-layout="${
+ const body=!d.items.length?catalogEmptyHtml({kind,filtered:!!q||(kind==='tags'&&tagIndexCategory!=='all'),configurable:runtimeConfigurable,online:onlineTags})
+ :people?`<div class="igrid" data-cells="${cells}" data-layout="${
peopleIndexLayout()}">${peopleHtml(d.items)}</div>`:tagHtml(tagItems);
const categoryOptions=onlineTags?ONLINE_TAG_CATEGORIES:TAG_CATEGORIES;
const visibleTagCategories=categoryOptions.filter(([key])=>key==='all'||Number(d.categories?.[key]||0)>0);
@@ -6511,7 +6515,6 @@ const MANAGE_SECTIONS=[
const MANAGE_MENU_SECTIONS=['stats','taste','cleanup','follow','configuration'];
/* 「配置」只对运行 Peach 的这台电脑有意义:服务端按调用方回 `/healthz` 的 `configurable`,
手机和另一台电脑的菜单里不列它。第一次画管理条时问一次,答复回来后重画。 */
-let runtimeConfigurable=null;
function probeConfigurable(){
if(runtimeConfigurable!==null)return;
runtimeConfigurable=false;
@@ -7020,15 +7023,22 @@ async function load(reset){
const html=state.state==='trash'?d.items.map(resourceCardHtml).join('')
:batchWithMix(d.items,isCatalogPath(decodeURIComponent(location.pathname))&&state.state!=='trash');
if(reset)releaseHoverPreviews($('#grid'));
+ let libraryEmpty=false;
+ if(reset&&!d.items.length&&state.state!=='trash'){
+ const library=await surfaceApi(surface,'/api/items?limit=1&thumb=0');
+ if(requestSeq!==loadRequestSeq||!surfaceCurrent(surface))return;
+ libraryEmpty=library.total===0;
+ }
if(reset&&state.state==='trash'&&!d.items.length)
$('#grid').innerHTML=emptyState('trash','回收站是空的','删掉的内容会先到这里;确认不再需要后再清空。');
else if(reset&&!d.items.length)
- $('#grid').innerHTML=emptyState('search','没有符合条件的作品','调整筛选或搜索条件后再试。');
+ $('#grid').innerHTML=catalogEmptyHtml({jav:javActive()&&!libraryEmpty,configurable:runtimeConfigurable,
+ filtered:!libraryEmpty});
/* 接下来这一页新增在当前这段里的起点:竖屏带的落点要落在新增的那几行之间,
不能又插回已经看过的上半屏。 */
const addedFrom=reset?0:[...lastGridSection().children].filter(x=>x.matches('.card[data-id]')).length;
- if(reset)setGridCards(html);
- else appendGridCards(html);
+ if(reset&&d.items.length)setGridCards(html);
+ else if(!reset)appendGridCards(html);
renderCount();
$('#loadSentinel').hidden=reset?d.items.length>=total:!d.has_more;
wireCards($('#grid'),state.state==='trash'?openResourceCard:undefined);
@@ -7043,33 +7053,23 @@ const loadObserver=new IntersectionObserver(entries=>{
offset+=appSettings.batchSize;load(false)}
},{rootMargin:'320px'});
loadObserver.observe($('#loadSentinel'));
-const SEARCH_HINTS=['Prestige','FC2','Sakura Misaki','丝袜','足交','ABW'];
-/* 推荐词取自真实数据,所以每一条都保证能搜到东西;写死的常量池只有 6 个词,
- 翻两次就重复。顶部聚合只给几十条,不够;索引接口一次能给近千条名字。 */
-let searchPoolCache=null;
-function searchPool(){
- if(searchPoolCache&&searchPoolCache.length)return searchPoolCache;
- const pool=[];
- const take=list=>(list||[]).forEach(x=>{const v=x&&x.k;if(v)pool.push(String(v))});
- if(typeof facets==='object'&&facets){take(facets.creators);take(facets.tagperformers);take(facets.tags)}
- const seen=new Set();
- const unique=pool.filter(v=>v.length>1&&!seen.has(v)&&seen.add(v));
- return unique.length>=8?unique:SEARCH_HINTS;
-}
+let searchPoolCache=[];
+let searchPoolRequest=0;
+function searchPool(){return searchPoolCache}
async function loadSearchPool(){
- if(searchPoolCache)return searchPoolCache;
+ const request=++searchPoolRequest;
+ searchPoolCache=[];
+ $('#q').dataset.suggestion='';$('#q').placeholder='搜索馆藏';
try{
- const lists=await Promise.all(['performers','creators','tags'].map(
- kind=>api(`/api/index?kind=${kind}&limit=400`)));
- const seen=new Set();
- const names=lists.flatMap(d=>(d.items||[]).map(x=>String(x.k||'')))
- .filter(v=>v.length>1&&!seen.has(v)&&seen.add(v));
- if(names.length>=50)searchPoolCache=names;
- }catch(e){/* 取不到就退回聚合结果,不影响搜索本身 */}
+ const names=await catalogSuggestions(state,api);
+ if(request!==searchPoolRequest)return searchPool();
+ searchPoolCache=names;
+ const searchSuggestion=names[Math.floor(Math.random()*names.length)]||'';
+ $('#q').dataset.suggestion=searchSuggestion;$('#q').placeholder=searchSuggestion||'搜索馆藏';
+ }catch(e){/* 推荐不可用时仍可直接输入搜索。 */}
return searchPool();
}
-const searchSuggestion=SEARCH_HINTS[Math.floor(Math.random()*SEARCH_HINTS.length)];
-$('#q').dataset.suggestion=searchSuggestion;$('#q').placeholder=searchSuggestion;
+$('#q').dataset.suggestion='';$('#q').placeholder='搜索馆藏';
let searchHistory=[];
function readSearchHistory(){return searchHistory.slice(0,appSettings.searchHistoryLimit)}
const loadSearchHistory=()=>api('/api/search-history?limit='+appSettings.searchHistoryLimit).then(d=>{searchHistory=Array.isArray(d.items)?d.items:[];return searchHistory}).catch(()=>searchHistory);
@@ -7083,8 +7083,8 @@ function renderSearchMenu(){const menu=$('#searchMenu'),history=readSearchHistor
const recommendations=[...searchPool()].sort(()=>Math.random()-.5).filter(x=>!history.some(h=>foldName(h)===foldName(x))).slice(0,5);
const row=(value,type)=>`<div class="searchoption" data-search-value="${esc(value)}">${icon(type==='history'?'history':'sparkles')}<span>${esc(value)}</span>${type==='history'?`<button class="removehistory" data-remove-history="${esc(value)}" aria-label="删除历史 ${esc(value)}">${icon('x')}</button>`:''}</div>`;
menu.innerHTML=(history.length?`<section class="searchgroup"><h3>搜索记录</h3>${history.map(x=>row(x,'history')).join('')}</section>`:'')+
- `<section class="searchgroup"><h3>推荐</h3>${recommendations.map(x=>row(x,'recommend')).join('')}</section>`;
- menu.hidden=false;searchActive=-1;
+ (recommendations.length?`<section class="searchgroup"><h3>推荐</h3>${recommendations.map(x=>row(x,'recommend')).join('')}</section>`:'');
+ menu.hidden=!menu.innerHTML;searchActive=-1;
menu.querySelectorAll('[data-search-value]').forEach(x=>x.onclick=e=>{if(e.target.closest('[data-remove-history]'))return;
$('#q').value=x.dataset.searchValue;runSearch(false,true);menu.hidden=true});
menu.querySelectorAll('[data-remove-history]').forEach(b=>{
@@ -8271,7 +8271,7 @@ function openCatalog(path){
junkKind=cleanJunkKind(params.get('type')||'');
junkView=params.get('view')==='dismissed'?'dismissed':'pending';
}
- state={...state,loc:params.get('loc')||'local,115',creator:params.get('creator')||'',studio:params.get('studio')||'',
+ state={...state,loc:params.get('loc')??'local,115',creator:params.get('creator')||'',studio:params.get('studio')||'',
tag:cleanTagFilter(params.get('tag')),tag_match:params.get('tag_match')==='any'?'any':'all',len:params.get('len')||'',
dur_min:params.get('dur_min')||'',dur_max:params.get('dur_max')||'',orient:params.get('orient')||'',
state:ROUTE_STATES[path]||params.get('state')||'',...resolveSort(params.get('sort'),params.get('dir')),
diff --git a/web/css/01-base.css b/web/css/01-base.css
index e6d90e767..ea6342874 100644
--- a/web/css/01-base.css
+++ b/web/css/01-base.css
@@ -185,6 +185,7 @@ button,a,input,textarea,select,summary{touch-action:manipulation}
line-height:1;white-space:nowrap;cursor:pointer;
transition:background-color .15s ease-in-out,border-color .15s ease-in-out,color .15s ease-in-out}
.geist-button:hover:not(:disabled){background:var(--surface)}
+.geist-button:is(a),.geist-button:is(a):hover{text-decoration:none}
.geist-button:focus-visible{outline:2px solid var(--tungsten);outline-offset:2px}
.geist-button:disabled{background:var(--sunk);border-color:var(--line-soft);color:var(--muted);cursor:default}
/* Vercel/Geist loading actions look unavailable and reject repeat activation,
diff --git a/web/css/09-skeleton.css b/web/css/09-skeleton.css
index bd37cd7b2..140aafbec 100644
--- a/web/css/09-skeleton.css
+++ b/web/css/09-skeleton.css
@@ -34,6 +34,12 @@
.postercard-skeleton .skeletoncard i{grid-column:1/-1}
.postercard-skeleton .skeletoncard s{display:block;grid-column:1;grid-row:2/span 3;align-self:start;
width:38px;height:38px;margin-top:5px;border-radius:50%;background:var(--hover)}
+.catalog-placeholder{pointer-events:none}
+.catalog-placeholder .ring,.catalog-placeholder .nm,.catalog-placeholder .mk,.catalog-placeholder .placeholder-name,.catalog-placeholder .pill{background:var(--hover)}
+.catalog-placeholder .nm{width:60%;margin-inline:auto;border-radius:var(--badge-radius)}
+.catalog-placeholder .placeholder-name{width:48px;border-radius:var(--badge-radius)}
+.placeholder-tags{display:inline-flex;gap:8px}
+.placeholder-tags .pill{width:64px;border-color:transparent}
.postercard-skeleton .skeletoncard b,
.postercard-skeleton .skeletoncard em,
.postercard-skeleton .skeletoncard u{grid-column:2}
diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.js
index ae5aec5df..7139db336 100644
--- a/web/dist/peach-ui.js
+++ b/web/dist/peach-ui.js
@@ -753,20 +753,22 @@ function nt({ data: e, receipt: t }) {
return S ? /* @__PURE__ */ W("div", {
class: "configsaved",
role: "status",
- children: [/* @__PURE__ */ W(G, { html: r("配置已保存,Peach 正在重新启动。", {
- variant: "success",
- label: "已保存"
- }) }), /* @__PURE__ */ W("p", {
- class: "confighelp",
- children: [
- "几秒后自动打开新地址;没跳转就点 ",
+ children: /* @__PURE__ */ W("div", {
+ class: "geist-note geist-note-success",
+ role: "note",
+ children: [/* @__PURE__ */ W("svg", {
+ "aria-hidden": "true",
+ viewBox: "0 0 24 24",
+ children: /* @__PURE__ */ W("use", { href: "#i-check" })
+ }), /* @__PURE__ */ W("p", { children: /* @__PURE__ */ W("span", { children: [
+ "配置已保存,Peach 正在重新启动。稍后自动跳转,或点击",
/* @__PURE__ */ W("a", {
href: S.url,
children: "进入馆藏"
}),
"。"
- ]
- })]
+ ] }) })]
+ })
}) : /* @__PURE__ */ W("form", {
class: "configfieldset",
"data-geist-fieldset": !0,
@@ -1878,8 +1880,62 @@ function nn(e, t) {
<div class="entitysection">${t}</div></div></section>`;
}
//#endregion
+//#region src/catalog-onboarding.ts
+var rn = [
+ "loc",
+ "creator",
+ "performer",
+ "studio",
+ "series",
+ "agency",
+ "tag",
+ "tag_match",
+ "len",
+ "dur_min",
+ "dur_max",
+ "orient",
+ "state",
+ "jav",
+ "thumb"
+];
+function an() {
+ let e = (e) => [
+ ,
+ ,
+ ,
+ ].fill(e).join("");
+ return {
+ tiers: "<div class=\"tier catalog-placeholder\" aria-hidden=\"true\">" + e("<span class=\"av\"><span class=\"ring\"></span><span class=\"nm\">&nbsp;</span></span>") + "</div><div class=\"tier catalog-placeholder\" aria-hidden=\"true\">" + e("<span class=\"brandpill\"><span class=\"mk\"></span><span class=\"placeholder-name\">&nbsp;</span></span>") + "</div>",
+ tags: "<span class=\"catalog-placeholder placeholder-tags\" aria-hidden=\"true\">" + e("<span class=\"pill\">&nbsp;</span>") + "</span>"
+ };
+}
+async function on(e, t) {
+ let n = new URLSearchParams();
+ for (let t of rn) e[t] && n.set(t, e[t]);
+ let [r, i] = await Promise.all([t("/api/facets?" + n), t("/api/items?" + n + "&limit=5")]), a = [...new Set([
+ ...r.creators || [],
+ ...r.tagperformers || [],
+ ...r.tags || []
+ ].map((e) => String(e.k || "")).concat((i.items || []).map((e) => e.code || e.name || "")))].filter((e) => e.length > 1).slice(0, 10);
+ return (await Promise.all(a.map(async (e) => {
+ let r = new URLSearchParams(n);
+ return r.set("q", e), r.set("limit", "1"), (await t("/api/items?" + r)).total > 0 ? e : "";
+ }))).filter(Boolean);
+}
+function sn({ kind: e = "catalog", filtered: n = !1, jav: r = !1, configurable: i = !1, online: a = !1 } = {}) {
+ let o = i ? "<a class=\"geist-button primary\" href=\"/configuration\">添加内容</a>" : "", s = "<a class=\"geist-button\" href=\"/follow-manage\">添加来源</a>";
+ return n || r ? t("search", r ? "还没有符合条件的 JAV 作品" : "没有符合条件的内容", r ? "已扫描但尚未补充发行资料的视频可在全部内容中查看。" : "清除筛选或搜索条件后查看全部内容。", { actions: "<a class=\"geist-button primary\" href=\"/?loc=&thumb=0\">查看全部内容</a>" }) : e === "catalog" ? t("play", "还没有视频", "添加媒体文件夹或关注来源,开始建立你的馆藏。", { actions: o + s }) : t(e === "tags" ? "tags" : "user-round", "还没有" + ({
+ tags: "标签",
+ performers: "艺人",
+ creators: "创作者",
+ studios: "厂牌",
+ agencies: "事务所",
+ series: "系列"
+ }[e] || "资料"), a ? "添加关注来源并获取内容后,这里会显示对应标签。" : "添加内容并补充资料后,这里会显示对应信息。", { actions: a ? s : o + s });
+}
+//#endregion
//#region src/sidebar.ts
-function rn(e) {
+function cn(e) {
return [
"/",
"/unseen",
@@ -1889,23 +1945,23 @@ function rn(e) {
"/junk-files"
].includes(e) || /^\/(item|mix|parts|editions)\//.test(e) || /^\/playlists\/\d+\/\d+$/.test(e) || /^\/(performers|studios|creators|series|agencies)\/.+/.test(e);
}
-function an(e, t) {
+function ln(e, t) {
return e.dataset.surface === t && e.querySelector(".dnav") ? !1 : (e.dataset.surface = t, e.replaceChildren(), !0);
}
-function on(e) {
+function un(e) {
let t = /* @__PURE__ */ new Map();
for (let n of e) for (let e of new Set(n.tags || [])) t.set(e, (t.get(e) || 0) + 1);
return [...t].sort((e, t) => t[1] - e[1]).slice(0, 30);
}
//#endregion
//#region src/management.ts
-function sn(e) {
+function dn(e) {
return e.filter((e) => ["115", "pikpak"].includes(e.location) && (e.roots === void 0 || e.roots.length > 0)).map((e) => e.location);
}
-function cn(e, t) {
+function fn(e, t) {
return t.filter((t) => e.some((e) => e.location === t));
}
-function ln() {
+function pn() {
return `<div class="cleanuppage" data-skeleton="cleanup" aria-busy="true" aria-label="正在读取数据管理状态">
<div class="cleanupgrid">${[
[
@@ -1951,7 +2007,7 @@ function ln() {
<footer class="geist-fieldset-footer" data-geist-fieldset-footer><button type="button"${r === 3 ? " class=\"danger\"" : ""} disabled>${r === 3 ? "<svg aria-hidden=\"true\"><use href=\"#i-trash\"></use></svg><span>" + t + "</span>" : t}</button></footer>
</section>`).join("")}</div></div>`;
}
-function un(e, t = !1, n = !1) {
+function mn(e, t = !1, n = !1) {
if (t || n) return "";
let r = "<svg aria-hidden=\"true\"><use href=\"#i-external-link\"></use></svg>";
return `<details class="taste-history-guide"${e ? " open" : ""}>
@@ -1965,43 +2021,43 @@ function un(e, t = !1, n = !1) {
<button type="button" class="taste-guide-skip">跳过</button>
</div></details>`;
}
-var dn = "peach-taste-guide-dismissed";
-function fn(e, t) {
+var hn = "peach-taste-guide-dismissed";
+function gn(e, t) {
let n = e.querySelector(".taste-history-guide");
n?.querySelector(".taste-guide-skip")?.addEventListener("click", () => {
- t.setItem(dn, "1"), n.remove();
+ t.setItem(hn, "1"), n.remove();
});
}
//#endregion
//#region src/jav-artwork.ts
-function pn(e) {
+function _n(e) {
return [
"small",
"sleeve",
"preview"
].includes(String(e)) ? "small" : "big";
}
-function mn(e) {
+function vn(e) {
return {
- javLayout: pn(e.javLayout),
- javImage: hn(e.javLayout === "preview" ? "thumbnail" : e.javImage)
+ javLayout: _n(e.javLayout),
+ javImage: yn(e.javLayout === "preview" ? "thumbnail" : e.javImage)
};
}
-function hn(e) {
+function yn(e) {
return e === "thumbnail" ? "thumbnail" : "cover";
}
-function gn(e, t) {
- return e.is_jav && e.code && e.has_cover && (hn(t) === "cover" || !e.has_thumb) ? "cover" : e.has_thumb ? "thumbnail" : "";
+function bn(e, t) {
+ return e.is_jav && e.code && e.has_cover && (yn(t) === "cover" || !e.has_thumb) ? "cover" : e.has_thumb ? "thumbnail" : "";
}
-function _n(e, t) {
+function xn(e, t) {
e.querySelectorAll("img[data-jav-image]").forEach((e) => {
- let n = e.dataset.javCover || "", r = e.dataset.javThumb || "", i = !!(n && (hn(t) === "cover" || !r)), a = i ? n : r;
+ let n = e.dataset.javCover || "", r = e.dataset.javThumb || "", i = !!(n && (yn(t) === "cover" || !r)), a = i ? n : r;
e.classList.toggle("cover", i), e.classList.toggle("whole", i && e.dataset.javImageLayout !== "big"), e.classList.toggle("front", i && e.dataset.javImageLayout === "big"), e.removeAttribute("style"), a && e.getAttribute("src") !== a && (e.src = a);
});
}
//#endregion
//#region src/islands.ts
-var vn = {
+var Sn = {
scraping: {
load: qt,
component: Xt
@@ -2014,11 +2070,11 @@ var vn = {
load: Ze,
component: rt
}
-}, yn = () => Object.keys(vn), $ = /* @__PURE__ */ new Map();
-async function bn(e, t, n, r = {}) {
- let i = vn[e];
+}, Cn = () => Object.keys(Sn), $ = /* @__PURE__ */ new Map();
+async function wn(e, t, n, r = {}) {
+ let i = Sn[e];
if (!i) throw Error(`未注册的 island:${String(e)}`);
- xn(t);
+ Tn(t);
let a = {
controller: new AbortController(),
painted: !1
@@ -2049,9 +2105,9 @@ async function bn(e, t, n, r = {}) {
};
xe(te(i.component, s), t);
}
-function xn(e) {
+function Tn(e) {
let t = $.get(e);
t && (t.controller.abort(), $.delete(e), t.painted && xe(null, e));
}
//#endregion
-export { dn as TASTE_GUIDE_KEY, ln as cleanupSkeletonHtml, sn as cloudLocations, cn as cloudPreferenceLocations, nn as entitySkeletonHtml, Kt as followJobProgress, yn as islandNames, gn as javImageKind, en as matchesFaceSource, bn as mountIsland, tn as nativeImageFit, hn as normalizeJavImage, pn as normalizeJavLayout, mn as normalizeJavPreferences, $t as refreshStore, rn as sidebarHasCatalogContent, on as sidebarTagCounts, Qt as storeNames, _n as syncJavImages, an as syncSidebarSurface, un as tasteHistoryGuideHtml, xn as unmountIsland, Gt as watchJob, fn as wireTasteHistoryGuide };
+export { hn as TASTE_GUIDE_KEY, sn as catalogEmptyHtml, on as catalogSuggestions, pn as cleanupSkeletonHtml, dn as cloudLocations, fn as cloudPreferenceLocations, an as emptyCatalogLayout, nn as entitySkeletonHtml, Kt as followJobProgress, Cn as islandNames, bn as javImageKind, en as matchesFaceSource, wn as mountIsland, tn as nativeImageFit, yn as normalizeJavImage, _n as normalizeJavLayout, vn as normalizeJavPreferences, $t as refreshStore, cn as sidebarHasCatalogContent, un as sidebarTagCounts, Qt as storeNames, xn as syncJavImages, ln as syncSidebarSurface, mn as tasteHistoryGuideHtml, Tn as unmountIsland, Gt as watchJob, gn as wireTasteHistoryGuide };