diff --git a/README.md b/README.md index cee70c8..f82a961 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,86 @@ # 抖音直播间监控(douyinWEB) -批量监控抖音直播间 **开播 / 停播 / 播放时长 / 截图**,控制台对齐 `sh2` 的 `youtube-relay-log` 可视化与场次列表。 - -探测逻辑参考 `sh2/d2ypp2`(`web/enter + a_bogus`、Cookie、循环间隔),默认不爬直播间 HTML,降低风控。 +批量监控抖音直播间 **开播 / 停播 / 播放时长 / 截图 / 开播时段规律**。探测对齐 `sh2/d2ypp2`(`web/enter + a_bogus`、Cookie、间隔抖动),默认不爬直播间 HTML。 ## 线上地址 | 用途 | URL | |------|-----| | 控制台 | https://dylive.nomadro.com/ | -| API | https://dylive.nomadro.com/api/health · `/docs` 见下方直连 | +| API Health | https://dylive.nomadro.com/api/health | | PocketBase | https://dylive.nomadro.com/_/ | | SeaweedFS S3 | https://feiniu.nomadro.com/ | | S3 别名 | https://s3.nomadro.com/ | -HTTPS 由服务器 **Caddy** 自动签发;进程端口: +HTTPS 由服务器 **Caddy** 自动签发。进程端口: -| 服务 | 端口 | +| 服务 | 端口 | systemd | +|------|------|---------| +| Next.js | `4015` | `douyinweb-web` | +| FastAPI | `8014` | `douyinweb-api` | +| PocketBase | `8092` | `douyinweb-pb` | +| SeaweedFS S3 | `8333` | `seaweed-master\|volume\|filer\|s3` | + +部署目录:`/opt/douyinWEB`(VPS `107.173.30.245`)。 + +## 技术栈与数据流 + +| 层 | 职责 | +|----|------| +| **SQLite**(`backend/data/monitor.db`) | 监控热路径:轮询队列、场次、事件 | +| **PocketBase** | 业务元数据双写镜像(房间 / 场次 / 事件),Admin 可查 | +| **SeaweedFS S3** | 封面媒体存储;UI 经 API 代理展示(私有桶可读) | +| **Next.js 15** | 控制台 | +| **FastAPI** | 轮询、REST、SSE、封面补抓 | + +## 功能一览 + +### 监控核心 + +- 直播间:单条 / 批量添加、标签(含「重点」)、启用停用、黑名单、CSV 导出 +- 开播建场、停播结场;**每房仅一场进行中**(幂等去重) +- **僵尸场次对账**:离线强制结场 + 定时 reconcile;可 `POST /api/sessions/reconcile-stale` +- **单场手动结束**:概览 / 场次列表 / 详情弹窗(`POST /api/sessions/{id}/end`) +- 进行中实时计时(前端秒级刷新) + +### 封面(S3) + +- 开播自动截图:优先拉流帧,失败回退封面图 / 头像 +- 在播缺图自动重试;设置页 / 截图库可「补抓在播」「补缺图」 +- 截图库:**有图 / 缺图** 页签;缺图行级补抓与详情 +- UI 优先 `cover_proxy_url`(经 API 代理私有桶) + +### 控制台页面 + +| 路由 | 说明 | |------|------| -| Next.js | `4015` | -| FastAPI | `8014` | -| PocketBase | `8092` | -| SeaweedFS S3 | `8333` | +| `/` | 雷达台:健康条(Cookie / 静默 / 探测异常)、重点看板、今日六段、预计开播、在播 ★/⏹ | +| `/slots` | **开播时段规律**:24h→6×4h,日/周热力,按开播时刻看昵称缩略图 | +| `/sessions` | 场次列表 + 图表;日期预设(今天/7天/30天);标签筛选;CSV 导出含 tag | +| `/rooms` | 批量管理;预检首行;重检异常;批量增删标签 | +| `/anchors` | 主播画像与下次开播启发式 | +| `/covers` | 截图库(有图墙 / 缺图表) | +| `/events` | SSE 时间线;点击带 `session_id` 打开场次详情;CSV/JSON 导出 | +| `/settings` | 防风控参数、通知、静默时段、PB/S3 运维面板 | +| `/blacklist` | 黑名单 | -systemd:`douyinweb-web` / `douyinweb-api` / `douyinweb-pb`,以及 `seaweed-master|volume|filer|s3`。 +### 运维与通知 -## 技术栈 - -- **Next.js 15** — 雷达台 / 场次 / 直播间 / 主播 / 截图 / 设置 -- **FastAPI** — 轮询、场次、SSE、REST -- **PocketBase** — 可选镜像 -- **SQLite** — 监控热路径 -- **SeaweedFS** — 开源对象存储(S3 API),封面上传 - -## 功能 - -- 直播间:单条 / 批量添加、标签、启用停用、黑名单、CSV 导出 -- 开播建场、停播结场、进行中实时计时(每房仅一场,幂等去重) -- 开播截图 → 本地 + 上传 SeaweedFS;进行中场次缩略图,**点击放大** -- 可视化分析、主播画像、封面墙、事件时间线、SSE + Toast -- Cookie:可从 sh2 `config.ini` 的 `抖音cookie` 导入(`POST /api/settings/sync-cookie`) -- 防风控(对齐 sh2): - - 仅 `webcast/room/web/enter` + `a_bogus` - - 并发 1、间隔抖动、离线约 300s / 在播约 120s - - 错误退避;风控短冷却约 90s +- Cookie:设置页保存会记录年龄;可从 sh2 `config.ini` 同步(`POST /api/settings/sync-cookie`) +- 静默时段:降低夜间探测频率 +- Webhook / 浏览器 Notification(开播、风控) +- PB:`/api/pb/bootstrap`、`sync-rooms`、`sync-sessions` +- 防风控建议:并发 1、离线 ≥300s、在播 ≥90–120s、请求间隔 ≥3s + jitter、风控冷却约 90s ## 目录 ``` douyinWEB/ - backend/app/ FastAPI(douyin / monitor / ab_sign / s3_storage …) - backend/data/ SQLite、封面、导入快照(入库便于部署同步) + backend/app/ FastAPI(douyin / monitor / cover / s3_storage / pb_sync …) + backend/data/ SQLite、封面缓存(入库便于部署同步) frontend/src/ Next.js App Router - pb/ PocketBase 数据;Linux 二进制部署时下载 - scripts/ 本地启动与 VPS 部署脚本 + pb/ PocketBase 数据与 migrations + scripts/ 本地启动与 VPS 部署 / 探测脚本 ``` ## 本地启动 @@ -81,6 +108,25 @@ cd backend && pip install -r requirements.txt cd frontend && npm install ``` +## 常用 API(节选) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/monitor/status` | 运行态 + Cookie 年龄 + 静默 + 异常房数 | +| GET | `/api/sessions/active` | 进行中场次 | +| POST | `/api/sessions/{id}/end` | 手动结束单场 | +| POST | `/api/sessions/reconcile-stale` | 对账僵尸场次 | +| POST | `/api/sessions/{id}/recapture` | 补抓封面 | +| GET | `/api/sessions/missing-covers` | 缺图列表 | +| GET | `/api/sessions/export` | 场次导出(支持 `tag`) | +| GET | `/api/events/export` | 事件导出 | +| GET | `/api/events/stream` | SSE | +| POST | `/api/rooms/probe` | 添加前预检 | +| POST | `/api/rooms/bulk` | 批量 enable/disable/tags/check_queue… | +| GET | `/api/anchors/upcoming` | 预计下次开播 | + +完整文档:线上 `/docs` 或本地 `8000/docs`。 + ## 导入与运维脚本 ```bat @@ -89,12 +135,14 @@ python scripts\apply_sh2_antirisk.py # 对齐 sh2 防风控并错开检测 python scripts\sync_cookie_and_probe.py # 同步 Cookie 并抽样探测 ``` -VPS 相关(需 SSH 可达): +VPS(需 SSH): ```bat -python scripts\deploy_seaweedfs.py # 安装 SeaweedFS + 部署封面能力 -python scripts\setup_caddy_dylive.py # 配置 dylive / feiniu / s3 反代 -python scripts\recapture_covers_now.py # 为当前进行中场次补抓封面 +python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署 +python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力 +python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代 +python scripts\deploy_pass4.py # 近期功能增量上传 + 构建重启 +python scripts\recapture_covers_now.py # 为进行中场次补抓封面 python scripts\restart_vps.py # 重启 douyinWEB 进程 ``` @@ -107,7 +155,8 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程 | `live_interval_sec` | ≥ 90–120 | | `min_request_gap_sec` | ≥ 3 + jitter | | `dy_cookie` | 有效抖音 Cookie | -| `capture_cover_on_start` | 开播截图(上传 SeaweedFS) | +| `quiet_hours_*` | 可选夜间静默 | +| `capture_cover_on_start` | 开播截图并上传 S3 | ## 环境变量(`DY_` 前缀) @@ -134,3 +183,4 @@ https://gitea.dsx2020.com/eric/douyinWEB.git - 仓库含 `backend/data/` 与 `pb/pb_data/`,便于部署后带真实房间与 Cookie 开箱可用。 - Windows `pocketbase.exe` 不入库;Ubuntu 使用 Linux 版 `pocketbase`。 - 仅状态监控与场次统计,不含推流录制(推流仍在 sh2)。 +- 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。 diff --git a/backend/app/cover.py b/backend/app/cover.py index 0a2863d..b5cd167 100644 --- a/backend/app/cover.py +++ b/backend/app/cover.py @@ -4,14 +4,49 @@ from __future__ import annotations import asyncio import subprocess from pathlib import Path +from typing import Any +from urllib.request import Request, urlopen from . import db +from . import pb_sync from . import s3_storage from .config import settings +async def _sync_session_to_pb(session_id: str) -> None: + try: + session = db.get_session(session_id) + if session: + await pb_sync.sync_session(session) + except Exception: + pass + + +def _persist_cover_file(session_id: str, out_path: Path) -> str: + """Persist cover bytes: S3 is required when enabled; local path only as last resort.""" + if not out_path.is_file() or out_path.stat().st_size < 64: + return "" + + stored = "" + if s3_storage.s3_enabled(): + try: + public = s3_storage.upload_cover(session_id, out_path) + if public: + stored = public + except Exception: + stored = "" + if not stored: + # S3 required — do not pretend local path is the media store + return "" + else: + stored = str(out_path) + + db.set_session_cover(session_id, stored) + return stored + + async def capture_cover(session_id: str, stream_url: str) -> str: - """Grab one frame via ffmpeg, optionally upload to SeaweedFS S3, persist URL/path.""" + """Grab one frame via ffmpeg → upload S3 → write URL → sync PocketBase.""" url = (stream_url or "").strip() if not url: return "" @@ -46,18 +81,106 @@ async def capture_cover(session_id: str, stream_url: str) -> str: return "" if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128: return "" - stored = str(out_path) + return _persist_cover_file(session_id, out_path) + + stored = await asyncio.to_thread(_run) + if stored: + await _sync_session_to_pb(session_id) + # optional: drop local file after S3 success to avoid disk fill if s3_storage.s3_enabled(): try: - public = s3_storage.upload_cover(session_id, out_path) - if public: - stored = public + out_path.unlink(missing_ok=True) except Exception: pass - db.set_session_cover(session_id, stored) - return stored + return stored - return await asyncio.to_thread(_run) + +async def save_cover_from_image_url(session_id: str, image_url: str) -> str: + """Download Douyin room cover / avatar → S3 → PocketBase.""" + url = (image_url or "").strip() + if not url.startswith("http"): + return "" + out_path = settings.covers_dir / f"{session_id}.jpg" + + def _run() -> str: + try: + req = Request( + url, + headers={ + "User-Agent": ( + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) " + "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1" + ), + "Referer": "https://live.douyin.com/", + "Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8", + }, + ) + with urlopen(req, timeout=15) as resp: + data = resp.read() + if not data or len(data) < 64: + return "" + out_path.write_bytes(data) + return _persist_cover_file(session_id, out_path) + except Exception: + return "" + + stored = await asyncio.to_thread(_run) + if stored: + await _sync_session_to_pb(session_id) + if s3_storage.s3_enabled(): + try: + out_path.unlink(missing_ok=True) + except Exception: + pass + return stored + + +async def ensure_session_cover( + session_id: str, + *, + stream_url: str = "", + cover_image: str = "", + prefer_stream: bool = True, + force: bool = False, +) -> dict[str, Any]: + """ + Ensure a session has a cover on S3 (+ PocketBase URL). + 1) ffmpeg frame from live stream (best) + 2) room cover / avatar image download (fallback) + """ + session = db.get_session(session_id) + if not session: + return {"ok": False, "error": "no session"} + existing = str(session.get("cover_path") or "").strip() + if not force and existing: + # still push to PB in case mirror lagged + await _sync_session_to_pb(session_id) + return {"ok": True, "skipped": True, "cover": existing} + + path = "" + method = "" + if prefer_stream and stream_url: + path = await capture_cover(session_id, stream_url) + if path: + method = "stream" + if not path and cover_image: + path = await save_cover_from_image_url(session_id, cover_image) + if path: + method = "image" + if not path and (not prefer_stream) and stream_url: + path = await capture_cover(session_id, stream_url) + if path: + method = "stream" + + if path: + return {"ok": True, "method": method, "cover": path, "s3": path.startswith("http")} + return { + "ok": False, + "error": "capture failed", + "had_stream": bool(stream_url), + "had_image": bool(cover_image), + "s3_enabled": s3_storage.s3_enabled(), + } def cover_path_for(session_id: str) -> Path | None: @@ -66,7 +189,7 @@ def cover_path_for(session_id: str) -> Path | None: return None raw = str(session.get("cover_path") or "") if raw.startswith("http://") or raw.startswith("https://"): - return None # remote URL — served via redirect/cover_url + return None path = Path(raw) if path.is_file(): return path diff --git a/backend/app/db.py b/backend/app/db.py index 27f42ee..26bda82 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -175,12 +175,66 @@ def update_settings_map(patch: dict[str, Any]) -> dict[str, Any]: "ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, json.dumps(value)), ) + if "dy_cookie" in patch and patch.get("dy_cookie") is not None: + conn.execute( + "INSERT INTO kv_settings(key, value) VALUES(?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", + ("dy_cookie_updated_at", json.dumps(time.time())), + ) conn.commit() finally: conn.close() return get_settings_map() +def count_recent_error_rooms(*, within_sec: float = 3600) -> int: + cutoff = time.time() - within_sec + with _lock: + conn = _connect() + try: + row = conn.execute( + """ + SELECT COUNT(*) AS c FROM rooms + WHERE enabled = 1 AND ( + last_status = 'error' + OR (error_count > 0 AND last_checked_at >= ?) + ) + """, + (cutoff,), + ).fetchone() + return int(row["c"] or 0) + finally: + conn.close() + + +def export_events_rows( + *, + kind: str = "", + q: str = "", + limit: int = 2000, +) -> list[dict[str, Any]]: + with _lock: + conn = _connect() + try: + clauses: list[str] = [] + params: list[Any] = [] + if kind.strip(): + clauses.append("kind = ?") + params.append(kind.strip()) + if q.strip(): + like = f"%{q.strip()}%" + clauses.append("(message LIKE ? OR anchor_name LIKE ? OR room_id LIKE ?)") + params.extend([like, like, like]) + where = ("WHERE " + " AND ".join(clauses)) if clauses else "" + rows = conn.execute( + f"SELECT * FROM events {where} ORDER BY ts DESC LIMIT ?", + [*params, max(1, min(limit, 10000))], + ).fetchall() + return [_row_to_dict(r) for r in rows] + finally: + conn.close() + + def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None: if row is None: return None @@ -201,11 +255,18 @@ def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None: except json.JSONDecodeError: data["meta"] = {} if data.get("cover_path"): - # Always expose via API proxy so SeaweedFS private buckets still display in UI - data["cover_url"] = f"/api/sessions/{data['id']}/cover" + raw = str(data.get("cover_path") or "").strip() + # Prefer public S3 URL directly; keep proxy path as fallback for private/local + if raw.startswith("http://") or raw.startswith("https://"): + data["cover_url"] = raw + data["cover_proxy_url"] = f"/api/sessions/{data['id']}/cover" + else: + data["cover_url"] = f"/api/sessions/{data['id']}/cover" + data["cover_proxy_url"] = data["cover_url"] else: if "cover_path" in data: data["cover_url"] = "" + data["cover_proxy_url"] = "" if data.get("status") == "active" and data.get("started_at") and not data.get("ended_at"): data["duration_seconds"] = int(max(0, time.time() - float(data["started_at"]))) return data @@ -360,7 +421,7 @@ def bulk_rooms(action: str, ids: list[str], *, tags: Any = None) -> dict[str, An ids = [i for i in ids if i] if not ids: raise ValueError("未选择直播间") - if action not in {"enable", "disable", "delete", "set_tags", "add_tags", "check_queue"}: + if action not in {"enable", "disable", "delete", "set_tags", "add_tags", "remove_tags", "check_queue"}: raise ValueError("不支持的批量操作") affected = 0 now = time.time() @@ -396,6 +457,19 @@ def bulk_rooms(action: str, ids: list[str], *, tags: Any = None) -> dict[str, An merged = _normalize_tags(((row["tags"] or "") + "," + ",".join(add)).strip(",")) conn.execute("UPDATE rooms SET tags = ?, updated_at = ? WHERE id = ?", (merged, now, i)) affected += 1 + elif action == "remove_tags": + remove = set(t for t in _normalize_tags(tags).split(",") if t) + for i in ids: + row = conn.execute("SELECT tags FROM rooms WHERE id = ?", (i,)).fetchone() + if not row: + continue + cur = [t for t in str(row["tags"] or "").split(",") if t.strip()] + kept = [t for t in cur if t not in remove] + conn.execute( + "UPDATE rooms SET tags = ?, updated_at = ? WHERE id = ?", + (_normalize_tags(kept), now, i), + ) + affected += 1 elif action == "check_queue": for i in ids: conn.execute( @@ -649,6 +723,20 @@ def add_event( bus.publish_sync(row) except Exception: pass + # Fire-and-forget PocketBase dual-write (do not block hot path) + try: + import asyncio + + from . import pb_sync + + try: + loop = asyncio.get_running_loop() + loop.create_task(pb_sync.sync_event(row)) + except RuntimeError: + # Called from sync context without a loop + pass + except Exception: + pass return row # type: ignore @@ -923,9 +1011,12 @@ def export_sessions_rows( date_from: str = "", date_to: str = "", status: str = "", + tag: str = "", limit: int = 5000, ) -> list[dict[str, Any]]: - data = list_sessions(q=q, date_from=date_from, date_to=date_to, status=status, limit=limit, offset=0) + data = list_sessions( + q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, limit=limit, offset=0 + ) return data["sessions"] # type: ignore @@ -1071,6 +1162,113 @@ def end_session(session_id: str, *, end_reason: str = "offline") -> dict[str, An conn.close() +def end_active_sessions_for_room( + *, + room_pk: str = "", + room_id: str = "", + end_reason: str = "offline", +) -> list[dict[str, Any]]: + """End all active sessions for a room (by pk and/or web rid).""" + now = time.time() + ended: list[dict[str, Any]] = [] + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT * FROM sessions + WHERE status = 'active' AND ended_at IS NULL + AND ( + (? != '' AND room_pk = ?) + OR (? != '' AND room_id = ?) + ) + """, + (room_pk, room_pk, room_id, room_id), + ).fetchall() + for row in rows: + duration = max(0.0, now - float(row["started_at"])) + conn.execute( + """ + UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended', + end_reason = ?, updated_at = ? WHERE id = ? + """, + (now, duration, end_reason, now, row["id"]), + ) + item = _row_to_dict(row) + item["ended_at"] = now + item["duration_seconds"] = duration + item["status"] = "ended" + item["end_reason"] = end_reason + ended.append(item) + if room_pk: + conn.execute( + "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, room_pk), + ) + conn.commit() + return ended + finally: + conn.close() + + +def reconcile_stale_active_sessions() -> dict[str, Any]: + """Close active sessions whose room is not live (zombie timers).""" + closed = 0 + kept = 0 + details: list[dict[str, str]] = [] + with _lock: + conn = _connect() + try: + rows = conn.execute( + "SELECT * FROM sessions WHERE status = 'active' AND ended_at IS NULL" + ).fetchall() + now = time.time() + for row in rows: + room = None + if row["room_pk"]: + room = conn.execute("SELECT * FROM rooms WHERE id = ?", (row["room_pk"],)).fetchone() + if not room and row["room_id"]: + room = conn.execute( + "SELECT * FROM rooms WHERE room_id = ?", (row["room_id"],) + ).fetchone() + room_status = (room["last_status"] if room else "") or "" + stale = False + reason = "keep" + if not room: + stale = True + reason = "no_room" + elif room_status in {"offline", "error", "unknown"}: + stale = True + reason = f"room_{room_status}" + elif room["active_session_id"] and room["active_session_id"] != row["id"]: + stale = True + reason = "orphaned" + if stale: + duration = max(0.0, now - float(row["started_at"])) + conn.execute( + """ + UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended', + end_reason = ?, updated_at = ? WHERE id = ? + """, + (now, duration, f"reconcile:{reason}", now, row["id"]), + ) + if room and (room["active_session_id"] or "") == row["id"]: + conn.execute( + "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, room["id"]), + ) + closed += 1 + details.append( + {"id": row["id"], "anchor": row["anchor_name"] or "", "reason": reason} + ) + else: + kept += 1 + conn.commit() + return {"closed": closed, "kept": kept, "details": details} + finally: + conn.close() + + def set_session_cover(session_id: str, cover_path: str) -> None: with _lock: conn = _connect() @@ -1093,12 +1291,31 @@ def get_session(session_id: str) -> dict[str, Any] | None: conn.close() +def list_sessions_missing_cover(*, limit: int = 50) -> list[dict[str, Any]]: + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT * FROM sessions + WHERE cover_path IS NULL OR trim(cover_path) = '' + ORDER BY started_at DESC + LIMIT ? + """, + (max(1, min(limit, 500)),), + ).fetchall() + return [_row_to_dict(r) for r in rows] + finally: + conn.close() + + def list_sessions( *, q: str = "", date_from: str = "", date_to: str = "", status: str = "", + tag: str = "", limit: int = 50, offset: int = 0, ) -> dict[str, Any]: @@ -1107,24 +1324,35 @@ def list_sessions( try: clauses: list[str] = [] params: list[Any] = [] + join = "" if status == "active": - clauses.append("ended_at IS NULL") + clauses.append("s.ended_at IS NULL") elif status == "ended": - clauses.append("ended_at IS NOT NULL") + clauses.append("s.ended_at IS NOT NULL") if date_from: - clauses.append("push_date >= ?") + clauses.append("s.push_date >= ?") params.append(date_from) if date_to: - clauses.append("push_date <= ?") + clauses.append("s.push_date <= ?") params.append(date_to) if q.strip(): like = f"%{q.strip()}%" - clauses.append("(anchor_name LIKE ? OR source_url LIKE ? OR room_id LIKE ? OR title LIKE ?)") + clauses.append( + "(s.anchor_name LIKE ? OR s.source_url LIKE ? OR s.room_id LIKE ? OR s.title LIKE ?)" + ) params.extend([like, like, like, like]) + if tag.strip(): + join = "LEFT JOIN rooms r ON r.id = s.room_pk" + t = tag.strip() + clauses.append("(r.tags = ? OR r.tags LIKE ? OR r.tags LIKE ? OR r.tags LIKE ?)") + params.extend([t, f"{t},%", f"%,{t}", f"%,{t},%"]) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" - total = conn.execute(f"SELECT COUNT(*) AS c FROM sessions {where}", params).fetchone()["c"] + total = conn.execute( + f"SELECT COUNT(*) AS c FROM sessions s {join} {where}", + params, + ).fetchone()["c"] rows = conn.execute( - f"SELECT * FROM sessions {where} ORDER BY started_at DESC LIMIT ? OFFSET ?", + f"SELECT s.* FROM sessions s {join} {where} ORDER BY s.started_at DESC LIMIT ? OFFSET ?", [*params, max(1, min(limit, 10000)), max(0, offset)], ).fetchall() return { @@ -1137,6 +1365,88 @@ def list_sessions( conn.close() +def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list[dict[str, Any]]: + """Heuristic next-open list from recent sessions + room tags.""" + from .stats import summarize_anchor_schedule + + priority_tags = {"重点", "priority", "vip", "高优"} + with _lock: + conn = _connect() + try: + room_rows = conn.execute( + """ + SELECT id, room_id, url, last_anchor, last_status, tags, enabled + FROM rooms WHERE enabled = 1 + """ + ).fetchall() + rooms_by_rid = {str(r["room_id"]): _row_to_dict(r) for r in room_rows if r["room_id"]} + # Recent anchors with enough history + sess_groups = conn.execute( + """ + SELECT COALESCE(NULLIF(anchor_name, ''), room_id) AS name, room_id, + COUNT(*) AS c + FROM sessions + WHERE started_at > ? + GROUP BY COALESCE(NULLIF(anchor_name, ''), room_id), room_id + HAVING c >= 1 + ORDER BY c DESC + LIMIT 120 + """, + (time.time() - 14 * 86400,), + ).fetchall() + session_cache: dict[str, list[dict[str, Any]]] = {} + for g in sess_groups: + name = str(g["name"] or "") + rid = str(g["room_id"] or "") + key = name or rid + if not key: + continue + rows = conn.execute( + """ + SELECT * FROM sessions + WHERE (anchor_name = ? OR room_id = ?) + ORDER BY started_at DESC LIMIT 80 + """, + (key, rid or key), + ).fetchall() + session_cache[key] = [_row_to_dict(x) for x in rows] + finally: + conn.close() + + items: list[dict[str, Any]] = [] + for key, sessions in session_cache.items(): + room = rooms_by_rid.get(str(sessions[0].get("room_id") or "")) if sessions else None + tags = (room or {}).get("tags") or [] + if isinstance(tags, str): + tags = [t.strip() for t in tags.split(",") if t.strip()] + is_priority = any(t in priority_tags for t in tags) + if priority_only and not is_priority: + continue + if room and room.get("last_status") == "live": + continue + schedule = summarize_anchor_schedule(sessions) + hint = schedule.get("next_open_hint") + if not hint or not hint.get("eta_ts"): + continue + items.append( + { + "anchor_name": (sessions[0].get("anchor_name") if sessions else "") or key, + "room_id": (room or {}).get("room_id") or (sessions[0].get("room_id") if sessions else ""), + "room_pk": (room or {}).get("id") or "", + "url": (room or {}).get("url") or (sessions[0].get("source_url") if sessions else ""), + "tags": tags, + "priority": is_priority, + "last_status": (room or {}).get("last_status") or "offline", + "typical_open_hint": schedule.get("typical_open_hint") or "", + "peak_slot_label": schedule.get("peak_slot_label") or "", + "next_open_hint": hint, + "eta_ts": float(hint["eta_ts"]), + } + ) + items.sort(key=lambda x: (0 if x.get("priority") else 1, float(x.get("eta_ts") or 0))) + return items[: max(1, min(limit, 50))] + + def all_sessions_for_stats( *, q: str = "", diff --git a/backend/app/douyin.py b/backend/app/douyin.py index f435347..1660b26 100644 --- a/backend/app/douyin.py +++ b/backend/app/douyin.py @@ -73,6 +73,46 @@ def _pick_stream_url(room: dict[str, Any]) -> str: return str(stream.get("flv_pull_url") or stream.get("hls_pull_url") or "") +def _pick_url_list(node: Any) -> str: + """Pick first usable URL from Douyin url_list / cover structures.""" + if not node: + return "" + if isinstance(node, str): + return node.strip() + if isinstance(node, dict): + urls = node.get("url_list") or node.get("urlList") or [] + if isinstance(urls, list): + for u in urls: + s = str(u or "").strip() + if s.startswith("http"): + return s + for key in ("url", "uri", "download_url"): + s = str(node.get(key) or "").strip() + if s.startswith("http"): + return s + if isinstance(node, list): + for item in node: + s = _pick_url_list(item) + if s: + return s + return "" + + +def _pick_cover_image(room: dict[str, Any]) -> str: + """Prefer live room cover, then owner avatar — usable even without stream.""" + for key in ("cover", "origin_cover", "keyframe_image"): + url = _pick_url_list(room.get(key)) + if url: + return url + owner = room.get("owner") or {} + if isinstance(owner, dict): + for key in ("avatar_medium", "avatar_thumb", "avatar_large"): + url = _pick_url_list(owner.get(key)) + if url: + return url + return "" + + def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]: status_code = room.get("status") is_live = status_code == 2 @@ -84,6 +124,7 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]: title = room.get("title") or "" room_id = str(room.get("id") or room.get("id_str") or extract_room_id(source_url) or "") web_rid = extract_room_id(source_url) + cover_image = _pick_cover_image(room) return { "ok": True, "is_live": bool(is_live), @@ -94,9 +135,12 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]: "room_id": web_rid or room_id, "source_url": normalize_room_url(source_url), "stream_url": _pick_stream_url(room) if is_live else "", + "cover_image": cover_image, "raw": { "status": status_code, "user_count": room.get("user_count") or room.get("user_count_str") or 0, + "has_stream": bool(_pick_stream_url(room)) if is_live else False, + "has_cover_image": bool(cover_image), }, } diff --git a/backend/app/main.py b/backend/app/main.py index e06b9d1..f6482c2 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -16,7 +16,7 @@ import httpx from . import cookie_loader, db, pb_sync from .config import settings -from .cover import capture_cover, cover_path_for +from .cover import cover_path_for, ensure_session_cover from .douyin import check_room from .events_bus import bus from .models import ( @@ -29,7 +29,7 @@ from .models import ( SettingsUpdate, ) from .monitor import monitor -from .stats import summarize_sessions +from .stats import summarize_anchor_schedule, summarize_sessions @asynccontextmanager @@ -69,7 +69,28 @@ app.mount("/covers", StaticFiles(directory=str(covers_dir)), name="covers") @app.get("/api/health") async def health() -> dict[str, Any]: pb = await pb_sync.health() - return {"ok": True, "time": time.time(), "pocketbase": pb, "monitor": monitor.status()} + from . import s3_storage + + s3_info: dict[str, Any] = { + "enabled": s3_storage.s3_enabled(), + "endpoint": settings.s3_endpoint if s3_storage.s3_enabled() else "", + "public_base": settings.s3_public_base if s3_storage.s3_enabled() else "", + "bucket": settings.s3_bucket if s3_storage.s3_enabled() else "", + "ok": False, + } + if s3_storage.s3_enabled(): + try: + s3_storage.ensure_bucket() + s3_info["ok"] = True + except Exception as exc: + s3_info["error"] = str(exc)[:200] + return { + "ok": True, + "time": time.time(), + "pocketbase": pb, + "s3": s3_info, + "monitor": monitor.status(), + } @app.get("/api/monitor/status") @@ -323,6 +344,40 @@ async def events_purge(body: PurgeEventsBody) -> dict[str, Any]: return {"deleted": deleted} +@app.get("/api/events/export") +async def events_export( + kind: str = "", + q: str = "", + format: str = Query("csv", pattern="^(csv|json)$"), +) -> Any: + rows = db.export_events_rows(kind=kind, q=q, limit=5000) + if format == "json": + return {"events": rows, "total": len(rows)} + buf = io.StringIO() + writer = csv.writer(buf) + writer.writerow(["id", "ts", "level", "kind", "room_id", "anchor_name", "message", "session_id"]) + for e in rows: + writer.writerow( + [ + e.get("id"), + e.get("ts"), + e.get("level"), + e.get("kind"), + e.get("room_id"), + e.get("anchor_name"), + e.get("message"), + e.get("session_id"), + ] + ) + buf.seek(0) + filename = f"events_{time.strftime('%Y%m%d_%H%M%S')}.csv" + return StreamingResponse( + iter(["\ufeff" + buf.getvalue()]), + media_type="text/csv; charset=utf-8", + headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"}, + ) + + @app.get("/api/sessions/active") async def sessions_active() -> dict[str, Any]: items = db.list_active_sessions() @@ -336,19 +391,86 @@ async def sessions_end_all_active() -> dict[str, Any]: return {"ended": n} +@app.post("/api/sessions/{session_id}/end") +async def sessions_end_one(session_id: str) -> dict[str, Any]: + session = db.get_session(session_id) + if not session: + raise HTTPException(404, "场次不存在") + if session.get("ended_at"): + return {"session": session, "already_ended": True} + ended = db.end_session(session_id, end_reason="manual") + if not ended: + raise HTTPException(404, "场次不存在") + db.add_event( + kind="ops", + level="warn", + message=f"手动结束场次:{ended.get('anchor_name') or ended.get('room_id') or session_id}", + room_id=str(ended.get("room_id") or ""), + session_id=session_id, + anchor_name=str(ended.get("anchor_name") or ""), + ) + try: + await pb_sync.sync_session(ended) + except Exception: + pass + return {"session": ended, "already_ended": False} + + +@app.post("/api/sessions/reconcile-stale") +async def sessions_reconcile_stale() -> dict[str, Any]: + result = db.reconcile_stale_active_sessions() + if result.get("closed"): + db.add_event( + kind="ops", + level="warn", + message=f"对账关闭僵尸场次:{result['closed']}(保留 {result['kept']})", + meta=result, + ) + return result + + @app.get("/api/anchors") async def anchors_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]: return {"anchors": db.list_anchors(limit=limit)} +@app.get("/api/anchors/upcoming") +async def anchors_upcoming( + limit: int = Query(20, ge=1, le=50), + priority_only: bool = False, +) -> dict[str, Any]: + items = db.list_upcoming_opens(limit=limit, priority_only=priority_only) + return {"items": items, "total": len(items)} + + @app.get("/api/anchors/{key}") async def anchors_detail(key: str) -> dict[str, Any]: profile = db.anchor_profile(key) if not profile: raise HTTPException(404, "未找到主播画像") + profile["schedule"] = summarize_anchor_schedule(profile.get("sessions") or []) return profile +@app.post("/api/notify/test") +async def notify_test() -> dict[str, Any]: + from .notify import send_webhook + + cfg = db.get_settings_map() + url = str(cfg.get("notify_webhook_url") or "").strip() + if not url: + raise HTTPException(400, "未配置 Webhook URL") + await send_webhook( + "ops", + { + "message": "【测试】DouyinWEB Webhook 连通性检查", + "test": True, + "time": time.time(), + }, + ) + return {"ok": True, "webhook": url} + + @app.get("/api/rooms/export") async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any: rows = db.export_rooms_rows() @@ -386,10 +508,13 @@ async def sessions_list( date_from: str = "", date_to: str = "", status: str = "", - limit: int = Query(50, ge=1, le=200), + tag: str = "", + limit: int = Query(50, ge=1, le=2000), offset: int = Query(0, ge=0), ) -> dict[str, Any]: - return db.list_sessions(q=q, date_from=date_from, date_to=date_to, status=status, limit=limit, offset=offset) + return db.list_sessions( + q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, limit=limit, offset=offset + ) @app.get("/api/sessions/stats") @@ -409,9 +534,12 @@ async def sessions_export( date_from: str = "", date_to: str = "", status: str = "", + tag: str = "", format: str = Query("csv", pattern="^(csv|json)$"), ) -> Any: - rows = db.export_sessions_rows(q=q, date_from=date_from, date_to=date_to, status=status, limit=5000) + rows = db.export_sessions_rows( + q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, limit=5000 + ) if format == "json": return {"sessions": rows, "total": len(rows)} @@ -445,6 +573,12 @@ async def sessions_export( ) +@app.get("/api/sessions/missing-covers") +async def sessions_missing_covers(limit: int = Query(100, ge=1, le=500)) -> dict[str, Any]: + items = db.list_sessions_missing_cover(limit=limit) + return {"sessions": items, "total": len(items)} + + @app.get("/api/sessions/{session_id}") async def sessions_detail(session_id: str) -> dict[str, Any]: session = db.get_session(session_id) @@ -505,34 +639,84 @@ async def recapture_active_covers() -> dict[str, Any]: continue try: probed = await check_room(room["url"], cookie=cookie, proxy=proxy) - stream_url = str(probed.get("stream_url") or "") - if not stream_url: - fail += 1 - results.append({"id": s.get("id"), "ok": False, "error": "no stream"}) - continue - path = await capture_cover(str(s["id"]), stream_url) - if path: + outcome = await ensure_session_cover( + str(s["id"]), + stream_url=str(probed.get("stream_url") or ""), + cover_image=str(probed.get("cover_image") or ""), + ) + if outcome.get("ok") and not outcome.get("skipped"): ok += 1 - results.append({"id": s.get("id"), "ok": True, "cover": path}) + results.append({"id": s.get("id"), **outcome}) + elif outcome.get("skipped"): + results.append({"id": s.get("id"), "ok": True, "skipped": True}) else: fail += 1 - results.append({"id": s.get("id"), "ok": False, "error": "capture failed"}) + results.append({"id": s.get("id"), **outcome}) except Exception as exc: fail += 1 results.append({"id": s.get("id"), "ok": False, "error": str(exc)}) - await asyncio.sleep(1.5) + await asyncio.sleep(1.2) return {"ok": ok, "fail": fail, "results": results} + +@app.post("/api/sessions/backfill-covers") +async def backfill_missing_covers(limit: int = Query(40, ge=1, le=200)) -> dict[str, Any]: + """ + Backfill thumbnails for sessions missing cover_path. + Uses live stream when still live; otherwise room cover / avatar image. + """ + cfg = db.get_settings_map() + cookie = str(cfg.get("dy_cookie") or "") + proxy = str(cfg.get("http_proxy") or "").strip() or None + missing = db.list_sessions_missing_cover(limit=limit) + ok = 0 + fail = 0 + results: list[dict[str, Any]] = [] + for s in missing: + room = db.get_room(str(s.get("room_pk") or "")) + if not room: + rid = str(s.get("room_id") or "") + if rid: + found = db.list_rooms(q=rid, limit=20) + rooms = found.get("rooms") if isinstance(found, dict) else found + for cand in rooms or []: + if str(cand.get("room_id") or "") == rid: + room = cand + break + if not room: + fail += 1 + results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), "ok": False, "error": "no room"}) + continue + try: + probed = await check_room(room["url"], cookie=cookie, proxy=proxy) + outcome = await ensure_session_cover( + str(s["id"]), + stream_url=str(probed.get("stream_url") or ""), + cover_image=str(probed.get("cover_image") or ""), + ) + if outcome.get("ok") and not outcome.get("skipped"): + ok += 1 + elif not outcome.get("ok"): + fail += 1 + results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), **outcome}) + except Exception as exc: + fail += 1 + results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), "ok": False, "error": str(exc)}) + await asyncio.sleep(1.0) + return {"ok": ok, "fail": fail, "attempted": len(missing), "results": results} + + @app.post("/api/sessions/{session_id}/recapture") async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]: session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") stream_url = "" + cover_image = "" if body: stream_url = str(body.get("stream_url") or "") - if not stream_url: - # probe room for current stream if still live + cover_image = str(body.get("cover_image") or "") + if not stream_url or not cover_image: room = db.get_room(session.get("room_pk") or "") if room: cfg = db.get_settings_map() @@ -541,13 +725,18 @@ async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None cookie=str(cfg.get("dy_cookie") or ""), proxy=str(cfg.get("http_proxy") or "").strip() or None, ) - stream_url = str(result.get("stream_url") or "") - if not stream_url: - raise HTTPException(400, "无法获取流地址,直播间可能已停播") - path = await capture_cover(session_id, stream_url) - if not path: - raise HTTPException(500, "截图失败") - return {"cover_url": f"/api/sessions/{session_id}/cover", "path": path} + stream_url = stream_url or str(result.get("stream_url") or "") + cover_image = cover_image or str(result.get("cover_image") or "") + # Force recapture even if cover exists + outcome = await ensure_session_cover( + session_id, + stream_url=stream_url, + cover_image=cover_image, + force=True, + ) + if not outcome.get("ok"): + raise HTTPException(400, outcome.get("error") or "无法获取封面(可能已停播且无房间封面)") + return {"cover_url": f"/api/sessions/{session_id}/cover", **outcome} @app.post("/api/pb/bootstrap") @@ -555,6 +744,40 @@ async def pb_bootstrap() -> dict[str, Any]: return await pb_sync.ensure_collections() +@app.post("/api/pb/sync-sessions") +async def pb_sync_sessions(limit: int = Query(500, ge=1, le=5000)) -> dict[str, Any]: + """Push recent SQLite sessions (incl. S3 cover_url) into PocketBase.""" + await pb_sync.ensure_collections() + rows = db.list_sessions(limit=limit, offset=0).get("sessions") or [] + ok = 0 + fail = 0 + with_cover = 0 + for s in rows: + try: + await pb_sync.sync_session(s) + ok += 1 + if str(s.get("cover_path") or "").startswith("http"): + with_cover += 1 + except Exception: + fail += 1 + return {"ok": ok, "fail": fail, "with_s3_cover": with_cover, "attempted": len(rows)} + + +@app.post("/api/pb/sync-rooms") +async def pb_sync_rooms(limit: int = Query(2000, ge=1, le=5000)) -> dict[str, Any]: + await pb_sync.ensure_collections() + rooms = (db.list_rooms(limit=limit, offset=0).get("rooms") or []) + ok = 0 + fail = 0 + for r in rooms: + try: + await pb_sync.sync_room(r) + ok += 1 + except Exception: + fail += 1 + return {"ok": ok, "fail": fail, "attempted": len(rooms)} + + @app.post("/api/demo/seed") async def demo_seed() -> dict[str, Any]: created_rooms = [] diff --git a/backend/app/models.py b/backend/app/models.py index 1fa37f3..c0261d5 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -56,7 +56,7 @@ class RoomUpdate(BaseModel): class RoomBulkAction(BaseModel): - action: str = Field(..., description="enable|disable|delete|set_tags|add_tags|check_queue") + action: str = Field(..., description="enable|disable|delete|set_tags|add_tags|remove_tags|check_queue") ids: list[str] tags: str = "" diff --git a/backend/app/monitor.py b/backend/app/monitor.py index df0dd37..0bb5ab1 100644 --- a/backend/app/monitor.py +++ b/backend/app/monitor.py @@ -8,7 +8,7 @@ from typing import Any, Optional from . import db from . import pb_sync from .config import settings -from .cover import capture_cover +from .cover import ensure_session_cover from .douyin import RiskControlError, check_room from .notify import send_webhook @@ -23,6 +23,7 @@ class MonitorService: self.risk_paused_until = 0.0 self._last_request_at = 0.0 self._lock = asyncio.Lock() + self._last_reconcile_at = 0.0 @property def running(self) -> bool: @@ -35,6 +36,9 @@ class MonitorService: def status(self) -> dict[str, Any]: cfg = db.get_settings_map() counts = db.counts() + quiet = self._in_quiet_hours(cfg) + cookie = str(cfg.get("dy_cookie") or "").strip() + cookie_updated = float(cfg.get("dy_cookie_updated_at") or 0) return { "running": self.running, "monitor_enabled": bool(cfg.get("monitor_enabled", True)), @@ -46,6 +50,14 @@ class MonitorService: "risk_paused_until": self.risk_paused_until, "last_error": self.last_error, "last_check_at": self.last_check_at, + "quiet_hours_active": quiet, + "error_rooms_1h": db.count_recent_error_rooms(within_sec=3600), + "cookie": { + "has": bool(cookie), + "length": len(cookie), + "updated_at": cookie_updated, + "age_hours": round((time.time() - cookie_updated) / 3600, 2) if cookie_updated else None, + }, "config": { "max_concurrency": cfg.get("max_concurrency", settings.max_concurrency), "min_request_gap_sec": cfg.get("min_request_gap_sec", settings.min_request_gap_sec), @@ -56,9 +68,12 @@ class MonitorService: "error_backoff_max_sec": cfg.get("error_backoff_max_sec", settings.error_backoff_max_sec), "global_pause_on_risk_sec": cfg.get("global_pause_on_risk_sec", settings.global_pause_on_risk_sec), "capture_cover_on_start": cfg.get("capture_cover_on_start", settings.capture_cover_on_start), - "has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()), + "has_cookie": bool(cookie), "has_proxy": bool(str(cfg.get("http_proxy") or "").strip()), "has_webhook": bool(str(cfg.get("notify_webhook_url") or "").strip()), + "quiet_hours_enabled": bool(cfg.get("quiet_hours_enabled", False)), + "quiet_hours_start": int(cfg.get("quiet_hours_start", 2) or 2), + "quiet_hours_end": int(cfg.get("quiet_hours_end", 7) or 7), }, } @@ -243,8 +258,26 @@ class MonitorService: await pb_sync.sync_session(session) except Exception: pass - if cfg.get("capture_cover_on_start", True) and result.get("stream_url"): - asyncio.create_task(capture_cover(active_sid, result["stream_url"])) + if cfg.get("capture_cover_on_start", True): + asyncio.create_task( + ensure_session_cover( + active_sid, + stream_url=str(result.get("stream_url") or ""), + cover_image=str(result.get("cover_image") or ""), + ) + ) + elif cfg.get("capture_cover_on_start", True) and active_sid: + # Retry: first capture may have missed stream / ffmpeg failed. + existing = db.get_session(active_sid) + if existing and not str(existing.get("cover_path") or "").strip(): + if result.get("stream_url") or result.get("cover_image"): + asyncio.create_task( + ensure_session_cover( + active_sid, + stream_url=str(result.get("stream_url") or ""), + cover_image=str(result.get("cover_image") or ""), + ) + ) nxt = time.time() + self._next_interval(cfg, live=True, errors=0, priority=self._is_priority(room)) db.touch_room( room["id"], @@ -257,33 +290,38 @@ class MonitorService: active_session_id=active_sid, ) else: - if prev == "live" and active_sid: - ended = db.end_session(active_sid, end_reason="offline") + # Always close any active session for this room — even if room pointer + # was already cleared / status already offline (prevents zombie timers). + ended_list = db.end_active_sessions_for_room( + room_pk=room["id"], + room_id=str(result.get("room_id") or room.get("room_id") or ""), + end_reason="offline", + ) + for ended in ended_list: db.add_event( kind="offline", level="info", message=f"停播:{anchor or room.get('room_id')}", room_id=room.get("room_id") or "", room_pk=room["id"], - session_id=active_sid, - anchor_name=anchor, - meta={"duration_seconds": (ended or {}).get("duration_seconds")}, + session_id=ended.get("id") or "", + anchor_name=anchor or ended.get("anchor_name") or "", + meta={"duration_seconds": ended.get("duration_seconds")}, ) await send_webhook( "offline", { "message": f"停播 {anchor or room.get('room_id')}", "room_id": room.get("room_id"), - "session_id": active_sid, - "duration_seconds": (ended or {}).get("duration_seconds"), + "session_id": ended.get("id"), + "duration_seconds": ended.get("duration_seconds"), }, ) - if ended: - try: - await pb_sync.sync_session(ended) - except Exception: - pass - active_sid = "" + try: + await pb_sync.sync_session(ended) + except Exception: + pass + active_sid = "" nxt = time.time() + self._next_interval( cfg, live=False, errors=0, priority=self._is_priority(room) ) @@ -295,7 +333,7 @@ class MonitorService: next_check_at=nxt, error_count=0, last_error="", - active_session_id=active_sid, + active_session_id="", ) try: @@ -319,6 +357,21 @@ class MonitorService: await asyncio.sleep(5) continue + # Periodically close zombie active sessions (room already offline). + if time.time() - self._last_reconcile_at > 60: + try: + result = db.reconcile_stale_active_sessions() + if result.get("closed"): + db.add_event( + kind="ops", + level="warn", + message=f"对账关闭僵尸场次:{result['closed']}(保留 {result['kept']})", + meta=result, + ) + except Exception as exc: + self.last_error = f"reconcile: {exc}" + self._last_reconcile_at = time.time() + rooms = db.due_rooms(limit=int(cfg.get("max_concurrency", settings.max_concurrency)) * 3) if not rooms: await asyncio.sleep(1.5) diff --git a/backend/app/notify.py b/backend/app/notify.py index 8db9ea9..3630a3d 100644 --- a/backend/app/notify.py +++ b/backend/app/notify.py @@ -19,6 +19,7 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None: return if event == "risk" and not cfg.get("notify_on_risk", True): return + # allow ops/test always when URL configured body = { "event": event, @@ -33,4 +34,8 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None: except Exception: pass - asyncio.create_task(_post()) + try: + asyncio.get_running_loop() + asyncio.create_task(_post()) + except RuntimeError: + await _post() diff --git a/backend/app/pb_sync.py b/backend/app/pb_sync.py index db704ea..9014bbd 100644 --- a/backend/app/pb_sync.py +++ b/backend/app/pb_sync.py @@ -1,12 +1,12 @@ """ -PocketBase bootstrap + lightweight sync helpers. - -Local SQLite is the hot path for the monitor worker. -PocketBase is used as the admin-facing datastore / backup mirror. +PocketBase sync — canonical admin datastore for rooms/sessions. +Monitor still uses SQLite as the hot-path worker DB; every mutation dual-writes here. +Media binaries live on SeaweedFS S3; only URLs are stored in PB/SQLite. """ from __future__ import annotations +import hashlib import time from typing import Any, Optional @@ -18,6 +18,11 @@ _token: str = "" _token_expire: float = 0 +def _pb_id(sqlite_id: str) -> str: + """PocketBase record id: 15-char [a-z0-9].""" + return hashlib.md5(str(sqlite_id).encode("utf-8")).hexdigest()[:15] + + async def _client() -> httpx.AsyncClient: return httpx.AsyncClient( base_url=settings.pb_url.rstrip("/"), @@ -29,7 +34,6 @@ async def _client() -> httpx.AsyncClient: async def ensure_admin() -> None: global _token, _token_expire async with await _client() as client: - # try login try: resp = await client.post( "/api/collections/_superusers/auth-with-password", @@ -43,7 +47,6 @@ async def ensure_admin() -> None: except Exception: pass - # first-time install try: resp = await client.post( "/api/collections/_superusers/records", @@ -80,9 +83,11 @@ COLLECTION_DEFS: list[dict[str, Any]] = [ {"name": "url", "type": "url", "required": True}, {"name": "room_id", "type": "text", "required": True}, {"name": "note", "type": "text"}, + {"name": "tags", "type": "text"}, {"name": "enabled", "type": "bool"}, {"name": "last_status", "type": "text"}, {"name": "last_anchor", "type": "text"}, + {"name": "last_title", "type": "text"}, {"name": "sqlite_id", "type": "text"}, ], }, @@ -101,6 +106,7 @@ COLLECTION_DEFS: list[dict[str, Any]] = [ "type": "base", "fields": [ {"name": "room_id", "type": "text"}, + {"name": "room_pk", "type": "text"}, {"name": "source_url", "type": "url"}, {"name": "anchor_name", "type": "text"}, {"name": "title", "type": "text"}, @@ -109,27 +115,82 @@ COLLECTION_DEFS: list[dict[str, Any]] = [ {"name": "duration_seconds", "type": "number"}, {"name": "push_date", "type": "text"}, {"name": "status", "type": "text"}, + {"name": "end_reason", "type": "text"}, + {"name": "cover_url", "type": "url"}, + {"name": "cover_path", "type": "text"}, + {"name": "sqlite_id", "type": "text"}, + ], + }, + { + "name": "dy_events", + "type": "base", + "fields": [ + {"name": "ts", "type": "number"}, + {"name": "kind", "type": "text"}, + {"name": "level", "type": "text"}, + {"name": "message", "type": "text"}, + {"name": "room_id", "type": "text"}, + {"name": "session_id", "type": "text"}, + {"name": "anchor_name", "type": "text"}, {"name": "sqlite_id", "type": "text"}, ], }, ] +def _field_names(col_json: dict[str, Any]) -> set[str]: + names: set[str] = set() + for f in col_json.get("fields") or col_json.get("schema") or []: + n = f.get("name") + if n: + names.add(n) + return names + + +async def _ensure_fields(client: httpx.AsyncClient, headers: dict[str, str], col_def: dict[str, Any]) -> list[str]: + """Add missing fields onto an existing PocketBase collection.""" + name = col_def["name"] + resp = await client.get(f"/api/collections/{name}", headers=headers) + if resp.status_code != 200: + return [f"{name}: fetch {resp.status_code}"] + col = resp.json() + existing = _field_names(col) + missing = [f for f in col_def["fields"] if f["name"] not in existing] + if not missing: + return [] + # PocketBase 0.22+ uses "fields" + fields = list(col.get("fields") or []) + if not fields and col.get("schema"): + fields = list(col.get("schema") or []) + for f in missing: + fields.append(dict(f)) + payload = {"fields": fields} + patch = await client.patch(f"/api/collections/{name}", headers=headers, json=payload) + if patch.status_code not in (200, 204): + return [f"{name}: patch fields {patch.status_code} {patch.text[:180]}"] + return [] + + async def ensure_collections() -> dict[str, Any]: await ensure_admin() headers = await _auth_headers() created: list[str] = [] + updated: list[str] = [] skipped: list[str] = [] errors: list[str] = [] async with await _client() as client: existing = await client.get("/api/collections", headers=headers) - names = set() + by_name: dict[str, Any] = {} if existing.status_code == 200: for item in existing.json().get("items") or []: - names.add(item.get("name")) + by_name[item.get("name")] = item for col in COLLECTION_DEFS: - if col["name"] in names: - skipped.append(col["name"]) + if col["name"] in by_name: + field_errs = await _ensure_fields(client, headers, col) + if field_errs: + errors.extend(field_errs) + else: + updated.append(col["name"]) continue payload = { "name": col["name"], @@ -146,7 +207,13 @@ async def ensure_collections() -> dict[str, Any]: created.append(col["name"]) else: errors.append(f"{col['name']}: {resp.status_code} {resp.text[:200]}") - return {"created": created, "skipped": skipped, "errors": errors, "ok": not errors} + return { + "created": created, + "updated": updated, + "skipped": skipped, + "errors": errors, + "ok": not errors, + } async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]: @@ -163,20 +230,47 @@ async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) - body = {**data, "sqlite_id": sqlite_id} if found.status_code == 200 and (found.json().get("items") or []): rid = found.json()["items"][0]["id"] - await client.patch( + resp = await client.patch( f"/api/collections/{collection}/records/{rid}", headers=headers, json=body, ) - return rid + if resp.status_code in (200, 204): + return rid + return None + # PocketBase text PK collections require explicit id on create + body["id"] = _pb_id(sqlite_id) resp = await client.post( f"/api/collections/{collection}/records", headers=headers, json=body, ) if resp.status_code in (200, 201): - return resp.json().get("id") - return None + return resp.json().get("id") or body["id"] + # conflict: try fetch again / patch + if resp.status_code in (400, 409): + found2 = await client.get( + f"/api/collections/{collection}/records", + headers=headers, + params={"filter": filt, "perPage": 1}, + ) + if found2.status_code == 200 and (found2.json().get("items") or []): + rid = found2.json()["items"][0]["id"] + await client.patch( + f"/api/collections/{collection}/records/{rid}", + headers=headers, + json={k: v for k, v in body.items() if k != "id"}, + ) + return rid + return None + + +def _session_cover_url(session: dict[str, Any]) -> str: + """Only absolute http(s) URLs belong in PocketBase url field (S3 public).""" + raw = str(session.get("cover_path") or "").strip() + if raw.startswith("http://") or raw.startswith("https://"): + return raw + return "" async def sync_room(room: dict[str, Any]) -> None: @@ -187,27 +281,51 @@ async def sync_room(room: dict[str, Any]) -> None: "url": room.get("url") or "", "room_id": room.get("room_id") or "", "note": room.get("note") or "", + "tags": room.get("tags") or "", "enabled": bool(room.get("enabled")), "last_status": room.get("last_status") or "", "last_anchor": room.get("last_anchor") or "", + "last_title": room.get("last_title") or "", }, ) async def sync_session(session: dict[str, Any]) -> None: + cover = _session_cover_url(session) + payload: dict[str, Any] = { + "room_id": session.get("room_id") or "", + "room_pk": session.get("room_pk") or "", + "source_url": session.get("source_url") or "", + "anchor_name": session.get("anchor_name") or "", + "title": session.get("title") or "", + "started_at": session.get("started_at") or 0, + "ended_at": session.get("ended_at") or 0, + "duration_seconds": session.get("duration_seconds") or 0, + "push_date": session.get("push_date") or "", + "status": session.get("status") or "", + "end_reason": session.get("end_reason") or "", + "cover_path": session.get("cover_path") or "", + } + if cover: + payload["cover_url"] = cover + await upsert_record("dy_sessions", session["id"], payload) + + +async def sync_event(event: dict[str, Any]) -> None: + eid = str(event.get("id") or "") + if not eid: + return await upsert_record( - "dy_sessions", - session["id"], + "dy_events", + eid, { - "room_id": session.get("room_id") or "", - "source_url": session.get("source_url") or "", - "anchor_name": session.get("anchor_name") or "", - "title": session.get("title") or "", - "started_at": session.get("started_at") or 0, - "ended_at": session.get("ended_at") or 0, - "duration_seconds": session.get("duration_seconds") or 0, - "push_date": session.get("push_date") or "", - "status": session.get("status") or "", + "ts": event.get("ts") or 0, + "kind": event.get("kind") or "", + "level": event.get("level") or "", + "message": event.get("message") or "", + "room_id": event.get("room_id") or "", + "session_id": event.get("session_id") or "", + "anchor_name": event.get("anchor_name") or "", }, ) diff --git a/backend/app/stats.py b/backend/app/stats.py index 7e5e4d9..4d97a55 100644 --- a/backend/app/stats.py +++ b/backend/app/stats.py @@ -10,6 +10,14 @@ from . import db WEEKDAY_ZH = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] WEEKDAY_EN = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] +SLOT_META = [ + {"id": 0, "label": "凌晨", "range": "00:00–04:00", "start_hour": 0}, + {"id": 1, "label": "清晨", "range": "04:00–08:00", "start_hour": 4}, + {"id": 2, "label": "上午", "range": "08:00–12:00", "start_hour": 8}, + {"id": 3, "label": "午后", "range": "12:00–16:00", "start_hour": 12}, + {"id": 4, "label": "傍晚", "range": "16:00–20:00", "start_hour": 16}, + {"id": 5, "label": "夜间", "range": "20:00–24:00", "start_hour": 20}, +] def _effective_duration(session: dict[str, Any], now: float) -> float: @@ -210,4 +218,126 @@ def summarize_sessions( "by_date": by_date_list, "duration_buckets": duration_buckets, "insights": insights, + "by_slot_6": _summarize_slots(sessions, now), + } + + +def _slot_index(hour: int) -> int: + return min(5, max(0, hour // 4)) + + +def _summarize_slots(sessions: list[dict[str, Any]], now: float) -> dict[str, Any]: + slot_opens = [0] * 6 + slot_rooms: list[set[str]] = [set() for _ in range(6)] + slot_duration = [0.0] * 6 + by_date_slot: dict[str, list[int]] = {} + + for s in sessions: + started = float(s.get("started_at") or 0) + if not started: + continue + dt = datetime.fromtimestamp(started) + idx = _slot_index(dt.hour) + slot_opens[idx] += 1 + slot_rooms[idx].add(str(s.get("room_id") or s.get("anchor_name") or s.get("id") or "?")) + slot_duration[idx] += _effective_duration(s, now) + date_key = s.get("push_date") or dt.strftime("%Y-%m-%d") + row = by_date_slot.setdefault(date_key, [0] * 6) + row[idx] += 1 + + total = sum(slot_opens) or 1 + slots = [] + for meta in SLOT_META: + i = meta["id"] + slots.append( + { + **meta, + "opens": slot_opens[i], + "unique_rooms": len(slot_rooms[i]), + "duration_seconds": int(slot_duration[i]), + "share": round(slot_opens[i] / total, 4), + } + ) + peak = max(range(6), key=lambda i: slot_opens[i]) if any(slot_opens) else None + dates = sorted(by_date_slot.keys()) + return { + "slots": slots, + "peak_slot": peak, + "by_date": [{"date": d, "opens": by_date_slot[d]} for d in dates], + "totals": {"opens": sum(slot_opens), "days": len(dates)}, + } + + +def summarize_anchor_schedule(sessions: list[dict[str, Any]]) -> dict[str, Any]: + """Derive open-time habit from an anchor's session list.""" + now = time.time() + hours: list[int] = [] + weekdays: list[int] = [] + starts: list[float] = [] + slot_counts = [0] * 6 + for s in sessions: + started = float(s.get("started_at") or 0) + if not started: + continue + dt = datetime.fromtimestamp(started) + hours.append(dt.hour) + weekdays.append(dt.weekday()) + starts.append(started) + slot_counts[_slot_index(dt.hour)] += 1 + + if not starts: + return { + "peak_hour": None, + "peak_weekday_label": None, + "peak_slot": None, + "slot_counts": slot_counts, + "avg_gap_hours": None, + "sessions_per_active_day": None, + "typical_open_hint": "样本不足", + "next_open_hint": None, + } + + peak_hour = max(range(24), key=lambda h: hours.count(h)) + peak_wd = max(range(7), key=lambda d: weekdays.count(d)) + peak_slot = max(range(6), key=lambda i: slot_counts[i]) + starts_sorted = sorted(starts) + gaps = [ + (starts_sorted[i] - starts_sorted[i - 1]) / 3600.0 + for i in range(1, len(starts_sorted)) + if starts_sorted[i] - starts_sorted[i - 1] > 0 + ] + dates_active = len({datetime.fromtimestamp(t).strftime("%Y-%m-%d") for t in starts}) or 1 + avg_gap = round(statistics.mean(gaps), 2) if gaps else None + slot = SLOT_META[peak_slot] + typical = f"常在 {slot['label']}({slot['range']})开播,高峰约 {peak_hour:02d}:00,多在{WEEKDAY_ZH[peak_wd]}" + + next_hint = None + last = starts_sorted[-1] + if avg_gap and avg_gap > 0: + eta = last + avg_gap * 3600.0 + if eta < now: + # overdue — suggest today's peak hour if still ahead, else tomorrow + today = datetime.now().replace(hour=peak_hour, minute=0, second=0, microsecond=0) + if today.timestamp() > now: + eta = today.timestamp() + else: + eta = today.timestamp() + 86400 + next_hint = { + "eta_ts": eta, + "label": datetime.fromtimestamp(eta).strftime("%m-%d %H:%M"), + "based_on": f"间隔均值 {avg_gap}h · 习惯 {peak_hour:02d}:00", + } + + return { + "peak_hour": peak_hour, + "peak_weekday_label": WEEKDAY_ZH[peak_wd], + "peak_slot": peak_slot, + "peak_slot_label": slot["label"], + "peak_slot_range": slot["range"], + "slot_counts": slot_counts, + "avg_gap_hours": avg_gap, + "sessions_per_active_day": round(len(starts) / dates_active, 2), + "dates_active": dates_active, + "typical_open_hint": typical, + "next_open_hint": next_hint, } diff --git a/backend/data/monitor.db b/backend/data/monitor.db index c9a0a97..36d099d 100644 Binary files a/backend/data/monitor.db and b/backend/data/monitor.db differ diff --git a/frontend/src/app/anchors/page.tsx b/frontend/src/app/anchors/page.tsx index 6608739..328282e 100644 --- a/frontend/src/app/anchors/page.tsx +++ b/frontend/src/app/anchors/page.tsx @@ -6,7 +6,7 @@ import { Loader2, RefreshCw, UserRound } from "lucide-react"; import { Shell } from "@/components/Shell"; import { AnimatedNumber, EmptyState, LivePulse } from "@/components/ui"; -import { fetchJson, fmtDuration, fmtTs } from "@/lib/api"; +import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api"; type AnchorRow = { anchor_name: string; @@ -27,6 +27,18 @@ type Profile = { active: number; last_started_at?: number; }; + schedule?: { + peak_hour?: number | null; + peak_weekday_label?: string | null; + peak_slot?: number | null; + peak_slot_label?: string; + peak_slot_range?: string; + slot_counts?: number[]; + avg_gap_hours?: number | null; + sessions_per_active_day?: number | null; + typical_open_hint?: string; + next_open_hint?: { eta_ts: number; label: string; based_on: string } | null; + }; sessions: Array<{ id: string; started_at?: number; @@ -39,6 +51,8 @@ type Profile = { rooms: Array<{ id: string; url: string; room_id: string; last_status?: string; enabled?: boolean }>; }; +const SLOT_LABELS = ["凌晨", "清晨", "上午", "午后", "傍晚", "夜间"]; + export default function AnchorsPage() { const [anchors, setAnchors] = useState([]); const [selected, setSelected] = useState(""); @@ -85,7 +99,7 @@ export default function AnchorsPage() {

