Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: add follow carousel and automatic updates

longmeidaoe81f3ae0d7e8
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index e58728309..e5337bf97 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -153,6 +153,7 @@ Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 U
- FastAPI 与前端保持单体部署,在线来源和 AI 只通过显式适配器进入;AI runtime 与推理 API 的协议边界见 ADR-0003。
- 当前页面、路由、交互与性能实现只写 `docs/STATUS.md`,由 API 和 `tests/test_web_ui.py` 守住;本文件不再复制易过期的版本号、像素值和控件清单。
- 追更连接器、凭据、变体和跨站归组以 ADR-0019 为准。Rule34.xxx 来源身份大小写不敏感;作者显示名与头像优先经固定主机校验的官方页面,归档站只回退。
+- 自动追更固定使用 APScheduler 3.11.3,只在 ledger writer 启动。频率保存在 `peach-data/state/follow-schedule.json`,默认每小时且启动后等待一个完整间隔;不要改成启动即抓。任务必须保持 `coalesce=True`、`max_instances=1`,并与手动检查共用 `WebContract.follow_check_lock`,reader 只显示不可用状态。
- 账本路径兼容和抽帧失败处理统一见 `.claude/skills/peach-cross-platform/SKILL.md` 与 `.claude/skills/peach-batch-jobs/SKILL.md`。
## Web 性能边界
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index cee476958..dab139f50 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -6,7 +6,7 @@
1. **寻找更好版本**:已经能逐条标记「高清 / 无水印 / 完整版」等目标;后续仍需相似内容匹配、候选去重、来源发现和人工替换确认。
2. **现代自适应播放**:Video.js、Range、统计面板和面向 115/PikPak 原生 MP4 的按需 HLS 清单已经上线;自适应码率、多路清单、快速首帧和来源层大块预取优化仍未完成。
-3. **在线追更**:kemono/coomer/pawchive、rule34video、rule34.xxx、f95zone 五类连接器、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、`peach follow`、看的 `/follow` 与管的 `/follow-manage` 两个页面(粘链接或只给名字/id,自动跨六个来源查找)已上线;仍缺定时轮询(APScheduler)、媒体下载落地,以及 simpcity 的可用入口(DDoS-Guard,未取得)。
+3. **在线追更**:kemono/coomer/pawchive、rule34video、rule34.xxx、f95zone 五类连接器、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、`peach follow`、看的 `/follow` 与管的 `/follow-manage` 两个页面(粘链接或只给名字/id,自动跨六个来源查找)已上线;writer 已用 APScheduler 按设置自动轮询。仍缺媒体下载落地,以及 simpcity 的可用入口(DDoS-Guard,未取得)。
4. **首尾帧出处与不完整候选**:已有受限 FFmpeg 首尾抽帧、Windows 内置 OCR、证据帧缓存、来源/Full version 候选和 `/review`;仍需决定全库批次范围,并把用户批准后的不完整版判断接到更好版本目标。
5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。
6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 986ad72f2..b543d2051 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -43,7 +43,7 @@
| HTML5/HLS/DASH 播放 | Video.js 8.23.9 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板 |
| 照片灯箱轮播 | Swiper 14.1.0(MIT,本地固定版本,按需 `<script>` 注入)的 Thumbs / Keyboard / Zoom 模块 | 图集来源与顺序、缩略图缓存与计费口径、瀑布流本身(CSS `column-count`,不经过 Swiper) |
| 图标 | 固定版本的本地 Lucide 子集;Health Icons 24 px outline(CC0)用于领域图标 | 标签、状态和交互设计 |
-| 定时轮询 | 持久追更配置落地后使用 APScheduler | 任务定义和安全策略 |
+| 定时轮询 | APScheduler 3.11.3(MIT,固定稳定版;3.x `BackgroundScheduler` / interval trigger) | 只在 ledger writer 启动、持久频率、首次延迟、单实例、手动/自动互斥、运行状态与来源错误汇总 |
| 本地文件事件 | watchdog + 定期对账 | 媒体身份和漏报修复 |
| 过渡期元数据/媒体 | Stash GraphQL、CommunityScrapers、Stash 任务系统 | 适配、对账、退出门槛 |
| 局域网发现 | Python zeroconf | 服务生命周期和真实客户端验收 |
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 13fbeffac..33012a060 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -72,6 +72,7 @@
- 2026-08-28 已完成全仓自研实现复用审计:浏览器历史、批处理 PID 锁、Rule34Video 媒体页和 FANBOX 正文模型有成熟替代或参考实现,进入替换队列;MP4 有界索引、固定项目 CA、SQLite 迁移、Gofile、系统网络监听、流媒体会话、单 writer 同步与 Windows 更新因已验证的 Peach 约束继续保留。详细候选、版本、真实 POC 与拒绝理由写入 `docs/REUSE.md`;本轮只改规则与文档,没有新增运行时依赖、部署、生产或 ledger 写入。
- 0.7.3 首项复用替换已完成:FANBOX 正文规范化固定参考 PixivUtil2 `v20251112` / `e537e96`,覆盖 image/text/file/article/video/entry、正文 blocks、四类 map 与旧 HTML;图片和视频进入现有多媒体切换,其他文件保留资源链接,URL 稳定去重。已保存 Cookie 对公开帖 12228983 的只读实测为 article、6 图、Gofile `OS2Qz9`;follow 391 项、正式 Windows 全量 1119 项通过,分别有 1/13 项按平台跳过。
- 0.7.3 正式 EXE 已替换为 SHA-256 `97EBAEE965794D100FA3BC7093B042EB36F1147CDEE1432C3504D7ECFB9D4582`,上版备份为 `dist/Peach/Peach.pre-0.7.3-20260828-152459.exe`;80/443 已由新进程恢复监听,打包迁移为 22 个、0 待处理,项目 CA 严格 HTTPS `/healthz` 返回 200、0.7.3、writer,`/follow` 返回 200。部署没有触发生产检查更新,部署前后 ledger SHA-256 均为 `BC98556370E285C2B627DBA3A36820E79AFF4599A33A265B0DBDDE520379A697`;本改动没有页面、CSS 或交互变化,桌面/手机视觉验收不适用。
+- 0.7.4 追更详情的多图改为左右按钮、方向键和点状分页;多视频继续使用 Mix 右侧队列。直达详情按条目 ID 精确读取,启动时不再先绘制首页。关注入口统一使用 RSS 图标,左侧窄栏与筛选抽屉共用可在设置中调整的顺序。自动追更固定复用 APScheduler 3.11.3,只在 writer 启动,默认每小时、首次等待完整间隔,手动与自动检查共用互斥锁;设置页可关闭或调整为 15 分钟至每天,并显示最近/下次运行状态。正式全量 1130 项先发现 1 条点状分页圆角门槛,修正后覆盖该门槛的 `catalog` 368 项全部通过;全量其余 1129 项通过、13 项按平台跳过。
## 下一批工作
@@ -82,7 +83,7 @@
5. 在 `/review` 人工处理本批 JAV 日文系列名、官方标签及现有创作者标签、FC2、Javinizer、Logo、头像和媒体失败候选;未经批准不写真相字段。
6. 将 Windows writer 的最新副本同步到共享传输点,再让 Mac reader 拉取;同步前后核对迁移版本、计数、完整性与 writer 身份。
7. 在 Mac Finder 以 `smb://peach-win.local/peach-sync` 连接一次并保存钥匙串记录,再重启菜单栏进程,核对自动挂载、reader 锁定、HTTPS、mDNS 和真实 LAN 客户端。
-8. 为追更接入 APScheduler;在实现下载器前先确定媒体凭据、流量与磁盘预算。
+8. 在实现下载器前先确定媒体凭据、流量与磁盘预算。
9. Windows writer 运行 PikPak 夜跑前重算 probe/抽帧队列,并按 `peach-batch-jobs` 设置流量与系统盘闸门。
10. 继续拆分 `web_contract.py` 的 catalog、stats、activity、review、trash 领域,保持路由和现有契约测试不变。
11. 补做 HLS 首帧、seek、自适应码率及桌面/手机视觉验收。
diff --git a/pyproject.toml b/pyproject.toml
index 716beffce..382a64014 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,6 +8,7 @@ dynamic = ["version"]
description = "Local-first media library, behavior ledger, and discovery application"
requires-python = ">=3.12"
dependencies = [
+ "APScheduler==3.11.3",
"beautifulsoup4==4.15.0",
"curl_cffi==0.16.2",
"fastapi==0.116.1",
diff --git a/src/peach/__init__.py b/src/peach/__init__.py
index e71f756e9..5d395ca8b 100644
--- a/src/peach/__init__.py
+++ b/src/peach/__init__.py
@@ -1,3 +1,3 @@
"""Peach application package."""
-__version__ = "0.7.3"
+__version__ = "0.7.4"
diff --git a/src/peach/api.py b/src/peach/api.py
index 52bdcfac1..2b6ffa256 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -17,10 +17,11 @@ from fastapi.responses import (
)
from fastapi.staticfiles import StaticFiles
-from . import __version__, web_contract
+from . import __version__, web_contract, web_follow
from .config import LOCATION_ROOT_DECLARATIONS, PROJECT_ROOT, PeachSettings
from .ffmpeg import FFmpegResolver
from .follow import FollowSourceError
+from .follow_scheduler import FollowUpdateScheduler
from .follow_avatar import resolve_official_avatar
from .follow_store import FollowStore
from .follow_stream import FollowMediaResolver, FollowMediaUnavailable
@@ -123,6 +124,7 @@ def create_app(
cover_root=settings.cover_root,
avatar_root=settings.avatar_root,
logo_root=settings.logo_root,
+ follow_state_root=settings.follow_state_root,
database=database,
)
repository = LedgerRepository(database)
@@ -163,11 +165,18 @@ def create_app(
token=settings.token,
proxy=settings.review_writer_proxy,
)
+ follow_scheduler = FollowUpdateScheduler(
+ settings.follow_state_root,
+ lambda: web_follow.w_follow_check(contract, {"automatic": True}),
+ available=sync is None or not sync.read_only,
+ )
+ contract.follow_scheduler = follow_scheduler
@asynccontextmanager
async def lifespan(_app: FastAPI):
if sync is not None:
sync.start()
+ follow_scheduler.start()
if mdns is not None:
try:
await asyncio.to_thread(mdns.start)
@@ -177,6 +186,7 @@ def create_app(
try:
yield
finally:
+ follow_scheduler.stop()
if mdns is not None:
await asyncio.to_thread(mdns.stop)
if sync is not None:
@@ -208,6 +218,7 @@ def create_app(
app.state.review_mirror = review_mirror
app.state.http_transport = http_transport
app.state.follow_media_resolver = follow_media_resolver
+ app.state.follow_scheduler = follow_scheduler
stream_sessions = StreamSessionRegistry()
app.state.stream_sessions = stream_sessions
app.state.sync = sync
diff --git a/src/peach/config.py b/src/peach/config.py
index 2039bd900..4edfd2f7c 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -120,3 +120,5 @@ class PeachSettings:
stream_root: Path = GENERATED_DIR / "stream-segments"
# 复核候选 CSV 的目录。走 settings 而不是模块常量,测试才不会读到真实的 generated 目录。
candidate_root: Path = GENERATED_DIR
+ # 自动追更频率是本机运行偏好,不属于 ledger 真相。
+ follow_state_root: Path = STATE_DIR
diff --git a/src/peach/follow_scheduler.py b/src/peach/follow_scheduler.py
new file mode 100644
index 000000000..4a3bc9e16
--- /dev/null
+++ b/src/peach/follow_scheduler.py
@@ -0,0 +1,169 @@
+"""APScheduler-backed automatic follow checks and their persisted preference."""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import threading
+from dataclasses import asdict, dataclass
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Callable
+
+from apscheduler.schedulers.background import BackgroundScheduler
+
+
+LOGGER = logging.getLogger(__name__)
+JOB_ID = "peach-follow-update"
+MIN_INTERVAL_MINUTES = 15
+MAX_INTERVAL_MINUTES = 7 * 24 * 60
+
+
+def _stamp(moment: datetime | None = None) -> str:
+ return (moment or datetime.now(timezone.utc)).astimezone(timezone.utc).isoformat().replace(
+ "+00:00", "Z")
+
+
+@dataclass(frozen=True)
+class FollowScheduleConfig:
+ enabled: bool = True
+ interval_minutes: int = 60
+
+
+class FollowScheduleStore:
+ """Small replace-on-write state file; scheduling preferences are not ledger truth."""
+
+ def __init__(self, state_root: Path):
+ self.path = Path(state_root) / "follow-schedule.json"
+
+ @staticmethod
+ def validate(enabled: object, interval_minutes: object) -> FollowScheduleConfig:
+ if not isinstance(enabled, bool) or isinstance(interval_minutes, bool):
+ raise ValueError("enabled must be a boolean and interval_minutes an integer")
+ interval = int(interval_minutes)
+ if not MIN_INTERVAL_MINUTES <= interval <= MAX_INTERVAL_MINUTES:
+ raise ValueError(
+ f"interval_minutes must be between {MIN_INTERVAL_MINUTES} and "
+ f"{MAX_INTERVAL_MINUTES}"
+ )
+ return FollowScheduleConfig(bool(enabled), interval)
+
+ def load(self) -> FollowScheduleConfig:
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ return self.validate(payload.get("enabled", True), payload.get("interval_minutes", 60))
+ except FileNotFoundError:
+ return FollowScheduleConfig()
+ except (OSError, TypeError, ValueError, json.JSONDecodeError):
+ LOGGER.warning("invalid follow schedule preference at %s; using defaults", self.path)
+ return FollowScheduleConfig()
+
+ def save(self, config: FollowScheduleConfig) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = self.path.with_name(f".{self.path.name}.{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps(asdict(config), ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
+ )
+ os.replace(temporary, self.path)
+
+
+class FollowUpdateScheduler:
+ """Own one interval job and expose its state to the settings surface."""
+
+ def __init__(self, state_root: Path, run_check: Callable[[], dict], *, available: bool):
+ self.store = FollowScheduleStore(state_root)
+ self.run_check = run_check
+ self.available = bool(available)
+ self.config = self.store.load()
+ self.scheduler = BackgroundScheduler(timezone=timezone.utc, daemon=True)
+ self._started = False
+ self._state_lock = threading.Lock()
+ self._running = False
+ self._last_started_at: str | None = None
+ self._last_finished_at: str | None = None
+ self._last_error: str | None = None
+ self._last_checked = 0
+ self._last_added = 0
+
+ def start(self) -> None:
+ if self._started or not self.available:
+ return
+ self.scheduler.start()
+ self._started = True
+ self._apply_job()
+
+ def stop(self) -> None:
+ if not self._started:
+ return
+ self.scheduler.shutdown(wait=False)
+ self._started = False
+
+ def update(self, *, enabled: object, interval_minutes: object) -> dict:
+ if not self.available:
+ raise ValueError("automatic follow updates are available only on the ledger writer")
+ self.config = self.store.validate(enabled, interval_minutes)
+ self.store.save(self.config)
+ if self._started:
+ self._apply_job()
+ return self.status()
+
+ def _apply_job(self) -> None:
+ if not self.config.enabled:
+ if self.scheduler.get_job(JOB_ID) is not None:
+ self.scheduler.remove_job(JOB_ID)
+ return
+ interval = self.config.interval_minutes
+ self.scheduler.add_job(
+ self._run,
+ "interval",
+ id=JOB_ID,
+ minutes=interval,
+ next_run_time=datetime.now(timezone.utc) + timedelta(minutes=interval),
+ replace_existing=True,
+ coalesce=True,
+ max_instances=1,
+ misfire_grace_time=min(interval * 60, 300),
+ )
+
+ def _run(self) -> None:
+ with self._state_lock:
+ self._running = True
+ self._last_started_at = _stamp()
+ self._last_error = None
+ try:
+ result = self.run_check()
+ if result.get("busy"):
+ raise RuntimeError("another follow check is already running")
+ rows = result.get("results") or []
+ failures = [row for row in rows if not row.get("ok")]
+ with self._state_lock:
+ self._last_checked = int(result.get("checked") or 0)
+ self._last_added = sum(int(row.get("added") or 0) for row in rows)
+ if failures:
+ self._last_error = f"{len(failures)} 个来源检查失败"
+ except Exception as error: # the background job must never terminate the scheduler
+ LOGGER.exception("automatic follow update failed")
+ with self._state_lock:
+ self._last_error = str(error)
+ finally:
+ with self._state_lock:
+ self._running = False
+ self._last_finished_at = _stamp()
+
+ def status(self) -> dict:
+ job = self.scheduler.get_job(JOB_ID) if self._started else None
+ next_run = job.next_run_time if job is not None else None
+ with self._state_lock:
+ return {
+ "ok": True,
+ "available": self.available,
+ "enabled": self.config.enabled,
+ "interval_minutes": self.config.interval_minutes,
+ "running": self._running,
+ "next_run_at": _stamp(next_run) if next_run else None,
+ "last_started_at": self._last_started_at,
+ "last_finished_at": self._last_finished_at,
+ "last_error": self._last_error,
+ "last_checked": self._last_checked,
+ "last_added": self._last_added,
+ }
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index eba4cfe19..1cc09a782 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -313,6 +313,23 @@ class FollowStore:
).fetchone()
return self._row(row) if row is not None else None
+ def items_for_item(self, item_id: int) -> tuple[FollowItemRow, ...]:
+ """Return the target and its grouping peers for a direct detail route."""
+ target = self.item(item_id)
+ if target is None:
+ return ()
+ clauses = ["i.release_key=?"]
+ params: list[object] = [target.release_key]
+ if target.group_hint:
+ clauses.append("i.group_hint=?")
+ params.append(target.group_hint)
+ rows = self._connect().execute(
+ self._SELECT + " WHERE " + " OR ".join(clauses) +
+ " ORDER BY COALESCE(i.published_at, i.first_seen_at) DESC, i.id DESC",
+ params,
+ ).fetchall()
+ return tuple(self._row(row) for row in rows)
+
@staticmethod
def _row(row) -> FollowItemRow:
try:
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 159e22cb9..08e859fa1 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -40,7 +40,8 @@ from .platform import (
)
from .repository import LedgerDatabase
from .web_follow import (
- q_follow, q_follow_credentials, w_follow_check, w_follow_credential, w_follow_resolve,
+ q_follow, q_follow_credentials, q_follow_schedule,
+ w_follow_check, w_follow_credential, w_follow_resolve, w_follow_schedule,
w_follow_author_alias, w_follow_save, w_follow_source, w_follow_status,
)
from .web_activity import (
@@ -130,6 +131,8 @@ class WebContract:
self.write_lock = self.database.write_lock
self.cache: dict[str, tuple[float, object]] = {}
self.cache_lock = threading.Lock()
+ self.follow_check_lock = threading.Lock()
+ self.follow_scheduler = None
self._fts_available: bool | None = None
def cached(self, key, fn):
@@ -2590,6 +2593,7 @@ def _post_empty_trash(contract, _body):
GET_HANDLERS = {
"/api/follow": q_follow,
"/api/follow/credentials": q_follow_credentials,
+ "/api/follow/schedule": q_follow_schedule,
"/api/items": q_items,
"/api/item": _get_item,
"/api/entity": q_entity,
@@ -2611,6 +2615,7 @@ GET_HANDLERS = {
POST_HANDLERS = {
"/api/follow/check": w_follow_check,
+ "/api/follow/schedule": w_follow_schedule,
"/api/follow/source": w_follow_source,
"/api/follow/author-alias": w_follow_author_alias,
"/api/follow/resolve": w_follow_resolve,
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 4f4692d66..27dd8f850 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -1,6 +1,7 @@
"""追更的 Web 契约层。
-读接口无副作用;`/api/follow/check` 是唯一会联网的端点,且只在用户显式点击时触发。
+读接口无副作用;`/api/follow/check` 是唯一会联网的端点,可由用户点击或已启用的
+APScheduler 任务触发。
`/api/follow/save` 写真相,走和 CLI 同一个 `save_asset(confirm=True)` 边界。
"""
from __future__ import annotations
@@ -533,6 +534,8 @@ def q_follow(contract, args) -> dict:
limit = 200
source = args.get("source")
source_id = int(source) if str(source or "").isdigit() else None
+ requested_item = args.get("item")
+ item_id = int(requested_item) if str(requested_item or "").isdigit() else None
with contract.database.read_connection() as connection:
store = _store(contract, connection)
source_rows = store.sources()
@@ -540,9 +543,13 @@ def q_follow(contract, args) -> dict:
sources = [_source_payload(row, alias_map) for row in source_rows]
alias_suggestions = _follow_alias_suggestions(source_rows, alias_map)
enabled_source_ids = {int(row["id"]) for row in source_rows if row["enabled"]}
- items = tuple(item for item in store.items(
- statuses=statuses, source_id=source_id, limit=limit)
- if item.source_id in enabled_source_ids and not _excluded_item(item))
+ if item_id is not None:
+ items = tuple(item for item in store.items_for_item(item_id)
+ if item.source_id in enabled_source_ids and not _excluded_item(item))
+ else:
+ items = tuple(item for item in store.items(
+ statuses=statuses, source_id=source_id, limit=limit)
+ if item.source_id in enabled_source_ids and not _excluded_item(item))
groups = [_group_payload(group) for group in store.group(items)]
counts = dict(connection.execute(
"SELECT i.status, count(*) FROM follow_item i"
@@ -658,6 +665,15 @@ def w_follow_check(contract, body) -> dict:
没有 `source` 就检查全部已启用来源。逐个来源独立成败:一个来源缺凭据或被
机器人验证挡住,不该让其余来源的更新一起消失。
"""
+ if not contract.follow_check_lock.acquire(blocking=False):
+ return {"ok": False, "busy": True, "checked": 0, "results": []}
+ try:
+ return _run_follow_check(contract, body)
+ finally:
+ contract.follow_check_lock.release()
+
+
+def _run_follow_check(contract, body) -> dict:
requested = body.get("source")
source_id = requested if isinstance(requested, int) else None
# 往回抓一页。这是**显式的、一次一页**的动作:常规检查永远只看第一页,
@@ -719,6 +735,24 @@ def w_follow_check(contract, body) -> dict:
return {"ok": True, "checked": len(results), "results": results}
+def q_follow_schedule(contract, _args) -> dict:
+ scheduler = contract.follow_scheduler
+ if scheduler is None:
+ return {"ok": True, "available": False, "enabled": False,
+ "interval_minutes": 60, "running": False, "next_run_at": None}
+ return scheduler.status()
+
+
+def w_follow_schedule(contract, body) -> dict:
+ scheduler = contract.follow_scheduler
+ if scheduler is None:
+ raise ValueError("automatic follow updates are unavailable")
+ return scheduler.update(
+ enabled=body.get("enabled", True),
+ interval_minutes=body.get("interval_minutes", 60),
+ )
+
+
def _failure(contract, row, error, moment, status) -> dict:
with contract.database.write_transaction() as connection:
_store(contract, connection).record_error(
diff --git a/tests/test_follow_scheduler.py b/tests/test_follow_scheduler.py
new file mode 100644
index 000000000..fc484ebc1
--- /dev/null
+++ b/tests/test_follow_scheduler.py
@@ -0,0 +1,61 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from peach.follow_scheduler import (
+ FollowScheduleConfig,
+ FollowScheduleStore,
+ FollowUpdateScheduler,
+)
+
+
+class FollowScheduleStoreTests(unittest.TestCase):
+ def test_defaults_are_enabled_hourly_and_updates_are_atomic(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ store = FollowScheduleStore(Path(temporary))
+ self.assertEqual(store.load(), FollowScheduleConfig(True, 60))
+ store.save(FollowScheduleConfig(False, 180))
+ self.assertEqual(store.load(), FollowScheduleConfig(False, 180))
+
+ def test_unbounded_intervals_are_rejected(self):
+ with self.assertRaises(ValueError):
+ FollowScheduleStore.validate(True, 14)
+ with self.assertRaises(ValueError):
+ FollowScheduleStore.validate(True, 10081)
+ with self.assertRaises(ValueError):
+ FollowScheduleStore.validate("false", 60)
+
+
+class FollowUpdateSchedulerTests(unittest.TestCase):
+ def test_interval_job_waits_one_interval_and_can_be_disabled(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ scheduler = FollowUpdateScheduler(Path(temporary), lambda: {"ok": True}, available=True)
+ self.addCleanup(scheduler.stop)
+ scheduler.start()
+ status = scheduler.status()
+ self.assertTrue(status["enabled"])
+ self.assertIsNotNone(status["next_run_at"])
+ status = scheduler.update(enabled=False, interval_minutes=60)
+ self.assertFalse(status["enabled"])
+ self.assertIsNone(status["next_run_at"])
+
+ def test_run_status_reports_checked_sources_and_additions(self):
+ result = {"ok": True, "checked": 2, "results": [
+ {"ok": True, "added": 3}, {"ok": False, "added": 0},
+ ]}
+ with tempfile.TemporaryDirectory() as temporary:
+ scheduler = FollowUpdateScheduler(Path(temporary), lambda: result, available=True)
+ scheduler._run()
+ status = scheduler.status()
+ self.assertEqual(status["last_checked"], 2)
+ self.assertEqual(status["last_added"], 3)
+ self.assertEqual(status["last_error"], "1 个来源检查失败")
+ self.assertIsNotNone(status["last_finished_at"])
+
+ def test_reader_never_starts_or_accepts_schedule_changes(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ scheduler = FollowUpdateScheduler(Path(temporary), lambda: {}, available=False)
+ scheduler.start()
+ self.assertFalse(scheduler.status()["available"])
+ with self.assertRaises(ValueError):
+ scheduler.update(enabled=True, interval_minutes=60)
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 7b6d39422..4027f6c21 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -167,6 +167,13 @@ class FollowContractTests(unittest.TestCase):
primary = self._get()["groups"][0]["primary"]
self.assertEqual(primary["published_precision"], "approximate")
+ def test_feed_can_restore_one_exact_item_outside_the_recent_limit(self):
+ self._seed()
+ item_id = self._get()["groups"][0]["primary"]["id"]
+ payload = self._get(item=str(item_id), limit="1")
+ self.assertEqual(payload["groups"][0]["primary"]["id"], item_id)
+ self.assertEqual(len(payload["groups"][0]["variants"]), 1)
+
def test_feed_never_exposes_the_raw_media_url(self):
# 界面只需要知道有没有媒体;直链是来源层的事,不进公共 JSON。
self._seed()
@@ -913,14 +920,15 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertIn("follow", keys)
self.assertEqual(keys[keys.index("follow") + 1], "immerse",
"关注入口应当排在沉浸模式前面")
- self.assertPageContains("['follow','关注','globe']")
+ self.assertPageContains("['follow','关注','rss']")
self.assertPageContains("if(k==='follow'){openFollow();return}")
self.assertPageContains("if(k==='follow')return path==='/follow';")
# 两个数组现在同名,字面量断言分不出是哪一个:
# 管理区这一项得在 MANAGE_SECTIONS 里找,否则它被删了测试照样绿。
manage = self.page[self.page.index("const MANAGE_SECTIONS=["):]
manage = manage[:manage.index("];")]
- self.assertIn("['follow','关注','globe']", manage)
+ self.assertIn("['follow','关注','rss']", manage)
+ self.assertPageContains('<symbol id="i-rss"')
self.assertPageContains("if(path==='/follow-manage')return 'follow'")
self.assertPageContains("if(section==='follow'){openFollowManage();return}")
@@ -930,6 +938,8 @@ class FollowWebSourceTests(unittest.TestCase):
"if(path==='/follow-manage'){await openFollowManage(false);return}")
self.assertPageContains(
"if(parts[0]==='follow'&&parts[1]==='item'&&/^\\d+$/.test(parts[2]||'')){await openFollowDetail(+parts[2],false);return}")
+ self.assertPageContains("api(`/api/follow?item=${encodeURIComponent(id)}`)")
+ self.assertPageContains(".then(async()=>{buildEdge();wireAllDrag();await restoreRoute();scheduleStickySurfaces()})")
def test_the_add_state_is_looked_up_outside_the_form(self):
# 提示行在表单外面。在 form 里找它会拿到 null,第一次赋值就抛 TypeError,
@@ -1237,11 +1247,11 @@ class FollowWebSourceTests(unittest.TestCase):
'class="mav fsourceavatar" title="${esc(item.provider_label)}">${sourceIcon(item.provider)}',
self.page,
)
- self.assertPageContains("async function openFollowDetail(id,push=true,mediaIndex=null)")
+ self.assertPageContains("async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=false)")
self.assertPageContains("const src=item.playable?`/follow-stream?id=${item.id}${selectedMedia?")
self.assertPageContains('data-follow-detail="${item.id}"')
self.assertPageContains("route(`/follow/item/${item.id}`)")
- self.assertPageContains('class="sgrid followdetailgrid${collection||embedded.length>1?\' mixgrid\':\'\'}"')
+ self.assertPageContains('class="sgrid followdetailgrid${collection||embeddedQueue?\' mixgrid\':\'\'}"')
self.assertPageContains('class="followorigin" href="${esc(item.url)}" target="_blank"')
self.assertPageContains('title="打开来源页面" aria-label="打开来源页面"')
self.assertNotIn('打开来源页面</a>', self.page)
@@ -1258,6 +1268,14 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("route(followDetailReturnPath||'/follow')")
self.assertPageContains(".followitem a{text-decoration:none}")
+ def test_follow_image_collections_use_buttons_dots_and_arrow_keys(self):
+ self.assertPageContains('class="followimagearrow prev"')
+ self.assertPageContains('class="followimagedots" role="group"')
+ self.assertPageContains('data-follow-image-item="${image.index}"')
+ self.assertPageContains("imageDots.length&&(e.key==='ArrowLeft'||e.key==='ArrowRight')")
+ self.assertPageContains("openFollowDetail(item.id,false,+index,true)")
+ self.assertPageContains(".followimagedots button[aria-current=\"true\"]")
+
def test_follow_filters_put_all_first_and_sources_are_icon_only(self):
self.assertPageContains("const FOLLOW_FILTERS=[['','全部'],['new','未看']")
self.assertPageContains('title="${esc(label)}" aria-label="来源:${esc(label)}">${sourceIcon(key)}</button>')
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index e6e36c5c5..17de6e838 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -461,7 +461,7 @@ class WebDataTests(unittest.TestCase):
"/api/index", "/api/duplicates", "/api/quality-goals",
"/api/stats", "/api/tops", "/api/ads", "/api/related", "/api/facets",
"/api/search-history", "/api/review", "/api/playlists", "/api/playlist",
- "/api/follow", "/api/follow/credentials",
+ "/api/follow", "/api/follow/credentials", "/api/follow/schedule",
})
self.assertEqual(set(rm_web.POST_HANDLERS), {
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
@@ -471,7 +471,7 @@ class WebDataTests(unittest.TestCase):
"/api/purge-missing", "/api/review/auto-apply",
"/api/follow/check", "/api/follow/status", "/api/follow/save",
"/api/follow/source", "/api/follow/resolve", "/api/follow/credential",
- "/api/follow/author-alias",
+ "/api/follow/author-alias", "/api/follow/schedule",
})
with self.assertRaises(rm_web.ContractRouteNotFound):
rm_web.dispatch_api_get(self.contract, "/api/typo", {})
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 12e9247e8..2c586711a 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -1111,6 +1111,11 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("appSettings.seekSeconds")
self.assertPageContains("appSettings.searchHistoryLimit")
self.assertPageContains("appSettings.relatedLimit")
+ self.assertPageContains('id="followScheduleSetting"')
+ self.assertPageContains("api('/api/follow/schedule'")
+ self.assertPageContains('id="sidebarOrderSetting"')
+ self.assertPageContains("appSettings.sidebarOrder")
+ self.assertPageContains("orderedEdgeIcons()")
self.assertPageLacks('id="ambientSetting"')
self.assertPageContains("color:#f5f7fa;color-scheme:dark")
diff --git a/web/app.css b/web/app.css
index 07083ea56..4143cdf95 100644
--- a/web/app.css
+++ b/web/app.css
@@ -907,6 +907,7 @@ body.index-open #tiers,body.index-open #tagbar{display:none}
内边距**里侧**,于是离右边框差着一大截,和桌面 Chromium 的样子也对不上。
`appearance:none` 关掉系统绘制,用背景图贴住右边框。 */
.settingrow select{min-width:148px;border:1px solid var(--line);border-radius:8px;background:#181a1d;color:#f5f7fa;color-scheme:dark;padding:9px 34px 9px 11px;font:inherit;font-size:var(--fs-md);appearance:none;-webkit-appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238e949e' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;background-size:16px 16px}.settingrow select:focus-visible{outline:2px solid var(--tungsten);outline-offset:2px}.settingrow select option{background:#181a1d;color:#f5f7fa}.settingrow input[type=checkbox]{width:20px;height:20px;accent-color:var(--tungsten)}
+.sidebarsetting{display:grid;gap:12px;padding:14px 0 0;border-top:1px solid var(--line-soft)}.sidebarsetting>span b,.sidebarsetting>span small{display:block}.sidebarsetting>span small{margin-top:3px;color:var(--muted);line-height:1.45}.sidebarorder{display:grid;gap:6px}.sidebarorderrow{display:flex;align-items:center;justify-content:space-between;min-height:44px;padding:5px 6px 5px 11px;border:1px solid var(--line-soft);border-radius:9px;background:var(--overlay-3)}.sidebarorderrow>span{display:flex;align-items:center;gap:8px}.sidebarorderrow svg{width:18px;height:18px;stroke:currentColor;fill:none}.sidebarorderrow button{display:grid;place-items:center;width:34px;height:34px;border:0;border-radius:7px;background:transparent;color:var(--muted);cursor:pointer}.sidebarorderrow button:hover:not(:disabled){background:var(--hover);color:var(--ink)}.sidebarorderrow button:disabled{opacity:.25;cursor:default}
@media(max-width:600px){.settingscard{padding:17px}.settingrow{grid-template-columns:1fr;gap:9px}.settingrow select{width:100%;min-width:0}.settingrow input[type=checkbox]{justify-self:start}}
/* ── 筛选抽屉(默认收起,不占版面) ── */
@@ -1264,7 +1265,7 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.fstate{flex:1 1 100%;font-size:var(--fs-xs);color:var(--drop)}
.fvkind{display:inline-block;max-width:120px;margin-right:6px;padding:1px 7px;border-radius:var(--badge-radius);overflow:hidden;text-overflow:ellipsis;vertical-align:-2px;background:var(--overlay-5);color:var(--muted);font-size:var(--fs-xs);font-style:normal}
.fvkind.wip{color:var(--meter)}.fvkind.alt{color:var(--tungsten)}
-.followdetailmedia{min-height:min(62vh,640px)}.followdetailposter{position:relative;z-index:1;display:block;width:100%;height:100%;max-height:76vh;object-fit:contain;background:#000}
+.followdetailmedia{min-height:min(62vh,640px)}.followdetailposter{position:relative;z-index:1;display:block;width:100%;height:100%;max-height:76vh;object-fit:contain;background:#000}.followimagearrow{position:absolute;z-index:4;top:50%;transform:translateY(-50%);display:grid;place-items:center;width:46px;height:46px;border:1px solid rgba(255,255,255,.24);border-radius:50%;background:rgba(0,0,0,.56);color:#fff;cursor:pointer;backdrop-filter:blur(10px)}.followimagearrow:hover{background:rgba(255,255,255,.18)}.followimagearrow.prev{left:16px}.followimagearrow.next{right:16px}.followimagearrow svg{width:25px;height:25px;stroke:currentColor;fill:none}.followimagedots{position:absolute;z-index:4;left:50%;bottom:18px;transform:translateX(-50%);display:flex;align-items:center;justify-content:center;gap:8px;max-width:calc(100% - 120px);padding:8px 11px;border-radius:14px;background:rgba(0,0,0,.5);overflow:hidden}.followimagedots button{flex:none;width:8px;height:8px;padding:0;border:0;border-radius:50%;background:rgba(255,255,255,.42);cursor:pointer}.followimagedots button[aria-current="true"]{width:20px;border-radius:5px;background:#fff}
.followdetailplaceholder{display:grid;place-items:center;gap:10px;color:var(--muted)}.followdetailplaceholder .ficon{width:34px;height:34px;margin:0}
.followdetailtitle{display:flex;gap:5px;align-items:flex-start;margin-bottom:8px}.followdetailtitle .stitle{width:auto;max-width:calc(100% - 35px);margin:0}.followdetailtitle .followorigin{flex:none;width:30px;height:30px;margin:0;display:grid;place-items:center;border-radius:7px}.followdetailtitle .followorigin:hover{background:var(--hover)}
.followdetailidentity{display:flex;align-items:center;gap:10px;margin:2px 0 12px}.followdetailidentity .mav{flex:none}.followdetailidentity b,.followdetailidentity span{display:block}.followdetailidentity>div>span{margin-top:3px;color:var(--muted);font-size:var(--fs-xs)}
@@ -1272,6 +1273,7 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.fnote.followmedianote{margin:18px 0 8px}.followresources{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 16px}.followresources a{display:inline-flex;align-items:center;gap:7px;height:34px;padding:0 11px;border:1px solid var(--border-15);border-radius:7px;color:var(--ink-2);text-decoration:none}.followresources a:hover{border-color:var(--tungsten);color:var(--ink);text-decoration:none}.followresources svg{width:15px;height:15px;stroke:currentColor;fill:none}.followdetailactions{margin-top:2px}.followdetailactions button:disabled{opacity:.45;cursor:default}.followorigin{display:inline-flex;align-items:center;gap:7px;width:max-content;margin-top:auto;color:var(--muted);text-decoration:none}.followorigin svg{width:16px;height:16px;stroke:currentColor;fill:none}.followorigin:hover{color:var(--ink);text-decoration:none}
@media (max-width:640px){.followhead{align-items:center}.follow .fcheck{height:36px;padding:0 13px}
.followauthors{margin-right:-12px;padding-top:3px}.followfilters{margin-right:-12px;padding-right:12px}
+ .followimagearrow{width:42px;height:42px}.followimagearrow.prev{left:10px}.followimagearrow.next{right:10px}.followimagedots{bottom:12px}
}
/* ── 关注管理页 ──
diff --git a/web/app.js b/web/app.js
index 8c35002c1..f1aebc2c7 100644
--- a/web/app.js
+++ b/web/app.js
@@ -71,7 +71,8 @@ function dropOfflineFromDefaultLoc(){
}
const DURATION_TAGS=new Set(['短片-2分内','中片-10分内','长片-30分内','超长片-30分上']);
const SETTINGS_KEY='peach.settings.v1';
-const DEFAULT_SETTINGS={rotateMinutes:0,batchSize:60,defaultSort:'seed',hoverDelaySeconds:5,seekSeconds:10,searchHistoryLimit:10,relatedLimit:20,javLayout:'big'};
+const DEFAULT_SIDEBAR_ORDER=['','performers','tags','jav','flagged','playlists','follow','immerse','manage'];
+const DEFAULT_SETTINGS={rotateMinutes:0,batchSize:60,defaultSort:'seed',hoverDelaySeconds:5,seekSeconds:10,searchHistoryLimit:10,relatedLimit:20,javLayout:'big',sidebarOrder:DEFAULT_SIDEBAR_ORDER};
let appSettings={...DEFAULT_SETTINGS};
try{appSettings={...DEFAULT_SETTINGS,...JSON.parse(localStorage.getItem(SETTINGS_KEY)||'{}')}}catch(_e){}
const allowedSetting=(value,allowed,fallback)=>allowed.includes(value)?value:fallback;
@@ -82,6 +83,7 @@ appSettings.hoverDelaySeconds=allowedSetting(+appSettings.hoverDelaySeconds,[3,5
appSettings.seekSeconds=allowedSetting(+appSettings.seekSeconds,[5,10,30],10);
appSettings.searchHistoryLimit=allowedSetting(+appSettings.searchHistoryLimit,[5,10,20],10);
appSettings.relatedLimit=allowedSetting(+appSettings.relatedLimit,[12,20,30],20);
+appSettings.sidebarOrder=[...new Set([...(Array.isArray(appSettings.sidebarOrder)?appSettings.sidebarOrder:[]),...DEFAULT_SIDEBAR_ORDER])].filter(key=>DEFAULT_SIDEBAR_ORDER.includes(key));
document.documentElement.style.setProperty('--hover-delay',`${appSettings.hoverDelaySeconds}s`);
const saveSettings=()=>localStorage.setItem(SETTINGS_KEY,JSON.stringify(appSettings));
function syncSettingsPanel(){
@@ -92,6 +94,8 @@ function syncSettingsPanel(){
$('#seekSecondsSetting').value=String(appSettings.seekSeconds);
$('#searchHistoryLimitSetting').value=String(appSettings.searchHistoryLimit);
$('#relatedLimitSetting').value=String(appSettings.relatedLimit);
+ renderSidebarOrderSetting();
+ loadFollowScheduleSetting();
}
let settingsReturnFocus=null;
function openSettings(open=true){
@@ -121,6 +125,32 @@ $('#hoverDelaySetting').onchange=e=>{appSettings.hoverDelaySeconds=+e.target.val
$('#seekSecondsSetting').onchange=e=>{appSettings.seekSeconds=+e.target.value||10;saveSettings()};
$('#searchHistoryLimitSetting').onchange=e=>{appSettings.searchHistoryLimit=+e.target.value||10;saveSettings();writeSearchHistory(readSearchHistory())};
$('#relatedLimitSetting').onchange=e=>{appSettings.relatedLimit=+e.target.value||20;saveSettings()};
+let followScheduleRequest=0;
+const followScheduleCopy=status=>{
+ if(!status.available)return '只在账本写入端运行';
+ if(status.running)return '正在检查全部来源…';
+ if(status.last_error)return `上次失败:${status.last_error}`;
+ if(status.last_finished_at)return `上次完成 ${localTime(status.last_finished_at)} · 新增 ${status.last_added||0}`;
+ if(status.next_run_at)return `下次 ${localTime(status.next_run_at)}`;
+ return status.enabled?'等待首次运行':'已关闭';
+};
+async function loadFollowScheduleSetting(){
+ const select=$('#followScheduleSetting'),state=$('#followScheduleState'),request=++followScheduleRequest;
+ select.disabled=true;
+ try{
+ const status=await api('/api/follow/schedule');if(request!==followScheduleRequest)return;
+ select.value=status.enabled?String(status.interval_minutes):'0';
+ select.disabled=!status.available;state.textContent=followScheduleCopy(status);
+ }catch(error){if(request===followScheduleRequest)state.textContent=`状态未取得:${error.message||error}`}
+}
+$('#followScheduleSetting').onchange=async e=>{
+ const minutes=+e.target.value,state=$('#followScheduleState');e.target.disabled=true;state.textContent='正在保存…';
+ try{
+ const status=await api('/api/follow/schedule',{method:'POST',body:JSON.stringify({enabled:minutes>0,interval_minutes:minutes||60})});
+ state.textContent=followScheduleCopy(status);
+ }catch(error){state.textContent=error.message||'保存失败'}
+ finally{e.target.disabled=false}
+};
/* 来源图标:品牌使用已缓存的官方资产;通用操作图标统一使用本地 Lucide 子集。 */
const SRCICON={
local:icon('hard-drive'),
@@ -785,7 +815,7 @@ async function buildBars(){
`<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">
<b class="disp" style="font-size:15px;letter-spacing:.1em">导航与筛选</b>
<button id="drawerClose" class="ib" title="收起">${icon('x')}</button></div>`+
- `<div class="dnav">${EDGE_ICONS.map(([k,label,ic])=>navBtn(k,label,ic)).join('')}</div>`+
+ `<div class="dnav">${orderedEdgeIcons().map(([k,label,ic])=>navBtn(k,label,ic)).join('')}</div>`+
sec('来源',chips(facetData.locations.map(l=>({k:l.k,label:LOC[l.k]||l.k,n:l.n,
cost:(l.k==='pikpak'||l.k==='online')?'metered':'free'})),'loc',true),'','src')
+sec('时长',facetData.stats.duration?`<div class="duration-filter"><div class="duration-readout"><span id="durMinText">不限</span><b>—</b><span id="durMaxText">不限</span></div>
@@ -1408,23 +1438,27 @@ function indexFollowItems(data){
async function followItemById(id){
if(followItemsById.has(id))return followItemsById.get(id);
- const data=await api('/api/follow?limit=1000');
+ const data=await api(`/api/follow?item=${encodeURIComponent(id)}`);
if(!followData)followData=data;
indexFollowItems(data);
return followItemsById.get(id);
}
-async function openFollowDetail(id,push=true,mediaIndex=null){
+async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=false){
releaseHoverPreviews();
const entering=!location.pathname.startsWith('/follow/item/');
if(push&&entering)followDetailReturnPath=location.pathname+location.search;
- if(!push)followDetailReturnPath='/follow';
+ if(!push&&!preserveReturn)followDetailReturnPath='/follow';
const item=await followItemById(+id);if(!item)return;
const group=followGroupByItemId.get(item.id);
const embedded=item.media_items||[];
const selectedMedia=embedded.length
?embedded.find(media=>media.index===(mediaIndex??embedded[0].index))||embedded[0]
:null;
+ const imageMedia=embedded.filter(media=>media.media_kind==='image');
+ const imagePosition=imageMedia.findIndex(media=>media.index===selectedMedia?.index);
+ const imageCarousel=imageMedia.length>1&&imagePosition>=0;
+ const embeddedQueue=embedded.length>1&&!imageCarousel;
const collection=!embedded.length&&group&&followVideoItems(group).length>1?group:null;
disposeStage(false);
if(push)route(`/follow/item/${item.id}`);
@@ -1441,14 +1475,17 @@ async function openFollowDetail(id,push=true,mediaIndex=null){
:item.thumb_url
?`<img class="followdetailposter" src="${esc(item.thumb_url)}" alt="${esc(item.title)}" referrerpolicy="no-referrer">`
:`<div class="followdetailplaceholder">${sourceIcon(item.provider)}<span>没有可用预览</span></div>`;
+ const imageControls=imageCarousel?`<button class="followimagearrow prev" data-follow-image-step="-1" aria-label="上一张图片" title="上一张">${icon('chevron-left')}</button>
+ <button class="followimagearrow next" data-follow-image-step="1" aria-label="下一张图片" title="下一张">${icon('chevron-right')}</button>
+ <div class="followimagedots" role="group" aria-label="${imageMedia.length} 张图片">${imageMedia.map((image,index)=>`<button data-follow-image-item="${image.index}" aria-current="${index===imagePosition}" aria-label="第 ${index+1} 张,共 ${imageMedia.length} 张" title="第 ${index+1} 张"></button>`).join('')}</div>`:'';
const badges=followBadges({primary:item,variants:[],duplicates:[],has_wip:item.variant_kind==='wip'});
const tags=(item.tags||[]).map(tag=>followTagChip(item,tag,'button')).join('');
const author=followAuthorName(authorSources)||item.author||item.source_label||'作者未取得';
const postedBy=item.author&&foldName(item.author)!==foldName(author)?item.author:'';
$('#stage').hidden=false;document.body.classList.add('detail-open');
- $('#stage').innerHTML=`<div class="sgrid followdetailgrid${collection||embedded.length>1?' mixgrid':''}">
- <div class="vwrap followdetailmedia"><button class="closestage" id="closeStage" title="关闭" aria-label="关闭">${icon('x')}</button>${media}</div>
- ${embedded.length>1?followEmbeddedQueueHtml(item,selectedMedia.index):(collection?followQueueHtml(collection,item.id):'')}
+ $('#stage').innerHTML=`<div class="sgrid followdetailgrid${collection||embeddedQueue?' mixgrid':''}">
+ <div class="vwrap followdetailmedia"><button class="closestage" id="closeStage" title="关闭" aria-label="关闭">${icon('x')}</button>${media}${imageControls}</div>
+ ${embeddedQueue?followEmbeddedQueueHtml(item,selectedMedia.index):(collection?followQueueHtml(collection,item.id):'')}
<div class="side followdetailside">
<div class="followdetailtitle"><div class="stitle">${esc(item.title)}</div>${item.url?`<a class="followorigin" href="${esc(item.url)}" target="_blank" rel="noreferrer noopener" title="打开来源页面" aria-label="打开来源页面">${icon('external-link')}</a>`:''}</div>
<div class="followdetailidentity"><span class="mav fsourceavatar">${followAuthorAvatar(authorSources)}</span>
@@ -1471,7 +1508,14 @@ async function openFollowDetail(id,push=true,mediaIndex=null){
$('#stage').querySelectorAll('[data-follow-queue-item]').forEach(button=>button.onclick=()=>
openFollowDetail(+button.dataset.followQueueItem,true));
$('#stage').querySelectorAll('[data-follow-media-item]').forEach(button=>button.onclick=()=>
- openFollowDetail(item.id,true,+button.dataset.followMediaItem));
+ openFollowDetail(item.id,false,+button.dataset.followMediaItem,true));
+ const switchImage=index=>openFollowDetail(item.id,false,+index,true);
+ $('#stage').querySelectorAll('[data-follow-image-item]').forEach(button=>button.onclick=()=>
+ switchImage(button.dataset.followImageItem));
+ $('#stage').querySelectorAll('[data-follow-image-step]').forEach(button=>button.onclick=()=>{
+ const next=(imagePosition+(+button.dataset.followImageStep)+imageMedia.length)%imageMedia.length;
+ switchImage(imageMedia[next].index);
+ });
$('#stage').querySelectorAll('.followdetailtags [data-follow-tag]').forEach(button=>button.onclick=async()=>{
const tag=button.dataset.followTag;
if(followTags.has(tag))followTags.delete(tag);else followTags.add(tag);
@@ -1952,7 +1996,7 @@ function renderFollowManage(credentials){
counts.new?` · <b>${counts.new}</b> 条未看`:''}</span>
<button class="fbtn" data-follow-check=""${sources.length?'':' disabled'}>${
icon('refresh-cw')}检查全部</button>
- <button class="fbtn" data-follow-view>${icon('globe')}去看更新</button></div>
+ <button class="fbtn" data-follow-view>${icon('rss')}去看更新</button></div>
${followCheckReport?followCheckSummary(followCheckReport):''}
${broken.length?`<p class="fnote warn">${broken.length} 个来源上次检查失败,原因见对应那一行。</p>`:''}
${sources.length?`<div class="frows fsources">${
@@ -2809,7 +2853,7 @@ const EDGE_ICONS=[
['jav','JAV','jav'],
['flagged','已标记','star'],
['playlists','播放列表','list-filter'],
- ['follow','关注','globe'],
+ ['follow','关注','rss'],
['immerse','沉浸模式','play'],
['manage','管理','settings'],
];
@@ -2824,9 +2868,29 @@ const MANAGE_SECTIONS=[
['ads','疑似广告','alert'],
['dupes','重复文件','hard-drive'],
['trash','回收站','trash'],
- ['follow','关注','globe'],
+ ['follow','关注','rss'],
['quality','高清版','sparkles'],
];
+function orderedEdgeIcons(){
+ const byKey=new Map(EDGE_ICONS.map(item=>[item[0],item]));
+ return appSettings.sidebarOrder.map(key=>byKey.get(key)).filter(Boolean);
+}
+function renderSidebarOrderSetting(){
+ const root=$('#sidebarOrderSetting');if(!root)return;
+ const labels=new Map(EDGE_ICONS.map(([key,label])=>[key,label]));
+ root.innerHTML=appSettings.sidebarOrder.map((key,index)=>{
+ const entry=EDGE_ICONS.find(item=>item[0]===key),label=labels.get(key)||key;
+ return `<div class="sidebarorderrow"><span>${icon(entry?.[2]||'home')}<b>${esc(label)}</b></span><span>
+ <button data-sidebar-key="${esc(key)}" data-sidebar-move="-1" aria-label="上移 ${esc(label)}" title="上移"${index===0?' disabled':''}>${icon('chevron-up')}</button>
+ <button data-sidebar-key="${esc(key)}" data-sidebar-move="1" aria-label="下移 ${esc(label)}" title="下移"${index===appSettings.sidebarOrder.length-1?' disabled':''}>${icon('chevron-down')}</button></span></div>`;
+ }).join('');
+ root.querySelectorAll('[data-sidebar-move]').forEach(button=>button.onclick=()=>{
+ const from=appSettings.sidebarOrder.indexOf(button.dataset.sidebarKey),to=from+(+button.dataset.sidebarMove);
+ if(from<0||to<0||to>=appSettings.sidebarOrder.length)return;
+ const next=[...appSettings.sidebarOrder];[next[from],next[to]]=[next[to],next[from]];
+ appSettings.sidebarOrder=next;saveSettings();renderSidebarOrderSetting();buildEdge();buildBars();
+ });
+}
function manageSection(){
const path=decodeURIComponent(location.pathname);
if(path==='/stats')return 'stats';
@@ -2970,7 +3034,7 @@ function syncHeaderActions(){
if(!canSelect&&selectMode)setSelectMode(false,true);
}
function buildEdge(){
- $('#edge').innerHTML=EDGE_ICONS.map(([k,t,ic])=>
+ $('#edge').innerHTML=orderedEdgeIcons().map(([k,t,ic])=>
`<button data-nav="${k}" title="${t}" aria-pressed="${navOn(k)}">
${icon(ic)}</button>`).join('')
;
@@ -3855,6 +3919,13 @@ document.addEventListener('keydown',e=>{
}
// 输入态不抢键:搜索框、标签弹窗和任何可编辑区域里的按键归它们自己处理。
if(isTypingTarget(e.target)||e.ctrlKey||e.metaKey||e.altKey)return;
+ const imageDots=[...document.querySelectorAll('#stage:not([hidden]) .followimagedots [data-follow-image-item]')];
+ if(imageDots.length&&(e.key==='ArrowLeft'||e.key==='ArrowRight')){
+ e.preventDefault();
+ const current=Math.max(0,imageDots.findIndex(dot=>dot.getAttribute('aria-current')==='true'));
+ imageDots[(current+(e.key==='ArrowRight'?1:-1)+imageDots.length)%imageDots.length].click();
+ return;
+ }
const video=activeVideo();
if(video){
if(e.key==='ArrowLeft'||e.key==='ArrowRight'){
@@ -3969,4 +4040,4 @@ window.addEventListener('popstate',restoreRoute);
buildEdge();
loadSourceStatus()
.then(buildBars)
- .then(async()=>{buildEdge();wireAllDrag();await load(true);await restoreRoute();scheduleStickySurfaces()});
+ .then(async()=>{buildEdge();wireAllDrag();await restoreRoute();scheduleStickySurfaces()});
diff --git a/web/index.html b/web/index.html
index 90cb88d2d..bedda3032 100644
--- a/web/index.html
+++ b/web/index.html
@@ -36,6 +36,7 @@
<symbol id="i-folder-open" viewBox="0 0 24 24"><path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></symbol>
<symbol id="i-hard-drive" viewBox="0 0 24 24"><path d="M10 16h.01"/><path d="M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><path d="M21.946 12.013H2.054"/><path d="M6 16h.01"/></symbol>
<symbol id="i-globe" viewBox="0 0 24 24"><path d="M21.54 15H17a2 2 0 0 0-2 2v4.54"/><path d="M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17"/><path d="M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05"/><circle cx="12" cy="12" r="10"/></symbol>
+ <symbol id="i-rss" viewBox="0 0 24 24"><path d="M4 11a9 9 0 0 1 9 9"/><path d="M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-thumbs-up" viewBox="0 0 24 24"><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"/><path d="M7 10v12"/></symbol>
<symbol id="i-thumbs-down" viewBox="0 0 24 24"><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"/><path d="M17 14V2"/></symbol>
<symbol id="i-eye" viewBox="0 0 24 24"><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/></symbol>
@@ -50,6 +51,9 @@
<symbol id="i-rotate-cw" viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></symbol>
<symbol id="i-maximize" viewBox="0 0 24 24"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></symbol>
<symbol id="i-chevron-left" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></symbol>
+ <symbol id="i-chevron-right" viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></symbol>
+ <symbol id="i-chevron-up" viewBox="0 0 24 24"><path d="m18 15-6-6-6 6"/></symbol>
+ <symbol id="i-chevron-down" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></symbol>
@@ -135,6 +139,8 @@
<label class="settingrow"><span><b>快进 / 快退</b><small>卡片预览和详情播放器共用。</small></span><select id="seekSecondsSetting"><option value="5">5 秒</option><option value="10">10 秒</option><option value="30">30 秒</option></select></label>
<label class="settingrow"><span><b>搜索记录</b><small>保存在 Peach 账本,所有访问端同步。</small></span><select id="searchHistoryLimitSetting"><option value="5">最近 5 条</option><option value="10">最近 10 条</option><option value="20">最近 20 条</option></select></label>
<label class="settingrow"><span><b>相关推荐</b><small>详情下方一次显示的相似作品数量。</small></span><select id="relatedLimitSetting"><option value="12">12 个</option><option value="20">20 个</option><option value="30">30 个</option></select></label>
+ <label class="settingrow"><span><b>关注自动更新</b><small id="followScheduleState" aria-live="polite">读取运行状态…</small></span><select id="followScheduleSetting"><option value="0">关闭</option><option value="15">每 15 分钟</option><option value="30">每 30 分钟</option><option value="60">每小时</option><option value="180">每 3 小时</option><option value="360">每 6 小时</option><option value="720">每 12 小时</option><option value="1440">每天</option></select></label>
+ <section class="sidebarsetting" aria-labelledby="sidebarOrderTitle"><span><b id="sidebarOrderTitle">左侧导航顺序</b><small>用箭头调整;窄栏和筛选抽屉会保持一致。</small></span><div class="sidebarorder" id="sidebarOrderSetting"></div></section>
</div>
</section>