Document slots/covers/PB ops UX and sync feature pass to main.

Ship zombie reconcile, S3 covers, session end/drill-down, rooms ops, and refresh README for production.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-08 20:07:15 -05:00
parent 2515f438c2
commit a360eec2ba
66 changed files with 5203 additions and 297 deletions

128
README.md
View File

@ -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)。
- 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。

View File

@ -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

View File

@ -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 = "",

View File

@ -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),
},
}

View File

@ -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 = []

View File

@ -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 = ""

View File

@ -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)

View File

@ -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()

View File

@ -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 "",
},
)

View File

@ -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,
}

Binary file not shown.

View File

@ -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<AnchorRow[]>([]);
const [selected, setSelected] = useState<string>("");
@ -85,7 +99,7 @@ export default function AnchorsPage() {
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">👤 主播画像</h2>
<p className="text-sm text-slate-400">按主播汇总场次、时长与最近表现。</p>
<p className="text-sm text-slate-400">按主播汇总场次、时长,并展示开播作息规律与预计下次开播。</p>
</div>
<button type="button" onClick={() => void loadList()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
@ -158,13 +172,76 @@ export default function AnchorsPage() {
</div>
</div>
{profile.schedule ? (
<div className="mb-4 rounded-xl border border-teal-500/20 bg-teal-500/5 p-3">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<h4 className="text-sm font-medium text-teal-100">开播作息规律</h4>
<Link
href={`/slots?date=${new Date().toISOString().slice(0, 10)}${
profile.schedule.peak_slot != null ? `&focus=${profile.schedule.peak_slot}` : ""
}`}
className="text-[11px] text-teal-300 hover:underline"
>
去时段页看全局 →
</Link>
</div>
<p className="text-sm text-slate-300">{profile.schedule.typical_open_hint || "样本不足"}</p>
<div className="mt-3 grid gap-2 sm:grid-cols-3">
<div className="rounded-lg bg-black/20 px-3 py-2 text-xs">
<div className="text-slate-500">常开时段</div>
<div className="mt-0.5 text-white">
{profile.schedule.peak_slot_label || "—"}
{profile.schedule.peak_slot_range ? (
<span className="ml-1 text-slate-400">({profile.schedule.peak_slot_range})</span>
) : null}
</div>
</div>
<div className="rounded-lg bg-black/20 px-3 py-2 text-xs">
<div className="text-slate-500">平均开播间隔</div>
<div className="mt-0.5 text-white">
{profile.schedule.avg_gap_hours != null ? `${profile.schedule.avg_gap_hours} 小时` : "—"}
</div>
</div>
<div className="rounded-lg bg-black/20 px-3 py-2 text-xs">
<div className="text-slate-500">预计下次</div>
<div className="mt-0.5 text-white">
{profile.schedule.next_open_hint?.label || "—"}
</div>
{profile.schedule.next_open_hint?.based_on ? (
<div className="mt-0.5 text-[10px] text-slate-500">{profile.schedule.next_open_hint.based_on}</div>
) : null}
</div>
</div>
{profile.schedule.slot_counts?.length === 6 ? (
<div className="mt-3 grid grid-cols-6 gap-1">
{profile.schedule.slot_counts.map((n, i) => {
const max = Math.max(1, ...profile.schedule!.slot_counts!);
return (
<div key={SLOT_LABELS[i]} className="text-center">
<div className="mx-auto flex h-12 w-full items-end justify-center rounded-md bg-black/20 px-1">
<div
className="w-full rounded-sm bg-gradient-to-t from-teal-500/80 to-teal-300/50"
style={{ height: `${Math.max(8, (n / max) * 100)}%` }}
title={`${SLOT_LABELS[i]}: ${n}`}
/>
</div>
<div className="mt-1 text-[10px] text-slate-500">{SLOT_LABELS[i]}</div>
<div className="text-[10px] tabular-nums text-slate-400">{n}</div>
</div>
);
})}
</div>
) : null}
</div>
) : null}
<h4 className="mb-2 text-sm font-medium text-slate-200">最近场次</h4>
<div className="max-h-[420px] space-y-2 overflow-auto">
{profile.sessions.map((s) => (
<div key={s.id} className="flex items-center gap-3 rounded-xl border border-white/5 bg-black/20 p-2">
{s.cover_url ? (
{sessionCoverSrc(s) ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="h-14 w-9 rounded object-cover" />
<img src={sessionCoverSrc(s)} alt="" className="h-14 w-9 rounded object-cover" />
) : (
<div className="flex h-14 w-9 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">N/A</div>
)}

View File

@ -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<Session[]>([]);
const [missing, setMissing] = useState<Session[]>([]);
const [tab, setTab] = useState<Tab>("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<Session | null>(null);
const [detail, setDetail] = useState<Session | null>(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 (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">🖼️ 截图库</h2>
<p className="text-sm text-slate-400">开播瞬间一帧存证,点击放大查看。</p>
<p className="text-sm text-slate-400">开播瞬间一帧存证(S3),缺图场次可在此查看并补抓。</p>
</div>
<button type="button" onClick={() => void load()} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={Boolean(opsBusy)}
onClick={() => void runOps("active")}
className="inline-flex items-center gap-2 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
>
{opsBusy === "active" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />}
补抓在播
</button>
<button
type="button"
disabled={Boolean(opsBusy)}
onClick={() => void runOps("backfill")}
className="inline-flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100"
>
{opsBusy === "backfill" ? <Loader2 className="h-4 w-4 animate-spin" /> : <ImagePlus className="h-4 w-4" />}
补缺图
</button>
<button
type="button"
onClick={() => void load()}
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
</div>
<div className="mb-4 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setTab("has")}
className={`rounded-xl px-3 py-1.5 text-sm ${
tab === "has" ? "bg-white/15 text-white ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
有图 ({sessions.length})
</button>
<button
type="button"
onClick={() => setTab("missing")}
className={`rounded-xl px-3 py-1.5 text-sm ${
tab === "missing" ? "bg-white/15 text-white ring-1 ring-amber-400/30" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
缺图 ({missing.length})
</button>
<input
value={q}
onChange={(e) => 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"
/>
</div>
<div className="mb-4">
<input value={q} onChange={(e) => 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" />
</div>
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm text-teal-100">{msg}</div> : null}
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="stagger grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{sessions.map((s) => (
<button
key={s.id}
type="button"
onClick={() => setSelected(s)}
className="hover-lift group overflow-hidden rounded-2xl border border-white/10 bg-black/30 text-left"
>
<div className="relative overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="aspect-[9/16] w-full object-cover transition duration-500 group-hover:scale-105" />
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-8">
<div className="truncate text-xs font-medium text-white">{s.anchor_name || s.room_id || "—"}</div>
</div>
</div>
<div className="p-2 text-[11px] text-slate-500">{fmtTs(s.started_at)}</div>
</button>
))}
</div>
{tab === "has" ? (
<div className="stagger grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{sessions.map((s) => {
const src = sessionCoverSrc(s);
return (
<button
key={s.id}
type="button"
onClick={() => setSelected(s)}
className="hover-lift group overflow-hidden rounded-2xl border border-white/10 bg-black/30 text-left"
>
<div className="relative overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt="" className="aspect-[9/16] w-full object-cover transition duration-500 group-hover:scale-105" />
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-8">
<div className="truncate text-xs font-medium text-white">{s.anchor_name || s.room_id || "—"}</div>
</div>
</div>
<div className="p-2 text-[11px] text-slate-500">{fmtTs(s.started_at)}</div>
</button>
);
})}
</div>
) : (
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-3">主播</th>
<th className="px-3 py-3">房间</th>
<th className="px-3 py-3">开播</th>
<th className="px-3 py-3">状态</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{missing.map((s) => (
<tr key={s.id} className="border-t border-white/5 hover:bg-white/[0.03]">
<td className="px-3 py-2">
<button type="button" onClick={() => setDetail(s)} className="text-left text-white hover:underline">
{s.anchor_name || "—"}
</button>
</td>
<td className="px-3 py-2 font-mono text-xs text-cyan-300/80">{s.room_id}</td>
<td className="px-3 py-2 text-xs text-slate-400">{fmtTs(s.started_at)}</td>
<td className="px-3 py-2 text-xs">{s.ended_at ? "已结束" : "进行中"}</td>
<td className="px-3 py-2">
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => setDetail(s)}
className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5"
>
详情
</button>
<button
type="button"
disabled={rowBusy === s.id}
onClick={() => void recaptureOne(s)}
className="rounded border border-teal-500/30 bg-teal-500/10 px-2 py-1 text-xs text-teal-100 disabled:opacity-40"
>
{rowBusy === s.id ? "补抓中…" : "补抓"}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!loading && sessions.length === 0 ? (
{!loading && view.length === 0 ? (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 px-4 py-12 text-center">
<div className="mb-2 text-4xl">📷</div>
<div className="font-display text-lg text-white">还没有截图</div>
<p className="mt-1 text-sm text-slate-500">真实开播并成功抓帧后会出现在这里。</p>
<div className="mb-2 text-4xl">{tab === "has" ? "📷" : "✅"}</div>
<div className="font-display text-lg text-white">{tab === "has" ? "还没有截图" : "暂无缺图场次"}</div>
<p className="mt-1 text-sm text-slate-500">
{tab === "has" ? "可点「补抓在播 / 补缺图」,或等下次开播自动落 S3。" : "全部近期场次都已有封面。"}
</p>
</div>
) : null}
{selected?.cover_url ? (
{selected && sessionCoverSrc(selected) ? (
<ImageLightbox
src={`${selected.cover_url}?ts=${selected.started_at || 0}`}
src={sessionCoverSrc(selected)}
title={selected.anchor_name || selected.room_id || "封面"}
subtitle={`${fmtTs(selected.started_at)} · ${fmtDuration(selected.duration_seconds)}`}
subtitle={fmtTs(selected.started_at)}
onClose={() => setSelected(null)}
/>
) : null}
{detail ? (
<SessionDetailModal
session={detail}
onClose={() => setDetail(null)}
onUpdated={() => void load()}
/>
) : null}
</Shell>
);
}

View File

@ -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<SessionDetail | null>(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 (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
@ -67,10 +113,23 @@ export default function EventsPage() {
<h2 className="font-display text-2xl font-semibold">⚡ 事件时间线</h2>
<p className="text-sm text-slate-400">开播 / 停播 / 风控 / 错误的实时审计流。</p>
</div>
<button type="button" onClick={() => void load()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
<div className="flex items-center gap-2">
<span
className={`rounded-lg border px-2.5 py-1 text-[11px] ${
connected ? "border-teal-500/30 bg-teal-500/10 text-teal-100" : "border-slate-500/30 bg-slate-500/10 text-slate-400"
}`}
>
{connected ? "🟢" : "⚪"} {liveHint}
</span>
<button
type="button"
onClick={() => void load()}
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
</div>
<div className="mb-4 flex flex-wrap gap-2">
@ -113,6 +172,18 @@ export default function EventsPage() {
>
🧹 清理 7 天前
</button>
<a
href={`/api/events/export?format=csv${kind ? `&kind=${encodeURIComponent(kind)}` : ""}${q.trim() ? `&q=${encodeURIComponent(q.trim())}` : ""}`}
className="rounded-xl border border-teal-500/30 bg-teal-500/10 px-3 py-1.5 text-sm text-teal-100 hover:bg-teal-500/20"
>
导出 CSV
</a>
<a
href={`/api/events/export?format=json${kind ? `&kind=${encodeURIComponent(kind)}` : ""}${q.trim() ? `&q=${encodeURIComponent(q.trim())}` : ""}`}
className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-sm text-slate-200 hover:bg-white/10"
>
导出 JSON
</a>
<span className="self-center text-xs text-slate-500">共 {total} 条</span>
</div>
@ -120,9 +191,22 @@ export default function EventsPage() {
<div className="timeline-rail stagger space-y-3 pl-1">
{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 (
<div key={ev.id} className="hover-lift relative ml-1 rounded-2xl border border-white/10 bg-black/25 px-4 py-3 pl-10">
<button
key={ev.id}
type="button"
disabled={!ev.session_id || detailBusy}
onClick={() => void openSession(ev)}
className={`hover-lift relative ml-1 w-full rounded-2xl border border-white/10 bg-black/25 px-4 py-3 pl-10 text-left ${
ev.session_id ? "cursor-pointer hover:border-teal-400/30" : "cursor-default opacity-95"
}`}
title={ev.session_id ? "查看场次详情" : undefined}
>
<span className="absolute left-[4px] top-4 flex h-5 w-5 items-center justify-center rounded-full bg-[#0b1626] text-xs ring-2 ring-teal-400/20">
{meta.emoji}
</span>
@ -131,9 +215,10 @@ export default function EventsPage() {
<span className={`rounded-md border px-1.5 py-0.5 ${meta.color}`}>{meta.label}</span>
{ev.anchor_name ? <span className="text-slate-300">{ev.anchor_name}</span> : null}
{ev.room_id ? <span className="font-mono text-cyan-300/80">{ev.room_id}</span> : null}
{ev.session_id ? <span className="text-teal-400/80">查看场次 →</span> : null}
</div>
<div className="mt-1.5 text-sm text-slate-100">{ev.message}</div>
</div>
</button>
);
})}
</div>
@ -141,6 +226,8 @@ export default function EventsPage() {
{!loading && events.length === 0 ? (
<EmptyState emoji="🛰️" title="雷达静默中" desc="还没有事件。开播、停播或风控触发后会出现在这条时间线上。" />
) : null}
{detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null}
</Shell>
);
}

View File

@ -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 {

View File

@ -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<Room[]>([]);
const [events, setEvents] = useState<EventItem[]>([]);
const [active, setActive] = useState<ActiveSession[]>([]);
const [todaySlots, setTodaySlots] = useState<number[]>([0, 0, 0, 0, 0, 0]);
const [upcoming, setUpcoming] = useState<UpcomingItem[]>([]);
const [focusOnly, setFocusOnly] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [lightbox, setLightbox] = useState<ActiveSession | null>(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<string>();
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 (
<Shell>
@ -134,11 +223,61 @@ export default function HomePage() {
{riskActive ? (
<span className="rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-[11px] text-amber-100">⚠️ 风控熔断中</span>
) : null}
{status?.quiet_hours_active ? (
<span className="rounded-md border border-sky-500/30 bg-sky-500/10 px-2 py-1 text-[11px] text-sky-100">
🌙 静默时段 {status.config?.quiet_hours_start ?? 2}–{status.config?.quiet_hours_end ?? 7}
</span>
) : status?.config?.quiet_hours_enabled ? (
<span className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400">静默已配置</span>
) : null}
{status?.cookie?.has ? (
<span
className={`rounded-md border px-2 py-1 text-[11px] ${
cookieStale
? "border-rose-500/30 bg-rose-500/10 text-rose-100"
: cookieWarn
? "border-amber-500/30 bg-amber-500/10 text-amber-100"
: "border-white/10 bg-white/5 text-slate-300"
}`}
title={status.cookie.updated_at ? `更新于 ${fmtTs(status.cookie.updated_at)}` : "Cookie 年龄未知"}
>
🍪 Cookie {cookieAge != null ? `${cookieAge}h` : "已配置"}
</span>
) : (
<Link href="/settings" className="rounded-md border border-rose-500/30 bg-rose-500/10 px-2 py-1 text-[11px] text-rose-100">
🍪 未配置 Cookie
</Link>
)}
{errorRooms > 0 ? (
<Link href="/rooms?status=error" className="rounded-md border border-orange-500/30 bg-orange-500/10 px-2 py-1 text-[11px] text-orange-100">
探测异常 {errorRooms}
</Link>
) : (
<span className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400">
探测正常 · {fmtTs(status?.last_check_at)}
</span>
)}
{status?.last_error ? (
<span className="max-w-[220px] truncate rounded-md border border-rose-500/20 bg-rose-500/5 px-2 py-1 text-[11px] text-rose-200/90" title={status.last_error}>
最近错误:{status.last_error}
</span>
) : null}
</div>
<h2 className="font-display text-2xl font-semibold tracking-tight">监控雷达台</h2>
<p className="mt-1 text-sm text-slate-400">实时开播态势 · 时段规律 · 事件回放</p>
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => setFocusOnly((v) => !v)}
className={`rounded-xl border px-3 py-2 text-sm ${
focusOnly
? "border-amber-400/40 bg-amber-500/15 text-amber-100"
: "border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"
}`}
>
{focusOnly ? "★ 重点看板 ON" : "☆ 重点看板"}
</button>
<button type="button" onClick={() => void load()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
@ -156,16 +295,6 @@ export default function HomePage() {
解除风控
</button>
) : null}
<button
type="button"
onClick={async () => {
await fetchJson("/api/demo/seed", { method: "POST" });
await load();
}}
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
✨ 演示数据
</button>
</div>
</section>
@ -178,19 +307,90 @@ export default function HomePage() {
<StatTile emoji="🎯" label="检查次数" value={<AnimatedNumber value={status?.checked_total || 0} />} hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" />
</div>
{active.length > 0 ? (
<section className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="font-display text-sm font-medium text-slate-100">🕐 今日开播六段分布</h3>
<Link href="/slots" className="text-xs text-teal-300 hover:underline">
看时段规律 →
</Link>
</div>
<div className="grid grid-cols-3 gap-2 sm:grid-cols-6">
{["凌晨", "清晨", "上午", "午后", "傍晚", "夜间"].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 (
<Link
key={label}
href={`/slots?focus=${i}`}
className={`rounded-xl border px-2 py-2 text-center ${
i === nowSlot ? "border-teal-400/40 bg-teal-500/10" : "border-white/10 bg-black/20"
}`}
>
<div className="text-[11px] text-slate-400">{label}</div>
<div className="font-display text-lg text-white">{n}</div>
<div className="mx-auto mt-1 h-1 w-full overflow-hidden rounded-full bg-white/5">
<div className="h-full bg-gradient-to-r from-teal-400/80 to-rose-400/60" style={{ width: `${(n / max) * 100}%` }} />
</div>
</Link>
);
})}
</div>
</section>
{upcomingView.length > 0 ? (
<section className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">🔴 进行中场次(实时计时)</h3>
<span className="text-xs text-slate-500">{active.length} 路</span>
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="font-display text-sm font-medium text-slate-100">
⏰ 预计下次开播{focusOnly ? " · 重点优先" : ""}
</h3>
<Link href="/anchors" className="text-xs text-teal-300 hover:underline">
主播作息 →
</Link>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{active.map((s) => (
{upcomingView.map((u) => (
<a
key={`${u.room_id}-${u.anchor_name}`}
href={u.url || "#"}
target="_blank"
rel="noreferrer"
className="hover-lift rounded-xl border border-white/10 bg-black/25 px-3 py-2"
>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{u.anchor_name}</div>
{u.priority ? (
<span className="shrink-0 rounded border border-amber-400/30 bg-amber-500/10 px-1.5 py-0.5 text-[10px] text-amber-100">
重点
</span>
) : null}
</div>
<div className="mt-1 font-mono text-xs text-teal-200">{u.next_open_hint?.label || "—"}</div>
<div className="mt-0.5 truncate text-[11px] text-slate-500">
{u.peak_slot_label ? `常开 ${u.peak_slot_label} · ` : ""}
{u.next_open_hint?.based_on || u.typical_open_hint || ""}
</div>
</a>
))}
</div>
</section>
) : null}
{focusLive.length > 0 ? (
<section className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">
🔴 进行中场次(实时计时){focusOnly ? " · 仅重点" : ""}
</h3>
<span className="text-xs text-slate-500">{focusLive.length} 路</span>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{focusLive.map((s) => (
<div
key={s.id}
className="hover-lift flex items-center gap-3 rounded-xl border border-rose-500/20 bg-rose-500/5 px-3 py-2"
>
{s.cover_url ? (
{sessionCoverSrc(s) ? (
<button
type="button"
onClick={() => setLightbox(s)}
@ -198,11 +398,7 @@ export default function HomePage() {
title="点击放大"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`${s.cover_url}${s.cover_url.includes("?") ? "&" : "?"}ts=${s.started_at || 0}`}
alt=""
className="h-14 w-10 object-cover"
/>
<img src={sessionCoverSrc(s)} alt="" className="h-14 w-10 object-cover" />
</button>
) : (
<div className="flex h-14 w-10 shrink-0 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">LIVE</div>
@ -211,15 +407,44 @@ export default function HomePage() {
<div className="truncate text-sm font-medium text-white">{s.anchor_name || s.room_id}</div>
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
</a>
<button
type="button"
onClick={async () => {
if (!confirm(`结束「${s.anchor_name || s.room_id}」这场?`)) return;
try {
await fetchJson(`/api/sessions/${s.id}/end`, { method: "POST" });
toast.push("已结束场次", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "warn");
}
}}
className="shrink-0 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/20"
title="手动结束场次"
>
⏹
</button>
<button
type="button"
onClick={() => void toggleFocus(s.room_id)}
className={`shrink-0 rounded-lg border px-2 py-1 text-xs ${
s.room_id && priorityRoomIds.has(s.room_id)
? "border-amber-400/40 bg-amber-500/15 text-amber-100"
: "border-white/10 bg-black/20 text-slate-400 hover:text-amber-100"
}`}
title={s.room_id && priorityRoomIds.has(s.room_id) ? "取消重点" : "标为重点"}
>
{s.room_id && priorityRoomIds.has(s.room_id) ? "★" : "☆"}
</button>
</div>
))}
</div>
</section>
) : null}
{lightbox?.cover_url ? (
{lightbox && sessionCoverSrc(lightbox) ? (
<ImageLightbox
src={`${lightbox.cover_url}${lightbox.cover_url.includes("?") ? "&" : "?"}ts=${lightbox.started_at || 0}`}
src={sessionCoverSrc(lightbox)}
title={lightbox.anchor_name || lightbox.room_id || "封面"}
subtitle={lightbox.source_url}
onClose={() => setLightbox(null)}
@ -299,6 +524,7 @@ export default function HomePage() {
</div>
<div className="flex flex-wrap gap-3 text-sm">
<Link href="/slots" className="hover-lift glass-panel rounded-xl px-4 py-3 text-rose-200">🕐 开播时段规律</Link>
<Link href="/rooms" className="hover-lift glass-panel rounded-xl px-4 py-3 text-teal-200">🏠 管理直播间</Link>
<Link href="/anchors" className="hover-lift glass-panel rounded-xl px-4 py-3 text-fuchsia-200">👤 主播画像</Link>
<Link href="/covers" className="hover-lift glass-panel rounded-xl px-4 py-3 text-sky-200">🖼️ 浏览截图库</Link>

View File

@ -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() {
标签(逗号分隔)
<input value={tagsInput} onChange={(e) => 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" />
</label>
<div className="flex items-end">
<div className="flex items-end gap-2">
<button
type="button"
disabled={!firstUrl || busy === "probe"}
onClick={() => void probeFirst()}
className="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm hover:bg-white/10 disabled:opacity-50"
>
{busy === "probe" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
预检首行
</button>
<button
type="button"
disabled={lineCount === 0 || busy === "add"}
@ -250,6 +327,7 @@ export default function RoomsPage() {
</button>
</div>
</div>
{probeMsg ? <div className="rounded-lg border border-teal-500/20 bg-teal-500/5 px-3 py-2 text-xs text-teal-100">{probeMsg}</div> : null}
</div>
<div className="mb-3 flex flex-wrap items-center gap-2">
@ -276,6 +354,15 @@ export default function RoomsPage() {
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
<button
type="button"
disabled={busy === "recheck" || errorRooms.length === 0}
onClick={() => void recheckErrors()}
className="inline-flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 disabled:opacity-40"
>
{busy === "recheck" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
重检异常{errorRooms.length ? `(${errorRooms.length})` : ""}
</button>
<a href="/api/rooms/export?format=csv" className="rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100 hover:bg-teal-500/20">
导出 CSV
</a>
@ -292,6 +379,7 @@ export default function RoomsPage() {
<input value={bulkTags} onChange={(e) => setBulkTags(e.target.value)} placeholder="批量标签" className="rounded border border-white/10 bg-slate-900 px-2 py-1 text-xs" />
<button type="button" onClick={() => void bulk("set_tags")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">设置标签</button>
<button type="button" onClick={() => void bulk("add_tags")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">追加标签</button>
<button type="button" onClick={() => void bulk("remove_tags")} className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10">移除标签</button>
</div>
) : null}

View File

@ -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<string[]>([]);
const [sessions, setSessions] = useState<Session[]>([]);
const [stats, setStats] = useState<RelayStats | null>(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() {
</div>
</div>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-5">
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-6">
<label className="block text-xs text-slate-400 xl:col-span-2">
检索(昵称 / URL / 房间号)
<div className="relative mt-1">
@ -167,6 +195,56 @@ export default function SessionsPage() {
<option value="ended">已结束</option>
</select>
</label>
<label className="block text-xs text-slate-400">
标签
<select value={tag} onChange={(e) => { setOffset(0); setTag(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">全部标签</option>
<option value="重点">重点</option>
{tagOptions.filter((t) => t !== "重点").map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
</label>
</div>
<div className="mb-4 flex flex-wrap gap-2">
{[
["今天", "today"] as const,
["近7天", 7] as const,
["近30天", 30] as const,
].map(([label, days]) => (
<button
key={label}
type="button"
onClick={() => applyPreset(days)}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300 hover:bg-white/10"
>
{label}
</button>
))}
<button
type="button"
onClick={() => {
setOffset(0);
setDateFrom("");
setDateTo("");
}}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/10"
>
清除日期
</button>
<button
type="button"
onClick={() => {
setOffset(0);
setStatus("active");
setDateFrom("");
setDateTo("");
}}
className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs text-rose-100 hover:bg-rose-500/20"
>
仅进行中
</button>
</div>
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
@ -196,15 +274,16 @@ export default function SessionsPage() {
<th className="px-3 py-3">停播</th>
<th className="px-3 py-3">总时长</th>
<th className="px-3 py-3">日期</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{sessions.map((session) => (
<tr key={session.id} className="cursor-pointer border-t border-white/5 hover:bg-white/[0.03]" onClick={() => setSelected(session)}>
<td className="px-3 py-3">
{session.cover_url ? (
{sessionCoverSrc(session) ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${session.cover_url}?ts=${session.started_at || 0}`} alt="" className="h-16 w-10 rounded object-cover ring-1 ring-white/10" />
<img src={sessionCoverSrc(session)} alt="" className="h-16 w-10 rounded object-cover ring-1 ring-white/10" />
) : (
<div className="flex h-16 w-10 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-500 ring-1 ring-white/10">N/A</div>
)}
@ -221,11 +300,32 @@ export default function SessionsPage() {
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{session.ended_at ? fmtTs(session.ended_at) : "进行中"}</td>
<td className="whitespace-nowrap px-3 py-3 font-mono">{fmtDuration(session.duration_seconds)}</td>
<td className="whitespace-nowrap px-3 py-3">{session.push_date || "—"}</td>
<td className="whitespace-nowrap px-3 py-3" onClick={(e) => e.stopPropagation()}>
{!session.ended_at ? (
<button
type="button"
onClick={async () => {
if (!confirm(`结束「${session.anchor_name || session.room_id}」?`)) return;
try {
await fetchJson(`/api/sessions/${session.id}/end`, { method: "POST" });
await load();
} catch (e) {
setError((e as Error).message);
}
}}
className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10"
>
结束
</button>
) : (
<span className="text-xs text-slate-600">—</span>
)}
</td>
</tr>
))}
{!loading && sessions.length === 0 ? (
<tr>
<td colSpan={7} className="px-3 py-10 text-center text-slate-500">暂无场次。添加直播间后,开播会自动记入。</td>
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">暂无场次。添加直播间后,开播会自动记入。</td>
</tr>
) : null}
</tbody>
@ -243,40 +343,11 @@ export default function SessionsPage() {
) : null}
{selected ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={() => setSelected(null)}>
<div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5 shadow-2xl" onClick={(e) => e.stopPropagation()}>
<div className="flex items-start justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">{selected.anchor_name || "场次详情"}</h2>
<p className="mt-1 text-sm text-slate-400">{selected.title || "—"}</p>
</div>
<button type="button" className="text-slate-400 hover:text-slate-200" onClick={() => setSelected(null)}>✕</button>
</div>
<div className="mt-4 grid gap-4 md:grid-cols-[8rem_1fr]">
{selected.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${selected.cover_url}?ts=${selected.started_at || 0}`} alt="" className="h-36 w-full rounded-lg object-cover ring-1 ring-white/10" />
) : null}
<dl className="grid gap-2 text-sm">
<div>
<dt className="text-slate-500">直播间 URL</dt>
<dd className="break-all font-mono text-cyan-300">
{selected.source_url ? (
<a href={selected.source_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{selected.source_url} <ExternalLink className="h-3.5 w-3.5" />
</a>
) : "—"}
</dd>
</div>
<div><dt className="text-slate-500">房间号</dt><dd>{selected.room_id || "—"}</dd></div>
<div><dt className="text-slate-500">开播</dt><dd>{fmtTs(selected.started_at)}</dd></div>
<div><dt className="text-slate-500">停播</dt><dd>{selected.ended_at ? fmtTs(selected.ended_at) : "进行中"}</dd></div>
<div><dt className="text-slate-500">总时长</dt><dd>{fmtDuration(selected.duration_seconds)}</dd></div>
<div><dt className="text-slate-500">结束原因</dt><dd>{selected.end_reason || "—"}</dd></div>
</dl>
</div>
</div>
</div>
<SessionDetailModal
session={selected}
onClose={() => setSelected(null)}
onUpdated={() => void load()}
/>
) : null}
</Shell>
);

View File

@ -213,8 +213,40 @@ export default function SettingsPage() {
</label>
))}
</div>
<div className="flex flex-wrap gap-2 pt-1">
<button
type="button"
onClick={async () => {
try {
await fetchJson("/api/notify/test", { method: "POST" });
setMsg("已发送 Webhook 测试");
} catch (e) {
setError((e as Error).message);
}
}}
className="rounded-lg border border-sky-500/30 bg-sky-500/10 px-3 py-1.5 text-xs text-sky-100"
>
发送 Webhook 测试
</button>
<button
type="button"
onClick={async () => {
if (!("Notification" in window)) {
setError("当前浏览器不支持系统通知");
return;
}
const perm = await Notification.requestPermission();
setMsg(perm === "granted" ? "已开启浏览器开播/风控通知" : `通知权限:${perm}`);
}}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs"
>
开启浏览器通知
</button>
</div>
</div>
<OpsPanel />
<div className="flex items-center gap-3">
<button type="button" onClick={() => void save()} className="inline-flex items-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d]">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
@ -226,3 +258,89 @@ export default function SettingsPage() {
</Shell>
);
}
function OpsPanel() {
const [health, setHealth] = useState<Record<string, any> | null>(null);
const [busy, setBusy] = useState("");
const [log, setLog] = useState("");
const refresh = useCallback(async () => {
try {
setHealth(await fetchJson("/api/health"));
} catch (e) {
setLog((e as Error).message);
}
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
async function run(label: string, path: string, method: string = "POST") {
setBusy(label);
setLog("");
try {
const data = await fetchJson(path, { method });
setLog(`${label} → ${JSON.stringify(data).slice(0, 280)}`);
await refresh();
} catch (e) {
setLog(`${label} 失败:${(e as Error).message}`);
} finally {
setBusy("");
}
}
const pbOk = Boolean(health?.pocketbase?.ok);
const s3Ok = Boolean(health?.s3?.ok);
const s3Enabled = Boolean(health?.s3?.enabled);
return (
<div className="mb-6 space-y-3 rounded-xl border border-teal-500/20 bg-teal-500/5 p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-medium text-teal-100">运维:PocketBase / S3 / 封面</h3>
<button type="button" onClick={() => void refresh()} className="text-xs text-slate-400 hover:text-white">
刷新状态
</button>
</div>
<div className="grid gap-2 sm:grid-cols-3 text-xs">
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">PocketBase</div>
<div className={pbOk ? "text-teal-200" : "text-rose-200"}>{pbOk ? "正常" : "异常"}</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">S3 媒体库</div>
<div className={s3Enabled && s3Ok ? "text-teal-200" : "text-amber-200"}>
{!s3Enabled ? "未启用" : s3Ok ? "正常" : "异常"}
</div>
<div className="mt-0.5 truncate text-[10px] text-slate-500">{health?.s3?.public_base || health?.s3?.bucket || ""}</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">监控</div>
<div className="text-slate-200">{health?.monitor?.running ? "运行中" : "未运行"}</div>
</div>
</div>
<div className="flex flex-wrap gap-2">
{[
["同步 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]) => (
<button
key={path}
type="button"
disabled={Boolean(busy)}
onClick={() => void run(label, path)}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10 disabled:opacity-50"
>
{busy === label ? "…" : label}
</button>
))}
</div>
{log ? <pre className="max-h-28 overflow-auto rounded-lg bg-black/40 p-2 text-[11px] text-slate-400 whitespace-pre-wrap">{log}</pre> : null}
</div>
);
}

View File

@ -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<Session[]>([]);
const [rangeSessions, setRangeSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<Session | null>(null);
const [focusSlot, setFocusSlot] = useState<number | null>(null);
const [tag, setTag] = useState("");
const [tagOptions, setTagOptions] = useState<string[]>([]);
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<string>[] = 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<string, number[]> = {};
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 (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">🕐 开播时段规律</h2>
<p className="text-sm text-slate-400">
一天拆成 6 个 4 小时段,按
<span className="mx-1 text-teal-200/90">开播时刻</span>
归类;可看单日明细或近 7 天稳定规律。
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex rounded-xl border border-white/10 bg-black/30 p-0.5 text-sm">
<button
type="button"
onClick={() => setRangeMode("day")}
className={`rounded-lg px-3 py-1.5 ${rangeMode === "day" ? "bg-white/15 text-white" : "text-slate-400"}`}
>
单日
</button>
<button
type="button"
onClick={() => setRangeMode("7d")}
className={`rounded-lg px-3 py-1.5 ${rangeMode === "7d" ? "bg-white/15 text-white" : "text-slate-400"}`}
>
近 7 天
</button>
</div>
<select
value={tag}
onChange={(e) => setTag(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-white"
>
<option value="">全部标签</option>
<option value="重点">重点</option>
{tagOptions.filter((t) => t !== "重点").map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
<label className="text-xs text-slate-400">
锚点日
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value || todayLocalISO())}
className="ml-2 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-white"
/>
</label>
<button
type="button"
onClick={() => setDate(todayLocalISO())}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
今天
</button>
<button
type="button"
onClick={() => void load()}
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
</div>
{error ? (
<div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div>
) : null}
<div className="mb-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatTile
emoji="📡"
label={rangeMode === "7d" ? "7 日开播场次" : "当日开播场次"}
value={rangeMode === "7d" ? patternTotal : dayTotalOpens}
hint={rangeMode === "7d" ? `${rangeFrom} → ${date}` : date}
accent="teal"
/>
<StatTile
emoji="🏠"
label="独立直播间"
value={new Set((rangeMode === "7d" ? patternSessions : daySessions).map((s) => s.room_id || s.id)).size}
hint="同一房间多次开播只计一次"
accent="sky"
/>
<StatTile
emoji="🔥"
label={rangeMode === "7d" ? "稳定高峰时段" : "当日高峰时段"}
value={peakSlot == null ? "—" : SLOTS[peakSlot].label}
hint={
peakSlot == null
? "暂无数据"
: `${SLOTS[peakSlot].range} · ${(rangeMode === "7d" ? patternSlotStats : daySlotStats)[peakSlot].opens} 场`
}
accent="rose"
/>
<StatTile
emoji="⏱️"
label="当日累计时长"
value={fmtDuration(daySessions.reduce((n, s) => n + (Number(s.duration_seconds) || 0), 0))}
hint="下方时间轴始终展示锚点日明细"
accent="amber"
/>
</div>
<div className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<h3 className="font-display text-sm font-semibold text-slate-200">
{rangeMode === "7d" ? "近 7 天六段开播分布(规律)" : "六段开播分布"}
</h3>
<button
type="button"
onClick={() => setFocusSlot(null)}
className={`rounded-lg px-2.5 py-1 text-xs ${
focusSlot == null ? "bg-white/15 text-white" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
看全天明细
</button>
</div>
<div className="grid gap-2 sm:grid-cols-3 lg:grid-cols-6">
{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 (
<button
key={slot.id}
type="button"
onClick={() => setFocusSlot(active ? null : slot.id)}
className={`rounded-xl border px-3 py-3 text-left transition ${
active || isPeak
? "border-teal-400/40 bg-teal-500/10"
: "border-white/10 bg-black/20 hover:bg-white/[0.04]"
}`}
>
<div className="flex items-center justify-between gap-1">
<span className="text-xs font-medium text-white">{slot.label}</span>
{isNow ? <LivePulse label="当前" /> : null}
</div>
<div className="mt-0.5 text-[10px] text-slate-500">{slot.range}</div>
<div className="mt-2 font-display text-xl font-semibold text-white">{st.opens}</div>
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-gradient-to-r from-teal-400/80 to-rose-400/70"
style={{ width: `${pct}%` }}
/>
</div>
<div className="mt-1 flex justify-between text-[10px] text-slate-500">
<span>{st.uniqueRooms} 间</span>
<span>{pct}%</span>
</div>
</button>
);
})}
</div>
</div>
{rangeMode === "7d" ? (
<div className="mb-6 glass-panel rounded-2xl p-4">
<h3 className="mb-3 font-display text-sm font-semibold text-slate-200">日 × 时段热力(开播次数)</h3>
<div className="overflow-x-auto">
<table className="min-w-full text-center text-xs">
<thead>
<tr className="text-slate-500">
<th className="px-2 py-2 text-left font-normal">日期</th>
{SLOTS.map((s) => (
<th key={s.id} className="px-2 py-2 font-normal">
{s.label}
</th>
))}
</tr>
</thead>
<tbody>
{heat.dates.map((d) => (
<tr key={d} className={d === date ? "bg-teal-500/5" : undefined}>
<td className="whitespace-nowrap px-2 py-1.5 text-left text-slate-300">
{d.slice(5)}
{d === date ? <span className="ml-1 text-teal-300">锚点</span> : null}
</td>
{heat.map[d].map((n, i) => {
const intensity = n / heat.max;
return (
<td key={`${d}-${i}`} className="px-1 py-1">
<button
type="button"
title={`${d} ${SLOTS[i].label}: ${n}`}
onClick={() => {
setDate(d);
setFocusSlot(i);
setRangeMode("day");
}}
className="mx-auto flex h-9 w-full min-w-[2.5rem] items-center justify-center rounded-md border border-white/5 tabular-nums"
style={{
background: `rgba(45, 212, 191, ${0.08 + intensity * 0.55})`,
color: intensity > 0.55 ? "#ecfeff" : "#94a3b8",
}}
>
{n || "·"}
</button>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
<p className="mt-2 text-[11px] text-slate-500">点击格子可跳到该日该时段明细。</p>
</div>
) : null}
{!loading && dayTotalOpens === 0 ? (
<EmptyState
emoji="🕐"
title="这一天还没有开播记录"
desc="换一天看看,或切到「近 7 天」查看整体开播规律。"
/>
) : (
<div className="relative space-y-0 pl-2">
<div className="mb-3 text-xs text-slate-500">时间轴:{date} 开播明细</div>
<div className="pointer-events-none absolute bottom-4 left-[22px] top-10 w-0.5 bg-gradient-to-b from-teal-400/50 via-amber-400/25 to-rose-400/20" />
{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 (
<section key={slot.id} className="relative pb-8 pl-10">
<div
className={`absolute left-3 top-3 flex h-5 w-5 items-center justify-center rounded-full border-2 ${
isPeak
? "border-rose-400 bg-rose-500/40"
: isNow
? "border-teal-300 bg-teal-400/50"
: "border-white/30 bg-slate-900"
}`}
>
<span className="h-1.5 w-1.5 rounded-full bg-white" />
</div>
<div className="glass-panel rounded-2xl p-4">
<div className="mb-3 flex flex-wrap items-end justify-between gap-3">
<div>
<div className="flex flex-wrap items-center gap-2">
<h3 className="font-display text-lg font-semibold text-white">
{slot.label}
<span className="ml-2 font-mono text-sm font-normal text-slate-400">{slot.range}</span>
</h3>
<span className={`rounded-md border px-2 py-0.5 text-[11px] ${SLOT_ACCENT[slot.id]}`}>
{slot.hint}
</span>
{isPeak ? (
<span className="rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-0.5 text-[11px] text-rose-100">
今日高峰
</span>
) : null}
{isNow ? <LivePulse label="当前时段" /> : null}
</div>
<p className="mt-1 text-xs text-slate-500">
开播 {st.opens} 场 · {st.uniqueRooms} 个直播间 · 占当日 {pct}%
{st.live > 0 ? ` · 仍在播 ${st.live}` : ""}
{st.duration > 0 ? ` · 时长合计 ${fmtDuration(st.duration)}` : ""}
</p>
</div>
</div>
{list.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 bg-black/20 px-4 py-8 text-center text-sm text-slate-500">
该时段无人开播
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{list.map((session) => (
<article
key={session.id}
className="hover-lift flex gap-3 rounded-xl border border-white/10 bg-black/25 p-2.5"
>
<button type="button" className="shrink-0" onClick={() => setSelected(session)} title="查看详情">
{sessionCoverSrc(session) ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={sessionCoverSrc(session)}
alt=""
className="h-20 w-14 rounded-lg object-cover ring-1 ring-white/10"
/>
) : (
<div className="flex h-20 w-14 items-center justify-center rounded-lg bg-slate-900 text-[10px] text-slate-500 ring-1 ring-white/10">
无图
</div>
)}
</button>
<div className="min-w-0 flex-1">
<button
type="button"
onClick={() => setSelected(session)}
className="block max-w-full truncate text-left text-sm font-medium text-teal-100 hover:text-white hover:underline"
>
{session.anchor_name || session.room_id || "未命名直播间"}
</button>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
<span className="font-mono text-slate-400">{fmtClock(session.started_at)} 开播</span>
{session.status === "active" || !session.ended_at ? (
<LivePulse />
) : (
<span>{fmtDuration(session.duration_seconds)}</span>
)}
</div>
{session.title ? (
<p className="mt-1 line-clamp-2 text-[11px] text-slate-500">{session.title}</p>
) : null}
</div>
</article>
))}
</div>
)}
</div>
</section>
);
})}
</div>
)}
<SessionDetailModal
session={selected}
onClose={() => setSelected(null)}
extraRows={
selected
? [
{
label: "所属时段",
value: (() => {
const idx = slotIndexFromStartedAt(selected.started_at);
if (idx == null) return "—";
return `${SLOTS[idx].label}(${SLOTS[idx].range})`;
})(),
},
]
: undefined
}
/>
</Shell>
);
}

View File

@ -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 (
<div
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm"
onClick={onClose}
role="dialog"
aria-modal="true"
<Modal
open
onClose={onClose}
zIndex={90}
panelClassName="relative max-h-[92vh] w-full max-w-3xl overflow-hidden rounded-2xl border border-white/10 bg-[#0b1220] shadow-2xl"
>
<div
className="relative max-h-[92vh] w-full max-w-3xl overflow-hidden rounded-2xl border border-white/10 bg-[#0b1220] shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<div className="min-w-0">
<div className="truncate text-sm font-medium text-white">{title || "封面预览"}</div>
{subtitle ? <div className="truncate text-xs text-slate-400">{subtitle}</div> : null}
</div>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 hover:bg-white/10"
>
关闭 Esc
</button>
</div>
<div className="flex max-h-[80vh] items-center justify-center bg-black/40 p-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={title || "cover"} className="max-h-[76vh] w-auto max-w-full rounded-lg object-contain" />
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<div className="min-w-0">
<div className="truncate text-sm font-medium text-white">{title || "封面预览"}</div>
{subtitle ? <div className="truncate text-xs text-slate-400">{subtitle}</div> : null}
</div>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200 hover:bg-white/10"
>
关闭 Esc
</button>
</div>
</div>
<div className="flex max-h-[80vh] items-center justify-center bg-black/40 p-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={title || "cover"} className="max-h-[76vh] w-auto max-w-full rounded-lg object-contain" />
</div>
</Modal>
);
}

View File

@ -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(
<div
className="fixed inset-0 flex items-center justify-center bg-black/70 p-4 backdrop-blur-[2px]"
style={{ zIndex, position: "fixed", top: 0, left: 0, right: 0, bottom: 0 }}
onClick={onClose}
role="dialog"
aria-modal="true"
>
<div className={panelClassName} onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>,
document.body,
);
}

View File

@ -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<SessionDetail | null>(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 (
<Modal open={Boolean(session)} onClose={onClose}>
{current ? (
<>
<div className="flex items-start justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">{current.anchor_name || "直播间详情"}</h2>
<p className="mt-1 text-sm text-slate-400">{current.title || "—"}</p>
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
{isActive ? (
<button
type="button"
disabled={Boolean(busy)}
onClick={() => void endNow()}
className="inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-1 text-xs text-amber-100 hover:bg-amber-500/20 disabled:opacity-50"
>
{busy === "end" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Square className="h-3.5 w-3.5" />}
结束场次
</button>
) : null}
<button
type="button"
disabled={Boolean(busy)}
onClick={() => void recapture()}
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-2.5 py-1 text-xs text-teal-100 hover:bg-teal-500/20 disabled:opacity-50"
>
{busy === "cover" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
补抓封面
</button>
<button
type="button"
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/10"
onClick={onClose}
>
关闭 Esc
</button>
</div>
</div>
{err ? <div className="mt-2 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-100">{err}</div> : null}
<div className="mt-4 grid gap-4 md:grid-cols-[8rem_1fr]">
{cover ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={cover} alt="" className="h-36 w-full rounded-lg object-cover ring-1 ring-white/10" />
) : (
<div className="flex h-36 items-center justify-center rounded-lg bg-slate-900 text-xs text-slate-500 ring-1 ring-white/10">
暂无截图
</div>
)}
<dl className="grid gap-2 text-sm">
<div>
<dt className="text-slate-500">直播间 URL</dt>
<dd className="break-all font-mono text-cyan-300">
{current.source_url ? (
<a
href={current.source_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 hover:underline"
>
{current.source_url} <ExternalLink className="h-3.5 w-3.5" />
</a>
) : (
"—"
)}
</dd>
</div>
<div>
<dt className="text-slate-500">房间号</dt>
<dd>{current.room_id || "—"}</dd>
</div>
{extraRows?.map((row) => (
<div key={row.label}>
<dt className="text-slate-500">{row.label}</dt>
<dd>{row.value}</dd>
</div>
))}
<div>
<dt className="text-slate-500">开播</dt>
<dd>{fmtTs(current.started_at)}</dd>
</div>
<div>
<dt className="text-slate-500">停播</dt>
<dd>{current.ended_at ? fmtTs(current.ended_at) : "进行中"}</dd>
</div>
<div>
<dt className="text-slate-500">总时长</dt>
<dd>{fmtDuration(current.duration_seconds)}</dd>
</div>
<div>
<dt className="text-slate-500">结束原因</dt>
<dd>{current.end_reason || "—"}</dd>
</div>
</dl>
</div>
</>
) : null}
</Modal>
);
}

View File

@ -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 }) {
</p>
</div>
</div>
<nav className="flex flex-wrap gap-2">
<nav className="hidden max-w-full flex-wrap gap-2 md:flex">
{NAV.map((item) => {
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
return (
@ -59,12 +62,53 @@ export function Shell({ children }: { children: React.ReactNode }) {
})}
</nav>
</div>
{/* 手机:顶部横向可滑导航 */}
<nav className="mt-4 flex gap-2 overflow-x-auto pb-1 md:hidden [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{NAV.map((item) => {
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
return (
<Link
key={item.href}
href={item.href}
className={`nav-chip shrink-0 rounded-xl px-3 py-1.5 text-sm ${
active
? "active bg-white/15 text-white ring-1 ring-teal-400/30"
: "bg-white/5 text-slate-400"
}`}
>
<span className="mr-1">{item.emoji}</span>
{item.label}
</Link>
);
})}
</nav>
</header>
<main className="page-enter flex-1 pb-10">{children}</main>
<footer className="border-t border-white/5 py-4 text-center text-[11px] text-slate-600">
<main className="page-enter flex-1 pb-24 md:pb-10">{children}</main>
<footer className="hidden border-t border-white/5 py-4 text-center text-[11px] text-slate-600 md:block">
Douyin Monitor · realtime radar for live rooms
</footer>
</div>
{/* 手机底部快捷栏 */}
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-white/10 bg-[#071018]/95 px-2 pb-[env(safe-area-inset-bottom)] pt-1 backdrop-blur-md md:hidden">
<div className="mx-auto flex max-w-lg items-stretch justify-between gap-1">
{NAV.filter((n) => MOBILE_PRIMARY.includes(n.href)).map((item) => {
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
return (
<Link
key={item.href}
href={item.href}
className={`flex min-w-0 flex-1 flex-col items-center gap-0.5 rounded-lg px-1 py-2 text-[10px] ${
active ? "text-teal-200" : "text-slate-500"
}`}
>
<span className="text-base leading-none">{item.emoji}</span>
<span className="truncate">{item.label}</span>
</Link>
);
})}
</div>
</nav>
</div>
);
}

View File

@ -46,3 +46,17 @@ export function fmtTs(ts) {
return String(ts);
}
}
/** Prefer API proxy so private S3 still loads; bust cache safely. */
export function sessionCoverSrc(session, bust = true) {
if (!session) return "";
const base =
session.cover_proxy_url ||
(session.id ? `/api/sessions/${session.id}/cover` : "") ||
session.cover_url ||
"";
if (!base) return "";
if (!bust) return base;
const ts = session.started_at || session.updated_at || Date.now();
return base.includes("?") ? `${base}&ts=${ts}` : `${base}?ts=${ts}`;
}

View File

@ -9,6 +9,7 @@ export type StreamEvent = {
message?: string;
anchor_name?: string;
room_id?: string;
session_id?: string;
};
export function useEventStream(enabled = true) {

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,167 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"hidden": false,
"id": "number3280375435",
"max": null,
"min": null,
"name": "ts",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1002749145",
"max": 0,
"min": 0,
"name": "kind",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2599078931",
"max": 0,
"min": 0,
"name": "level",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3065852031",
"max": 0,
"min": 0,
"name": "message",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1410822291",
"max": 0,
"min": 0,
"name": "room_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1631579359",
"max": 0,
"min": 0,
"name": "session_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2904793982",
"max": 0,
"min": 0,
"name": "anchor_name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3046793135",
"max": 0,
"min": 0,
"name": "sqlite_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_124438418",
"indexes": [],
"listRule": null,
"name": "dy_events",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_124438418");
return app.delete(collection);
})

View File

@ -0,0 +1,48 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_1332144992")
// add field
collection.fields.addAt(10, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1874629670",
"max": 0,
"min": 0,
"name": "tags",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
// add field
collection.fields.addAt(11, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1232948848",
"max": 0,
"min": 0,
"name": "last_title",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_1332144992")
// remove field
collection.fields.removeById("text1874629670")
// remove field
collection.fields.removeById("text1232948848")
return app.save(collection)
})

View File

@ -0,0 +1,83 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_596514221")
// add field
collection.fields.addAt(13, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1604895770",
"max": 0,
"min": 0,
"name": "room_pk",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
// add field
collection.fields.addAt(14, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1269031876",
"max": 0,
"min": 0,
"name": "end_reason",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
// add field
collection.fields.addAt(15, new Field({
"exceptDomains": null,
"hidden": false,
"id": "url1189499079",
"name": "cover_url",
"onlyDomains": null,
"presentable": false,
"required": false,
"system": false,
"type": "url"
}))
// add field
collection.fields.addAt(16, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text1065927398",
"max": 0,
"min": 0,
"name": "cover_path",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_596514221")
// remove field
collection.fields.removeById("text1604895770")
// remove field
collection.fields.removeById("text1269031876")
// remove field
collection.fields.removeById("url1189499079")
// remove field
collection.fields.removeById("text1065927398")
return app.save(collection)
})

View File

@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
"""Check the three suspicious rooms and whether active timers match Douyin."""
import json
import time
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
FOCUS = ["杭州光头煎饺", "阿超盖浇饭", "小易"]
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
script = r'''
import json, sqlite3, time, urllib.request
from pathlib import Path
db = "/opt/douyinWEB/backend/data/monitor.db"
conn = sqlite3.connect(db)
conn.row_factory = sqlite3.Row
now = time.time()
focus = ["杭州光头煎饺", "阿超盖浇饭", "小易"]
print("NOW", now)
print("=== focus rooms ===")
for name in focus:
rows = conn.execute(
"SELECT id, room_id, last_status, last_anchor, active_session_id, last_checked_at FROM rooms WHERE last_anchor LIKE ? OR note LIKE ?",
(f"%{name}%", f"%{name}%"),
).fetchall()
for r in rows:
print(dict(r))
sess = conn.execute(
"SELECT id, room_id, anchor_name, status, started_at, ended_at, end_reason, duration_seconds FROM sessions WHERE anchor_name LIKE ? ORDER BY started_at DESC LIMIT 3",
(f"%{name}%",),
).fetchall()
for s in sess:
d = dict(s)
if d.get("started_at"):
d["elapsed_if_active"] = now - float(d["started_at"])
print("sess", d)
print("=== active vs room status ===")
for s in conn.execute("SELECT id, room_id, room_pk, anchor_name, started_at FROM sessions WHERE status='active' AND ended_at IS NULL").fetchall():
room = conn.execute("SELECT last_status, active_session_id, last_anchor FROM rooms WHERE id=?", (s["room_pk"],)).fetchone()
el = now - float(s["started_at"])
print({
"anchor": s["anchor_name"],
"room_id": s["room_id"],
"elapsed_h": round(el/3600, 2),
"room_status": room["last_status"] if room else None,
"room_active_sid": (room["active_session_id"] if room else None) == s["id"],
})
# probe first 5 active via live check endpoint if exists
print("=== api monitor ===")
try:
print(urllib.request.urlopen("http://127.0.0.1:8014/api/monitor", timeout=20).read().decode()[:500])
except Exception as e:
print("monitor err", e)
try:
print(urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=10).read().decode()[:300])
except Exception as e:
print("health err", e)
'''
cmd = f"cd /opt/douyinWEB && /opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n{script}\nPY"
_, o, e = c.exec_command(cmd, timeout=60)
print(o.read().decode("utf-8", errors="replace"))
err = e.read().decode("utf-8", errors="replace")
if err.strip():
print("ERR", err[-800:])
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
import paramiko
SCRIPT = r'''
import sys, asyncio, json
sys.path.insert(0, "/opt/douyinWEB/backend")
from app import pb_sync, db
async def main():
await pb_sync.ensure_admin()
headers = await pb_sync._auth_headers()
s = (db.list_sessions(limit=1, offset=0).get("sessions") or [None])[0]
print("sample session", s.get("id"), s.get("anchor_name"), (s.get("cover_path") or "")[:60] if s else None)
body = {
"sqlite_id": s["id"],
"room_id": s.get("room_id") or "",
"source_url": s.get("source_url") or "",
"anchor_name": s.get("anchor_name") or "",
"title": s.get("title") or "",
"started_at": s.get("started_at") or 0,
"ended_at": s.get("ended_at") or 0,
"duration_seconds": s.get("duration_seconds") or 0,
"push_date": s.get("push_date") or "",
"status": s.get("status") or "",
}
if str(s.get("cover_path") or "").startswith("http"):
body["cover_url"] = s["cover_path"]
body["cover_path"] = s["cover_path"]
async with await pb_sync._client() as client:
# inspect collection rules
col = await client.get("/api/collections/dy_sessions", headers=headers)
cj = col.json()
print("createRule", cj.get("createRule"), "updateRule", cj.get("updateRule"), "listRule", cj.get("listRule"))
resp = await client.post("/api/collections/dy_sessions/records", headers=headers, json=body)
print("POST", resp.status_code, resp.text[:500])
# try rooms
rooms = db.list_rooms(limit=1).get("rooms") or []
if rooms:
r = rooms[0]
rbody = {"sqlite_id": r["id"], "url": r.get("url") or "", "room_id": r.get("room_id") or "", "note": r.get("note") or "", "enabled": bool(r.get("enabled")), "last_status": r.get("last_status") or "", "last_anchor": r.get("last_anchor") or ""}
rr = await client.post("/api/collections/dy_rooms/records", headers=headers, json=rbody)
print("ROOM POST", rr.status_code, rr.text[:300])
lst = await client.get("/api/collections/dy_rooms/records", headers=headers, params={"perPage": 2})
print("ROOM list", lst.status_code, lst.json().get("totalItems"))
asyncio.run(main())
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY",
timeout=60,
)
print(o.read().decode("utf-8", "replace"))
print(e.read().decode("utf-8", "replace")[-1000:])
c.close()

View File

@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command("""
set +e
systemctl reset-failed douyinweb-web
systemctl restart douyinweb-api
systemctl restart douyinweb-web
sleep 8
systemctl --no-pager -l status douyinweb-web | head -35
ss -lntp | grep -E '4014|8014|8333'
journalctl -u douyinweb-web -n 40 --no-pager
curl -s -o /dev/null -w 'web:%{http_code}\n' --max-time 20 http://127.0.0.1:4014/
curl -s -o /dev/null -w 'api:%{http_code}\n' --max-time 10 http://127.0.0.1:8014/api/health
python3 - <<'PY'
import json,urllib.request
d=json.load(urllib.request.urlopen('http://127.0.0.1:8014/api/sessions/active', timeout=15))
print('active', d.get('total'))
for s in (d.get('sessions') or [])[:3]:
print(s.get('anchor_name'), s.get('cover_url'), s.get('cover_path','')[:70])
sid=s.get('id')
if sid:
try:
r=urllib.request.urlopen(f'http://127.0.0.1:8014/api/sessions/{sid}/cover', timeout=20)
print(' cover_http', r.status, r.headers.get('content-type'), 'len', r.headers.get('content-length'))
except Exception as e:
print(' cover_err', e)
PY
""", timeout=120, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-7000:])
c.close()

114
scripts/deploy_cover_fix.py Normal file
View File

@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
"""Deploy cover fix + backfill missing thumbnails."""
import json
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/douyin.py",
"backend/app/cover.py",
"backend/app/monitor.py",
"backend/app/main.py",
"backend/app/db.py",
]
def run(c, cmd: str, timeout: int = 180) -> tuple[int, str]:
print("$", cmd, flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.2)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
out = "".join(buf)
print(out[-2000:], flush=True)
return code, out
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 4; systemctl is-active douyinweb-api")
for i in range(20):
_, out = run(
c,
"curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo fail",
timeout=30,
)
if "200" in out:
break
time.sleep(1)
# backfill can take a while (1s * N)
code, out = run(
c,
"curl -s -X POST 'http://127.0.0.1:8014/api/sessions/backfill-covers?limit=40'",
timeout=300,
)
if "{" in out:
raw = out[out.index("{") :]
try:
data = json.loads(raw)
print(
"BACKFILL",
{k: data.get(k) for k in ("ok", "fail", "attempted")},
flush=True,
)
for r in (data.get("results") or [])[:15]:
print(
" ",
r.get("anchor"),
"ok=",
r.get("ok"),
"method=",
r.get("method"),
"err=",
r.get("error"),
flush=True,
)
except Exception as exc:
print("parse err", exc, raw[:500], flush=True)
_, out = run(
c,
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n"
"import sqlite3\n"
"c=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db')\n"
"total=c.execute('select count(*) from sessions').fetchone()[0]\n"
"empty=c.execute(\"select count(*) from sessions where cover_path is null or trim(cover_path)=''\").fetchone()[0]\n"
"print(f'total={total} no_cover={empty} with_cover={total-empty}')\n"
"for name in ['雨汐','大墨鱼']:\n"
" rows=c.execute('select anchor_name, substr(cover_path,1,70), status from sessions where anchor_name like ? order by started_at desc limit 2', (f'%{name}%',)).fetchall()\n"
" print(name, rows)\n"
"PY",
timeout=40,
)
c.close()
print("done", flush=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"frontend/src/lib/api.js",
"frontend/src/components/SessionDetailModal.tsx",
"frontend/src/app/covers/page.tsx",
"frontend/src/app/settings/page.tsx",
"frontend/src/app/page.tsx",
"frontend/src/app/sessions/page.tsx",
"frontend/src/app/slots/page.tsx",
"frontend/src/app/anchors/page.tsx",
"backend/app/main.py",
"backend/app/db.py",
"backend/app/cover.py",
"backend/app/pb_sync.py",
"backend/app/monitor.py",
"backend/app/douyin.py",
]
def run(c, cmd, timeout=360):
print("$", cmd[:140], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
print("".join(buf)[-2200:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
local = LOCAL / rel
if not local.exists():
print("skip", rel)
continue
print("upload", rel, flush=True)
sftp.put(str(local), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
code = run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=360)
if code != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl start douyinweb-api douyinweb-web; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
run(
c,
"curl -s http://127.0.0.1:8014/api/health | head -c 500; echo; "
"curl -s -o /dev/null -w 'home=%{http_code} settings=%{http_code} covers=%{http_code}\\n' "
"http://127.0.0.1:4015/ http://127.0.0.1:4015/settings http://127.0.0.1:4015/covers",
)
c.close()
print("DONE")
if __name__ == "__main__":
main()

63
scripts/deploy_pass2.py Normal file
View File

@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"frontend/src/app/events/page.tsx",
"frontend/src/app/page.tsx",
"frontend/src/app/sessions/page.tsx",
"frontend/src/app/slots/page.tsx",
"frontend/src/app/settings/page.tsx",
"frontend/src/components/Shell.tsx",
"backend/app/db.py",
"backend/app/main.py",
"backend/app/notify.py",
]
def run(c, cmd, timeout=360):
print("$", cmd[:140], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
print("".join(buf)[-2000:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=360) != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl start douyinweb-api douyinweb-web; sleep 2; systemctl is-active douyinweb-api douyinweb-web")
run(c, "curl -s 'http://127.0.0.1:8014/api/anchors/upcoming?limit=5' | head -c 400; echo")
c.close()
print("DONE")
if __name__ == "__main__":
main()

69
scripts/deploy_pass3.py Normal file
View File

@ -0,0 +1,69 @@
# -*- coding: utf-8 -*-
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"backend/app/main.py",
"backend/app/models.py",
"backend/app/monitor.py",
"frontend/src/app/page.tsx",
"frontend/src/app/covers/page.tsx",
"frontend/src/app/events/page.tsx",
"frontend/src/app/rooms/page.tsx",
]
def run(c, cmd, timeout=360):
print("$", cmd[:160], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
print("".join(buf)[-2500:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
raise SystemExit(1)
run(
c,
"systemctl restart douyinweb-web --no-block; sleep 4; "
"systemctl start douyinweb-api douyinweb-web; sleep 2; "
"systemctl is-active douyinweb-api douyinweb-web",
)
run(c, "curl -s 'http://127.0.0.1:8014/api/monitor/status' | head -c 600; echo")
run(c, "curl -s 'http://127.0.0.1:8014/api/sessions/missing-covers?limit=3' | head -c 400; echo")
run(c, "curl -s 'http://127.0.0.1:8014/api/events/export?format=json' | head -c 300; echo")
c.close()
print("DONE")
if __name__ == "__main__":
main()

74
scripts/deploy_pass4.py Normal file
View File

@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"backend/app/main.py",
"frontend/src/components/SessionDetailModal.tsx",
"frontend/src/lib/realtime.ts",
"frontend/src/app/page.tsx",
"frontend/src/app/events/page.tsx",
"frontend/src/app/sessions/page.tsx",
"frontend/src/app/rooms/page.tsx",
"frontend/src/app/covers/page.tsx",
]
def run(c, cmd, timeout=420):
print("$", cmd[:160], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
print("".join(buf)[-2500:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
raise SystemExit(1)
run(
c,
"systemctl restart douyinweb-web --no-block; sleep 4; "
"systemctl start douyinweb-api douyinweb-web; sleep 2; "
"systemctl is-active douyinweb-api douyinweb-web",
)
run(c, "curl -s -X POST 'http://127.0.0.1:8014/api/sessions/missing-covers?limit=1' -o /dev/null -w '%{http_code}\n' || true")
run(
c,
"curl -s -o /dev/null -w '%{http_code}\\n' "
"-X POST 'http://127.0.0.1:8014/api/sessions/00000000-0000-0000-0000-000000000000/end'",
)
run(c, "curl -s 'http://127.0.0.1:8014/api/sessions/export?format=json&tag=%E9%87%8D%E7%82%B9' | head -c 200; echo")
c.close()
print("DONE")
if __name__ == "__main__":
main()

114
scripts/deploy_pb_s3_fix.py Normal file
View File

@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
"""Deploy PB+S3 architecture fix and sync data."""
import json
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/pb_sync.py",
"backend/app/cover.py",
"backend/app/db.py",
"backend/app/main.py",
"backend/app/monitor.py",
"backend/app/douyin.py",
]
def run(c, cmd: str, timeout: int = 300) -> tuple[int, str]:
print("$", cmd[:120], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.2)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
out = "".join(buf)
print(out[-2500:], flush=True)
return code, out
def curl_json(c, path: str, method: str = "GET", timeout: int = 300) -> dict:
flag = "-X POST" if method == "POST" else ""
_, out = run(c, f"curl -s {flag} 'http://127.0.0.1:8014{path}'", timeout=timeout)
if "{" not in out:
return {"raw": out[-500:]}
raw = out[out.index("{") :]
# strip trailing junk
try:
return json.loads(raw)
except Exception:
# try truncate to last }
end = raw.rfind("}")
if end > 0:
try:
return json.loads(raw[: end + 1])
except Exception:
pass
return {"raw": raw[:800]}
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 4; systemctl is-active douyinweb-api")
for _ in range(20):
_, out = run(c, "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health", timeout=20)
if "200" in out:
break
time.sleep(1)
print("=== PB bootstrap ===", flush=True)
print(curl_json(c, "/api/pb/bootstrap", "POST"), flush=True)
print("=== recapture active covers -> S3 ===", flush=True)
print(curl_json(c, "/api/sessions/active/recapture-covers", "POST", timeout=300), flush=True)
print("=== sync rooms to PB ===", flush=True)
print(curl_json(c, "/api/pb/sync-rooms", "POST", timeout=180), flush=True)
print("=== sync sessions to PB ===", flush=True)
print(curl_json(c, "/api/pb/sync-sessions?limit=500", "POST", timeout=180), flush=True)
print("=== verify sample ===", flush=True)
run(
c,
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n"
"import sqlite3, json, urllib.request\n"
"c=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db'); c.row_factory=sqlite3.Row\n"
"total=c.execute('select count(*) from sessions').fetchone()[0]\n"
"s3=c.execute(\"select count(*) from sessions where cover_path like 'http%'\").fetchone()[0]\n"
"empty=c.execute(\"select count(*) from sessions where cover_path is null or trim(cover_path)=''\").fetchone()[0]\n"
"print(f'sessions={total} s3_covers={s3} no_cover={empty}')\n"
"row=c.execute(\"select id,anchor_name,substr(cover_path,1,90) from sessions where cover_path like 'http%' order by started_at desc limit 1\").fetchone()\n"
"print('sample', dict(row) if row else None)\n"
"PY",
timeout=40,
)
c.close()
print("DONE", flush=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
"""Deploy zombie-session fix and reconcile on VPS."""
import json
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"backend/app/monitor.py",
"backend/app/main.py",
]
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
local = LOCAL / rel
remote = f"{REMOTE}/{rel}"
print(f"upload {rel} -> {remote}", flush=True)
sftp.put(str(local), remote)
sftp.close()
def run(cmd: str, timeout: int = 60) -> str:
print(f"$ {cmd}", flush=True)
_, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
out = o.read().decode("utf-8", errors="replace")
err = e.read().decode("utf-8", errors="replace")
if out.strip():
print(out.strip()[-2000:], flush=True)
if err.strip():
print("ERR:", err.strip()[-500:], flush=True)
return out
run("systemctl restart douyinweb-api && sleep 2 && systemctl is-active douyinweb-api")
for _ in range(20):
_, o, _ = c.exec_command(
"curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/status",
timeout=20,
)
code = o.read().decode().strip()
print(f"api status http={code}", flush=True)
if code.startswith("2"):
break
time.sleep(1)
_, o, _ = c.exec_command(
"curl -s -X POST http://127.0.0.1:8014/api/sessions/reconcile-stale",
timeout=40,
get_pty=True,
)
raw = o.read().decode("utf-8", errors="replace")
if "{" in raw:
raw = raw[raw.index("{") :]
print("reconcile:", raw.strip()[:3000], flush=True)
_, o, _ = c.exec_command(
"curl -s http://127.0.0.1:8014/api/sessions/active",
timeout=30,
get_pty=True,
)
raw = o.read().decode("utf-8", errors="replace")
if "{" in raw:
raw = raw[raw.index("{") :]
data = json.loads(raw)
print(f"active_total={data.get('total')}", flush=True)
now = time.time()
for s in data.get("sessions") or []:
started = float(s.get("started_at") or 0)
el = int(now - started) if started else 0
h, r = divmod(el, 3600)
m, sec = divmod(r, 60)
print(
f" LIVE {s.get('anchor_name')} {h}:{m:02d}:{sec:02d} room={s.get('room_id')}",
flush=True,
)
c.close()
print("done", flush=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
"""Deploy modal fix + slots/anchors/shell upgrades."""
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"frontend/src/components/Modal.tsx",
"frontend/src/components/SessionDetailModal.tsx",
"frontend/src/components/ImageLightbox.tsx",
"frontend/src/components/Shell.tsx",
"frontend/src/app/slots/page.tsx",
"frontend/src/app/sessions/page.tsx",
"frontend/src/app/anchors/page.tsx",
"frontend/src/app/page.tsx",
"frontend/src/app/globals.css",
"backend/app/main.py",
"backend/app/stats.py",
"backend/app/db.py",
"backend/app/monitor.py",
]
def run(c, cmd: str, timeout: int = 300) -> tuple[int, str]:
print("$", cmd, flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf: list[str] = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
out = "".join(buf)
print(out[-3000:], flush=True)
return code, out
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
local = LOCAL / rel
if not local.exists():
print("skip missing", rel, flush=True)
continue
remote = f"{REMOTE}/{rel}"
parent = "/".join(remote.split("/")[:-1])
run(c, f"mkdir -p {parent}", timeout=30)
print("upload", rel, flush=True)
sftp.put(str(local), remote)
sftp.close()
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
code, _ = run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=360)
if code != 0:
raise SystemExit("build failed")
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl start douyinweb-api douyinweb-web; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
run(
c,
"curl -s -o /dev/null -w 'api=%{http_code} ' http://127.0.0.1:8014/api/health; "
"curl -s -o /dev/null -w 'slots=%{http_code} ' http://127.0.0.1:4015/slots; "
"curl -s -o /dev/null -w 'anchors=%{http_code}\\n' http://127.0.0.1:4015/anchors",
)
c.close()
print("deployed ok", flush=True)
if __name__ == "__main__":
main()

16
scripts/find_caddyfile.py Normal file
View File

@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmds = [
"ps aux | grep -i caddy | grep -v grep",
"ls -la /etc/caddy /opt/caddy ~/Caddyfile /Caddyfile 2>/dev/null; find /etc /opt /root /home -maxdepth 3 -name 'Caddyfile*' 2>/dev/null | head",
"systemctl cat caddy 2>/dev/null | head -40",
"caddy version 2>/dev/null; which caddy",
]
for cmd in cmds:
print("====", cmd[:70], flush=True)
_, o, _ = c.exec_command(cmd, timeout=30, get_pty=True)
print(o.read().decode()[-2000:], flush=True)
c.close()

View File

@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
import json
import time
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
def exec_quiet(cmd: str, timeout: int = 90) -> str:
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buff = []
while True:
if chan.recv_ready():
buff.append(chan.recv(65535).decode("utf-8", errors="replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.2)
# drain
while chan.recv_ready():
buff.append(chan.recv(65535).decode("utf-8", errors="replace"))
code = chan.recv_exit_status()
out = "".join(buff)
print(f"$ {cmd}\nexit={code}\n{out[-1500:]}", flush=True)
return out
# restart in background so SSH doesn't hang on Type=notify
exec_quiet("systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api; systemctl status douyinweb-api --no-pager -l | head -n 20")
for i in range(25):
out = exec_quiet(
"curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/status || echo fail",
timeout=30,
)
code = "".join(ch for ch in out if ch.isdigit())[-3:]
print("probe", i, code, flush=True)
if code.startswith("2"):
break
time.sleep(1)
out = exec_quiet("curl -s -X POST http://127.0.0.1:8014/api/sessions/reconcile-stale", timeout=60)
if "{" in out:
js = out[out.index("{") :]
print("RECONCILE_JSON", js[:2500], flush=True)
out = exec_quiet("curl -s http://127.0.0.1:8014/api/sessions/active", timeout=40)
if "{" in out:
js = out[out.index("{") :]
data = json.loads(js)
print("active_total", data.get("total"), flush=True)
now = time.time()
for s in data.get("sessions") or []:
started = float(s.get("started_at") or 0)
el = int(now - started) if started else 0
h, r = divmod(el, 3600)
m, sec = divmod(r, 60)
print(
f"LIVE {s.get('anchor_name')} {h}:{m:02d}:{sec:02d} room={s.get('room_id')}",
flush=True,
)
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command("""
systemctl restart douyinweb-web
sleep 4
systemctl --no-pager status douyinweb-web | head -20
ss -lntp | grep 4014
curl -s -o /dev/null -w 'web:%{http_code}\n' --max-time 15 http://127.0.0.1:4014/
curl -s -o /dev/null -w 's3:%{http_code}\n' --max-time 10 http://127.0.0.1:8333/douyin-covers/covers/2d969f0e-ba00-4843-a57a-742710814cec.jpg
# make bucket publicly readable via seaweed if needed
""", timeout=60, get_pty=True)
print(o.read().decode())
c.close()

View File

@ -0,0 +1,61 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmd = r"""
set -e
cd /opt/douyinWEB
git fetch origin
git reset --hard origin/main
# keep next rewrite
cat > frontend/next.config.mjs <<'EOF'
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async rewrites() {
return [
{ source: "/api/:path*", destination: "http://127.0.0.1:8014/api/:path*" },
{ source: "/covers/:path*", destination: "http://127.0.0.1:8014/covers/:path*" },
];
},
};
export default nextConfig;
EOF
# anonymous read for SeaweedFS S3
cat >/etc/seaweedfs/s3.json <<'EOF'
{
"identities": [
{
"name": "anonymous",
"actions": ["Read"]
},
{
"name": "douyin",
"credentials": [
{"accessKey": "douyin", "secretKey": "douyinweb_s3_2026"}
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
}
]
}
EOF
systemctl restart seaweed-s3
cd frontend && npm run build
systemctl restart douyinweb-api douyinweb-web
sleep 6
systemctl is-active douyinweb-api douyinweb-web seaweed-s3
curl -s -o /dev/null -w 'web:%{http_code}\n' --max-time 15 http://127.0.0.1:4014/
SID=$(curl -s http://127.0.0.1:8014/api/sessions/active | python3 -c "import sys,json; d=json.load(sys.stdin); print((d.get('sessions') or [{}])[0].get('id',''))")
echo SID=$SID
curl -s -o /dev/null -w 'cover:%{http_code}\n' --max-time 20 "http://127.0.0.1:8014/api/sessions/$SID/cover"
curl -s http://127.0.0.1:8014/api/sessions/active | python3 -c "import sys,json; d=json.load(sys.stdin); print('n',d.get('total'));
[print(s.get('anchor_name'), s.get('cover_url')) for s in (d.get('sessions') or [])[:5]]"
"""
_, o, _ = c.exec_command(cmd, timeout=600, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-6000:])
c.close()

View File

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", port=22, username="root", password="Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmds = [
"ss -lntp | grep -E ':3000|:8000|:8090'",
"ps aux | grep -E 'uvicorn|next|pocketbase|node' | grep -v grep",
"systemctl list-units --type=service --state=running | grep -Ei 'douyin|next|uvicorn|node|pb|pocket|monitor|web' || true",
"ls /etc/systemd/system/*.service 2>/dev/null | head -50",
"command -v pm2; pm2 list 2>/dev/null || true",
"docker ps 2>/dev/null || true",
"curl -s http://127.0.0.1:8000/ | head -c 400; echo; curl -s http://127.0.0.1:8000/docs | head -c 200; echo; curl -s http://127.0.0.1:8000/openapi.json | head -c 300",
"ls -la /proc/$(ss -lntp | awk '/:8000/{print}' | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | head -1) 2>/dev/null | head",
"tr '\\0' ' ' < /proc/$(ss -lntp | python3 -c \"import sys,re; t=sys.stdin.read(); m=re.search(r':8000.*pid=(\\d+)', t); print(m.group(1) if m else '')\")/cmdline 2>/dev/null; echo",
]
for cmd in cmds:
print("\n====", cmd[:80], flush=True)
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-3000:], flush=True)
c.close()

82
scripts/move_web_4015.py Normal file
View File

@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
import paramiko
HOST = "107.173.30.245"
APP = "/opt/douyinWEB"
WEB = 4015
API = 8014
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmd = f"""
set -e
systemctl stop douyinweb-web || true
cat >/etc/systemd/system/douyinweb-web.service <<EOF
[Unit]
Description=DouyinWEB Next.js
After=network.target douyinweb-api.service
[Service]
Type=simple
WorkingDirectory={APP}/frontend
ExecStart=/usr/bin/npm run start -- --hostname 0.0.0.0 --port {WEB}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
# ensure rewrite points to API
cat > {APP}/frontend/next.config.mjs <<'EOF'
/** @type {{import('next').NextConfig}} */
const nextConfig = {{
reactStrictMode: true,
async rewrites() {{
return [
{{ source: "/api/:path*", destination: "http://127.0.0.1:{API}/api/:path*" }},
{{ source: "/covers/:path*", destination: "http://127.0.0.1:{API}/covers/:path*" }},
];
}},
}};
export default nextConfig;
EOF
cd {APP}
git fetch origin && git reset --hard origin/main
# restore rewrite after reset
cat > frontend/next.config.mjs <<'EOF'
/** @type {{import('next').NextConfig}} */
const nextConfig = {{
reactStrictMode: true,
async rewrites() {{
return [
{{ source: "/api/:path*", destination: "http://127.0.0.1:{API}/api/:path*" }},
{{ source: "/covers/:path*", destination: "http://127.0.0.1:{API}/covers/:path*" }},
];
}},
}};
export default nextConfig;
EOF
cd frontend && npm run build
systemctl daemon-reload
systemctl enable douyinweb-web
systemctl restart douyinweb-api douyinweb-web
sleep 7
ss -lntp | grep -E ':{WEB}|:{API}|:8333'
systemctl is-active douyinweb-web douyinweb-api
curl -s -o /dev/null -w 'web:%{{http_code}}\\n' --max-time 20 http://127.0.0.1:{WEB}/
curl -s http://127.0.0.1:{API}/api/sessions/active | python3 -c "import sys,json; d=json.load(sys.stdin); print('active',d.get('total'));
[print(s.get('anchor_name'), s.get('cover_url')) for s in (d.get('sessions') or [])[:5]]"
SID=$(curl -s http://127.0.0.1:{API}/api/sessions/active | python3 -c "import sys,json; d=json.load(sys.stdin); print((d.get('sessions') or [{{}}])[0].get('id',''))")
curl -s -o /dev/null -w 'cover:%{{http_code}} size:%{{size_download}}\\n' --max-time 20 http://127.0.0.1:{API}/api/sessions/$SID/cover
curl -s -o /dev/null -w 'cover_via_web:%{{http_code}}\\n' --max-time 20 http://127.0.0.1:{WEB}/api/sessions/$SID/cover
"""
_, o, _ = c.exec_command(cmd, timeout=600, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-5000:])
c.close()
print(f"\nOpen http://{HOST}:{WEB}/")

66
scripts/probe_covers2.py Normal file
View File

@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
import time
import paramiko
SCRIPT = r'''
import sqlite3, time, os, glob, json
from pathlib import Path
db="/opt/douyinWEB/backend/data/monitor.db"
conn=sqlite3.connect(db)
conn.row_factory=sqlite3.Row
# overall cover ratio
total=conn.execute("SELECT COUNT(*) c FROM sessions").fetchone()["c"]
empty=conn.execute("SELECT COUNT(*) c FROM sessions WHERE cover_path IS NULL OR trim(cover_path)=''").fetchone()["c"]
print(f"all_sessions={total} no_cover={empty} with_cover={total-empty} ratio_no={empty/total if total else 0:.2%}")
# by push_date last days
print("--- by push_date ---")
for r in conn.execute("SELECT push_date, COUNT(*) c, SUM(CASE WHEN cover_path IS NULL OR trim(cover_path)='' THEN 1 ELSE 0 END) nc FROM sessions GROUP BY push_date ORDER BY push_date DESC LIMIT 8"):
print(dict(r))
# recent no cover
print("--- recent no cover ---")
now=time.time()
for r in conn.execute("SELECT anchor_name, push_date, status, started_at, cover_path, substr(metadata_json,1,120) meta FROM sessions WHERE cover_path IS NULL OR trim(cover_path)='' ORDER BY started_at DESC LIMIT 15"):
d=dict(r); d["ago_h"]=round((now-float(d["started_at"] or 0))/3600,2); print(d)
# sample WITH cover
print("--- recent WITH cover ---")
for r in conn.execute("SELECT anchor_name, push_date, status, started_at, substr(cover_path,1,80) cover FROM sessions WHERE cover_path IS NOT NULL AND trim(cover_path)!='' ORDER BY started_at DESC LIMIT 8"):
print(dict(r))
# metadata stream?
print("--- metadata has stream? sample from no cover ---")
for r in conn.execute("SELECT anchor_name, metadata_json FROM sessions WHERE (cover_path IS NULL OR trim(cover_path)='') AND metadata_json!='' ORDER BY started_at DESC LIMIT 5"):
meta=r["metadata_json"]
has_stream=("flv" in meta.lower()) or ("stream" in meta.lower()) or ("m3u8" in meta.lower())
print(r["anchor_name"], "meta_len", len(meta), "has_streamish", has_stream, "snippet", meta[:200])
# app settings table name?
print("--- tables ---", [x[0] for x in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")])
for t in ["app_settings","setting","kv"]:
try:
print(t, conn.execute(f"SELECT * FROM {t} LIMIT 3").fetchall())
except Exception as e:
pass
# covers filesystem
covers=list(Path("/opt/douyinWEB/backend/data/covers").glob("*.jpg")) if Path("/opt/douyinWEB/backend/data/covers").exists() else []
print("local_jpg", len(covers))
# ffmpeg
import shutil
print("ffmpeg", shutil.which("ffmpeg"))
# check one live room for stream_url via API
import urllib.request
try:
d=json.load(urllib.request.urlopen("http://127.0.0.1:8014/api/sessions/active", timeout=20))
print("active", d.get("total"))
for s in (d.get("sessions") or [])[:5]:
print("active", s.get("anchor_name"), "cover_url", bool(s.get("cover_url")), "cover_path", (s.get("cover_path") or "")[:60])
except Exception as e:
print("api err", e)
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command("/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY", timeout=60)
print(o.read().decode())
err = e.read().decode()
if err.strip():
print("ERR", err[-1000:])
c.close()

View File

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmds = [
"nginx -v 2>&1; ls /etc/nginx/sites-enabled/ 2>/dev/null; ls /etc/nginx/conf.d/ 2>/dev/null",
"grep -Rni 'server_name\\|listen' /etc/nginx/sites-enabled /etc/nginx/conf.d 2>/dev/null | head -60",
"command -v certbot; ls /etc/letsencrypt/live 2>/dev/null",
"ss -lntp | grep -E ':80|:443|:4015|:8014|:8333|:8092'",
"curl -sI --max-time 5 http://dylive.nomadro.com/ | head -10",
"curl -sI --max-time 5 http://s3.nomadro.com/ | head -10",
"curl -sI --max-time 5 http://feiniu.nomadro.com/ | head -10",
]
for cmd in cmds:
print("\n====", cmd[:90], flush=True)
_, o, _ = c.exec_command(cmd, timeout=40, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-2500:], flush=True)
c.close()

View File

@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""Inspect why active/recent sessions have no covers."""
import json
import time
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
SCRIPT = r'''
import json, sqlite3, time, os
db="/opt/douyinWEB/backend/data/monitor.db"
conn=sqlite3.connect(db)
conn.row_factory=sqlite3.Row
now=time.time()
# today sessions without cover
rows=conn.execute("""
SELECT id, anchor_name, room_id, status, started_at, ended_at, cover_path, duration_seconds, push_date
FROM sessions
WHERE push_date=date('now','localtime')
ORDER BY started_at DESC
""").fetchall()
total=len(rows)
no_cover=[dict(r) for r in rows if not (r['cover_path'] or '').strip()]
with_cover=total-len(no_cover)
print(f"today_total={total} with_cover={with_cover} no_cover={len(no_cover)}")
print("--- no_cover sample ---")
for r in no_cover[:20]:
el=now-float(r['started_at'] or 0)
print(f"{r['anchor_name']!r} status={r['status']} cover={r['cover_path']!r} started_ago_h={el/3600:.2f} id={r['id'][:8]}")
# focus names
for name in ["雨汐","大墨鱼"]:
print("--- focus", name)
for r in conn.execute("SELECT id,anchor_name,status,cover_path,started_at,ended_at FROM sessions WHERE anchor_name LIKE ? ORDER BY started_at DESC LIMIT 5",(f"%{name}%",)):
print(dict(r))
# settings related
print("--- settings ---")
for r in conn.execute("SELECT key,value FROM settings WHERE key LIKE '%cover%' OR key LIKE '%ffmpeg%' OR key LIKE '%s3%' OR key LIKE '%seaweed%'"):
print(dict(r))
# env / service
print("--- cover dir ---")
import glob
print("local covers count", len(glob.glob('/opt/douyinWEB/backend/data/covers/*')))
print("s3 env", {k:os.environ.get(k,'')[:40] for k in ['S3_ENDPOINT','S3_BUCKET','S3_PUBLIC_BASE','AWS_ACCESS_KEY_ID']})
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
sftp.putfo(__import__("io").BytesIO(SCRIPT.encode()), "/tmp/check_covers.py")
# better write via open
sftp.close()
chan = c.get_transport().open_session()
chan.settimeout(60)
chan.exec_command("/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY")
import sys
out = chan.recv(1 << 20).decode("utf-8", "replace")
err = chan.recv_stderr(1 << 20).decode("utf-8", "replace")
print(out)
if err.strip():
print("ERR", err[-1500:])
c.close()

View File

@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
import json
import paramiko
SCRIPT = r'''
import sys, asyncio, json, sqlite3
sys.path.insert(0, "/opt/douyinWEB/backend")
from app.douyin import _fetch_web_enter, check_room, _normalize_result
from app import db
import httpx
cfg = db.get_settings_map()
cookie = str(cfg.get("dy_cookie") or "")
conn = sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db")
conn.row_factory = sqlite3.Row
# sessions missing cover with room
rows = conn.execute("""
SELECT s.anchor_name, s.room_id, r.url, r.last_status
FROM sessions s
LEFT JOIN rooms r ON r.id = s.room_pk
WHERE (s.cover_path IS NULL OR trim(s.cover_path)='')
AND s.anchor_name IN ('雨汐在农村','大墨鱼(硕士裸辞摆摊ing)','小媛发面鸡蛋饼')
""").fetchall()
print("targets", [dict(x) for x in rows])
async def inspect(url, rid, name):
print("====", name, rid)
async with httpx.AsyncClient(timeout=20, verify=False, trust_env=False) as client:
room = await _fetch_web_enter(client, rid, cookie=cookie)
print("keys", sorted(room.keys())[:40])
print("status", room.get("status"), "has_cover", "cover" in room, "has_owner", "owner" in room)
if room.get("cover"):
print("cover", json.dumps(room.get("cover"), ensure_ascii=False)[:220])
owner = room.get("owner") or {}
if isinstance(owner, dict) and owner.get("avatar_thumb"):
print("avatar", json.dumps(owner.get("avatar_thumb"), ensure_ascii=False)[:220])
# also dump user-level if present? enter wrapper
norm = _normalize_result(room, url)
print("norm cover_image", (norm.get("cover_image") or "")[:120], "stream", bool(norm.get("stream_url")), "live", norm.get("is_live"))
probed = await check_room(url, cookie=cookie)
print("check_room cover", (probed.get("cover_image") or "")[:120], "err", probed.get("error"))
async def main():
for r in rows:
if not r["url"]:
print("no url", r["anchor_name"]); continue
await inspect(r["url"], r["room_id"], r["anchor_name"])
await asyncio.sleep(1.2)
asyncio.run(main())
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
# upload fixed files that may not have been latest for cover.py force
sftp = c.open_sftp()
from pathlib import Path
LOCAL = Path(r"C:\Users\admin\Desktop\douyinWEB")
for rel in ["backend/app/cover.py", "backend/app/main.py"]:
sftp.put(str(LOCAL / rel), f"/opt/douyinWEB/{rel}")
sftp.close()
_, o, e = c.exec_command(
"systemctl restart douyinweb-api --no-block; sleep 3; "
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY",
timeout=120,
)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print("ERR", err[-2000:])
c.close()

View File

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
import paramiko
SCRIPT = r'''
import sys, asyncio, json
sys.path.insert(0, "/opt/douyinWEB/backend")
from app.douyin import check_room, _fetch_web_enter
from app import db
import httpx
cfg = db.get_settings_map()
cookie = str(cfg.get("dy_cookie") or "")
rows = db.list_rooms(limit=5, status="live") if hasattr(db, "list_rooms") else None
import sqlite3
conn = sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db")
conn.row_factory = sqlite3.Row
r = conn.execute("SELECT url, room_id, last_anchor FROM rooms WHERE last_status='live' LIMIT 1").fetchone()
print("room", dict(r) if r else None)
if not r:
raise SystemExit(0)
async def main():
res = await check_room(r["url"], cookie=cookie)
print("probe is_live", res.get("is_live"), "has_stream", bool(res.get("stream_url")))
async with httpx.AsyncClient(timeout=20, verify=False, trust_env=False) as client:
room = await _fetch_web_enter(client, r["room_id"], cookie=cookie)
print("room_top_keys", sorted(list(room.keys()))[:50])
for k in ["cover", "cover_url", "origin_cover", "share_url", "keyframe_image"]:
if k in room:
print(k, json.dumps(room.get(k), ensure_ascii=False)[:300])
owner = room.get("owner") or {}
print("owner_type", type(owner).__name__)
if isinstance(owner, dict):
print("owner_keys", list(owner.keys())[:40])
for k in ["avatar_thumb", "avatar_medium", "avatar_large", "nickname"]:
print("owner", k, json.dumps(owner.get(k), ensure_ascii=False)[:250])
stream = room.get("stream_url") or {}
if isinstance(stream, dict):
print("stream_keys", list(stream.keys())[:25])
flv = stream.get("flv_pull_url") or {}
print("flv_keys", list(flv.keys())[:10] if isinstance(flv, dict) else flv)
asyncio.run(main())
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY",
timeout=90,
)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print("ERR", err[-2000:])
c.close()

View File

@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmds = [
"which minio mc rclone aws 2>/dev/null; ls /opt 2>/dev/null | head",
"ss -lntp | grep -Ei '9000|9001|8333|7480|4566|9292' || true",
"docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null | head -20",
"systemctl list-units --type=service --state=running | grep -Ei 'minio|s3|oss|seaweed|garage' || true",
"ls /etc/systemd/system/*minio* /etc/systemd/system/*s3* 2>/dev/null; cat /etc/systemd/system/minio.service 2>/dev/null | head -40",
"find /opt /home /root -maxdepth 3 -iname '*minio*' 2>/dev/null | head",
"curl -s --max-time 5 http://127.0.0.1:8014/api/sessions/active | python3 -c \"import sys,json; d=json.load(sys.stdin); print('total',d.get('total'));\n[print(s.get('anchor_name'), s.get('cover_url'), s.get('cover_path')) for s in (d.get('sessions') or [])[:5]]\"",
"ls -la /opt/douyinWEB/backend/data/covers | head",
]
for cmd in cmds:
print("\n====", cmd[:90], flush=True)
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-2500:], flush=True)
c.close()

15
scripts/probe_s3_env.py Normal file
View File

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
for cmd in [
"grep -Rni 'minio\\|S3_\\|AWS_\\|boto3\\|9000' /opt/xauto /opt/wauto /etc/systemd/system 2>/dev/null | head -40",
"ls /opt/xauto 2>/dev/null | head; ls /opt/wauto 2>/dev/null | head",
"cat /opt/xauto/.env 2>/dev/null | grep -iE 's3|minio|oss|aws' | head -20",
"cat /opt/wauto/.env 2>/dev/null | grep -iE 's3|minio|oss|aws' | head -20",
]:
print("====", cmd[:70], flush=True)
_, o, _ = c.exec_command(cmd, timeout=40, get_pty=True)
print(o.read().decode()[-2000:], flush=True)
c.close()

8
scripts/read_caddy.py Normal file
View File

@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command("echo '=== MAIN ==='; cat /etc/caddy/Caddyfile; echo; echo '=== SITES ==='; ls -la /etc/caddy/sites/; echo; for f in /etc/caddy/sites/*; do echo \"--- $f ---\"; cat \"$f\"; echo; done", timeout=30, get_pty=True)
print(o.read().decode())
c.close()

View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
cmd = (
"systemctl start douyinweb-api douyinweb-web; sleep 5; "
"systemctl is-active douyinweb-api douyinweb-web; "
"curl -s -o /dev/null -w 'api=%{http_code}\\n' http://127.0.0.1:8014/api/health; "
"curl -s -o /dev/null -w 'web=%{http_code}\\n' http://127.0.0.1:4015/slots; "
"systemctl status douyinweb-web --no-pager -l | head -n 25"
)
chan = c.get_transport().open_session()
chan.settimeout(90)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
print("".join(buf))
c.close()

View File

@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
import paramiko
SCRIPT = r'''
import sys, asyncio
sys.path.insert(0, "/opt/douyinWEB/backend")
from app import pb_sync, db
async def main():
await pb_sync.ensure_collections()
# count PB sessions
headers = await pb_sync._auth_headers()
async with await pb_sync._client() as client:
rec = await client.get(
"/api/collections/dy_sessions/records",
headers=headers,
params={"perPage": 5, "skipTotal": "false"},
)
data = rec.json()
print("pb_total", data.get("totalItems"), "page_items", len(data.get("items") or []))
for it in (data.get("items") or [])[:5]:
print(it.get("anchor_name"), (it.get("cover_url") or "")[:80], it.get("sqlite_id"))
# re-sync all
rows = db.list_sessions(limit=500, offset=0).get("sessions") or []
ok=fail=0
for s in rows:
try:
rid = await pb_sync.upsert_record("dy_sessions", s["id"], {
"room_id": s.get("room_id") or "",
"room_pk": s.get("room_pk") or "",
"source_url": s.get("source_url") or "",
"anchor_name": s.get("anchor_name") or "",
"title": s.get("title") or "",
"started_at": s.get("started_at") or 0,
"ended_at": s.get("ended_at") or 0,
"duration_seconds": s.get("duration_seconds") or 0,
"push_date": s.get("push_date") or "",
"status": s.get("status") or "",
"end_reason": s.get("end_reason") or "",
"cover_path": s.get("cover_path") or "",
**({"cover_url": s["cover_path"]} if str(s.get("cover_path") or "").startswith("http") else {}),
})
if rid: ok += 1
else: fail += 1
except Exception as e:
fail += 1
print("err", e)
print("resync ok", ok, "fail", fail)
async with await pb_sync._client() as client:
rec = await client.get(
"/api/collections/dy_sessions/records",
headers=headers,
params={"perPage": 5, "sort": "-started_at"},
)
data = rec.json()
print("after_total", data.get("totalItems"))
for it in (data.get("items") or [])[:5]:
print({
"anchor": it.get("anchor_name"),
"cover_url": (it.get("cover_url") or "")[:90],
"status": it.get("status"),
})
asyncio.run(main())
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY",
timeout=180,
)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print("ERR", err[-1500:])
c.close()

50
scripts/ssh_probe.py Normal file
View File

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
import paramiko
host = "107.173.30.245"
combos = [
("root", "Xiao4669805", 4014),
("root", "Xiao4669805", 22),
("root", "4669805", 4014),
("root", "4669805", 22),
("eric", "4669805", 4014),
("eric", "Xiao4669805", 4014),
("eric", "4669805", 22),
("root", "Xiao4669805", 4014, True),
]
for item in combos:
user, pwd, port = item[0], item[1], item[2]
use_ki = len(item) > 3 and item[3]
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
if use_ki:
# keyboard-interactive
transport = paramiko.Transport((host, port))
transport.connect()
def handler(title, instructions, prompt_list):
return [pwd for _ in prompt_list]
transport.auth_interactive(user, handler)
print("OK-KI", user, port)
sess = transport.open_session()
sess.exec_command("whoami; hostname")
print(sess.recv(4096).decode())
transport.close()
break
c.connect(
host,
port=port,
username=user,
password=pwd,
timeout=20,
allow_agent=False,
look_for_keys=False,
banner_timeout=20,
)
_, o, _ = c.exec_command("whoami; hostname", timeout=20)
print("OK", user, port, o.read().decode().strip())
c.close()
break
except Exception as e:
print("FAIL", user, port, "KI" if use_ki else "PW", type(e).__name__, e)

View File

@ -0,0 +1,126 @@
# -*- coding: utf-8 -*-
"""Verify active session timers vs real Douyin live status."""
import asyncio
import json
import sys
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
def ssh_json(path: str):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command(
f"curl -s --max-time 20 http://127.0.0.1:8014{path}",
timeout=40,
get_pty=True,
)
raw = o.read().decode("utf-8", errors="replace").strip()
c.close()
# strip ANSI / pty junk
if "{" in raw:
raw = raw[raw.index("{") :]
if raw.endswith("%"):
raw = raw[:-1]
return json.loads(raw)
def fmt_dur(sec: float) -> str:
sec = int(max(0, sec))
h, r = divmod(sec, 3600)
m, s = divmod(r, 60)
return f"{h}:{m:02d}:{s:02d}"
async def main():
active = ssh_json("/api/sessions/active")
sessions = active.get("sessions") or []
now = time.time()
print(f"server_active_total={active.get('total')} local_now={now}", flush=True)
# focus names user asked
focus = ["杭州光头煎饺", "阿超盖浇饭", "小易"]
for s in sessions:
name = s.get("anchor_name") or ""
started = float(s.get("started_at") or 0)
elapsed = now - started if started else 0
print(
f"ACTIVE {name!r} room={s.get('room_id')} started={started} "
f"elapsed={fmt_dur(elapsed)} ({elapsed:.0f}s) cover={bool(s.get('cover_url'))}",
flush=True,
)
# probe each active via API check one room
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
script = r"""
import json, time, urllib.request
now=time.time()
d=json.load(urllib.request.urlopen('http://127.0.0.1:8014/api/sessions/active', timeout=30))
rooms=json.load(urllib.request.urlopen('http://127.0.0.1:8014/api/rooms?limit=2000&status=live', timeout=30))
print('active', d.get('total'), 'live_rooms_api', rooms.get('total'))
# map room_pk
by_pk={}
allr=json.load(urllib.request.urlopen('http://127.0.0.1:8014/api/rooms?limit=2000', timeout=30))
for r in allr.get('rooms') or []:
by_pk[r['id']]=r
for s in d.get('sessions') or []:
r=by_pk.get(s.get('room_pk') or '') or {}
started=float(s.get('started_at') or 0)
el=now-started
print('---')
print('anchor', s.get('anchor_name'))
print('session', s.get('id'))
print('room_id', s.get('room_id'), 'room_status', r.get('last_status'), 'room_last_check', r.get('last_checked_at'))
print('started_at', started, 'elapsed_h', round(el/3600,2), 'elapsed', int(el))
print('url', s.get('source_url') or r.get('url'))
"""
# write and run probe with check_room for focus names
cmd = f"""
cd /opt/douyinWEB/backend
. .venv/bin/activate
python - <<'PY'
import asyncio, json, time, urllib.request
from app.douyin import check_room
from app import db
db.init_db()
cfg=db.get_settings_map()
cookie=str(cfg.get('dy_cookie') or '')
now=time.time()
active=db.list_active_sessions()
print('db_active', len(active))
for s in active:
name=s.get('anchor_name') or ''
started=float(s.get('started_at') or 0)
el=now-started
room=db.get_room(str(s.get('room_pk') or '')) or {{}}
print('===', name)
print(' elapsed', f"{{int(el//3600)}}:{{int(el%3600//60):02d}}:{{int(el%60):02d}}", f"({{el/3600:.2f}}h)")
print(' started', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(started)), 'unix', started)
print(' room_last_status', room.get('last_status'), 'last_checked', room.get('last_checked_at'))
print(' room_id', s.get('room_id'), room.get('url'))
try:
r=asyncio.run(check_room(room.get('url') or s.get('source_url') or '', cookie=cookie))
print(' probe_ok', r.get('ok'), 'is_live', r.get('is_live'), 'status', r.get('status'), 'anchor', r.get('anchor_name'), 'err', r.get('error'))
except Exception as e:
print(' probe_fail', type(e).__name__, e)
PY
"""
print("\n--- remote probe ---", flush=True)
_, o, _ = c.exec_command(cmd, timeout=300, get_pty=True)
print(o.read().decode("utf-8", errors="replace")[-8000:], flush=True)
c.close()
if __name__ == "__main__":
asyncio.run(main())

View File

@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
import json
import paramiko
SCRIPT = r'''
import sys, asyncio
sys.path.insert(0, "/opt/douyinWEB/backend")
from app import pb_sync
async def main():
print("bootstrap", await pb_sync.ensure_collections())
await pb_sync.ensure_admin()
headers = await pb_sync._auth_headers()
print("has_token", bool(headers.get("Authorization")), "token_prefix", (headers.get("Authorization") or "")[:20])
async with await pb_sync._client() as client:
cols = await client.get("/api/collections", headers=headers)
print("collections_status", cols.status_code)
names = [i.get("name") for i in (cols.json().get("items") or [])]
print("names", names)
sess = await client.get("/api/collections/dy_sessions", headers=headers)
print("dy_sessions_status", sess.status_code)
if sess.status_code == 200:
fields = [f.get("name") for f in (sess.json().get("fields") or sess.json().get("schema") or [])]
print("fields", fields)
# sample record with cover
rec = await client.get(
"/api/collections/dy_sessions/records",
headers=headers,
params={"perPage": 3, "sort": "-started_at"},
)
print("records_status", rec.status_code)
items = (rec.json().get("items") or []) if rec.status_code == 200 else []
for it in items:
print({
"anchor": it.get("anchor_name"),
"cover_url": (it.get("cover_url") or "")[:90],
"cover_path": (it.get("cover_path") or "")[:60],
"status": it.get("status"),
})
asyncio.run(main())
'''
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
"/opt/douyinWEB/backend/.venv/bin/python - <<'PY'\n" + SCRIPT + "\nPY",
timeout=90,
)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print("ERR", err[-1500:])
c.close()

View File

@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-
"""Run on VPS: inspect focus rooms + active session consistency."""
import json
import sqlite3
import time
import urllib.request
DB = "/opt/douyinWEB/backend/data/monitor.db"
FOCUS = ["杭州光头煎饺", "阿超盖浇饭", "小易"]
def main() -> None:
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
now = time.time()
print("NOW", now)
print("=== focus rooms ===")
for name in FOCUS:
print("---", name)
rows = conn.execute(
"SELECT id, room_id, last_status, last_anchor, active_session_id, last_checked_at FROM rooms WHERE last_anchor LIKE ? OR note LIKE ?",
(f"%{name}%", f"%{name}%"),
).fetchall()
for r in rows:
print(dict(r))
sess = conn.execute(
"""
SELECT id, room_id, anchor_name, status, started_at, ended_at, end_reason, duration_seconds
FROM sessions WHERE anchor_name LIKE ? ORDER BY started_at DESC LIMIT 3
""",
(f"%{name}%",),
).fetchall()
for s in sess:
d = dict(s)
if d.get("started_at"):
d["age_h"] = round((now - float(d["started_at"])) / 3600, 2)
print("sess", d)
print("=== active vs room status ===")
for s in conn.execute(
"SELECT id, room_id, room_pk, anchor_name, started_at FROM sessions WHERE status='active' AND ended_at IS NULL"
).fetchall():
room = conn.execute(
"SELECT last_status, active_session_id FROM rooms WHERE id=?",
(s["room_pk"],),
).fetchone()
el = now - float(s["started_at"])
print(
{
"anchor": s["anchor_name"],
"room_id": s["room_id"],
"elapsed_h": round(el / 3600, 2),
"room_status": room["last_status"] if room else None,
"sid_match": ((room["active_session_id"] if room else None) == s["id"]),
}
)
for path in ("/api/monitor", "/api/health", "/api/sessions/active"):
try:
raw = urllib.request.urlopen(f"http://127.0.0.1:8014{path}", timeout=20).read().decode()
print(path, raw[:400])
except Exception as exc:
print(path, "ERR", exc)
if __name__ == "__main__":
main()