👤 主播画像

-

按主播汇总场次、时长与最近表现。

+

按主播汇总场次、时长,并展示开播作息规律与预计下次开播。

+ {profile.schedule ? ( +
+
+

开播作息规律

+ + 去时段页看全局 → + +
+

{profile.schedule.typical_open_hint || "样本不足"}

+
+
+
常开时段
+
+ {profile.schedule.peak_slot_label || "—"} + {profile.schedule.peak_slot_range ? ( + ({profile.schedule.peak_slot_range}) + ) : null} +
+
+
+
平均开播间隔
+
+ {profile.schedule.avg_gap_hours != null ? `${profile.schedule.avg_gap_hours} 小时` : "—"} +
+
+
+
预计下次
+
+ {profile.schedule.next_open_hint?.label || "—"} +
+ {profile.schedule.next_open_hint?.based_on ? ( +
{profile.schedule.next_open_hint.based_on}
+ ) : null} +
+
+ {profile.schedule.slot_counts?.length === 6 ? ( +
+ {profile.schedule.slot_counts.map((n, i) => { + const max = Math.max(1, ...profile.schedule!.slot_counts!); + return ( +
+
+
+
+
{SLOT_LABELS[i]}
+
{n}
+
+ ); + })} +
+ ) : null} +
+ ) : null} +

