Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 提供高清封面采集与本机来源配置

longmeidaoff516fbb3473
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index fffa444d0..b9ffd6beb 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -10,8 +10,8 @@
- 数据与查询:标签、实体筛选从关系索引驱动;随机排序有唯一次序;重复索引与外键启用先做副本验证;补固定规模基准。
- 安装与诊断:下面第 12、13、21、22、23 项按依赖实施,覆盖最小源码安装、wheel 资源、仓库外启动、就绪检查。独立桌面制品及操作系统 VM 验收仍按第 15、21 项推进。
- 抓取可复现性:按 [ADR-0024](adr/0024-mark-manifest-not-bundled-bytes.md) 落地来源配置与清单。
- 先处理 [抓取审计](SCRAPING_AUDIT.md) 中的 client 所有权、私有后缀误判和重复限流,再共用网络、缓存、
- 凭据与任务服务;提供 Cookie 粘贴/文件导入/有效性验证、按来源代理与标准/最高可得画质模式。
+ `/scraping` 已有定点高清封面、FC2 Cookie 粘贴/文件导入和封面来源网络配置;剩余来源还需接入
+ 统一配置、会话有效性验证与完整批量 GUI。清单导入导出、标准模式与 Javinizer-Go 工具配置待实施。
Instagram 成熟解析器须有独立用户会话 POC;Windows/macOS 干净安装和二次运行缓存命中是交付条件。
- 后续结构:显式 API 模型、前端构建与高频页面迁移、候选分页、任务持久化按垂直功能实施;不为 AppContext 或文件尺寸单独做全仓搬迁。
当前已实现运行缓存、关系筛选、wheel 资源、仓库外冒烟和分级健康检查;Windows 基础依赖安装通过。真实库只读对照七轮中位数:标签 195.5→25.5 ms、创作者 148.8→45.6 ms、女优 162.7→15.7 ms、厂牌 162.0→19.6 ms,返回 ID 与总数一致;这不是浏览器端延迟。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index e6cfe75ab..ce96eab5a 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -7,10 +7,18 @@
- 抓取入口的复用缺口与证据统一见 [抓取复用审计](SCRAPING_AUDIT.md) 和 [逐脚本 CSV](scraping-audit.csv);
跨用户安装、来源网络、Cookie GUI、最高可得画质与图像清单按 [ADR-0024](adr/0024-mark-manifest-not-bundled-bytes.md)。
- Instagram 的 Instaloader 4.15.3(MIT)、browser_cookie3 会话导入、tldextract 私有后缀判断均是待 POC
- 候选,本轮未新增依赖。Javinizer-Go、HTTPX、curl_cffi、Pillow 和现有候选缓存继续作为正式基础;
+ 私有后缀判断采用 tldextract 5.3.2(BSD-3-Clause、Python ≥3.10、平台无关),使用随包 PSL、
+ `suffix_list_urls=()`、`cache_dir=None`、`include_psl_private_domains=True`;106 kB wheel,依赖
+ requests、requests-file、filelock、idna;日本二级后缀与 GitHub Pages/Blogspot 租户 POC 通过。
+ Instaloader 4.15.3(MIT)匿名解析 Bambi/LINX 均为 ConnectionException;独立登录会话未取得,
+ 它和 browser_cookie3 均不进入正式依赖。Javinizer-Go、HTTPX、curl_cffi、Pillow 和现有候选缓存是正式基础;
各脚本的请求节拍应复用 `scripting.RateLimiter`/`HostLimiter`,不为同一职责再装一套框架。
+- 采集 GUI 复用 Preact island、CredentialStore、HTTPX、Pillow 和 BackgroundJob;
+ `jav_cover_fetch` 同时服务界面与 CLI。Peach 保留域内凭据、来源路由、预算、冷却、番号身份与
+ 高清替换策略。Cookie 文本由标准库 SimpleCookie/MozillaCookieJar 解析;不导入 pickle。
+ 实施范围与跨平台缺口见 [来源采集](SOURCING.md);POC 脱敏证据在本机 attic 的抓取复现目录。
+
- 删除失效链接与资源同步的执行阶段复用 `BackgroundJob.start_result` 保存终态回执;刷新只查状态,写入请求不自动重放,原有确认与检查结果过期门槛保持有效。
- 关注进度复用 Fieldset 与 Progress;完成时保留内容取数,按作者检查复用 `sources` 范围参数,报错作者复用现有身份解析。无新依赖;参考取证见 `reference-snapshots/vercel-geist-note-progress-switch-analytics.md`。
diff --git a/docs/SCRAPING_AUDIT.md b/docs/SCRAPING_AUDIT.md
index d5420e15d..04e06d4f9 100644
--- a/docs/SCRAPING_AUDIT.md
+++ b/docs/SCRAPING_AUDIT.md
@@ -1,8 +1,19 @@
# 抓取复用与复现审计
-核验日期:2026-09-05;代码基线:`349048f`。架构方案见 [ADR-0024](adr/0024-mark-manifest-not-bundled-bytes.md),逐入口结论见 [审计 CSV](scraping-audit.csv)。本次交付是文档与只读取证,不表示抓取服务、GUI 或依赖已升级。
+核验日期:2026-09-05;审计基线:`349048f`。架构方案见 [ADR-0024](adr/0024-mark-manifest-not-bundled-bytes.md),逐入口基线结论见 [审计 CSV](scraping-audit.csv)。下方问题列表是基线发现,实施状态以下节为准。
-## 范围与结论
+## 实施状态
+
+- 5 个内部重复入口已复用 RateLimiter/HostLimiter;图标下载使用共享 16 MiB 有界 transport,
+ 保留首页单次请求缓存和图像策略。官网探测及 page_cache 显式持有自建 client 的关闭所有权。
+- 私有后缀采用离线 tldextract 5.3.2,GitHub Pages/Blogspot 独立租户与日本域名 POC 通过。
+- `/scraping` 接入定点高清封面、来源网络和 FC2 Cookie 配置;完整下载重新核对实际尺寸,
+ 保留原图字节并拒绝低清覆盖。接口、凭据隔离与实际消费范围见 [来源采集](SOURCING.md)。
+- Instaloader 4.15.3 的 Bambi/LINX 匿名 POC 均为 ConnectionException;未取得独立登录会话,
+ 不将匿名失败解释为所有登录用户都失败,也不把库的接口存在解释为稳定成功。
+- 整体 ADR 仍有来源清单、完整批量 GUI、标准模式、子进程网络统一及跨用户/平台验收缺口。
+
+## 审计基线范围与结论
扫描 `scripts/harvest_*.py`、`fetch_*.py`、`scrape_*.py`,加上有来源请求的头像审计、厂牌本地化、Babepedia 匹配与链接重发现,共 **17 个业务入口**。同时核对共享 HTTP、页面缓存、图像候选缓存、Javinizer-Go 适配、关注连接器和凭据 GUI。发布检查、连通性验收、纯离线导入/安装脚本不计入业务抓取入口;这个分母不代表 Git 历史中的全部脚本或所有 provider 类。
diff --git a/docs/SOURCING.md b/docs/SOURCING.md
index bebe048b4..b17147699 100644
--- a/docs/SOURCING.md
+++ b/docs/SOURCING.md
@@ -1,5 +1,35 @@
# 身份、来源与标识采集
+## 本机采集入口
+
+「数据管理」→「采集来源与 Cookie 设置」(`/scraping`)提供官方高清封面定点抓取和来源连接设置。
+界面与 `scripts/fetch_jav_covers.py` 共用 `peach.jav_cover_fetch`;不需要把开发者的映射文件或
+Cookie 复制到新用户电脑。已有成功元数据快照优先,缺快照的公开来源可联网查询。
+
+- R18、DMM、Prestige、MGStage 的封面 HTTP 路径使用按来源的环境/应用直连/指定代理配置。
+ DMM 连接检查分别报告页面与高清 CDN;HTTPX 环境代理不等于系统 PAC,应用直连也不能排除 TUN。
+- FC2 的 Cookie 粘贴与 Netscape 文件导入复用 CredentialStore;仅保存当前来源域内未过期项目。
+ `fetch_fc2_metadata.py` 默认读取这份配置,`--cookies` 可显式指定文件。保存不代表登录会话有效。
+- GUI 封面任务每次只接受馆藏命中的一个番号,复用 BackgroundJob;最多 80 个请求、32 MiB,
+ 请求发出前检查 180 秒截止时间。只在完整图与探测尺寸相同、可完整解码且面积更大时原子替换。
+ 原始字节不降采样;成功边车记录原图与安装摘要,24 小时内摘要匹配则不重复下载。
+- 429 的 Retry-After 冷却落本机文件,新 transport 也遵守;失败不删除已有封面。
+ 程序重启不自动重放写入任务,未完成任务由用户重新发起。
+
+该配置目前覆盖封面 HTTP 与 FC2 CLI。Javinizer-Go 子进程、其它采集脚本与 curl_cffi 连接器
+仍使用各自配置;来源清单导出/首次同步、标准模式、浏览器会话导入和完整批量 GUI 尚待实施。
+Instagram 的 Instaloader 4.15.3 匿名 POC 对 Bambi、LINX 返回 ConnectionException;独立用户
+登录会话未取得,不能承诺自动发现全部高清头像。自动适配器不进入正式依赖。
+
+Windows 空数据预览的项目 CA HTTPS、合成 Cookie 保存/撤销、DMM 2184×1464 CDN 与界面产物
+摘要验证通过;这不是第二名真实用户、macOS 或全部地区网络的验收。测试步骤见
+[Windows 测试版](TESTING_DESKTOP.md),架构完整要求见 [ADR-0024](adr/0024-mark-manifest-not-bundled-bytes.md)。
+
+无元数据缓存的 ABW-232 POC 取得 1024×690,16 次请求、775899 字节。即时 r18 厂牌证据与
+本机快照使用同一来源路由,Prestige 与 MGS 都参加候选比较;原始图片没有派生降采样。
+
+## 采集判据
+
本文件保存「从外部站点取得身份与标识」这件事的判据细节:脚本分工、实测反例、判词含义和不能走的路。
`docs/HANDOFF.md` 只留一句话的边界并指到这里;采集本身的限流、续跑与流量预算见
`.claude/skills/peach-batch-jobs/SKILL.md`,参考产品证据的登记方式见 `.claude/skills/peach-reference-evidence/SKILL.md`。
diff --git a/docs/TESTING_DESKTOP.md b/docs/TESTING_DESKTOP.md
index f50433603..712bde3c6 100644
--- a/docs/TESTING_DESKTOP.md
+++ b/docs/TESTING_DESKTOP.md
@@ -15,6 +15,23 @@
- 端口被占用时,退出占用该端口的其他程序后重试;修改端口时界面会检查冲突。
- 测试包没有代码签名。如果 Windows 提示未识别应用,请核对下载来自本项目 Release,并与 `SHA256SUMS.txt` 对照后再决定是否运行。
+## 采集测试
+
+1. 完成媒体扫描后,进入「数据管理」→「采集来源与 Cookie 设置」。
+2. 高清来源可能需要代理。在对应来源选「指定代理」,填写该电脑可用的代理地址并保存;
+ 「环境代理」读取 Peach 启动环境,「应用直连」不使用应用代理,但仍可能经过系统隧道。
+3. 点击「检查已保存的连接」。DMM 分别检查页面与高清 CDN,图片检查会显示实际像素尺寸。
+4. 在「高清封面」填入馆藏番号,点击「抓取或升级封面」。任务只处理该番号;只有完整解码且
+ 像素面积更大的封面才替换,失败保留已有图片。相同成功结果在 24 小时内复用本机文件。
+5. FC2 CLI 用户可在同页粘贴 Cookie 请求头或导入 Netscape `.txt`。凭据保存于本机,
+ 「已保存」不表示会话有效;撤销后该来源的登录采集需重新提供 Cookie。
+
+当前测试入口覆盖官方高清封面与 FC2 凭据配置。FC2 元数据批量采集、Javinizer-Go 的工具安装和
+完整来源代理配置仍走各自 CLI;Instagram 自动头像、来源清单迁移、浏览器 Cookie 直接导入和
+跨用户登录态验收尚未完成。请勿把 Cookie、带签名图片网址、`secrets` 或完整账本发送给测试者。
+
+反馈时记录版本、操作系统、来源、连接方式、番号、状态与图片像素;不同电脑不共享 Cookie。
+
## 播放与更新
浏览器支持的 MP4 可以直接播放。转码、抽帧和缩略图需要 FFmpeg 与 ffprobe:安装后加入 PATH,或把两个程序放到数据目录下的 `tools\ffmpeg\bin`,退出并重新启动 Peach。
diff --git a/docs/scraping-audit.csv b/docs/scraping-audit.csv
index 89b7bf3ed..b920eaf73 100644
--- a/docs/scraping-audit.csv
+++ b/docs/scraping-audit.csv
@@ -1,18 +1,18 @@
script,classification,evidence,reuse_or_action,reproduction_gap
audit_performer_portraits.py,未发现明显重复,AvatarCandidateCache与Gfriends索引及Pillow,保留身份和质量策略,候选导出与GUI入口
-fetch_fc2_metadata.py,复现缺口,MozillaCookieJar及HTTPX已复用但仅CLI cookies,接入共用凭据和任务服务,GUI文件导入及网络与断点
-fetch_jav_covers.py,内部重复,HostLimitedTransport重复主机节拍,Javinizer高清映射已复用并保留Range及候选策略,统一HostLimiter默认主机与预算
-fetch_studio_avatar_candidates.py,内部重复,main自算monotonic节拍但unavatar及LogoCandidateCache已复用,复用RateLimiter且保留平台CDN与身份复核,公共服务可用性和确认handle
-harvest_agency_rosters.py,内部重复,脚本自有Site重复共享RateLimiter而minnano_av已复用,复用RateLimiter且保留成员关系与重名复核,来源身份映射与GUI编排
+fetch_fc2_metadata.py,复现缺口,HTTPX与MozillaCookieJar共用GUI凭据和来源网络,Cookie文件导入与撤销已接入,会话有效性与完整批量GUI待实施
+fetch_jav_covers.py,内部重复已收口,CLI与GUI共用jav_cover_fetch和HostLimiter,保留全候选Range并复核完整图片及像素升级,标准模式及跨用户实测待完成
+fetch_studio_avatar_candidates.py,内部重复已收口,RateLimiter与unavatar及LogoCandidateCache,保留平台CDN与身份复核,公共服务可用性和确认handle
+harvest_agency_rosters.py,内部重复已收口,RateLimiter与minnano_av,保留成员关系与重名复核,来源身份映射与GUI编排
harvest_directory_links.py,未发现明显重复,Site与social_links及站点名录策略,保留名录字段和匹配,PROXY_SOURCES需按用户配置
harvest_javdatabase_names.py,未发现明显重复,Site与番号到人物页链路,保留身份消歧,来源网络与缓存状态
harvest_javdb_cn_names.py,未发现明显重复,javdb与Site及OpenCC,保留现名和别名判据,网络冷却与GUI入口
harvest_mgstage_makers.py,未发现明显重复,Site和厂牌名录及复用图标判据,保留名录映射,网络与年龄门配置
-harvest_performer_links.py,内部重复,run自算monotonic节拍而minnano_av与social_links已复用,复用RateLimiter且保留唯一重定向身份判据,统一缓存和GUI入口
-harvest_social_avatars.py,外部复用缺口,Instagram仅链接且未登记成熟头像POC,优先验证Instaloader头像与会话接口,不能要求人工长期维护CDN直链
-harvest_studio_icons.py,内部重复,Fetcher自行实现请求节拍重试内存缓存,共用有界下载及缓存而保留判形策略,全量响应上限与最高画质选择
-harvest_studio_sites.py,生命周期缺口,HttpxTransport注入client后close不关闭client,修复调用方所有权再测池行为,断网和大量失败主机验证
+harvest_performer_links.py,内部重复已收口,RateLimiter与minnano_av及social_links,保留唯一重定向身份判据,统一缓存和GUI入口
+harvest_social_avatars.py,外部复用待验证,Instaloader4.15.3匿名Bambi与LINX均ConnectionException,独立登录会话POC尚未取得,不能要求人工长期维护CDN直链
+harvest_studio_icons.py,内部重复已收口,共享RateLimiter与HttpxTransport有界下载,保留首页缓存重试与判形策略,最高画质模式与统一来源配置待完成
+harvest_studio_sites.py,生命周期已修复,HttpxTransport显式拥有自建client,调用方关闭责任及异常重试已有隔离测试,大量失败主机现场验证待补
localize_studio_names.py,未发现明显重复,Site与精确番号厂牌证据,保留规范名候选,网络选项与复核GUI
match_babepedia_creators.py,未发现明显重复,HttpxTransport与档案标题身份判据,保留别名变体和人工确认,网络错误与候选GUI
-rediscover_entity_links.py,外部复用缺口,registrable把不同github.io租户判同站,验证含private suffix的PSL成熟实现,来源身份不可仅靠可注册域
+rediscover_entity_links.py,外部复用已接入,tldextract5.3.2离线PRIVATE租户POC通过,固定随包PSL且关闭启动联网更新,来源身份不可仅靠可注册域
scrape_codes.py,未发现明显重复,JavinizerGoProvider固定v1.5.1且逐来源JSON,保留字段候选及精确番号与健康,平台工具安装及统一来源配置
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 463dcf327..4070b0d78 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -57,9 +57,9 @@ export async function apiGet<T>(path: string, signal?: AbortSignal): Promise<T>
}
/** 带 JSON 请求体的写操作。失败时原响应体挂在 `ApiError.body` 上,字段级原因由调用方取。 */
-export async function apiSend<T>(path: string, body: unknown, method = 'POST'): Promise<T> {
+export async function apiSend<T>(path: string, body: unknown, method = 'POST', signal?: AbortSignal): Promise<T> {
const response = await fetch(path, {
- method,
+ method, ...(signal ? { signal } : {}),
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(body),
diff --git a/frontend/src/islands.ts b/frontend/src/islands.ts
index 14f970eba..0b41217f9 100644
--- a/frontend/src/islands.ts
+++ b/frontend/src/islands.ts
@@ -21,6 +21,8 @@ import type { ConfigurationData, ConfigurationProps } from './islands/configurat
import { QualityGoals, loadQualityGoals } from './islands/quality-goals';
import type { QualityGoalsProps } from './islands/quality-goals';
import type { QualityGoalsData } from './state/quality-goals';
+import { Scraping, loadScraping } from './islands/scraping';
+import type { ScrapingData, ScrapingProps } from './islands/scraping';
/* 跨岛共享状态的入口一起从这里出去。遗留层拿到的是一个 bundle,它有两种用法:
* `mountIsland` 挂一屏,`refreshStore` 告诉已经挂着的那屏「数据变了」。
@@ -38,6 +40,7 @@ export interface IslandState<D> {
/** 每个 island 的 props 与首屏数据类型。新增 island 时在这里登记,注册表随之要求实现。 */
export interface IslandContracts {
+ 'scraping': { props: ScrapingProps; data: ScrapingData };
'quality-goals': { props: QualityGoalsProps; data: QualityGoalsData };
configuration: { props: ConfigurationProps; data: ConfigurationData };
}
@@ -53,6 +56,7 @@ interface IslandDefinition<N extends IslandName> {
}
const REGISTRY: { [N in IslandName]: IslandDefinition<N> } = {
+ 'scraping': { load: loadScraping, component: Scraping },
'quality-goals': { load: loadQualityGoals, component: QualityGoals },
configuration: { load: loadConfiguration, component: Configuration },
};
diff --git a/frontend/src/islands/scraping.tsx b/frontend/src/islands/scraping.tsx
new file mode 100644
index 000000000..5240ebfee
--- /dev/null
+++ b/frontend/src/islands/scraping.tsx
@@ -0,0 +1,146 @@
+import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
+import { apiGet, apiSend, errorMessage } from '../api';
+import { noteHtml, fieldsetTitle, setActionBusy } from '@peach/legacy/ui';
+import type { IslandState } from '../islands';
+import { watchJob } from '../jobs';
+import type { JobState } from '../jobs';
+
+interface Source {
+ source: string; label: string; login: string; accepts_cookie: boolean;
+ network: string; proxy_saved: boolean; cookie_saved: boolean;
+}
+export interface ScrapingData { sources: Source[] }
+export interface ScrapingProps { toast(message: string): void }
+interface Check { label: string; ok: boolean; status?: number; message?: string; width?: number; height?: number }
+export const loadScraping = (_props: ScrapingProps, signal: AbortSignal) => apiGet<ScrapingData>('/api/scraping', signal);
+
+function SourceForm({ source, toast }: { source: Source } & ScrapingProps) {
+ const [saved, setSaved] = useState(source);
+ const [network, setNetwork] = useState(source.network);
+ const [proxy, setProxy] = useState('');
+ const [cookie, setCookie] = useState('');
+ const [cookieText, setCookieText] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
+ const [checks, setChecks] = useState<Check[]>([]);
+ const file = useRef<HTMLInputElement>(null);
+ const form = useRef<HTMLFormElement>(null);
+ useLayoutEffect(() => {
+ form.current?.querySelectorAll('button').forEach(button => setActionBusy(button, busy));
+ }, [busy]);
+ const lifetime = useRef(new AbortController());
+ useEffect(() => () => lifetime.current.abort(), []);
+ async function action(kind: 'save' | 'revoke' | 'check') {
+ if (busy) return;
+ setBusy(true); setError(''); setChecks([]);
+ try {
+ if (kind === 'check') {
+ const result = await apiSend<{ results: Check[] }>('/api/scraping/check', { source: source.source }, 'POST', lifetime.current.signal);
+ if (!lifetime.current.signal.aborted) setChecks(result.results);
+ } else {
+ const result = await apiSend<{ saved: Source }>('/api/scraping/settings', {
+ source: source.source, network, proxy, cookie, cookies_text: cookieText, revoke: kind === 'revoke',
+ }, 'POST', lifetime.current.signal);
+ if (!lifetime.current.signal.aborted) {
+ setSaved(result.saved); setProxy(''); setCookie(''); setCookieText('');
+ if (file.current) file.current.value = '';
+ toast(kind === 'revoke' ? 'Cookie 已撤销' : '来源设置已保存');
+ }
+ }
+ } catch (cause) {
+ if (!lifetime.current.signal.aborted) setError(errorMessage(cause));
+ } finally {
+ if (!lifetime.current.signal.aborted) setBusy(false);
+ }
+ }
+ return <section class="scraping-source">
+ <form ref={form} class="cleanupfieldset" data-geist-fieldset onSubmit={event => { event.preventDefault(); void action('save'); }}>
+ <div class="geist-fieldset-content scraping-fields">
+ <div dangerouslySetInnerHTML={{ __html: fieldsetTitle(`scraping-${source.source}`, source.label) }} />
+ <label>连接方式<select class="geist-input" value={network} disabled={busy} onChange={event => setNetwork(event.currentTarget.value)}>
+ <option value="environment">环境代理</option><option value="direct">应用直连</option><option value="proxy">指定代理</option>
+ </select></label>
+ {network === 'proxy' && <label>代理地址<input class="geist-input" type="password" autoComplete="off" value={proxy}
+ placeholder={saved.proxy_saved ? '已保存,留空保留' : 'http://127.0.0.1:7890'} disabled={busy}
+ onInput={event => setProxy(event.currentTarget.value)} /></label>}
+ {source.accepts_cookie && <>
+ <p><a href={source.login} target="_blank" rel="noopener noreferrer">打开官网登录</a> · {saved.cookie_saved ? 'Cookie 已保存,尚未验证会话' : '尚未提供 Cookie'}</p>
+ <label>Cookie 请求头<input class="geist-input" type="password" autoComplete="off" value={cookie} disabled={busy || !!cookieText}
+ onInput={event => setCookie(event.currentTarget.value)} /></label>
+ <label>Netscape Cookie 文件<input class="geist-input" ref={file} type="file" accept=".txt" disabled={busy || !!cookie}
+ onChange={async event => {
+ const selected = event.currentTarget.files?.[0];
+ if (!selected) { setCookieText(''); return; }
+ setCookieText('');
+ if (selected.size > 256 * 1024) { setError('Cookie 文本超过 256 KiB'); event.currentTarget.value = ''; return; }
+ setBusy(true);
+ try { const text = await selected.text(); if (!lifetime.current.signal.aborted) setCookieText(text); }
+ catch { if (!lifetime.current.signal.aborted) setError('Cookie 文件未读取,请重新选择'); }
+ finally { if (!lifetime.current.signal.aborted) setBusy(false); }
+ }} /></label>
+ </>}
+ {error && <div role="alert" dangerouslySetInnerHTML={{ __html: noteHtml(error, { variant: 'error' }) }} />}
+ {checks.map(check => <p role="status" key={check.label}>{check.label}:{check.ok ? '可连接' : '未取得'}
+ {check.width ? ` · ${check.width} × ${check.height}` : ''}{check.message ? ` · ${check.message}` : ''}</p>)}
+ </div>
+ <footer class="geist-fieldset-footer" data-geist-fieldset-footer>
+ <button class="geist-button primary" type="submit">保存</button>
+ <button class="geist-button" type="button" onClick={() => void action('check')}>检查已保存的连接</button>
+ {source.accepts_cookie && saved.cookie_saved && <button class="geist-button" type="button" onClick={() => void action('revoke')}>撤销 Cookie</button>}
+ </footer>
+ </form>
+ </section>;
+}
+
+export function Scraping({ data, error, toast }: ScrapingProps & IslandState<ScrapingData>) {
+ const [code, setCode] = useState('');
+ const [running, setRunning] = useState(false);
+ const [problem, setProblem] = useState('');
+ const submit = useRef<HTMLButtonElement>(null);
+ useLayoutEffect(() => setActionBusy(submit.current, running), [running]);
+ const lifetime = useRef(new AbortController());
+ const generation = useRef(0);
+ async function followJob(resume = false) {
+ const epoch = ++generation.current;
+ await watchJob<JobState & { result?: string; width?: number; height?: number }>({
+ read: signal => apiGet('/api/scraping/cover', signal),
+ active: () => !lifetime.current.signal.aborted && epoch === generation.current,
+ render: state => {
+ setRunning(state.status === 'running');
+ if (state.status === 'running') resume = false;
+ if (state.status === 'failed' && !resume) setProblem(state.error || '采集未取得');
+ if (state.status === 'complete' && !resume) toast(state.result || '封面采集完成');
+ },
+ disconnected: () => setProblem('连接中断,正在重新读取后台进度'),
+ });
+ }
+ useEffect(() => { void followJob(true); return () => lifetime.current.abort(); }, []);
+ async function fetchCover() {
+ if (running) return;
+ generation.current++;
+ setRunning(true); setProblem('');
+ try {
+ await apiSend('/api/scraping/cover', { code }, 'POST', lifetime.current.signal);
+ await followJob();
+ } catch (cause) {
+ if (!lifetime.current.signal.aborted) { setRunning(false); setProblem(errorMessage(cause)); }
+ }
+ }
+ if (error) return <div role="alert" dangerouslySetInnerHTML={{ __html: noteHtml(error, { variant: 'error' }) }} />;
+ return <div class="scraping-page">
+ <p>高清来源可能需要代理。环境代理读取服务进程的代理环境变量;应用直连仍可能经过系统隧道。</p>
+ <p>封面采集保留最高可得画质,失败保留已有图片。连接检查不验证登录会话。</p>
+ <section class="cleanupfieldset scraping-source" data-geist-fieldset>
+ <div class="geist-fieldset-content scraping-fields">
+ <div dangerouslySetInnerHTML={{ __html: fieldsetTitle('scraping-cover', '高清封面') }} />
+ <form onSubmit={event => { event.preventDefault(); void fetchCover(); }}>
+ <label>馆藏番号<input class="geist-input" required value={code} disabled={running} placeholder="ABW-232"
+ onInput={event => setCode(event.currentTarget.value)} /></label>
+ <button ref={submit} class="geist-button primary" type="submit">抓取或升级封面</button>
+ </form>
+ {problem && <div role="alert" dangerouslySetInnerHTML={{ __html: noteHtml(problem, { variant: 'error' }) }} />}
+ </div>
+ </section>
+ {data?.sources.map(source => <SourceForm key={source.source} source={source} toast={toast} />)}
+ </div>;
+}
diff --git a/frontend/test/islands.test.ts b/frontend/test/islands.test.ts
index bd21b3982..66d71baf6 100644
--- a/frontend/test/islands.test.ts
+++ b/frontend/test/islands.test.ts
@@ -22,7 +22,7 @@ afterEach(() => {
describe('island 注册表', () => {
it('登记的名字就是遗留路由能挂载的名字', () => {
- expect(islandNames()).toEqual(['quality-goals', 'configuration']);
+ expect(islandNames()).toEqual(['scraping', 'quality-goals', 'configuration']);
});
it('未注册的名字立刻失败,不是静默什么都不画', async () => {
diff --git a/frontend/test/scraping.test.tsx b/frontend/test/scraping.test.tsx
new file mode 100644
index 000000000..69701bc6c
--- /dev/null
+++ b/frontend/test/scraping.test.tsx
@@ -0,0 +1,46 @@
+import { h, render } from 'preact';
+import { act } from 'preact/test-utils';
+import { afterEach, expect, it, vi } from 'vitest';
+import { Scraping } from '../src/islands/scraping';
+
+const source = { source: 'fc2cmadb', label: 'FC2 CMADB', login: 'https://fc2cmadb.com/',
+ accepts_cookie: true, network: 'environment', cookie_saved: false, proxy_saved: false };
+let host: HTMLDivElement;
+afterEach(() => { if (host) render(null, host); document.body.innerHTML = ''; vi.unstubAllGlobals(); });
+
+it('保存后清空秘密输入,状态只表示保存且撤销可操作', async () => {
+ const requests: { path: string; body: unknown }[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (path: string, init?: RequestInit) => {
+ if (init?.method === 'POST') {
+ requests.push({ path, body: JSON.parse(String(init.body)) });
+ return { ok: true, json: async () => ({ saved: { ...source, cookie_saved: true } }) };
+ }
+ return { ok: true, json: async () => ({ status: 'idle' }) };
+ }));
+ host = document.createElement('div'); document.body.append(host);
+ const toast = vi.fn();
+ await act(async () => render(h(Scraping, { data: { sources: [source] }, error: '', toast }), host));
+ const input = host.querySelector<HTMLInputElement>('input[type=password]')!;
+ await act(async () => { input.value = 'session=fixture'; input.dispatchEvent(new Event('input', { bubbles: true })); });
+ await act(async () => {
+ input.closest('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(requests[0]).toEqual({ path: '/api/scraping/settings', body: {
+ source: 'fc2cmadb', network: 'environment', proxy: '', cookie: 'session=fixture', cookies_text: '', revoke: false,
+ } });
+ expect(host.querySelector<HTMLInputElement>('input[type=password]')!.value).toBe('');
+ expect(host.textContent).toContain('尚未验证会话');
+ expect(host.textContent).toContain('撤销 Cookie');
+ expect(toast).toHaveBeenCalledWith('来源设置已保存');
+});
+
+it('已有后台结果不在首屏冒充新结果', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ status: 'complete', result: 'old result' }) })));
+ host = document.createElement('div'); document.body.append(host);
+ const toast = vi.fn();
+ await act(async () => render(h(Scraping, { data: { sources: [] }, error: '', toast }), host));
+ expect(toast).not.toHaveBeenCalled();
+ expect(host.textContent).not.toContain('old result');
+ expect(host.querySelector('input[required]')).not.toBeNull();
+});
diff --git a/pyproject.toml b/pyproject.toml
index a039a3d51..f88524cc7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,6 +27,7 @@ classifiers = [
"Topic :: Multimedia :: Video",
]
dependencies = [
+ "tldextract==5.3.2",
"APScheduler==3.11.3",
"beautifulsoup4==4.15.0",
"browserexport==0.4.4",
diff --git a/scripts/fetch_fc2_metadata.py b/scripts/fetch_fc2_metadata.py
index a5f830602..27f327c5d 100644
--- a/scripts/fetch_fc2_metadata.py
+++ b/scripts/fetch_fc2_metadata.py
@@ -51,6 +51,8 @@ if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from peach.catalog_rules import normalise_code_key
+from peach.config import SECRETS_DIR
+from peach.scraping_access import client_for, cookie_jar, values_for
from peach.genre_taxonomy import map_genres
from peach.review_csv import read_rows, write_rows
from peach.scripting import USER_AGENT, open_readonly
@@ -90,7 +92,7 @@ def high_resolution_cover_url(url: str) -> str:
def load_cookies(path: Path) -> http.cookiejar.MozillaCookieJar:
jar = http.cookiejar.MozillaCookieJar(str(path))
- jar.load(ignore_discard=True, ignore_expires=True)
+ jar.load(ignore_discard=True, ignore_expires=False)
return jar
@@ -435,19 +437,19 @@ def run(args: argparse.Namespace) -> int:
write_rows(args.metadata_log, METADATA_FIELDS, candidates)
print(f"完成:{len(candidates)} 个 FC2 元数据字段候选 -> {args.metadata_log}")
return 0
- if args.cookies is None:
- raise SystemExit("联网抓取必须传 --cookies;离线重建请用 --rebuild-metadata-only")
+ jar = (load_cookies(args.cookies) if args.cookies else
+ cookie_jar(values_for(SECRETS_DIR, "fc2cmadb"), "fc2cmadb"))
+ if not list(jar):
+ raise SystemExit("请在 /scraping 提供 FC2 Cookie,或传 --cookies;离线重建用 --rebuild-metadata-only")
todo = pending(args.db, args.limit)
owned = {video_id for _, video_id in todo}
- jar = load_cookies(args.cookies)
rows: list[dict] = []
collected: dict = {}
stats = {"hit": 0, "miss": 0}
args.raw.parent.mkdir(parents=True, exist_ok=True)
raw_log = args.raw.open("w", encoding="utf-8")
print(f"待抓 {len(todo)} 个 FC2 作品", flush=True)
- with httpx.Client(cookies=jar, headers={"User-Agent": USER_AGENT},
- follow_redirects=True) as client:
+ with client_for(SECRETS_DIR, "fc2cmadb", cookies=jar) as client:
for index, (code, video_id) in enumerate(todo, 1):
try:
props = fetch_article(client, video_id)
diff --git a/scripts/fetch_jav_covers.py b/scripts/fetch_jav_covers.py
index a2120b0f1..7048f6713 100644
--- a/scripts/fetch_jav_covers.py
+++ b/scripts/fetch_jav_covers.py
@@ -1,972 +1,10 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-r"""按番号抓官方封套:把所有候选量一遍,留像素最多的那张。
-
-**不用固定优先级链**,因为实测证明没有哪个源恒定最好:
-
- GYAN-017 awsimgsrc 2184x1464 有数字版,DMM 自己的高清路径最好
- ABW-232 duga 1000x674 没有数字版,awsimgsrc 四种写法全 404
- PPT-018 pics.dmm 800x539 只有低清
-
-同一个 DMM 有两条路径,差 7.4 倍像素——之前一直用的是低清那条:
-
- 低清 pics.dmm.co.jp/mono/movie/adult/<cid>/<cid>pl.jpg 800x539
- 高清 awsimgsrc.dmm.co.jp/pics_dig/digital/video/<cid>/<cid>pl.jpg 2184x1464
-
-候选不是固定优先级,而是汇总后量像素:
-
-- 已保存的 Javinizer-Go 原始证据,离线复用 cover URL 与 content_id;
-- r18.dev 官方 DMM jacket(本地没有成功快照时才联网补);
-- DMM 新旧 awsimgsrc CDN 的 digital/video、digital/amateur、mono/movie 路径;
-- 有 Prestige 厂牌证据时,直连 Prestige API 与 MGS EnlargeImage;
-- 上轮成功日志里的原 URL,保住已经发现但当前无法重新检索的 DUGA 等官方图。
-
-AVBase 已返回 Cloudflare 验证页,不再进入批量流程,也不尝试绕过。DUGA 批量搜索 API
-需要代理店应用 ID,未配置前只复用成功日志中已经取得的精确图片 URL。
-
-两条番号改写规则,都由实测得出:
-
-- cid 数字段必须补到 5 位。`waaa415` 404,`waaa00415` 命中 2184x1468。
-- 素人系要去掉三位厂牌前缀。`278GYAN-017` 查不到,`GYAN-017` 能查到。
-
-为省流量,先用 Range 只取前 64 KiB 量尺寸,只有胜出的那张才整张下载。
-
-存原图不裁:4:3 与 16:9 两种版式在界面上靠 `object-fit` / `object-position` 取景,
-切版式零成本也不重新下载。官方那张独立正封 `ps.jpg` 只有 147x200,比裁出来的还小。
-"""
-from __future__ import annotations
-
-import argparse
-import io
-import json
-import re
-import time
-import urllib.parse
+"""按番号抓取最高可得官方封套。"""
import sys
-from dataclasses import dataclass
-from html.parser import HTMLParser
from pathlib import Path
-from urllib.parse import urlparse
-
-import httpx
-from PIL import Image, UnidentifiedImageError
-
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
-SRC_DIR = PROJECT_ROOT / "src"
-if str(SRC_DIR) not in sys.path:
- sys.path.insert(0, str(SRC_DIR))
-
-from peach.review_csv import ENCODING, read_rows, write_rows
-from peach.scripting import USER_AGENT, open_readonly
-from peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIR
-from peach.http import HttpRequest, HttpTransport, HttpxTransport
-from peach.jobs import DiskGuard, JobPolicyError
-from peach.platform import system_volume
-from peach.catalog_rules import (
- code_letter_stem,
- is_amateur_code,
- is_jav_code,
- normalise_code_key,
-)
-
-AWS_LEGACY_DIGITAL = (
- "https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/{cid}/{cid}pl.jpg"
-)
-AWS_MODERN = "https://awsimgsrc.dmm.com/dig/{kind}/{cid}/{cid}pl.jpg"
-AWS_LEGACY = "https://awsimgsrc.dmm.co.jp/pics_dig/{kind}/{cid}/{cid}pl.jpg"
-R18_DETAIL = "https://r18.dev/videos/vod/movies/detail/-/dvd_id={code}/json"
-MGS_DETAIL = "https://www.mgstage.com/product/product_detail/{code}/"
-PRESTIGE_SEARCH = "https://www.prestige-av.com/api/search"
-PRESTIGE_PRODUCT = "https://www.prestige-av.com/api/product/{uuid}"
-PRESTIGE_MEDIA = "https://www.prestige-av.com/api/media/{path}"
-DEFAULT_METADATA_ROOT = SOURCES_DIR / "metadata" / "javinizer-go"
-DEFAULT_FC2_METADATA_LOG = GENERATED_DIR / "fc2-candidate-log.csv"
-
-#: 低于这个宽度的是缩略图或占位图,不当封套。实测最低的正片封套是 800 宽。
-MIN_WIDTH = 700
-#: 量尺寸只需要 JPEG 头部,别把整张 1 MB 的图拉下来。
-PROBE_BYTES = 64 * 1024
-# 瞬时 TLS EOF / 连接重置不能落成“官方没有封面”。按项目外网退避规则重试,
-# 只有 2/4/6/8 秒四次重试全部失败后,才把网络异常交给逐条日志记录。
-NETWORK_RETRY_DELAYS = (2, 4, 6, 8)
-#: 页面与上游证据里可能混着剧照与缩略图,按文件名排除。
-THUMBNAIL = re.compile(r"(thumb|small|icon|/ts/|-s\d|_s\.)", re.I)
-FC2_HIRES = re.compile(r"https://contents-thumbnail\d*\.fc2\.com/w(?:7\d\d|[89]\d\d|\d{4,})/", re.I)
-IMAGE_URL = re.compile(r"https?://[^\"'\\ )]+?\.(?:jpg|jpeg|png|webp)")
-
-
-@dataclass(frozen=True)
-class Candidate:
- source: str
- url: str
- referer: str = "https://www.dmm.co.jp/"
-
-
-@dataclass(frozen=True)
-class MetadataEvidence:
- candidates: tuple[Candidate, ...] = ()
- makers: frozenset[str] = frozenset()
- sources: frozenset[str] = frozenset()
-
-
-class Unavailable(RuntimeError):
- pass
-
-
-class HostLimitedTransport:
- """把请求间隔按主机分别计算;不同官方站点互不阻塞。"""
-
- def __init__(self, inner: HttpxTransport, interval: float, *,
- clock=time.monotonic, sleeper=time.sleep) -> None:
- self.inner = inner
- self.interval = max(0.0, interval)
- self.clock = clock
- self.sleeper = sleeper
- self.next_request: dict[str, float] = {}
-
- def __call__(self, request: HttpRequest, timeout: float, limit: int):
- host = urlparse(request.url).netloc.lower()
- now = self.clock()
- wait = self.next_request.get(host, now) - now
- if wait > 0:
- self.sleeper(wait)
- now = self.clock()
- self.next_request[host] = now + self.interval
- return self.inner(request, timeout, limit)
-
- def renew(self) -> None:
- self.inner.close()
- self.inner = HttpxTransport()
-
- def close(self) -> None:
- self.inner.close()
-
-
-class _MGSDetailParser(HTMLParser):
- """只读取 MGS 的放大图链接;列表缩略图和剧照不进入候选。"""
-
- def __init__(self) -> None:
- super().__init__(convert_charrefs=True)
- self.urls: list[str] = []
-
- def handle_starttag(self, tag: str,
- attrs: list[tuple[str, str | None]]) -> None:
- values = dict(attrs)
- url = None
- if tag.lower() == "a" and values.get("id") == "EnlargeImage":
- url = values.get("href")
- elif tag.lower() == "a" and "link_magnify" in (values.get("class") or "").split():
- url = values.get("href")
- elif tag.lower() == "img" and any(
- token in (values.get("src") or "").lower()
- for token in ("jacket", "cover")):
- url = values.get("src") or values.get("data-src")
- if url:
- url = url.replace("ps.", "pl.", 1)
- if url and (IMAGE_URL.fullmatch(url)
- or re.search(r"\.(?:jpg|jpeg|png|webp)(?:\?.*)?$", url, re.I)):
- self.urls.append(url)
-
-
-def _fetch(transport: HttpTransport, url: str, *, referer: str,
- limit: int, ranged: bool = False,
- extra_headers: dict[str, str] | None = None) -> bytes:
- headers = {"User-Agent": USER_AGENT, "Referer": referer,
- "Accept-Language": "ja,en;q=0.9"}
- if extra_headers:
- headers.update(extra_headers)
- if ranged:
- headers["Range"] = f"bytes=0-{PROBE_BYTES - 1}"
- request = HttpRequest("GET", url, headers)
- for attempt in range(len(NETWORK_RETRY_DELAYS) + 1):
- try:
- response = transport(request, 30, limit)
- break
- except httpx.TransportError:
- if attempt == len(NETWORK_RETRY_DELAYS):
- raise
- time.sleep(NETWORK_RETRY_DELAYS[attempt])
- if response.status not in (200, 206):
- raise Unavailable(f"HTTP {response.status}")
- return response.body
-
-
-def code_variants(code: str) -> list[str]:
- """素人系番号带三位厂牌前缀,去掉才查得到:`278GYAN-017` -> `GYAN-017`。"""
- value = normalise_code_key(code)
- out = [value]
- stripped = re.sub(r"^\d{3}(?=[A-Z])", "", value)
- if stripped != value:
- out.append(stripped)
- return out
-
-
-def cid_variants(content_id: str) -> list[str]:
- """数字段补到 5 位是必须的;带厂牌数字前缀的多半没有数字版,但仍试一次。"""
- cid = (content_id or "").strip().lower()
- if not cid:
- return []
- out = [cid]
- shape = re.match(r"^(\d{2,4})?([a-z]+)(\d+)$", cid)
- if shape:
- letters, digits = shape.group(2), shape.group(3)
- out.append(f"{letters}{int(digits):05d}")
- out.append(f"{letters}{digits}")
- seen: set[str] = set()
- return [c for c in out if not (c in seen or seen.add(c))]
-
-
-def _referer_for(url: str) -> str:
- host = urlparse(url).netloc.lower()
- if "mgstage.com" in host:
- return "https://www.mgstage.com/"
- if "prestige-av.com" in host:
- return "https://www.prestige-av.com/"
- if "duga.jp" in host:
- return "https://duga.jp/"
- return "https://www.dmm.co.jp/"
-
-
-def candidate_for(url: str) -> Candidate:
- return Candidate(urlparse(url).netloc.lower(), url, _referer_for(url))
-
-
-def fc2_cover_candidates(path: Path | None) -> dict[str, Candidate]:
- """Reuse FC2CMADB article evidence, upgrading its listing thumb to measured w1200."""
- if path is None or not path.is_file():
- return {}
- found = {}
- for row in read_rows(path):
- url = re.sub(r"(/w)\d+(/)", r"\g<1>1200\2", str(row.get("cover_url") or ""), count=1)
- code = normalise_code_key(str(row.get("code") or ""))
- if (row.get("result") == "取得" and not row.get("is_collection")
- and code.startswith("FC2-PPV-") and IMAGE_URL.fullmatch(url)):
- found[code] = Candidate(urlparse(url).netloc.lower(), url, "https://fc2cmadb.com/")
- return found
-
-
-def _unique_candidates(candidates: list[Candidate]) -> list[Candidate]:
- seen: set[str] = set()
- return [candidate for candidate in candidates
- if candidate.url and not (candidate.url in seen or seen.add(candidate.url))]
-
-
-def dmm_cdn_images(url: str) -> list[Candidate]:
- """按 Javinizer-Go 当前已验证映射生成 DMM 新旧 CDN 候选。
-
- 主机名和路径不能当清晰度:同一 CID 的 legacy、modern、原始 URL 都要量尺寸。
- """
- clean = (url or "").split("?", 1)[0]
- parsed = urlparse(clean)
- match = re.search(
- r"/(?:pics_dig/|dig/)?(?P<kind>digital/(?:video|amateur)|mono/movie)"
- r"(?:/adult)?/(?P<cid>[^/]+)/",
- parsed.path,
- re.I,
- )
- candidates = [candidate_for(clean)] if IMAGE_URL.fullmatch(clean) else []
- if not match:
- return candidates
- kind = match.group("kind").lower()
- cid = match.group("cid").lower()
- candidates.extend([
- candidate_for(AWS_MODERN.format(kind=kind, cid=cid)),
- candidate_for(AWS_LEGACY.format(kind=kind, cid=cid)),
- ])
- return _unique_candidates(candidates)
-
-
-def content_id_images(content_id: str) -> list[Candidate]:
- candidates: list[Candidate] = []
- for cid in cid_variants(content_id):
- candidates.extend([
- candidate_for(AWS_MODERN.format(kind="digital/video", cid=cid)),
- candidate_for(AWS_LEGACY_DIGITAL.format(cid=cid)),
- ])
- return _unique_candidates(candidates)
-
-
-def cached_metadata(metadata_root: Path | None, code: str) -> MetadataEvidence:
- """复用已落盘的 Javinizer 原始快照,不把网络缓存伪装成实时查询。"""
- if metadata_root is None:
- return MetadataEvidence()
- candidates: list[Candidate] = []
- makers: set[str] = set()
- sources: set[str] = set()
- for variant in code_variants(code):
- folder = metadata_root / variant
- if not folder.is_dir():
- continue
- for path in sorted(folder.glob("*.json")):
- try:
- wrapper = json.loads(path.read_text(encoding=ENCODING))
- except (OSError, ValueError):
- continue
- result = wrapper.get("result")
- if not isinstance(result, dict):
- continue
- source = str(result.get("source") or wrapper.get("source") or path.stem)
- sources.add(source.lower())
- for value in (result.get("maker"), result.get("label")):
- if isinstance(value, str) and value.strip():
- makers.add(value.strip().lower())
- cover_url = result.get("cover_url")
- if isinstance(cover_url, str) and IMAGE_URL.fullmatch(cover_url.strip()):
- candidates.extend(dmm_cdn_images(cover_url.strip()))
- candidates.extend(content_id_images(str(result.get("content_id") or "")))
- return MetadataEvidence(
- tuple(_unique_candidates(candidates)), frozenset(makers), frozenset(sources),
- )
-
-
-def logged_success_evidence(
- rows: list[dict], code: str,
- ) -> tuple[Candidate, tuple[int, int]] | None:
- """复用历史精确 URL 与已量尺寸;DUGA 等无需重复探同一张图。"""
- for row in reversed(rows):
- if (normalise_code_key(str(row.get("code") or "")) == code
- and row.get("result") == "取得"
- and isinstance(row.get("url"), str)
- and IMAGE_URL.fullmatch(str(row["url"]))):
- try:
- size = (int(row.get("width") or 0), int(row.get("height") or 0))
- except (TypeError, ValueError):
- size = (0, 0)
- return candidate_for(str(row["url"])), size
- return None
-
-
-def logged_success_candidate(rows: list[dict], code: str) -> Candidate | None:
- """兼容只需要历史 URL 的调用方。"""
- evidence = logged_success_evidence(rows, code)
- return evidence[0] if evidence is not None else None
-
-
-#: DMM 的 content_id 一定带番号字母段:`ABW-232` -> `118abw232`、
-#: `MGT-164` -> `h_1711mgt00164`。
-_DMM_CID = re.compile(
- r"/(?:pics_dig/|dig/)?(?:digital/(?:video|amateur)|mono/movie)"
- r"(?:/adult)?/(?P<cid>[^/]+)/",
- re.I,
-)
-
-
-def is_cross_product_cover(code: str, url: str) -> bool:
- """这个 URL 指向的是另一部片的封套。
-
- 素人系番号在 avbase 上会连到 DVD 合集:`259LUXU-1475` 的页面主图取到的是
- `SNG-021` 的封套(`118sng021`)。内容是同一段,封面却不是这部片的——大图
- 模式的人脸定位、番号搜索和「这张图是谁」全都跟着错位。
-
- avbase 抓取已在 65fd95f 删掉,这批 URL 却靠「复用上一轮成功记录」一路带到
- 今天:复用只看 result 是不是「取得」,不看它和番号是否对得上,于是错误封面
- 再也没有机会被重探。判据落在 URL 上而不是抓取路径上,正是因为下一个引入
- 错图的来源不会用同一个函数。
- """
- stem = code_letter_stem(code)
- match = _DMM_CID.search(urlparse(url or "").path)
- if not stem or match is None:
- return False
- return stem not in match.group("cid").lower()
-
-
-def _is_prestige(evidence: MetadataEvidence) -> bool:
- return any("prestige" in value or "プレステージ" in value
- for value in evidence.makers)
-
-
-def r18_images(transport: HttpTransport, code: str) -> list[Candidate]:
- """读取 r18 返回的官方封套,并保留旧数字版高清 URL 探测。
-
- `content_id` 不是稳定的数字版路径。Prestige 的 ABW 系列会返回
- `118abw232`,对应 `pics.dmm.co.jp/mono/.../118abw232pl.jpg`;把它补零后
- 拼到 `awsimgsrc.../digital/video` 只会得到 404。r18 已在
- `images.jacket_image` 给出官方原图 URL,必须优先把这个证据加入候选。
- """
- for variant in code_variants(code):
- try:
- payload = json.loads(_fetch(
- transport, R18_DETAIL.format(code=urllib.parse.quote(variant)),
- referer="https://r18.dev/", limit=2 * 1024 * 1024,
- ).decode("utf-8", "ignore"))
- except (Unavailable, ValueError, httpx.TransportError):
- continue
- found: list[Candidate] = []
- jacket = ((payload.get("images") or {}).get("jacket_image") or {})
- if isinstance(jacket, dict):
- for raw_url in jacket.values():
- url = raw_url.strip() if isinstance(raw_url, str) else ""
- if url and IMAGE_URL.fullmatch(url) and not THUMBNAIL.search(url):
- found.extend(dmm_cdn_images(url))
- cid = str(payload.get("content_id") or "")
- found.extend(content_id_images(cid))
- return _unique_candidates(found)
- return []
-
-
-def mgstage_images(transport: HttpTransport, code: str) -> list[Candidate]:
- """直取 MGS 商品页 EnlargeImage;年龄确认只用公开 cookie,不绕挑战。"""
- for variant in code_variants(code):
- try:
- page = _fetch(
- transport,
- MGS_DETAIL.format(code=urllib.parse.quote(variant)),
- referer="https://www.mgstage.com/",
- limit=4 * 1024 * 1024,
- extra_headers={"Cookie": "adc=1"},
- ).decode("utf-8", "ignore")
- except (Unavailable, httpx.TransportError):
- continue
- parser = _MGSDetailParser()
- parser.feed(page)
- found: list[Candidate] = []
- for url in parser.urls:
- absolute = urllib.parse.urljoin("https://www.mgstage.com/", url)
- if THUMBNAIL.search(absolute):
- continue
- found.append(candidate_for(absolute))
- if found:
- return _unique_candidates(found)
- return []
-
-
-def prestige_images(transport: HttpTransport, code: str) -> list[Candidate]:
- """按 MDCX 固定 revision 的公开 API 模型直取 Prestige packageImage。"""
- query = urllib.parse.urlencode({
- "isEnabledQuery": "true",
- "searchText": code,
- "isEnableAggregation": "false",
- "release": "false",
- "reservation": "false",
- "soldOut": "false",
- "from": 0,
- "aggregationTermsSize": 0,
- "size": 20,
- })
- try:
- payload = json.loads(_fetch(
- transport, f"{PRESTIGE_SEARCH}?{query}",
- referer="https://www.prestige-av.com/", limit=4 * 1024 * 1024,
- ).decode("utf-8", "ignore"))
- except (Unavailable, ValueError, httpx.TransportError):
- return []
- hits = (((payload.get("hits") or {}).get("hits")) or [])
- exact: list[str] = []
- fallback: list[str] = []
- for hit in hits:
- source = hit.get("_source") if isinstance(hit, dict) else None
- if not isinstance(source, dict):
- continue
- item_id = normalise_code_key(str(source.get("deliveryItemId") or ""))
- uuid = str(source.get("productUuid") or "").strip()
- if not uuid:
- continue
- if item_id == normalise_code_key(code):
- exact.append(uuid)
- elif str(source.get("deliveryItemId") or "").upper().endswith(code.upper()):
- fallback.append(uuid)
- uuids = list(dict.fromkeys(exact or fallback))
- for uuid in uuids:
- try:
- product = json.loads(_fetch(
- transport, PRESTIGE_PRODUCT.format(uuid=urllib.parse.quote(uuid)),
- referer="https://www.prestige-av.com/", limit=4 * 1024 * 1024,
- ).decode("utf-8", "ignore"))
- except (Unavailable, ValueError, httpx.TransportError):
- continue
- package = product.get("packageImage") or {}
- path = package.get("path") if isinstance(package, dict) else ""
- if isinstance(path, str) and path.strip():
- url = PRESTIGE_MEDIA.format(path=path.strip().lstrip("/"))
- if IMAGE_URL.fullmatch(url):
- return [candidate_for(url)]
- return []
-
-
-def prestige_group_images(transport: HttpTransport, code: str) -> list[Candidate]:
- """Prestige 官方 API 命中后不再等待较小的 MGS 图;未命中才回退 MGS。"""
- official = prestige_images(transport, code)
- return official if official else mgstage_images(transport, code)
-
-
-def probe_size(transport: HttpTransport, candidate: Candidate) -> tuple[int, int]:
- head = _fetch(transport, candidate.url, referer=candidate.referer,
- limit=PROBE_BYTES * 2, ranged=True)
- return Image.open(io.BytesIO(head)).size
-
-
-def best_cover(transport: HttpTransport, code: str, delay: float, *,
- metadata_root: Path | None = None,
- prior_candidates: tuple[Candidate, ...] = (),
- known_sizes: dict[str, tuple[int, int]] | None = None,
- minimum_pixels: int = 0,
- ) -> tuple[Candidate, tuple[int, int], bytes]:
- # 来源一律记主机名。缓存、构造路径和官方页常指向同一个主机,记成多个名字
- # 会让覆盖率统计凭空多出「渠道」。
- evidence = cached_metadata(metadata_root, code)
- candidates = list(prior_candidates) + list(evidence.candidates)
- is_fc2 = code.upper().startswith("FC2-PPV-")
- # 有成功快照时不重复打 r18;失败快照不算证据,仍允许联网刷新。
- if not is_fc2 and "r18dev" not in evidence.sources:
- candidates += r18_images(transport, code)
- time.sleep(delay)
- # MGS 与 Prestige 都是 Prestige 集团的官方供给面。只在本地厂牌证据命中时
- # 查询,避免把全库 960 个番号无差别打到两个站点。
- if not is_fc2 and _is_prestige(evidence):
- candidates += prestige_group_images(transport, code)
- time.sleep(delay)
- # 素人系番号按形状就能确定发行面是 MGS,不必先有元数据。等元数据的旧写法让
- # 259LUXU / 300MIUM / 428SUKE 这批番号一次也没问过 MGS——而 MGS 一直有图。
- elif not is_fc2 and (is_amateur_code(code) or "mgstage" in evidence.sources):
- candidates += mgstage_images(transport, code)
- time.sleep(delay)
- candidates = _unique_candidates([
- candidate for candidate in candidates
- if (not THUMBNAIL.search(candidate.url) or FC2_HIRES.match(candidate.url))
- and not is_cross_product_cover(code, candidate.url)
- ])
- # 升级模式已在成功日志中量过的精确 URL,若像素不大于当前本地图,就不再
- # 发 Range 请求。其他 URL 和尺寸未知的候选仍完整探测,不改变择优语义。
- known_sizes = known_sizes or {}
- candidates = [
- candidate for candidate in candidates
- if candidate.url not in known_sizes
- or known_sizes[candidate.url][0] * known_sizes[candidate.url][1]
- > minimum_pixels
- ]
- if not candidates:
- raise Unavailable("所有渠道都没有候选")
-
- measured: list[tuple[int, Candidate, tuple[int, int]]] = []
- for candidate in candidates:
- try:
- width, height = probe_size(transport, candidate)
- except (Unavailable, UnidentifiedImageError, OSError, httpx.TransportError):
- continue
- finally:
- time.sleep(delay)
- if width >= MIN_WIDTH:
- measured.append((width * height, candidate, (width, height)))
- if not measured:
- raise Unavailable("候选都不是可用封套")
-
- for _pixels, winner, size in sorted(measured, key=lambda item: item[0], reverse=True):
- try:
- data = _fetch(transport, winner.url, referer=winner.referer,
- limit=16 * 1024 * 1024)
- except (Unavailable, httpx.TransportError):
- continue
- return winner, size, data
- raise Unavailable("可用候选完整下载都失败")
-
-
-FIELDS = ("code", "result", "source", "width", "height", "kb", "url", "note")
-
-
-#: 判定为「所有渠道都没有」的落空,续跑时不必重来;连接类失败必须重试。
-#: 三态口径:一次超时不等于确认没有,不能靠它把番号永久踢出队列。
-TRANSIENT = re.compile(r"(Error|Timeout|SSL|Connect|Proxy|Protocol)", re.I)
-
-
-def settled_misses(log: Path) -> set[str]:
- """上一轮已经把所有源探完、确认没有封套的番号。
-
- 这类落空是最贵的:每条都要把全部候选源挨个试完才能确定。实测 194 条里
- 150 条落空,重探一遍就是好几个小时,而结论不会变。
- """
- rows = logged_rows(log)
- return {str(row.get("code") or "").strip() for row in rows
- if row.get("result") == "未取得"
- and not TRANSIENT.search(str(row.get("note") or ""))
- and str(row.get("code") or "").strip()}
-
-
-def carried_rows(log: Path, keep: set[str]) -> list[dict]:
- """把这轮跳过的番号的上轮记录原样带进新日志。"""
- if not keep:
- return []
- return [{field: row.get(field, "") for field in FIELDS}
- for row in logged_rows(log)
- if str(row.get("code") or "").strip() in keep]
-
-
-def logged_rows(log: Path) -> list[dict]:
- if not log.is_file():
- return []
- return read_rows(log)
-
-
-def restore_logged_successes(transport: HttpTransport, log: Path, root: Path,
- delay: float = 0.0, guard: DiskGuard | None = None) -> dict:
- """Re-download missing covers from the exact successful URLs already in the audit log.
-
- This is intentionally narrower than a fresh scrape: it makes no discovery requests,
- preserves the existing audit log and refuses an upstream image whose dimensions changed.
- """
- root.mkdir(parents=True, exist_ok=True)
- restored = skipped = 0
- failed: list[dict[str, str]] = []
- # 恢复不做发现请求,所以它比抓取更容易把历史错图原样搬回本地:跨片封套在这里
- # 也要挡掉,否则删掉错图重跑恢复只会把同一张再下一次。
- successes = [row for row in logged_rows(log)
- if row.get("result") == "取得" and row.get("code") and row.get("url")
- and not is_cross_product_cover(str(row["code"]), str(row["url"]))]
- for index, row in enumerate(successes, 1):
- if guard is not None:
- guard.check()
- code = normalise_code_key(str(row["code"]))
- target = root / f"{code}.jpg"
- if target.is_file():
- skipped += 1
- continue
- temporary = target.with_suffix(".restore.tmp")
- try:
- data = _fetch(transport, str(row["url"]), referer=_referer_for(str(row["url"])),
- limit=16 * 1024 * 1024)
- with Image.open(io.BytesIO(data)) as image:
- size = image.size
- image.verify()
- expected = (int(row["width"]), int(row["height"]))
- if size != expected or size[0] < MIN_WIDTH:
- raise Unavailable(f"尺寸变化:日志 {expected[0]}x{expected[1]},当前 {size[0]}x{size[1]}")
- temporary.write_bytes(data)
- temporary.replace(target)
- restored += 1
- print(f"[{index}/{len(successes)}] 恢复 {code} {size[0]}x{size[1]}", flush=True)
- # 与完整抓取同一条长跑边界:单张网络异常降级成失败记录,不能让余下恢复归零;
- # KeyboardInterrupt 等 BaseException 仍会正常中断。
- except Exception as exc:
- failed.append({"code": code, "error": f"{type(exc).__name__}: {exc}"[:120]})
- print(f"[{index}/{len(successes)}] 未恢复 {code}:{type(exc).__name__} {exc}",
- flush=True)
- finally:
- temporary.unlink(missing_ok=True)
- if delay:
- time.sleep(delay)
- return {"logged": len(successes), "restored": restored, "skipped": skipped,
- "failed": failed}
-
-
-def pending(database: Path, root: Path, only_shaped: bool,
- location: str | None = None, *, existing: bool = False,
- max_width: int = 0, fc2_only: bool = False) -> list[str]:
- connection = open_readonly(database)
- try:
- location_sql = " AND location=?" if location else ""
- parameters: tuple[object, ...] = (location,) if location else ()
- rows = connection.execute(
- "SELECT code, COUNT(*) FROM asset WHERE medium='video' "
- "AND code IS NOT NULL AND code<>''" + location_sql
- + " GROUP BY code ORDER BY 2 DESC",
- parameters,
- ).fetchall()
- finally:
- connection.close()
- result = []
- for code, _count in rows:
- if fc2_only and not str(code).upper().startswith("FC2"):
- continue
- # 判形态必须看原值。`normalise_code_key` 会补上分隔符,把 `RAIKUN325`
- # (myfans 账号名,241 个文件)改写成 `RAIKUN-325` 并通过形态检查,
- # 于是队列里全是查不到的账号名。判据与 web_contract 共用一份实现。
- if only_shaped and not is_jav_code(str(code)):
- continue
- # FC2 在 r18/avsox/javbus 三源实测零命中(见 HANDOFF),本抓取器用的是
- # 同一批来源。默认跳过 400 个必然落空的请求;`--all-codes` 仍可强制尝试。
- if only_shaped and str(code).upper().startswith("FC2"):
- continue
- key = normalise_code_key(str(code))
- target = root / f"{key}.jpg"
- if existing:
- if not target.is_file():
- continue
- try:
- with Image.open(target) as image:
- width = image.size[0]
- except (UnidentifiedImageError, OSError):
- width = 0
- if max_width and width > max_width:
- continue
- result.append(key)
- elif not target.is_file():
- result.append(key)
- return result
-
-
-def audit_state(database: Path, root: Path, log: Path) -> dict[str, object]:
- """只读盘点当前 JAV 封面;用于批次前后使用同一统计口径。"""
- connection = open_readonly(database)
- try:
- raw_codes = [str(row[0]) for row in connection.execute(
- "SELECT DISTINCT code FROM asset WHERE medium='video' "
- "AND code IS NOT NULL AND code<>''"
- )]
- finally:
- connection.close()
- codes = {
- normalise_code_key(code) for code in raw_codes
- if is_jav_code(code) and not code.upper().startswith("FC2")
- }
- dimensions: dict[str, tuple[int, int]] = {}
- invalid: list[str] = []
- for path in sorted(root.glob("*.jpg")) if root.is_dir() else []:
- try:
- with Image.open(path) as image:
- dimensions[path.stem] = image.size
- except (UnidentifiedImageError, OSError):
- invalid.append(path.name)
- widths = {
- "le_800": sum(width <= 800 for width, _height in dimensions.values()),
- "801_999": sum(801 <= width <= 999 for width, _height in dimensions.values()),
- "1000_1199": sum(1000 <= width <= 1199
- for width, _height in dimensions.values()),
- "ge_1200": sum(width >= 1200 for width, _height in dimensions.values()),
- }
- rows = logged_rows(log)
- return {
- "jav_codes": len(codes),
- "decoded_covers": len(dimensions),
- "missing": len(codes - set(dimensions)),
- "invalid": invalid,
- "width_buckets": widths,
- "log_successes": sum(row.get("result") == "取得" for row in rows),
- "log_misses": sum(row.get("result") == "未取得" for row in rows),
- "settled_misses": len(settled_misses(log)),
- }
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="按番号抓最高清的官方封套")
- parser.add_argument("--db", type=Path, default=DATABASE_PATH)
- parser.add_argument("--out", type=Path, default=COVER_DIR)
- parser.add_argument("--log", type=Path,
- default=GENERATED_DIR / "cover-fetch-log.csv")
- parser.add_argument(
- "--metadata-root", type=Path, default=DEFAULT_METADATA_ROOT,
- help="Javinizer-Go 原始快照目录;先离线复用成功证据,再补联网来源",
- )
- parser.add_argument("--fc2-metadata-log", type=Path, default=DEFAULT_FC2_METADATA_LOG,
- help="fc2cmadb 文章封面证据,只对 --fc2-only 生效")
- parser.add_argument("--limit", type=int, default=0)
- parser.add_argument("--code", help="只处理一个已归一化番号,用于定点重试")
- parser.add_argument("--delay", type=float, default=1.5)
- parser.add_argument("--min-free", type=float, default=40.0,
- help="系统盘最低可用 GiB;运行中每隔一段时间复查")
- parser.add_argument("--disk-check-secs", type=float, default=20.0)
- parser.add_argument("--location",
- help="只抓指定来源的番号封套,例如 pikpak;封套仍按番号共享")
- parser.add_argument("--retry-misses", action="store_true",
- help="连上轮确认没有封套的番号也重探一遍")
- parser.add_argument("--restore-successes", action="store_true",
- help="只按成功日志中的原 URL 恢复缺失封套,不重新探测来源")
- parser.add_argument("--upgrade-existing", action="store_true",
- help="重探已有封套;只有候选像素更多时才原子替换")
- parser.add_argument("--upgrade-max-width", type=int, default=0,
- help="升级模式只重探不超过此宽度的已有封套;0 表示全部")
- parser.add_argument("--all-codes", action="store_true",
- help="连 FC2/日期番号一起试;默认只跑片商与素人形态")
- parser.add_argument("--fc2-only", action="store_true",
- help="只用 fc2cmadb 已存证据抓 FC2 官方 CDN 封面")
- parser.add_argument("--audit", action="store_true",
- help="只读输出封面数量、缺失、损坏和尺寸分布,不联网不写文件")
- return parser
-
-
-def _write_log(path: Path, rows: list[dict]) -> None:
- """每条都落盘:这个任务要跑三四个小时,只在结束时写等于全程看不见进度。"""
- write_rows(path, FIELDS, rows)
-
-
-def _renew_transport_after_error(transport: HttpTransport,
- error: Exception) -> HttpTransport:
- """永久 transport 失败后丢弃连接池,避免后续番号连续 PoolTimeout。"""
- if not isinstance(error, httpx.TransportError):
- return transport
- if isinstance(transport, HostLimitedTransport):
- transport.renew()
- return transport
- transport.close()
- return HttpxTransport()
-
-
-def _replace_log_row(rows: list[dict], code: str, replacement: dict) -> None:
- """一个番号只保留一条最新成功证据,不扰动其他番号。"""
- rows[:] = [row for row in rows
- if str(row.get("code") or "").strip() != code]
- rows.append({field: replacement.get(field, "") for field in FIELDS})
-
-
-def run(args: argparse.Namespace) -> int:
- if args.audit:
- print(json.dumps(audit_state(args.db, args.out, args.log),
- ensure_ascii=False, indent=2))
- return 0
- if args.upgrade_max_width < 0:
- print("[stop] --upgrade-max-width 不能小于 0")
- return 2
- if args.upgrade_max_width and not args.upgrade_existing:
- print("[stop] --upgrade-max-width 只能与 --upgrade-existing 一起使用")
- return 2
- if args.upgrade_existing and args.retry_misses:
- print("[stop] --upgrade-existing 与 --retry-misses 不能同时使用")
- return 2
- if args.restore_successes and args.upgrade_existing:
- print("[stop] --restore-successes 与 --upgrade-existing 不能同时使用")
- return 2
- if args.fc2_only and args.all_codes:
- print("[stop] --fc2-only 与 --all-codes 不能同时使用")
- return 2
- args.out.mkdir(parents=True, exist_ok=True)
- guard = DiskGuard(system_volume(), args.min_free, args.disk_check_secs)
- try:
- free_gb = guard.check(force=True)
- except JobPolicyError as exc:
- print(f"[stop] {exc}")
- return exc.exit_code
- print(f"系统盘可用 {free_gb:.1f} GiB,运行期阈值 {args.min_free:.1f} GiB")
- if args.restore_successes:
- transport = HttpxTransport()
- try:
- result = restore_logged_successes(
- transport, args.log, args.out, args.delay, guard=guard,
- )
- except JobPolicyError as exc:
- print(f"[stop] {exc}")
- return exc.exit_code
- finally:
- transport.close()
- print(f"成功日志 {result['logged']},恢复 {result['restored']},"
- f"已存在 {result['skipped']},失败 {len(result['failed'])} → {args.out}")
- return 2 if result["failed"] else 0
-
- todo = pending(
- args.db, args.out, not args.all_codes and not args.fc2_only, args.location,
- existing=args.upgrade_existing, max_width=args.upgrade_max_width,
- fc2_only=args.fc2_only,
- )
- if args.code:
- wanted = normalise_code_key(args.code)
- todo = [code for code in todo if code == wanted]
- skipped = set()
- if not args.upgrade_existing and not args.retry_misses:
- skipped = settled_misses(args.log) & set(todo)
- todo = [code for code in todo if code not in skipped]
- if args.limit:
- todo = todo[:args.limit]
- selected = set(todo)
- if args.upgrade_existing:
- width_note = (f",当前宽度不超过 {args.upgrade_max_width}"
- if args.upgrade_max_width else "")
- print(f"待重探已有封套 {len(todo)} 个{width_note};只在像素更多时替换")
- else:
- print(f"待抓番号 {len(todo)} 个(已落盘的跳过,"
- f"上轮确认没有的跳过 {len(skipped)} 个,--retry-misses 可重试)")
-
- transport = HostLimitedTransport(HttpxTransport(), args.delay)
- # 日志是整份重写:这轮只跑 pikpak 或只跑 --limit 时,未选中的旧记录也必须保留;
- # 只删除本轮会重新生成的番号。否则一次来源小批次就会抹掉其他来源的复核证据。
- previous_rows = logged_rows(args.log)
- fc2_candidates = fc2_cover_candidates(args.fc2_metadata_log) if args.fc2_only else {}
- rows: list[dict] = [
- {field: row.get(field, "") for field in FIELDS}
- for row in previous_rows
- if args.upgrade_existing
- or str(row.get("code") or "").strip() not in selected
- ]
- stats = {"ok": 0, "miss": 0, "kept": 0}
- stopped: JobPolicyError | None = None
- try:
- for index, code in enumerate(todo, 1):
- try:
- guard.check()
- except JobPolicyError as exc:
- stopped = exc
- print(f"[stop] {exc}", flush=True)
- break
- try:
- target = args.out / f"{code}.jpg"
- current_size = (0, 0)
- if args.upgrade_existing:
- try:
- with Image.open(target) as image:
- current_size = image.size
- except (UnidentifiedImageError, OSError):
- pass
- previous = logged_success_evidence(previous_rows, code)
- prior = tuple(candidate for candidate in (
- fc2_candidates.get(code), previous[0] if previous is not None else None,
- ) if candidate is not None)
- known_sizes = ({previous[0].url: previous[1]}
- if previous is not None else {})
- winner, (width, height), data = best_cover(
- transport, code, 0,
- metadata_root=args.metadata_root, prior_candidates=prior,
- known_sizes=known_sizes,
- minimum_pixels=current_size[0] * current_size[1],
- )
- # 网络异常必须按条吞掉。一次 SSL 抖动
- # (httpx.ConnectError: UNEXPECTED_EOF_WHILE_READING)此前直接打死了
- # 整个三小时的任务,而且死得很安静——日志停在半路,看起来像跑完了。
- # 长跑批处理不能因为一个番号的连接问题就整体退出。
- # `Exception` 已涵盖 Unavailable 与网络异常;Ctrl-C 是 BaseException
- # 的另一支,不会被这里吞掉,仍能正常中断。
- except Exception as exc:
- transport = _renew_transport_after_error(transport, exc)
- stats["miss"] += 1
- if args.upgrade_existing:
- print(f"[{index}/{len(todo)}] 保留 {code}:重探失败 "
- f"{type(exc).__name__} {exc}", flush=True)
- else:
- rows.append({"code": code, "result": "未取得", "source": "",
- "width": "", "height": "", "kb": "", "url": "",
- "note": f"{type(exc).__name__}: {exc}"[:80]})
- print(f"[{index}/{len(todo)}] 未取得 {code}:"
- f"{type(exc).__name__} {exc}", flush=True)
- else:
- if (args.upgrade_existing
- and width * height <= current_size[0] * current_size[1]):
- stats["kept"] += 1
- print(f"[{index}/{len(todo)}] 保留 {code} "
- f"{current_size[0]}x{current_size[1]} >= {width}x{height}",
- flush=True)
- else:
- temporary = target.with_suffix(".tmp")
- temporary.write_bytes(data)
- try:
- temporary.replace(target)
- finally:
- temporary.unlink(missing_ok=True)
- stats["ok"] += 1
- row = {"code": code, "result": "取得", "source": winner.source,
- "width": width, "height": height, "kb": len(data) // 1024,
- "url": winner.url, "note": ""}
- if args.upgrade_existing:
- _replace_log_row(rows, code, row)
- else:
- rows.append(row)
- verb = "升级" if args.upgrade_existing else "取得"
- print(f"[{index}/{len(todo)}] {verb} {code} {width}x{height} "
- f"{len(data)//1024} KB <- {winner.source}", flush=True)
- # 落空的行也要落盘。这句只放在取得分支里的话,连续落空时 CSV 整段不动;
- # 被强杀时 finally 也来不及跑,那一串判定就白做了——而「查不到」恰恰
- # 是最贵的一类:每条都要把所有候选源挨个探完才能确定。
- _write_log(args.log, rows)
- finally:
- transport.close()
- _write_log(args.log, rows)
-
- if args.upgrade_existing:
- print(f"\n升级 {stats['ok']},保留 {stats['kept']},"
- f"重探失败但保留原图 {stats['miss']} → {args.out}")
- else:
- print(f"\n取得 {stats['ok']},未取得 {stats['miss']} → {args.out}")
- print(f"逐条记录 → {args.log}")
- return stopped.exit_code if stopped is not None else 0
-
-def main(argv: list[str] | None = None) -> int:
- return run(build_parser().parse_args(argv))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+from peach.jav_cover_fetch import main
if __name__ == "__main__":
raise SystemExit(main())
diff --git a/scripts/fetch_studio_avatar_candidates.py b/scripts/fetch_studio_avatar_candidates.py
index c463652f8..5471728e0 100644
--- a/scripts/fetch_studio_avatar_candidates.py
+++ b/scripts/fetch_studio_avatar_candidates.py
@@ -35,7 +35,7 @@ from peach.logo_provider import ( # noqa: E402
from peach.config import GENERATED_DIR # noqa: E402
from peach.social_links import twimg_tiers # noqa: E402
from peach.review_csv import read_rows, write_rows
-from peach.scripting import USER_AGENT
+from peach.scripting import USER_AGENT, RateLimiter
RESOLVER = "https://unavatar.io/{platform}/{handle}?json"
FIELDS = (
@@ -150,7 +150,7 @@ def main(argv: list[str] | None = None, *, transport=None) -> int:
batch_hashes: dict[str, str] = {}
owned_http = transport is None
http = transport or HttpxTransport()
- last = 0.0
+ limiter = RateLimiter(args.interval)
try:
for studio in studios:
health["attempted"] += 1
@@ -168,10 +168,7 @@ def main(argv: list[str] | None = None, *, transport=None) -> int:
"reason": "未取得该厂牌的社交 handle"})
health["no_handle"] += 1
continue
- wait = args.interval - (time.monotonic() - last)
- if wait > 0:
- time.sleep(wait)
- last = time.monotonic()
+ limiter.wait()
resolver_url = RESOLVER.format(platform=args.platform, handle=handle)
record = {"studio": studio, "handle": handle, "platform": args.platform,
"resolver_url": resolver_url, "resolved_url": "", "width": "",
diff --git a/scripts/harvest_agency_rosters.py b/scripts/harvest_agency_rosters.py
index b5c19428e..3687f9f77 100644
--- a/scripts/harvest_agency_rosters.py
+++ b/scripts/harvest_agency_rosters.py
@@ -47,7 +47,7 @@ from peach.minnano_av import ( # noqa: E402
)
from peach.review_csv import write_rows # noqa: E402
from peach.scripting import ( # noqa: E402
- USER_AGENT, add_ledger_write_args, counts_of, open_for_write, verify_after_write,
+ USER_AGENT, RateLimiter, add_ledger_write_args, counts_of, open_for_write, verify_after_write,
)
FIELDS = ("agency", "agency_id", "production", "roster_name", "actress_id",
@@ -148,13 +148,10 @@ class Site:
self.timeout = timeout
self.interval = interval
self.fetched = 0
- self._last = 0.0
+ self._limiter = RateLimiter(interval)
def __call__(self, url: str) -> tuple[str, str]:
- wait = self.interval - (time.monotonic() - self._last)
- if wait > 0:
- time.sleep(wait)
- self._last = time.monotonic()
+ self._limiter.wait()
try:
response = self.http(HttpRequest("GET", url, {"User-Agent": USER_AGENT}),
self.timeout, 4 << 20)
diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.py
index 46eb72c79..583197bdb 100644
--- a/scripts/harvest_performer_links.py
+++ b/scripts/harvest_performer_links.py
@@ -32,7 +32,7 @@ from peach.minnano_av import ( # noqa: E402,F401
actress_id, profile_fields, profile_text, search_url,
)
from peach.review_csv import write_rows # noqa: E402
-from peach.scripting import USER_AGENT, open_readonly # noqa: E402
+from peach.scripting import USER_AGENT, open_readonly, RateLimiter # noqa: E402
# 平台判据与选人规则和目录型采集器共用,定义在 peach.social_links;这里只保留 minnano-av 的解析。
from peach.social_links import ( # noqa: E402,F401
classify, host_owners, load_performers, under,
@@ -97,16 +97,13 @@ def run(args) -> int:
results: list[dict[str, object]] = []
http = HttpxTransport()
- last = 0.0
+ limiter = RateLimiter(args.interval)
hit = 0
try:
for record in performers:
rows, found_id, agency, note, used = [], "", "", "未取得:没有可用于日文站的名字", ""
for candidate in record["chain"]:
- wait = args.interval - (time.monotonic() - last)
- if wait > 0:
- time.sleep(wait)
- last = time.monotonic()
+ limiter.wait()
try:
rows, found_id, agency, note = scan(http, candidate, args.timeout,
owners.get)
diff --git a/scripts/harvest_studio_icons.py b/scripts/harvest_studio_icons.py
index ef29a863c..ca527c37d 100644
--- a/scripts/harvest_studio_icons.py
+++ b/scripts/harvest_studio_icons.py
@@ -78,6 +78,8 @@ import httpx
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach import face_detect, images, link_marks, site_icons, site_logos # noqa: E402
+from peach.http import HttpRequest, HttpxTransport
+from peach.scripting import RateLimiter
from peach.config import GENERATED_DIR, REVIEW_DIR, STATE_DIR
from peach.review_csv import write_rows
@@ -330,13 +332,14 @@ class Fetcher:
def __init__(self, client: httpx.Client, timeout: float, interval: float,
retries: int = 2, backoff: float = 2.0):
self.client = client
+ self.transport = HttpxTransport(client)
self.timeout = timeout
self.interval = interval
self.retries = retries
self.backoff = backoff
self.fetched = 0
self.retried = 0
- self._last = 0.0
+ self._limiter = RateLimiter(interval)
#: 同一份首页这一趟会被要三次:`site_icons` 找声明、这边找 header 的 `<img>`、
#: 再找页面上的 X 账号。缓存把它压回一次,省的是站点的带宽和这一轮的墙上时间。
self._cache: dict[str, tuple[bytes, str] | None] = {}
@@ -353,13 +356,10 @@ class Fetcher:
def _get(self, target: str):
for attempt in range(self.retries + 1):
- wait = self.interval - (time.monotonic() - self._last)
- if wait > 0:
- time.sleep(wait)
- self._last = time.monotonic()
+ self._limiter.wait()
try:
- response = self.client.get(target, headers={"User-Agent": USER_AGENT},
- timeout=self.timeout, follow_redirects=True)
+ response = self.transport(HttpRequest("GET", target, {"User-Agent": USER_AGENT}),
+ self.timeout, 16 * 1024 * 1024)
except (OSError, httpx.HTTPError):
# 和 `page_cache.Site` 同一条规矩:这些站的 TLS 大约三次断一次,重试即成。
# 上一轮 Fitch、Idea Pocket、Wanz Factory 都取到了,这一轮四个全断,
@@ -370,10 +370,10 @@ class Fetcher:
time.sleep(self.backoff * (attempt + 1))
continue
# 状态码不重试:404 重试三次还是 404。
- if response.status_code != 200 or not response.content:
+ if response.status != 200 or not response.body or len(response.body) > 16 * 1024 * 1024:
return None
self.fetched += 1
- return response.content, response.headers.get("content-type", "")
+ return response.body, response.headers.get("content-type", "")
return None
diff --git a/scripts/harvest_studio_sites.py b/scripts/harvest_studio_sites.py
index 053e28279..dd620d047 100644
--- a/scripts/harvest_studio_sites.py
+++ b/scripts/harvest_studio_sites.py
@@ -321,7 +321,7 @@ def probe(url: str, timeout: float, retries: int = 2, backoff: float = 2.0
这个空结论当成事实。只重试传输层异常:HTTP 状态码是站点的回答,不是抖动。
"""
for attempt in range(retries + 1):
- http = HttpxTransport(crawler_client())
+ http = HttpxTransport(crawler_client(), owns_client=True)
try:
response = http(HttpRequest("GET", url, {"User-Agent": USER_AGENT}),
timeout, 4 << 20)
diff --git a/scripts/rediscover_entity_links.py b/scripts/rediscover_entity_links.py
index a4375835e..778a205f1 100644
--- a/scripts/rediscover_entity_links.py
+++ b/scripts/rediscover_entity_links.py
@@ -26,6 +26,9 @@ from pathlib import Path
from urllib.parse import unquote, urljoin, urlsplit
import httpx
+import tldextract
+
+_PSL = tldextract.TLDExtract(suffix_list_urls=(), cache_dir=None, include_psl_private_domains=True)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
@@ -52,15 +55,8 @@ def fetch(url: str, timeout: float = 12.0) -> tuple[int, str, str]:
def registrable(host: str) -> str:
- """粗粒度的「同一个站」:取末两段,日本的二级后缀再多取一段。
-
- 不引 publicsuffix 依赖——这里只需要把 `www.t-powers.co.jp` 和 `t-powers.co.jp` 判成
- 一家、把 `x.com` 判成另一家,而不需要处理公共后缀列表的全部边角。
- """
- parts = host.casefold().split(".")
- if len(parts) >= 3 and parts[-2] in {"co", "or", "ne", "ac", "go", "com", "net", "org"}:
- return ".".join(parts[-3:])
- return ".".join(parts[-2:])
+ """固定离线 PSL 含 PRIVATE 区段;不同托管租户保持独立。"""
+ return _PSL(host.casefold().rstrip(".")).top_domain_under_public_suffix
def same_site(candidate: str, original: str) -> bool:
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 1f143a2a5..a08b0e171 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -36,7 +36,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py",
"test_mdns.py", "test_netwatch.py", "test_certs.py",
"test_review_mirror.py"),
- "metadata": ("test_metadata*.py", "test_genre_taxonomy.py", "test_fc2*.py",
+ "metadata": ("test_scraping_access.py", "test_metadata*.py", "test_genre_taxonomy.py", "test_fc2*.py",
"test_babepedia_match.py",
"test_jav*.py", "test_code_creators.py", "test_logo_provider.py",
"test_avatar_provider.py", "test_face_detect.py", "test_performer*.py",
diff --git a/src/peach/http.py b/src/peach/http.py
index cf888e393..c55198d40 100644
--- a/src/peach/http.py
+++ b/src/peach/http.py
@@ -40,13 +40,13 @@ class HttpTransport(Protocol):
class HttpxTransport:
"""可跨请求复用的同步 HTTPX client;不会自动重试或持久化响应。"""
- def __init__(self, client: httpx.Client | None = None):
+ def __init__(self, client: httpx.Client | None = None, *, owns_client: bool = False):
self.client = client or httpx.Client(
follow_redirects=True,
limits=httpx.Limits(max_connections=32, max_keepalive_connections=16),
headers={"User-Agent": "Peach/0.2"},
)
- self._owns_client = client is None
+ self._owns_client = client is None or owns_client
def __call__(
self,
diff --git a/src/peach/jav_cover_fetch.py b/src/peach/jav_cover_fetch.py
new file mode 100644
index 000000000..3aa1426b1
--- /dev/null
+++ b/src/peach/jav_cover_fetch.py
@@ -0,0 +1,985 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+r"""按番号抓官方封套:把所有候选量一遍,留像素最多的那张。
+
+**不用固定优先级链**,因为实测证明没有哪个源恒定最好:
+
+ GYAN-017 awsimgsrc 2184x1464 有数字版,DMM 自己的高清路径最好
+ ABW-232 duga 1000x674 没有数字版,awsimgsrc 四种写法全 404
+ PPT-018 pics.dmm 800x539 只有低清
+
+同一个 DMM 有两条路径,差 7.4 倍像素——之前一直用的是低清那条:
+
+ 低清 pics.dmm.co.jp/mono/movie/adult/<cid>/<cid>pl.jpg 800x539
+ 高清 awsimgsrc.dmm.co.jp/pics_dig/digital/video/<cid>/<cid>pl.jpg 2184x1464
+
+候选不是固定优先级,而是汇总后量像素:
+
+- 已保存的 Javinizer-Go 原始证据,离线复用 cover URL 与 content_id;
+- r18.dev 官方 DMM jacket(本地没有成功快照时才联网补);
+- DMM 新旧 awsimgsrc CDN 的 digital/video、digital/amateur、mono/movie 路径;
+- 有 Prestige 厂牌证据时,直连 Prestige API 与 MGS EnlargeImage;
+- 上轮成功日志里的原 URL,保住已经发现但当前无法重新检索的 DUGA 等官方图。
+
+AVBase 已返回 Cloudflare 验证页,不再进入批量流程,也不尝试绕过。DUGA 批量搜索 API
+需要代理店应用 ID,未配置前只复用成功日志中已经取得的精确图片 URL。
+
+两条番号改写规则,都由实测得出:
+
+- cid 数字段必须补到 5 位。`waaa415` 404,`waaa00415` 命中 2184x1468。
+- 素人系要去掉三位厂牌前缀。`278GYAN-017` 查不到,`GYAN-017` 能查到。
+
+为省流量,先用 Range 只取前 64 KiB 量尺寸,只有胜出的那张才整张下载。
+
+存原图不裁:4:3 与 16:9 两种版式在界面上靠 `object-fit` / `object-position` 取景,
+切版式零成本也不重新下载。官方那张独立正封 `ps.jpg` 只有 147x200,比裁出来的还小。
+"""
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import re
+import time
+import urllib.parse
+import sys
+from dataclasses import dataclass
+from html.parser import HTMLParser
+from pathlib import Path
+from urllib.parse import urlparse
+
+import httpx
+from PIL import Image, UnidentifiedImageError
+
+from peach.review_csv import ENCODING, read_rows, write_rows
+from peach.scripting import USER_AGENT, open_readonly
+from peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIR
+from peach.http import HttpRequest, HttpTransport, HttpxTransport
+from peach.scripting import HostLimiter
+from peach.scraping_access import SourceTransport
+from peach.config import SECRETS_DIR
+from peach.jobs import DiskGuard, JobPolicyError
+from peach.platform import system_volume
+from peach.catalog_rules import (
+ code_letter_stem,
+ is_amateur_code,
+ is_jav_code,
+ normalise_code_key,
+)
+
+AWS_LEGACY_DIGITAL = (
+ "https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/{cid}/{cid}pl.jpg"
+)
+AWS_MODERN = "https://awsimgsrc.dmm.com/dig/{kind}/{cid}/{cid}pl.jpg"
+AWS_LEGACY = "https://awsimgsrc.dmm.co.jp/pics_dig/{kind}/{cid}/{cid}pl.jpg"
+R18_DETAIL = "https://r18.dev/videos/vod/movies/detail/-/dvd_id={code}/json"
+MGS_DETAIL = "https://www.mgstage.com/product/product_detail/{code}/"
+PRESTIGE_SEARCH = "https://www.prestige-av.com/api/search"
+PRESTIGE_PRODUCT = "https://www.prestige-av.com/api/product/{uuid}"
+PRESTIGE_MEDIA = "https://www.prestige-av.com/api/media/{path}"
+DEFAULT_METADATA_ROOT = SOURCES_DIR / "metadata" / "javinizer-go"
+DEFAULT_FC2_METADATA_LOG = GENERATED_DIR / "fc2-candidate-log.csv"
+
+#: 低于这个宽度的是缩略图或占位图,不当封套。实测最低的正片封套是 800 宽。
+MIN_WIDTH = 700
+#: 量尺寸只需要 JPEG 头部,别把整张 1 MB 的图拉下来。
+PROBE_BYTES = 64 * 1024
+# 瞬时 TLS EOF / 连接重置不能落成“官方没有封面”。按项目外网退避规则重试,
+# 只有 2/4/6/8 秒四次重试全部失败后,才把网络异常交给逐条日志记录。
+NETWORK_RETRY_DELAYS = (2, 4, 6, 8)
+#: 页面与上游证据里可能混着剧照与缩略图,按文件名排除。
+THUMBNAIL = re.compile(r"(thumb|small|icon|/ts/|-s\d|_s\.)", re.I)
+FC2_HIRES = re.compile(r"https://contents-thumbnail\d*\.fc2\.com/w(?:7\d\d|[89]\d\d|\d{4,})/", re.I)
+IMAGE_URL = re.compile(r"https?://[^\"'\\ )]+?\.(?:jpg|jpeg|png|webp)")
+
+
+@dataclass(frozen=True)
+class Candidate:
+ source: str
+ url: str
+ referer: str = "https://www.dmm.co.jp/"
+
+
+@dataclass(frozen=True)
+class MetadataEvidence:
+ candidates: tuple[Candidate, ...] = ()
+ makers: frozenset[str] = frozenset()
+ sources: frozenset[str] = frozenset()
+
+
+class Unavailable(RuntimeError):
+ pass
+
+
+class HostLimitedTransport:
+ """把请求间隔按主机分别计算;不同官方站点互不阻塞。"""
+
+ def __init__(self, inner: HttpxTransport, interval: float, *,
+ clock=time.monotonic, sleeper=time.sleep) -> None:
+ self.inner = inner
+ self.interval = max(0.0, interval)
+ self.clock = clock
+ self.sleeper = sleeper
+ self.limiter = HostLimiter({}, default_interval=self.interval, clock=clock, sleeper=sleeper)
+
+ def __call__(self, request: HttpRequest, timeout: float, limit: int):
+ self.limiter.wait(request.url)
+ return self.inner(request, timeout, limit)
+
+ def renew(self) -> None:
+ if hasattr(self.inner, "renew"):
+ self.inner.renew()
+ return
+ self.inner.close()
+ self.inner = HttpxTransport()
+
+ def close(self) -> None:
+ self.inner.close()
+
+
+class _MGSDetailParser(HTMLParser):
+ """只读取 MGS 的放大图链接;列表缩略图和剧照不进入候选。"""
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.urls: list[str] = []
+
+ def handle_starttag(self, tag: str,
+ attrs: list[tuple[str, str | None]]) -> None:
+ values = dict(attrs)
+ url = None
+ if tag.lower() == "a" and values.get("id") == "EnlargeImage":
+ url = values.get("href")
+ elif tag.lower() == "a" and "link_magnify" in (values.get("class") or "").split():
+ url = values.get("href")
+ elif tag.lower() == "img" and any(
+ token in (values.get("src") or "").lower()
+ for token in ("jacket", "cover")):
+ url = values.get("src") or values.get("data-src")
+ if url:
+ url = url.replace("ps.", "pl.", 1)
+ if url and (IMAGE_URL.fullmatch(url)
+ or re.search(r"\.(?:jpg|jpeg|png|webp)(?:\?.*)?$", url, re.I)):
+ self.urls.append(url)
+
+
+def _fetch(transport: HttpTransport, url: str, *, referer: str,
+ limit: int, ranged: bool = False,
+ extra_headers: dict[str, str] | None = None) -> bytes:
+ headers = {"User-Agent": USER_AGENT, "Referer": referer,
+ "Accept-Language": "ja,en;q=0.9"}
+ if extra_headers:
+ headers.update(extra_headers)
+ if ranged:
+ headers["Range"] = f"bytes=0-{PROBE_BYTES - 1}"
+ request = HttpRequest("GET", url, headers)
+ for attempt in range(len(NETWORK_RETRY_DELAYS) + 1):
+ try:
+ response = transport(request, 30, limit)
+ break
+ except httpx.TransportError:
+ if attempt == len(NETWORK_RETRY_DELAYS):
+ raise
+ time.sleep(NETWORK_RETRY_DELAYS[attempt])
+ if response.status not in (200, 206):
+ raise Unavailable(f"HTTP {response.status}")
+ return response.body
+
+
+def code_variants(code: str) -> list[str]:
+ """素人系番号带三位厂牌前缀,去掉才查得到:`278GYAN-017` -> `GYAN-017`。"""
+ value = normalise_code_key(code)
+ out = [value]
+ stripped = re.sub(r"^\d{3}(?=[A-Z])", "", value)
+ if stripped != value:
+ out.append(stripped)
+ return out
+
+
+def cid_variants(content_id: str) -> list[str]:
+ """数字段补到 5 位是必须的;带厂牌数字前缀的多半没有数字版,但仍试一次。"""
+ cid = (content_id or "").strip().lower()
+ if not cid:
+ return []
+ out = [cid]
+ shape = re.match(r"^(\d{2,4})?([a-z]+)(\d+)$", cid)
+ if shape:
+ letters, digits = shape.group(2), shape.group(3)
+ out.append(f"{letters}{int(digits):05d}")
+ out.append(f"{letters}{digits}")
+ seen: set[str] = set()
+ return [c for c in out if not (c in seen or seen.add(c))]
+
+
+def _referer_for(url: str) -> str:
+ host = urlparse(url).netloc.lower()
+ if "mgstage.com" in host:
+ return "https://www.mgstage.com/"
+ if "prestige-av.com" in host:
+ return "https://www.prestige-av.com/"
+ if "duga.jp" in host:
+ return "https://duga.jp/"
+ return "https://www.dmm.co.jp/"
+
+
+def candidate_for(url: str) -> Candidate:
+ return Candidate(urlparse(url).netloc.lower(), url, _referer_for(url))
+
+
+def fc2_cover_candidates(path: Path | None) -> dict[str, Candidate]:
+ """Reuse FC2CMADB article evidence, upgrading its listing thumb to measured w1200."""
+ if path is None or not path.is_file():
+ return {}
+ found = {}
+ for row in read_rows(path):
+ url = re.sub(r"(/w)\d+(/)", r"\g<1>1200\2", str(row.get("cover_url") or ""), count=1)
+ code = normalise_code_key(str(row.get("code") or ""))
+ if (row.get("result") == "取得" and not row.get("is_collection")
+ and code.startswith("FC2-PPV-") and IMAGE_URL.fullmatch(url)):
+ found[code] = Candidate(urlparse(url).netloc.lower(), url, "https://fc2cmadb.com/")
+ return found
+
+
+def _unique_candidates(candidates: list[Candidate]) -> list[Candidate]:
+ seen: set[str] = set()
+ return [candidate for candidate in candidates
+ if candidate.url and not (candidate.url in seen or seen.add(candidate.url))]
+
+
+def dmm_cdn_images(url: str) -> list[Candidate]:
+ """按 Javinizer-Go 当前已验证映射生成 DMM 新旧 CDN 候选。
+
+ 主机名和路径不能当清晰度:同一 CID 的 legacy、modern、原始 URL 都要量尺寸。
+ """
+ clean = (url or "").split("?", 1)[0]
+ parsed = urlparse(clean)
+ match = re.search(
+ r"/(?:pics_dig/|dig/)?(?P<kind>digital/(?:video|amateur)|mono/movie)"
+ r"(?:/adult)?/(?P<cid>[^/]+)/",
+ parsed.path,
+ re.I,
+ )
+ candidates = [candidate_for(clean)] if IMAGE_URL.fullmatch(clean) else []
+ if not match:
+ return candidates
+ kind = match.group("kind").lower()
+ cid = match.group("cid").lower()
+ candidates.extend([
+ candidate_for(AWS_MODERN.format(kind=kind, cid=cid)),
+ candidate_for(AWS_LEGACY.format(kind=kind, cid=cid)),
+ ])
+ return _unique_candidates(candidates)
+
+
+def content_id_images(content_id: str) -> list[Candidate]:
+ candidates: list[Candidate] = []
+ for cid in cid_variants(content_id):
+ candidates.extend([
+ candidate_for(AWS_MODERN.format(kind="digital/video", cid=cid)),
+ candidate_for(AWS_LEGACY_DIGITAL.format(cid=cid)),
+ ])
+ return _unique_candidates(candidates)
+
+
+def cached_metadata(metadata_root: Path | None, code: str) -> MetadataEvidence:
+ """复用已落盘的 Javinizer 原始快照,不把网络缓存伪装成实时查询。"""
+ if metadata_root is None:
+ return MetadataEvidence()
+ candidates: list[Candidate] = []
+ makers: set[str] = set()
+ sources: set[str] = set()
+ for variant in code_variants(code):
+ folder = metadata_root / variant
+ if not folder.is_dir():
+ continue
+ for path in sorted(folder.glob("*.json")):
+ try:
+ wrapper = json.loads(path.read_text(encoding=ENCODING))
+ except (OSError, ValueError):
+ continue
+ result = wrapper.get("result")
+ if not isinstance(result, dict):
+ continue
+ source = str(result.get("source") or wrapper.get("source") or path.stem)
+ sources.add(source.lower())
+ for value in (result.get("maker"), result.get("label")):
+ if isinstance(value, str) and value.strip():
+ makers.add(value.strip().lower())
+ cover_url = result.get("cover_url")
+ if isinstance(cover_url, str) and IMAGE_URL.fullmatch(cover_url.strip()):
+ candidates.extend(dmm_cdn_images(cover_url.strip()))
+ candidates.extend(content_id_images(str(result.get("content_id") or "")))
+ return MetadataEvidence(
+ tuple(_unique_candidates(candidates)), frozenset(makers), frozenset(sources),
+ )
+
+
+def logged_success_evidence(
+ rows: list[dict], code: str,
+ ) -> tuple[Candidate, tuple[int, int]] | None:
+ """复用历史精确 URL 与已量尺寸;DUGA 等无需重复探同一张图。"""
+ for row in reversed(rows):
+ if (normalise_code_key(str(row.get("code") or "")) == code
+ and row.get("result") == "取得"
+ and isinstance(row.get("url"), str)
+ and IMAGE_URL.fullmatch(str(row["url"]))):
+ try:
+ size = (int(row.get("width") or 0), int(row.get("height") or 0))
+ except (TypeError, ValueError):
+ size = (0, 0)
+ return candidate_for(str(row["url"])), size
+ return None
+
+
+def logged_success_candidate(rows: list[dict], code: str) -> Candidate | None:
+ """兼容只需要历史 URL 的调用方。"""
+ evidence = logged_success_evidence(rows, code)
+ return evidence[0] if evidence is not None else None
+
+
+#: DMM 的 content_id 一定带番号字母段:`ABW-232` -> `118abw232`、
+#: `MGT-164` -> `h_1711mgt00164`。
+_DMM_CID = re.compile(
+ r"/(?:pics_dig/|dig/)?(?:digital/(?:video|amateur)|mono/movie)"
+ r"(?:/adult)?/(?P<cid>[^/]+)/",
+ re.I,
+)
+
+
+def is_cross_product_cover(code: str, url: str) -> bool:
+ """这个 URL 指向的是另一部片的封套。
+
+ 素人系番号在 avbase 上会连到 DVD 合集:`259LUXU-1475` 的页面主图取到的是
+ `SNG-021` 的封套(`118sng021`)。内容是同一段,封面却不是这部片的——大图
+ 模式的人脸定位、番号搜索和「这张图是谁」全都跟着错位。
+
+ avbase 抓取已在 65fd95f 删掉,这批 URL 却靠「复用上一轮成功记录」一路带到
+ 今天:复用只看 result 是不是「取得」,不看它和番号是否对得上,于是错误封面
+ 再也没有机会被重探。判据落在 URL 上而不是抓取路径上,正是因为下一个引入
+ 错图的来源不会用同一个函数。
+ """
+ stem = code_letter_stem(code)
+ match = _DMM_CID.search(urlparse(url or "").path)
+ if not stem or match is None:
+ return False
+ return stem not in match.group("cid").lower()
+
+
+def _is_prestige(evidence: MetadataEvidence) -> bool:
+ return any("prestige" in value or "プレステージ" in value
+ for value in evidence.makers)
+
+
+def r18_evidence(transport: HttpTransport, code: str) -> MetadataEvidence:
+ """读取 r18 返回的官方封套,并保留旧数字版高清 URL 探测。
+
+ `content_id` 不是稳定的数字版路径。Prestige 的 ABW 系列会返回
+ `118abw232`,对应 `pics.dmm.co.jp/mono/.../118abw232pl.jpg`;把它补零后
+ 拼到 `awsimgsrc.../digital/video` 只会得到 404。r18 已在
+ `images.jacket_image` 给出官方原图 URL,必须优先把这个证据加入候选。
+ """
+ for variant in code_variants(code):
+ try:
+ payload = json.loads(_fetch(
+ transport, R18_DETAIL.format(code=urllib.parse.quote(variant)),
+ referer="https://r18.dev/", limit=2 * 1024 * 1024,
+ ).decode("utf-8", "ignore"))
+ except (Unavailable, ValueError, httpx.TransportError):
+ continue
+ found: list[Candidate] = []
+ jacket = ((payload.get("images") or {}).get("jacket_image") or {})
+ if isinstance(jacket, dict):
+ for raw_url in jacket.values():
+ url = raw_url.strip() if isinstance(raw_url, str) else ""
+ if url and IMAGE_URL.fullmatch(url) and not THUMBNAIL.search(url):
+ found.extend(dmm_cdn_images(url))
+ cid = str(payload.get("content_id") or "")
+ found.extend(content_id_images(cid))
+ makers = frozenset(str(payload.get(key, {}).get("name", "")).casefold()
+ for key in ("maker", "label") if isinstance(payload.get(key), dict))
+ return MetadataEvidence(tuple(_unique_candidates(found)), makers, frozenset({"r18dev"}))
+ return MetadataEvidence()
+
+
+def r18_images(transport: HttpTransport, code: str) -> list[Candidate]:
+ return list(r18_evidence(transport, code).candidates)
+
+
+def mgstage_images(transport: HttpTransport, code: str) -> list[Candidate]:
+ """直取 MGS 商品页 EnlargeImage;年龄确认只用公开 cookie,不绕挑战。"""
+ for variant in code_variants(code):
+ try:
+ page = _fetch(
+ transport,
+ MGS_DETAIL.format(code=urllib.parse.quote(variant)),
+ referer="https://www.mgstage.com/",
+ limit=4 * 1024 * 1024,
+ extra_headers={"Cookie": "adc=1"},
+ ).decode("utf-8", "ignore")
+ except (Unavailable, httpx.TransportError):
+ continue
+ parser = _MGSDetailParser()
+ parser.feed(page)
+ found: list[Candidate] = []
+ for url in parser.urls:
+ absolute = urllib.parse.urljoin("https://www.mgstage.com/", url)
+ if THUMBNAIL.search(absolute):
+ continue
+ found.append(candidate_for(absolute))
+ if found:
+ return _unique_candidates(found)
+ return []
+
+
+def prestige_images(transport: HttpTransport, code: str) -> list[Candidate]:
+ """按 MDCX 固定 revision 的公开 API 模型直取 Prestige packageImage。"""
+ query = urllib.parse.urlencode({
+ "isEnabledQuery": "true",
+ "searchText": code,
+ "isEnableAggregation": "false",
+ "release": "false",
+ "reservation": "false",
+ "soldOut": "false",
+ "from": 0,
+ "aggregationTermsSize": 0,
+ "size": 20,
+ })
+ try:
+ payload = json.loads(_fetch(
+ transport, f"{PRESTIGE_SEARCH}?{query}",
+ referer="https://www.prestige-av.com/", limit=4 * 1024 * 1024,
+ ).decode("utf-8", "ignore"))
+ except (Unavailable, ValueError, httpx.TransportError):
+ return []
+ hits = (((payload.get("hits") or {}).get("hits")) or [])
+ exact: list[str] = []
+ fallback: list[str] = []
+ for hit in hits:
+ source = hit.get("_source") if isinstance(hit, dict) else None
+ if not isinstance(source, dict):
+ continue
+ item_id = normalise_code_key(str(source.get("deliveryItemId") or ""))
+ uuid = str(source.get("productUuid") or "").strip()
+ if not uuid:
+ continue
+ if item_id == normalise_code_key(code):
+ exact.append(uuid)
+ elif str(source.get("deliveryItemId") or "").upper().endswith(code.upper()):
+ fallback.append(uuid)
+ uuids = list(dict.fromkeys(exact or fallback))
+ for uuid in uuids:
+ try:
+ product = json.loads(_fetch(
+ transport, PRESTIGE_PRODUCT.format(uuid=urllib.parse.quote(uuid)),
+ referer="https://www.prestige-av.com/", limit=4 * 1024 * 1024,
+ ).decode("utf-8", "ignore"))
+ except (Unavailable, ValueError, httpx.TransportError):
+ continue
+ package = product.get("packageImage") or {}
+ path = package.get("path") if isinstance(package, dict) else ""
+ if isinstance(path, str) and path.strip():
+ url = PRESTIGE_MEDIA.format(path=path.strip().lstrip("/"))
+ if IMAGE_URL.fullmatch(url):
+ return [candidate_for(url)]
+ return []
+
+
+def prestige_group_images(transport: HttpTransport, code: str) -> list[Candidate]:
+ """汇总 Prestige 与 MGS 的官方候选,尺寸由统一探测比较。"""
+ official = prestige_images(transport, code)
+ return _unique_candidates(official + mgstage_images(transport, code))
+
+
+def probe_size(transport: HttpTransport, candidate: Candidate) -> tuple[int, int]:
+ head = _fetch(transport, candidate.url, referer=candidate.referer,
+ limit=PROBE_BYTES * 2, ranged=True)
+ return Image.open(io.BytesIO(head)).size
+
+
+def best_cover(transport: HttpTransport, code: str, delay: float, *,
+ metadata_root: Path | None = None,
+ prior_candidates: tuple[Candidate, ...] = (),
+ known_sizes: dict[str, tuple[int, int]] | None = None,
+ minimum_pixels: int = 0,
+ ) -> tuple[Candidate, tuple[int, int], bytes]:
+ # 来源一律记主机名。缓存、构造路径和官方页常指向同一个主机,记成多个名字
+ # 会让覆盖率统计凭空多出「渠道」。
+ evidence = cached_metadata(metadata_root, code)
+ live_evidence = MetadataEvidence()
+ candidates = list(prior_candidates) + list(evidence.candidates)
+ is_fc2 = code.upper().startswith("FC2-PPV-")
+ # 有成功快照时不重复打 r18;失败快照不算证据,仍允许联网刷新。
+ if not is_fc2 and "r18dev" not in evidence.sources:
+ live_evidence = r18_evidence(transport, code)
+ candidates += list(live_evidence.candidates)
+ time.sleep(delay)
+ # MGS 与 Prestige 都是 Prestige 集团的官方供给面。只在本地厂牌证据命中时
+ # 查询,避免把全库 960 个番号无差别打到两个站点。
+ if not is_fc2 and (_is_prestige(evidence) or _is_prestige(live_evidence)):
+ candidates += prestige_group_images(transport, code)
+ time.sleep(delay)
+ # 素人系番号按形状就能确定发行面是 MGS,不必先有元数据。等元数据的旧写法让
+ # 259LUXU / 300MIUM / 428SUKE 这批番号一次也没问过 MGS——而 MGS 一直有图。
+ elif not is_fc2 and (is_amateur_code(code) or "mgstage" in evidence.sources):
+ candidates += mgstage_images(transport, code)
+ time.sleep(delay)
+ candidates = _unique_candidates([
+ candidate for candidate in candidates
+ if (not THUMBNAIL.search(candidate.url) or FC2_HIRES.match(candidate.url))
+ and not is_cross_product_cover(code, candidate.url)
+ ])
+ # 升级模式已在成功日志中量过的精确 URL,若像素不大于当前本地图,就不再
+ # 发 Range 请求。其他 URL 和尺寸未知的候选仍完整探测,不改变择优语义。
+ known_sizes = known_sizes or {}
+ candidates = [
+ candidate for candidate in candidates
+ if candidate.url not in known_sizes
+ or known_sizes[candidate.url][0] * known_sizes[candidate.url][1]
+ > minimum_pixels
+ ]
+ if not candidates:
+ raise Unavailable("所有渠道都没有候选")
+
+ measured: list[tuple[int, Candidate, tuple[int, int]]] = []
+ for candidate in candidates:
+ try:
+ width, height = probe_size(transport, candidate)
+ except (Unavailable, UnidentifiedImageError, OSError, httpx.TransportError):
+ continue
+ finally:
+ time.sleep(delay)
+ if width >= MIN_WIDTH:
+ measured.append((width * height, candidate, (width, height)))
+ if not measured:
+ raise Unavailable("候选都不是可用封套")
+
+ for _pixels, winner, size in sorted(measured, key=lambda item: item[0], reverse=True):
+ try:
+ data = _fetch(transport, winner.url, referer=winner.referer,
+ limit=16 * 1024 * 1024)
+ except (Unavailable, httpx.TransportError):
+ continue
+ try:
+ with Image.open(io.BytesIO(data)) as image:
+ image.load()
+ actual_size = image.size
+ except (OSError, ValueError, Image.DecompressionBombError):
+ continue
+ if actual_size != size or actual_size[0] < MIN_WIDTH:
+ continue
+ if actual_size[0] * actual_size[1] <= minimum_pixels:
+ continue
+ return winner, actual_size, data
+ raise Unavailable("可用候选完整下载都失败")
+
+
+FIELDS = ("code", "result", "source", "width", "height", "kb", "url", "note")
+
+
+#: 判定为「所有渠道都没有」的落空,续跑时不必重来;连接类失败必须重试。
+#: 三态口径:一次超时不等于确认没有,不能靠它把番号永久踢出队列。
+TRANSIENT = re.compile(r"(Error|Timeout|SSL|Connect|Proxy|Protocol)", re.I)
+
+
+def settled_misses(log: Path) -> set[str]:
+ """上一轮已经把所有源探完、确认没有封套的番号。
+
+ 这类落空是最贵的:每条都要把全部候选源挨个试完才能确定。实测 194 条里
+ 150 条落空,重探一遍就是好几个小时,而结论不会变。
+ """
+ rows = logged_rows(log)
+ return {str(row.get("code") or "").strip() for row in rows
+ if row.get("result") == "未取得"
+ and not TRANSIENT.search(str(row.get("note") or ""))
+ and str(row.get("code") or "").strip()}
+
+
+def carried_rows(log: Path, keep: set[str]) -> list[dict]:
+ """把这轮跳过的番号的上轮记录原样带进新日志。"""
+ if not keep:
+ return []
+ return [{field: row.get(field, "") for field in FIELDS}
+ for row in logged_rows(log)
+ if str(row.get("code") or "").strip() in keep]
+
+
+def logged_rows(log: Path) -> list[dict]:
+ if not log.is_file():
+ return []
+ return read_rows(log)
+
+
+def restore_logged_successes(transport: HttpTransport, log: Path, root: Path,
+ delay: float = 0.0, guard: DiskGuard | None = None) -> dict:
+ """Re-download missing covers from the exact successful URLs already in the audit log.
+
+ This is intentionally narrower than a fresh scrape: it makes no discovery requests,
+ preserves the existing audit log and refuses an upstream image whose dimensions changed.
+ """
+ root.mkdir(parents=True, exist_ok=True)
+ restored = skipped = 0
+ failed: list[dict[str, str]] = []
+ # 恢复不做发现请求,所以它比抓取更容易把历史错图原样搬回本地:跨片封套在这里
+ # 也要挡掉,否则删掉错图重跑恢复只会把同一张再下一次。
+ successes = [row for row in logged_rows(log)
+ if row.get("result") == "取得" and row.get("code") and row.get("url")
+ and not is_cross_product_cover(str(row["code"]), str(row["url"]))]
+ for index, row in enumerate(successes, 1):
+ if guard is not None:
+ guard.check()
+ code = normalise_code_key(str(row["code"]))
+ target = root / f"{code}.jpg"
+ if target.is_file():
+ skipped += 1
+ continue
+ temporary = target.with_suffix(".restore.tmp")
+ try:
+ data = _fetch(transport, str(row["url"]), referer=_referer_for(str(row["url"])),
+ limit=16 * 1024 * 1024)
+ with Image.open(io.BytesIO(data)) as image:
+ size = image.size
+ image.verify()
+ expected = (int(row["width"]), int(row["height"]))
+ if size != expected or size[0] < MIN_WIDTH:
+ raise Unavailable(f"尺寸变化:日志 {expected[0]}x{expected[1]},当前 {size[0]}x{size[1]}")
+ temporary.write_bytes(data)
+ temporary.replace(target)
+ restored += 1
+ print(f"[{index}/{len(successes)}] 恢复 {code} {size[0]}x{size[1]}", flush=True)
+ # 与完整抓取同一条长跑边界:单张网络异常降级成失败记录,不能让余下恢复归零;
+ # KeyboardInterrupt 等 BaseException 仍会正常中断。
+ except Exception as exc:
+ failed.append({"code": code, "error": f"{type(exc).__name__}: {exc}"[:120]})
+ print(f"[{index}/{len(successes)}] 未恢复 {code}:{type(exc).__name__} {exc}",
+ flush=True)
+ finally:
+ temporary.unlink(missing_ok=True)
+ if delay:
+ time.sleep(delay)
+ return {"logged": len(successes), "restored": restored, "skipped": skipped,
+ "failed": failed}
+
+
+def pending(database: Path, root: Path, only_shaped: bool,
+ location: str | None = None, *, existing: bool = False,
+ max_width: int = 0, fc2_only: bool = False) -> list[str]:
+ connection = open_readonly(database)
+ try:
+ location_sql = " AND location=?" if location else ""
+ parameters: tuple[object, ...] = (location,) if location else ()
+ rows = connection.execute(
+ "SELECT code, COUNT(*) FROM asset WHERE medium='video' "
+ "AND code IS NOT NULL AND code<>''" + location_sql
+ + " GROUP BY code ORDER BY 2 DESC",
+ parameters,
+ ).fetchall()
+ finally:
+ connection.close()
+ result = []
+ for code, _count in rows:
+ if fc2_only and not str(code).upper().startswith("FC2"):
+ continue
+ # 判形态必须看原值。`normalise_code_key` 会补上分隔符,把 `RAIKUN325`
+ # (myfans 账号名,241 个文件)改写成 `RAIKUN-325` 并通过形态检查,
+ # 于是队列里全是查不到的账号名。判据与 web_contract 共用一份实现。
+ if only_shaped and not is_jav_code(str(code)):
+ continue
+ # FC2 在 r18/avsox/javbus 三源实测零命中(见 HANDOFF),本抓取器用的是
+ # 同一批来源。默认跳过 400 个必然落空的请求;`--all-codes` 仍可强制尝试。
+ if only_shaped and str(code).upper().startswith("FC2"):
+ continue
+ key = normalise_code_key(str(code))
+ target = root / f"{key}.jpg"
+ if existing:
+ if not target.is_file():
+ continue
+ try:
+ with Image.open(target) as image:
+ width = image.size[0]
+ except (UnidentifiedImageError, OSError):
+ width = 0
+ if max_width and width > max_width:
+ continue
+ result.append(key)
+ elif not target.is_file():
+ result.append(key)
+ return result
+
+
+def audit_state(database: Path, root: Path, log: Path) -> dict[str, object]:
+ """只读盘点当前 JAV 封面;用于批次前后使用同一统计口径。"""
+ connection = open_readonly(database)
+ try:
+ raw_codes = [str(row[0]) for row in connection.execute(
+ "SELECT DISTINCT code FROM asset WHERE medium='video' "
+ "AND code IS NOT NULL AND code<>''"
+ )]
+ finally:
+ connection.close()
+ codes = {
+ normalise_code_key(code) for code in raw_codes
+ if is_jav_code(code) and not code.upper().startswith("FC2")
+ }
+ dimensions: dict[str, tuple[int, int]] = {}
+ invalid: list[str] = []
+ for path in sorted(root.glob("*.jpg")) if root.is_dir() else []:
+ try:
+ with Image.open(path) as image:
+ dimensions[path.stem] = image.size
+ except (UnidentifiedImageError, OSError):
+ invalid.append(path.name)
+ widths = {
+ "le_800": sum(width <= 800 for width, _height in dimensions.values()),
+ "801_999": sum(801 <= width <= 999 for width, _height in dimensions.values()),
+ "1000_1199": sum(1000 <= width <= 1199
+ for width, _height in dimensions.values()),
+ "ge_1200": sum(width >= 1200 for width, _height in dimensions.values()),
+ }
+ rows = logged_rows(log)
+ return {
+ "jav_codes": len(codes),
+ "decoded_covers": len(dimensions),
+ "missing": len(codes - set(dimensions)),
+ "invalid": invalid,
+ "width_buckets": widths,
+ "log_successes": sum(row.get("result") == "取得" for row in rows),
+ "log_misses": sum(row.get("result") == "未取得" for row in rows),
+ "settled_misses": len(settled_misses(log)),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="按番号抓最高清的官方封套")
+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)
+ parser.add_argument("--out", type=Path, default=COVER_DIR)
+ parser.add_argument("--log", type=Path,
+ default=GENERATED_DIR / "cover-fetch-log.csv")
+ parser.add_argument(
+ "--metadata-root", type=Path, default=DEFAULT_METADATA_ROOT,
+ help="Javinizer-Go 原始快照目录;先离线复用成功证据,再补联网来源",
+ )
+ parser.add_argument("--fc2-metadata-log", type=Path, default=DEFAULT_FC2_METADATA_LOG,
+ help="fc2cmadb 文章封面证据,只对 --fc2-only 生效")
+ parser.add_argument("--limit", type=int, default=0)
+ parser.add_argument("--code", help="只处理一个已归一化番号,用于定点重试")
+ parser.add_argument("--delay", type=float, default=1.5)
+ parser.add_argument("--min-free", type=float, default=40.0,
+ help="系统盘最低可用 GiB;运行中每隔一段时间复查")
+ parser.add_argument("--disk-check-secs", type=float, default=20.0)
+ parser.add_argument("--location",
+ help="只抓指定来源的番号封套,例如 pikpak;封套仍按番号共享")
+ parser.add_argument("--retry-misses", action="store_true",
+ help="连上轮确认没有封套的番号也重探一遍")
+ parser.add_argument("--restore-successes", action="store_true",
+ help="只按成功日志中的原 URL 恢复缺失封套,不重新探测来源")
+ parser.add_argument("--upgrade-existing", action="store_true",
+ help="重探已有封套;只有候选像素更多时才原子替换")
+ parser.add_argument("--upgrade-max-width", type=int, default=0,
+ help="升级模式只重探不超过此宽度的已有封套;0 表示全部")
+ parser.add_argument("--all-codes", action="store_true",
+ help="连 FC2/日期番号一起试;默认只跑片商与素人形态")
+ parser.add_argument("--fc2-only", action="store_true",
+ help="只用 fc2cmadb 已存证据抓 FC2 官方 CDN 封面")
+ parser.add_argument("--audit", action="store_true",
+ help="只读输出封面数量、缺失、损坏和尺寸分布,不联网不写文件")
+ return parser
+
+
+def _write_log(path: Path, rows: list[dict]) -> None:
+ """每条都落盘:这个任务要跑三四个小时,只在结束时写等于全程看不见进度。"""
+ write_rows(path, FIELDS, rows)
+
+
+def _renew_transport_after_error(transport: HttpTransport,
+ error: Exception) -> HttpTransport:
+ """永久 transport 失败后丢弃连接池,避免后续番号连续 PoolTimeout。"""
+ if not isinstance(error, httpx.TransportError):
+ return transport
+ if isinstance(transport, HostLimitedTransport):
+ transport.renew()
+ return transport
+ transport.close()
+ return HttpxTransport()
+
+
+def _replace_log_row(rows: list[dict], code: str, replacement: dict) -> None:
+ """一个番号只保留一条最新成功证据,不扰动其他番号。"""
+ rows[:] = [row for row in rows
+ if str(row.get("code") or "").strip() != code]
+ rows.append({field: replacement.get(field, "") for field in FIELDS})
+
+
+def run(args: argparse.Namespace) -> int:
+ if args.audit:
+ print(json.dumps(audit_state(args.db, args.out, args.log),
+ ensure_ascii=False, indent=2))
+ return 0
+ if args.upgrade_max_width < 0:
+ print("[stop] --upgrade-max-width 不能小于 0")
+ return 2
+ if args.upgrade_max_width and not args.upgrade_existing:
+ print("[stop] --upgrade-max-width 只能与 --upgrade-existing 一起使用")
+ return 2
+ if args.upgrade_existing and args.retry_misses:
+ print("[stop] --upgrade-existing 与 --retry-misses 不能同时使用")
+ return 2
+ if args.restore_successes and args.upgrade_existing:
+ print("[stop] --restore-successes 与 --upgrade-existing 不能同时使用")
+ return 2
+ if args.fc2_only and args.all_codes:
+ print("[stop] --fc2-only 与 --all-codes 不能同时使用")
+ return 2
+ args.out.mkdir(parents=True, exist_ok=True)
+ guard = DiskGuard(system_volume(), args.min_free, args.disk_check_secs)
+ try:
+ free_gb = guard.check(force=True)
+ except JobPolicyError as exc:
+ print(f"[stop] {exc}")
+ return exc.exit_code
+ print(f"系统盘可用 {free_gb:.1f} GiB,运行期阈值 {args.min_free:.1f} GiB")
+ if args.restore_successes:
+ transport = HttpxTransport()
+ try:
+ result = restore_logged_successes(
+ transport, args.log, args.out, args.delay, guard=guard,
+ )
+ except JobPolicyError as exc:
+ print(f"[stop] {exc}")
+ return exc.exit_code
+ finally:
+ transport.close()
+ print(f"成功日志 {result['logged']},恢复 {result['restored']},"
+ f"已存在 {result['skipped']},失败 {len(result['failed'])} → {args.out}")
+ return 2 if result["failed"] else 0
+
+ todo = pending(
+ args.db, args.out, not args.all_codes and not args.fc2_only, args.location,
+ existing=args.upgrade_existing, max_width=args.upgrade_max_width,
+ fc2_only=args.fc2_only,
+ )
+ if args.code:
+ wanted = normalise_code_key(args.code)
+ todo = [code for code in todo if code == wanted]
+ skipped = set()
+ if not args.upgrade_existing and not args.retry_misses:
+ skipped = settled_misses(args.log) & set(todo)
+ todo = [code for code in todo if code not in skipped]
+ if args.limit:
+ todo = todo[:args.limit]
+ selected = set(todo)
+ if args.upgrade_existing:
+ width_note = (f",当前宽度不超过 {args.upgrade_max_width}"
+ if args.upgrade_max_width else "")
+ print(f"待重探已有封套 {len(todo)} 个{width_note};只在像素更多时替换")
+ else:
+ print(f"待抓番号 {len(todo)} 个(已落盘的跳过,"
+ f"上轮确认没有的跳过 {len(skipped)} 个,--retry-misses 可重试)")
+
+ transport = HostLimitedTransport(SourceTransport(SECRETS_DIR), args.delay)
+ # 日志是整份重写:这轮只跑 pikpak 或只跑 --limit 时,未选中的旧记录也必须保留;
+ # 只删除本轮会重新生成的番号。否则一次来源小批次就会抹掉其他来源的复核证据。
+ previous_rows = logged_rows(args.log)
+ fc2_candidates = fc2_cover_candidates(args.fc2_metadata_log) if args.fc2_only else {}
+ rows: list[dict] = [
+ {field: row.get(field, "") for field in FIELDS}
+ for row in previous_rows
+ if args.upgrade_existing
+ or str(row.get("code") or "").strip() not in selected
+ ]
+ stats = {"ok": 0, "miss": 0, "kept": 0}
+ stopped: JobPolicyError | None = None
+ try:
+ for index, code in enumerate(todo, 1):
+ try:
+ guard.check()
+ except JobPolicyError as exc:
+ stopped = exc
+ print(f"[stop] {exc}", flush=True)
+ break
+ try:
+ target = args.out / f"{code}.jpg"
+ current_size = (0, 0)
+ if target.exists():
+ try:
+ with Image.open(target) as image:
+ current_size = image.size
+ except (UnidentifiedImageError, OSError):
+ pass
+ previous = logged_success_evidence(previous_rows, code)
+ prior = tuple(candidate for candidate in (
+ fc2_candidates.get(code), previous[0] if previous is not None else None,
+ ) if candidate is not None)
+ known_sizes = ({previous[0].url: previous[1]}
+ if previous is not None else {})
+ winner, (width, height), data = best_cover(
+ transport, code, 0,
+ metadata_root=args.metadata_root, prior_candidates=prior,
+ known_sizes=known_sizes,
+ minimum_pixels=current_size[0] * current_size[1],
+ )
+ # 网络异常必须按条吞掉。一次 SSL 抖动
+ # (httpx.ConnectError: UNEXPECTED_EOF_WHILE_READING)此前直接打死了
+ # 整个三小时的任务,而且死得很安静——日志停在半路,看起来像跑完了。
+ # 长跑批处理不能因为一个番号的连接问题就整体退出。
+ # `Exception` 已涵盖 Unavailable 与网络异常;Ctrl-C 是 BaseException
+ # 的另一支,不会被这里吞掉,仍能正常中断。
+ except Exception as exc:
+ transport = _renew_transport_after_error(transport, exc)
+ stats["miss"] += 1
+ if args.upgrade_existing:
+ print(f"[{index}/{len(todo)}] 保留 {code}:重探失败 "
+ f"{type(exc).__name__} {exc}", flush=True)
+ else:
+ rows.append({"code": code, "result": "未取得", "source": "",
+ "width": "", "height": "", "kb": "", "url": "",
+ "note": f"{type(exc).__name__}: {exc}"[:80]})
+ print(f"[{index}/{len(todo)}] 未取得 {code}:"
+ f"{type(exc).__name__} {exc}", flush=True)
+ else:
+ if (args.upgrade_existing
+ and width * height <= current_size[0] * current_size[1]):
+ stats["kept"] += 1
+ print(f"[{index}/{len(todo)}] 保留 {code} "
+ f"{current_size[0]}x{current_size[1]} >= {width}x{height}",
+ flush=True)
+ else:
+ temporary = target.with_suffix(".tmp")
+ temporary.write_bytes(data)
+ try:
+ temporary.replace(target)
+ finally:
+ temporary.unlink(missing_ok=True)
+ stats["ok"] += 1
+ row = {"code": code, "result": "取得", "source": winner.source,
+ "width": width, "height": height, "kb": len(data) // 1024,
+ "url": winner.url, "note": ""}
+ if args.upgrade_existing:
+ _replace_log_row(rows, code, row)
+ else:
+ rows.append(row)
+ verb = "升级" if args.upgrade_existing else "取得"
+ print(f"[{index}/{len(todo)}] {verb} {code} {width}x{height} "
+ f"{len(data)//1024} KB <- {winner.source}", flush=True)
+ # 落空的行也要落盘。这句只放在取得分支里的话,连续落空时 CSV 整段不动;
+ # 被强杀时 finally 也来不及跑,那一串判定就白做了——而「查不到」恰恰
+ # 是最贵的一类:每条都要把所有候选源挨个探完才能确定。
+ _write_log(args.log, rows)
+ finally:
+ transport.close()
+ _write_log(args.log, rows)
+
+ if args.upgrade_existing:
+ print(f"\n升级 {stats['ok']},保留 {stats['kept']},"
+ f"重探失败但保留原图 {stats['miss']} → {args.out}")
+ else:
+ print(f"\n取得 {stats['ok']},未取得 {stats['miss']} → {args.out}")
+ print(f"逐条记录 → {args.log}")
+ return stopped.exit_code if stopped is not None else 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ return run(build_parser().parse_args(argv))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/peach/page_cache.py b/src/peach/page_cache.py
index 3a7fcd13e..a50d632be 100644
--- a/src/peach/page_cache.py
+++ b/src/peach/page_cache.py
@@ -16,6 +16,7 @@ from pathlib import Path
import httpx
from .http import HttpRequest, HttpxTransport
+from .scripting import RateLimiter
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
@@ -41,19 +42,17 @@ class Site:
backoff: float = 2.0):
self.cache_dir, self.interval, self.timeout, self.refresh = cache_dir, interval, timeout, refresh
self.transport = transport or HttpxTransport(
- httpx.Client(trust_env=via_proxy, follow_redirects=True, cookies=cookies or {}))
+ httpx.Client(trust_env=via_proxy, follow_redirects=True, cookies=cookies or {}),
+ owns_client=True)
self.retries, self.backoff = max(0, retries), backoff
- self._last = 0.0
+ self._limiter = RateLimiter(interval)
self.fetched = self.cached = self.retried = 0
def request(self, method: str, url: str, body: bytes | None = None,
headers: dict[str, str] | None = None) -> str:
response = None
for attempt in range(self.retries + 1):
- wait = self.interval - (time.monotonic() - self._last)
- if wait > 0:
- time.sleep(wait)
- self._last = time.monotonic()
+ self._limiter.wait()
try:
response = self.transport(
HttpRequest(method, url, {"User-Agent": USER_AGENT, **(headers or {})},
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index dc46317ba..48dbce604 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -767,6 +767,7 @@ def peach_logo():
@router.api_route("/data-cleanup", methods=["GET", "HEAD"])
@router.api_route("/duplicates", methods=["GET", "HEAD"])
@router.api_route("/quality-goals", methods=["GET", "HEAD"])
[email protected]_route("/scraping", methods=["GET", "HEAD"])
@router.api_route("/resource-sync", methods=["GET", "HEAD"])
@router.api_route("/follow", methods=["GET", "HEAD"])
@router.api_route("/follow-manage", methods=["GET", "HEAD"])
diff --git a/src/peach/scraping_access.py b/src/peach/scraping_access.py
new file mode 100644
index 000000000..f79cf28e5
--- /dev/null
+++ b/src/peach/scraping_access.py
@@ -0,0 +1,235 @@
+"""采集来源的本机设置、域内 Cookie 和按来源连接策略。"""
+from __future__ import annotations
+
+import http.cookiejar
+import hashlib
+from http.cookies import SimpleCookie, CookieError
+import json
+import os
+from pathlib import Path
+import tempfile
+import threading
+import time
+from email.utils import parsedate_to_datetime
+from urllib.parse import urlsplit, urljoin
+
+import httpx
+
+from .follow_secrets import CredentialStore
+from .http import HttpRequest, HttpxTransport
+from .scripting import USER_AGENT, host_under, hostname_of
+
+
+SOURCES = {
+ "r18dev": {"label": "R18.dev", "domains": ("r18.dev",), "login": "https://r18.dev/"},
+ "dmm": {"label": "DMM / FANZA", "domains": ("dmm.co.jp", "dmm.com"), "login": "https://www.dmm.co.jp/"},
+ "prestige": {"label": "Prestige", "domains": ("prestige-av.com",), "login": "https://www.prestige-av.com/"},
+ "mgstage": {"label": "MGStage", "domains": ("mgstage.com",), "login": "https://www.mgstage.com/"},
+ "fc2cmadb": {"label": "FC2 CMADB", "domains": ("fc2cmadb.com",), "login": "https://fc2cmadb.com/", "cookie": True},
+ "instagram": {"label": "Instagram", "domains": ("instagram.com", "cdninstagram.com"), "login": "https://www.instagram.com/accounts/login/", "cookie": True},
+}
+_LOCK = threading.RLock()
+
+
+class SourcePaused(RuntimeError):
+ """来源冷却期内停止请求,保留已有图像。"""
+
+
+def source_for(url: str) -> str | None:
+ return next((name for name, spec in SOURCES.items()
+ if host_under(hostname_of(url), spec["domains"])), None)
+
+
+def _store(root: Path) -> CredentialStore:
+ return CredentialStore(root)
+
+
+def values_for(root: Path, source: str) -> dict[str, str]:
+ if source not in SOURCES:
+ raise ValueError("未知采集来源")
+ credential = _store(root).load("scraping-" + source)
+ return dict(credential.values) if credential else {}
+
+
+def cookie_jar(values: dict[str, str], source: str) -> http.cookiejar.CookieJar:
+ """文本导入复用标准库;过期项、异域项和 CDN 会话项不参与请求。"""
+ domain = urlsplit(SOURCES[source]["login"]).hostname or ""
+ domain = domain.removeprefix("www.")
+ jar = http.cookiejar.MozillaCookieJar()
+ text = values.get("cookies_text", "")
+ if text:
+ path = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", delete=False) as handle:
+ path = handle.name
+ handle.write(text)
+ jar.load(path, ignore_discard=True, ignore_expires=False)
+ except (OSError, http.cookiejar.LoadError) as exc:
+ raise ValueError("Cookie 文件须为 Netscape 文本格式") from exc
+ finally:
+ if path:
+ Path(path).unlink(missing_ok=True)
+ for cookie in list(jar):
+ if not host_under(cookie.domain.lstrip(".").lower(), (domain,)):
+ jar.clear(cookie.domain, cookie.path, cookie.name)
+ elif values.get("cookie"):
+ text = values["cookie"]
+ if "\r" in text or "\n" in text:
+ raise ValueError("请粘贴一行 Cookie 请求头")
+ parsed = SimpleCookie()
+ try:
+ parsed.load(text)
+ except CookieError as exc:
+ raise ValueError("Cookie 请求头格式无效") from exc
+ for name, item in parsed.items():
+ jar.set_cookie(http.cookiejar.Cookie(
+ 0, name, item.value, None, False, domain, True, False,
+ "/", True, True, None, True, None, None, {}, False))
+ return jar
+
+
+def save(root: Path, source: str, body: dict) -> dict:
+ with _LOCK:
+ values = values_for(root, source)
+ mode = body.get("network", values.get("network", "environment"))
+ if mode not in {"direct", "environment", "proxy"}:
+ raise ValueError("请选择来源连接方式")
+ proxy = body.get("proxy") or values.get("proxy", "")
+ if mode == "proxy":
+ parsed = urlsplit(proxy)
+ if parsed.scheme not in {"http", "https", "socks5", "socks5h"} or not parsed.hostname:
+ raise ValueError("请填写有效的 HTTP 或 SOCKS 代理地址")
+ values["network"] = mode
+ values["proxy"] = proxy if mode == "proxy" else ""
+ if body.get("revoke"):
+ values.pop("cookie", None)
+ values.pop("cookies_text", None)
+ elif body.get("cookie") or body.get("cookies_text"):
+ if not SOURCES[source].get("cookie"):
+ raise ValueError("此来源不接受登录 Cookie")
+ if body.get("cookie") and body.get("cookies_text"):
+ raise ValueError("Cookie 粘贴与文件导入只选一种")
+ supplied = {name: str(body.get(name) or "") for name in ("cookie", "cookies_text")}
+ if sum(map(len, supplied.values())) > 256 * 1024:
+ raise ValueError("Cookie 文本超过 256 KiB")
+ if not list(cookie_jar(supplied, source)):
+ raise ValueError("未找到该来源尚未过期的 Cookie")
+ values.update(supplied)
+ path = _store(root).path_for("scraping-" + source)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = None
+ try:
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent,
+ delete=False) as handle:
+ temporary = Path(handle.name)
+ json.dump(values, handle, ensure_ascii=False)
+ if os.name != "nt":
+ temporary.chmod(0o600)
+ temporary.replace(path)
+ finally:
+ if temporary:
+ temporary.unlink(missing_ok=True)
+ return describe(root, source)
+
+
+def describe(root: Path, source: str) -> dict:
+ values = values_for(root, source)
+ return {"source": source, "label": SOURCES[source]["label"],
+ "login": SOURCES[source]["login"], "accepts_cookie": bool(SOURCES[source].get("cookie")),
+ "network": values.get("network", "environment"),
+ "proxy_saved": bool(values.get("proxy")),
+ "cookie_saved": bool(values.get("cookie") or values.get("cookies_text"))}
+
+
+def client_for(root: Path, source: str, *, session: bool = False, **kwargs) -> httpx.Client:
+ values = values_for(root, source)
+ mode = values.get("network", "environment")
+ options = {"trust_env": mode == "environment", "follow_redirects": True,
+ "headers": {"User-Agent": USER_AGENT}}
+ if mode == "proxy":
+ options["proxy"] = values["proxy"]
+ if session:
+ options["cookies"] = cookie_jar(values, source)
+ options.update(kwargs)
+ return httpx.Client(**options)
+
+
+class SourceTransport:
+ """公开采集按来源复用连接池;登录会话由特定来源消费者显式建立。"""
+
+ def __init__(self, secrets_root: Path, *, max_requests: int = 0,
+ max_bytes: int = 0, max_seconds: float = 0):
+ self.root = secrets_root
+ self.transports: dict[str | None, HttpxTransport] = {}
+ self.max_requests, self.max_bytes = max_requests, max_bytes
+ self.deadline = time.monotonic() + max_seconds if max_seconds else 0
+ self.requests = self.bytes = 0
+
+ def __call__(self, request: HttpRequest, timeout: float, max_bytes: int):
+ for _ in range(6):
+ response = self._request(request, timeout, max_bytes)
+ if response.status not in {301, 302, 303, 307, 308} or not response.headers.get("location"):
+ return response
+ target = urljoin(request.url, response.headers["location"])
+ if urlsplit(target).scheme != "https":
+ raise ValueError("采集重定向必须使用 HTTPS")
+ cross_origin = urlsplit(target).netloc != urlsplit(request.url).netloc
+ headers = {k: v for k, v in request.headers.items()
+ if not cross_origin or k.lower() not in {"cookie", "authorization", "host"}}
+ request = HttpRequest("GET" if response.status == 303 else request.method,
+ target, headers, None if response.status == 303 else request.body)
+ raise ValueError("采集重定向次数超过上限")
+
+ def _request(self, request: HttpRequest, timeout: float, max_bytes: int):
+ source = source_for(request.url)
+ if self.max_requests and self.requests >= self.max_requests:
+ raise SourcePaused("请求预算已用完;已有图片保留")
+ if self.deadline:
+ timeout = min(timeout, self.deadline - time.monotonic())
+ if timeout <= 0:
+ raise SourcePaused("采集时间预算已用完;已有图片保留")
+ if self.max_bytes:
+ remaining = self.max_bytes - self.bytes
+ if remaining <= 0:
+ raise SourcePaused("下载预算已用完;已有图片保留")
+ max_bytes = min(max_bytes, remaining - 1)
+ key = source or hashlib.sha256(hostname_of(request.url).encode()).hexdigest()
+ cooldown = self.root / ("scraping-" + key + ".cooldown.json")
+ try:
+ until = float(json.loads(cooldown.read_text(encoding="utf-8"))["until"])
+ except (OSError, ValueError, KeyError, TypeError):
+ until = 0
+ if until > time.time():
+ raise SourcePaused("来源正在冷却,请稍后重试;已有图片保留")
+ if source not in self.transports:
+ client = (client_for(self.root, source, follow_redirects=False) if source else
+ httpx.Client(follow_redirects=False, headers={"User-Agent": USER_AGENT}))
+ self.transports[source] = HttpxTransport(client, owns_client=True)
+ self.requests += 1
+ try:
+ response = self.transports[source](request, timeout, max_bytes)
+ except httpx.HTTPError as exc:
+ raise httpx.TransportError("来源连接未取得,请检查该来源的网络设置") from None
+ self.bytes += len(response.body)
+ if response.status == 429:
+ retry = response.headers.get("retry-after", "")
+ try:
+ until = time.time() + max(0, int(retry))
+ except ValueError:
+ try:
+ until = parsedate_to_datetime(retry).timestamp()
+ except (ValueError, TypeError, OverflowError):
+ until = time.time() + 900
+ with _LOCK:
+ cooldown.parent.mkdir(parents=True, exist_ok=True)
+ cooldown.write_text(json.dumps({"until": max(until, time.time() + 1)}), encoding="utf-8")
+ raise SourcePaused("来源限流,已记录冷却时间;已有图片保留")
+ return response
+
+ def renew(self):
+ self.close()
+
+ def close(self):
+ for transport in self.transports.values():
+ transport.close()
+ self.transports.clear()
diff --git a/src/peach/scripting.py b/src/peach/scripting.py
index 271a6f8e5..c3e728c38 100644
--- a/src/peach/scripting.py
+++ b/src/peach/scripting.py
@@ -158,8 +158,10 @@ class HostLimiter:
"""
def __init__(self, intervals: dict[str, float], *,
- clock=time.monotonic, sleeper=time.sleep):
+ clock=time.monotonic, sleeper=time.sleep, default_interval: float = 0):
self._intervals = dict(intervals)
+ self._default_interval = max(0.0, default_interval)
+ self._registry_lock = threading.Lock()
self._locks = {host: threading.Lock() for host in self._intervals}
self._next = {host: 0.0 for host in self._intervals}
self._clock = clock
@@ -167,7 +169,14 @@ class HostLimiter:
def _key(self, url: str) -> str | None:
host = hostname_of(url)
- return next((h for h in self._intervals if host_under(host, (h,))), None)
+ with self._registry_lock:
+ key = next((h for h in self._intervals if host_under(host, (h,))), None)
+ if key is None and self._default_interval > 0:
+ key = host
+ self._intervals[key] = self._default_interval
+ self._locks[key] = threading.Lock()
+ self._next[key] = 0.0
+ return key
def wait(self, url: str) -> None:
key = self._key(url)
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index 17da162ac..4506032ce 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -52,6 +52,7 @@ from .web_playlists import q_playlist, q_playlists, w_playlist
from .web_resource_sync import w_purge_missing, w_resource_sync_apply, w_resource_sync_scan
from .web_review import q_review, w_review_auto_apply, w_review_decision
from .web_settings import q_settings, w_settings
+from .web_scraping import q_scraping, w_scraping_settings, w_scraping_check, w_scraping_cover
from .web_state import WebContract
from .web_stats import (
q_quality_goals,
@@ -172,6 +173,8 @@ def _post_empty_trash(contract, _body):
GET_HANDLERS = {
+ "/api/scraping": q_scraping,
+ "/api/scraping/cover": lambda contract, args: contract.scraping_cover_job.snapshot() or {"status": "idle"},
"/api/settings": q_settings,
"/api/follow": q_follow,
"/api/follow/credentials": q_follow_credentials,
@@ -206,6 +209,9 @@ GET_HANDLERS = {
}
POST_HANDLERS = {
+ "/api/scraping/settings": w_scraping_settings,
+ "/api/scraping/cover": w_scraping_cover,
+ "/api/scraping/check": w_scraping_check,
"/api/follow/check": w_follow_check,
"/api/follow/schedule": w_follow_schedule,
"/api/follow/source": w_follow_source,
@@ -246,6 +252,7 @@ POST_HANDLERS = {
#: 不该拦它们——「查找」只联网、「存凭据」只写本机 secrets 文件,都不碰账本。
#: 追更的「查找」在只读端被拦成 409 是实测踩到的。
READ_ONLY_POST_ROUTES = frozenset({
+ "/api/scraping/settings", "/api/scraping/check",
"/api/follow/resolve", "/api/follow/credential",
"/api/taste/refresh", "/api/taste/source", "/api/resource-sync/scan",
"/api/links/check", "/api/data-cleanup/empty-folders",
diff --git a/src/peach/web_scraping.py b/src/peach/web_scraping.py
new file mode 100644
index 000000000..90083f36f
--- /dev/null
+++ b/src/peach/web_scraping.py
@@ -0,0 +1,122 @@
+"""采集设置与有界来源连接检查;凭据只写本机。"""
+import io
+import hashlib
+import json
+import time
+import threading
+
+from PIL import Image
+
+from .http import HttpRequest
+from .scraping_access import SOURCES, SourceTransport, describe, save
+
+_COVER_LOCK = threading.Lock()
+
+
+def w_scraping_cover(contract, body):
+ """仅处理用户指定且馆藏命中的番号;完整解码后才允许升级封面。"""
+ from .metadata import validate_provider_code
+ code = validate_provider_code(str(body.get("code", "")))
+ with contract.database.read_connection() as connection:
+ if not connection.execute("SELECT 1 FROM asset WHERE code=? LIMIT 1", (code,)).fetchone():
+ raise ValueError("馆藏未找到这个番号")
+ return contract.scraping_cover_job.start_result(lambda: _fetch_cover(contract, code))
+
+
+def _fetch_cover(contract, code):
+ from .jav_cover_fetch import (best_cover, HostLimitedTransport, Unavailable,
+ fc2_cover_candidates, logged_success_evidence)
+ from .review_csv import read_rows
+ target = contract.cover_root / (code + ".jpg")
+ sidecar = target.with_suffix(".scraping.json")
+ try:
+ previous = json.loads(sidecar.read_text(encoding="utf-8"))
+ if (time.time() - float(previous["checked_at"]) < 86400 and target.is_file()
+ and hashlib.sha256(target.read_bytes()).hexdigest() == previous["raw_sha256"]):
+ return {"ok": True, "code": code, "result": "已复用本机封面", **{
+ key: previous[key] for key in ("width", "height", "raw_sha256")}}
+ except (OSError, ValueError, KeyError, TypeError):
+ pass
+ raw = SourceTransport(contract.follow_secrets_root, max_requests=80,
+ max_bytes=32 * 1024 * 1024, max_seconds=180)
+ transport = HostLimitedTransport(raw, 1.5)
+ try:
+ minimum = 0
+ if target.is_file():
+ with Image.open(target) as image:
+ minimum = image.width * image.height
+ fc2 = fc2_cover_candidates(contract.candidate_root / "fc2-candidate-log.csv").get(code)
+ log = contract.candidate_root / "cover-fetch-log.csv"
+ previous = logged_success_evidence(read_rows(log), code) if log.is_file() else None
+ prior = tuple(item for item in (fc2, previous[0] if previous else None) if item)
+ candidate, size, data = best_cover(transport, code, 0, minimum_pixels=minimum,
+ prior_candidates=prior,
+ metadata_root=contract.follow_sources_root / "metadata" / "javinizer-go")
+ with _COVER_LOCK:
+ if target.is_file():
+ with Image.open(target) as image:
+ if image.width * image.height >= size[0] * size[1]:
+ return {"ok": True, "code": code, "result": "已保留更清晰的本机封面"}
+ target.parent.mkdir(parents=True, exist_ok=True)
+ temporary = target.with_suffix(".scraping.tmp")
+ try:
+ temporary.write_bytes(data)
+ temporary.replace(target)
+ finally:
+ temporary.unlink(missing_ok=True)
+ evidence = {"code": code, "width": size[0], "height": size[1],
+ "source": candidate.source, "source_url": candidate.url,
+ "raw_sha256": hashlib.sha256(data).hexdigest(),
+ "installed_sha256": hashlib.sha256(data).hexdigest(),
+ "checked_at": time.time(), "resolver": "peach-jav-cover-v1"}
+ sidecar.write_text(json.dumps(evidence, ensure_ascii=False), encoding="utf-8")
+ return {"ok": True, "code": code, "result": "高清封面已保存", "width": size[0],
+ "height": size[1], "requests": raw.requests, "bytes": raw.bytes}
+ except Unavailable:
+ return {"ok": False, "code": code, "error": "未取得可升级封面,已有图片保留。高清来源可能需要代理。"}
+ except Exception as exc:
+ return {"ok": False, "code": code, "error": "采集未取得,已有图片保留。请检查来源连接与冷却状态。",
+ "error_type": type(exc).__name__}
+ finally:
+ transport.close()
+
+
+def q_scraping(contract, _args):
+ return {"sources": [describe(contract.follow_secrets_root, source) for source in SOURCES
+ if source != "instagram"],
+ "instagram_status": "Instagram 自动头像定位尚待独立登录会话验证"}
+
+
+def w_scraping_settings(contract, body):
+ return {"ok": True, "saved": save(contract.follow_secrets_root, str(body.get("source", "")), body)}
+
+
+def w_scraping_check(contract, body):
+ source = str(body.get("source", ""))
+ if source not in SOURCES:
+ raise ValueError("未知采集来源")
+ targets = [("来源页面", SOURCES[source]["login"])]
+ if source == "dmm":
+ targets.append(("高清图片 CDN", "https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/gyan00017/gyan00017pl.jpg"))
+ results = []
+ transport = SourceTransport(contract.follow_secrets_root)
+ try:
+ for label, url in targets:
+ result = {"label": label, "ok": False}
+ try:
+ response = transport(HttpRequest("GET", url, {"Range": "bytes=0-65535"}), 10, 65536)
+ result.update(status=response.status, bytes=len(response.body),
+ ok=response.status in {200, 206})
+ if label == "高清图片 CDN" and result["ok"]:
+ with Image.open(io.BytesIO(response.body)) as image:
+ result["width"], result["height"] = image.size
+ if not result["ok"]:
+ result["message"] = ("来源要求登录或验证,请在官网完成后重试。"
+ if response.status in {401, 403} else "来源暂不可用,请稍后重试。")
+ except Exception as exc:
+ result.update(ok=False, message="连接未取得;此来源可能需要代理,请检查来源连接方式。",
+ error_type=type(exc).__name__)
+ results.append(result)
+ finally:
+ transport.close()
+ return {"ok": True, "results": results, "session_verified": False}
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index 3eadd4cc0..ecd05f57e 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -134,6 +134,7 @@ class WebContract:
self.follow_resolve_job = BackgroundJob("PeachFollowResolveJob")
self.taste_refresh_job = BackgroundJob("PeachTasteRefreshJob")
self.link_prune_job = BackgroundJob("PeachLinkPruneJob")
+ self.scraping_cover_job = BackgroundJob("PeachScrapingCoverJob")
self.resource_apply_job = BackgroundJob("PeachResourceApplyJob")
self.follow_scheduler = None
# 两块后台任务的锁、状态和线程都归 BackgroundJob 管,契约上只留这两个字段。
@@ -201,6 +202,7 @@ class WebContract:
"""
self.resource_scan.stop()
self.follow_job.stop()
+ self.scraping_cover_job.stop()
self.follow_resolve_job.stop()
self.taste_refresh_job.stop()
self.link_prune_job.stop()
diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.py
index ade9f83ac..256ba3e0e 100644
--- a/tests/test_dependency_policy.py
+++ b/tests/test_dependency_policy.py
@@ -30,6 +30,7 @@ class DependencyPolicyTests(unittest.TestCase):
def test_every_imported_external_module_has_a_declared_owner(self):
owners = {
+ "tldextract": "tldextract",
"AppKit": "pyobjc-framework-Cocoa",
"PIL": "pillow",
"PyObjCTools": "pyobjc-framework-Cocoa",
diff --git a/tests/test_jav_covers.py b/tests/test_jav_covers.py
index 066ebfba7..18bdbe127 100644
--- a/tests/test_jav_covers.py
+++ b/tests/test_jav_covers.py
@@ -12,7 +12,7 @@ from unittest.mock import call, patch
from PIL import Image
-SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "fetch_jav_covers.py"
+SCRIPT = Path(__file__).resolve().parents[1] / "src" / "peach" / "jav_cover_fetch.py"
_spec = importlib.util.spec_from_file_location("fetch_jav_covers", SCRIPT)
covers = importlib.util.module_from_spec(_spec)
sys.modules["fetch_jav_covers"] = covers
@@ -32,6 +32,15 @@ class _Response:
class FetchRetryTests(unittest.TestCase):
+ def test_full_download_dimensions_must_match_probe_and_exceed_existing_image(self):
+ candidate = covers.Candidate("test", "https://example.test/large.jpg")
+ with patch.object(covers, "cached_metadata", return_value=covers.MetadataEvidence()), \
+ patch.object(covers, "probe_size", return_value=(1600, 1000)), \
+ patch.object(covers, "_fetch", return_value=jpeg(800, 500)):
+ with self.assertRaises(covers.Unavailable):
+ covers.best_cover(lambda *args: None, "FC2-PPV-123456", 0,
+ prior_candidates=(candidate,), minimum_pixels=1000 * 700)
+
def test_transient_transport_errors_use_the_project_backoff_window(self):
attempts = 0
@@ -257,15 +266,15 @@ class OfficialSourceTests(unittest.TestCase):
}), "ABW-232")
self.assertEqual([candidate.url for candidate in candidates], [image])
- def test_prestige_hit_skips_the_smaller_mgstage_fallback(self):
+ def test_prestige_and_mgstage_both_participate_in_quality_comparison(self):
official = [covers.candidate_for(
"https://www.prestige-av.com/api/media/a/package.jpg"
)]
with patch.object(covers, "prestige_images", return_value=official), \
- patch.object(covers, "mgstage_images") as mgstage:
+ patch.object(covers, "mgstage_images", return_value=[]) as mgstage:
actual = covers.prestige_group_images(object(), "ABW-232")
self.assertEqual(actual, official)
- mgstage.assert_not_called()
+ mgstage.assert_called_once_with(unittest.mock.ANY, "ABW-232")
def test_prestige_miss_uses_mgstage_as_the_fallback(self):
fallback = [covers.candidate_for(
@@ -384,6 +393,18 @@ class CrossProductCoverTests(unittest.TestCase):
class BestCoverTests(unittest.TestCase):
+ def test_cold_cache_uses_live_maker_evidence_to_find_hd_sources(self):
+ large = "https://www.prestige-av.com/api/media/fixture.jpg"
+ pages = {covers.R18_DETAIL.format(code="ABW-232"): (200, json.dumps({
+ "content_id": "118abw232", "maker": {"name": "Prestige"},
+ }).encode()), large: (200, jpeg(1024, 690))}
+ with patch.object(covers, "prestige_group_images", return_value=[covers.candidate_for(large)]) as group:
+ candidate, size, data = covers.best_cover(transport_for(pages), "ABW-232", 0)
+ group.assert_called_once()
+ self.assertEqual(size, (1024, 690))
+ self.assertEqual(candidate.url, large)
+ self.assertEqual(data, pages[large][1])
+
def test_known_same_size_url_is_not_probed_during_upgrade(self):
known = "https://pics.dmm.co.jp/mono/movie/adult/118abw232/118abw232pl.jpg"
larger = "https://awsimgsrc.dmm.com/dig/mono/movie/118abw232/118abw232pl.jpg"
diff --git a/tests/test_link_rediscovery.py b/tests/test_link_rediscovery.py
index d2b66be7c..44d5d9d58 100644
--- a/tests/test_link_rediscovery.py
+++ b/tests/test_link_rediscovery.py
@@ -18,6 +18,12 @@ def load_module():
class SameSiteTests(unittest.TestCase):
+ def test_private_suffix_tenants_are_independent(self):
+ module = load_module()
+ self.assertFalse(module.same_site("https://a.github.io/x", "https://b.github.io/y"))
+ self.assertFalse(module.same_site("https://a.blogspot.com/x", "https://b.blogspot.com/y"))
+ self.assertFalse(module.same_site("https://co.jp/", "https://co.jp/"))
+
def setUp(self):
self.module = load_module()
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index a25576fdf..53d4c55cc 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -764,6 +764,7 @@ class WebDataTests(unittest.TestCase):
def test_contract_handler_registries_are_complete_and_unknown_routes_fail(self):
self.assertEqual(set(rm_web.GET_HANDLERS), {
+ "/api/scraping", "/api/scraping/cover",
"/api/items", "/api/item", "/api/entity", "/api/photos", "/api/photo-set",
"/api/index", "/api/parts", "/api/editions", "/api/duplicates", "/api/quality-goals",
"/api/stats", "/api/tops", "/api/ads", "/api/related", "/api/facets",
@@ -775,6 +776,7 @@ class WebDataTests(unittest.TestCase):
"/api/taste", "/api/settings", "/api/links",
})
self.assertEqual(set(rm_web.POST_HANDLERS), {
+ "/api/scraping/settings", "/api/scraping/check", "/api/scraping/cover",
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
"/api/playlist",
"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch",
diff --git a/tests/test_scraping_access.py b/tests/test_scraping_access.py
new file mode 100644
index 000000000..dff783738
--- /dev/null
+++ b/tests/test_scraping_access.py
@@ -0,0 +1,142 @@
+"""独立安装的来源配置、凭据边界与实际传输行为。"""
+import json
+import io
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+import httpx
+from PIL import Image
+
+from peach.http import HttpRequest, HttpResponse, HttpxTransport
+from peach.scraping_access import (SourceTransport, client_for, cookie_jar, describe,
+ save, source_for, values_for)
+from peach.web_scraping import q_scraping, w_scraping_check
+
+
+class ScrapingAccessTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name).resolve()
+
+ def test_independent_installations_never_share_session_or_proxy(self):
+ save(self.root, "fc2cmadb", {"cookie": "session=private-cookie", "network": "proxy",
+ "proxy": "http://user:[email protected]:7890"})
+ public = q_scraping(SimpleNamespace(follow_secrets_root=self.root), {})
+ self.assertNotIn("private-cookie", json.dumps(public))
+ self.assertNotIn("private-proxy", json.dumps(public))
+ self.assertFalse(describe(self.root / "other-user", "fc2cmadb")["cookie_saved"])
+ save(self.root, "fc2cmadb", {"revoke": True})
+ self.assertFalse(describe(self.root, "fc2cmadb")["cookie_saved"])
+ self.assertEqual(values_for(self.root, "fc2cmadb")["network"], "proxy")
+
+ def test_import_discards_expired_foreign_and_cdn_cookies(self):
+ text = ("# Netscape HTTP Cookie File\n"
+ ".instagram.com\tTRUE\t/\tTRUE\t4102444800\tsessionid\tvalid\n"
+ ".instagram.com\tTRUE\t/\tTRUE\t1\texpired\told\n"
+ ".cdninstagram.com\tTRUE\t/\tTRUE\t4102444800\tsession\tcdn\n"
+ ".example.org\tTRUE\t/\tTRUE\t4102444800\tforeign\tother\n")
+ jar = cookie_jar({"cookies_text": text}, "instagram")
+ self.assertEqual([(c.name, c.value) for c in jar], [("sessionid", "valid")])
+ with httpx.Client(cookies=jar) as client:
+ self.assertIn("sessionid", client.build_request("GET", "https://www.instagram.com/").headers["cookie"])
+ self.assertNotIn("cookie", client.build_request("GET", "https://scontent.cdninstagram.com/x.jpg").headers)
+
+ def test_empty_malformed_and_cross_site_cookie_imports_are_rejected(self):
+ for supplied in ({"cookie": "bad\nheader"}, {"cookies_text": "not a cookie jar"},
+ {"cookie": "a=b", "cookies_text": "anything"}):
+ with self.subTest(supplied=list(supplied)), self.assertRaises(ValueError):
+ save(self.root, "instagram", supplied)
+
+ def test_network_mode_reaches_the_client_and_survives_renewal(self):
+ save(self.root, "dmm", {"network": "direct"})
+ with patch("peach.scraping_access.httpx.Client") as factory:
+ client_for(self.root, "dmm")
+ self.assertFalse(factory.call_args.kwargs["trust_env"])
+ transport = SourceTransport(self.root)
+ self.addCleanup(transport.close)
+ with patch("peach.scraping_access.client_for") as factory:
+ fake = factory.return_value
+ fake.stream.return_value.__enter__.return_value.iter_bytes.return_value = [b"ok"]
+ for _ in range(2):
+ transport(HttpRequest("GET", "https://pics.dmm.co.jp/x", {}), 1, 10)
+ transport.renew()
+ self.assertEqual(factory.call_count, 2)
+ self.assertEqual(fake.close.call_count, 2)
+
+ def test_redirect_selects_destination_policy_and_strips_secrets(self):
+ transport = SourceTransport(self.root)
+ with patch.object(transport, "_request", side_effect=[
+ HttpResponse(302, {"location": "https://pics.dmm.co.jp/x"}, b""),
+ HttpResponse(200, {}, b"image"),
+ ]) as request:
+ result = transport(HttpRequest("GET", "https://r18.dev/x", {"Cookie": "secret", "Authorization": "secret"}), 1, 20)
+ self.assertEqual(result.body, b"image")
+ self.assertEqual(request.call_args_list[1].args[0].headers, {})
+ self.assertEqual(source_for("https://evil-dmm.co.jp/x"), None)
+ self.assertEqual(source_for("https://awsimgsrc.dmm.com/x"), "dmm")
+
+ def test_connections_do_not_claim_session_validity_or_echo_exception_urls(self):
+ contract = SimpleNamespace(follow_secrets_root=self.root)
+ with patch("peach.web_scraping.SourceTransport") as factory:
+ factory.return_value.side_effect = httpx.ConnectError("https://secret:[email protected]/")
+ result = w_scraping_check(contract, {"source": "fc2cmadb"})
+ self.assertFalse(result["session_verified"])
+ self.assertNotIn("password", json.dumps(result))
+ self.assertFalse(result["results"][0]["ok"])
+
+ def test_transport_ownership_is_explicit(self):
+ for owned in (True, False):
+ client = httpx.Client()
+ transport = HttpxTransport(client, owns_client=owned)
+ transport.close()
+ self.assertEqual(client.is_closed, owned)
+ client.close()
+
+ def test_rate_limit_cooldown_survives_a_new_transport(self):
+ from peach.scraping_access import SourcePaused
+ transport = SourceTransport(self.root)
+ transport.transports["dmm"] = lambda *args: HttpResponse(429, {"retry-after": "600"}, b"")
+ request = HttpRequest("GET", "https://pics.dmm.co.jp/x", {})
+ with self.assertRaises(SourcePaused):
+ transport(request, 1, 100)
+ with patch("peach.scraping_access.client_for") as factory:
+ with self.assertRaises(SourcePaused):
+ SourceTransport(self.root)(request, 1, 100)
+ factory.assert_not_called()
+
+ def test_full_quality_bytes_are_installed_and_cache_avoids_download(self):
+ from peach.web_scraping import _fetch_cover
+ from peach.jav_cover_fetch import Candidate
+ output = io.BytesIO()
+ Image.new("RGB", (1600, 1000)).save(output, "JPEG")
+ original = output.getvalue()
+ contract = SimpleNamespace(cover_root=self.root / "covers", candidate_root=self.root,
+ follow_secrets_root=self.root / "secrets", follow_sources_root=self.root)
+ with patch("peach.jav_cover_fetch.best_cover", return_value=(
+ Candidate("dmm", "https://pics.dmm.co.jp/fixture.jpg"), (1600, 1000), original,
+ )) as fetch:
+ result = _fetch_cover(contract, "ABW-232")
+ cached = _fetch_cover(contract, "ABW-232")
+ self.assertTrue(result["ok"])
+ self.assertTrue(cached["ok"])
+ self.assertEqual(fetch.call_count, 1)
+ self.assertEqual((contract.cover_root / "ABW-232.jpg").read_bytes(), original)
+
+ def test_smaller_candidate_cannot_overwrite_a_full_quality_cover(self):
+ from peach.web_scraping import _fetch_cover
+ from peach.jav_cover_fetch import Candidate
+ target = self.root / "ABW-232.jpg"
+ Image.new("RGB", (2000, 1400)).save(target, "JPEG")
+ original = target.read_bytes()
+ contract = SimpleNamespace(cover_root=self.root, candidate_root=self.root,
+ follow_secrets_root=self.root / "secrets", follow_sources_root=self.root)
+ with patch("peach.jav_cover_fetch.best_cover", return_value=(
+ Candidate("dmm", "https://pics.dmm.co.jp/fixture.jpg"), (800, 600), b"small",
+ )):
+ result = _fetch_cover(contract, "ABW-232")
+ self.assertTrue(result["ok"])
+ self.assertEqual(target.read_bytes(), original)
diff --git a/tests/test_studio_icon_variants.py b/tests/test_studio_icon_variants.py
index 9ad005aee..d5e7d927d 100644
--- a/tests/test_studio_icon_variants.py
+++ b/tests/test_studio_icon_variants.py
@@ -12,6 +12,7 @@ import json
import sqlite3
import tempfile
import unittest
+import httpx
from pathlib import Path
from types import SimpleNamespace
@@ -1666,10 +1667,17 @@ class FetcherCacheTests(unittest.TestCase):
self.status = status
self.calls: list[str] = []
- def get(self, url, **kwargs):
- self.calls.append(url)
- return SimpleNamespace(status_code=self.status, content=b"<html></html>",
- headers={"content-type": "text/html"})
+ def stream(self, method, url, **kwargs):
+ from contextlib import contextmanager
+ @contextmanager
+ def response():
+ self.calls.append(url)
+ result = httpx.Response(self.status, content=b"<html></html>",
+ headers={"content-type": "text/html"},
+ request=httpx.Request(method, url))
+ yield result
+ result.close()
+ return response()
def test_the_same_page_is_only_fetched_once(self):
client = self.Client()
diff --git a/tests/test_studio_site_harvest.py b/tests/test_studio_site_harvest.py
index 78f2ddcd7..cb6e68c84 100644
--- a/tests/test_studio_site_harvest.py
+++ b/tests/test_studio_site_harvest.py
@@ -521,7 +521,7 @@ class ProbeRetryTests(unittest.TestCase):
results = list(outcomes)
class Fake:
- def __init__(self, client):
+ def __init__(self, client, *, owns_client=False):
pass
def __call__(self, request, timeout, limit):
diff --git a/web/app.js b/web/app.js
index 86e6ab167..19acbb567 100644
--- a/web/app.js
+++ b/web/app.js
@@ -147,6 +147,8 @@ const ROUTES=[
{match:'/resource-sync',title:'数据管理',open:(params,push)=>openResourceSync(push)},
{match:'/quality-goals',section:'quality',title:'高清版',refresh:'reopen',
open:(params,push)=>openQualityGoals(push)},
+ {match:'/scraping',section:'cleanup',title:'采集来源',refresh:'reopen',
+ open:(params,push)=>openScraping(push)},
{match:'/follow',nav:'follow',title:'关注',refresh:'skip',
open:(params,push)=>openFollow(push),reload:()=>openFollow(false)},
{match:'/follow-manage',section:'follow',title:'关注管理',refresh:'skip',
@@ -271,7 +273,7 @@ function renderInitialSurfaceLoading(){
renderCatalogLoading('正在读取垃圾文件');
return;
}
- const management=new Set(['/stats','/taste','/review','/data-cleanup','/duplicates','/quality-goals',
+ const management=new Set(['/stats','/taste','/review','/data-cleanup','/duplicates','/quality-goals','/scraping',
'/playlists','/resource-sync','/follow','/follow-manage','/configuration']);
if(management.has(path)||path.startsWith('/follow/item/')){
hideDiscoveryBars();
@@ -3353,7 +3355,7 @@ async function openDataCleanup(push=true){
const junkBreakdown=[...JUNK_KIND_OPTIONS.filter(([key])=>key&&Number(junkCounts[key])>0)
.map(([key,label])=>`${esc(label)} ${Number(junkCounts[key]).toLocaleString()}`),
...(Number(junk.dismissed_total)>0?[`已忽略 ${Number(junk.dismissed_total).toLocaleString()}`]:[])].join(' · ');
- $('#stats').innerHTML=`<div class="cleanuppage"><div class="cleanupgrid">
+ $('#stats').innerHTML=`<div class="cleanuppage"><p><a href="/scraping">采集来源与 Cookie 设置</a></p><div class="cleanupgrid">
<section class="cleanupfieldset" data-geist-fieldset aria-labelledby="cleanupJunkTitle">
<div class="geist-fieldset-content">${fieldsetTitle('cleanupJunkTitle','垃圾文件')}
<strong>${Number(junk.pending_total||0).toLocaleString()} 个待判断</strong>
@@ -3711,6 +3713,16 @@ async function openConfiguration(push=true){
if(surfaceCurrent(surface))window.scrollTo({top:0,behavior:'smooth'});
}
+async function openScraping(push=true){
+ releaseHoverPreviews();disposeStage(false);enterManagementSurface();
+ if(push)route('/scraping');
+ const surface=claimSurface('/scraping');
+ showManagementBody({placeholder:pageSkeletonHtml('正在读取采集来源',{cards:true})});
+ $('#manageTitle').textContent='采集来源';
+ const ui=await import('/dist/peach-ui.js');
+ await ui.mountIsland('scraping',$('#stats'),{toast},{isCurrent:()=>surfaceCurrent(surface)});
+}
+
/* ── 在线追更 ──
两个页面,因为是两件事:
- `/follow`(左侧导航)是**看**:一张卡片一个作品,点开就去看。本站的 alt 与 WIP
diff --git a/web/css/04-manage.css b/web/css/04-manage.css
index c102d7967..263a53b96 100644
--- a/web/css/04-manage.css
+++ b/web/css/04-manage.css
@@ -77,4 +77,14 @@
.cleanupfieldset .cleanupstate:empty{display:none}
.stats h2{margin:0 0 4px;font-size:var(--fs-2xl)}
.stats .sub{color:var(--muted);margin:0}
-
+/* 采集来源表单复用管理页 Fieldset。 */
+.scraping-page{max-width:960px;margin:0 auto;display:grid;gap:16px}
+.scraping-page>h1,.scraping-page p{margin:0}
+.scraping-fields form{display:grid;gap:12px;justify-items:start}
+.scraping-fields form label{width:100%}
+.scraping-fields{padding:20px;display:grid;gap:16px;min-width:0}
+.scraping-fields label{display:grid;gap:8px;min-width:0}
+.scraping-fields input,.scraping-fields select{width:100%;min-width:0;min-height:var(--control-h);box-sizing:border-box}
+.scraping-source{min-width:0}
+.scraping-source .geist-fieldset-footer{display:flex;gap:8px;flex-wrap:wrap;height:auto;min-height:52px;padding:12px 16px}
+@media(max-width:600px){.scraping-page{--control-h:44px}.scraping-source button{min-height:44px}.scraping-fields{padding:16px}}
diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.js
index 02bbc3c8c..4a1e8d3ea 100644
--- a/web/dist/peach-ui.js
+++ b/web/dist/peach-ui.js
@@ -284,42 +284,43 @@ async function Se(e, t) {
if (!n.ok) throw new be(xe(r) || `请求失败(${n.status})`, n.status);
return r;
}
-async function Ce(e, t, n = "POST") {
- let r = await fetch(e, {
+async function P(e, t, n = "POST", r) {
+ let i = await fetch(e, {
method: n,
+ ...r ? { signal: r } : {},
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
credentials: "same-origin",
body: JSON.stringify(t)
- }), i = null;
+ }), a = null;
try {
- i = await r.json();
+ a = await i.json();
} catch {}
- if (!r.ok) throw new be(xe(i) || `请求失败(${r.status})`, r.status, i);
- return i;
+ if (!i.ok) throw new be(xe(a) || `请求失败(${i.status})`, i.status, a);
+ return a;
}
//#endregion
//#region node_modules/preact/hooks/dist/hooks.module.js
-var P, F, we, Te, Ee = 0, De = [], I = c, Oe = I.__b, ke = I.__r, Ae = I.diffed, je = I.__c, Me = I.unmount, Ne = I.__;
-function Pe(e, t) {
- I.__h && I.__h(F, e, Ee || t), Ee = 0;
- var n = F.__H || (F.__H = {
+var F, I, Ce, we, Te = 0, Ee = [], L = c, De = L.__b, Oe = L.__r, ke = L.diffed, Ae = L.__c, je = L.unmount, Me = L.__;
+function Ne(e, t) {
+ L.__h && L.__h(I, e, Te || t), Te = 0;
+ var n = I.__H || (I.__H = {
__: [],
__h: []
});
return e >= n.__.length && n.__.push({}), n.__[e];
}
-function L(e) {
- return Ee = 1, Fe(Ke, e);
+function R(e) {
+ return Te = 1, Pe(We, e);
}
-function Fe(e, t, n) {
- var r = Pe(P++, 2);
- if (r.t = e, !r.__c && (r.__ = [n ? n(t) : Ke(void 0, t), function(e) {
+function Pe(e, t, n) {
+ var r = Ne(F++, 2);
+ if (r.t = e, !r.__c && (r.__ = [n ? n(t) : We(void 0, t), function(e) {
var t = r.__N ? r.__N[0] : r.__[0], n = r.t(t, e);
t !== n && (r.__N = [n, r.__[1]], r.__c.setState({}));
- }], r.__c = F, !F.__f)) {
+ }], r.__c = I, !I.__f)) {
var i = function(e, t, n) {
if (!r.__c.__H) return !0;
var i = !1, o = r.__c.props !== e;
@@ -335,112 +336,112 @@ function Fe(e, t, n) {
}
return !i || o;
};
- F.__f = !0;
- var a = F.shouldComponentUpdate, o = F.componentWillUpdate;
- F.componentWillUpdate = function(e, t, n) {
+ I.__f = !0;
+ var a = I.shouldComponentUpdate, o = I.componentWillUpdate;
+ I.componentWillUpdate = function(e, t, n) {
if (this.__e) {
var r = a;
a = void 0, i(e, t, n), a = r;
}
o && o.call(this, e, t, n);
- }, F.shouldComponentUpdate = i;
+ }, I.shouldComponentUpdate = i;
}
return r.__N || r.__;
}
-function Ie(e, t) {
- var n = Pe(P++, 3);
- !I.__s && Ge(n.__H, t) && (n.__ = e, n.u = t, F.__H.__h.push(n));
+function Fe(e, t) {
+ var n = Ne(F++, 3);
+ !L.__s && Ue(n.__H, t) && (n.__ = e, n.u = t, I.__H.__h.push(n));
}
-function Le(e, t) {
- var n = Pe(P++, 4);
- !I.__s && Ge(n.__H, t) && (n.__ = e, n.u = t, F.__h.push(n));
+function Ie(e, t) {
+ var n = Ne(F++, 4);
+ !L.__s && Ue(n.__H, t) && (n.__ = e, n.u = t, I.__h.push(n));
}
-function Re(e) {
- return Ee = 5, ze(function() {
+function z(e) {
+ return Te = 5, Le(function() {
return { current: e };
}, []);
}
-function ze(e, t) {
- var n = Pe(P++, 7);
- return Ge(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
+function Le(e, t) {
+ var n = Ne(F++, 7);
+ return Ue(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
}
-function Be() {
- for (var e; e = De.shift();) {
+function Re() {
+ for (var e; e = Ee.shift();) {
var t = e.__H;
if (e.__P && t) try {
- t.__h.some(Ue), t.__h.some(We), t.__h = [];
+ t.__h.some(Ve), t.__h.some(He), t.__h = [];
} catch (n) {
- t.__h = [], I.__e(n, e.__v);
+ t.__h = [], L.__e(n, e.__v);
}
}
}
-I.__b = function(e) {
- F = null, Oe && Oe(e);
-}, I.__ = function(e, t) {
- e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Ne && Ne(e, t);
-}, I.__r = function(e) {
- ke && ke(e), P = 0;
- var t = (F = e.__c).__H;
- t && (we === F ? (t.__h = [], F.__h = [], t.__.some(function(e) {
+L.__b = function(e) {
+ I = null, De && De(e);
+}, L.__ = function(e, t) {
+ e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Me && Me(e, t);
+}, L.__r = function(e) {
+ Oe && Oe(e), F = 0;
+ var t = (I = e.__c).__H;
+ t && (Ce === I ? (t.__h = [], I.__h = [], t.__.some(function(e) {
e.__N && (e.__ = e.__N), e.u = e.__N = void 0;
- })) : (t.__h.some(Ue), t.__h.some(We), t.__h = [], P = 0)), we = F;
-}, I.diffed = function(e) {
- Ae && Ae(e);
+ })) : (t.__h.some(Ve), t.__h.some(He), t.__h = [], F = 0)), Ce = I;
+}, L.diffed = function(e) {
+ ke && ke(e);
var t = e.__c;
- t && t.__H && (t.__H.__h.length && (De.push(t) !== 1 && Te === I.requestAnimationFrame || ((Te = I.requestAnimationFrame) || He)(Be)), t.__H.__.some(function(e) {
+ t && t.__H && (t.__H.__h.length && (Ee.push(t) !== 1 && we === L.requestAnimationFrame || ((we = L.requestAnimationFrame) || Be)(Re)), t.__H.__.some(function(e) {
e.u &&= (e.__H = e.u, void 0);
- })), we = F = null;
-}, I.__c = function(e, t) {
+ })), Ce = I = null;
+}, L.__c = function(e, t) {
t.some(function(e) {
try {
- e.__h.some(Ue), e.__h = e.__h.filter(function(e) {
- return !e.__ || We(e);
+ e.__h.some(Ve), e.__h = e.__h.filter(function(e) {
+ return !e.__ || He(e);
});
} catch (n) {
t.some(function(e) {
e.__h &&= [];
- }), t = [], I.__e(n, e.__v);
+ }), t = [], L.__e(n, e.__v);
}
- }), je && je(e, t);
-}, I.unmount = function(e) {
- Me && Me(e);
+ }), Ae && Ae(e, t);
+}, L.unmount = function(e) {
+ je && je(e);
var t, n = e.__c;
n && n.__H && (n.__H.__.some(function(e) {
try {
- Ue(e);
+ Ve(e);
} catch (e) {
t = e;
}
- }), n.__H = void 0, t && I.__e(t, n.__v));
+ }), n.__H = void 0, t && L.__e(t, n.__v));
};
-var Ve = typeof requestAnimationFrame == "function";
-function He(e) {
+var ze = typeof requestAnimationFrame == "function";
+function Be(e) {
var t, n = function() {
- clearTimeout(r), Ve && cancelAnimationFrame(t), setTimeout(e);
+ clearTimeout(r), ze && cancelAnimationFrame(t), setTimeout(e);
}, r = setTimeout(n, 35);
- Ve && (t = requestAnimationFrame(n));
+ ze && (t = requestAnimationFrame(n));
}
-function Ue(e) {
- var t = F, n = e.__c;
- typeof n == "function" && (e.__c = void 0, n()), F = t;
+function Ve(e) {
+ var t = I, n = e.__c;
+ typeof n == "function" && (e.__c = void 0, n()), I = t;
}
-function We(e) {
- var t = F;
- e.__c = e.__(), F = t;
+function He(e) {
+ var t = I;
+ e.__c = e.__(), I = t;
}
-function Ge(e, t) {
+function Ue(e, t) {
return !e || e.length !== t.length || t.some(function(t, n) {
return t !== e[n];
});
}
-function Ke(e, t) {
+function We(e, t) {
return typeof t == "function" ? t(e) : t;
}
//#endregion
//#region node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js
-var qe = 0;
+var Ge = 0;
Array.isArray;
-function R(e, t, n, r, i, a) {
+function B(e, t, n, r, i, a) {
t ||= {};
var o, s, l = t;
if ("ref" in l) for (s in l = {}, t) s == "ref" ? o = t[s] : l[s] = t[s];
@@ -455,7 +456,7 @@ function R(e, t, n, r, i, a) {
__e: null,
__c: null,
constructor: void 0,
- __v: --qe,
+ __v: --Ge,
__i: -1,
__u: 0,
__source: i,
@@ -466,31 +467,31 @@ function R(e, t, n, r, i, a) {
}
//#endregion
//#region src/islands/configuration.tsx
-var Je = "/api/configuration", Ye = "/api/pick-folder", Xe = 8e3, Ze = (e, t) => Se(Je, t), z = ({ html: e, class: t }) => /* @__PURE__ */ R("div", {
+var Ke = "/api/configuration", qe = "/api/pick-folder", Je = 8e3, Ye = (e, t) => Se(Ke, t), V = ({ html: e, class: t }) => /* @__PURE__ */ B("div", {
class: t,
dangerouslySetInnerHTML: { __html: e }
-}), Qe = (e) => !(e instanceof be) || e.status !== 400 ? null : e.body?.errors ?? null;
-function $e({ facts: e }) {
- return /* @__PURE__ */ R("section", {
+}), Xe = (e) => !(e instanceof be) || e.status !== 400 ? null : e.body?.errors ?? null;
+function Ze({ facts: e }) {
+ return /* @__PURE__ */ B("section", {
class: "configfieldset",
"data-geist-fieldset": !0,
"aria-labelledby": "configFactsTitle",
- children: /* @__PURE__ */ R("div", {
+ children: /* @__PURE__ */ B("div", {
class: "geist-fieldset-content",
- children: [/* @__PURE__ */ R(z, { html: t("configFactsTitle", "运行信息") }), /* @__PURE__ */ R("dl", {
+ children: [/* @__PURE__ */ B(V, { html: t("configFactsTitle", "运行信息") }), /* @__PURE__ */ B("dl", {
class: "configfacts",
- children: e.map((e) => /* @__PURE__ */ R(k, { children: [/* @__PURE__ */ R("dt", { children: e.term }), /* @__PURE__ */ R("dd", { children: e.value })] }))
+ children: e.map((e) => /* @__PURE__ */ B(k, { children: [/* @__PURE__ */ B("dt", { children: e.term }), /* @__PURE__ */ B("dd", { children: e.value })] }))
})]
})
});
}
-function et({ data: e, receipt: i }) {
- let [a, o] = L(e.media_dirs.length ? e.media_dirs : [""]), [s, c] = L(String(e.port)), [l, u] = L(!1), [d, f] = L([]), [p, m] = L(""), [h, g] = L(""), [_, v] = L(null), [y, b] = L(null), x = Re(!1), S = Re(e.revision), C = Re([]), w = Re(null);
- Le(() => {
+function Qe({ data: e, receipt: i }) {
+ let [a, o] = R(e.media_dirs.length ? e.media_dirs : [""]), [s, c] = R(String(e.port)), [l, u] = R(!1), [d, f] = R([]), [p, m] = R(""), [h, g] = R(""), [_, v] = R(null), [y, b] = R(null), x = z(!1), S = z(e.revision), C = z([]), w = z(null);
+ Ie(() => {
y !== null && (C.current[y]?.focus(), b(null));
- }, [y]), Ie(() => {
+ }, [y]), Fe(() => {
if (!_) return;
- let e = setTimeout(() => location.assign(_.url), Xe);
+ let e = setTimeout(() => location.assign(_.url), Je);
return () => clearTimeout(e);
}, [_]);
let T = (e, t) => {
@@ -509,7 +510,7 @@ function et({ data: e, receipt: i }) {
if (t.getAttribute("aria-busy") !== "true") {
r(t, !0);
try {
- let { path: t } = await Ce(Ye, { initial: a[e] ?? "" });
+ let { path: t } = await P(qe, { initial: a[e] ?? "" });
t && (T(e, t), D(e, ""));
} catch (t) {
D(e, N(t));
@@ -518,24 +519,24 @@ function et({ data: e, receipt: i }) {
}
}
};
- return _ ? /* @__PURE__ */ R("div", {
+ return _ ? /* @__PURE__ */ B("div", {
class: "configsaved",
role: "status",
- children: [/* @__PURE__ */ R(z, { html: n("配置已保存,Peach 正在重新启动。", {
+ children: [/* @__PURE__ */ B(V, { html: n("配置已保存,Peach 正在重新启动。", {
variant: "success",
label: "已保存"
- }) }), /* @__PURE__ */ R("p", {
+ }) }), /* @__PURE__ */ B("p", {
class: "confighelp",
children: [
"几秒后自动打开新地址;没跳转就点 ",
- /* @__PURE__ */ R("a", {
+ /* @__PURE__ */ B("a", {
href: _.url,
children: "进入馆藏"
}),
"。"
]
})]
- }) : /* @__PURE__ */ R("form", {
+ }) : /* @__PURE__ */ B("form", {
class: "configfieldset",
"data-geist-fieldset": !0,
"aria-labelledby": "configTitle",
@@ -543,7 +544,7 @@ function et({ data: e, receipt: i }) {
if (e.preventDefault(), !x.current) {
x.current = !0, r(w.current, !0), g("");
try {
- let e = await Ce(Je, {
+ let e = await P(Ke, {
revision: S.current,
media_dirs: a,
port: s,
@@ -551,7 +552,7 @@ function et({ data: e, receipt: i }) {
});
S.current = e.revision, f([]), m(""), i("已保存配置"), v(e);
} catch (e) {
- let t = Qe(e);
+ let t = Xe(e);
t ? (f(t.media_dirs ?? []), m(t.port ?? "")) : (f([]), m(""), g(N(e)));
} finally {
x.current = !1, r(w.current, !1);
@@ -559,26 +560,26 @@ function et({ data: e, receipt: i }) {
}
},
noValidate: !0,
- children: [/* @__PURE__ */ R("div", {
+ children: [/* @__PURE__ */ B("div", {
class: "geist-fieldset-content",
children: [
- /* @__PURE__ */ R(z, { html: t("configTitle", "这台电脑") }),
- /* @__PURE__ */ R("div", {
+ /* @__PURE__ */ B(V, { html: t("configTitle", "这台电脑") }),
+ /* @__PURE__ */ B("div", {
class: "configfield",
children: [
- /* @__PURE__ */ R("span", {
+ /* @__PURE__ */ B("span", {
class: "configlabel",
id: "configDirsLabel",
children: "媒体文件夹"
}),
- /* @__PURE__ */ R("div", {
+ /* @__PURE__ */ B("div", {
class: "configdirs",
role: "group",
"aria-labelledby": "configDirsLabel",
- children: a.map((e, t) => /* @__PURE__ */ R("div", {
+ children: a.map((e, t) => /* @__PURE__ */ B("div", {
class: "configdir",
children: [
- /* @__PURE__ */ R("input", {
+ /* @__PURE__ */ B("input", {
class: "geist-input",
type: "text",
value: e,
@@ -589,29 +590,29 @@ function et({ data: e, receipt: i }) {
C.current[t] = e;
}
}),
- /* @__PURE__ */ R("button", {
+ /* @__PURE__ */ B("button", {
type: "button",
class: "geist-button configpick",
"aria-label": "选择文件夹",
onClick: (e) => O(t, e.currentTarget),
- children: /* @__PURE__ */ R("svg", {
+ children: /* @__PURE__ */ B("svg", {
viewBox: "0 0 24 24",
"aria-hidden": "true",
- children: /* @__PURE__ */ R("use", { href: "#i-folder-search" })
+ children: /* @__PURE__ */ B("use", { href: "#i-folder-search" })
})
}),
- a.length > 1 ? /* @__PURE__ */ R("button", {
+ a.length > 1 ? /* @__PURE__ */ B("button", {
type: "button",
class: "geist-button configrm",
"aria-label": "移除这个文件夹",
onClick: () => ee(t),
- children: /* @__PURE__ */ R("svg", {
+ children: /* @__PURE__ */ B("svg", {
viewBox: "0 0 24 24",
"aria-hidden": "true",
- children: /* @__PURE__ */ R("use", { href: "#i-x" })
+ children: /* @__PURE__ */ B("use", { href: "#i-x" })
})
}) : null,
- d[t] ? /* @__PURE__ */ R("p", {
+ d[t] ? /* @__PURE__ */ B("p", {
class: "configbad",
role: "alert",
children: d[t]
@@ -619,26 +620,26 @@ function et({ data: e, receipt: i }) {
]
}, t))
}),
- /* @__PURE__ */ R("button", {
+ /* @__PURE__ */ B("button", {
type: "button",
class: "geist-button configadd",
onClick: E,
children: "添加文件夹"
}),
- /* @__PURE__ */ R("p", {
+ /* @__PURE__ */ B("p", {
class: "confighelp",
children: "Peach 从这些文件夹读取视频和图片。可以是外置硬盘上的文件夹,但必须已经存在。"
})
]
}),
- /* @__PURE__ */ R("div", {
+ /* @__PURE__ */ B("div", {
class: "configfield",
children: [
- /* @__PURE__ */ R("label", {
+ /* @__PURE__ */ B("label", {
for: "configPort",
children: "本机访问端口"
}),
- /* @__PURE__ */ R("input", {
+ /* @__PURE__ */ B("input", {
id: "configPort",
class: "geist-input",
type: "text",
@@ -647,43 +648,43 @@ function et({ data: e, receipt: i }) {
"aria-invalid": p ? "true" : void 0,
onInput: (e) => c(e.currentTarget.value)
}),
- p ? /* @__PURE__ */ R("p", {
+ p ? /* @__PURE__ */ B("p", {
class: "configbad",
role: "alert",
children: p
}) : null,
- /* @__PURE__ */ R("p", {
+ /* @__PURE__ */ B("p", {
class: "confighelp",
children: "浏览器地址里冒号后面的数字,一般不用改。"
})
]
}),
- /* @__PURE__ */ R("label", {
+ /* @__PURE__ */ B("label", {
class: "configcheck",
- children: [/* @__PURE__ */ R("span", {
+ children: [/* @__PURE__ */ B("span", {
class: "pcheck",
- children: [/* @__PURE__ */ R("input", {
+ children: [/* @__PURE__ */ B("input", {
type: "checkbox",
checked: l,
onChange: (e) => u(e.currentTarget.checked)
- }), /* @__PURE__ */ R("span", {
+ }), /* @__PURE__ */ B("span", {
"aria-hidden": "true",
- children: /* @__PURE__ */ R("svg", {
+ children: /* @__PURE__ */ B("svg", {
viewBox: "0 0 24 24",
- children: /* @__PURE__ */ R("use", { href: "#i-check" })
+ children: /* @__PURE__ */ B("use", { href: "#i-check" })
})
})]
- }), /* @__PURE__ */ R("span", { children: "保存后扫描媒体文件夹" })]
+ }), /* @__PURE__ */ B("span", { children: "保存后扫描媒体文件夹" })]
}),
- h ? /* @__PURE__ */ R(z, { html: n(h, {
+ h ? /* @__PURE__ */ B(V, { html: n(h, {
variant: "error",
label: "没有保存"
}) }) : null
]
- }), /* @__PURE__ */ R("div", {
+ }), /* @__PURE__ */ B("div", {
class: "geist-fieldset-footer",
"data-geist-fieldset-footer": !0,
- children: [/* @__PURE__ */ R("p", { children: "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ R("button", {
+ children: [/* @__PURE__ */ B("p", { children: "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ B("button", {
type: "submit",
class: "geist-button primary",
ref: w,
@@ -692,43 +693,43 @@ function et({ data: e, receipt: i }) {
})]
});
}
-function tt({ receipt: e, data: t, error: r }) {
- return r || !t ? /* @__PURE__ */ R(z, {
+function $e({ receipt: e, data: t, error: r }) {
+ return r || !t ? /* @__PURE__ */ B(V, {
class: "configpage",
html: n(r || "没有读到配置", {
variant: "error",
label: "打不开配置"
})
- }) : /* @__PURE__ */ R("div", {
+ }) : /* @__PURE__ */ B("div", {
class: "configpage",
- children: [t.editable ? /* @__PURE__ */ R(et, {
+ children: [t.editable ? /* @__PURE__ */ B(Qe, {
data: t,
receipt: e
- }) : /* @__PURE__ */ R(z, { html: n(t.notice, {
+ }) : /* @__PURE__ */ B(V, { html: n(t.notice, {
variant: "secondary",
label: "只读"
- }) }), /* @__PURE__ */ R($e, { facts: t.facts })]
+ }) }), /* @__PURE__ */ B(Ze, { facts: t.facts })]
});
}
//#endregion
//#region node_modules/@preact/signals-core/dist/signals-core.module.js
-var nt = Symbol.for("preact-signals");
-function B() {
+var et = Symbol.for("preact-signals");
+function tt() {
if (G > 1) G--;
else {
var e, t = !1;
for ((function() {
- var e = st;
- for (st = void 0; e !== void 0;) {
+ var e = ot;
+ for (ot = void 0; e !== void 0;) {
var t = e.S;
if (t.v === e.v) for (var n = t.t; n !== void 0; n = n.x) n.i === e.i && (n.i = t.i);
e = e.o;
}
})(); W !== void 0;) {
var n = W;
- for (W = void 0, it++; n !== void 0;) {
+ for (W = void 0, K++; n !== void 0;) {
var r = n.u;
- if (n.u = void 0, n.f &= -3, !(8 & n.f) && dt(n)) try {
+ if (n.u = void 0, n.f &= -3, !(8 & n.f) && ut(n)) try {
n.c();
} catch (n) {
t ||= (e = n, !0);
@@ -736,116 +737,116 @@ function B() {
n = r;
}
}
- if (it = 0, G--, t) throw e;
+ if (K = 0, G--, t) throw e;
}
}
-function rt(e) {
+function nt(e) {
if (G > 0) return e();
- ot = ++at, G++;
+ at = ++it, G++;
try {
return e();
} finally {
- B();
+ tt();
}
}
-var V, H = void 0;
-function U(e) {
- var t = H, n = V;
- H = void 0, V = void 0;
+var H, U = void 0;
+function rt(e) {
+ var t = U, n = H;
+ U = void 0, H = void 0;
try {
return e();
} finally {
- H = t, V = n;
+ U = t, H = n;
}
}
-var W = void 0, G = 0, it = 0, at = 0, ot = 0, st = void 0, ct = 0;
-function lt(e) {
- if (H !== void 0) {
+var W = void 0, G = 0, K = 0, it = 0, at = 0, ot = void 0, st = 0;
+function ct(e) {
+ if (U !== void 0) {
var t = e.n;
- if (t === void 0 || t.t !== H) return t = {
+ if (t === void 0 || t.t !== U) return t = {
i: 0,
S: e,
- p: H.s,
+ p: U.s,
n: void 0,
- t: H,
+ t: U,
e: void 0,
x: void 0,
r: t
- }, H.s !== void 0 && (H.s.n = t), H.s = t, e.n = t, 32 & H.f && e.S(t), t;
- if (t.i === -1) return t.i = 0, t.n !== void 0 && (t.n.p = t.p, t.p !== void 0 && (t.p.n = t.n), t.p = H.s, t.n = void 0, H.s.n = t, H.s = t), t;
+ }, U.s !== void 0 && (U.s.n = t), U.s = t, e.n = t, 32 & U.f && e.S(t), t;
+ if (t.i === -1) return t.i = 0, t.n !== void 0 && (t.n.p = t.p, t.p !== void 0 && (t.p.n = t.n), t.p = U.s, t.n = void 0, U.s.n = t, U.s = t), t;
}
}
-function K(e, t) {
+function q(e, t) {
this.v = e, this.i = 0, this.n = void 0, this.t = void 0, this.l = 0, this.W = t?.watched, this.Z = t?.unwatched, this.name = t?.name;
}
-K.prototype.brand = nt, K.prototype.h = function() {
+q.prototype.brand = et, q.prototype.h = function() {
return !0;
-}, K.prototype.S = function(e) {
+}, q.prototype.S = function(e) {
var t = this, n = this.t;
- n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? U(function() {
+ n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? rt(function() {
var e;
(e = t.W) == null || e.call(t);
}) : n.e = e);
-}, K.prototype.U = function(e) {
+}, q.prototype.U = function(e) {
var t = this;
if (this.t !== void 0) {
var n = e.e, r = e.x;
- n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && U(function() {
+ n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && rt(function() {
var e;
(e = t.Z) == null || e.call(t);
}));
}
-}, K.prototype.subscribe = function(e) {
+}, q.prototype.subscribe = function(e) {
var t = this;
return X(function() {
var n = t.value;
- U(function() {
+ rt(function() {
return e(n);
});
}, { name: "sub" });
-}, K.prototype.valueOf = function() {
+}, q.prototype.valueOf = function() {
return this.value;
-}, K.prototype.toString = function() {
+}, q.prototype.toString = function() {
return this.value + "";
-}, K.prototype.toJSON = function() {
+}, q.prototype.toJSON = function() {
return this.value;
-}, K.prototype.peek = function() {
+}, q.prototype.peek = function() {
var e = this;
- return U(function() {
+ return rt(function() {
return e.value;
});
-}, Object.defineProperty(K.prototype, "value", {
+}, Object.defineProperty(q.prototype, "value", {
get: function() {
- var e = lt(this);
+ var e = ct(this);
return e !== void 0 && (e.i = this.i), this.v;
},
set: function(e) {
if (e !== this.v) {
- if (it > 100) throw Error("Cycle detected");
+ if (K > 100) throw Error("Cycle detected");
(function(e) {
- G !== 0 && it === 0 && e.l !== ot && (e.l = ot, st = {
+ G !== 0 && K === 0 && e.l !== at && (e.l = at, ot = {
S: e,
v: e.v,
i: e.i,
- o: st
+ o: ot
});
- })(this), this.v = e, this.i++, ct++, G++;
+ })(this), this.v = e, this.i++, st++, G++;
try {
for (var t = this.t; t !== void 0; t = t.x) t.t.N();
} finally {
- B();
+ tt();
}
}
}
});
-function ut(e, t) {
- return new K(e, t);
+function lt(e, t) {
+ return new q(e, t);
}
-function dt(e) {
+function ut(e) {
for (var t = e.s; t !== void 0; t = t.n) if (t.S.i !== t.i || !t.S.h() || t.S.i !== t.i) return !0;
return !1;
}
-function ft(e) {
+function dt(e) {
for (var t = e.s; t !== void 0; t = t.n) {
var n = t.S.n;
if (n !== void 0 && (t.r = n), t.S.n = t, t.i = -1, t.n === void 0) {
@@ -854,66 +855,66 @@ function ft(e) {
}
}
}
-function pt(e) {
+function ft(e) {
for (var t = e.s, n = void 0; t !== void 0;) {
var r = t.p;
t.i === -1 ? (t.S.U(t), r !== void 0 && (r.n = t.n), t.n !== void 0 && (t.n.p = r)) : n = t, t.S.n = t.r, t.r !== void 0 && (t.r = void 0), t = r;
}
e.s = n;
}
-function q(e, t) {
- K.call(this, void 0, t), this.x = e, this.s = void 0, this.g = ct - 1, this.f = 4;
+function J(e, t) {
+ q.call(this, void 0, t), this.x = e, this.s = void 0, this.g = st - 1, this.f = 4;
}
-q.prototype = new K(), q.prototype.h = function() {
+J.prototype = new q(), J.prototype.h = function() {
if (this.f &= -3, 1 & this.f) return !1;
- if ((36 & this.f) == 32 || (this.f &= -5, this.g === ct)) return !0;
- if (this.g = ct, this.f |= 1, this.i > 0 && !dt(this)) return this.f &= -2, !0;
- var e = H;
+ if ((36 & this.f) == 32 || (this.f &= -5, this.g === st)) return !0;
+ if (this.g = st, this.f |= 1, this.i > 0 && !ut(this)) return this.f &= -2, !0;
+ var e = U;
try {
- ft(this), H = this;
+ dt(this), U = this;
var t = this.x();
(16 & this.f || this.v !== t || this.i === 0) && (this.v = t, this.f &= -17, this.i++);
} catch (e) {
this.v = e, this.f |= 16, this.i++;
}
- return H = e, pt(this), this.f &= -2, !0;
-}, q.prototype.S = function(e) {
+ return U = e, ft(this), this.f &= -2, !0;
+}, J.prototype.S = function(e) {
if (this.t === void 0) {
this.f |= 36;
for (var t = this.s; t !== void 0; t = t.n) t.S.S(t);
}
- K.prototype.S.call(this, e);
-}, q.prototype.U = function(e) {
- if (this.t !== void 0 && (K.prototype.U.call(this, e), this.t === void 0)) {
+ q.prototype.S.call(this, e);
+}, J.prototype.U = function(e) {
+ if (this.t !== void 0 && (q.prototype.U.call(this, e), this.t === void 0)) {
this.f &= -33;
for (var t = this.s; t !== void 0; t = t.n) t.S.U(t);
}
-}, q.prototype.N = function() {
+}, J.prototype.N = function() {
if (!(2 & this.f)) {
this.f |= 6;
for (var e = this.t; e !== void 0; e = e.x) e.t.N();
}
-}, Object.defineProperty(q.prototype, "value", { get: function() {
+}, Object.defineProperty(J.prototype, "value", { get: function() {
if (1 & this.f) throw Error("Cycle detected");
- var e = lt(this);
+ var e = ct(this);
if (this.h(), e !== void 0 && (e.i = this.i), 16 & this.f) throw this.v;
return this.v;
} });
-function J(e, t) {
- return new q(e, t);
+function pt(e, t) {
+ return new J(e, t);
}
function mt(e) {
var t = e.m;
if (e.m = void 0, typeof t == "function") {
G++;
- var n = H;
- H = void 0;
+ var n = U;
+ U = void 0;
try {
t();
} catch (t) {
throw e.f &= -2, e.f |= 8, ht(e), t;
} finally {
- H = n, B();
+ U = n, tt();
}
}
}
@@ -922,11 +923,11 @@ function ht(e) {
e.x = void 0, e.s = void 0, mt(e);
}
function gt(e) {
- if (H !== this) throw Error("Out-of-order effect");
- pt(this), H = e, this.f &= -2, 8 & this.f && ht(this), B();
+ if (U !== this) throw Error("Out-of-order effect");
+ ft(this), U = e, this.f &= -2, 8 & this.f && ht(this), tt();
}
function Y(e, t) {
- this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, V && V.push(this);
+ this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, H && H.push(this);
}
Y.prototype.c = function() {
var e = this.S();
@@ -939,9 +940,9 @@ Y.prototype.c = function() {
}
}, Y.prototype.S = function() {
if (1 & this.f) throw Error("Cycle detected");
- this.f |= 1, this.f &= -9, mt(this), ft(this), G++;
- var e = H;
- return H = this, gt.bind(this, e);
+ this.f |= 1, this.f &= -9, mt(this), dt(this), G++;
+ var e = U;
+ return U = this, gt.bind(this, e);
}, Y.prototype.N = function() {
2 & this.f || (this.f |= 2, this.u = W, W = this);
}, Y.prototype.d = function() {
@@ -978,15 +979,15 @@ function xt(e) {
function St(e) {
var t = this, n = e.data, r = wt(n);
r.name = "ReactiveDom", r.value = n;
- var i = ze(function() {
+ var i = Le(function() {
for (var e = t, n = t.__v; n = n.__;) if (n.__c) {
n.__c.__$f |= 4;
break;
}
- var i = J(function() {
+ var i = pt(function() {
var e = r.value.value;
return e === 0 ? 0 : !0 === e ? "" : e || "";
- }), a = J(function() {
+ }), a = pt(function() {
return !Array.isArray(i.value) && !u(i.value);
}), o = X(function() {
if (this.N = Dt, a.value) {
@@ -1000,7 +1001,7 @@ function St(e) {
}, []), a = i[0], o = i[1];
return a.value ? o.peek() : o.value;
}
-St.displayName = "ReactiveTextNode", Object.defineProperties(K.prototype, {
+St.displayName = "ReactiveTextNode", Object.defineProperties(q.prototype, {
constructor: {
configurable: !0,
value: void 0
@@ -1027,7 +1028,7 @@ St.displayName = "ReactiveTextNode", Object.defineProperties(K.prototype, {
var n, r = t.props;
for (var i in r) if (i !== "children") {
var a = r[i];
- a instanceof K && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());
+ a instanceof q && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());
}
}
e(t);
@@ -1066,7 +1067,7 @@ St.displayName = "ReactiveTextNode", Object.defineProperties(K.prototype, {
e(t);
});
function Ct(e, t, n, r) {
- var i = t in e && e.ownerSVGElement === void 0, a = ut(n);
+ var i = t in e && e.ownerSVGElement === void 0, a = lt(n);
return {
o: function(e, t) {
a.value = e, r = t;
@@ -1117,8 +1118,8 @@ Z("unmount", function(e, t) {
return !1;
};
function wt(e, t) {
- return ze(function() {
- return ut(e, t);
+ return Le(function() {
+ return lt(e, t);
}, []);
}
var Tt = function(e) {
@@ -1127,7 +1128,7 @@ var Tt = function(e) {
});
};
function Et() {
- rt(function() {
+ nt(function() {
for (var e; e = bt.shift();) _t.call(e);
});
}
@@ -1139,8 +1140,8 @@ function Dt() {
var Ot = "/api/quality-goals?limit=200", kt = {
data: null,
error: ""
-}, Q = ut(kt), At = 0, jt = J(() => Q.value);
-J(() => Q.value.data?.total ?? null);
+}, Q = lt(kt), At = 0, jt = pt(() => Q.value);
+pt(() => Q.value.data?.total ?? null);
function Mt() {
At += 1, Q.value = kt;
}
@@ -1164,7 +1165,7 @@ async function Nt(e) {
var Pt = (e, t) => Nt(t), Ft = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;
function It({ openItem: t, javTitleHtml: r, javDisplayName: s, srcBadge: c }) {
let { data: l, error: u } = jt.value;
- if (u) return /* @__PURE__ */ R("div", {
+ if (u) return /* @__PURE__ */ B("div", {
class: "qualitylist",
dangerouslySetInnerHTML: { __html: n(u, {
variant: "error",
@@ -1172,66 +1173,51 @@ function It({ openItem: t, javTitleHtml: r, javDisplayName: s, srcBadge: c }) {
}) }
});
let d = l?.items ?? [];
- return d.length ? /* @__PURE__ */ R("div", {
+ return d.length ? /* @__PURE__ */ B("div", {
class: "qualitylist",
- children: d.map((e) => /* @__PURE__ */ R("article", {
+ children: d.map((e) => /* @__PURE__ */ B("article", {
class: "qualityitem",
- children: [/* @__PURE__ */ R("button", {
+ children: [/* @__PURE__ */ B("button", {
class: "qualitycover",
type: "button",
"aria-label": `打开 ${s(e)}`,
onClick: () => t(e.id),
- children: /* @__PURE__ */ R("img", {
+ children: /* @__PURE__ */ B("img", {
src: Ft(e),
alt: "",
loading: "lazy",
onError: (e) => e.currentTarget.remove()
})
- }), /* @__PURE__ */ R("div", { children: [
- /* @__PURE__ */ R("h3", { children: /* @__PURE__ */ R("button", {
+ }), /* @__PURE__ */ B("div", { children: [
+ /* @__PURE__ */ B("h3", { children: /* @__PURE__ */ B("button", {
type: "button",
"data-middle-truncate": !0,
onClick: () => t(e.id),
dangerouslySetInnerHTML: { __html: r(e) }
}) }),
- /* @__PURE__ */ R("p", {
+ /* @__PURE__ */ B("p", {
class: "mono",
children: [
- /* @__PURE__ */ R("span", {
+ /* @__PURE__ */ B("span", {
style: "display:contents",
dangerouslySetInnerHTML: { __html: c(e.location, e.cost) }
}),
- /* @__PURE__ */ R("span", { children: i[e.location] ?? e.location }),
- /* @__PURE__ */ R("span", { children: a(e.duration) }),
- /* @__PURE__ */ R("span", { children: o(e.size ?? 0) })
+ /* @__PURE__ */ B("span", { children: i[e.location] ?? e.location }),
+ /* @__PURE__ */ B("span", { children: a(e.duration) }),
+ /* @__PURE__ */ B("span", { children: o(e.size ?? 0) })
]
}),
- e.reason ? /* @__PURE__ */ R("p", { children: e.reason }) : null
+ e.reason ? /* @__PURE__ */ B("p", { children: e.reason }) : null
] })]
}, e.id))
- }) : /* @__PURE__ */ R("div", {
+ }) : /* @__PURE__ */ B("div", {
class: "qualitylist",
dangerouslySetInnerHTML: { __html: e("sparkles", "没有标记中的高清版目标", "现有版本都已满足条件,或还没有加入追踪。") }
});
}
//#endregion
-//#region src/state/index.ts
-var Lt = { "quality-goals": {
- refresh: Nt,
- reset: Mt
-} }, Rt = () => Object.keys(Lt);
-async function zt(e) {
- let t = Lt[e];
- if (!t) throw Error(`未登记的共享 store:${String(e)}`);
- try {
- return await t.refresh(), !0;
- } catch {
- return !1;
- }
-}
-//#endregion
//#region src/jobs.ts
-async function Bt(e) {
+async function Lt(e) {
let t = e.pause || ((e) => new Promise((t) => setTimeout(t, e))), n = 0;
for (; e.active();) {
let r;
@@ -1246,11 +1232,11 @@ async function Bt(e) {
await t(2e3);
}
}
-function Vt(e) {
+function Rt(e) {
let t = document.createElement("div");
e.host.hidden = !0, t.dataset.followJob = "", t.setAttribute("aria-live", "polite"), e.host.prepend(t);
let n = e.storageKey || "peach-follow-job", r = sessionStorage.getItem(n) || void 0, i = !1;
- Bt({
+ Lt({
read: e.read,
active: () => !i && e.active() && t.isConnected,
keepWatching: e.watchIdle !== !1,
@@ -1275,8 +1261,261 @@ function Vt(e) {
});
}
//#endregion
+//#region src/islands/scraping.tsx
+var zt = (e, t) => Se("/api/scraping", t);
+function Bt({ source: e, toast: i }) {
+ let [a, o] = R(e), [s, c] = R(e.network), [l, u] = R(""), [d, f] = R(""), [p, m] = R(""), [h, g] = R(!1), [_, v] = R(""), [y, b] = R([]), x = z(null), S = z(null);
+ Ie(() => {
+ S.current?.querySelectorAll("button").forEach((e) => r(e, h));
+ }, [h]);
+ let C = z(new AbortController());
+ Fe(() => () => C.current.abort(), []);
+ async function w(t) {
+ if (!h) {
+ g(!0), v(""), b([]);
+ try {
+ if (t === "check") {
+ let t = await P("/api/scraping/check", { source: e.source }, "POST", C.current.signal);
+ C.current.signal.aborted || b(t.results);
+ } else {
+ let n = await P("/api/scraping/settings", {
+ source: e.source,
+ network: s,
+ proxy: l,
+ cookie: d,
+ cookies_text: p,
+ revoke: t === "revoke"
+ }, "POST", C.current.signal);
+ C.current.signal.aborted || (o(n.saved), u(""), f(""), m(""), x.current && (x.current.value = ""), i(t === "revoke" ? "Cookie 已撤销" : "来源设置已保存"));
+ }
+ } catch (e) {
+ C.current.signal.aborted || v(N(e));
+ } finally {
+ C.current.signal.aborted || g(!1);
+ }
+ }
+ }
+ return /* @__PURE__ */ B("section", {
+ class: "scraping-source",
+ children: /* @__PURE__ */ B("form", {
+ ref: S,
+ class: "cleanupfieldset",
+ "data-geist-fieldset": !0,
+ onSubmit: (e) => {
+ e.preventDefault(), w("save");
+ },
+ children: [/* @__PURE__ */ B("div", {
+ class: "geist-fieldset-content scraping-fields",
+ children: [
+ /* @__PURE__ */ B("div", { dangerouslySetInnerHTML: { __html: t(`scraping-${e.source}`, e.label) } }),
+ /* @__PURE__ */ B("label", { children: ["连接方式", /* @__PURE__ */ B("select", {
+ class: "geist-input",
+ value: s,
+ disabled: h,
+ onChange: (e) => c(e.currentTarget.value),
+ children: [
+ /* @__PURE__ */ B("option", {
+ value: "environment",
+ children: "环境代理"
+ }),
+ /* @__PURE__ */ B("option", {
+ value: "direct",
+ children: "应用直连"
+ }),
+ /* @__PURE__ */ B("option", {
+ value: "proxy",
+ children: "指定代理"
+ })
+ ]
+ })] }),
+ s === "proxy" && /* @__PURE__ */ B("label", { children: ["代理地址", /* @__PURE__ */ B("input", {
+ class: "geist-input",
+ type: "password",
+ autoComplete: "off",
+ value: l,
+ placeholder: a.proxy_saved ? "已保存,留空保留" : "http://127.0.0.1:7890",
+ disabled: h,
+ onInput: (e) => u(e.currentTarget.value)
+ })] }),
+ e.accepts_cookie && /* @__PURE__ */ B(k, { children: [
+ /* @__PURE__ */ B("p", { children: [
+ /* @__PURE__ */ B("a", {
+ href: e.login,
+ target: "_blank",
+ rel: "noopener noreferrer",
+ children: "打开官网登录"
+ }),
+ " · ",
+ a.cookie_saved ? "Cookie 已保存,尚未验证会话" : "尚未提供 Cookie"
+ ] }),
+ /* @__PURE__ */ B("label", { children: ["Cookie 请求头", /* @__PURE__ */ B("input", {
+ class: "geist-input",
+ type: "password",
+ autoComplete: "off",
+ value: d,
+ disabled: h || !!p,
+ onInput: (e) => f(e.currentTarget.value)
+ })] }),
+ /* @__PURE__ */ B("label", { children: ["Netscape Cookie 文件", /* @__PURE__ */ B("input", {
+ class: "geist-input",
+ ref: x,
+ type: "file",
+ accept: ".txt",
+ disabled: h || !!d,
+ onChange: async (e) => {
+ let t = e.currentTarget.files?.[0];
+ if (!t) {
+ m("");
+ return;
+ }
+ if (m(""), t.size > 262144) {
+ v("Cookie 文本超过 256 KiB"), e.currentTarget.value = "";
+ return;
+ }
+ g(!0);
+ try {
+ let e = await t.text();
+ C.current.signal.aborted || m(e);
+ } catch {
+ C.current.signal.aborted || v("Cookie 文件未读取,请重新选择");
+ } finally {
+ C.current.signal.aborted || g(!1);
+ }
+ }
+ })] })
+ ] }),
+ _ && /* @__PURE__ */ B("div", {
+ role: "alert",
+ dangerouslySetInnerHTML: { __html: n(_, { variant: "error" }) }
+ }),
+ y.map((e) => /* @__PURE__ */ B("p", {
+ role: "status",
+ children: [
+ e.label,
+ ":",
+ e.ok ? "可连接" : "未取得",
+ e.width ? ` · ${e.width} × ${e.height}` : "",
+ e.message ? ` · ${e.message}` : ""
+ ]
+ }, e.label))
+ ]
+ }), /* @__PURE__ */ B("footer", {
+ class: "geist-fieldset-footer",
+ "data-geist-fieldset-footer": !0,
+ children: [
+ /* @__PURE__ */ B("button", {
+ class: "geist-button primary",
+ type: "submit",
+ children: "保存"
+ }),
+ /* @__PURE__ */ B("button", {
+ class: "geist-button",
+ type: "button",
+ onClick: () => void w("check"),
+ children: "检查已保存的连接"
+ }),
+ e.accepts_cookie && a.cookie_saved && /* @__PURE__ */ B("button", {
+ class: "geist-button",
+ type: "button",
+ onClick: () => void w("revoke"),
+ children: "撤销 Cookie"
+ })
+ ]
+ })]
+ })
+ });
+}
+function Vt({ data: e, error: i, toast: a }) {
+ let [o, s] = R(""), [c, l] = R(!1), [u, d] = R(""), f = z(null);
+ Ie(() => r(f.current, c), [c]);
+ let p = z(new AbortController()), m = z(0);
+ async function h(e = !1) {
+ let t = ++m.current;
+ await Lt({
+ read: (e) => Se("/api/scraping/cover", e),
+ active: () => !p.current.signal.aborted && t === m.current,
+ render: (t) => {
+ l(t.status === "running"), t.status === "running" && (e = !1), t.status === "failed" && !e && d(t.error || "采集未取得"), t.status === "complete" && !e && a(t.result || "封面采集完成");
+ },
+ disconnected: () => d("连接中断,正在重新读取后台进度")
+ });
+ }
+ Fe(() => (h(!0), () => p.current.abort()), []);
+ async function g() {
+ if (!c) {
+ m.current++, l(!0), d("");
+ try {
+ await P("/api/scraping/cover", { code: o }, "POST", p.current.signal), await h();
+ } catch (e) {
+ p.current.signal.aborted || (l(!1), d(N(e)));
+ }
+ }
+ }
+ return i ? /* @__PURE__ */ B("div", {
+ role: "alert",
+ dangerouslySetInnerHTML: { __html: n(i, { variant: "error" }) }
+ }) : /* @__PURE__ */ B("div", {
+ class: "scraping-page",
+ children: [
+ /* @__PURE__ */ B("p", { children: "高清来源可能需要代理。环境代理读取服务进程的代理环境变量;应用直连仍可能经过系统隧道。" }),
+ /* @__PURE__ */ B("p", { children: "封面采集保留最高可得画质,失败保留已有图片。连接检查不验证登录会话。" }),
+ /* @__PURE__ */ B("section", {
+ class: "cleanupfieldset scraping-source",
+ "data-geist-fieldset": !0,
+ children: /* @__PURE__ */ B("div", {
+ class: "geist-fieldset-content scraping-fields",
+ children: [
+ /* @__PURE__ */ B("div", { dangerouslySetInnerHTML: { __html: t("scraping-cover", "高清封面") } }),
+ /* @__PURE__ */ B("form", {
+ onSubmit: (e) => {
+ e.preventDefault(), g();
+ },
+ children: [/* @__PURE__ */ B("label", { children: ["馆藏番号", /* @__PURE__ */ B("input", {
+ class: "geist-input",
+ required: !0,
+ value: o,
+ disabled: c,
+ placeholder: "ABW-232",
+ onInput: (e) => s(e.currentTarget.value)
+ })] }), /* @__PURE__ */ B("button", {
+ ref: f,
+ class: "geist-button primary",
+ type: "submit",
+ children: "抓取或升级封面"
+ })]
+ }),
+ u && /* @__PURE__ */ B("div", {
+ role: "alert",
+ dangerouslySetInnerHTML: { __html: n(u, { variant: "error" }) }
+ })
+ ]
+ })
+ }),
+ e?.sources.map((e) => /* @__PURE__ */ B(Bt, {
+ source: e,
+ toast: a
+ }, e.source))
+ ]
+ });
+}
+//#endregion
+//#region src/state/index.ts
+var Ht = { "quality-goals": {
+ refresh: Nt,
+ reset: Mt
+} }, Ut = () => Object.keys(Ht);
+async function Wt(e) {
+ let t = Ht[e];
+ if (!t) throw Error(`未登记的共享 store:${String(e)}`);
+ try {
+ return await t.refresh(), !0;
+ } catch {
+ return !1;
+ }
+}
+//#endregion
//#region src/sidebar.ts
-function Ht(e) {
+function Gt(e) {
return [
"/",
"/unseen",
@@ -1286,30 +1525,34 @@ function Ht(e) {
"/junk-files"
].includes(e) || /^\/(item|mix|parts|editions)\//.test(e) || /^\/playlists\/\d+\/\d+$/.test(e) || /^\/(performers|studios|creators|series|agencies)\/.+/.test(e);
}
-function Ut(e, t) {
+function Kt(e, t) {
return e.dataset.surface === t && e.querySelector(".dnav") ? !1 : (e.dataset.surface = t, e.replaceChildren(), !0);
}
-function Wt(e) {
+function qt(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/islands.ts
-var Gt = {
+var Jt = {
+ scraping: {
+ load: zt,
+ component: Vt
+ },
"quality-goals": {
load: Pt,
component: It
},
configuration: {
- load: Ze,
- component: tt
+ load: Ye,
+ component: $e
}
-}, Kt = () => Object.keys(Gt), $ = /* @__PURE__ */ new Map();
-async function qt(e, t, n, r = {}) {
- let i = Gt[e];
+}, Yt = () => Object.keys(Jt), $ = /* @__PURE__ */ new Map();
+async function Xt(e, t, n, r = {}) {
+ let i = Jt[e];
if (!i) throw Error(`未注册的 island:${String(e)}`);
- Jt(t);
+ Zt(t);
let a = {
controller: new AbortController(),
painted: !1
@@ -1340,9 +1583,9 @@ async function qt(e, t, n, r = {}) {
};
ye(D(i.component, s), t);
}
-function Jt(e) {
+function Zt(e) {
let t = $.get(e);
t && (t.controller.abort(), $.delete(e), t.painted && ye(null, e));
}
//#endregion
-export { Vt as followJobProgress, Kt as islandNames, qt as mountIsland, zt as refreshStore, Ht as sidebarHasCatalogContent, Wt as sidebarTagCounts, Rt as storeNames, Ut as syncSidebarSurface, Jt as unmountIsland, Bt as watchJob };
+export { Rt as followJobProgress, Yt as islandNames, Xt as mountIsland, Wt as refreshStore, Gt as sidebarHasCatalogContent, qt as sidebarTagCounts, Ut as storeNames, Kt as syncSidebarSurface, Zt as unmountIsland, Lt as watchJob };