最近场次

{profile.sessions.map((s) => (
- {s.cover_url ? ( + {sessionCoverSrc(s) ? ( // eslint-disable-next-line @next/next/no-img-element - + ) : (
N/A
)} diff --git a/frontend/src/app/covers/page.tsx b/frontend/src/app/covers/page.tsx index b7debcd..dd39bb6 100644 --- a/frontend/src/app/covers/page.tsx +++ b/frontend/src/app/covers/page.tsx @@ -1,11 +1,12 @@ "use client"; import { useCallback, useEffect, useState } from "react"; -import { Loader2, RefreshCw } from "lucide-react"; +import { Loader2, RefreshCw, ImagePlus, Camera } from "lucide-react"; import { Shell } from "@/components/Shell"; import { ImageLightbox } from "@/components/ImageLightbox"; -import { fetchJson, fmtDuration, fmtTs } from "@/lib/api"; +import { SessionDetailModal } from "@/components/SessionDetailModal"; +import { fetchJson, fmtTs, sessionCoverSrc } from "@/lib/api"; type Session = { id: string; @@ -16,16 +17,26 @@ type Session = { ended_at?: number | null; duration_seconds?: number; cover_url?: string; + cover_proxy_url?: string; push_date?: string; title?: string; + status?: string; }; +type Tab = "has" | "missing"; + export default function CoversPage() { const [sessions, setSessions] = useState([]); + const [missing, setMissing] = useState([]); + const [tab, setTab] = useState("has"); const [q, setQ] = useState(""); const [loading, setLoading] = useState(false); + const [opsBusy, setOpsBusy] = useState(""); const [error, setError] = useState(""); + const [msg, setMsg] = useState(""); const [selected, setSelected] = useState(null); + const [detail, setDetail] = useState(null); + const [rowBusy, setRowBusy] = useState(""); const load = useCallback(async () => { setLoading(true); @@ -34,8 +45,19 @@ export default function CoversPage() { const params = new URLSearchParams(); if (q.trim()) params.set("q", q.trim()); params.set("limit", "100"); - const data = await fetchJson(`/api/sessions?${params}`); - setSessions((data.sessions || []).filter((s: Session) => s.cover_url)); + const [withCover, noCover] = await Promise.all([ + fetchJson(`/api/sessions?${params}`), + fetchJson("/api/sessions/missing-covers?limit=100"), + ]); + const needle = q.trim().toLowerCase(); + let miss = (noCover.sessions || []) as Session[]; + if (needle) { + miss = miss.filter((s) => + `${s.anchor_name || ""} ${s.room_id || ""} ${s.title || ""}`.toLowerCase().includes(needle), + ); + } + setSessions((withCover.sessions || []).filter((s: Session) => s.cover_url || s.cover_proxy_url)); + setMissing(miss); } catch (e) { setError((e as Error).message); } finally { @@ -47,61 +69,211 @@ export default function CoversPage() { void load(); }, [load]); + async function runOps(kind: "active" | "backfill") { + setOpsBusy(kind); + setMsg(""); + setError(""); + try { + const path = + kind === "active" + ? "/api/sessions/active/recapture-covers" + : "/api/sessions/backfill-covers?limit=30"; + const data = await fetchJson(path, { method: "POST" }); + setMsg( + kind === "active" + ? `在播补抓:成功 ${data.ok || 0} · 失败 ${data.fail || 0}` + : `历史补图:成功 ${data.ok || 0} · 失败 ${data.fail || 0} · 尝试 ${data.attempted || 0}`, + ); + await load(); + } catch (e) { + setError((e as Error).message); + } finally { + setOpsBusy(""); + } + } + + async function recaptureOne(s: Session) { + setRowBusy(s.id); + setMsg(""); + setError(""); + try { + await fetchJson(`/api/sessions/${s.id}/recapture`, { method: "POST", body: "{}" }); + setMsg(`已补抓:${s.anchor_name || s.room_id}`); + await load(); + } catch (e) { + setError((e as Error).message); + } finally { + setRowBusy(""); + } + } + + const view = tab === "has" ? sessions : missing; + return (

🖼️ 截图库

-

开播瞬间一帧存证,点击放大查看。

+

开播瞬间一帧存证(S3),缺图场次可在此查看并补抓。

- + + +
+
+ +
+ + + setQ(e.target.value)} + placeholder="筛选主播 / 房间号…" + className="w-full max-w-md rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" + />
-
- setQ(e.target.value)} placeholder="筛选主播 / 房间号…" className="w-full max-w-md rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" /> -
- + {msg ?
{msg}
: null} {error ?
{error}
: null} -
- {sessions.map((s) => ( - - ))} -
+ {tab === "has" ? ( +
+ {sessions.map((s) => { + const src = sessionCoverSrc(s); + return ( + + ); + })} +
+ ) : ( +
+ + + + + + + + + + + + {missing.map((s) => ( + + + + + + + + ))} + +
主播房间开播状态操作
+ + {s.room_id}{fmtTs(s.started_at)}{s.ended_at ? "已结束" : "进行中"} +
+ + +
+
+
+ )} - {!loading && sessions.length === 0 ? ( + {!loading && view.length === 0 ? (
-
📷
-
还没有截图
-

真实开播并成功抓帧后会出现在这里。

+
{tab === "has" ? "📷" : "✅"}
+
{tab === "has" ? "还没有截图" : "暂无缺图场次"}
+

+ {tab === "has" ? "可点「补抓在播 / 补缺图」,或等下次开播自动落 S3。" : "全部近期场次都已有封面。"} +

) : null} - {selected?.cover_url ? ( + {selected && sessionCoverSrc(selected) ? ( setSelected(null)} /> ) : null} + + {detail ? ( + setDetail(null)} + onUpdated={() => void load()} + /> + ) : null} ); } diff --git a/frontend/src/app/events/page.tsx b/frontend/src/app/events/page.tsx index fbe43e0..626a620 100644 --- a/frontend/src/app/events/page.tsx +++ b/frontend/src/app/events/page.tsx @@ -1,11 +1,13 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { Loader2, RefreshCw } from "lucide-react"; import { Shell } from "@/components/Shell"; import { EmptyState } from "@/components/ui"; +import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal"; import { fetchJson, fmtTs } from "@/lib/api"; +import { useEventStream } from "@/lib/realtime"; type EventItem = { id: string; @@ -35,6 +37,9 @@ export default function EventsPage() { const [q, setQ] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); + const [detail, setDetail] = useState(null); + const [detailBusy, setDetailBusy] = useState(false); + const { connected, last, tick } = useEventStream(true); const load = useCallback(async () => { setLoading(true); @@ -56,10 +61,51 @@ export default function EventsPage() { useEffect(() => { void load(); - const t = setInterval(() => void load(), 10000); - return () => clearInterval(t); }, [load]); + useEffect(() => { + if (!last?.id && !last?.message) return; + const incoming: EventItem = { + id: String(last.id || `sse-${tick}`), + ts: Number(last.ts || Date.now() / 1000), + kind: last.kind, + message: last.message, + anchor_name: last.anchor_name, + room_id: last.room_id, + session_id: last.session_id, + }; + if (kind && incoming.kind !== kind) return; + if (q.trim()) { + const needle = q.trim().toLowerCase(); + const hay = `${incoming.message || ""} ${incoming.anchor_name || ""} ${incoming.room_id || ""}`.toLowerCase(); + if (!hay.includes(needle)) return; + } + setEvents((prev) => { + if (prev.some((x) => x.id === incoming.id)) return prev; + return [incoming, ...prev].slice(0, 200); + }); + setTotal((n) => n + 1); + }, [tick, last, kind, q]); + + const liveHint = useMemo( + () => (connected ? "SSE 实时推送中" : "SSE 重连中 · 可手动刷新"), + [connected], + ); + + async function openSession(ev: EventItem) { + if (!ev.session_id) return; + setDetailBusy(true); + setError(""); + try { + const data = await fetchJson(`/api/sessions/${ev.session_id}`); + setDetail((data.session || data) as SessionDetail); + } catch (e) { + setError((e as Error).message); + } finally { + setDetailBusy(false); + } + } + return (
@@ -67,10 +113,23 @@ export default function EventsPage() {

⚡ 事件时间线

开播 / 停播 / 风控 / 错误的实时审计流。

- +
+ + {connected ? "🟢" : "⚪"} {liveHint} + + +
@@ -113,6 +172,18 @@ export default function EventsPage() { > 🧹 清理 7 天前 + + 导出 CSV + + + 导出 JSON + 共 {total} 条
@@ -120,9 +191,22 @@ export default function EventsPage() {
{events.map((ev) => { - const meta = KIND_META[ev.kind || ""] || { emoji: "📌", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: ev.kind || "event" }; + const meta = KIND_META[ev.kind || ""] || { + emoji: "📌", + color: "text-teal-200 border-teal-500/30 bg-teal-500/10", + label: ev.kind || "event", + }; return ( -
+
{ev.message}
-
+ ); })}
@@ -141,6 +226,8 @@ export default function EventsPage() { {!loading && events.length === 0 ? ( ) : null} + + {detail ? setDetail(null)} /> : null} ); } diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 0f56c96..ed774b4 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -285,7 +285,8 @@ body { } .page-enter { - animation: fade-up 0.45s ease both; + /* opacity-only: avoid transform so nested `fixed` overlays stay viewport-bound */ + animation: fade-in 0.35s ease both; } .hover-lift { diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 421e494..4165629 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -9,7 +9,7 @@ import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { AnimatedNumber, LivePulse, StatTile } from "@/components/ui"; import { useToast } from "@/components/Toast"; import { ImageLightbox } from "@/components/ImageLightbox"; -import { fetchJson, fmtTs } from "@/lib/api"; +import { fetchJson, fmtTs, sessionCoverSrc } from "@/lib/api"; import { liveElapsed, useEventStream, useNow } from "@/lib/realtime"; type MonitorStatus = { @@ -23,6 +23,21 @@ type MonitorStatus = { risk_paused_until: number; last_error: string; last_check_at: number; + quiet_hours_active?: boolean; + error_rooms_1h?: number; + cookie?: { + has?: boolean; + length?: number; + updated_at?: number; + age_hours?: number | null; + }; + config?: { + quiet_hours_enabled?: boolean; + quiet_hours_start?: number; + quiet_hours_end?: number; + has_cookie?: boolean; + has_proxy?: boolean; + }; }; type Room = { @@ -31,6 +46,18 @@ type Room = { room_id: string; last_status: string; last_anchor?: string; + tags?: string[] | string; +}; + +type UpcomingItem = { + anchor_name?: string; + room_id?: string; + url?: string; + priority?: boolean; + peak_slot_label?: string; + eta_ts?: number; + next_open_hint?: { label?: string; based_on?: string }; + typical_open_hint?: string; }; type EventItem = { @@ -49,6 +76,7 @@ type ActiveSession = { source_url?: string; started_at?: number; cover_url?: string; + cover_proxy_url?: string; }; export default function HomePage() { @@ -57,6 +85,9 @@ export default function HomePage() { const [rooms, setRooms] = useState([]); const [events, setEvents] = useState([]); const [active, setActive] = useState([]); + const [todaySlots, setTodaySlots] = useState([0, 0, 0, 0, 0, 0]); + const [upcoming, setUpcoming] = useState([]); + const [focusOnly, setFocusOnly] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [lightbox, setLightbox] = useState(null); @@ -68,18 +99,22 @@ export default function HomePage() { setLoading(true); setError(""); try { - const [s, m, r, e, a] = await Promise.all([ + const today = new Date(); + const iso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`; + const [s, m, r, e, a, daySessions, up] = await Promise.all([ fetchJson("/api/sessions/stats?top_anchors=25"), fetchJson("/api/monitor/status"), - fetchJson("/api/rooms?limit=200"), + fetchJson("/api/rooms?limit=500"), fetchJson("/api/events?limit=20"), fetchJson("/api/sessions/active"), + fetchJson(`/api/sessions?date_from=${iso}&date_to=${iso}&limit=500`), + fetchJson("/api/anchors/upcoming?limit=12"), ]); setStats(s); setStatus(m); setRooms(r.rooms || []); setEvents(e.events || []); - // one card per room_id (guard against stale duplicate actives) + setUpcoming(up.items || []); const sessions = (a.sessions || []) as ActiveSession[]; const seen = new Set(); setActive( @@ -90,6 +125,14 @@ export default function HomePage() { return true; }), ); + const buckets = [0, 0, 0, 0, 0, 0]; + for (const sess of daySessions.sessions || []) { + const ts = Number(sess.started_at || 0); + if (!ts) continue; + const hour = new Date(ts * 1000).getHours(); + buckets[Math.min(5, Math.floor(hour / 4))] += 1; + } + setTodaySlots(buckets); } catch (err) { setError((err as Error).message); } finally { @@ -112,12 +155,58 @@ export default function HomePage() { if (last.kind === "live" || last.kind === "risk") { toast.push(last.message, last.kind === "risk" ? "warn" : "ok"); void load(); + if (typeof window !== "undefined" && "Notification" in window && Notification.permission === "granted") { + try { + new Notification(last.kind === "risk" ? "风控告警" : "开播提醒", { + body: last.message || "", + tag: last.id || last.kind, + }); + } catch { + /* ignore */ + } + } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [tick]); - const liveRooms = rooms.filter((r) => r.last_status === "live"); + const priorityRoomIds = new Set( + rooms + .filter((r) => { + const tags = Array.isArray(r.tags) ? r.tags : String(r.tags || "").split(",").map((t) => t.trim()).filter(Boolean); + return tags.some((t) => ["重点", "priority", "vip", "高优"].includes(t)); + }) + .map((r) => r.room_id), + ); + const liveRooms = rooms.filter((r) => r.last_status === "live" && (!focusOnly || priorityRoomIds.has(r.room_id))); + const focusLive = active.filter((s) => !focusOnly || (s.room_id && priorityRoomIds.has(s.room_id))); const riskActive = !!(status?.risk_paused_until && status.risk_paused_until * 1000 > Date.now()); + const upcomingView = focusOnly ? upcoming.filter((u) => u.priority) : upcoming; + + async function toggleFocus(roomId?: string) { + if (!roomId) return; + const room = rooms.find((r) => r.room_id === roomId); + if (!room) return; + const isFocus = priorityRoomIds.has(roomId); + try { + await fetchJson("/api/rooms/bulk", { + method: "POST", + body: JSON.stringify({ + action: isFocus ? "remove_tags" : "add_tags", + ids: [room.id], + tags: "重点", + }), + }); + toast.push(isFocus ? "已取消重点" : "已标为重点", "ok"); + await load(); + } catch (e) { + toast.push((e as Error).message, "warn"); + } + } + + const cookieAge = status?.cookie?.age_hours; + const cookieStale = cookieAge != null && cookieAge >= 72; + const cookieWarn = cookieAge != null && cookieAge >= 24; + const errorRooms = Number(status?.error_rooms_1h || 0); return ( @@ -134,11 +223,61 @@ export default function HomePage() { {riskActive ? ( ⚠️ 风控熔断中 ) : null} + {status?.quiet_hours_active ? ( + + 🌙 静默时段 {status.config?.quiet_hours_start ?? 2}–{status.config?.quiet_hours_end ?? 7} + + ) : status?.config?.quiet_hours_enabled ? ( + 静默已配置 + ) : null} + {status?.cookie?.has ? ( + + 🍪 Cookie {cookieAge != null ? `${cookieAge}h` : "已配置"} + + ) : ( + + 🍪 未配置 Cookie + + )} + {errorRooms > 0 ? ( + + 探测异常 {errorRooms} + + ) : ( + + 探测正常 · {fmtTs(status?.last_check_at)} + + )} + {status?.last_error ? ( + + 最近错误:{status.last_error} + + ) : null}

监控雷达台

实时开播态势 · 时段规律 · 事件回放

+ ) : null} -
@@ -178,19 +307,90 @@ export default function HomePage() { } hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" /> - {active.length > 0 ? ( +
+
+

🕐 今日开播六段分布

+ + 看时段规律 → + +
+
+ {["凌晨", "清晨", "上午", "午后", "傍晚", "夜间"].map((label, i) => { + const n = todaySlots[i] || 0; + const max = Math.max(1, ...todaySlots); + const nowSlot = Math.min(5, Math.floor(new Date().getHours() / 4)); + return ( + +
{label}
+
{n}
+
+
+
+ + ); + })} +
+
+ + {upcomingView.length > 0 ? (
-
-

🔴 进行中场次(实时计时)

- {active.length} 路 +
+

+ ⏰ 预计下次开播{focusOnly ? " · 重点优先" : ""} +

+ + 主播作息 → +
+
+ ) : null} + + {focusLive.length > 0 ? ( +
+
+

+ 🔴 进行中场次(实时计时){focusOnly ? " · 仅重点" : ""} +

+ {focusLive.length} 路 +
+
+ {focusLive.map((s) => (
- {s.cover_url ? ( + {sessionCoverSrc(s) ? ( ) : (
LIVE
@@ -211,15 +407,44 @@ export default function HomePage() {
{s.anchor_name || s.room_id}
{liveElapsed(s.started_at, now)}
+ +
))}
) : null} - {lightbox?.cover_url ? ( + {lightbox && sessionCoverSrc(lightbox) ? ( setLightbox(null)} @@ -299,6 +524,7 @@ export default function HomePage() {
+ 🕐 开播时段规律 🏠 管理直播间 👤 主播画像 🖼️ 浏览截图库 diff --git a/frontend/src/app/rooms/page.tsx b/frontend/src/app/rooms/page.tsx index 23d4631..9ed2a8d 100644 --- a/frontend/src/app/rooms/page.tsx +++ b/frontend/src/app/rooms/page.tsx @@ -38,12 +38,33 @@ export default function RoomsPage() { const [error, setError] = useState(""); const [msg, setMsg] = useState(""); const [bulkTags, setBulkTags] = useState(""); + const [probeMsg, setProbeMsg] = useState(""); + + useEffect(() => { + if (typeof window === "undefined") return; + const p = new URLSearchParams(window.location.search); + const s = p.get("status"); + if (s) setStatus(s); + const t = p.get("tag"); + if (t) setTag(t); + }, []); const lineCount = urlsText .split(/\r?\n/) .map((l) => l.trim()) .filter((l) => l && !l.startsWith("#")).length; + const firstUrl = useMemo(() => { + return ( + urlsText + .split(/\r?\n/) + .map((l) => l.trim()) + .find((l) => l && !l.startsWith("#")) || "" + ); + }, [urlsText]); + + const errorRooms = useMemo(() => rooms.filter((r) => r.last_status === "error"), [rooms]); + const query = useMemo(() => { const p = new URLSearchParams(); if (q.trim()) p.set("q", q.trim()); @@ -187,6 +208,53 @@ export default function RoomsPage() { } } + async function probeFirst() { + if (!firstUrl) return; + setBusy("probe"); + setProbeMsg(""); + setError(""); + try { + const data = await fetchJson("/api/rooms/probe", { + method: "POST", + body: JSON.stringify({ url: firstUrl }), + }); + const bits = [ + data.status || "unknown", + data.anchor_name || data.nickname || "", + data.room_id || "", + data.title || "", + ].filter(Boolean); + setProbeMsg(`预检:${bits.join(" · ")}`); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(""); + } + } + + async function recheckErrors() { + const targets = errorRooms.length ? errorRooms : rooms.filter((r) => selected.has(r.id) && r.last_status === "error"); + const ids = (targets.length ? targets : errorRooms).map((r) => r.id); + if (!ids.length) { + setMsg("当前没有错误状态的直播间"); + return; + } + setBusy("recheck"); + setError(""); + try { + const data = await fetchJson("/api/rooms/bulk", { + method: "POST", + body: JSON.stringify({ action: "check_queue", ids }), + }); + setMsg(`已将 ${data.affected || ids.length} 个异常房加入检查队列`); + await load(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(""); + } + } + function toggleSelect(id: string) { setSelected((prev) => { const next = new Set(prev); @@ -238,7 +306,16 @@ export default function RoomsPage() { 标签(逗号分隔) setTagsInput(e.target.value)} placeholder="重点,竞品" className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" /> -
+
+
+ {probeMsg ?
{probeMsg}
: null}
@@ -276,6 +354,15 @@ export default function RoomsPage() { {loading ? : } 刷新 + 导出 CSV @@ -292,6 +379,7 @@ export default function RoomsPage() { setBulkTags(e.target.value)} placeholder="批量标签" className="rounded border border-white/10 bg-slate-900 px-2 py-1 text-xs" /> +
) : null} diff --git a/frontend/src/app/sessions/page.tsx b/frontend/src/app/sessions/page.tsx index edd1e8a..be996ad 100644 --- a/frontend/src/app/sessions/page.tsx +++ b/frontend/src/app/sessions/page.tsx @@ -1,11 +1,12 @@ "use client"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react"; +import { Loader2, RefreshCw, Search } from "lucide-react"; import { Shell } from "@/components/Shell"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; -import { fetchJson, fmtDuration, fmtTs } from "@/lib/api"; +import { SessionDetailModal } from "@/components/SessionDetailModal"; +import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api"; type Session = { id: string; @@ -28,6 +29,8 @@ export default function SessionsPage() { const [dateFrom, setDateFrom] = useState(""); const [dateTo, setDateTo] = useState(""); const [status, setStatus] = useState(""); + const [tag, setTag] = useState(""); + const [tagOptions, setTagOptions] = useState([]); const [sessions, setSessions] = useState([]); const [stats, setStats] = useState(null); const [total, setTotal] = useState(0); @@ -43,10 +46,11 @@ export default function SessionsPage() { if (dateFrom) params.set("date_from", dateFrom); if (dateTo) params.set("date_to", dateTo); if (status) params.set("status", status); + if (tag) params.set("tag", tag); params.set("limit", String(limit)); params.set("offset", String(offset)); return params.toString(); - }, [q, dateFrom, dateTo, status, offset]); + }, [q, dateFrom, dateTo, status, tag, offset]); const statsQuery = useMemo(() => { const params = new URLSearchParams(); @@ -64,9 +68,27 @@ export default function SessionsPage() { if (dateFrom) params.set("date_from", dateFrom); if (dateTo) params.set("date_to", dateTo); if (status) params.set("status", status); + if (tag) params.set("tag", tag); params.set("format", "csv"); return `/api/sessions/export?${params.toString()}`; - }, [q, dateFrom, dateTo, status]); + }, [q, dateFrom, dateTo, status, tag]); + + function isoDate(d: Date) { + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; + } + + function applyPreset(days: number | "today") { + const to = new Date(); + const from = new Date(); + if (days === "today") { + // today only + } else { + from.setDate(from.getDate() - (days - 1)); + } + setOffset(0); + setDateFrom(isoDate(from)); + setDateTo(isoDate(to)); + } const load = useCallback(async () => { setLoading(true); @@ -90,6 +112,12 @@ export default function SessionsPage() { void load(); }, [load]); + useEffect(() => { + void fetchJson("/api/rooms/tags") + .then((d) => setTagOptions(d.tags || [])) + .catch(() => undefined); + }, []); + const pageCount = Math.max(1, Math.ceil(total / limit)); const pageIndex = Math.floor(offset / limit) + 1; @@ -135,7 +163,7 @@ export default function SessionsPage() { -
+
))}
+
+ + +
+ +
+
+
+
+
PocketBase
+
{pbOk ? "正常" : "异常"}
+
+
+
S3 媒体库
+
+ {!s3Enabled ? "未启用" : s3Ok ? "正常" : "异常"} +
+
{health?.s3?.public_base || health?.s3?.bucket || ""}
+
+
+
监控
+
{health?.monitor?.running ? "运行中" : "未运行"}
+
+
+
+ {[ + ["同步 Cookie", "/api/settings/sync-cookie"], + ["PB 初始化字段", "/api/pb/bootstrap"], + ["同步房间→PB", "/api/pb/sync-rooms"], + ["同步场次→PB", "/api/pb/sync-sessions?limit=500"], + ["补抓在播封面", "/api/sessions/active/recapture-covers"], + ["补历史缺图", "/api/sessions/backfill-covers?limit=30"], + ["对账僵尸场次", "/api/sessions/reconcile-stale"], + ].map(([label, path]) => ( + + ))} +
+ {log ?
{log}
: null} + + ); +} diff --git a/frontend/src/app/slots/page.tsx b/frontend/src/app/slots/page.tsx new file mode 100644 index 0000000..0c042ba --- /dev/null +++ b/frontend/src/app/slots/page.tsx @@ -0,0 +1,568 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; +import { Loader2, RefreshCw } from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { SessionDetailModal } from "@/components/SessionDetailModal"; +import { EmptyState, LivePulse, StatTile } from "@/components/ui"; +import { fetchJson, fmtDuration, sessionCoverSrc } from "@/lib/api"; + +type Session = { + id: string; + anchor_name?: string; + source_url?: string; + room_id?: string; + title?: string; + started_at?: number; + ended_at?: number | null; + duration_seconds?: number; + push_date?: string; + cover_url?: string; + status?: string; + end_reason?: string; + cover_proxy_url?: string; +}; + +const SLOTS = [ + { id: 0, label: "凌晨", range: "00:00 – 04:00", hint: "深夜 / 凌晨档" }, + { id: 1, label: "清晨", range: "04:00 – 08:00", hint: "早市 / 早餐档" }, + { id: 2, label: "上午", range: "08:00 – 12:00", hint: "上午营业档" }, + { id: 3, label: "午后", range: "12:00 – 16:00", hint: "午市 / 下午档" }, + { id: 4, label: "傍晚", range: "16:00 – 20:00", hint: "傍晚高峰前" }, + { id: 5, label: "夜间", range: "20:00 – 24:00", hint: "晚间主峰档" }, +] as const; + +const SLOT_ACCENT = [ + "border-violet-400/30 bg-violet-500/10 text-violet-100", + "border-sky-400/30 bg-sky-500/10 text-sky-100", + "border-teal-400/30 bg-teal-500/10 text-teal-100", + "border-amber-400/30 bg-amber-500/10 text-amber-100", + "border-orange-400/30 bg-orange-500/10 text-orange-100", + "border-rose-400/30 bg-rose-500/10 text-rose-100", +] as const; + +function todayLocalISO(): string { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +} + +function shiftDateISO(iso: string, days: number): string { + const d = new Date(`${iso}T12:00:00`); + d.setDate(d.getDate() + days); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +} + +function slotIndexFromStartedAt(ts?: number): number | null { + if (!ts) return null; + return Math.min(5, Math.floor(new Date(ts * 1000).getHours() / 4)); +} + +function fmtClock(ts?: number): string { + if (!ts) return "—"; + try { + return new Date(ts * 1000).toLocaleTimeString("zh-CN", { + hour: "2-digit", + minute: "2-digit", + hour12: false, + }); + } catch { + return "—"; + } +} + +export default function SlotsPage() { + const [date, setDate] = useState(todayLocalISO); + const [rangeMode, setRangeMode] = useState<"day" | "7d">("day"); + const [daySessions, setDaySessions] = useState([]); + const [rangeSessions, setRangeSessions] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [selected, setSelected] = useState(null); + const [focusSlot, setFocusSlot] = useState(null); + const [tag, setTag] = useState(""); + const [tagOptions, setTagOptions] = useState([]); + + const rangeFrom = useMemo(() => (rangeMode === "7d" ? shiftDateISO(date, -6) : date), [date, rangeMode]); + + useEffect(() => { + if (typeof window === "undefined") return; + const params = new URLSearchParams(window.location.search); + const d = params.get("date"); + const f = params.get("focus"); + const t = params.get("tag"); + if (d && /^\d{4}-\d{2}-\d{2}$/.test(d)) setDate(d); + if (f != null && f !== "" && !Number.isNaN(Number(f))) { + const n = Number(f); + if (n >= 0 && n <= 5) setFocusSlot(n); + } + if (t) setTag(t); + }, []); + + useEffect(() => { + void fetchJson("/api/rooms/tags") + .then((d) => setTagOptions(d.tags || [])) + .catch(() => undefined); + }, []); + + const load = useCallback(async () => { + setLoading(true); + setError(""); + try { + const dayParams = new URLSearchParams({ + date_from: date, + date_to: date, + limit: "2000", + offset: "0", + }); + if (tag) dayParams.set("tag", tag); + const dayData = await fetchJson(`/api/sessions?${dayParams}`); + setDaySessions(dayData.sessions || []); + + if (rangeMode === "7d") { + const rangeParams = new URLSearchParams({ + date_from: shiftDateISO(date, -6), + date_to: date, + limit: "2000", + offset: "0", + }); + if (tag) rangeParams.set("tag", tag); + const rangeData = await fetchJson(`/api/sessions?${rangeParams}`); + setRangeSessions(rangeData.sessions || []); + } else { + setRangeSessions(dayData.sessions || []); + } + } catch (e) { + setError((e as Error).message); + } finally { + setLoading(false); + } + }, [date, rangeMode, tag]); + + useEffect(() => { + void load(); + }, [load]); + + const patternSessions = rangeMode === "7d" ? rangeSessions : daySessions; + + const buckets = useMemo(() => { + const groups: Session[][] = Array.from({ length: 6 }, () => []); + for (const s of daySessions) { + const idx = slotIndexFromStartedAt(s.started_at); + if (idx == null) continue; + groups[idx].push(s); + } + for (const g of groups) g.sort((a, b) => (a.started_at || 0) - (b.started_at || 0)); + return groups; + }, [daySessions]); + + const daySlotStats = useMemo(() => { + return buckets.map((list) => { + const rooms = new Set(list.map((s) => s.room_id || s.anchor_name || s.id)); + const duration = list.reduce((sum, s) => sum + (Number(s.duration_seconds) || 0), 0); + const live = list.filter((s) => s.status === "active" || !s.ended_at).length; + return { opens: list.length, uniqueRooms: rooms.size, duration, live }; + }); + }, [buckets]); + + const patternSlotStats = useMemo(() => { + const opens = Array(6).fill(0) as number[]; + const rooms: Set[] = Array.from({ length: 6 }, () => new Set()); + for (const s of patternSessions) { + const idx = slotIndexFromStartedAt(s.started_at); + if (idx == null) continue; + opens[idx] += 1; + rooms[idx].add(String(s.room_id || s.anchor_name || s.id)); + } + return opens.map((n, i) => ({ opens: n, uniqueRooms: rooms[i].size })); + }, [patternSessions]); + + const heat = useMemo(() => { + const dates: string[] = []; + for (let i = 6; i >= 0; i -= 1) dates.push(shiftDateISO(date, -i)); + const map: Record = {}; + for (const d of dates) map[d] = [0, 0, 0, 0, 0, 0]; + for (const s of rangeSessions) { + const d = + s.push_date || + (s.started_at + ? (() => { + const x = new Date(s.started_at * 1000); + return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, "0")}-${String(x.getDate()).padStart(2, "0")}`; + })() + : ""); + const idx = slotIndexFromStartedAt(s.started_at); + if (!d || idx == null || !map[d]) continue; + map[d][idx] += 1; + } + const max = Math.max(1, ...dates.flatMap((d) => map[d])); + return { dates, map, max }; + }, [date, rangeSessions]); + + const dayTotalOpens = useMemo(() => daySlotStats.reduce((n, s) => n + s.opens, 0), [daySlotStats]); + const patternTotal = useMemo(() => patternSlotStats.reduce((n, s) => n + s.opens, 0), [patternSlotStats]); + + const peakSlot = useMemo(() => { + const stats = rangeMode === "7d" ? patternSlotStats : daySlotStats; + let best = 0; + for (let i = 1; i < stats.length; i += 1) { + if (stats[i].opens > stats[best].opens) best = i; + } + return stats[best].opens > 0 ? best : null; + }, [daySlotStats, patternSlotStats, rangeMode]); + + const currentSlot = + date === todayLocalISO() ? Math.min(5, Math.floor(new Date().getHours() / 4)) : null; + + const visibleSlots = focusSlot == null ? SLOTS : SLOTS.filter((s) => s.id === focusSlot); + const displayStats = daySlotStats; + + return ( + +
+
+

🕐 开播时段规律

+

+ 一天拆成 6 个 4 小时段,按 + 开播时刻 + 归类;可看单日明细或近 7 天稳定规律。 +

+
+
+
+ + +
+ + + + +
+
+ + {error ? ( +
{error}
+ ) : null} + +
+ + s.room_id || s.id)).size} + hint="同一房间多次开播只计一次" + accent="sky" + /> + + n + (Number(s.duration_seconds) || 0), 0))} + hint="下方时间轴始终展示锚点日明细" + accent="amber" + /> +
+ +
+
+

+ {rangeMode === "7d" ? "近 7 天六段开播分布(规律)" : "六段开播分布"} +

+ +
+
+ {SLOTS.map((slot) => { + const st = (rangeMode === "7d" ? patternSlotStats : daySlotStats)[slot.id]; + const total = rangeMode === "7d" ? patternTotal : dayTotalOpens; + const pct = total > 0 ? Math.round((st.opens / total) * 100) : 0; + const isPeak = peakSlot === slot.id; + const isNow = currentSlot === slot.id; + const active = focusSlot === slot.id; + return ( + + ); + })} +
+
+ + {rangeMode === "7d" ? ( +
+

日 × 时段热力(开播次数)

+
+ + + + + {SLOTS.map((s) => ( + + ))} + + + + {heat.dates.map((d) => ( + + + {heat.map[d].map((n, i) => { + const intensity = n / heat.max; + return ( + + ); + })} + + ))} + +
日期 + {s.label} +
+ {d.slice(5)} + {d === date ? 锚点 : null} + + +
+
+

点击格子可跳到该日该时段明细。

+
+ ) : null} + + {!loading && dayTotalOpens === 0 ? ( + + ) : ( +
+
时间轴:{date} 开播明细
+
+ + {visibleSlots.map((slot) => { + const list = buckets[slot.id]; + const st = displayStats[slot.id]; + const pct = dayTotalOpens > 0 ? Math.round((st.opens / dayTotalOpens) * 100) : 0; + const isPeak = peakSlot === slot.id && rangeMode === "day"; + const isNow = currentSlot === slot.id; + return ( +
+
+ +
+ +
+
+
+
+

+ {slot.label} + {slot.range} +

+ + {slot.hint} + + {isPeak ? ( + + 今日高峰 + + ) : null} + {isNow ? : null} +
+

+ 开播 {st.opens} 场 · {st.uniqueRooms} 个直播间 · 占当日 {pct}% + {st.live > 0 ? ` · 仍在播 ${st.live}` : ""} + {st.duration > 0 ? ` · 时长合计 ${fmtDuration(st.duration)}` : ""} +

+
+
+ + {list.length === 0 ? ( +
+ 该时段无人开播 +
+ ) : ( +
+ {list.map((session) => ( +
+ +
+ +
+ {fmtClock(session.started_at)} 开播 + {session.status === "active" || !session.ended_at ? ( + + ) : ( + {fmtDuration(session.duration_seconds)} + )} +
+ {session.title ? ( +

{session.title}

+ ) : null} +
+
+ ))} +
+ )} +
+
+ ); + })} +
+ )} + + setSelected(null)} + extraRows={ + selected + ? [ + { + label: "所属时段", + value: (() => { + const idx = slotIndexFromStartedAt(selected.started_at); + if (idx == null) return "—"; + return `${SLOTS[idx].label}(${SLOTS[idx].range})`; + })(), + }, + ] + : undefined + } + /> + + ); +} diff --git a/frontend/src/components/ImageLightbox.tsx b/frontend/src/components/ImageLightbox.tsx index 6ed9c54..ad42fff 100644 --- a/frontend/src/components/ImageLightbox.tsx +++ b/frontend/src/components/ImageLightbox.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect } from "react"; +import { Modal } from "@/components/Modal"; type Props = { src: string; @@ -10,48 +10,30 @@ type Props = { }; export function ImageLightbox({ src, title, subtitle, onClose }: Props) { - useEffect(() => { - const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape") onClose(); - }; - window.addEventListener("keydown", onKey); - const prev = document.body.style.overflow; - document.body.style.overflow = "hidden"; - return () => { - window.removeEventListener("keydown", onKey); - document.body.style.overflow = prev; - }; - }, [onClose]); - return ( -
-
e.stopPropagation()} - > -
-
-
{title || "封面预览"}
- {subtitle ?
{subtitle}
: null} -
- -
-
- {/* eslint-disable-next-line @next/next/no-img-element */} - {title +
+
+
{title || "封面预览"}
+ {subtitle ?
{subtitle}
: null}
+
-
+
+ {/* eslint-disable-next-line @next/next/no-img-element */} + {title +
+ ); } diff --git a/frontend/src/components/Modal.tsx b/frontend/src/components/Modal.tsx new file mode 100644 index 0000000..642899a --- /dev/null +++ b/frontend/src/components/Modal.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { useEffect, useState, type ReactNode } from "react"; +import { createPortal } from "react-dom"; + +type ModalProps = { + open: boolean; + onClose: () => void; + children: ReactNode; + /** Panel wrapper classes (the dialog card). */ + panelClassName?: string; + zIndex?: number; +}; + +/** + * Viewport-locked overlay. Always portals to document.body so parent + * transforms (e.g. Shell `.page-enter`) cannot trap `position: fixed`. + */ +export function Modal({ + open, + onClose, + children, + panelClassName = "max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5 shadow-2xl", + zIndex = 80, +}: ModalProps) { + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + useEffect(() => { + if (!open) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + window.addEventListener("keydown", onKey); + const prev = document.body.style.overflow; + document.body.style.overflow = "hidden"; + return () => { + window.removeEventListener("keydown", onKey); + document.body.style.overflow = prev; + }; + }, [open, onClose]); + + if (!mounted || !open) return null; + + return createPortal( +
+
e.stopPropagation()}> + {children} +
+
, + document.body, + ); +} diff --git a/frontend/src/components/SessionDetailModal.tsx b/frontend/src/components/SessionDetailModal.tsx new file mode 100644 index 0000000..b309d99 --- /dev/null +++ b/frontend/src/components/SessionDetailModal.tsx @@ -0,0 +1,172 @@ +"use client"; + +import { useState } from "react"; +import { ExternalLink, Loader2, RefreshCw, Square } from "lucide-react"; + +import { Modal } from "@/components/Modal"; +import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api"; + +export type SessionDetail = { + id: string; + anchor_name?: string; + source_url?: string; + room_id?: string; + title?: string; + started_at?: number; + ended_at?: number | null; + duration_seconds?: number; + cover_url?: string; + cover_proxy_url?: string; + status?: string; + end_reason?: string; +}; + +type Props = { + session: SessionDetail | null; + onClose: () => void; + onUpdated?: (session: SessionDetail) => void; + extraRows?: Array<{ label: string; value: React.ReactNode }>; +}; + +export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: Props) { + const [busy, setBusy] = useState(""); + const [err, setErr] = useState(""); + const [local, setLocal] = useState(null); + const current = local && local.id === session?.id ? local : session; + const cover = sessionCoverSrc(current || undefined); + const isActive = Boolean(current && !current.ended_at); + + async function recapture() { + if (!current?.id) return; + setBusy("cover"); + setErr(""); + try { + await fetchJson(`/api/sessions/${current.id}/recapture`, { method: "POST", body: "{}" }); + const data = await fetchJson(`/api/sessions/${current.id}`); + const next = (data.session || data) as SessionDetail; + setLocal(next); + onUpdated?.(next); + } catch (e) { + setErr((e as Error).message); + } finally { + setBusy(""); + } + } + + async function endNow() { + if (!current?.id) return; + if (!confirm(`确认手动结束「${current.anchor_name || current.room_id}」这场?`)) return; + setBusy("end"); + setErr(""); + try { + const data = await fetchJson(`/api/sessions/${current.id}/end`, { method: "POST" }); + const next = (data.session || data) as SessionDetail; + setLocal(next); + onUpdated?.(next); + } catch (e) { + setErr((e as Error).message); + } finally { + setBusy(""); + } + } + + return ( + + {current ? ( + <> +
+
+

{current.anchor_name || "直播间详情"}

+

{current.title || "—"}

+
+
+ {isActive ? ( + + ) : null} + + +
+
+ {err ?
{err}
: null} +
+ {cover ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
+ 暂无截图 +
+ )} +
+
+
直播间 URL
+
+ {current.source_url ? ( + + {current.source_url} + + ) : ( + "—" + )} +
+
+
+
房间号
+
{current.room_id || "—"}
+
+ {extraRows?.map((row) => ( +
+
{row.label}
+
{row.value}
+
+ ))} +
+
开播
+
{fmtTs(current.started_at)}
+
+
+
停播
+
{current.ended_at ? fmtTs(current.ended_at) : "进行中"}
+
+
+
总时长
+
{fmtDuration(current.duration_seconds)}
+
+
+
结束原因
+
{current.end_reason || "—"}
+
+
+
+ + ) : null} +
+ ); +} diff --git a/frontend/src/components/Shell.tsx b/frontend/src/components/Shell.tsx index 058b9ec..11d2247 100644 --- a/frontend/src/components/Shell.tsx +++ b/frontend/src/components/Shell.tsx @@ -7,6 +7,7 @@ import { BrandMark } from "@/components/ui"; const NAV = [ { href: "/", label: "概览", emoji: "📡" }, + { href: "/slots", label: "时段", emoji: "🕐" }, { href: "/sessions", label: "场次", emoji: "🎬" }, { href: "/anchors", label: "主播", emoji: "👤" }, { href: "/covers", label: "截图", emoji: "🖼️" }, @@ -16,6 +17,8 @@ const NAV = [ { href: "/settings", label: "设置", emoji: "⚙️" }, ]; +const MOBILE_PRIMARY = ["/", "/slots", "/sessions", "/events", "/settings"]; + export function Shell({ children }: { children: React.ReactNode }) { const pathname = usePathname(); return ( @@ -39,7 +42,7 @@ export function Shell({ children }: { children: React.ReactNode }) {

-
+ {/* 手机:顶部横向可滑导航 */} + -
{children}
-