Handle YouTube Video Uploads daily quota (429) with project budget and pause-until-reset.

Add shorts_yt_quota module, Shorts UI quota banner, overview tweaks (hide upcoming opens, align events panel height), Electron desktop client scaffold, and deploy scripts; update README.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-11 02:04:44 -05:00
parent 5c45d7538a
commit 1112a4d055
79 changed files with 21881 additions and 179 deletions

View File

@ -6,6 +6,22 @@
控制台默认开启 **站点登录**(Cookie 会话);可选 `DY_API_KEY` 保护写操作。
## Windows 客户端(本地独立运行)
仓库 [`desktop/`](desktop/) 为 Electron + React 桌面端:启动时在本机拉起 **PocketBase + FastAPI + youtube-svc**,不依赖线上服务器。
```bat
scripts\start-desktop.bat
```
或:
```bat
cd desktop && npm install && npm run electron:dev
```
默认本机端口:API `8014` · PB `8090` · youtube-svc `8020` · UI `5173`。说明见 [desktop/README.md](desktop/README.md)。打包:`cd desktop && npm run pack`。
## 线上地址
| 用途 | URL |
@ -92,6 +108,7 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
- **成片**:默认 **15 秒**,设置可切换 15 / 30 / 60 / 90 秒
- **错峰上传**:录完 → `scheduled` + 抖动 `upload_at`;可「立即上传」绕过排程
- **上传**:每频道 Google OAuth 一键授权;每频道北京日配额固定 **9** 条
- **YouTube 项目配额**:官方默认 **100 次 `videos.insert`/天/项目**(太平洋日独立桶);系统保守限制 **90 次/天**(`shorts_yt_daily_upload_limit`),撞线或 HTTP **429** 时全局暂停至太平洋 0 点,待上传任务自动延后、不再无效重试
- **不复用** sh2 RTMP 转播通道
### 封面(S3)
@ -106,7 +123,7 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
| 路由 | 说明 |
|------|------|
| `/login` | 站点登录 |
| `/` | 雷达台:健康条、重点看板、今日六段、预计开播、抖音/YT 在播 ticker |
| `/` | 雷达台:健康条、重点看板、今日六段、抖音/YT 在播 ticker、可视化分析 + 最近事件 |
| `/slots` | 开播时段规律:24h→6×4h,日/周热力 |
| `/sessions` | 场次列表 + 图表;`platform` 可筛抖音 / youtube / shorts |
| `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 |
@ -131,10 +148,11 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
```
douyinWEB/
backend/app/ FastAPI(auth / monitor / cover / shorts_* / youtube_* …)
backend/app/ FastAPI(auth / monitor / cover / shorts_* / shorts_yt_quota / youtube_* …)
backend/tests/ pytest(Shorts / live / reconcile 等)
backend/data/ SQLite、封面/成片缓存
frontend/src/ Next.js App Router(含 middleware)
frontend/src/ Next.js 控制台(Web)
desktop/ Windows Electron 客户端(本机 PB+API+UI)
youtube-svc/ YouTube.js sidecar(InnerTube)
pb/ PocketBase 数据与 migrations
docs/ 专题文档(如 Shorts)
@ -181,7 +199,7 @@ cd youtube-svc && npm install
| GET | `/api/youtube/live-map` | YT 分组 + Shorts 在播地图 |
| GET | `/api/youtube/manage/channels` | OAuth 频道管理入口 |
| GET | `/api/groups/analytics` | 分组场次分析 |
| GET | `/api/shorts/status` | Shorts worker / 配额 / OAuth |
| GET | `/api/shorts/status` | Shorts worker / 北京日配额 / OAuth / **YouTube 上传配额**(`upload_quota_blocked`、`yt_upload_used/limit`) |
| GET | `/api/shorts/schedule` | 即将上传日程 |
| POST | `/api/shorts/jobs/{id}/upload-now` | 立即上传(绕过错峰) |
| POST | `/api/shorts/fill-quota` | 按配额补取样 |
@ -200,6 +218,8 @@ cd youtube-svc && npm install
## 导入与运维脚本
```bat
scripts\start.bat # Web:PB + API + Next
scripts\start-desktop.bat # Windows 客户端(Electron + 本地后端)
python scripts\import_from_11.py # 从 Desktop\11.txt 导入房间
python scripts\apply_sh2_antirisk.py # 对齐 sh2 防风控并错开检测
python scripts\sync_cookie_and_probe.py # 同步 Cookie 并抽样探测
@ -212,6 +232,7 @@ python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署
python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力
python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代
python scripts\deploy_shorts.py # Shorts 旁路增量
python scripts\deploy_yt_quota_fix.py # YouTube Video Uploads 429 配额暂停/预算
python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量
python scripts\deploy_site_auth.py # 站点登录
python scripts\deploy_youtube_live.py # 在播地图 / LIVE 角标
@ -243,6 +264,15 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程
| `shorts_sample_any_live` | 默认 `true`;取样不限标签 |
| `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 |
| `shorts_upload_spread` | 默认 `true`;错峰排程 |
| `shorts_yt_daily_upload_limit` | 默认 `90`;YouTube 项目级日上传预算(太平洋日,低于官方 100) |
| `shorts_yt_upload_blocked_until` | 运行时写入;429 或预算用尽后暂停上传至该时间戳(太平洋 0 点) |
### YouTube 上传配额(429)
- 错误示例:`Quota exceeded for quota metric 'Video Uploads' … Video Uploads per day`
- **不是程序崩溃**:Google Cloud 项目每日 Video Uploads 桶用尽(默认约 100 次/天,[官方文档](https://developers.google.com/youtube/v3/docs/videos/insert))
- 配额在 **太平洋时间 0 点** 重置;Console → YouTube Data API → Quotas 可查看用量与申请提额
- 实现:`backend/app/shorts_yt_quota.py`(预算计数、429 检测、全局暂停、任务延后);Shorts 页展示暂停横幅与 `已用/上限`
## 环境变量(`DY_` 前缀)

View File

@ -2,9 +2,9 @@
"""Optional API key gate for mutating routes (DY_API_KEY)."""
from __future__ import annotations
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.datastructures import Headers, QueryParams
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from .config import settings
@ -15,24 +15,41 @@ _PUBLIC_PATHS = {
}
class ApiKeyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
class ApiKeyMiddleware:
"""Pure ASGI middleware — avoid BaseHTTPMiddleware (deadlocks SSE/streaming)."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
required = str(settings.api_key or "").strip()
if not required:
return await call_next(request)
await self.app(scope, receive, send)
return
path = request.url.path
path = scope.get("path") or ""
method = (scope.get("method") or "GET").upper()
if path in _PUBLIC_PATHS or path.startswith("/covers/"):
return await call_next(request)
if request.method in {"GET", "HEAD", "OPTIONS"}:
return await call_next(request)
await self.app(scope, receive, send)
return
if method in {"GET", "HEAD", "OPTIONS"}:
await self.app(scope, receive, send)
return
headers = Headers(scope=scope)
qs = QueryParams((scope.get("query_string") or b"").decode("latin-1"))
provided = (
request.headers.get("X-API-Key")
or request.headers.get("x-api-key")
or request.query_params.get("api_key")
headers.get("X-API-Key")
or headers.get("x-api-key")
or qs.get("api_key")
or ""
).strip()
if provided != required:
return JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401)
return await call_next(request)
resp = JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401)
await resp(scope, receive, send)
return
await self.app(scope, receive, send)

View File

@ -11,7 +11,11 @@ BACKEND = Path(__file__).resolve().parents[1]
class Settings(BaseSettings):
api_host: str = "127.0.0.1"
api_port: int = 8000
cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000"
cors_origins: str = (
"http://localhost:3000,http://127.0.0.1:3000,"
"http://localhost:5173,http://127.0.0.1:5173,"
"http://127.0.0.1:18574,http://localhost:18574"
)
pb_url: str = "http://127.0.0.1:8090"
pb_admin_email: str = "admin@douyin.local"

View File

@ -22,9 +22,10 @@ def _force_daily_quota(value: Any = None) -> int:
def _connect() -> sqlite3.Connection:
conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False)
conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False, timeout=8.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=8000")
conn.execute("PRAGMA foreign_keys=ON")
return conn
@ -313,6 +314,10 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"shorts_oauth_client_secret": "",
"shorts_oauth_redirect_uri": "https://dylive.nomadro.com/api/shorts/oauth/callback",
"shorts_gcp_project_id": "live-473104",
"shorts_yt_daily_upload_limit": 90,
"shorts_yt_upload_blocked_until": 0,
"shorts_yt_uploads_pt_date": "",
"shorts_yt_uploads_pt_count": 0,
}
for key, value in defaults.items():
row = conn.execute("SELECT 1 FROM kv_settings WHERE key = ?", (key,)).fetchone()
@ -328,14 +333,138 @@ def get_settings_map() -> dict[str, Any]:
with _lock:
conn = _connect()
try:
rows = conn.execute("SELECT key, value FROM kv_settings").fetchall()
out: dict[str, Any] = {}
for row in rows:
try:
out[row["key"]] = json.loads(row["value"])
except json.JSONDecodeError:
out[row["key"]] = row["value"]
return out
return _settings_map_from_conn(conn)
finally:
conn.close()
def _settings_map_from_conn(conn: sqlite3.Connection) -> dict[str, Any]:
rows = conn.execute("SELECT key, value FROM kv_settings").fetchall()
out: dict[str, Any] = {}
for row in rows:
try:
out[row["key"]] = json.loads(row["value"])
except json.JSONDecodeError:
out[row["key"]] = row["value"]
return out
def monitor_status_data(*, light: bool = False) -> dict[str, Any]:
"""Settings + monitor counters in a single SQLite lock (desktop-friendly)."""
now = time.time()
with _lock:
conn = _connect()
try:
cfg = _settings_map_from_conn(conn)
rooms = int(conn.execute("SELECT COUNT(*) AS c FROM rooms").fetchone()["c"] or 0)
live = int(
conn.execute("SELECT COUNT(*) AS c FROM rooms WHERE last_status = 'live'").fetchone()["c"] or 0
)
bl = int(conn.execute("SELECT COUNT(*) AS c FROM blacklist").fetchone()["c"] or 0)
events = int(conn.execute("SELECT COUNT(*) AS c FROM events").fetchone()["c"] or 0)
counts = {"rooms": rooms, "live_rooms": live, "blacklist": bl, "events": events}
error_rooms_1h = 0
overdue: dict[str, Any] = {"count": 0, "oldest_next_check_at": None, "max_lag_sec": 0}
if not light:
cutoff = now - 3600
error_rooms_1h = int(
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()["c"]
or 0
)
grace_cutoff = now - 60
row = conn.execute(
"""
SELECT COUNT(*) AS c, MIN(next_check_at) AS oldest
FROM rooms
WHERE enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(grace_cutoff,),
).fetchone()
oldest = float(row["oldest"] or 0)
overdue = {
"count": int(row["c"] or 0),
"oldest_next_check_at": oldest or None,
"max_lag_sec": round(max(0.0, now - oldest), 1) if oldest else 0,
}
return {
"settings": cfg,
"counts": counts,
"error_rooms_1h": error_rooms_1h,
"overdue": overdue,
}
finally:
conn.close()
def youtube_monitor_status_data() -> dict[str, Any]:
"""YouTube monitor settings + group counters in one lock."""
now = time.time()
with _lock:
conn = _connect()
try:
cfg = _settings_map_from_conn(conn)
platform = "youtube"
total = int(
conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ?",
(platform,),
).fetchone()["c"]
or 0
)
enabled = int(
conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ? AND enabled = 1",
(platform,),
).fetchone()["c"]
or 0
)
live = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND last_status = 'live'
""",
(platform,),
).fetchone()["c"]
or 0
)
errors = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND last_status = 'error'
""",
(platform,),
).fetchone()["c"]
or 0
)
overdue = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(platform, now - 60),
).fetchone()["c"]
or 0
)
groups = {
"total": total,
"enabled": enabled,
"live": live,
"errors": errors,
"overdue": overdue,
}
return {"settings": cfg, "groups": groups}
finally:
conn.close()
@ -1141,8 +1270,9 @@ def dedupe_active_sessions() -> int:
conn.close()
def list_active_sessions() -> list[dict[str, Any]]:
dedupe_active_sessions()
def list_active_sessions(*, dedupe: bool = True) -> list[dict[str, Any]]:
if dedupe:
dedupe_active_sessions()
with _lock:
conn = _connect()
try:
@ -2910,8 +3040,12 @@ def room_ids_with_shorts_job_today(push_date: str) -> set[str]:
conn.close()
def pick_shorts_channel(push_date: str) -> dict[str, Any] | None:
def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
"""Pick enabled channel with most room left today (Beijing day); under daily_min first."""
from .shorts_yt_quota import project_uploads_available
if not project_uploads_available(cfg):
return None
channels = list_shorts_channels(enabled=True)
if not channels:
return None
@ -3162,10 +3296,11 @@ def claim_next_shorts_job() -> dict[str, Any] | None:
return claim_pending_shorts_record()
def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0) -> int:
"""Reset stuck uploading jobs back to scheduled (immediate retry)."""
def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0, retry_at: float = 0) -> int:
"""Reset stuck uploading jobs back to scheduled."""
cutoff = time.time() - max(60.0, float(max_age_sec))
now = time.time()
upload_at = float(retry_at or now)
with _lock:
conn = _connect()
try:
@ -3178,7 +3313,7 @@ def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0) -> int:
AND youtube_video_id = ''
AND COALESCE(NULLIF(started_at, 0), updated_at) < ?
""",
(now, now, cutoff),
(upload_at, now, cutoff),
)
conn.commit()
return int(cur.rowcount)
@ -3346,6 +3481,8 @@ def _classify_shorts_error(error: str) -> str:
return "missing_clip"
if "quota" in err or "rate" in err or "429" in err or "daily limit" in err:
return "quota"
if "video upload" in err or "video uploads" in err or "配额已用尽" in (error or ""):
return "quota"
if "ffmpeg" in err or "录制" in err or "stream" in err or "直播流" in err:
return "record"
if "上传" in err or "upload" in err or "youtube" in err or "googleapis" in err:
@ -3591,6 +3728,8 @@ def list_auto_retry_failed_jobs(*, max_attempts: int = 3, limit: int = 8) -> lis
continue
if "频道不存在" in err:
continue
if _classify_shorts_error(err) == "quota":
continue
out.append(job)
return out
finally:

View File

@ -3,11 +3,20 @@ from __future__ import annotations
import asyncio
import csv
import io
import os
import sys
import time
from contextlib import asynccontextmanager
from typing import Any, Optional
from urllib.parse import quote
# Windows Proactor + httpx/uvicorn can accept TCP then never respond (UI buttons look dead).
if sys.platform == "win32":
try:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
except Exception:
pass
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, StreamingResponse
@ -57,9 +66,9 @@ from .timeutil import stamp_beijing
@asynccontextmanager
async def lifespan(_: FastAPI):
db.init_db()
await asyncio.to_thread(db.init_db)
try:
cookie_loader.bootstrap_cookie_into_db()
await asyncio.to_thread(cookie_loader.bootstrap_cookie_into_db)
except Exception:
pass
@ -69,85 +78,149 @@ async def lifespan(_: FastAPI):
except Exception:
pass
asyncio.create_task(_pb_boot())
_desktop_light = str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"}
if not _desktop_light:
asyncio.create_task(_pb_boot())
async def _live_map_refresh_loop() -> None:
# 启动立刻探测一次,之后每 20s 强制刷新缓存
if str(os.environ.get("DY_DISABLE_LIVE_MAP_LOOP") or "").strip().lower() in {"1", "true", "yes"}:
return
try:
await asyncio.sleep(20)
except asyncio.CancelledError:
raise
while True:
try:
await youtube_live.build_live_map(force=True)
await asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30)
except asyncio.CancelledError:
raise
except Exception:
pass
try:
await asyncio.sleep(20)
await asyncio.sleep(30)
except asyncio.CancelledError:
raise
asyncio.create_task(_live_map_refresh_loop())
await monitor.start()
await yt_monitor.start()
# Idle loop when disabled — does not affect monitor
try:
await shorts_pipeline.start()
except Exception:
pass
if not _desktop_light:
asyncio.create_task(_live_map_refresh_loop())
async def _start_workers() -> None:
if _desktop_light:
return
try:
await monitor.start()
except Exception:
pass
try:
await yt_monitor.start()
except Exception:
pass
try:
await shorts_pipeline.start()
except Exception:
pass
asyncio.create_task(_start_workers())
yield
try:
await shorts_pipeline.stop()
except Exception:
pass
await yt_monitor.stop()
await monitor.stop()
try:
await yt_monitor.stop()
except Exception:
pass
try:
await monitor.stop()
except Exception:
pass
app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)
app.add_middleware(ApiKeyMiddleware)
app.add_middleware(CORSMiddleware,
allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()],
_DESKTOP_LIGHT = str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"}
# CORS first (outermost after reverse add order). Keep origins open enough for Electron/Vite.
_cors = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
if _DESKTOP_LIGHT:
for o in (
"http://127.0.0.1:5173",
"http://localhost:5173",
"http://127.0.0.1:18574",
"http://localhost:18574",
):
if o not in _cors:
_cors.append(o)
app.add_middleware(
CORSMiddleware,
allow_origins=_cors,
allow_origin_regex=r"https?://(127\.0\.0\.1|localhost)(:\d+)?" if _DESKTOP_LIGHT else None,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
app.add_middleware(SessionAuthMiddleware)
# BaseHTTPMiddleware-style stacks deadlock SSE; our pure ASGI ports are safer,
# but on desktop light skip them entirely so UI clicks never wedge on auth glue.
if not _DESKTOP_LIGHT:
app.add_middleware(ApiKeyMiddleware)
app.add_middleware(SessionAuthMiddleware)
covers_dir = settings.covers_dir
covers_dir.mkdir(parents=True, exist_ok=True)
app.mount("/covers", StaticFiles(directory=str(covers_dir)), name="covers")
async def _db(fn, /, *args, **kwargs):
"""Run sync SQLite work off the event loop (Windows desktop stays clickable)."""
return await asyncio.to_thread(fn, *args, **kwargs)
@app.get("/api/ping")
async def ping() -> dict[str, Any]:
return {"ok": True, "t": time.time(), "desktop_light": _DESKTOP_LIGHT}
@app.get("/api/health")
async def health() -> dict[str, Any]:
pb = await pb_sync.health()
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]
yt = await youtube_client.health()
return {
"""Fast health — desktop banner must never touch SQLite."""
if _DESKTOP_LIGHT:
return {"ok": True, "time": time.time(), "desktop_light": True}
out: dict[str, Any] = {
"ok": True,
"time": time.time(),
"pocketbase": pb,
"s3": s3_info,
"youtube": yt,
"youtube_monitor": yt_monitor.status(),
"monitor": monitor.status(),
"shorts": shorts_pipeline.status(),
"api_key_required": bool(str(settings.api_key or "").strip()),
"desktop_light": False,
}
try:
out["monitor"] = await asyncio.to_thread(monitor.status)
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
except Exception as exc:
out["status_error"] = str(exc)[:120]
async def _pb() -> dict[str, Any]:
try:
return await asyncio.wait_for(pb_sync.health(), timeout=0.8)
except Exception as exc:
return {"ok": False, "error": str(exc)[:120]}
async def _yt() -> dict[str, Any]:
try:
return await asyncio.wait_for(youtube_client.health(), timeout=0.8)
except Exception as exc:
return {"ok": False, "error": str(exc)[:120]}
try:
pb, yt = await asyncio.wait_for(asyncio.gather(_pb(), _yt()), timeout=1.2)
out["pocketbase"] = pb
out["youtube"] = yt
except Exception as exc:
out["pocketbase"] = {"ok": False, "error": "timeout"}
out["youtube"] = {"ok": False, "error": str(exc)[:80]}
return out
@app.get("/api/auth/status")
@ -206,34 +279,43 @@ async def auth_change_password(request: Request, body: dict[str, Any]) -> dict[s
@app.get("/api/monitor/status")
async def monitor_status() -> dict[str, Any]:
return monitor.status()
fn = monitor.status_light if _DESKTOP_LIGHT else monitor.status
try:
return await asyncio.wait_for(asyncio.to_thread(fn), timeout=12.0)
except asyncio.TimeoutError as exc:
raise HTTPException(503, "monitor status 超时") from exc
@app.post("/api/monitor/start")
async def monitor_start() -> dict[str, Any]:
db.update_settings_map({"monitor_enabled": True})
await _db(db.update_settings_map, {"monitor_enabled": True})
await monitor.start()
return monitor.status()
return await asyncio.to_thread(monitor.status_light if _DESKTOP_LIGHT else monitor.status)
@app.post("/api/monitor/stop")
async def monitor_stop() -> dict[str, Any]:
db.update_settings_map({"monitor_enabled": False})
return monitor.status()
await _db(db.update_settings_map, {"monitor_enabled": False})
return await asyncio.to_thread(monitor.status_light if _DESKTOP_LIGHT else monitor.status)
@app.post("/api/monitor/clear-risk")
async def monitor_clear_risk() -> dict[str, Any]:
monitor.clear_risk_pause()
db.add_event(kind="ops", level="info", message="手动清除风控暂停")
return monitor.status()
await _db(db.add_event, kind="ops", level="info", message="手动清除风控暂停")
return await asyncio.to_thread(monitor.status_light if _DESKTOP_LIGHT else monitor.status)
@app.get("/api/youtube-monitor/status")
async def youtube_monitor_status() -> dict[str, Any]:
status = yt_monitor.status()
yt = await youtube_client.health()
status["youtube_svc"] = yt
fn = yt_monitor.status_light if _DESKTOP_LIGHT else yt_monitor.status
status = await asyncio.to_thread(fn)
if not _DESKTOP_LIGHT:
try:
yt = await asyncio.wait_for(youtube_client.health(), timeout=1.5)
status["youtube_svc"] = yt
except Exception as exc:
status["youtube_svc"] = {"ok": False, "error": str(exc)[:120]}
return status
@ -340,11 +422,11 @@ def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
@app.get("/api/shorts/status")
async def shorts_status() -> dict[str, Any]:
st = shorts_pipeline.status()
st = await asyncio.to_thread(shorts_pipeline.status)
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri("https://dylive.nomadro.com")
st["oauth_scopes"] = shorts_oauth.requested_scopes()
cfg = db.get_settings_map()
cfg = await _db(db.get_settings_map)
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
return st
@ -681,13 +763,13 @@ async def monitor_check_one(room_pk: str) -> dict[str, Any]:
@app.get("/api/settings")
async def get_settings() -> dict[str, Any]:
return db.get_settings_map()
return await asyncio.to_thread(db.get_settings_map)
@app.patch("/api/settings")
async def patch_settings(body: SettingsUpdate) -> dict[str, Any]:
patch = body.model_dump(exclude_none=True)
return db.update_settings_map(patch)
return await asyncio.to_thread(db.update_settings_map, patch)
@app.post("/api/settings/sync-cookie")
@ -713,7 +795,7 @@ async def rooms_list(
limit: int = Query(500, ge=1, le=2000),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_rooms(q=q, enabled=enabled, status=status, tag=tag, limit=limit, offset=offset)
return await _db(db.list_rooms, q=q, enabled=enabled, status=status, tag=tag, limit=limit, offset=offset)
@app.get("/api/rooms/tags")
@ -1220,7 +1302,7 @@ async def events_list(
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_events(kind=kind, q=q, platform=platform, limit=limit, offset=offset)
return await _db(db.list_events, kind=kind, q=q, platform=platform, limit=limit, offset=offset)
@app.get("/api/events/stream")
@ -1293,7 +1375,7 @@ async def events_export(
@app.get("/api/sessions/active")
async def sessions_active() -> dict[str, Any]:
items = db.list_active_sessions()
items = await _db(db.list_active_sessions, dedupe=not _DESKTOP_LIGHT)
return {"sessions": items, "total": len(items)}
@ -1352,7 +1434,7 @@ 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)
items = await _db(db.list_upcoming_opens, limit=limit, priority_only=priority_only)
return {"items": items, "total": len(items)}
@ -1426,7 +1508,8 @@ async def sessions_list(
limit: int = Query(50, ge=1, le=2000),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_sessions(
return await _db(
db.list_sessions,
q=q,
date_from=date_from,
date_to=date_to,
@ -1448,7 +1531,8 @@ async def sessions_stats(
platform: str = "",
top_anchors: int = Query(25, ge=1, le=50),
) -> dict[str, Any]:
return summarize_sessions(
return await _db(
summarize_sessions,
q=q,
date_from=date_from,
date_to=date_to,

View File

@ -34,9 +34,10 @@ class MonitorService:
self.risk_paused_until = 0.0
self.last_error = ""
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
counts = db.counts()
def status(self, *, light: bool = False) -> dict[str, Any]:
data = db.monitor_status_data(light=light)
cfg = data["settings"]
counts = data["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)
@ -53,8 +54,8 @@ class MonitorService:
"last_check_at": self.last_check_at,
"quiet_hours_active": quiet,
"quiet_hours_priority_only": bool(quiet and cfg.get("quiet_hours_allow_priority", True)),
"error_rooms_1h": db.count_recent_error_rooms(within_sec=3600),
"overdue": db.overdue_rooms_stats(grace_sec=60),
"error_rooms_1h": data["error_rooms_1h"],
"overdue": data["overdue"],
"cookie": {
"has": bool(cookie),
"length": len(cookie),
@ -79,8 +80,12 @@ class MonitorService:
"quiet_hours_end": int(cfg.get("quiet_hours_end", 7) or 7),
"quiet_hours_allow_priority": bool(cfg.get("quiet_hours_allow_priority", True)),
},
**({"desktop_light": True} if light else {}),
}
def status_light(self) -> dict[str, Any]:
return self.status(light=True)
async def start(self) -> None:
if self.running:
return

View File

@ -10,9 +10,9 @@ import secrets
import time
from typing import Any, Optional
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.types import ASGIApp, Receive, Scope, Send
from .config import settings
@ -25,7 +25,9 @@ _PUBLIC_API_PREFIXES = (
"/api/auth/status",
)
_PUBLIC_API_EXACT = {
"/api/health",
"/api/shorts/oauth/callback",
"/api/events/stream",
}
@ -137,24 +139,42 @@ def _request_secure(request: Request) -> bool:
return proto == "https"
class SessionAuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if not settings.auth_enabled:
return await call_next(request)
class SessionAuthMiddleware:
"""Pure ASGI middleware — avoid BaseHTTPMiddleware (deadlocks SSE/streaming)."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
if not settings.auth_enabled:
await self.app(scope, receive, send)
return
request = Request(scope, receive=receive)
path = request.url.path
if path.startswith("/covers/"):
if session_user_from_request(request):
return await call_next(request)
return JSONResponse({"detail": "未登录"}, status_code=401)
await self.app(scope, receive, send)
return
resp = JSONResponse({"detail": "未登录"}, status_code=401)
await resp(scope, receive, send)
return
if not path.startswith("/api/"):
return await call_next(request)
await self.app(scope, receive, send)
return
if path in _PUBLIC_API_EXACT or any(path.startswith(p) for p in _PUBLIC_API_PREFIXES):
return await call_next(request)
await self.app(scope, receive, send)
return
if session_user_from_request(request):
return await call_next(request)
await self.app(scope, receive, send)
return
return JSONResponse({"detail": "未登录,请先登录"}, status_code=401)
resp = JSONResponse({"detail": "未登录,请先登录"}, status_code=401)
await resp(scope, receive, send)

View File

@ -16,7 +16,15 @@ from typing import Any, Optional
from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_upload import upload_shorts_mp4
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_yt_quota import (
detect_and_block_from_recent_errors,
pause_uploads_until_reset,
project_uploads_available,
reserve_yt_upload_slot,
yt_upload_budget,
)
from .timeutil import format_beijing, next_youtube_quota_reset_ts
from .timeutil import push_date_from_ts
@ -66,7 +74,7 @@ def _enqueue_job(
if used < daily_max:
channel = ch
if not channel:
channel = db.pick_shorts_channel(day)
channel = db.pick_shorts_channel(day, settings)
if not channel:
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
@ -127,7 +135,7 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
if not settings.get("shorts_live_sample", True):
return 0
day = push_date_from_ts(time.time())
if not db.pick_shorts_channel(day):
if not db.pick_shorts_channel(day, settings):
return 0
batch = max(1, min(int(settings.get("shorts_live_sample_batch") or 1), 5))
any_live = settings.get("shorts_sample_any_live", True)
@ -154,7 +162,7 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
enqueued += 1
used.add(str(room.get("room_id") or ""))
# stop if channel full after this assign
if not db.pick_shorts_channel(day):
if not db.pick_shorts_channel(day, settings):
break
return enqueued
except Exception:
@ -167,11 +175,13 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return 0
if not project_uploads_available(settings):
return 0
day = push_date_from_ts(time.time())
gap_total = db.shorts_total_quota_gap(day)
if gap_total <= 0:
return 0
if not db.pick_shorts_channel(day):
if not db.pick_shorts_channel(day, settings):
return 0
from .timeutil import beijing_day_bounds
@ -207,7 +217,7 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
for room in candidates:
if enqueued >= base_batch:
break
if not db.pick_shorts_channel(day):
if not db.pick_shorts_channel(day, settings):
break
sid = str(room.get("active_session_id") or "")
session = db.get_session(sid) if sid else None
@ -430,6 +440,23 @@ class ShortsPipeline:
)
except Exception:
pass
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
try:
detected, detected_until = detect_and_block_from_recent_errors(cfg)
if detected:
quota_blocked = True
quota_until = max(quota_until, detected_until)
except Exception:
pass
if not quota_blocked and is_upload_quota_error(self.last_error):
quota_until = next_youtube_quota_reset_ts()
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": quota_until})
except Exception:
pass
quota_blocked = True
last_error = quota_error_message() if quota_blocked else self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg)
return {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
@ -443,7 +470,12 @@ class ShortsPipeline:
"auto_retried": self.auto_retried,
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
"quota_gap": db.shorts_total_quota_gap(),
"last_error": self.last_error,
"upload_quota_blocked": quota_blocked,
"upload_quota_blocked_until": quota_until,
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"last_error": last_error,
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
"live_sample": bool(cfg.get("shorts_live_sample", True)),
"sample_any_live": bool(cfg.get("shorts_sample_any_live", True)),
@ -474,6 +506,10 @@ class ShortsPipeline:
async def start(self) -> None:
if self._task and not self._task.done():
return
try:
detect_and_block_from_recent_errors()
except Exception:
pass
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="shorts-pipeline")
@ -527,7 +563,12 @@ class ShortsPipeline:
asyncio.create_task(self._probe_oauth(cfg))
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
if cfg.get("shorts_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
quota_blocked_loop, _ = self._upload_quota_blocked(cfg)
if (
not quota_blocked_loop
and cfg.get("shorts_auto_retry_failed", True)
and (time.time() - self._last_auto_retry_at) >= retry_interval
):
self._last_auto_retry_at = time.time()
try:
n = self._auto_retry_failed(cfg)
@ -543,7 +584,11 @@ class ShortsPipeline:
pass
try:
n = db.reclaim_stale_shorts_uploads(max_age_sec=180)
retry_at = 0.0
quota_blocked_loop, quota_until_loop = self._upload_quota_blocked(cfg)
if quota_blocked_loop:
retry_at = quota_until_loop + 300
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, retry_at=retry_at)
if n:
self.last_error = ""
except Exception:
@ -565,9 +610,13 @@ class ShortsPipeline:
record_max = self._record_max(cfg)
upload_max = self._upload_max(cfg)
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
if not quota_blocked and not project_uploads_available(cfg):
quota_until = pause_uploads_until_reset(cfg)
quota_blocked = True
job: dict[str, Any] | None = None
runner: str = ""
if self._active_uploads < upload_max:
if not quota_blocked and self._active_uploads < upload_max:
job = db.claim_due_shorts_upload()
if job:
runner = "upload"
@ -595,6 +644,8 @@ class ShortsPipeline:
await self._process(job, cfg)
self.processed += 1
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
@ -698,6 +749,48 @@ class ShortsPipeline:
except Exception:
pass
def _upload_quota_blocked(self, cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
settings = cfg if cfg is not None else db.get_settings_map()
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
now = time.time()
if until <= now:
if until > 0:
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": 0})
except Exception:
pass
return False, 0.0
return True, until
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
until = pause_uploads_until_reset(reason=quota_error_message())
friendly = quota_error_message()
jid = str(job.get("id") or "")
if jid:
db.update_shorts_job(
jid,
status="scheduled",
error=friendly,
upload_at=until + 300,
finished_at=0,
)
self.last_error = friendly
self._emit_shorts_event(
kind="shorts_quota",
level="warn",
message=f"Shorts 上传配额用尽,已暂停至 {format_beijing(until)}(太平洋 0 点重置)",
job=job,
extra={"error": raw_error[:200], "blocked_until": until},
)
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
"""Return True if handled (quota deferral)."""
msg = str(exc)
if is_upload_quota_error(msg):
self._pause_uploads_for_quota(job, msg)
return True
return False
def _mark_failed(self, job: dict[str, Any], error: str) -> None:
jid = str(job["id"])
err = str(error or "失败")[:300]
@ -766,6 +859,10 @@ class ShortsPipeline:
raise ValueError(f"状态 {st} 不可手动上传")
cfg = db.get_settings_map()
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
if quota_blocked:
raise ValueError(f"{quota_error_message()} 预计 {format_beijing(quota_until)} 恢复。")
upload_max = self._upload_max(cfg)
if st == "uploading":
waited = await self._wait_upload_done(job_id, timeout_sec=120)
@ -816,6 +913,8 @@ class ShortsPipeline:
done = waited
return done
except Exception as exc:
if self._handle_upload_error(claimed, exc):
raise ValueError(quota_error_message()) from exc
if "成片文件不存在" in str(exc):
refreshed = db.get_shorts_job(job_id) or claimed
if str(refreshed.get("youtube_video_id") or "").strip():
@ -833,6 +932,8 @@ class ShortsPipeline:
await self._do_upload(job, cfg)
self.processed += 1
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
@ -860,6 +961,8 @@ class ShortsPipeline:
if status == "uploading":
await self._do_upload(job, cfg)
except Exception as exc:
if self._handle_upload_error(job, exc):
return
if "成片文件不存在" in str(exc):
if str(job.get("youtube_video_id") or "").strip():
db.update_shorts_job(
@ -995,6 +1098,9 @@ class ShortsPipeline:
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
if "#Shorts" not in title and "#shorts" not in title.lower():
title = f"{title} #Shorts"
if not reserve_yt_upload_slot(cfg):
pause_uploads_until_reset(cfg)
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()}")
result = await upload_shorts_mp4(
file_path=clip,
title=title,

View File

@ -8,6 +8,31 @@ from typing import Any
import httpx
def is_upload_quota_error(msg: str) -> bool:
"""Detect YouTube Data API daily Video Uploads quota (HTTP 429)."""
raw = msg or ""
low = raw.lower()
if not low.strip():
return False
if "quota_exceeded" in low or "配额已用尽" in raw:
return True
if "quota exceeded" in low and ("video upload" in low or "uploads per day" in low):
return True
if "429" in low and ("video upload" in low or "uploads per day" in low):
return True
if '"code": 429' in low or 'code": 429' in low:
if "upload" in low or "video" in low:
return True
return False
def quota_error_message() -> str:
return (
"YouTube 每日 Video Uploads 配额已用尽(429)。"
"上传已自动暂停,待太平洋时间 0 点配额重置后会继续。"
)
async def refresh_access_token(*, client_id: str, client_secret: str, refresh_token: str) -> str:
if not (client_id and client_secret and refresh_token):
raise ValueError("缺少 OAuth client_id / client_secret / refresh_token")
@ -76,7 +101,10 @@ async def upload_shorts_mp4(
)
upload_url = init.headers.get("location") or init.headers.get("Location")
if init.status_code >= 400 or not upload_url:
raise ValueError(f"初始化上传失败: {init.text[:400]}")
body = init.text[:800]
if init.status_code == 429 or is_upload_quota_error(body):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})")
raise ValueError(f"初始化上传失败: {body[:400]}")
put = await client.put(
upload_url,
headers={
@ -88,7 +116,10 @@ async def upload_shorts_mp4(
)
data = put.json() if put.content else {}
if put.status_code >= 400 or not data.get("id"):
raise ValueError(f"上传失败: {data.get('error') or put.text[:400]}")
err_text = str(data.get("error") or put.text[:800])
if put.status_code == 429 or is_upload_quota_error(err_text):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})")
raise ValueError(f"上传失败: {err_text[:400]}")
vid = str(data["id"])
return {
"ok": True,

View File

@ -0,0 +1,184 @@
# -*- coding: utf-8 -*-
"""YouTube Data API project-level daily upload budget (Video Uploads bucket, PT day)."""
from __future__ import annotations
import time
from typing import Any
from . import db
from .shorts_upload import is_upload_quota_error, quota_error_message
from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts
YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90
def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int:
settings = cfg if cfg is not None else db.get_settings_map()
return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT))
def _count_uploads_from_db_pt_day(day: str = "") -> int:
"""Best-effort count of upload API uses in the current Pacific day."""
pt_day = day or pacific_day_from_ts(time.time())
start, end = pacific_day_bounds(pt_day)
with db._lock:
conn = db._connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE youtube_video_id != ''
AND finished_at >= ? AND finished_at < ?
""",
(start, end),
).fetchone()
uploaded = int(row["c"] if row else 0)
row2 = conn.execute(
"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE status = 'uploading'
AND clip_path != ''
AND youtube_video_id = ''
""",
).fetchone()
in_flight = int(row2["c"] if row2 else 0)
row3 = conn.execute(
"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE status IN ('failed', 'scheduled')
AND error LIKE '%429%'
AND updated_at >= ? AND updated_at < ?
""",
(start, end),
).fetchone()
quota_fails = int(row3["c"] if row3 else 0)
return uploaded + in_flight + quota_fails
finally:
conn.close()
def _sync_counter(cfg: dict[str, Any]) -> tuple[str, int]:
pt_day = pacific_day_from_ts(time.time())
stored_day = str(cfg.get("shorts_yt_uploads_pt_date") or "")
stored_count = int(cfg.get("shorts_yt_uploads_pt_count") or 0)
if stored_day != pt_day:
db_count = _count_uploads_from_db_pt_day(pt_day)
stored_count = max(stored_count, db_count) if stored_day else db_count
try:
db.update_settings_map(
{
"shorts_yt_uploads_pt_date": pt_day,
"shorts_yt_uploads_pt_count": stored_count,
}
)
except Exception:
pass
cfg["shorts_yt_uploads_pt_date"] = pt_day
cfg["shorts_yt_uploads_pt_count"] = stored_count
return pt_day, stored_count
def yt_upload_budget(cfg: dict[str, Any] | None = None) -> tuple[int, int, int]:
"""Return (limit, used, remaining) for the current Pacific quota day."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
limit = yt_daily_limit(settings)
_, used = _sync_counter(settings)
remaining = max(0, limit - used)
return limit, used, remaining
def reserve_yt_upload_slot(cfg: dict[str, Any] | None = None) -> bool:
"""Reserve one upload slot before calling YouTube API. Returns False if budget exhausted."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
limit, used, remaining = yt_upload_budget(settings)
if remaining <= 0:
return False
pt_day = pacific_day_from_ts(time.time())
new_count = used + 1
try:
db.update_settings_map(
{
"shorts_yt_uploads_pt_date": pt_day,
"shorts_yt_uploads_pt_count": new_count,
}
)
except Exception:
pass
return True
def project_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
return yt_upload_budget(cfg)[2] > 0
def pause_uploads_until_reset(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float:
"""Block uploads until Pacific midnight and defer pending jobs."""
until = next_youtube_quota_reset_ts()
patch: dict[str, Any] = {"shorts_yt_upload_blocked_until": until}
try:
db.update_settings_map(patch)
except Exception:
pass
defer_all_shorts_uploads(until, reason=reason or quota_error_message())
return until
def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
"""Reschedule all pending/uploading shorts jobs to after until_ts."""
now = time.time()
retry_at = max(until_ts, now) + 300
msg = (reason or quota_error_message())[:400]
with db._lock:
conn = db._connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET status = 'scheduled',
upload_at = ?,
error = ?,
finished_at = 0,
updated_at = ?
WHERE status IN ('scheduled', 'uploading', 'recorded')
AND clip_path != ''
AND youtube_video_id = ''
""",
(retry_at, msg, now),
)
conn.commit()
return int(cur.rowcount)
finally:
conn.close()
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
"""If recent jobs/errors show quota exhaustion, activate global upload pause."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
if until > time.time():
return True, until
limit, used, _ = yt_upload_budget(settings)
if used >= limit:
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
with db._lock:
conn = db._connect()
try:
rows = conn.execute(
"""
SELECT error FROM shorts_jobs
WHERE error != ''
ORDER BY updated_at DESC
LIMIT 30
""",
).fetchall()
finally:
conn.close()
for row in rows:
err = str(row["error"] or "")
if is_upload_quota_error(err):
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
return False, 0.0

View File

@ -2,11 +2,13 @@
from __future__ import annotations
import time
from datetime import datetime, timedelta, timezone
from typing import Optional
from zoneinfo import ZoneInfo
BJ = ZoneInfo("Asia/Shanghai")
PT = ZoneInfo("America/Los_Angeles")
UTC = timezone.utc
@ -57,3 +59,25 @@ def beijing_day_bounds(push_date: str = "") -> tuple[float, float]:
start = datetime(y, m, d, 0, 0, 0, tzinfo=BJ)
end = start + timedelta(days=1)
return start.timestamp(), end.timestamp()
def next_youtube_quota_reset_ts() -> float:
"""YouTube Data API daily upload quotas reset at midnight US Pacific."""
now = datetime.now(PT)
midnight_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
midnight_next = midnight_today + timedelta(days=1)
return midnight_next.timestamp()
def pacific_day_from_ts(ts: float | int | None = None) -> str:
"""US Pacific calendar date YYYY-MM-DD (YouTube quota day)."""
return datetime.fromtimestamp(float(ts if ts is not None else time.time()), PT).strftime("%Y-%m-%d")
def pacific_day_bounds(day: str = "") -> tuple[float, float]:
"""Pacific calendar day [start, end) as Unix timestamps."""
d = day or pacific_day_from_ts(time.time())
y, m, dd = [int(x) for x in d.split("-")]
start = datetime(y, m, dd, 0, 0, 0, tzinfo=PT)
end = start + timedelta(days=1)
return start.timestamp(), end.timestamp()

View File

@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import os
import time
from typing import Any, Optional
@ -187,19 +188,59 @@ async def _oauth_live_for_shorts(channel_pk: str, youtube_channel_id: str) -> Op
)
_REFRESH_TASK: Optional[asyncio.Task] = None
def _empty_live_map(*, now: float, refreshing: bool = False) -> dict[str, Any]:
return {
"ok": True,
"checked_at": int(now),
"live_count": 0,
"source": "none",
"entries": {},
"groups_total": 0,
"shorts_total": 0,
"poll_sec": 20,
"cache_ttl_sec": _CACHE_TTL_SEC,
"refreshing": refreshing,
}
def _schedule_live_map_refresh() -> None:
"""Kick a background rebuild; never block HTTP handlers on youtube-svc."""
global _REFRESH_TASK
if str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"}:
# Desktop UI must stay clickable; live-map refresh is opt-in via force loop elsewhere
return
lock = _refresh_lock()
if lock.locked():
return
task = _REFRESH_TASK
if task is not None and not task.done():
return
async def _run() -> None:
try:
async with _refresh_lock():
await _build_live_map_unlocked(now=time.time())
except Exception:
pass
_REFRESH_TASK = asyncio.create_task(_run())
async def build_live_map(*, force: bool = False) -> dict[str, Any]:
global _LAST_OAUTH_AT
now = time.time()
cached = _CACHE.get("payload")
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
fresh = bool(cached) and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC
if cached and (fresh or not force):
if force or not fresh:
_schedule_live_map_refresh()
return cached
async with _refresh_lock():
now = time.time()
cached = _CACHE.get("payload")
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
return cached
return await _build_live_map_unlocked(now=now)
# No cache yet: return empty immediately and refresh in background
_schedule_live_map_refresh()
return _empty_live_map(now=now, refreshing=True)
async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:

View File

@ -36,9 +36,14 @@ class YouTubeMonitorService:
def running(self) -> bool:
return self._task is not None and not self._task.done()
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
stats = db.channel_groups_live_stats(platform="youtube")
def status(self, *, light: bool = False) -> dict[str, Any]:
if light:
data = db.youtube_monitor_status_data()
cfg = data["settings"]
stats = data["groups"]
else:
cfg = db.get_settings_map()
stats = db.channel_groups_live_stats(platform="youtube")
quiet = self._in_quiet_hours(cfg)
return {
"running": self.running,
@ -55,8 +60,12 @@ class YouTubeMonitorService:
"yt_request_gap_sec": float(cfg.get("yt_request_gap_sec", 2) or 2),
"quiet_hours_enabled": bool(cfg.get("quiet_hours_enabled", False)),
},
**({"desktop_light": True} if light else {}),
}
def status_light(self) -> dict[str, Any]:
return self.status(light=True)
async def start(self) -> None:
if self.running:
return

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
"""Desktop API entry — set Windows Selector loop BEFORE uvicorn creates the loop."""
from __future__ import annotations
import asyncio
import os
import sys
def main() -> None:
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
import uvicorn
host = os.environ.get("DY_API_HOST", "127.0.0.1")
port = int(os.environ.get("DY_API_PORT", "8014"))
uvicorn.run(
"app.main:app",
host=host,
port=port,
loop="asyncio",
http="h11",
log_level="info",
)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from app.shorts_upload import is_upload_quota_error
from app.shorts_yt_quota import (
YT_DAILY_UPLOAD_LIMIT_DEFAULT,
pause_uploads_until_reset,
reserve_yt_upload_slot,
yt_upload_budget,
)
from app.timeutil import pacific_day_from_ts
def test_is_upload_quota_error_matches_429():
err = 'Quota exceeded for quota metric "Video Uploads" and limit "Video Uploads per day"'
assert is_upload_quota_error(err)
def test_yt_upload_budget_and_reserve(temp_db):
cfg = temp_db.get_settings_map()
limit, used, remaining = yt_upload_budget(cfg)
assert limit == YT_DAILY_UPLOAD_LIMIT_DEFAULT
assert used >= 0
assert remaining == limit - used
assert reserve_yt_upload_slot(cfg) is True
_, used2, remaining2 = yt_upload_budget(temp_db.get_settings_map())
assert used2 == used + 1
assert remaining2 == remaining - 1
def test_pause_uploads_defers_jobs(temp_db):
ch = temp_db.create_shorts_channel(name="Y", enabled=True)
job = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"])
temp_db.update_shorts_job(job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=time.time())
until = pause_uploads_until_reset(temp_db.get_settings_map(), reason="test pause")
refreshed = temp_db.get_shorts_job(job["id"])
assert refreshed is not None
assert refreshed["status"] == "scheduled"
assert float(refreshed["upload_at"]) >= until
cfg = temp_db.get_settings_map()
assert float(cfg.get("shorts_yt_upload_blocked_until") or 0) >= until
def test_pacific_day_from_ts():
day = pacific_day_from_ts(time.time())
assert len(day) == 10 and day[4] == "-"

6
desktop/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
node_modules/
dist/
dist-electron/
release/
*.log
.DS_Store

60
desktop/README.md Normal file
View File

@ -0,0 +1,60 @@
# Windows 桌面客户端(Electron + React)
本目录是 **独立 Windows 客户端**:启动时在本机拉起 **PocketBase + FastAPI + youtube-svc**,UI 连本地 API,**不依赖** `dylive.nomadro.com`。
## 要求
- Windows 10/11 x64
- Node.js 20+
- Python 3.10+(已 `pip install -r ../backend/requirements.txt`)
- 仓库内 `pb/pocketbase.exe`
- (可选)`ffmpeg` 在 PATH,用于封面/Shorts
## 开发
```bat
cd desktop
npm install
npm run electron:dev
```
流程:
1. Electron main 启动本地 PB `:8090`、API `:8014`、youtube-svc `:8020`
2. Vite `:5173`(代理 `/api`、`/covers` → API)
3. 打开桌面窗口加载 UI
仅预览 UI(需你已手动起后端):
```bat
npm run dev
```
## 打包
```bat
npm run pack
```
产物在 `desktop/release/`(NSIS 安装包 + portable)。打包会把 `backend/`、`pb/`、`youtube-svc/` 打进 `extraResources`(不含 `pocketbase.exe` 时需自行放入 runtime/pb)。
## 端口
| 服务 | 默认 |
|------|------|
| FastAPI | `127.0.0.1:8014` |
| PocketBase | `127.0.0.1:8090` |
| youtube-svc | `127.0.0.1:8020` |
| Vite / UI | `127.0.0.1:5173`(开发)或 `:18574`(打包) |
## 客户端能力
- 系统托盘(关闭窗口可托盘驻留)
- 开播/风控等 **Windows 原生通知**
- 单实例锁;外链用系统浏览器
- 设置页「Windows 客户端 · 本地后端」:服务状态、日志目录、诊断复制
- 窗口失焦时降低轮询频率(SSE 仍保持以便通知)
## 登录
与 Web 相同:本地 API 的站点登录(默认见后端 `DY_ADMIN_*` / 设置页改密)。

284
desktop/electron/main.ts Normal file
View File

@ -0,0 +1,284 @@
import {
app,
BrowserWindow,
ipcMain,
Menu,
nativeImage,
Notification,
screen,
shell,
Tray,
} from "electron";
import path from "node:path";
import { getConfig, setConfig } from "./store";
import { listServicePids, startLocalServices, stopLocalServices } from "./services";
import { startUiServer } from "./uiServer";
let mainWindow: BrowserWindow | null = null;
let tray: Tray | null = null;
let serviceStatus: Record<string, string> = {};
let quitting = false;
let uiClose: (() => void) | null = null;
let uiUrl = "http://127.0.0.1:5173";
const isDev = !app.isPackaged;
const openDevtools = process.env.ELECTRON_OPEN_DEVTOOLS === "1";
function trayIcon(): Electron.NativeImage {
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAPElEQVQ4T2NkYGD4z0ABYBzVMKoBBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAD+AQX5Yp1mAAAAAElFTkSuQmCC",
"base64",
);
const img = nativeImage.createFromBuffer(png);
return img.isEmpty() ? nativeImage.createFromDataURL("data:image/png;base64," + png.toString("base64")) : img;
}
function createTray() {
if (tray) return;
try {
tray = new Tray(trayIcon());
} catch (err) {
console.error("tray create failed", err);
return;
}
tray.setToolTip("抖音直播监控");
tray.setContextMenu(
Menu.buildFromTemplate([
{
label: "打开主窗口",
click: () => {
mainWindow?.show();
mainWindow?.focus();
},
},
{
label: "本地服务状态",
click: () => {
const lines = Object.entries(serviceStatus)
.map(([k, v]) => `${k}: ${v}`)
.join("\n");
if (Notification.isSupported()) {
new Notification({ title: "本地服务", body: lines || "未知" }).show();
}
},
},
{ type: "separator" },
{
label: "退出",
click: () => {
quitting = true;
app.quit();
},
},
]),
);
tray.on("double-click", () => {
mainWindow?.show();
mainWindow?.focus();
});
}
function resolveWindowBounds(): { width: number; height: number; x?: number; y?: number } {
const cfg = getConfig();
const saved = cfg.windowBounds;
const width = Math.max(1100, Number(saved?.width) || 1280);
const height = Math.max(700, Number(saved?.height) || 800);
const display = screen.getPrimaryDisplay().workArea;
const x = typeof saved?.x === "number" ? saved.x : undefined;
const y = typeof saved?.y === "number" ? saved.y : undefined;
if (
x == null ||
y == null ||
x + 80 < display.x ||
y + 80 < display.y ||
x > display.x + display.width - 80 ||
y > display.y + display.height - 80
) {
return {
width: Math.min(width, display.width),
height: Math.min(height, display.height),
x: display.x + Math.max(0, Math.floor((display.width - Math.min(width, display.width)) / 2)),
y: display.y + Math.max(0, Math.floor((display.height - Math.min(height, display.height)) / 2)),
};
}
return { width, height, x, y };
}
const SPLASH = `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html>
<html><head><meta charset="utf-8"/><title>抖音直播监控</title>
<style>
body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;
font-family:Segoe UI,sans-serif;color:#edf3ff;background:#071018}
.box{text-align:center}
.h{font-size:22px;font-weight:700;margin:0 0 8px}
.p{color:#93a4bd;font-size:13px;margin:0}
.spin{width:28px;height:28px;margin:18px auto 0;border:2px solid #2dd4bf55;border-top-color:#2dd4bf;
border-radius:50%;animation:r .7s linear infinite}
@keyframes r{to{transform:rotate(360deg)}}
</style></head><body><div class="box"><p class="h">直播监控中心</p>
<p class="p">正在启动本地服务…</p><div class="spin"></div></div></body></html>`)}`;
function createWindow() {
const bounds = resolveWindowBounds();
mainWindow = new BrowserWindow({
width: bounds.width,
height: bounds.height,
x: bounds.x,
y: bounds.y,
minWidth: 1000,
minHeight: 640,
show: true,
backgroundColor: "#071018",
title: "抖音直播监控",
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
backgroundThrottling: true,
spellcheck: false,
},
});
mainWindow.webContents.on("did-fail-load", (_e, code, desc, url) => {
console.error("did-fail-load", code, desc, url);
});
mainWindow.webContents.on("did-finish-load", () => {
console.log("did-finish-load", mainWindow?.webContents.getURL());
});
mainWindow.on("close", (e) => {
if (!quitting && getConfig().minimizeToTray) {
e.preventDefault();
mainWindow?.hide();
}
});
mainWindow.on("resize", () => persistBounds());
mainWindow.on("move", () => persistBounds());
mainWindow.on("focus", () => mainWindow?.webContents.send("desktop:focus", true));
mainWindow.on("blur", () => mainWindow?.webContents.send("desktop:focus", false));
// Instant splash — do not wait for backends
void mainWindow.loadURL(SPLASH);
if (openDevtools) {
mainWindow.webContents.openDevTools({ mode: "detach" });
}
}
async function loadAppUi() {
if (!mainWindow || mainWindow.isDestroyed()) return;
void mainWindow.loadURL(uiUrl);
}
function persistBounds() {
if (!mainWindow) return;
const b = mainWindow.getBounds();
setConfig({ windowBounds: b });
}
function registerIpc() {
ipcMain.handle("desktop:getConfig", () => getConfig());
ipcMain.handle("desktop:setConfig", (_e, patch) => setConfig(patch || {}));
ipcMain.handle("desktop:getServiceStatus", () => ({
...serviceStatus,
pids: listServicePids(),
}));
ipcMain.handle("desktop:notify", (_e, payload: { title: string; body: string }) => {
if (!getConfig().nativeNotify) return;
if (!Notification.isSupported()) return;
new Notification({ title: payload.title, body: payload.body }).show();
});
ipcMain.handle("desktop:openExternal", (_e, url: string) => {
if (typeof url === "string" && /^https?:\/\//i.test(url)) {
void shell.openExternal(url);
}
});
ipcMain.handle("desktop:openLogs", () => {
void shell.openPath(app.getPath("logs"));
});
ipcMain.handle("desktop:getDiagnostics", () => {
const cfg = getConfig();
return {
version: app.getVersion(),
electron: process.versions.electron,
chrome: process.versions.chrome,
platform: process.platform,
apiBase: cfg.apiBase,
services: serviceStatus,
packaged: app.isPackaged,
};
});
ipcMain.handle("desktop:minimizeToTray", () => {
mainWindow?.hide();
});
}
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
// Must be before ready
app.commandLine.appendSwitch("disable-features", "CalculateNativeWinOcclusion");
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
}
});
app.whenReady().then(() => {
registerIpc();
createTray();
createWindow(); // instant splash
const cfg = getConfig();
void (async () => {
try {
const started = await startLocalServices({
apiPort: cfg.apiPort,
pbPort: cfg.pbPort,
ytPort: cfg.ytPort,
});
serviceStatus = started.status;
setConfig({ apiBase: started.apiBase });
if (isDev) {
uiUrl = "http://127.0.0.1:5173";
} else {
const ui = await startUiServer({
distDir: path.join(__dirname, "..", "dist"),
apiBase: started.apiBase,
port: 18574,
});
uiClose = ui.close;
uiUrl = ui.url;
}
} catch (err) {
serviceStatus = { boot: String((err as Error).message) };
console.error("Failed to start local services", err);
}
await loadAppUi();
})();
});
app.on("before-quit", () => {
quitting = true;
try {
uiClose?.();
} catch {
/* ignore */
}
stopLocalServices();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
quitting = true;
app.quit();
}
});
}

View File

@ -0,0 +1,31 @@
import { contextBridge, ipcRenderer } from "electron";
export type DesktopBridge = {
getConfig: () => Promise<Record<string, unknown>>;
setConfig: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
getServiceStatus: () => Promise<Record<string, unknown>>;
notify: (title: string, body: string) => Promise<void>;
openExternal: (url: string) => Promise<void>;
openLogs: () => Promise<void>;
getDiagnostics: () => Promise<Record<string, unknown>>;
onWindowFocus: (cb: (focused: boolean) => void) => () => void;
minimizeToTray: () => Promise<void>;
};
const bridge: DesktopBridge = {
getConfig: () => ipcRenderer.invoke("desktop:getConfig"),
setConfig: (patch) => ipcRenderer.invoke("desktop:setConfig", patch),
getServiceStatus: () => ipcRenderer.invoke("desktop:getServiceStatus"),
notify: (title, body) => ipcRenderer.invoke("desktop:notify", { title, body }),
openExternal: (url) => ipcRenderer.invoke("desktop:openExternal", url),
openLogs: () => ipcRenderer.invoke("desktop:openLogs"),
getDiagnostics: () => ipcRenderer.invoke("desktop:getDiagnostics"),
onWindowFocus: (cb) => {
const handler = (_: Electron.IpcRendererEvent, focused: boolean) => cb(focused);
ipcRenderer.on("desktop:focus", handler);
return () => ipcRenderer.removeListener("desktop:focus", handler);
},
minimizeToTray: () => ipcRenderer.invoke("desktop:minimizeToTray"),
};
contextBridge.exposeInMainWorld("desktop", bridge);

View File

@ -0,0 +1,296 @@
import { ChildProcess, spawn, SpawnOptions } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import net from "node:net";
import path from "node:path";
import { app } from "electron";
export type ServiceName = "pocketbase" | "api" | "youtube";
type Running = {
name: ServiceName;
proc: ChildProcess;
cwd: string;
};
const children: Running[] = [];
function isPackaged(): boolean {
return app.isPackaged;
}
export function resolveRuntimeRoot(): string {
if (isPackaged()) {
return path.join(process.resourcesPath, "runtime");
}
return path.resolve(__dirname, "..", "..");
}
export function resolvePaths() {
const root = resolveRuntimeRoot();
if (isPackaged()) {
return {
root,
backend: path.join(root, "backend"),
pb: path.join(root, "pb"),
youtube: path.join(root, "youtube-svc"),
};
}
return {
root,
backend: path.join(root, "backend"),
pb: path.join(root, "pb"),
youtube: path.join(root, "youtube-svc"),
};
}
function spawnLogged(
name: ServiceName,
command: string,
args: string[],
opts: SpawnOptions,
): ChildProcess {
const proc = spawn(command, args, {
...opts,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
const prefix = `[${name}]`;
let lines = 0;
const onChunk = (buf: Buffer, isErr: boolean) => {
if (lines > 30) return;
const line = String(buf).trim();
if (!line) return;
lines += 1;
if (isErr || lines <= 6) {
(isErr ? console.error : console.log)(prefix, line.slice(0, 220));
}
};
proc.stdout?.on("data", (b) => onChunk(b, false));
proc.stderr?.on("data", (b) => onChunk(b, true));
proc.on("exit", (code, signal) => {
console.log(prefix, `exited code=${code} signal=${signal}`);
});
children.push({ name, proc, cwd: String(opts.cwd || "") });
return proc;
}
function portOpen(port: number, host = "127.0.0.1"): Promise<boolean> {
return new Promise((resolve) => {
const sock = net.connect({ port, host });
sock.setTimeout(500);
sock.on("connect", () => {
sock.destroy();
resolve(true);
});
sock.on("timeout", () => {
sock.destroy();
resolve(false);
});
sock.on("error", () => resolve(false));
});
}
function probeHttp(url: string, timeoutMs = 1000): Promise<boolean> {
return new Promise((resolve) => {
const req = http.get(url, { timeout: timeoutMs }, (res) => {
res.resume();
resolve((res.statusCode || 500) < 500);
});
req.on("timeout", () => {
req.destroy();
resolve(false);
});
req.on("error", () => resolve(false));
});
}
function waitPort(port: number, timeoutMs = 45000, host = "127.0.0.1"): Promise<void> {
const start = Date.now();
return new Promise((resolve, reject) => {
let settled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
let sock: net.Socket | null = null;
const finish = (err?: Error) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
try {
sock?.destroy();
} catch {
/* ignore */
}
if (err) reject(err);
else resolve();
};
const tick = () => {
if (settled) return;
if (Date.now() - start > timeoutMs) {
finish(new Error(`timeout waiting port ${host}:${port}`));
return;
}
try {
sock?.destroy();
} catch {
/* ignore */
}
sock = net.connect({ port, host });
sock.setTimeout(800);
sock.once("connect", () => finish());
sock.once("timeout", () => {
try {
sock?.destroy();
} catch {
/* ignore */
}
timer = setTimeout(tick, 400);
});
sock.once("error", () => {
timer = setTimeout(tick, 400);
});
};
tick();
});
}
function findPython(): string {
return process.platform === "win32" ? "python" : "python3";
}
export async function startLocalServices(ports: {
apiPort: number;
pbPort: number;
ytPort: number;
}): Promise<{ apiBase: string; status: Record<string, string> }> {
const paths = resolvePaths();
const status: Record<string, string> = {};
const apiBase = `http://127.0.0.1:${ports.apiPort}`;
// Fast path: ports already open (avoid HTTP probes that can hang a wedged stack)
if (await portOpen(ports.apiPort)) {
status.api = "ok";
status.pocketbase = (await portOpen(ports.pbPort)) ? "ok" : "down";
status.youtube = (await portOpen(ports.ytPort)) ? "ok" : "optional";
console.log("[boot] reuse open ports", status);
return { apiBase, status };
}
// --- PocketBase ---
if (!(await portOpen(ports.pbPort))) {
const pbExe = path.join(paths.pb, process.platform === "win32" ? "pocketbase.exe" : "pocketbase");
if (!fs.existsSync(pbExe)) {
status.pocketbase = `missing: ${pbExe}`;
} else {
spawnLogged("pocketbase", pbExe, ["serve", `--http=127.0.0.1:${ports.pbPort}`], {
cwd: paths.pb,
env: { ...process.env },
});
try {
await waitPort(ports.pbPort, 20000);
status.pocketbase = "ok";
} catch (e) {
status.pocketbase = String((e as Error).message);
}
}
} else {
status.pocketbase = "ok";
}
// --- youtube-svc (optional) ---
if (!(await portOpen(ports.ytPort))) {
const ytPkg = path.join(paths.youtube, "package.json");
if (!fs.existsSync(ytPkg)) {
status.youtube = "skipped";
} else {
const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
spawnLogged("youtube", npmCmd, ["start"], {
cwd: paths.youtube,
env: { ...process.env, YT_SVC_PORT: String(ports.ytPort) },
shell: process.platform === "win32",
});
status.youtube = "optional";
void waitPort(ports.ytPort, 20000)
.then(() => {
status.youtube = "ok";
})
.catch(() => {
status.youtube = "optional";
});
}
} else {
status.youtube = "ok";
}
// --- FastAPI ---
if (await portOpen(ports.apiPort)) {
status.api = "ok";
} else {
const python = findPython();
const env = {
...process.env,
DY_PB_URL: `http://127.0.0.1:${ports.pbPort}`,
DY_YOUTUBE_SVC_URL: `http://127.0.0.1:${ports.ytPort}`,
DY_API_HOST: "127.0.0.1",
DY_API_PORT: String(ports.apiPort),
DY_AUTH_ENABLED: "false",
DY_DISABLE_LIVE_MAP_LOOP: "true",
// Keep event loop free for UI clicks on Windows desktop
DY_DESKTOP_LIGHT: "true",
DY_CORS_ORIGINS: [
"http://127.0.0.1:5173",
"http://localhost:5173",
"http://127.0.0.1:18574",
"http://localhost:18574",
].join(","),
DY_S3_ENABLED: process.env.DY_S3_ENABLED || "false",
TZ: "Asia/Shanghai",
PYTHONUTF8: "1",
};
const proc = spawnLogged(
"api",
python,
["run_desktop_api.py"],
{ cwd: paths.backend, env },
);
let spawnFailed = false;
proc.once("exit", (code) => {
if (code && code !== 0) spawnFailed = true;
});
try {
await waitPort(ports.apiPort, 45000);
status.api = "ok";
} catch (e) {
status.api = spawnFailed
? "api process exited (port busy?)"
: String((e as Error).message);
}
}
console.log("[boot] services", status);
return { apiBase, status };
}
export function stopLocalServices(): void {
for (const child of [...children].reverse()) {
try {
if (process.platform === "win32" && child.proc.pid) {
spawn("taskkill", ["/pid", String(child.proc.pid), "/T", "/F"], {
stdio: "ignore",
windowsHide: true,
});
} else {
child.proc.kill("SIGTERM");
}
} catch {
/* ignore */
}
}
children.length = 0;
}
export function listServicePids(): { name: ServiceName; pid?: number }[] {
return children.map((c) => ({ name: c.name, pid: c.proc.pid }));
}

44
desktop/electron/store.ts Normal file
View File

@ -0,0 +1,44 @@
import Store from "electron-store";
export type DesktopConfig = {
apiBase: string;
apiPort: number;
pbPort: number;
ytPort: number;
minimizeToTray: boolean;
nativeNotify: boolean;
windowBounds?: { x?: number; y?: number; width: number; height: number };
};
const defaults: DesktopConfig = {
apiBase: "http://127.0.0.1:8014",
apiPort: 8014,
pbPort: 8090,
ytPort: 8020,
minimizeToTray: true,
nativeNotify: true,
};
export const store = new Store<DesktopConfig>({
name: "douyinweb-desktop",
defaults,
});
export function getConfig(): DesktopConfig {
return {
apiBase: store.get("apiBase", defaults.apiBase),
apiPort: store.get("apiPort", defaults.apiPort),
pbPort: store.get("pbPort", defaults.pbPort),
ytPort: store.get("ytPort", defaults.ytPort),
minimizeToTray: store.get("minimizeToTray", defaults.minimizeToTray),
nativeNotify: store.get("nativeNotify", defaults.nativeNotify),
windowBounds: store.get("windowBounds"),
};
}
export function setConfig(patch: Partial<DesktopConfig>): DesktopConfig {
for (const [k, v] of Object.entries(patch)) {
if (v !== undefined) store.set(k as keyof DesktopConfig, v as never);
}
return getConfig();
}

View File

@ -0,0 +1,79 @@
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { URL } from "node:url";
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".ico": "image/x-icon",
".woff2": "font/woff2",
".map": "application/json",
};
function proxy(req: http.IncomingMessage, res: http.ServerResponse, apiBase: string) {
const target = new URL(req.url || "/", apiBase);
const headers = { ...req.headers, host: target.host };
const preq = http.request(
{
protocol: target.protocol,
hostname: target.hostname,
port: target.port,
path: target.pathname + target.search,
method: req.method,
headers,
},
(pres) => {
res.writeHead(pres.statusCode || 502, pres.headers);
pres.pipe(res);
},
);
preq.on("error", (err) => {
res.writeHead(502, { "Content-Type": "text/plain" });
res.end(`proxy error: ${err.message}`);
});
req.pipe(preq);
}
export function startUiServer(opts: {
distDir: string;
apiBase: string;
port?: number;
}): Promise<{ port: number; url: string; close: () => void }> {
const port = opts.port ?? 18574;
const server = http.createServer((req, res) => {
const url = req.url || "/";
if (url.startsWith("/api") || url.startsWith("/covers")) {
proxy(req, res, opts.apiBase);
return;
}
let filePath = path.join(opts.distDir, url === "/" ? "index.html" : decodeURIComponent(url.split("?")[0]));
if (!filePath.startsWith(opts.distDir)) {
res.writeHead(403);
res.end("forbidden");
return;
}
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
filePath = path.join(opts.distDir, "index.html");
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream" });
fs.createReadStream(filePath).pipe(res);
});
return new Promise((resolve, reject) => {
server.listen(port, "127.0.0.1", () => {
resolve({
port,
url: `http://127.0.0.1:${port}`,
close: () => server.close(),
});
});
server.on("error", reject);
});
}

18
desktop/index.html Normal file
View File

@ -0,0 +1,18 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>抖音直播监控</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;700&family=Space+Grotesk:wght@500;600;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

8609
desktop/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

80
desktop/package.json Normal file
View File

@ -0,0 +1,80 @@
{
"name": "douyinweb-desktop",
"version": "0.1.0",
"private": true,
"description": "抖音直播监控 Windows 客户端(本地 FastAPI + PocketBase)",
"main": "dist-electron/main.js",
"author": "douyinWEB",
"scripts": {
"dev": "vite",
"build:renderer": "vite build",
"build:electron": "tsc -p tsconfig.electron.json",
"build": "npm run build:renderer && npm run build:electron",
"start": "npm run build:electron && electron .",
"electron:dev": "npm run build:electron && concurrently -k \"vite\" \"wait-on http://127.0.0.1:5173 && electron .\"",
"pack": "npm run build && electron-builder --win",
"dist": "npm run pack"
},
"dependencies": {
"echarts": "^5.5.1",
"electron-store": "^8.2.0",
"lucide-react": "^0.468.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"concurrently": "^9.1.0",
"electron": "^33.2.1",
"electron-builder": "^25.1.8",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5",
"vite": "^6.0.3",
"wait-on": "^8.0.1"
},
"build": {
"appId": "com.douyinweb.desktop",
"productName": "抖音直播监控",
"directories": {
"output": "release"
},
"files": [
"dist/**/*",
"dist-electron/**/*",
"package.json"
],
"extraResources": [
{
"from": "../backend",
"to": "runtime/backend",
"filter": ["**/*", "!**/__pycache__/**", "!**/.venv/**", "!**/venv/**"]
},
{
"from": "../pb",
"to": "runtime/pb",
"filter": ["**/*"]
},
{
"from": "../youtube-svc",
"to": "runtime/youtube-svc",
"filter": ["**/*", "!node_modules/**"]
}
],
"win": {
"target": [
{ "target": "nsis", "arch": ["x64"] },
{ "target": "portable", "arch": ["x64"] }
]
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true
}
}
}

View File

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

59
desktop/src/App.tsx Normal file
View File

@ -0,0 +1,59 @@
import { Suspense, lazy } from "react";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { Loader2 } from "lucide-react";
import { Providers } from "@/components/Providers";
import { AuthGate } from "@/components/AuthGate";
import { ServiceBanner } from "@/components/ServiceBanner";
import LoginPage from "@/pages/LoginPage";
import OverviewPage from "@/pages/OverviewPage";
import ShortsPage from "@/pages/ShortsPage";
import SettingsPage from "@/pages/SettingsPage";
const SlotsPage = lazy(() => import("@/pages/SlotsPage"));
const SessionsPage = lazy(() => import("@/pages/SessionsPage"));
const AnchorsPage = lazy(() => import("@/pages/AnchorsPage"));
const CoversPage = lazy(() => import("@/pages/CoversPage"));
const EventsPage = lazy(() => import("@/pages/EventsPage"));
const RoomsPage = lazy(() => import("@/pages/RoomsPage"));
const GroupsPage = lazy(() => import("@/pages/GroupsPage"));
const YoutubePage = lazy(() => import("@/pages/YoutubePage"));
const BlacklistPage = lazy(() => import("@/pages/BlacklistPage"));
function PageFallback() {
return (
<div className="flex min-h-[40vh] items-center justify-center text-slate-500">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
);
}
export default function App() {
return (
<Providers>
<BrowserRouter>
<ServiceBanner />
<Suspense fallback={<PageFallback />}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AuthGate />}>
<Route path="/" element={<OverviewPage />} />
<Route path="/slots" element={<SlotsPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/anchors" element={<AnchorsPage />} />
<Route path="/covers" element={<CoversPage />} />
<Route path="/events" element={<EventsPage />} />
<Route path="/rooms" element={<RoomsPage />} />
<Route path="/groups" element={<GroupsPage />} />
<Route path="/youtube" element={<YoutubePage />} />
<Route path="/shorts" element={<ShortsPage />} />
<Route path="/blacklist" element={<BlacklistPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
</BrowserRouter>
</Providers>
);
}

View File

@ -0,0 +1,64 @@
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import { fetchJson } from "@/lib/api";
import { SKIP_DESKTOP_AUTH } from "@/lib/authFlags";
export function AuthGate() {
const location = useLocation();
const [state, setState] = useState<"loading" | "ok" | "login">(
SKIP_DESKTOP_AUTH ? "ok" : "loading",
);
const [bootError, setBootError] = useState("");
useEffect(() => {
// --- auth temporarily bypassed (keep block for restore) ---
if (SKIP_DESKTOP_AUTH) {
setState("ok");
return;
}
let cancelled = false;
void (async () => {
try {
const d = await fetchJson("/api/auth/status");
if (cancelled) return;
if (!d.auth_enabled || d.authenticated) setState("ok");
else setState("login");
} catch (e) {
if (cancelled) return;
setBootError((e as Error).message || "无法连接本地 API");
setState("login");
}
})();
return () => {
cancelled = true;
};
}, [location.pathname]);
if (SKIP_DESKTOP_AUTH) {
return <Outlet />;
}
if (state === "loading") {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-3 text-slate-400">
<Loader2 className="h-8 w-8 animate-spin text-teal-300" />
<p className="text-sm">正在连接本地服务…</p>
<p className="text-xs text-slate-600">PocketBase · FastAPI · YouTube sidecar</p>
</div>
);
}
if (state === "login") {
return (
<Navigate
to={`/login?next=${encodeURIComponent(location.pathname + location.search)}`}
replace
state={{ bootError }}
/>
);
}
return <Outlet />;
}

View File

@ -0,0 +1,92 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { Modal } from "@/components/Modal";
export type ConfirmOptions = {
title: string;
message?: string;
confirmLabel?: string;
cancelLabel?: string;
destructive?: boolean;
};
type Pending = ConfirmOptions & {
resolve: (ok: boolean) => void;
};
const ConfirmCtx = createContext<(opts: ConfirmOptions) => Promise<boolean>>(async () => false);
export function ConfirmProvider({ children }: { children: ReactNode }) {
const [pending, setPending] = useState<Pending | null>(null);
const [busy, setBusy] = useState(false);
const confirm = useCallback((opts: ConfirmOptions) => {
return new Promise<boolean>((resolve) => {
setPending({ ...opts, resolve });
});
}, []);
const close = useCallback(
(ok: boolean) => {
pending?.resolve(ok);
setPending(null);
setBusy(false);
},
[pending],
);
const value = useMemo(() => confirm, [confirm]);
return (
<ConfirmCtx.Provider value={value}>
{children}
<Modal
open={Boolean(pending)}
onClose={() => close(false)}
panelClassName="w-full max-w-md rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl"
>
{pending ? (
<>
<div className="border-b border-white/10 px-5 py-4">
<h3 className="font-display text-lg font-semibold text-white">{pending.title}</h3>
{pending.message ? (
<p className="mt-2 text-sm leading-relaxed text-slate-400">{pending.message}</p>
) : null}
</div>
<div className="flex gap-2 px-5 py-4">
<button
type="button"
disabled={busy}
onClick={() => close(false)}
className="flex-1 rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-slate-300 hover:bg-white/10"
>
{pending.cancelLabel || "取消"}
</button>
<button
type="button"
disabled={busy}
onClick={() => {
setBusy(true);
close(true);
}}
className={`inline-flex flex-1 items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium text-white ${
pending.destructive
? "bg-rose-500 hover:bg-rose-400"
: "bg-teal-500 hover:bg-teal-400"
}`}
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
{pending.confirmLabel || "确认"}
</button>
</div>
</>
) : null}
</Modal>
</ConfirmCtx.Provider>
);
}
export function useConfirm() {
return useContext(ConfirmCtx);
}

View File

@ -0,0 +1,178 @@
import { useEffect, useRef, useState } from "react";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
import { useEventStream } from "@/lib/realtime";
type NotifyFlags = {
live: boolean;
offline: boolean;
risk: boolean;
shortsFail: boolean;
shortsOk: boolean;
shortsQuota: boolean;
};
function applyFlags(s: Record<string, unknown>): NotifyFlags {
return {
live: s.notify_on_live !== false,
offline: Boolean(s.notify_on_offline),
risk: s.notify_on_risk !== false,
shortsFail: s.notify_on_shorts_fail !== false,
shortsOk: Boolean(s.notify_on_shorts_ok),
shortsQuota: s.notify_on_shorts_quota !== false,
};
}
/**
* App-wide SSE → toast + browser Notification (any page under Shell).
* Clickable alerts open SessionDetailModal when session_id is present.
*/
export function GlobalEventAlerts() {
const toast = useToast();
const { last, tick } = useEventStream(false); // desktop: no SSE (was freezing API)
const flagsRef = useRef<NotifyFlags>({
live: true,
offline: false,
risk: true,
shortsFail: true,
shortsOk: false,
shortsQuota: true,
});
const seenRef = useRef<Set<string>>(new Set());
const [detail, setDetail] = useState<SessionDetail | null>(null);
useEffect(() => {
const loadFlags = () => {
void fetchJson("/api/settings")
.then((s) => {
flagsRef.current = applyFlags(s);
})
.catch(() => undefined);
};
loadFlags();
const onChange = () => loadFlags();
window.addEventListener("dy-settings-changed", onChange);
const t = window.setInterval(loadFlags, 30000);
return () => {
window.removeEventListener("dy-settings-changed", onChange);
window.clearInterval(t);
};
}, []);
async function openSession(sessionId?: string) {
if (!sessionId) return;
try {
const data = await fetchJson(`/api/sessions/${sessionId}`);
setDetail((data.session || data) as SessionDetail);
} catch {
/* ignore */
}
}
useEffect(() => {
if (!last?.message) return;
const kind = last.kind || "";
if (!["live", "offline", "risk", "shorts_fail", "shorts_ok", "shorts_quota"].includes(kind)) return;
const flags = flagsRef.current;
if (kind === "live" && !flags.live) return;
if (kind === "offline" && !flags.offline) return;
if (kind === "risk" && !flags.risk) return;
if (kind === "shorts_fail" && !flags.shortsFail) return;
if (kind === "shorts_ok" && !flags.shortsOk) return;
if (kind === "shorts_quota" && !flags.shortsQuota) return;
const key = String(last.id || `${kind}:${last.message}:${last.ts || tick}`);
if (seenRef.current.has(key)) return;
seenRef.current.add(key);
if (seenRef.current.size > 200) {
const keep = Array.from(seenRef.current).slice(-80);
seenRef.current = new Set(keep);
}
const tone =
kind === "risk" || kind === "shorts_fail" || kind === "shorts_quota"
? "warn"
: kind === "offline"
? "err"
: "ok";
const sid = last.session_id;
const meta = (last.meta && typeof last.meta === "object" ? last.meta : {}) as Record<string, unknown>;
const isYt = meta.platform === "youtube" || String(last.room_id || "").startsWith("yt:");
const isShorts = kind === "shorts_fail" || kind === "shorts_ok" || kind === "shorts_quota";
const ytUrl = String(meta.youtube_url || "").trim();
const liveUrl = String(meta.live_url || meta.url || "").trim();
const shortsHref = "/shorts";
const fallbackHref = isShorts
? shortsHref
: !liveUrl
? isYt
? "/groups"
: last.room_id
? `/events?q=${encodeURIComponent(last.room_id)}`
: last.anchor_name
? `/events?q=${encodeURIComponent(last.anchor_name)}`
: undefined
: undefined;
toast.push(last.message, tone, {
onClick: sid
? () => void openSession(sid)
: ytUrl
? () => window.open(ytUrl, "_blank", "noopener,noreferrer")
: liveUrl
? () => window.open(liveUrl, "_blank", "noopener,noreferrer")
: undefined,
href: sid || ytUrl || liveUrl ? undefined : fallbackHref,
actionLabel: sid
? "查看场次 →"
: ytUrl
? "打开 Shorts →"
: liveUrl
? "打开直播 →"
: fallbackHref
? isShorts
? "打开 Shorts →"
: isYt
? "查看分组 →"
: "查看事件 →"
: undefined,
});
const title =
kind === "risk"
? "风控告警"
: kind === "offline"
? "停播提醒"
: kind === "shorts_fail"
? "Shorts 失败"
: kind === "shorts_ok"
? "Shorts 已上传"
: kind === "shorts_quota"
? "Shorts 配额落后"
: isYt
? "YouTube 开播"
: "开播提醒";
// Electron 原生通知(托盘/系统中心)
void window.desktop?.notify?.(title, String(last.message || ""));
if (typeof window !== "undefined" && "Notification" in window && Notification.permission === "granted") {
try {
const n = new Notification(title, { body: last.message, tag: key });
n.onclick = () => {
window.focus();
if (sid) void openSession(sid);
else if (ytUrl) window.open(ytUrl, "_blank", "noopener,noreferrer");
else if (liveUrl) window.open(liveUrl, "_blank", "noopener,noreferrer");
else if (fallbackHref) window.location.assign(fallbackHref);
};
} catch {
/* ignore */
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);
return detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null;
}

View File

@ -0,0 +1,196 @@
import { useState } from "react";
import { Check, Copy, ExternalLink } from "lucide-react";
import { fetchJson } from "@/lib/api";
const DEFAULT_PROJECT = "live-473104";
const DEFAULT_REDIRECT = "https://dylive.nomadro.com/api/shorts/oauth/callback";
function gcpLinks(projectId: string) {
const p = encodeURIComponent(projectId || DEFAULT_PROJECT);
return {
enableApi: `https://console.cloud.google.com/apis/library/youtube.googleapis.com?project=${p}`,
consent: `https://console.cloud.google.com/apis/credentials/consent?project=${p}`,
createClient: `https://console.cloud.google.com/apis/credentials/oauthclient?project=${p}`,
credentials: `https://console.cloud.google.com/apis/credentials?project=${p}`,
};
}
type Props = {
initialProjectId?: string;
initialClientId?: string;
initialClientSecret?: string;
redirectUri?: string;
configured?: boolean;
onSaved?: () => void;
};
export function GoogleOauthSetupWizard({
initialProjectId = DEFAULT_PROJECT,
initialClientId = "",
initialClientSecret = "",
redirectUri = DEFAULT_REDIRECT,
configured = false,
onSaved,
}: Props) {
const [projectId, setProjectId] = useState(initialProjectId || DEFAULT_PROJECT);
const [clientId, setClientId] = useState(initialClientId);
const [clientSecret, setClientSecret] = useState(initialClientSecret);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState("");
const [error, setError] = useState("");
const [copied, setCopied] = useState(false);
const links = gcpLinks(projectId);
async function copyRedirect() {
try {
await navigator.clipboard.writeText(redirectUri);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
setError("复制失败,请手动选中下方 URI");
}
}
function openAll() {
// User gesture required; open critical pages in order.
window.open(links.enableApi, "_blank", "noopener,noreferrer");
window.setTimeout(() => window.open(links.consent, "_blank", "noopener,noreferrer"), 400);
window.setTimeout(() => window.open(links.createClient, "_blank", "noopener,noreferrer"), 800);
}
async function saveClient() {
setBusy(true);
setMsg("");
setError("");
try {
if (!clientId.trim() || !clientSecret.trim()) {
throw new Error("请粘贴 Client ID 和 Client Secret");
}
await fetchJson("/api/settings", {
method: "PATCH",
body: JSON.stringify({
shorts_oauth_client_id: clientId.trim(),
shorts_oauth_client_secret: clientSecret.trim(),
shorts_oauth_redirect_uri: redirectUri,
shorts_gcp_project_id: projectId.trim() || DEFAULT_PROJECT,
}),
});
setMsg("已保存。下面给频道点「Google 授权」即可。");
onSaved?.();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<div className="mb-4 space-y-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4 text-sm">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<h3 className="font-medium text-amber-100">Google 一键引导(无法代建客户端)</h3>
<p className="mt-1 text-xs text-slate-400">
Google 禁止第三方替你创建 OAuth 客户端。点下面按钮直达你的项目页面,创建后粘贴回来保存——频道授权才是真正一键。
</p>
</div>
{configured ? (
<span className="rounded-lg border border-teal-500/30 bg-teal-500/10 px-2 py-1 text-xs text-teal-200">Client 已配置</span>
) : (
<span className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-xs text-amber-100">待配置 Client</span>
)}
</div>
<label className="block text-xs text-slate-400">
GCP Project ID
<input
value={projectId}
onChange={(e) => setProjectId(e.target.value)}
className="mt-1 w-full max-w-md rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm font-mono"
/>
</label>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={openAll}
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
>
<ExternalLink className="h-3.5 w-3.5" />
一键打开:启用 API + 同意屏幕 + 创建客户端
</button>
<a
href={links.credentials}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
已有凭据列表
</a>
</div>
<ol className="list-decimal space-y-1 pl-5 text-xs text-slate-400">
<li>弹出页里启用 YouTube Data API v3(建议同时启用 YouTube Analytics API)</li>
<li>
同意屏幕选 External,加你自己为 Test user;Scopes 尽量加全:
<code className="ml-1 text-[10px] text-slate-300">youtube</code>、
<code className="text-[10px] text-slate-300">youtube.force-ssl</code>、
<code className="text-[10px] text-slate-300">youtube.upload</code>、
<code className="text-[10px] text-slate-300">youtube.readonly</code>、
<code className="text-[10px] text-slate-300">youtubepartner</code>、
<code className="text-[10px] text-slate-300">yt-analytics.readonly</code>
</li>
<li>
创建 <b className="text-slate-200">Web application</b>,重定向 URI 填下面这行(先复制)
</li>
<li>把 Client ID / Secret 粘贴到下方 → 保存</li>
<li>权限变更后,到 Shorts 页对每个频道点「重新授权」才会拿到新 scope</li>
</ol>
<div className="flex flex-wrap items-center gap-2">
<code className="rounded bg-black/50 px-2 py-1 font-mono text-[11px] text-teal-200">{redirectUri}</code>
<button
type="button"
onClick={() => void copyRedirect()}
className="inline-flex items-center gap-1 rounded border border-white/10 bg-white/5 px-2 py-1 text-xs"
>
{copied ? <Check className="h-3 w-3 text-teal-300" /> : <Copy className="h-3 w-3" />}
{copied ? "已复制" : "复制回调 URI"}
</button>
</div>
<div className="grid gap-2 md:grid-cols-2">
<label className="block text-xs text-slate-400">
Client ID
<input
value={clientId}
onChange={(e) => setClientId(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="xxxx.apps.googleusercontent.com"
/>
</label>
<label className="block text-xs text-slate-400">
Client Secret
<input
type="password"
value={clientSecret}
onChange={(e) => setClientSecret(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="GOCSPX-..."
/>
</label>
</div>
<button
type="button"
disabled={busy}
onClick={() => void saveClient()}
className="rounded-lg border border-teal-500/30 bg-teal-500/15 px-3 py-2 text-sm text-teal-100"
>
{busy ? "保存中…" : "保存 Client 到本站"}
</button>
{msg ? <p className="text-xs text-teal-300">{msg}</p> : null}
{error ? <p className="text-xs text-rose-300">{error}</p> : null}
</div>
);
}

View File

@ -0,0 +1,41 @@
import { Modal } from "@/components/Modal";
type Props = {
src: string;
title?: string;
subtitle?: string;
onClose: () => void;
};
export function ImageLightbox({ src, title, subtitle, onClose }: Props) {
return (
<Modal
open
onClose={onClose}
zIndex={90}
panelClassName="relative flex max-h-[96vh] w-full max-w-[min(96vw,72rem)] flex-col overflow-hidden rounded-2xl border border-white/10 bg-[#0b1220] shadow-2xl"
>
<div className="flex shrink-0 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 min-h-0 flex-1 items-center justify-center bg-black/50 p-2 sm:p-4">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={src}
alt={title || "cover"}
className="max-h-[min(88vh,900px)] w-auto max-w-full rounded-lg object-contain"
/>
</div>
</Modal>
);
}

View File

@ -0,0 +1,60 @@
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,10 @@
import { ConfirmProvider } from "@/components/ConfirmDialog";
import { ToastProvider } from "@/components/Toast";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ToastProvider>
<ConfirmProvider>{children}</ConfirmProvider>
</ToastProvider>
);
}

View File

@ -0,0 +1,174 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Ban, Loader2, Star } from "lucide-react";
import { fetchJson, detectPlatform } from "@/lib/api";
import { useConfirm } from "@/components/ConfirmDialog";
export type RoomRef = {
room_pk?: string;
room_id?: string;
source_url?: string;
url?: string;
anchor_name?: string;
tags?: string[] | string;
};
const FAV_TAGS = new Set(["收藏", "重点", "priority", "vip", "高优"]);
export function isFavorited(tags?: string[] | string | null) {
const list = Array.isArray(tags)
? tags
: String(tags || "")
.split(",")
.map((t) => t.trim())
.filter(Boolean);
return list.some((t) => FAV_TAGS.has(t));
}
export async function roomQuickAction(
action: "favorite" | "unfavorite" | "ban",
ref: RoomRef,
reason = "",
) {
return fetchJson("/api/rooms/quick", {
method: "POST",
body: JSON.stringify({
action,
room_pk: ref.room_pk || "",
room_id: ref.room_id || "",
url: ref.source_url || ref.url || "",
reason,
}),
});
}
type Props = {
room: RoomRef;
/** known favorited state; if omitted, component will lookup when possible */
favorited?: boolean;
onDone?: (result: { action: string; favorited?: boolean; room?: any }) => void;
onError?: (message: string) => void;
/** compact icon-only */
compact?: boolean;
className?: string;
disabled?: boolean;
};
export function RoomQuickActions({
room,
favorited: favoritedProp,
onDone,
onError,
compact = false,
className = "",
disabled = false,
}: Props) {
const confirm = useConfirm();
const [busy, setBusy] = useState("");
const [fav, setFav] = useState(Boolean(favoritedProp));
const isYt =
detectPlatform(room) === "youtube" || String(room.room_id || "").startsWith("yt:");
useEffect(() => {
if (favoritedProp != null) setFav(Boolean(favoritedProp));
}, [favoritedProp, room.room_id, room.room_pk]);
useEffect(() => {
if (favoritedProp != null || isYt) return;
const key = room.room_pk || room.room_id;
if (!key) return;
let cancelled = false;
void (async () => {
try {
const q = encodeURIComponent(room.room_id || room.room_pk || "");
const data = await fetchJson(`/api/rooms?q=${q}&limit=20`);
const hit = (data.rooms || []).find(
(r: any) =>
(room.room_pk && r.id === room.room_pk) ||
(room.room_id && r.room_id === room.room_id),
);
if (!cancelled && hit) setFav(isFavorited(hit.tags));
} catch {
/* ignore */
}
})();
return () => {
cancelled = true;
};
}, [favoritedProp, isYt, room.room_id, room.room_pk]);
if (isYt) {
return (
<Link
to="/groups"
className={`inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-slate-400 hover:text-red-100 ${className}`}
title="YouTube 请到分组管理"
onClick={(e) => e.stopPropagation()}
>
分组
</Link>
);
}
async function run(action: "favorite" | "unfavorite" | "ban") {
if (disabled || busy) return;
if (action === "ban") {
const label = room.anchor_name || room.room_id || room.source_url || room.url || "该直播间";
const ok = await confirm({
title: "加入黑名单",
message: `将「${label}」加入黑名单并停用?`,
confirmLabel: "拉黑",
destructive: true,
});
if (!ok) return;
}
setBusy(action);
try {
const data = await roomQuickAction(action, room, action === "ban" ? "快捷拉黑" : "");
if (action !== "ban") setFav(Boolean(data.favorited));
onDone?.({ action, favorited: data.favorited, room: data.room });
} catch (e) {
onError?.((e as Error).message);
} finally {
setBusy("");
}
}
const btnBase = compact
? "inline-flex items-center justify-center rounded-lg border px-2 py-1 text-xs"
: "inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs";
return (
<div className={`inline-flex flex-wrap items-center gap-1.5 ${className}`} onClick={(e) => e.stopPropagation()}>
<button
type="button"
disabled={disabled || Boolean(busy)}
onClick={() => void run(fav ? "unfavorite" : "favorite")}
className={`${btnBase} disabled:opacity-50 ${
fav
? "border-amber-400/40 bg-amber-500/15 text-amber-100"
: "border-white/10 bg-white/5 text-slate-300 hover:text-amber-100"
}`}
title={fav ? "取消收藏" : "收藏直播间(重点轮询)"}
>
{busy === "favorite" || busy === "unfavorite" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Star className={`h-3.5 w-3.5 ${fav ? "fill-current" : ""}`} />
)}
{compact ? null : fav ? "已收藏" : "收藏"}
</button>
<button
type="button"
disabled={disabled || Boolean(busy)}
onClick={() => void run("ban")}
className={`${btnBase} border-rose-500/30 bg-rose-500/10 text-rose-100 hover:bg-rose-500/20 disabled:opacity-50`}
title="加入黑名单"
>
{busy === "ban" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Ban className="h-3.5 w-3.5" />}
{compact ? null : "拉黑"}
</button>
</div>
);
}

View File

@ -0,0 +1,56 @@
import { useEffect, useState } from "react";
export function ServiceBanner() {
const [msg, setMsg] = useState("");
useEffect(() => {
let cancelled = false;
const check = async () => {
if (window.desktop?.getServiceStatus) {
try {
const st = await window.desktop.getServiceStatus();
if (cancelled) return;
const apiOk = String(st?.api || "") === "ok";
if (apiOk) {
setMsg("");
return;
}
if (String(st?.boot || "").trim()) {
setMsg("正在启动本地服务…");
return;
}
} catch {
/* fall through */
}
}
const ctrl = new AbortController();
const t = window.setTimeout(() => ctrl.abort(), 2500);
try {
const { apiUrl } = await import("@/lib/api");
const res = await fetch(apiUrl("/api/ping"), {
credentials: "omit",
signal: ctrl.signal,
cache: "no-store",
});
if (cancelled) return;
setMsg(res.ok ? "" : `API 异常 HTTP ${res.status}`);
} catch {
if (!cancelled) setMsg("正在连接本地 API…");
} finally {
window.clearTimeout(t);
}
};
void check();
const id = window.setInterval(() => void check(), 12000);
return () => {
cancelled = true;
window.clearInterval(id);
};
}, []);
if (!msg) return null;
return (
<div className="pointer-events-none fixed left-0 right-0 top-0 z-[100] bg-amber-500/90 px-4 py-2 text-center text-xs text-black">
{msg}
</div>
);
}

View File

@ -0,0 +1,339 @@
import { useEffect, useMemo, useRef } from "react";
export type RelayStats = {
overview?: {
sessions?: number;
unique_anchors?: number;
active_sessions?: number;
total_hours?: number;
avg_duration_seconds?: number;
median_duration_seconds?: number;
};
top_anchors?: Array<{
anchor_name?: string;
sessions?: number;
hours_total?: number;
avg_duration_seconds?: number;
peak_hour?: number;
peak_weekday_label?: string;
dates_active?: number;
sessions_per_active_day?: number;
avg_gap_hours?: number | null;
source_room_id?: string;
}>;
by_hour?: { starts?: number[]; minutes?: number[]; labels?: string[] };
by_weekday?: { starts?: number[]; minutes?: number[]; labels?: string[]; labels_zh?: string[] };
heatmap?: {
starts?: number[][];
weekday_labels?: string[];
weekday_labels_zh?: string[];
hour_labels?: string[];
};
by_date?: Array<{ date: string; sessions: number; hours: number; unique_anchors: number }>;
duration_buckets?: Record<string, number>;
insights?: Array<{ zh: string; en: string }>;
};
function useEchart(option: Record<string, unknown> | null, height: number) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el || !option) return;
let disposed = false;
let chart: import("echarts").ECharts | null = null;
const onResize = () => chart?.resize();
import("echarts").then((echarts) => {
if (disposed || !ref.current) return;
chart = echarts.init(ref.current, undefined, { renderer: "canvas" });
chart.setOption(option, true);
window.addEventListener("resize", onResize);
});
return () => {
disposed = true;
window.removeEventListener("resize", onResize);
chart?.dispose();
};
}, [option]);
return <div ref={ref} style={{ height }} className="w-full" />;
}
const FG = "#edf3ff";
const MUTED = "#93a4bd";
const GRID = "rgba(255,255,255,0.06)";
const TOOLTIP = {
backgroundColor: "#0f1c2e",
borderColor: GRID,
textStyle: { color: FG, fontSize: 12 },
};
export function SessionCharts({ stats }: { stats: RelayStats | null }) {
const overview = stats?.overview;
const weekdayLabels = stats?.by_weekday?.labels_zh || stats?.by_weekday?.labels;
const heatWeekday = stats?.heatmap?.weekday_labels_zh || stats?.heatmap?.weekday_labels;
const dailyOption = useMemo(() => {
const rows = stats?.by_date || [];
if (!rows.length) return null;
return {
color: ["#2dd4bf", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: ["场次", "时长(小时)"], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 48 },
xAxis: {
type: "category",
data: rows.map((r) => r.date.slice(5)),
axisLabel: { color: MUTED, rotate: rows.length > 14 ? 45 : 0 },
axisLine: { lineStyle: { color: GRID } },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions), barMaxWidth: 18 },
{ name: "时长(小时)", type: "line", yAxisIndex: 1, smooth: true, data: rows.map((r) => Number(r.hours.toFixed(2))) },
],
};
}, [stats?.by_date]);
const anchorOption = useMemo(() => {
const rows = (stats?.top_anchors || []).slice(0, 12).reverse();
if (!rows.length) return null;
return {
color: ["#34d399", "#38bdf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis", axisPointer: { type: "shadow" } },
legend: { data: ["场次", "累计小时"], textStyle: { color: MUTED } },
grid: { left: 110, right: 48, top: 36, bottom: 28 },
xAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
yAxis: {
type: "category",
data: rows.map((r) => (r.anchor_name || "—").slice(0, 14)),
axisLabel: { color: MUTED, fontSize: 11 },
},
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions || 0), barMaxWidth: 14 },
{ name: "累计小时", type: "bar", data: rows.map((r) => Number((r.hours_total || 0).toFixed(2))), barMaxWidth: 14 },
],
};
}, [stats?.top_anchors]);
const hourOption = useMemo(() => {
const starts = stats?.by_hour?.starts || [];
const minutes = stats?.by_hour?.minutes || [];
if (!starts.some((n) => n > 0) && !minutes.some((n) => n > 0)) return null;
return {
color: ["#fbbf24", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: ["开播次数", "在播分钟"], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 36 },
xAxis: {
type: "category",
data: stats?.by_hour?.labels || Array.from({ length: 24 }, (_, h) => `${String(h).padStart(2, "0")}:00`),
axisLabel: { color: MUTED, fontSize: 10 },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "开播次数", type: "bar", data: starts, barMaxWidth: 12 },
{ name: "在播分钟", type: "line", yAxisIndex: 1, smooth: true, areaStyle: { opacity: 0.12 }, data: minutes.map((n) => Number(n.toFixed(1))) },
],
};
}, [stats?.by_hour]);
const weekdayOption = useMemo(() => {
const starts = stats?.by_weekday?.starts || [];
if (!starts.some((n) => n > 0)) return null;
return {
color: ["#818cf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
grid: { left: 48, right: 16, top: 28, bottom: 36 },
xAxis: { type: "category", data: weekdayLabels || [], axisLabel: { color: MUTED } },
yAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
series: [{ type: "bar", data: starts, barMaxWidth: 28, name: "开播场次" }],
};
}, [stats?.by_weekday, weekdayLabels]);
const heatmapOption = useMemo(() => {
const matrix = stats?.heatmap?.starts || [];
if (!matrix.length) return null;
const data: [number, number, number][] = [];
let max = 0;
matrix.forEach((row, wd) => {
row.forEach((val, hour) => {
data.push([hour, wd, val]);
if (val > max) max = val;
});
});
if (max <= 0) return null;
return {
textStyle: { color: FG },
tooltip: {
...TOOLTIP,
formatter: (p: { data?: [number, number, number] }) => {
const d = p.data;
if (!d) return "";
const label = (heatWeekday || [])[d[1]] || String(d[1]);
return `${label} ${String(d[0]).padStart(2, "0")}:00<br/>开播: <b>${d[2]}</b>`;
},
},
grid: { left: 56, right: 24, top: 16, bottom: 40 },
xAxis: {
type: "category",
data: stats?.heatmap?.hour_labels || Array.from({ length: 24 }, (_, h) => `${h}`),
splitArea: { show: true },
axisLabel: { color: MUTED, fontSize: 10 },
},
yAxis: { type: "category", data: heatWeekday || [], splitArea: { show: true }, axisLabel: { color: MUTED } },
visualMap: {
min: 0,
max: Math.max(1, max),
calculable: true,
orient: "horizontal",
left: "center",
bottom: 0,
textStyle: { color: MUTED },
inRange: { color: ["#0f1c2e", "#0e7490", "#2dd4bf", "#fbbf24", "#ff2d55"] },
},
series: [{ type: "heatmap", data, label: { show: false } }],
};
}, [stats?.heatmap, heatWeekday]);
const durationOption = useMemo(() => {
const buckets = stats?.duration_buckets || {};
const keys = Object.keys(buckets);
if (!keys.length || !Object.values(buckets).some((n) => n > 0)) return null;
return {
color: ["#2dd4bf"],
tooltip: { ...TOOLTIP, trigger: "item" },
series: [
{
type: "pie",
radius: ["42%", "68%"],
data: keys.map((k) => ({ name: k, value: buckets[k] })),
label: { color: MUTED, formatter: "{b}\n{c}" },
},
],
};
}, [stats?.duration_buckets]);
const dailyChart = useEchart(dailyOption, 280);
const anchorChart = useEchart(anchorOption, 340);
const hourChart = useEchart(hourOption, 280);
const weekdayChart = useEchart(weekdayOption, 240);
const heatChart = useEchart(heatmapOption, 300);
const durationChart = useEchart(durationOption, 260);
if (!stats || !(overview?.sessions || 0)) {
return (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-10 text-center">
<div className="mx-auto mb-3 text-4xl">📈</div>
<div className="font-display text-base text-white">暂无统计数据</div>
<p className="mt-1 text-sm text-slate-500">添加直播间并积累开播记录后,这里会显示频率与时段规律。</p>
</div>
);
}
const fmtDur = (seconds?: number) => {
const total = Math.max(0, Math.floor(Number(seconds) || 0));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h}小时${m}分`;
return `${m}分`;
};
return (
<div className="space-y-4">
<div className="stagger grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
{[
["🎬 总场次", String(overview?.sessions ?? 0)],
["👤 主播数", String(overview?.unique_anchors ?? 0)],
["⏱️ 累计时长", `${Number(overview?.total_hours || 0).toFixed(1)}h`],
["📏 平均场长", fmtDur(overview?.avg_duration_seconds)],
["📐 中位场长", fmtDur(overview?.median_duration_seconds)],
["🔴 进行中", String(overview?.active_sessions ?? 0)],
].map(([label, value]) => (
<div key={label} className="hover-lift rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.07] to-transparent px-4 py-3">
<div className="text-[11px] tracking-wide text-slate-500">{label}</div>
<div className="mt-1 font-display text-xl font-semibold tabular-nums text-white">{value}</div>
</div>
))}
</div>
{stats.insights?.length ? (
<div className="animate-fade-up rounded-xl border border-teal-500/20 bg-teal-500/5 px-4 py-3 text-sm text-teal-50/90">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-teal-300/80">💡 规律速览</div>
<ul className="space-y-1 text-slate-200">
{stats.insights.map((item, idx) => (
<li key={idx}>· {item.zh}</li>
))}
</ul>
</div>
) : null}
<div className="stagger grid gap-4 xl:grid-cols-2">
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📅 每日开播频率与时长</h3>
{dailyChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🏆 主播排行(场次 / 累计小时)</h3>
{anchorChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🕐 一天内时段分布</h3>
{hourChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📆 星期分布</h3>
{weekdayChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4 xl:col-span-2">
<h3 className="mb-1 text-sm font-medium text-slate-200">🔥 星期 × 小时 热力图</h3>
{heatChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🥧 单场时长分布</h3>
{durationChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-200">📋 主播明细</h3>
<div className="max-h-[260px] overflow-auto">
<table className="min-w-full text-left text-xs">
<thead className="sticky top-0 bg-[#0b1626] text-slate-500">
<tr>
<th className="px-2 py-2">主播</th>
<th className="px-2 py-2">场次</th>
<th className="px-2 py-2">小时</th>
<th className="px-2 py-2">日均场</th>
<th className="px-2 py-2">峰值</th>
<th className="px-2 py-2">间隔</th>
</tr>
</thead>
<tbody>
{(stats.top_anchors || []).map((row) => (
<tr key={`${row.anchor_name}-${row.source_room_id}`} className="border-t border-white/5 text-slate-300">
<td className="px-2 py-2 font-medium text-slate-100">{row.anchor_name || "—"}</td>
<td className="px-2 py-2 tabular-nums">{row.sessions ?? 0}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.hours_total || 0).toFixed(1)}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.sessions_per_active_day || 0).toFixed(2)}</td>
<td className="px-2 py-2">
{String(row.peak_hour ?? 0).padStart(2, "0")}:00
{row.peak_weekday_label ? ` · ${row.peak_weekday_label}` : ""}
</td>
<td className="px-2 py-2 tabular-nums">{row.avg_gap_hours == null ? "—" : `${Number(row.avg_gap_hours).toFixed(1)}h`}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
</div>
);
}

View File

@ -0,0 +1,266 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { ExternalLink, Loader2, RefreshCw, Square } from "lucide-react";
import { ImageLightbox } from "@/components/ImageLightbox";
import { useConfirm } from "@/components/ConfirmDialog";
import { Modal } from "@/components/Modal";
import { useToast } from "@/components/Toast";
import { RoomQuickActions } from "@/components/RoomQuickActions";
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api";
export type SessionDetail = {
id: string;
anchor_name?: string;
source_url?: string;
room_id?: string;
room_pk?: 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 confirm = useConfirm();
const toast = useToast();
const [busy, setBusy] = useState("");
const [err, setErr] = useState("");
const [local, setLocal] = useState<SessionDetail | null>(null);
const [zoom, setZoom] = useState(false);
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;
const ok = await confirm({
title: "结束场次",
message: `确认手动结束「${current.anchor_name || current.room_id}」这场?`,
confirmLabel: "结束",
destructive: true,
});
if (!ok) 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);
toast.push("场次已结束", "ok");
} catch (e) {
setErr((e as Error).message);
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
return (
<>
<Modal
open={Boolean(session)}
onClose={onClose}
panelClassName="max-h-[94vh] w-full max-w-5xl overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-4 shadow-2xl sm:p-5"
>
{current ? (
<>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h2 className="truncate text-lg font-semibold">{current.anchor_name || "直播间详情"}</h2>
<p className="mt-1 line-clamp-2 text-sm text-slate-400">{current.title || "—"}</p>
</div>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
<RoomQuickActions
room={{
room_pk: current.room_pk,
room_id: current.room_id,
source_url: current.source_url,
anchor_name: current.anchor_name,
}}
onDone={() => onUpdated?.(current)}
onError={(m) => setErr(m)}
/>
{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 lg:grid-cols-[minmax(240px,42%)_1fr]">
{cover ? (
<button
type="button"
onClick={() => setZoom(true)}
className="group relative flex max-h-[72vh] min-h-[280px] items-center justify-center overflow-hidden rounded-xl bg-black/50 ring-1 ring-white/10"
title="点击放大封面"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={cover}
alt=""
className="max-h-[72vh] w-full object-contain transition duration-300 group-hover:scale-[1.02]"
/>
<span className="pointer-events-none absolute bottom-2 right-2 rounded-md bg-black/60 px-2 py-1 text-[10px] text-slate-200 opacity-0 ring-1 ring-white/10 transition group-hover:opacity-100">
点击放大
</span>
</button>
) : (
<div className="flex min-h-[220px] items-center justify-center rounded-xl bg-slate-900 text-sm text-slate-500 ring-1 ring-white/10">
暂无截图
</div>
)}
<dl className="grid content-start gap-2.5 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 shrink-0" />
</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>
<div className="flex flex-wrap gap-2 pt-1">
{current.anchor_name ? (
<Link
to={`/sessions?q=${encodeURIComponent(current.anchor_name)}`}
className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-teal-200 hover:bg-white/10"
onClick={onClose}
>
本主播场次
</Link>
) : null}
{current.room_id ? (
<Link
to={`/events?q=${encodeURIComponent(current.room_id)}`}
className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-sky-200 hover:bg-white/10"
onClick={onClose}
>
本房事件
</Link>
) : null}
{current.anchor_name || current.room_id ? (
<Link
to={`/covers?q=${encodeURIComponent(current.anchor_name || current.room_id || "")}`}
className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-fuchsia-200 hover:bg-white/10"
onClick={onClose}
>
相关截图
</Link>
) : null}
{current.anchor_name ? (
<Link
to={`/anchors?q=${encodeURIComponent(current.anchor_name)}`}
className="rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-amber-100 hover:bg-white/10"
onClick={onClose}
>
主播画像
</Link>
) : null}
</div>
</dl>
</div>
</>
) : null}
</Modal>
{zoom && cover ? (
<ImageLightbox
src={cover}
title={current?.anchor_name || current?.room_id || "封面"}
subtitle={current?.source_url}
onClose={() => setZoom(false)}
/>
) : null}
</>
);
}

View File

@ -0,0 +1,192 @@
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { BrandMark, LivePulse } from "@/components/ui";
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
import { fetchJson } from "@/lib/api";
import { YouTubeLiveContextProvider, useYouTubeLiveCount, useYouTubeLiveMap, useYouTubeLiveProviderValue } from "@/lib/youtubeLive";
import { Link } from "react-router-dom";
const NAV = [
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" },
{ href: "/covers", label: "截图", emoji: "🖼️" },
{ href: "/events", label: "事件", emoji: "⚡" },
{ href: "/rooms", label: "直播间", emoji: "🏠" },
{ href: "/groups", label: "分组", emoji: "📺" },
{ href: "/youtube", label: "YouTube", emoji: "▶️" },
{ href: "/shorts", label: "Shorts", emoji: "📱" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
const MOBILE_PRIMARY = ["/", "/groups", "/shorts", "/youtube", "/settings"];
export function Shell({ children }: { children: React.ReactNode }) {
const liveCtx = useYouTubeLiveProviderValue();
return (
<YouTubeLiveContextProvider value={liveCtx}>
<ShellFrame>{children}</ShellFrame>
</YouTubeLiveContextProvider>
);
}
function ShellFrame({ children }: { children: React.ReactNode }) {
const pathname = useLocation().pathname;
const navigate = useNavigate();
const ytLiveCount = useYouTubeLiveCount();
const { map: ytLiveMap } = useYouTubeLiveMap();
const [username, setUsername] = useState("");
useEffect(() => {
void fetchJson("/api/auth/status")
.then((d) => setUsername(String(d.username || "")))
.catch(() => setUsername(""));
}, [pathname]);
async function logout() {
try {
await fetchJson("/api/auth/logout", { method: "POST" });
} catch {
/* ignore */
}
navigate("/login");
}
return (
<div className="relative min-h-screen">
<GlobalEventAlerts />
<div className="ambient-orb a" />
<div className="ambient-orb b" />
<div className="ambient-orb c" />
<div className="relative z-10 mx-auto flex min-h-screen max-w-7xl flex-col px-4 py-5 sm:px-6">
<header className="mb-6 animate-fade-up border-b border-white/10 pb-5">
<div className="flex flex-wrap items-end justify-between gap-4">
<div className="flex items-start gap-3">
<BrandMark className="mt-1 h-12 w-12" />
<div>
<p className="font-display text-xs uppercase tracking-[0.28em] text-teal-300/90">Live Radar</p>
<h1 className="font-display text-3xl font-bold tracking-tight text-white sm:text-4xl">
直播监控中心
</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证 · Windows 客户端
</p>
{ytLiveCount > 0 ? (
<div className="mt-2 flex flex-wrap items-center gap-2">
<Link to="/groups">
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
</Link>
{ytLiveMap?.checked_at ? (
<span className="text-[10px] text-slate-500">
轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前
</span>
) : null}
</div>
) : (
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
{ytLiveMap?.svc_error ? (
<span className="text-amber-300" title={ytLiveMap.svc_error}>
⚠ YouTube 探测异常(轮询兜底中)
</span>
) : (
<span>YouTube 直播轮询中</span>
)}
{ytLiveMap?.checked_at ? (
<span className="text-[10px]">
· {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前刷新
</span>
) : null}
</div>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{username ? (
<span className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300">
{username}
</span>
) : null}
<button
type="button"
onClick={() => void logout()}
className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/10 hover:text-white"
>
退出
</button>
</div>
<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 (
<button
key={item.href}
type="button"
onClick={() => navigate(item.href)}
className={`nav-chip 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 hover:bg-white/10 hover:text-white"
}`}
>
<span className="mr-1.5">{item.emoji}</span>
{item.label}
</button>
);
})}
</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 (
<button
key={item.href}
type="button"
onClick={() => navigate(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}
</button>
);
})}
</nav>
</header>
<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 + YouTube Monitor · realtime radar
</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 (
<button
key={item.href}
type="button"
onClick={() => navigate(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>
</button>
);
})}
</div>
</nav>
</div>
);
}

View File

@ -0,0 +1,173 @@
import { ExternalLink, Loader2, X } from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";
import { Modal } from "@/components/Modal";
import { fetchJson, fmtTs } from "@/lib/api";
type JobDetail = {
id: string;
status: string;
anchor_name?: string;
room_id?: string;
channel_name?: string;
channel_pk?: string;
push_date?: string;
clip_path?: string;
clip_ready?: boolean;
clip_seconds?: number;
youtube_url?: string;
youtube_video_id?: string;
error?: string;
attempts?: number;
session_id?: string;
source_url?: string;
created_at?: number;
updated_at?: number;
upload_at?: number;
started_at?: number;
finished_at?: number;
preview_title?: string;
preview_description?: string;
};
const STATUS_STYLE: Record<string, string> = {
pending: "bg-slate-500/20 text-slate-200",
recording: "bg-sky-500/20 text-sky-100",
recorded: "bg-indigo-500/20 text-indigo-100",
scheduled: "bg-amber-500/20 text-amber-100",
uploading: "bg-violet-500/20 text-violet-100",
uploaded: "bg-teal-500/20 text-teal-100",
failed: "bg-rose-500/20 text-rose-100",
};
function Row({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="grid grid-cols-[88px_1fr] gap-2 border-t border-white/5 py-2 text-xs first:border-t-0">
<div className="text-slate-500">{label}</div>
<div className="min-w-0 text-slate-200">{children}</div>
</div>
);
}
export function ShortsJobDetailModal({
jobId,
onClose,
}: {
jobId: string | null;
onClose: () => void;
}) {
const [job, setJob] = useState<JobDetail | null>(null);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState("");
useEffect(() => {
if (!jobId) {
setJob(null);
return;
}
let cancelled = false;
setLoading(true);
setErr("");
void fetchJson(`/api/shorts/jobs/${jobId}`)
.then((data) => {
if (!cancelled) setJob(data.job || data);
})
.catch((e) => {
if (!cancelled) setErr((e as Error).message);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [jobId]);
const clipUrl = job?.clip_ready ? `/api/shorts/jobs/${job.id}/clip` : "";
return (
<Modal open={Boolean(jobId)} onClose={onClose} panelClassName="w-full max-w-lg rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl">
<div className="flex items-start justify-between gap-3 border-b border-white/10 px-5 py-4">
<div className="min-w-0">
<p className="text-xs uppercase tracking-wider text-teal-300/80">任务详情</p>
<h3 className="mt-1 truncate font-display text-lg font-semibold text-white">
{job?.anchor_name || job?.room_id || jobId || "—"}
</h3>
</div>
<button type="button" onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:bg-white/5 hover:text-white">
<X className="h-4 w-4" />
</button>
</div>
<div className="max-h-[70vh] overflow-y-auto px-5 py-4">
{loading ? (
<div className="flex items-center justify-center gap-2 py-12 text-sm text-slate-400">
<Loader2 className="h-4 w-4 animate-spin" />
加载中…
</div>
) : err ? (
<p className="py-8 text-center text-sm text-rose-300">{err}</p>
) : job ? (
<>
{clipUrl ? (
<video
src={clipUrl}
controls
playsInline
preload="metadata"
className="mb-4 aspect-[9/16] max-h-64 w-full rounded-xl bg-black object-contain"
/>
) : null}
<Row label="状态">
<span className={`inline-block rounded-md px-2 py-0.5 text-[11px] ${STATUS_STYLE[job.status] || "bg-white/10"}`}>
{job.status}
</span>
</Row>
<Row label="频道">{job.channel_name || "—"}</Row>
<Row label="北京日">{job.push_date || "—"}</Row>
<Row label="排程上传">{job.upload_at ? fmtTs(Number(job.upload_at)) : "—"}</Row>
<Row label="创建">{job.created_at ? fmtTs(Number(job.created_at)) : "—"}</Row>
<Row label="尝试次数">{String(job.attempts ?? 0)}</Row>
<Row label="成片">
{job.clip_ready ? `${Math.round(Number(job.clip_seconds || 15))}s · 可预览` : job.clip_path ? "路径失效" : "无"}
</Row>
{job.preview_title ? (
<Row label="标题预览">
<span className="break-words text-slate-300">{job.preview_title}</span>
</Row>
) : null}
{job.error ? (
<Row label="错误">
<span className="break-words text-rose-300">{job.error}</span>
</Row>
) : null}
{job.youtube_url ? (
<Row label="YouTube">
<a href={job.youtube_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-teal-300 hover:underline">
已发布
<ExternalLink className="h-3 w-3" />
</a>
</Row>
) : null}
{job.session_id ? (
<Row label="场次">
<a href={`/sessions?highlight=${job.session_id}`} className="font-mono text-[10px] text-sky-300 hover:underline">
{job.session_id.slice(0, 8)}…
</a>
</Row>
) : null}
{job.source_url ? (
<Row label="来源">
<a href={job.source_url} target="_blank" rel="noreferrer" className="break-all text-sky-300 hover:underline">
{job.source_url}
</a>
</Row>
) : null}
<Row label="任务 ID">
<span className="break-all font-mono text-[10px] text-slate-500">{job.id}</span>
</Row>
</>
) : null}
</div>
</Modal>
);
}

View File

@ -0,0 +1,363 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
AlertCircle,
CheckCircle2,
ExternalLink,
Loader2,
Upload,
X,
} from "lucide-react";
import { Modal } from "@/components/Modal";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
export type ShortsUploadTarget = {
id: string;
anchor_name?: string;
room_id?: string;
channel_name?: string;
channel_pk?: string;
upload_at?: number;
clip_ready?: boolean;
status?: string;
};
type UploadPhase = "idle" | "uploading" | "success" | "failed";
type UploadTrack = {
phase: UploadPhase;
startedAt: number;
youtubeUrl?: string;
error?: string;
};
function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms));
}
function labelOf(t: ShortsUploadTarget) {
return t.anchor_name || t.room_id || "素材";
}
export function useShortsUpload(onRefresh: () => Promise<void>) {
const toast = useToast();
const [confirmTarget, setConfirmTarget] = useState<ShortsUploadTarget | null>(null);
const [tracks, setTracks] = useState<Record<string, UploadTrack>>({});
const pollRef = useRef<AbortController | null>(null);
const patchTrack = useCallback((id: string, patch: Partial<UploadTrack>) => {
setTracks((prev) => {
const cur = prev[id] || { phase: "idle" as const, startedAt: Date.now() };
return { ...prev, [id]: { ...cur, ...patch } };
});
}, []);
const finishSuccess = useCallback(
async (jobId: string, label: string, url: string) => {
patchTrack(jobId, { phase: "success", youtubeUrl: url });
toast.push(`「${label}」上传成功`, "ok", {
href: url || undefined,
actionLabel: url ? "在 YouTube 查看 Shorts →" : undefined,
durationMs: 8000,
});
await onRefresh();
window.setTimeout(() => {
setTracks((prev) => {
const next = { ...prev };
delete next[jobId];
return next;
});
}, 4000);
},
[onRefresh, patchTrack, toast],
);
const pollJob = useCallback(
async (jobId: string, label: string, signal: AbortSignal) => {
for (let i = 0; i < 120; i++) {
if (signal.aborted) return;
try {
const data = await fetchJson(`/api/shorts/jobs/${jobId}`);
const job = data.job || data;
const st = String(job.status || "");
if (st === "uploaded" || st === "done") {
const url = String(job.youtube_url || "");
await finishSuccess(jobId, label, url);
return;
}
if (st === "failed") {
const err = String(job.error || "上传失败");
patchTrack(jobId, { phase: "failed", error: err });
toast.push(`「${label}」上传失败:${err}`, "err", { durationMs: 6000 });
await onRefresh();
return;
}
if (st === "pending") {
const err = String(job.error || "成片已丢失,已重新排队录制");
patchTrack(jobId, { phase: "failed", error: err });
toast.push(`「${label}」${err}`, "warn", { durationMs: 6000 });
await onRefresh();
return;
}
} catch (e) {
if (signal.aborted) return;
if (i >= 2) {
const err = (e as Error).message;
patchTrack(jobId, { phase: "failed", error: err });
toast.push(err, "err");
return;
}
}
await sleep(i < 20 ? 1000 : 2000);
}
patchTrack(jobId, { phase: "failed", error: "上传耗时较长,请稍后刷新查看" });
toast.push(`「${label}」仍在处理,请稍后刷新`, "warn", { durationMs: 5000 });
await onRefresh();
},
[finishSuccess, onRefresh, patchTrack, toast],
);
const startUpload = useCallback(
async (target: ShortsUploadTarget) => {
const id = target.id;
const label = labelOf(target);
setConfirmTarget(null);
patchTrack(id, { phase: "uploading", startedAt: Date.now(), error: "", youtubeUrl: "" });
pollRef.current?.abort();
const ac = new AbortController();
pollRef.current = ac;
try {
const data = await fetchJson(`/api/shorts/jobs/${id}/upload-now`, { method: "POST" });
const job = data.job || data;
const st = String(job.status || "");
if (st === "uploaded" || st === "done") {
await finishSuccess(id, label, String(job.youtube_url || ""));
return;
}
if (st === "failed") {
const err = String(job.error || "上传失败");
patchTrack(id, { phase: "failed", error: err });
toast.push(`「${label}」上传失败:${err}`, "err");
return;
}
toast.push(`「${label}」上传中…`, "ok", { durationMs: 2000 });
void pollJob(id, label, ac.signal);
} catch (e) {
const err = (e as Error).message;
patchTrack(id, { phase: "failed", error: err });
toast.push(err, "err");
}
},
[finishSuccess, patchTrack, pollJob, toast],
);
useEffect(() => () => pollRef.current?.abort(), []);
return {
confirmTarget,
openConfirm: setConfirmTarget,
cancelConfirm: () => setConfirmTarget(null),
confirmUpload: () => confirmTarget && void startUpload(confirmTarget),
tracks,
retryUpload: (target: ShortsUploadTarget) => void startUpload(target),
};
}
export function ShortsUploadConfirmModal({
target,
onCancel,
onConfirm,
busy,
}: {
target: ShortsUploadTarget | null;
onCancel: () => void;
onConfirm: () => void;
busy?: boolean;
}) {
if (!target) return null;
const label = labelOf(target);
const scheduled = target.upload_at ? fmtTs(Number(target.upload_at)) : "未排程";
return (
<Modal open={Boolean(target)} onClose={onCancel} panelClassName="w-full max-w-md rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl">
<div className="border-b border-white/10 px-5 py-4">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-xs uppercase tracking-wider text-teal-300/80">手动上传</p>
<h3 className="mt-1 font-display text-lg font-semibold text-white">确认立即上传?</h3>
</div>
<button type="button" onClick={onCancel} className="rounded-lg p-1 text-slate-400 hover:bg-white/5 hover:text-white">
<X className="h-4 w-4" />
</button>
</div>
</div>
<div className="space-y-3 px-5 py-4 text-sm">
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="font-medium text-slate-100">{label}</div>
<div className="mt-2 space-y-1 text-xs text-slate-400">
<div>目标频道 · {target.channel_name || "—"}</div>
<div>原错峰排程 · {scheduled}</div>
<div>{target.clip_ready === false ? "成片状态 · 等待录制完成" : "成片状态 · 已就绪"}</div>
</div>
{target.clip_ready !== false && target.id ? (
<video
src={`/api/shorts/jobs/${target.id}/clip`}
controls
playsInline
preload="metadata"
className="mt-3 aspect-[9/16] max-h-48 w-full rounded-lg bg-black object-contain"
/>
) : null}
</div>
<p className="text-xs leading-relaxed text-amber-200/90">
将跳过错峰等待,立即发布到 YouTube Shorts。15 秒成片通常需 20–60 秒(含 OAuth 与传到 Google)。
</p>
</div>
<div className="flex gap-2 border-t border-white/10 px-5 py-4">
<button
type="button"
disabled={busy}
onClick={onCancel}
className="flex-1 rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-slate-300 hover:bg-white/10"
>
取消
</button>
<button
type="button"
disabled={busy || target.clip_ready === false}
onClick={onConfirm}
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-teal-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-teal-400 disabled:opacity-50"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
确认上传
</button>
</div>
</Modal>
);
}
function elapsedSec(startedAt: number) {
return Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
}
export function ShortsUpcomingUploadRow({
item,
track,
onRequestUpload,
onRetry,
}: {
item: ShortsUploadTarget;
track?: UploadTrack;
onRequestUpload: (item: ShortsUploadTarget) => void;
onRetry: (item: ShortsUploadTarget) => void;
}) {
const phase = track?.phase || "idle";
const [tick, setTick] = useState(0);
useEffect(() => {
if (phase !== "uploading") return;
const t = window.setInterval(() => setTick((n) => n + 1), 1000);
return () => window.clearInterval(t);
}, [phase]);
const label = labelOf(item);
const clipReady = item.clip_ready !== false;
const border =
phase === "uploading"
? "border-violet-500/40 bg-violet-500/[0.06]"
: phase === "success"
? "border-teal-500/40 bg-teal-500/[0.06]"
: phase === "failed"
? "border-rose-500/35 bg-rose-500/[0.05]"
: "border-white/10 bg-black/40";
return (
<div className={`rounded-xl border px-3 py-2.5 transition-colors ${border}`}>
<div className="flex items-center gap-3">
<div
className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${
phase === "success"
? "bg-teal-500/20 text-teal-300"
: phase === "failed"
? "bg-rose-500/15 text-rose-300"
: phase === "uploading"
? "bg-violet-500/20 text-violet-300"
: "bg-amber-500/15 text-amber-300"
}`}
>
{phase === "uploading" ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : phase === "success" ? (
<CheckCircle2 className="h-4 w-4" />
) : phase === "failed" ? (
<AlertCircle className="h-4 w-4" />
) : (
<Upload className="h-4 w-4" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-slate-100">{label}</div>
<div className="text-[11px] text-slate-500">
{item.channel_name || "频道"}
{item.upload_at ? ` · 排程 ${fmtTs(Number(item.upload_at))}` : " · 待排程"}
{!clipReady ? " · 等待成片" : phase === "idle" ? " · 成片就绪" : ""}
</div>
</div>
{phase === "idle" && clipReady ? (
<button
type="button"
onClick={() => onRequestUpload(item)}
className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-teal-500 px-3 py-1.5 text-xs font-medium text-white shadow-sm hover:bg-teal-400"
>
<Upload className="h-3.5 w-3.5" />
立即上传
</button>
) : null}
{phase === "failed" ? (
<button
type="button"
onClick={() => onRetry(item)}
className="inline-flex shrink-0 items-center gap-1 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs text-rose-100"
>
重试
</button>
) : null}
{phase === "success" && track?.youtubeUrl ? (
<a
href={track.youtubeUrl}
target="_blank"
rel="noreferrer"
className="inline-flex shrink-0 items-center gap-1 rounded-lg bg-teal-500/15 px-3 py-1.5 text-xs text-teal-100"
>
<ExternalLink className="h-3 w-3" />
查看
</a>
) : null}
</div>
{phase === "uploading" ? (
<div className="mt-3">
<div className="mb-1 flex items-center justify-between text-[11px] text-violet-200/90">
<span>
{elapsedSec(track?.startedAt || Date.now()) >= 45
? "YouTube 仍在接收,请稍候…"
: "正在上传到 YouTube…"}
</span>
<span>{elapsedSec(track?.startedAt || Date.now())}s</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/10">
<div className="h-full w-full animate-pulse rounded-full bg-gradient-to-r from-violet-600/40 via-violet-400/80 to-violet-600/40" />
</div>
</div>
) : null}
{phase === "failed" && track?.error ? (
<p className="mt-2 text-[11px] leading-relaxed text-rose-300">{track.error}</p>
) : null}
{phase === "success" ? (
<p className="mt-2 text-[11px] text-teal-300">上传完成,已从排队列表移除</p>
) : null}
</div>
);
}

View File

@ -0,0 +1,102 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
type ToastTone = "ok" | "warn" | "err";
type ToastItem = {
id: string;
text: string;
tone?: ToastTone;
href?: string;
actionLabel?: string;
onClick?: () => void;
};
type PushOpts = {
href?: string;
actionLabel?: string;
onClick?: () => void;
durationMs?: number;
};
const ToastCtx = createContext<{
push: (text: string, tone?: ToastTone, opts?: PushOpts) => void;
} | null>(null);
export function ToastProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<ToastItem[]>([]);
const push = useCallback((text: string, tone: ToastTone = "ok", opts?: PushOpts) => {
const id = `${Date.now()}-${Math.random()}`;
setItems((prev) => [
...prev.slice(-4),
{
id,
text,
tone,
href: opts?.href,
actionLabel: opts?.actionLabel,
onClick: opts?.onClick,
},
]);
window.setTimeout(() => {
setItems((prev) => prev.filter((x) => x.id !== id));
}, opts?.durationMs ?? (opts?.onClick || opts?.href ? 6000 : 3200));
}, []);
const value = useMemo(() => ({ push }), [push]);
return (
<ToastCtx.Provider value={value}>
{children}
<div className="pointer-events-none fixed inset-x-4 bottom-20 z-[80] flex flex-col gap-2 md:inset-x-auto md:bottom-4 md:right-4 md:w-[min(92vw,22rem)] md:pb-[env(safe-area-inset-bottom)]">
{items.map((t) => {
const clickable = Boolean(t.onClick || t.href);
const body = (
<>
<div>{t.text}</div>
{clickable ? (
<div className="mt-1 text-[11px] opacity-80">{t.actionLabel || "点击查看 →"}</div>
) : null}
</>
);
const cls = `pointer-events-auto animate-fade-up rounded-xl border px-3 py-2 text-left text-sm shadow-lg backdrop-blur ${
t.tone === "err"
? "border-rose-500/40 bg-rose-500/20 text-rose-50"
: t.tone === "warn"
? "border-amber-500/40 bg-amber-500/20 text-amber-50"
: "border-teal-500/40 bg-teal-500/20 text-teal-50"
} ${clickable ? "cursor-pointer hover:brightness-110" : ""}`;
if (t.href) {
return (
<a key={t.id} href={t.href} className={cls}>
{body}
</a>
);
}
if (t.onClick) {
return (
<button key={t.id} type="button" onClick={t.onClick} className={cls}>
{body}
</button>
);
}
return (
<div key={t.id} className={cls}>
{body}
</div>
);
})}
</div>
</ToastCtx.Provider>
);
}
export function useToast() {
const ctx = useContext(ToastCtx);
if (!ctx) {
return {
push: (_t: string, _tone?: ToastTone, _opts?: PushOpts) => undefined,
};
}
return ctx;
}

View File

@ -0,0 +1,75 @@
import { LivePulse } from "@/components/ui";
import { useYouTubeLiveEntry, type YouTubeLiveEntry } from "@/lib/youtubeLive";
type Props = {
/** e.g. group:uuid, shorts:uuid, channel:UCxxx */
refKey?: string;
/** Direct entry override (probe tab, etc.) */
entry?: YouTubeLiveEntry | null;
className?: string;
/** Show stream title next to badge */
showTitle?: boolean;
compact?: boolean;
/** When not live, still show 离线/检测中 instead of hiding */
showOffline?: boolean;
};
export function YouTubeLiveBadge({
refKey,
entry,
className = "",
showTitle = false,
compact = false,
showOffline = false,
}: Props) {
const fromMap = useYouTubeLiveEntry(refKey);
const live = entry ?? fromMap;
if (!live) {
if (!showOffline) return null;
return (
<span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-500 ring-1 ring-white/10 ${className}`}>
检测中
</span>
);
}
if (!live.is_live) {
if (!showOffline) return null;
const tip = live.error ? String(live.error) : "YouTube 未开播";
return (
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-500 ring-1 ring-white/10 ${className}`}
title={tip}
>
离线
</span>
);
}
const label = compact ? "LIVE" : "LIVE";
const inner = (
<>
<LivePulse label={label} />
{showTitle && live.title ? (
<span className="max-w-[180px] truncate text-[11px] text-rose-100/90">{live.title}</span>
) : null}
</>
);
if (live.live_url) {
return (
<a
href={live.live_url}
target="_blank"
rel="noreferrer"
className={`inline-flex items-center gap-2 hover:opacity-90 ${className}`}
title={live.title || "打开直播"}
>
{inner}
</a>
);
}
return <span className={`inline-flex items-center gap-2 ${className}`}>{inner}</span>;
}

View File

@ -0,0 +1,49 @@
import { Link } from "react-router-dom";
import { LivePulse } from "@/components/ui";
import { useYouTubeLiveMap } from "@/lib/youtubeLive";
/** Home ticker: all live YouTube groups + Shorts channels from live-map. */
export function YouTubeLiveTicker() {
const { map } = useYouTubeLiveMap();
const entries = map?.entries || {};
const live = Object.entries(entries).filter(
([k, v]) => (k.startsWith("group:") || k.startsWith("shorts:")) && v?.is_live,
);
if (!live.length) return null;
const items = live.map(([key, v]) => ({
key,
title: v.title || key.replace(/^(group|shorts):/, ""),
url: v.live_url || "#",
source: v.source,
}));
return (
<div className="mb-6 overflow-hidden rounded-2xl border border-red-500/25 bg-red-500/5">
<div className="flex items-center gap-2 border-b border-white/5 px-4 py-2 text-xs text-red-100/90">
<LivePulse label={`YouTube ${items.length} 路在播`} />
<Link to="/groups" className="ml-auto text-teal-300 hover:underline">
分组 →
</Link>
</div>
<div className="relative overflow-hidden py-3">
<div className="ticker-track gap-8 px-4 text-sm text-slate-200">
{[...items, ...items].map((item, idx) => (
<a
key={`${item.key}-${idx}`}
href={item.url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 whitespace-nowrap hover:text-white"
>
<span className="live-dot" />
<span className="font-medium">{item.title}</span>
{item.source ? <span className="text-[10px] text-slate-500">{item.source}</span> : null}
</a>
))}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,166 @@
import { useEffect, useState, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
export function AnimatedNumber({
value,
decimals = 0,
duration = 700,
suffix = "",
}: {
value: number;
decimals?: number;
duration?: number;
suffix?: string;
}) {
const [display, setDisplay] = useState(0);
useEffect(() => {
const target = Number(value) || 0;
const start = performance.now();
let from = 0;
setDisplay((prev) => {
from = prev;
return prev;
});
let raf = 0;
const tick = (now: number) => {
const t = Math.min(1, (now - start) / duration);
const eased = 1 - Math.pow(1 - t, 3);
setDisplay(from + (target - from) * eased);
if (t < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [value, duration]);
return (
<span className="tabular-nums">
{display.toFixed(decimals)}
{suffix}
</span>
);
}
export function LivePulse({ label = "LIVE" }: { label?: string }) {
return (
<span className="inline-flex items-center gap-2 rounded-md border border-rose-500/30 bg-rose-500/10 px-2 py-1 text-[11px] font-semibold tracking-wide text-rose-100">
<span className="live-dot" />
{label}
</span>
);
}
export function BrandMark({ className = "h-10 w-10" }: { className?: string }) {
return (
<svg className={`${className} float-slow`} viewBox="0 0 64 64" aria-hidden>
<defs>
<linearGradient id="bm" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#ff2d55" />
<stop offset="100%" stopColor="#2dd4bf" />
</linearGradient>
</defs>
<rect x="4" y="4" width="56" height="56" rx="16" fill="url(#bm)" opacity="0.18" />
<path className="logo-stroke" d="M18 40 V24 l12 16 12-16 v16 M14 48 h36" stroke="url(#bm)" />
<circle cx="48" cy="16" r="4" fill="#ff2d55">
<animate attributeName="opacity" values="1;0.35;1" dur="1.4s" repeatCount="indefinite" />
</circle>
</svg>
);
}
export function StatTile({
emoji,
label,
value,
hint,
accent = "teal",
}: {
emoji: string;
label: string;
value: ReactNode;
hint?: string;
accent?: "teal" | "rose" | "amber" | "sky";
}) {
const ring =
accent === "rose"
? "from-rose-500/20"
: accent === "amber"
? "from-amber-500/20"
: accent === "sky"
? "from-sky-500/20"
: "from-teal-500/20";
return (
<div className={`hover-lift glass-panel relative overflow-hidden rounded-2xl bg-gradient-to-br px-4 py-4 ${ring} to-transparent`}>
<div className="flex items-start justify-between gap-2">
<div className="text-2xl leading-none">{emoji}</div>
<div className="text-right">
<div className="text-[11px] uppercase tracking-wide text-slate-500">{label}</div>
<div className="mt-1 font-display text-2xl font-semibold text-white">{value}</div>
</div>
</div>
{hint ? <div className="mt-3 text-xs text-slate-500">{hint}</div> : null}
</div>
);
}
export function EmptyState({
emoji,
title,
desc,
}: {
emoji: string;
title: string;
desc: string;
}) {
return (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 bg-black/20 px-6 py-12 text-center">
<div className="mx-auto mb-3 flex h-16 w-16 items-center justify-center rounded-2xl bg-white/5 text-3xl">{emoji}</div>
<div className="font-display text-lg text-white">{title}</div>
<p className="mx-auto mt-1 max-w-md text-sm text-slate-500">{desc}</p>
</div>
);
}
export function PlatformBadge({
platform,
className = "",
}: {
platform?: string;
className?: string;
}) {
const yt = platform === "youtube";
return (
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ring-1 ${
yt
? "bg-red-500/15 text-red-200 ring-red-400/30"
: "bg-fuchsia-500/15 text-fuchsia-100 ring-fuchsia-400/30"
} ${className}`}
>
{yt ? "YT" : "抖音"}
</span>
);
}
export function PageLoader({ label = "加载中…" }: { label?: string }) {
return (
<div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
<Loader2 className="h-5 w-5 animate-spin text-teal-400" />
{label}
</div>
);
}
export function TableSkeleton({ rows = 5, cols = 4 }: { rows?: number; cols?: number }) {
return (
<div className="animate-pulse space-y-2">
{Array.from({ length: rows }).map((_, i) => (
<div key={i} className="flex gap-3 rounded-lg bg-white/[0.04] px-3 py-3">
{Array.from({ length: cols }).map((__, j) => (
<div key={j} className="h-3 flex-1 rounded bg-white/10" style={{ maxWidth: j === 0 ? "40%" : undefined }} />
))}
</div>
))}
</div>
);
}

245
desktop/src/lib/api.ts Normal file
View File

@ -0,0 +1,245 @@
import { SKIP_DESKTOP_AUTH } from "@/lib/authFlags";
export function clearAuthRedirect() {
if (typeof window !== "undefined") {
delete (window as unknown as { __dyAuthRedirect?: boolean }).__dyAuthRedirect;
}
}
declare global {
interface Window {
__dyAuthRedirect?: boolean;
__dyApiBase?: string;
desktop?: {
getConfig: () => Promise<Record<string, unknown>>;
setConfig: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
getServiceStatus: () => Promise<Record<string, unknown>>;
notify: (title: string, body: string) => Promise<void>;
openExternal: (url: string) => Promise<void>;
openLogs: () => Promise<void>;
getDiagnostics: () => Promise<Record<string, unknown>>;
onWindowFocus: (cb: (focused: boolean) => void) => () => void;
minimizeToTray: () => Promise<void>;
};
}
}
/** Desktop: talk to FastAPI directly (avoid Vite proxy + SSE starving the connection pool). */
export function getApiBase(): string {
if (typeof window === "undefined") return "";
if (window.__dyApiBase) return window.__dyApiBase.replace(/\/$/, "");
// Electron file/ui always has desktop bridge; prefer local API
if (window.desktop) return "http://127.0.0.1:8014";
return "";
}
export function setApiBase(base: string) {
if (typeof window === "undefined") return;
window.__dyApiBase = String(base || "").replace(/\/$/, "");
}
export function apiUrl(path: string): string {
if (!path) return path;
if (/^https?:\/\//i.test(path)) return path;
const p = path.startsWith("/") ? path : `/${path}`;
const base = getApiBase();
return base ? `${base}${p}` : p;
}
export async function openDesktopExternal(url: string) {
if (!url || url === "#") return;
if (window.desktop?.openExternal && /^https?:\/\//i.test(url)) {
await window.desktop.openExternal(url);
return;
}
window.open(url, "_blank", "noopener,noreferrer");
}
const FETCH_TIMEOUT_MS = 20000;
export async function fetchJson(url: string, init?: RequestInit) {
const apiKey =
typeof window !== "undefined" ? window.localStorage.getItem("dy_api_key") || "" : "";
const ctrl = new AbortController();
const timer = window.setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
// Auth bypassed on desktop — omit cookies so CORS stays simple/reliable on Windows
const creds: RequestCredentials = SKIP_DESKTOP_AUTH ? "omit" : "include";
const method = String(init?.method || "GET").toUpperCase();
const headers: Record<string, string> = {
...(apiKey ? { "X-API-Key": apiKey } : {}),
...((init?.headers as Record<string, string>) || {}),
};
if (method !== "GET" && method !== "HEAD" && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
let res: Response;
try {
res = await fetch(apiUrl(url), {
...init,
signal: ctrl.signal,
credentials: creds,
headers,
});
} catch (e) {
window.clearTimeout(timer);
if ((e as Error)?.name === "AbortError") {
throw new Error(`请求超时(${FETCH_TIMEOUT_MS / 1000}s):${url}`);
}
throw e;
}
window.clearTimeout(timer);
const text = await res.text();
let data: Record<string, unknown> | null = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = { raw: text };
}
if (!SKIP_DESKTOP_AUTH && res.status === 401 && typeof window !== "undefined") {
const path = window.location.pathname;
const detail = typeof data?.detail === "string" ? data.detail : "";
const authFail =
path !== "/login" &&
(detail.includes("未登录") ||
detail.includes("登录") ||
detail.includes("API Key") ||
detail.includes("Unauthorized") ||
url.includes("/api/"));
if (authFail && !window.__dyAuthRedirect) {
window.__dyAuthRedirect = true;
const next = encodeURIComponent(path + window.location.search);
window.location.assign(`/login?next=${next}`);
}
}
if (!res.ok) {
const detail = data?.detail || data?.message || text || res.statusText;
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
}
return data as any;
}
export function fmtDuration(seconds?: number | null) {
const total = Math.max(0, Math.floor(Number(seconds) || 0));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
if (h > 0) return `${h}小时${m}分${s}秒`;
if (m > 0) return `${m}分${s}秒`;
return `${s}秒`;
}
export const BJ_TZ = "Asia/Shanghai";
export function beijingParts(dateOrMs: number | Date = Date.now()) {
const d = typeof dateOrMs === "number" ? new Date(dateOrMs) : dateOrMs;
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: BJ_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).formatToParts(d);
const get = (type: string) => parts.find((p) => p.type === type)?.value || "";
return {
year: get("year"),
month: get("month"),
day: get("day"),
hour: Number(get("hour") || 0),
minute: Number(get("minute") || 0),
second: Number(get("second") || 0),
};
}
export function todayBeijingISO() {
const p = beijingParts();
return `${p.year}-${p.month}-${p.day}`;
}
export function shiftBeijingISO(iso: string, days: number) {
const d = new Date(`${iso}T12:00:00+08:00`);
d.setTime(d.getTime() + Number(days || 0) * 86400000);
const p = beijingParts(d);
return `${p.year}-${p.month}-${p.day}`;
}
export function beijingHourFromTs(tsSec?: number) {
if (!tsSec) return 0;
return beijingParts(Number(tsSec) * 1000).hour;
}
export function beijingDateFromTs(tsSec?: number) {
if (!tsSec) return "";
const p = beijingParts(Number(tsSec) * 1000);
return `${p.year}-${p.month}-${p.day}`;
}
export function fmtTs(ts?: number) {
if (!ts) return "—";
try {
return new Date(ts * 1000).toLocaleString("zh-CN", {
timeZone: BJ_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
});
} catch {
return String(ts);
}
}
export function fmtClock(ts?: number) {
if (!ts) return "—";
try {
return new Date(ts * 1000).toLocaleTimeString("zh-CN", {
timeZone: BJ_TZ,
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
} catch {
return "—";
}
}
export function sessionCoverSrc(session: any, bust = true) {
if (!session) return "";
const publicUrl = String(session.cover_url || "").trim();
const proxyUrl = String(session.cover_proxy_url || "").trim();
const fallback = session.id ? apiUrl(`/api/sessions/${session.id}/cover`) : "";
const base =
(publicUrl.startsWith("http://") || publicUrl.startsWith("https://") ? publicUrl : "") ||
(proxyUrl.startsWith("http://") || proxyUrl.startsWith("https://") ? proxyUrl : "") ||
(proxyUrl.startsWith("/") ? apiUrl(proxyUrl) : proxyUrl) ||
fallback ||
publicUrl ||
"";
if (!base) return "";
if (!bust) return base;
const ts = session.started_at || session.updated_at || session.id || "";
if (!ts) return base;
return base.includes("?") ? `${base}&v=${ts}` : `${base}?v=${ts}`;
}
export function detectPlatform(row: any) {
if (!row) return "douyin";
const meta = row.metadata || row.meta || {};
if (meta.platform === "youtube") return "youtube";
const rid = String(row.room_id || "");
if (rid.startsWith("yt:")) return "youtube";
const url = String(row.source_url || row.url || row.channel_url || "");
if (/youtube\.com|youtu\.be/i.test(url)) return "youtube";
if (String(row.message || "").includes("YouTube")) return "youtube";
return "douyin";
}
export function platformLabel(p: string) {
return p === "youtube" ? "YouTube" : "抖音";
}

View File

@ -0,0 +1,6 @@
/**
* Temporary desktop auth bypass.
* Set SKIP_DESKTOP_AUTH = false to restore login gate + session redirects.
* Login page / auth API code is kept; only gating is skipped.
*/
export const SKIP_DESKTOP_AUTH = true;

191
desktop/src/lib/realtime.ts Normal file
View File

@ -0,0 +1,191 @@
import { useEffect, useRef, useState } from "react";
import { apiUrl } from "@/lib/api";
export type StreamEvent = {
id?: string;
ts?: number;
kind?: string;
message?: string;
anchor_name?: string;
room_id?: string;
session_id?: string;
meta?: Record<string, unknown>;
};
export type RefreshOpts = { silent?: boolean };
function useDesktopFocused(defaultFocused = true) {
const [focused, setFocused] = useState(defaultFocused);
useEffect(() => {
const unsub = window.desktop?.onWindowFocus?.((f) => setFocused(f));
const onVis = () => setFocused(document.visibilityState === "visible");
document.addEventListener("visibilitychange", onVis);
return () => {
unsub?.();
document.removeEventListener("visibilitychange", onVis);
};
}, []);
return focused;
}
/** One shared EventSource — avoid reconnect storms starving fetch. */
let sharedEs: EventSource | null = null;
let sharedEsUrl = "";
let sharedEsRefCount = 0;
const sharedListeners = new Set<(ev: StreamEvent) => void>();
const sharedOpenListeners = new Set<(ok: boolean) => void>();
let sharedEsPaused = false;
/** Pause SSE while API is wedged (desktop boot / health fail). */
export function setEventStreamPaused(paused: boolean) {
sharedEsPaused = Boolean(paused);
if (sharedEsPaused && sharedEs) {
try {
sharedEs.close();
} catch {
/* ignore */
}
sharedEs = null;
sharedOpenListeners.forEach((fn) => fn(false));
} else if (!sharedEsPaused && sharedEsRefCount > 0 && !sharedEs) {
acquireSharedEventSource();
}
}
function acquireSharedEventSource() {
sharedEsRefCount += 1;
if (sharedEsPaused) return null;
const url = apiUrl("/api/events/stream");
if (sharedEs && sharedEsUrl === url) {
return sharedEs;
}
try {
sharedEs?.close();
} catch {
/* ignore */
}
sharedEsUrl = url;
sharedEs = new EventSource(url);
sharedEs.onopen = () => {
sharedOpenListeners.forEach((fn) => fn(true));
};
sharedEs.onerror = () => {
sharedOpenListeners.forEach((fn) => fn(false));
try {
sharedEs?.close();
} catch {
/* ignore */
}
sharedEs = null;
window.setTimeout(() => {
if (!sharedEsPaused && sharedEsRefCount > 0 && !sharedEs) {
// reconnect without bumping refcount
sharedEsRefCount = Math.max(0, sharedEsRefCount - 1);
acquireSharedEventSource();
}
}, 4000);
};
sharedEs.onmessage = (msg) => {
try {
const data = JSON.parse(msg.data) as StreamEvent;
sharedListeners.forEach((fn) => fn(data));
} catch {
/* ignore */
}
};
return sharedEs;
}
function releaseSharedEventSource() {
sharedEsRefCount = Math.max(0, sharedEsRefCount - 1);
if (sharedEsRefCount === 0 && sharedEs) {
try {
sharedEs.close();
} catch {
/* ignore */
}
sharedEs = null;
sharedEsUrl = "";
}
}
export function useEventStream(enabled = true) {
const [connected, setConnected] = useState(false);
const [last, setLast] = useState<StreamEvent | null>(null);
const [tick, setTick] = useState(0);
const focused = useDesktopFocused(true);
useEffect(() => {
if (!enabled) return;
const onMsg = (data: StreamEvent) => {
setLast(data);
setTick((n) => n + 1);
};
const onOpen = (ok: boolean) => setConnected(ok);
sharedListeners.add(onMsg);
sharedOpenListeners.add(onOpen);
acquireSharedEventSource();
return () => {
sharedListeners.delete(onMsg);
sharedOpenListeners.delete(onOpen);
releaseSharedEventSource();
};
}, [enabled]);
return { connected, last, tick, focused };
}
export function useAutoRefresh(
load: (opts?: RefreshOpts) => void | Promise<void>,
opts?: {
intervalMs?: number;
eventKinds?: string[] | false;
enabled?: boolean;
},
) {
const intervalMs = opts?.intervalMs ?? 30000;
const enabled = opts?.enabled !== false;
const eventKinds = opts?.eventKinds === false ? null : opts?.eventKinds ?? ["live", "offline", "risk"];
const { connected, last, tick, focused } = useEventStream(Boolean(eventKinds) && enabled);
const loadRef = useRef(load);
loadRef.current = load;
useEffect(() => {
if (!enabled) return;
void loadRef.current({ silent: false });
if (!intervalMs || intervalMs <= 0) return;
const ms = focused ? intervalMs : Math.max(intervalMs * 3, 60000);
const t = window.setInterval(() => void loadRef.current({ silent: true }), ms);
return () => window.clearInterval(t);
}, [load, intervalMs, enabled, focused]);
useEffect(() => {
if (!enabled || !eventKinds || !last?.kind) return;
if (!eventKinds.includes(String(last.kind))) return;
void loadRef.current({ silent: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick, enabled]);
return { connected };
}
export function useNow(intervalMs = 1000) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(t);
}, [intervalMs]);
return now;
}
export function liveElapsed(startedAt?: number, nowMs?: number) {
if (!startedAt) return "—";
const now = (nowMs || Date.now()) / 1000;
const total = Math.max(0, Math.floor(now - startedAt));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
return `${m}:${String(s).padStart(2, "0")}`;
}

View File

@ -0,0 +1,111 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { fetchJson } from "@/lib/api";
export type YouTubeLiveEntry = {
is_live?: boolean;
live_url?: string;
title?: string;
channel_id?: string;
source?: string;
error?: string;
};
export type YouTubeLiveMap = {
ok?: boolean;
checked_at?: number;
live_count?: number;
source?: string;
entries?: Record<string, YouTubeLiveEntry>;
svc_error?: string;
};
const YouTubeLiveContext = createContext<{
map: YouTubeLiveMap | null;
loading: boolean;
refresh: () => Promise<void>;
}>({
map: null,
loading: false,
refresh: async () => {},
});
export function groupLiveRef(groupId: string) {
return `group:${groupId}`;
}
export function shortsLiveRef(channelPk: string) {
return `shorts:${channelPk}`;
}
export function channelLiveRef(channelId: string) {
return `channel:${channelId}`;
}
export function useYouTubeLiveProviderValue(intervalMs = 30000) {
const [map, setMap] = useState<YouTubeLiveMap | null>(null);
const [loading, setLoading] = useState(false);
const [focused, setFocused] = useState(true);
useEffect(() => {
const unsub = window.desktop?.onWindowFocus?.((f) => setFocused(f));
const onVis = () => setFocused(document.visibilityState === "visible");
document.addEventListener("visibilitychange", onVis);
return () => {
unsub?.();
document.removeEventListener("visibilitychange", onVis);
};
}, []);
const refresh = useCallback(async (silent = false) => {
if (!silent) setLoading(true);
try {
const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap;
setMap(data);
} catch {
/* keep last map */
} finally {
if (!silent) setLoading(false);
}
}, []);
useEffect(() => {
void refresh(true);
const ms = focused ? intervalMs : Math.max(intervalMs * 3, 45000);
const id = window.setInterval(() => void refresh(true), ms);
const onVis = () => {
if (document.visibilityState === "visible") void refresh(true);
};
document.addEventListener("visibilitychange", onVis);
return () => {
window.clearInterval(id);
document.removeEventListener("visibilitychange", onVis);
};
}, [intervalMs, refresh, focused]);
return useMemo(
() => ({
map,
loading,
refresh: () => refresh(false),
}),
[map, loading, refresh],
);
}
export const YouTubeLiveContextProvider = YouTubeLiveContext.Provider;
export function useYouTubeLiveMap() {
return useContext(YouTubeLiveContext);
}
export function useYouTubeLiveEntry(refKey?: string): YouTubeLiveEntry | null {
const { map } = useYouTubeLiveMap();
if (!refKey) return null;
return map?.entries?.[refKey] ?? null;
}
export function useYouTubeLiveCount() {
const { map } = useYouTubeLiveMap();
return Number(map?.live_count || 0);
}

25
desktop/src/main.tsx Normal file
View File

@ -0,0 +1,25 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { setApiBase } from "./lib/api";
import "./styles/globals.css";
// Never block first paint on IPC
setApiBase("http://127.0.0.1:8014");
// Hold SSE until /api/health succeeds (avoids wedging API on boot)
void import("./lib/realtime").then((m) => m.setEventStreamPaused(true));
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
// Optional: refresh apiBase from Electron store (non-blocking)
void window.desktop?.getConfig?.()
.then((cfg) => {
const base = String(cfg?.apiBase || "").trim();
if (base) setApiBase(base);
})
.catch(() => undefined);

View File

@ -0,0 +1,386 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, RefreshCw, UserRound } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { RoomQuickActions } from "@/components/RoomQuickActions";
import { AnimatedNumber, EmptyState, LivePulse } from "@/components/ui";
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc, todayBeijingISO } from "@/lib/api";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type AnchorRow = {
anchor_name: string;
room_id?: string;
sessions: number;
hours_total: number;
last_started_at?: number;
active?: number;
};
type Profile = {
anchor_name: string;
room_id?: string;
overview: {
sessions: number;
total_hours: number;
avg_duration_seconds: number;
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;
ended_at?: number | null;
duration_seconds?: number;
cover_url?: string;
cover_proxy_url?: string;
title?: string;
status?: string;
source_url?: string;
room_id?: string;
anchor_name?: string;
}>;
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>("");
const [profile, setProfile] = useState<Profile | null>(null);
const [q, setQ] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [detail, setDetail] = useState<SessionDetail | null>(null);
const [bootstrapped, setBootstrapped] = useState(false);
useEffect(() => {
if (typeof window === "undefined") return;
const p = new URLSearchParams(window.location.search);
const query = p.get("q") || p.get("name") || "";
if (query) setQ(query);
setBootstrapped(true);
}, []);
const loadList = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const data = await fetchJson("/api/anchors?limit=80");
const list = (data.anchors || []) as AnchorRow[];
setAnchors(list);
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, []);
const loadProfile = useCallback(async (key: string) => {
if (!key) return;
try {
const data = await fetchJson(`/api/anchors/${encodeURIComponent(key)}`);
setProfile(data);
} catch (e) {
setError((e as Error).message);
}
}, []);
const refreshAll = useCallback(
async (opts?: RefreshOpts) => {
await loadList(opts);
if (selected) void loadProfile(selected);
},
[loadList, loadProfile, selected],
);
useAutoRefresh(refreshAll, { intervalMs: 30000 });
const filtered = useMemo(() => {
const needle = q.trim().toLowerCase();
if (!needle) return anchors;
return anchors.filter((a) =>
`${a.anchor_name} ${a.room_id || ""}`.toLowerCase().includes(needle),
);
}, [anchors, q]);
useEffect(() => {
if (!bootstrapped || !anchors.length) return;
if (selected) return;
const needle = q.trim().toLowerCase();
if (needle) {
const hit = anchors.find((a) =>
`${a.anchor_name} ${a.room_id || ""}`.toLowerCase().includes(needle),
);
if (hit) {
setSelected(hit.anchor_name);
return;
}
}
setSelected(anchors[0].anchor_name);
}, [bootstrapped, anchors, q, selected]);
useEffect(() => {
if (selected) void loadProfile(selected);
}, [selected, loadProfile]);
async function openSession(s: Profile["sessions"][number]) {
try {
const data = await fetchJson(`/api/sessions/${s.id}`);
setDetail((data.session || { ...s, anchor_name: profile?.anchor_name }) as SessionDetail);
} catch {
setDetail({
id: s.id,
anchor_name: profile?.anchor_name || s.anchor_name,
room_id: s.room_id || profile?.room_id,
title: s.title,
started_at: s.started_at,
ended_at: s.ended_at,
duration_seconds: s.duration_seconds,
cover_url: s.cover_url,
cover_proxy_url: s.cover_proxy_url,
status: s.status,
source_url: s.source_url,
});
}
}
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>
</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" />}
刷新
</button>
</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}
{!anchors.length && !loading ? (
<EmptyState emoji="🎤" title="还没有主播数据" desc="有开播场次后,这里会自动生成主播排行与画像。" />
) : (
<div className="grid gap-4 lg:grid-cols-[20rem_1fr]">
<aside className="glass-panel max-h-[70vh] space-y-2 overflow-auto rounded-2xl p-3">
<input
value={q}
onChange={(e) => {
setQ(e.target.value);
setSelected("");
}}
placeholder="搜索主播 / 房间号…"
className="mb-2 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
{filtered.map((a) => (
<button
key={`${a.anchor_name}-${a.room_id}`}
type="button"
onClick={() => setSelected(a.anchor_name)}
className={`hover-lift w-full rounded-xl border px-3 py-2 text-left text-sm ${
selected === a.anchor_name ? "border-teal-400/40 bg-teal-500/10" : "border-white/10 bg-black/20"
}`}
>
<div className="flex items-center justify-between gap-2">
<span className="truncate font-medium text-white">{a.anchor_name}</span>
{a.active ? <LivePulse label="LIVE" /> : null}
</div>
<div className="mt-1 text-[11px] text-slate-500">
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h
</div>
</button>
))}
{!filtered.length ? (
<div className="px-2 py-6 text-center text-xs text-slate-500">无匹配主播</div>
) : null}
</aside>
<section className="glass-panel rounded-2xl p-4">
{profile ? (
<>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<UserRound className="h-5 w-5 text-teal-300" />
<h3 className="font-display text-xl font-semibold">{profile.anchor_name}</h3>
{profile.overview.active ? <LivePulse /> : null}
</div>
<p className="mt-1 font-mono text-xs text-cyan-300/80">{profile.room_id || "—"}</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<RoomQuickActions
room={{
room_pk: profile.rooms?.[0]?.id,
room_id: profile.room_id || profile.rooms?.[0]?.room_id,
url: profile.rooms?.[0]?.url,
source_url: profile.rooms?.[0]?.url,
anchor_name: profile.anchor_name,
}}
onError={(m) => setError(m)}
/>
{profile.rooms?.[0]?.url ? (
<a href={profile.rooms[0].url} target="_blank" rel="noreferrer" className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10">
打开直播间
</a>
) : null}
</div>
</div>
<div className="mb-4 grid gap-3 sm:grid-cols-4">
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">场次</div>
<div className="font-display text-xl"><AnimatedNumber value={profile.overview.sessions} /></div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">累计小时</div>
<div className="font-display text-xl"><AnimatedNumber value={profile.overview.total_hours} decimals={1} /></div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">平均场长</div>
<div className="font-display text-xl">{fmtDuration(profile.overview.avg_duration_seconds)}</div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">最近开播</div>
<div className="text-sm text-slate-200">{fmtTs(profile.overview.last_started_at)}</div>
</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
to={`/slots?date=${todayBeijingISO()}${
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 w-full items-center gap-3 rounded-xl border border-white/5 bg-black/20 p-2"
>
<button
type="button"
onClick={() => void openSession(s)}
className="flex min-w-0 flex-1 items-center gap-3 text-left hover:opacity-90"
>
{sessionCoverSrc(s) ? (
// eslint-disable-next-line @next/next/no-img-element
<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>
)}
<div className="min-w-0 flex-1 text-sm">
<div className="truncate text-slate-200">{s.title || "场次"}</div>
<div className="text-xs text-slate-500">
{fmtTs(s.started_at)} · {fmtDuration(s.duration_seconds)} · {s.status}
</div>
</div>
<span className="shrink-0 text-[11px] text-teal-400/80">详情 →</span>
</button>
<RoomQuickActions
compact
room={{
room_pk: profile.rooms?.[0]?.id,
room_id: s.room_id || profile.room_id,
source_url: s.source_url || profile.rooms?.[0]?.url,
anchor_name: profile.anchor_name,
}}
onError={(m) => setError(m)}
/>
</div>
))}
</div>
<div className="mt-4 text-xs text-slate-500">
也可在 <Link to={`/sessions?q=${encodeURIComponent(profile.anchor_name)}`} className="text-teal-300 hover:underline">场次日志</Link> 中按主播名筛选。
</div>
</>
) : (
<div className="py-16 text-center text-slate-500">选择左侧主播查看画像</div>
)}
</section>
</div>
)}
{detail ? (
<SessionDetailModal session={detail} onClose={() => setDetail(null)} onUpdated={() => selected && void loadProfile(selected)} />
) : null}
</Shell>
);
}

View File

@ -0,0 +1,168 @@
import { useCallback, useEffect, useState } from "react";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { useConfirm } from "@/components/ConfirmDialog";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { EmptyState, PageLoader } from "@/components/ui";
import { fetchJson, fmtTs } from "@/lib/api";
type Item = {
id: string;
value: string;
room_id?: string;
reason?: string;
created_at?: number;
};
export default function BlacklistPage() {
const confirm = useConfirm();
const toast = useToast();
const [items, setItems] = useState<Item[]>([]);
const [value, setValue] = useState("");
const [reason, setReason] = useState("");
const [loading, setLoading] = useState(true);
const [adding, setAdding] = useState(false);
const [deletingId, setDeletingId] = useState("");
const [error, setError] = useState("");
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const data = await fetchJson("/api/blacklist");
setItems(data.items || []);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
async function add() {
setAdding(true);
setError("");
try {
await fetchJson("/api/blacklist", {
method: "POST",
body: JSON.stringify({ value, reason }),
});
setValue("");
setReason("");
toast.push("已加入黑名单", "ok");
await load();
} catch (e) {
const msg = (e as Error).message;
setError(msg);
toast.push(msg, "err");
} finally {
setAdding(false);
}
}
async function remove(item: Item) {
const ok = await confirm({
title: "移出黑名单",
message: `确定移除「${item.value}」?相关房间将恢复可监控状态。`,
confirmLabel: "移除",
destructive: true,
});
if (!ok) return;
setDeletingId(item.id);
try {
await fetchJson(`/api/blacklist/${item.id}`, { method: "DELETE" });
toast.push("已从黑名单移除", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setDeletingId("");
}
}
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">🚫 直播间黑名单</h2>
<p className="text-sm text-slate-400">命中后自动停用相关房间并结束进行中场次,不再进入轮询。</p>
</div>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-[1fr_1fr_auto]">
<label className="block text-xs text-slate-400">
房间号 / URL / 关键词
<input
value={value}
onChange={(e) => setValue(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
原因
<input
value={reason}
onChange={(e) => setReason(e.target.value)}
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">
<button
type="button"
disabled={!value.trim() || adding}
onClick={() => void add()}
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm hover:bg-white/15 disabled:opacity-50"
>
{adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
加入黑名单
</button>
</div>
</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}
{loading ? (
<PageLoader />
) : items.length === 0 ? (
<EmptyState emoji="🚫" title="黑名单为空" desc="添加房间号、URL 或关键词后,命中项将自动停用并不再轮询。" />
) : (
<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>
{items.map((item) => (
<tr key={item.id} className="border-t border-white/5">
<td className="px-3 py-3 font-mono text-xs">{item.value}</td>
<td className="px-3 py-3">{item.room_id || "—"}</td>
<td className="px-3 py-3 text-slate-400">{item.reason || "—"}</td>
<td className="px-3 py-3 text-slate-400">{fmtTs(item.created_at)}</td>
<td className="px-3 py-3">
<button
type="button"
disabled={deletingId === item.id}
onClick={() => void remove(item)}
className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200 hover:bg-rose-500/10 disabled:opacity-50"
>
{deletingId === item.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
移除
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Shell>
);
}

View File

@ -0,0 +1,288 @@
import { useCallback, useEffect, useState } from "react";
import { Loader2, RefreshCw, ImagePlus, Camera } from "lucide-react";
import { Shell } from "@/components/Shell";
import { ImageLightbox } from "@/components/ImageLightbox";
import { SessionDetailModal } from "@/components/SessionDetailModal";
import { fetchJson, fmtTs, sessionCoverSrc } from "@/lib/api";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Session = {
id: string;
anchor_name?: string;
room_id?: string;
source_url?: string;
started_at?: number;
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("");
useEffect(() => {
if (typeof window === "undefined") return;
const p = new URLSearchParams(window.location.search);
const qq = p.get("q");
if (qq) setQ(qq);
const t = p.get("tab");
if (t === "missing" || t === "has") setTab(t);
}, []);
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
params.set("limit", "100");
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) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [q]);
useAutoRefresh(load, { intervalMs: 30000 });
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">开播瞬间一帧存证(S3),缺图场次可在此查看并补抓。</p>
</div>
<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>
{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}
{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 && 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">{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 && sessionCoverSrc(selected) ? (
<ImageLightbox
src={sessionCoverSrc(selected)}
title={selected.anchor_name || selected.room_id || "封面"}
subtitle={fmtTs(selected.started_at)}
onClose={() => setSelected(null)}
/>
) : null}
{detail ? (
<SessionDetailModal
session={detail}
onClose={() => setDetail(null)}
onUpdated={() => void load()}
/>
) : null}
</Shell>
);
}

View File

@ -0,0 +1,307 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { EmptyState, PlatformBadge } from "@/components/ui";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { fetchJson, fmtTs, detectPlatform } from "@/lib/api";
import { useEventStream } from "@/lib/realtime";
type EventItem = {
id: string;
ts: number;
level?: string;
kind?: string;
room_id?: string;
anchor_name?: string;
message?: string;
session_id?: string;
meta?: Record<string, unknown>;
};
const KIND_META: Record<string, { emoji: string; color: string; label: string }> = {
live: { emoji: "🎬", color: "text-rose-300 border-rose-500/30 bg-rose-500/10", label: "开播" },
offline: { emoji: "📴", color: "text-slate-300 border-slate-500/30 bg-slate-500/10", label: "停播" },
risk: { emoji: "⚠️", color: "text-amber-200 border-amber-500/30 bg-amber-500/10", label: "风控" },
error: { emoji: "💥", color: "text-orange-200 border-orange-500/30 bg-orange-500/10", label: "错误" },
blacklist: { emoji: "🚫", color: "text-fuchsia-200 border-fuchsia-500/30 bg-fuchsia-500/10", label: "黑名单" },
ops: { emoji: "🛠️", color: "text-sky-200 border-sky-500/30 bg-sky-500/10", label: "运维" },
demo: { emoji: "✨", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: "演示" },
};
const PAGE_SIZE = 50;
export default function EventsPage() {
const confirm = useConfirm();
const toast = useToast();
const [events, setEvents] = useState<EventItem[]>([]);
const [total, setTotal] = useState(0);
const [kind, setKind] = useState("");
const [platform, setPlatform] = useState("");
const [q, setQ] = useState("");
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState("");
const [detail, setDetail] = useState<SessionDetail | null>(null);
const [detailBusy, setDetailBusy] = useState(false);
const { connected, last, tick } = useEventStream(false);
useEffect(() => {
if (typeof window === "undefined") return;
const p = new URLSearchParams(window.location.search);
const k = p.get("kind");
if (k) setKind(k);
const pf = p.get("platform");
if (pf) setPlatform(pf);
const qq = p.get("q");
if (qq) setQ(qq);
}, []);
const load = useCallback(
async (opts?: { append?: boolean; offset?: number }) => {
const append = Boolean(opts?.append);
if (append) setLoadingMore(true);
else setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (kind) params.set("kind", kind);
if (platform) params.set("platform", platform);
if (q.trim()) params.set("q", q.trim());
params.set("limit", String(PAGE_SIZE));
params.set("offset", String(append ? opts?.offset ?? 0 : 0));
const data = await fetchJson(`/api/events?${params}`);
const rows = data.events || [];
setEvents((prev) => (append ? [...prev, ...rows] : rows));
setTotal(Number(data.total) || 0);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
setLoadingMore(false);
}
},
[kind, platform, q],
);
useEffect(() => {
void load();
}, [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,
meta: last.meta,
};
if (kind && incoming.kind !== kind) return;
if (platform) {
const p = detectPlatform(incoming);
if (p !== platform) 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, platform, 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">
<div>
<h2 className="font-display text-2xl font-semibold">⚡ 事件时间线</h2>
<p className="text-sm text-slate-400">开播 / 停播 / 风控 / 错误的实时审计流。</p>
</div>
<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">
{[
["", "全部"],
["live", "开播"],
["offline", "停播"],
["risk", "风控"],
["error", "错误"],
["blacklist", "黑名单"],
].map(([value, label]) => (
<button
key={value || "all"}
type="button"
onClick={() => setKind(value)}
className={`rounded-xl px-3 py-1.5 text-sm transition ${
kind === value ? "bg-white/15 text-white ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
{label}
</button>
))}
{[
["", "全部平台"],
["douyin", "抖音"],
["youtube", "YouTube"],
].map(([value, label]) => (
<button
key={`p-${value || "all"}`}
type="button"
onClick={() => setPlatform(value)}
className={`rounded-xl px-3 py-1.5 text-sm transition ${
platform === value ? "bg-white/15 text-white ring-1 ring-rose-400/30" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
{label}
</button>
))}
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="🔍 搜索消息 / 主播 / 房间号"
className="w-full max-w-sm rounded-xl border border-white/10 bg-slate-900/80 px-3 py-2 text-sm"
/>
<button
type="button"
onClick={async () => {
const ok = await confirm({
title: "清理历史事件",
message: "确定清理 7 天前的事件?此操作不可撤销。",
confirmLabel: "清理",
destructive: true,
});
if (!ok) return;
try {
await fetchJson("/api/events/purge", {
method: "POST",
body: JSON.stringify({ older_than_days: 7 }),
});
toast.push("已清理 7 天前的事件", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}}
className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-sm text-amber-100"
>
🧹 清理 7 天前
</button>
<a
href={`/api/events/export?format=csv${kind ? `&kind=${encodeURIComponent(kind)}` : ""}${platform ? `&platform=${encodeURIComponent(platform)}` : ""}${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)}` : ""}${platform ? `&platform=${encodeURIComponent(platform)}` : ""}${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>
{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="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",
};
return (
<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>
<div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
<span>{fmtTs(ev.ts)}</span>
<span className={`rounded-md border px-1.5 py-0.5 ${meta.color}`}>{meta.label}</span>
<PlatformBadge platform={detectPlatform(ev)} />
{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>
</button>
);
})}
</div>
{!loading && events.length === 0 ? (
<EmptyState emoji="🛰️" title="雷达静默中" desc="还没有事件。开播、停播或风控触发后会出现在这条时间线上。" />
) : null}
{!loading && events.length > 0 && events.length < total ? (
<div className="mt-6 flex justify-center">
<button
type="button"
disabled={loadingMore}
onClick={() => void load({ append: true, offset: events.length })}
className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-5 py-2.5 text-sm text-slate-200 hover:bg-white/10 disabled:opacity-50"
>
{loadingMore ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
加载更多({events.length}/{total})
</button>
</div>
) : null}
{detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null}
</Shell>
);
}

View File

@ -0,0 +1,867 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { Modal } from "@/components/Modal";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
import { groupLiveRef } from "@/lib/youtubeLive";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Group = {
id: string;
name: string;
platform: string;
channel_url: string;
channel_key?: string;
handle?: string;
urls?: string[];
url_count?: number;
note?: string;
enabled: boolean;
last_status?: string;
last_title?: string;
last_live_url?: string;
last_checked_at?: number;
next_check_at?: number;
last_error?: string;
updated_at?: number;
};
type ChannelStat = {
group_id?: string | null;
name?: string;
channel_id?: string;
channel_url?: string;
handle?: string;
enabled?: boolean | null;
last_status?: string;
last_title?: string;
last_live_url?: string;
sessions?: number;
hours_total?: number;
last_started_at?: number | null;
active?: number;
room_id?: string;
};
type RecentSession = {
id: string;
anchor_name?: string;
title?: string;
room_id?: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
status?: string;
source_url?: string;
};
const emptyForm = {
name: "",
channel_url: "",
urls: "",
note: "",
enabled: true,
};
export default function GroupsPage() {
const confirm = useConfirm();
const toast = useToast();
const [tab, setTab] = useState<"monitor" | "analytics">("monitor");
const [groups, setGroups] = useState<Group[]>([]);
const [total, setTotal] = useState(0);
const [q, setQ] = useState("");
const [enabledFilter, setEnabledFilter] = useState("");
const [form, setForm] = useState(emptyForm);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
const [edit, setEdit] = useState<Group | null>(null);
const [editForm, setEditForm] = useState(emptyForm);
const [editBusy, setEditBusy] = useState(false);
const [probeBusy, setProbeBusy] = useState("");
const [probeInfo, setProbeInfo] = useState<Record<string, any>>({});
const [monStatus, setMonStatus] = useState<any>(null);
const [ytStats, setYtStats] = useState<RelayStats | null>(null);
const [channelStats, setChannelStats] = useState<ChannelStat[]>([]);
const [recentSessions, setRecentSessions] = useState<RecentSession[]>([]);
const [analyticsBusy, setAnalyticsBusy] = useState(false);
const [dateFrom, setDateFrom] = useState(() => shiftBeijingISO(todayBeijingISO(), -29));
const [dateTo, setDateTo] = useState(() => todayBeijingISO());
const query = useMemo(() => {
const p = new URLSearchParams();
p.set("platform", "youtube");
if (q.trim()) p.set("q", q.trim());
if (enabledFilter === "1") p.set("enabled", "true");
if (enabledFilter === "0") p.set("enabled", "false");
p.set("limit", "500");
return p.toString();
}, [q, enabledFilter]);
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const [data, mon] = await Promise.all([
fetchJson(`/api/groups?${query}`),
fetchJson("/api/youtube-monitor/status").catch(() => null),
]);
setGroups(data.groups || []);
setTotal(Number(data.total) || 0);
if (!silent) setSelected(new Set());
if (mon) setMonStatus(mon);
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [query]);
const loadAnalytics = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) setAnalyticsBusy(true);
try {
const p = new URLSearchParams();
if (dateFrom) p.set("date_from", dateFrom);
if (dateTo) p.set("date_to", dateTo);
p.set("top_anchors", "25");
const data = await fetchJson(`/api/groups/analytics?${p}`);
setYtStats((data.stats || null) as RelayStats | null);
setChannelStats((data.channels || []) as ChannelStat[]);
setRecentSessions((data.recent_sessions || []) as RecentSession[]);
if (data.monitor) setMonStatus(data.monitor);
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setAnalyticsBusy(false);
}
}, [dateFrom, dateTo]);
useAutoRefresh(load, { intervalMs: 20000, enabled: tab === "monitor" });
useAutoRefresh(loadAnalytics, { intervalMs: 30000, enabled: tab === "analytics" });
useEffect(() => {
if (typeof window === "undefined") return;
const p = new URLSearchParams(window.location.search);
const channel = p.get("channel") || p.get("url") || "";
const name = p.get("name") || "";
const t = p.get("tab");
if (t === "analytics") setTab("analytics");
if (channel || name) {
setForm((f) => ({
...f,
channel_url: channel || f.channel_url,
name: name || f.name,
}));
}
}, []);
useEffect(() => {
if (tab === "analytics") void loadAnalytics();
}, [tab, loadAnalytics]);
const urlLineCount = form.urls
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l && !l.startsWith("#")).length;
async function createGroup() {
setBusy("create");
setError("");
setMsg("");
try {
await fetchJson("/api/groups", {
method: "POST",
body: JSON.stringify({
name: form.name,
channel_url: form.channel_url,
urls: form.urls,
note: form.note,
platform: "youtube",
enabled: form.enabled,
}),
});
setForm(emptyForm);
setMsg("已创建分组");
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
function openEdit(g: Group) {
setEdit(g);
setEditForm({
name: g.name || "",
channel_url: g.channel_url || "",
urls: (g.urls || []).join("\n"),
note: g.note || "",
enabled: !!g.enabled,
});
}
async function saveEdit() {
if (!edit) return;
setEditBusy(true);
setError("");
try {
await fetchJson(`/api/groups/${edit.id}`, {
method: "PATCH",
body: JSON.stringify({
name: editForm.name,
channel_url: editForm.channel_url,
urls: editForm.urls,
note: editForm.note,
enabled: editForm.enabled,
}),
});
setMsg(`已更新 ${editForm.name}`);
setEdit(null);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setEditBusy(false);
}
}
async function removeOne(id: string) {
const ok = await confirm({
title: "删除分组",
message: "确定删除该 YouTube 分组?关联监控将停止。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(id);
try {
await fetchJson(`/api/groups/${id}`, { method: "DELETE" });
toast.push("分组已删除", "ok");
await load();
} catch (e) {
setError((e as Error).message);
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
async function probeOne(id: string) {
setProbeBusy(id);
setError("");
try {
const data = await fetchJson(`/api/groups/${id}/probe`, { method: "POST" });
const probe = data.probe || data.result || {};
const g = data.group || {};
setProbeInfo((prev) => ({ ...prev, [id]: { ...probe, last_status: g.last_status } }));
const live = Boolean(probe.is_live || g.last_status === "live");
setMsg(
live
? `${g.name || probe.title || "频道"} 正在直播${g.last_title || probe.live?.title ? `:${g.last_title || probe.live?.title}` : ""}`
: `${g.name || probe.title || "频道"} 当前未开播`,
);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setProbeBusy("");
}
}
async function toggleYtMonitor(enabled: boolean) {
setBusy(enabled ? "mon-on" : "mon-off");
try {
await fetchJson(enabled ? "/api/youtube-monitor/start" : "/api/youtube-monitor/stop", { method: "POST" });
setMsg(enabled ? "已开启 YouTube 分组轮询" : "已暂停 YouTube 分组轮询");
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function bulk(action: "enable" | "disable" | "delete") {
const ids = Array.from(selected);
if (!ids.length) {
setMsg("请先勾选分组");
return;
}
if (action === "delete") {
const ok = await confirm({
title: "批量删除分组",
message: `确定删除选中的 ${ids.length} 个分组?`,
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
}
setBusy(action);
setError("");
try {
const data = await fetchJson("/api/groups/bulk", {
method: "POST",
body: JSON.stringify({ action, ids }),
});
setMsg(`批量${action}:${data.affected || ids.length}`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
function toggleAll(checked: boolean) {
setSelected(checked ? new Set(groups.map((g) => g.id)) : new Set());
}
function toggleOne(id: string, checked: boolean) {
setSelected((prev) => {
const next = new Set(prev);
if (checked) next.add(id);
else next.delete(id);
return next;
});
}
return (
<Shell>
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">📺 YouTube 频道分组</h2>
<p className="text-sm text-slate-400">
开播轮询入库场次,与抖音共用同一套时长 / 时段 / 排行分析。
</p>
</div>
<div className="flex flex-wrap gap-2">
<Link
to="/sessions?platform=youtube"
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
场次明细
</Link>
<Link
to="/slots?platform=youtube"
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
时段分析
</Link>
<a
href="/api/groups/export"
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
<Download className="h-4 w-4" />
导出 CSV
</a>
</div>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => {
setTab("monitor");
if (typeof window !== "undefined") {
const u = new URL(window.location.href);
u.searchParams.delete("tab");
window.history.replaceState({}, "", u.pathname + u.search);
}
}}
className={`rounded-xl px-4 py-2 text-sm ${
tab === "monitor" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
}`}
>
监控
</button>
<button
type="button"
onClick={() => {
setTab("analytics");
if (typeof window !== "undefined") {
const u = new URL(window.location.href);
u.searchParams.set("tab", "analytics");
window.history.replaceState({}, "", u.pathname + u.search);
}
}}
className={`rounded-xl px-4 py-2 text-sm ${
tab === "analytics" ? "bg-amber-500/20 text-amber-50 ring-1 ring-amber-400/30" : "bg-white/5 text-slate-400"
}`}
>
数据分析
</button>
</div>
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm">
<span className={monStatus?.yt_monitor_enabled ? "text-teal-300" : "text-slate-500"}>
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"}
{monStatus?.running ? "" : " · 任务未启动"}
</span>
<span className="text-slate-500">
启用 {monStatus?.groups?.enabled ?? "—"} · 直播中 {monStatus?.groups?.live ?? "—"} · 积压{" "}
{monStatus?.groups?.overdue ?? "—"} · 已检 {monStatus?.checked_total ?? 0}
</span>
{monStatus?.quiet_hours_active ? <span className="text-amber-300">静默时段中</span> : null}
{monStatus?.youtube_svc?.ok === false ? (
<span className="text-rose-300">youtube-svc 异常</span>
) : null}
<button
type="button"
disabled={busy === "mon-on"}
onClick={() => void toggleYtMonitor(true)}
className="rounded-lg border border-teal-500/30 px-2 py-1 text-xs text-teal-100"
>
开启轮询
</button>
<button
type="button"
disabled={busy === "mon-off"}
onClick={() => void toggleYtMonitor(false)}
className="rounded-lg border border-white/10 px-2 py-1 text-xs"
>
暂停轮询
</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}
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm">{msg}</div> : null}
{tab === "analytics" ? (
<div className="space-y-4">
<div className="flex flex-wrap items-end gap-2 rounded-xl border border-white/10 bg-black/25 p-3">
<label className="text-xs text-slate-400">
起
<input
type="date"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
/>
</label>
<label className="text-xs text-slate-400">
止
<input
type="date"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
/>
</label>
<button
type="button"
onClick={() => void loadAnalytics()}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
{analyticsBusy ? <Loader2 className="inline h-3.5 w-3.5 animate-spin" /> : null} 刷新分析
</button>
<span className="text-xs text-slate-500">北京日 · 与抖音场次统计同一口径</span>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{[
["场次", String(ytStats?.overview?.sessions ?? 0), "YouTube 开播记录"],
["在播", String(ytStats?.overview?.active_sessions ?? 0), "当前未结场"],
["累计小时", Number(ytStats?.overview?.total_hours || 0).toFixed(1), "含进行中时长"],
["频道数", String(ytStats?.overview?.unique_anchors ?? channelStats.length), "有场次的频道"],
].map(([label, value, hint]) => (
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
<div className="text-xs text-slate-500">{label}</div>
<div className="mt-1 font-display text-2xl text-white">{value}</div>
<div className="mt-1 text-[11px] text-slate-500">{hint}</div>
</div>
))}
</div>
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 font-display text-sm font-medium text-slate-100">可视化分析</h3>
<SessionCharts stats={ytStats} />
</section>
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
<div className="border-b border-white/5 px-4 py-3 text-sm font-medium text-slate-100">频道排行</div>
<div className="overflow-x-auto">
<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-2">频道</th>
<th className="px-3 py-2">状态</th>
<th className="px-3 py-2">场次</th>
<th className="px-3 py-2">小时</th>
<th className="px-3 py-2">最近开播</th>
</tr>
</thead>
<tbody>
{channelStats.map((ch) => (
<tr key={String(ch.group_id || ch.room_id || ch.name)} className="border-t border-white/5">
<td className="px-3 py-2">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-slate-100">{ch.name || "—"}</span>
{ch.group_id ? <YouTubeLiveBadge refKey={groupLiveRef(ch.group_id)} compact showOffline /> : null}
</div>
<div className="font-mono text-[10px] text-slate-500">{ch.channel_id || ch.room_id || "—"}</div>
</td>
<td className="px-3 py-2">
<span className={Number(ch.active) > 0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}>
{Number(ch.active) > 0 || ch.last_status === "live" ? "LIVE" : ch.last_status || "offline"}
</span>
</td>
<td className="px-3 py-2 tabular-nums">{ch.sessions ?? 0}</td>
<td className="px-3 py-2 tabular-nums">{Number(ch.hours_total || 0).toFixed(1)}</td>
<td className="px-3 py-2 text-slate-400">{ch.last_started_at ? fmtTs(ch.last_started_at) : "—"}</td>
</tr>
))}
{!channelStats.length ? (
<tr>
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
暂无 YouTube 场次。开启分组轮询并等频道开播后会出现在这里。
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<span className="text-sm font-medium text-slate-100">最近场次</span>
<Link to="/sessions?platform=youtube" className="text-xs text-teal-300 hover:underline">
全部 →
</Link>
</div>
<div className="overflow-x-auto">
<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-2">频道</th>
<th className="px-3 py-2">标题</th>
<th className="px-3 py-2">开始</th>
<th className="px-3 py-2">时长</th>
<th className="px-3 py-2">状态</th>
</tr>
</thead>
<tbody>
{recentSessions.map((s) => (
<tr key={s.id} className="border-t border-white/5">
<td className="px-3 py-2 text-slate-100">{s.anchor_name || s.room_id || "—"}</td>
<td className="max-w-[240px] truncate px-3 py-2 text-slate-400">{s.title || "—"}</td>
<td className="px-3 py-2 text-slate-400">{fmtTs(s.started_at)}</td>
<td className="px-3 py-2 tabular-nums text-slate-300">{fmtDuration(s.duration_seconds)}</td>
<td className="px-3 py-2">{s.ended_at ? "已结束" : <span className="text-rose-300">在播</span>}</td>
</tr>
))}
{!recentSessions.length ? (
<tr>
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
暂无场次
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
</div>
) : null}
{tab === "monitor" ? (
<>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2">
<label className="block text-xs text-slate-400">
分组名称
<input
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
placeholder="例如:Google Developers"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
频道 URL / @handle / UC…
<input
value={form.channel_url}
onChange={(e) => setForm((f) => ({ ...f, channel_url: e.target.value }))}
placeholder="https://www.youtube.com/@xxx 或 UC…"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400 md:col-span-2">
分组内 URL(频道未播时也会探测,每行一条,最多 6 条,共 {urlLineCount})
<textarea
value={form.urls}
onChange={(e) => setForm((f) => ({ ...f, urls: e.target.value }))}
rows={4}
placeholder={"https://www.youtube.com/watch?v=...\nhttps://youtu.be/..."}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
/>
</label>
<label className="block text-xs text-slate-400">
备注
<input
value={form.note}
onChange={(e) => setForm((f) => ({ ...f, note: e.target.value }))}
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 justify-between gap-3">
<label className="flex items-center gap-2 text-sm text-slate-300">
<input
type="checkbox"
checked={form.enabled}
onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}
/>
启用
</label>
<button
type="button"
disabled={!form.name.trim() || !form.channel_url.trim() || busy === "create"}
onClick={() => void createGroup()}
className="inline-flex items-center gap-2 rounded-lg bg-teal-500/20 px-4 py-2 text-sm text-teal-100 ring-1 ring-teal-400/30 hover:bg-teal-500/30 disabled:opacity-50"
>
{busy === "create" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
新建分组
</button>
</div>
</div>
<div className="mb-4 flex flex-wrap items-center gap-2">
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="搜索名称 / 频道 / URL / 备注"
className="min-w-[200px] flex-1 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<select
value={enabledFilter}
onChange={(e) => setEnabledFilter(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value="">全部状态</option>
<option value="1">仅启用</option>
<option value="0">仅停用</option>
</select>
<button
type="button"
onClick={() => void load()}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
刷新 {loading ? <Loader2 className="ml-1 inline h-3 w-3 animate-spin" /> : null}
</button>
<button type="button" onClick={() => void bulk("enable")} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
批量启用
</button>
<button type="button" onClick={() => void bulk("disable")} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
批量停用
</button>
<button
type="button"
onClick={() => void bulk("delete")}
className="rounded-lg border border-rose-500/30 px-3 py-2 text-sm text-rose-200"
>
批量删除
</button>
<span className="text-xs text-slate-500">共 {total} · 已选 {selected.size}</span>
</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">
<input
type="checkbox"
checked={groups.length > 0 && selected.size === groups.length}
onChange={(e) => toggleAll(e.target.checked)}
/>
</th>
<th className="px-3 py-3">名称</th>
<th className="px-3 py-3">频道</th>
<th className="px-3 py-3">URL 数</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>
{groups.map((g) => (
<tr key={g.id} className="border-t border-white/5 align-top">
<td className="px-3 py-3">
<input
type="checkbox"
checked={selected.has(g.id)}
onChange={(e) => toggleOne(g.id, e.target.checked)}
/>
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap items-center gap-2">
<div className="font-medium text-white">{g.name}</div>
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} compact />
</div>
{g.note ? <div className="mt-1 text-xs text-slate-500">{g.note}</div> : null}
{g.last_title || probeInfo[g.id]?.live?.title ? (
<div className="mt-1 max-w-[220px] truncate text-xs text-slate-500">
{g.last_title || probeInfo[g.id]?.live?.title}
</div>
) : null}
</td>
<td className="px-3 py-3">
<a
href={g.channel_url}
target="_blank"
rel="noreferrer"
className="font-mono text-xs text-teal-300/90 hover:underline"
>
{g.channel_key || g.channel_url}
</a>
{g.handle ? <div className="mt-1 text-xs text-slate-500">@{g.handle}</div> : null}
</td>
<td className="px-3 py-3">
<div>{g.url_count ?? (g.urls || []).length}</div>
{(g.urls || []).slice(0, 2).map((u) => (
<div key={u} className="mt-0.5 max-w-[220px] truncate font-mono text-[11px] text-slate-500">
{u}
</div>
))}
{(g.urls || []).length > 2 ? (
<div className="text-[11px] text-slate-600">+{(g.urls || []).length - 2} more</div>
) : null}
</td>
<td className="px-3 py-3">
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} showTitle />
{g.last_status === "error" ? (
<span className="mt-1 block text-amber-300" title={g.last_error || ""}>
错误
</span>
) : null}
{g.last_checked_at ? (
<div className="mt-1 text-[11px] text-slate-600">{fmtTs(g.last_checked_at)}</div>
) : null}
</td>
<td className="px-3 py-3">
<span className={g.enabled ? "text-teal-300" : "text-slate-500"}>{g.enabled ? "启用" : "停用"}</span>
</td>
<td className="px-3 py-3 text-slate-400">{fmtTs(g.updated_at)}</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => void probeOne(g.id)}
className="inline-flex items-center gap-1 rounded border border-teal-500/30 px-2 py-1 text-xs text-teal-100"
>
{probeBusy === g.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Zap className="h-3 w-3" />}
探测
</button>
<button
type="button"
onClick={() => openEdit(g)}
className="inline-flex items-center gap-1 rounded border border-white/10 px-2 py-1 text-xs"
>
<Pencil className="h-3 w-3" />
编辑
</button>
<button
type="button"
onClick={() => void removeOne(g.id)}
className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200"
>
{busy === g.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
删除
</button>
</div>
</td>
</tr>
))}
{groups.length === 0 && !loading ? (
<tr>
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">
暂无 YouTube 分组
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</>
) : null}
<Modal open={!!edit} onClose={() => setEdit(null)}>
{edit ? (
<div className="grid gap-3">
<h3 className="font-display text-lg font-semibold text-white">编辑分组</h3>
<label className="block text-xs text-slate-400">
分组名称
<input
value={editForm.name}
onChange={(e) => setEditForm((f) => ({ ...f, name: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
频道 URL
<input
value={editForm.channel_url}
onChange={(e) => setEditForm((f) => ({ ...f, channel_url: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
分组内 URL(多行)
<textarea
value={editForm.urls}
onChange={(e) => setEditForm((f) => ({ ...f, urls: e.target.value }))}
rows={6}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
/>
</label>
<label className="block text-xs text-slate-400">
备注
<input
value={editForm.note}
onChange={(e) => setEditForm((f) => ({ ...f, note: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="flex items-center gap-2 text-sm text-slate-300">
<input
type="checkbox"
checked={editForm.enabled}
onChange={(e) => setEditForm((f) => ({ ...f, enabled: e.target.checked }))}
/>
启用
</label>
<div className="flex justify-end gap-2 pt-2">
<button type="button" onClick={() => setEdit(null)} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
取消
</button>
<button
type="button"
disabled={editBusy || !editForm.name.trim() || !editForm.channel_url.trim()}
onClick={() => void saveEdit()}
className="inline-flex items-center gap-2 rounded-lg bg-teal-500/20 px-4 py-2 text-sm text-teal-100 ring-1 ring-teal-400/30 disabled:opacity-50"
>
{editBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
保存
</button>
</div>
</div>
) : null}
</Modal>
</Shell>
);
}

View File

@ -0,0 +1,107 @@
import { Suspense } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { FormEvent, useEffect, useState } from "react";
import { Loader2, LockKeyhole } from "lucide-react";
import { BrandMark } from "@/components/ui";
import { clearAuthRedirect, fetchJson } from "@/lib/api";
import { SKIP_DESKTOP_AUTH } from "@/lib/authFlags";
function LoginForm() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const next = searchParams.get("next") || "/";
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
// --- auth temporarily bypassed ---
if (SKIP_DESKTOP_AUTH) {
navigate(next || "/", { replace: true });
return;
}
void fetchJson("/api/auth/status")
.then((d) => {
if (d.authenticated) navigate(next);
})
.catch(() => {});
}, [next, navigate]);
async function onSubmit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError("");
try {
await fetchJson("/api/auth/login", {
method: "POST",
body: JSON.stringify({ username, password }),
});
clearAuthRedirect();
navigate(next);
} catch (err) {
setError((err as Error).message || "登录失败");
} finally {
setBusy(false);
}
}
return (
<div className="relative flex min-h-screen items-center justify-center px-4">
<div className="ambient-orb a" />
<div className="ambient-orb b" />
<div className="relative z-10 w-full max-w-md animate-fade-up rounded-2xl border border-white/10 bg-black/40 p-8 shadow-2xl backdrop-blur-md">
<div className="mb-6 flex flex-col items-center text-center">
<BrandMark className="mb-4 h-14 w-14" />
<p className="font-display text-xs uppercase tracking-[0.28em] text-teal-300/90">Live Radar</p>
<h1 className="mt-2 font-display text-2xl font-bold text-white">登录监控中心</h1>
<p className="mt-2 text-sm text-slate-500">抖音 + YouTube 直播监控 · 请登录后继续</p>
</div>
<form onSubmit={(e) => void onSubmit(e)} className="space-y-4">
<label className="block text-xs text-slate-400">
用户名
<input
type="text"
autoComplete="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="用户名"
className="mt-1 w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2.5 text-sm text-white outline-none ring-teal-400/30 focus:ring-2"
required
/>
</label>
<label className="block text-xs text-slate-400">
密码
<input
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2.5 text-sm text-white outline-none ring-teal-400/30 focus:ring-2"
required
/>
</label>
{error ? <div className="text-sm text-rose-300">{error}</div> : null}
<button
type="submit"
disabled={busy}
className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-[#ff2d55] px-4 py-2.5 text-sm font-medium text-white hover:bg-[#ff4d6d] disabled:opacity-60"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <LockKeyhole className="h-4 w-4" />}
登录
</button>
</form>
</div>
</div>
);
}
export default function LoginPage() {
return (
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-slate-500">加载中…</div>}>
<LoginForm />
</Suspense>
);
}

View File

@ -0,0 +1,774 @@
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { AnimatedNumber, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { YouTubeLiveTicker } from "@/components/YouTubeLiveTicker";
import { useToast } from "@/components/Toast";
import { useConfirm } from "@/components/ConfirmDialog";
import { ImageLightbox } from "@/components/ImageLightbox";
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
import { fetchJson, fmtTs, sessionCoverSrc, todayBeijingISO, beijingHourFromTs, beijingParts, detectPlatform } from "@/lib/api";
import { liveElapsed, useEventStream, useNow, type RefreshOpts } from "@/lib/realtime";
import { channelLiveRef, useYouTubeLiveCount } from "@/lib/youtubeLive";
type MonitorStatus = {
running: boolean;
monitor_enabled: boolean;
checked_total: number;
live_count: number;
room_count: number;
blacklist_count: number;
events_count?: number;
risk_paused_until: number;
last_error: string;
last_check_at: number;
quiet_hours_active?: boolean;
quiet_hours_priority_only?: boolean;
error_rooms_1h?: number;
overdue?: { count?: number; max_lag_sec?: 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 = {
id: string;
url: string;
room_id: string;
last_status: string;
last_anchor?: string;
tags?: string[] | string;
};
type UpcomingItem = {
anchor_name?: string;
room_id?: string;
room_pk?: string;
url?: string;
priority?: boolean;
last_status?: string;
peak_slot_label?: string;
eta_ts?: number;
next_open_hint?: { label?: string; based_on?: string };
typical_open_hint?: string;
};
type EventItem = {
id: string;
ts: number;
kind?: string;
message?: string;
anchor_name?: string;
room_id?: string;
session_id?: string;
};
type ActiveSession = {
id: string;
anchor_name?: string;
room_id?: string;
room_pk?: string;
source_url?: string;
started_at?: number;
cover_url?: string;
cover_proxy_url?: string;
};
export default function HomePage() {
const [stats, setStats] = useState<RelayStats | null>(null);
const [ytStats, setYtStats] = useState<RelayStats | null>(null);
const [status, setStatus] = useState<MonitorStatus | null>(null);
const [ytStatus, setYtStatus] = useState<Record<string, any> | null>(null);
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);
const [detail, setDetail] = useState<SessionDetail | null>(null);
const [opsBusy, setOpsBusy] = useState("");
const toast = useToast();
const confirm = useConfirm();
const now = useNow(1000);
const { connected, last, tick } = useEventStream(false); // desktop: poll only — SSE was wedging Windows API
const ytLiveCount = useYouTubeLiveCount();
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const iso = todayBeijingISO();
const desktop = Boolean(window.desktop);
if (desktop) {
// Windows desktop: serialize SQLite-backed API calls (avoid 20s timeouts)
const m = await fetchJson("/api/monitor/status");
const a = await fetchJson("/api/sessions/active");
const s = await fetchJson("/api/sessions/stats?top_anchors=25");
const e = await fetchJson("/api/events?limit=20");
const daySessions = await fetchJson(`/api/sessions?date_from=${iso}&date_to=${iso}&limit=200`);
const ytS = await fetchJson("/api/sessions/stats?platform=youtube&top_anchors=10").catch(() => null);
const yt = await fetchJson("/api/youtube-monitor/status").catch(() => null);
const r = await fetchJson("/api/rooms?limit=200").catch(() => ({ rooms: [] }));
const up = await fetchJson("/api/anchors/upcoming?limit=12").catch(() => ({ items: [] }));
setStats(s);
setYtStats(ytS);
setStatus(m);
setYtStatus(yt);
setRooms(r.rooms || []);
setEvents(e.events || []);
setUpcoming(up.items || []);
const sessions = (a.sessions || []) as ActiveSession[];
const seen = new Set<string>();
setActive(
sessions.filter((s) => {
const key = s.room_id || s.id;
if (!key || seen.has(key)) return false;
seen.add(key);
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 = beijingHourFromTs(ts);
buckets[Math.min(5, Math.floor(hour / 4))] += 1;
}
setTodaySlots(buckets);
return;
}
const m = await fetchJson("/api/monitor/status");
const a = await fetchJson("/api/sessions/active");
const [s, e, daySessions] = await Promise.all([
fetchJson("/api/sessions/stats?top_anchors=25"),
fetchJson("/api/events?limit=20"),
fetchJson(`/api/sessions?date_from=${iso}&date_to=${iso}&limit=200`),
]);
const ytS = await fetchJson("/api/sessions/stats?platform=youtube&top_anchors=10").catch(() => null);
const yt = await fetchJson("/api/youtube-monitor/status").catch(() => null);
const r = await fetchJson("/api/rooms?limit=200").catch(() => ({ rooms: [] }));
const up = await fetchJson("/api/anchors/upcoming?limit=12").catch(() => ({ items: [] }));
setStats(s);
setYtStats(ytS);
setStatus(m);
setYtStatus(yt);
setRooms(r.rooms || []);
setEvents(e.events || []);
setUpcoming(up.items || []);
const sessions = (a.sessions || []) as ActiveSession[];
const seen = new Set<string>();
setActive(
sessions.filter((s) => {
const key = s.room_id || s.id;
if (!key || seen.has(key)) return false;
seen.add(key);
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 = beijingHourFromTs(ts);
buckets[Math.min(5, Math.floor(hour / 4))] += 1;
}
setTodaySlots(buckets);
} catch (err) {
if (!silent) setError((err as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, []);
useEffect(() => {
void load({ silent: false });
const t = setInterval(() => void load({ silent: true }), 20000);
return () => clearInterval(t);
}, [load]);
useEffect(() => {
if (!last?.message) return;
setEvents((prev) => {
const next = [
{
...(last as EventItem),
id: last.id || `${tick}`,
session_id: last.session_id,
},
...prev.filter((x) => x.id !== last.id),
];
return next.slice(0, 30);
});
if (last.kind === "live" || last.kind === "risk" || last.kind === "offline") {
void load({ silent: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);
const priorityRoomIds = new Set(
rooms
.filter((r) => isFavorited(r.tags))
.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) => {
const isYt = detectPlatform(s) === "youtube";
if (focusOnly && isYt) return false;
return !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;
const missedOpens = upcoming.filter(
(u) =>
u.priority &&
Number(u.eta_ts || 0) > 0 &&
Number(u.eta_ts) * 1000 < now &&
u.last_status !== "live",
);
async function toggleFocus(roomId?: string) {
if (!roomId || roomId.startsWith("yt:")) {
toast.push("YouTube 场次请到「分组」管理", "warn");
return;
}
const room = rooms.find((r) => r.room_id === roomId);
try {
const { roomQuickAction } = await import("@/components/RoomQuickActions");
await roomQuickAction(
room && isFavorited(room.tags) ? "unfavorite" : "favorite",
{ room_pk: room?.id, room_id: roomId, url: room?.url },
);
toast.push(room && isFavorited(room.tags) ? "已取消收藏" : "已收藏", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "warn");
}
}
async function openSessionDetail(sessionId?: string) {
if (!sessionId) return;
try {
const data = await fetchJson(`/api/sessions/${sessionId}`);
setDetail((data.session || data) as SessionDetail);
} catch (e) {
toast.push((e as Error).message, "warn");
}
}
async function toggleMonitor(enabled: boolean) {
setOpsBusy(enabled ? "start" : "stop");
try {
await fetchJson(enabled ? "/api/monitor/start" : "/api/monitor/stop", { method: "POST" });
toast.push(enabled ? "监控已恢复" : "监控已暂停", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "warn");
} finally {
setOpsBusy("");
}
}
async function syncCookie() {
setOpsBusy("cookie");
try {
const data = await fetchJson("/api/settings/sync-cookie", { method: "POST" });
toast.push(data.message || (data.ok ? "Cookie 已同步" : "同步完成"), "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "warn");
} finally {
setOpsBusy("");
}
}
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>
<section className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div>
<div className="mb-2 flex flex-wrap items-center gap-2">
{status?.monitor_enabled ? <LivePulse label="MONITOR ON" /> : (
<span className="rounded-md border border-slate-500/30 bg-slate-500/10 px-2 py-1 text-[11px] text-slate-300">⏸ 已暂停</span>
)}
{liveRooms.length > 0 ? <LivePulse label={`抖音 ${liveRooms.length} 路`} /> : null}
{ytLiveCount > 0 ? (
<Link to="/groups" className="rounded-md border border-red-500/30 bg-red-500/10 px-2 py-1 text-[11px] text-red-100">
<span className="inline-flex items-center gap-1.5">
<span className="live-dot" />
YT 在播 {ytLiveCount}
</span>
</Link>
) : ytStatus?.yt_monitor_enabled !== false && ytStatus?.running ? (
<Link to="/groups" className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400">
▶ YT 轮询中 · {String(ytStatus?.groups?.enabled ?? "—")} 组
</Link>
) : (
<Link to="/settings" className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-500">
▶ YT 已暂停
</Link>
)}
<span className={`rounded-md border px-2 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 ? "🟢 SSE 已连接" : "⚪ SSE 重连中"}
</span>
{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.quiet_hours_priority_only ? "·仅重点" : ""} {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 ? (
cookieStale || cookieWarn ? (
<button
type="button"
disabled={opsBusy === "cookie"}
onClick={() => void syncCookie()}
className={`rounded-md border px-2 py-1 text-[11px] ${
cookieStale
? "border-rose-500/30 bg-rose-500/10 text-rose-100"
: "border-amber-500/30 bg-amber-500/10 text-amber-100"
}`}
title="点击从 sh2 同步 Cookie"
>
🍪 Cookie {cookieAge != null ? `${cookieAge}h` : "陈旧"} · 点此同步
</button>
) : (
<span
className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-300"
title={status.cookie.updated_at ? `更新于 ${fmtTs(status.cookie.updated_at)}` : "Cookie 年龄未知"}
>
🍪 Cookie {cookieAge != null ? `${cookieAge}h` : "已配置"}
</span>
)
) : (
<Link to="/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 to="/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>
)}
{Number(status?.overdue?.count || 0) > 0 ? (
<Link
to="/rooms?overdue=1"
className="rounded-md border border-violet-500/30 bg-violet-500/10 px-2 py-1 text-[11px] text-violet-100"
title={`最大滞后 ${Math.round(Number(status?.overdue?.max_lag_sec || 0))}s`}
>
队列积压 {status?.overdue?.count}
</Link>
) : null}
{missedOpens.length > 0 ? (
<span className="rounded-md border border-rose-500/30 bg-rose-500/10 px-2 py-1 text-[11px] text-rose-100">
重点延误 {missedOpens.length}
</span>
) : null}
{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">抖音 + YouTube 双平台开播态势 · 时段规律 · 事件回放</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>
{status?.monitor_enabled ? (
<button
type="button"
disabled={Boolean(opsBusy)}
onClick={() => void toggleMonitor(false)}
className="rounded-xl border border-slate-500/30 bg-slate-500/10 px-3 py-2 text-sm text-slate-200"
>
{opsBusy === "stop" ? <Loader2 className="inline h-4 w-4 animate-spin" /> : "⏸"} 暂停
</button>
) : (
<button
type="button"
disabled={Boolean(opsBusy)}
onClick={() => void toggleMonitor(true)}
className="rounded-xl border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
>
{opsBusy === "start" ? <Loader2 className="inline h-4 w-4 animate-spin" /> : "▶"} 恢复监控
</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" />}
刷新
</button>
{riskActive ? (
<button
type="button"
onClick={async () => {
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
await load();
}}
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100"
>
<ShieldOff className="h-4 w-4" />
解除风控
</button>
) : null}
</div>
</section>
{error ? <div className="mb-4 animate-fade-up rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
{missedOpens.length > 0 ? (
<section className="mb-6 rounded-2xl border border-rose-500/30 bg-rose-500/10 p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="font-display text-sm font-medium text-rose-100">⏰ 重点延误开播(已过预计时间仍未开播)</h3>
<span className="text-xs text-rose-200/80">{missedOpens.length} 个</span>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{missedOpens.slice(0, 9).map((u) => {
const lateMin = Math.max(1, Math.round((now / 1000 - Number(u.eta_ts || 0)) / 60));
return (
<div key={`miss-${u.room_id}-${u.anchor_name}`} className="flex items-center gap-2 rounded-xl border border-rose-500/20 bg-black/25 px-3 py-2">
<Link
to={`/anchors?q=${encodeURIComponent(u.anchor_name || u.room_id || "")}`}
className="min-w-0 flex-1"
>
<div className="truncate text-sm font-medium text-white">{u.anchor_name}</div>
<div className="text-[11px] text-rose-200/90">延误约 {lateMin} 分钟 · {u.next_open_hint?.label || "—"}</div>
</Link>
{u.room_pk ? (
<button
type="button"
onClick={async () => {
try {
await fetchJson(`/api/monitor/check/${u.room_pk}`, { method: "POST" });
toast.push(`已检查 ${u.anchor_name || u.room_id}`, "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "warn");
}
}}
className="shrink-0 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs hover:bg-white/10"
>
立刻检查
</button>
) : null}
</div>
);
})}
</div>
</section>
) : null}
<div className="stagger mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-6">
<StatTile emoji="🏠" label="抖音直播间" value={<AnimatedNumber value={status?.room_count || 0} />} hint="已纳入监控队列" accent="sky" />
<StatTile emoji="🔴" label="抖音在播" value={<AnimatedNumber value={status?.live_count || 0} />} hint="正在直播中的房间" accent="rose" />
<StatTile emoji="▶️" label="YT 在播" value={<AnimatedNumber value={ytLiveCount} />} hint={`启用分组 ${String(ytStatus?.groups?.enabled ?? "—")}`} accent="amber" />
<StatTile
emoji="📺"
label="YT 场次/时长"
value={
<span className="tabular-nums">
<AnimatedNumber value={Number(ytStats?.overview?.sessions || 0)} />
<span className="mx-1 text-base text-slate-500">/</span>
<AnimatedNumber value={Number(ytStats?.overview?.total_hours || 0)} decimals={1} suffix="h" />
</span>
}
hint="YouTube 历史场次合计"
accent="teal"
/>
<StatTile emoji="⏱️" label="全平台时长" value={<AnimatedNumber value={Number(stats?.overview?.total_hours || 0)} decimals={1} suffix="h" />} hint="抖音+YouTube" accent="teal" />
<StatTile emoji="🎯" label="检查次数" value={<AnimatedNumber value={status?.checked_total || 0} />} hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" />
</div>
<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 to="/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(beijingParts().hour / 4));
return (
<Link
key={label}
to={`/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>
{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"
>
{sessionCoverSrc(s) ? (
<button
type="button"
onClick={() => setLightbox(s)}
className="shrink-0 overflow-hidden rounded ring-1 ring-white/10 transition hover:ring-rose-300/50"
title="点击放大"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<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>
)}
<button
type="button"
onClick={() => void openSessionDetail(s.id)}
className="min-w-0 flex-1 text-left"
title="查看场次详情"
>
<div className="truncate text-sm font-medium text-white hover:underline">
<span className="mr-1.5 inline-block align-middle">
<PlatformBadge platform={detectPlatform(s)} />
</span>
{s.anchor_name || s.room_id}
{detectPlatform(s) === "youtube" && s.room_id?.startsWith("yt:UC") ? (
<span className="ml-1.5 inline-block align-middle">
<YouTubeLiveBadge refKey={channelLiveRef(s.room_id.slice(3))} compact />
</span>
) : null}
</div>
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
</button>
<button
type="button"
onClick={async () => {
const ok = await confirm({
title: "结束场次",
message: `结束「${s.anchor_name || s.room_id}」这场?`,
confirmLabel: "结束",
destructive: true,
});
if (!ok) 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>
{detectPlatform(s) === "youtube" ? (
<Link
to="/groups"
className="shrink-0 rounded-lg border border-white/10 bg-black/20 px-2 py-1 text-xs text-slate-400 hover:text-red-100"
title="前往 YouTube 分组"
>
分组
</Link>
) : (
<RoomQuickActions
compact
room={{
room_pk: s.room_pk || rooms.find((r) => r.room_id === s.room_id)?.id,
room_id: s.room_id,
source_url: s.source_url,
anchor_name: s.anchor_name,
}}
favorited={Boolean(s.room_id && priorityRoomIds.has(s.room_id))}
onDone={() => void load()}
onError={(m) => toast.push(m, "warn")}
/>
)}
</div>
))}
</div>
</section>
) : null}
{lightbox && sessionCoverSrc(lightbox) ? (
<ImageLightbox
src={sessionCoverSrc(lightbox)}
title={lightbox.anchor_name || lightbox.room_id || "封面"}
subtitle={lightbox.source_url}
onClose={() => setLightbox(null)}
/>
) : null}
{detail ? (
<SessionDetailModal
session={detail}
onClose={() => setDetail(null)}
onUpdated={() => void load()}
/>
) : null}
{(liveRooms.length > 0 || events.length > 0) ? (
<div className="mb-6 overflow-hidden rounded-2xl border border-rose-500/20 bg-rose-500/5">
<div className="flex items-center gap-2 border-b border-white/5 px-4 py-2 text-xs text-rose-100/80">
<span className="live-dot" />
实时动态条
</div>
<div className="relative overflow-hidden py-3">
<div className="ticker-track gap-8 px-4 text-sm text-slate-200">
{[...liveRooms, ...liveRooms].length ? (
[...liveRooms, ...liveRooms, ...events.slice(0, 8), ...events.slice(0, 8)].map((item, idx) => {
if ("last_status" in item) {
return (
<a key={`live-${item.id}-${idx}`} href={item.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 whitespace-nowrap hover:text-white">
<span>🔴</span>
<span className="font-medium">{item.last_anchor || item.room_id}</span>
<span className="text-slate-500">在播中</span>
</a>
);
}
return (
<span key={`ev-${item.id}-${idx}`} className="inline-flex items-center gap-2 whitespace-nowrap text-slate-300">
<span>{item.kind === "live" ? "🎬" : item.kind === "risk" ? "⚠️" : "⚡"}</span>
<span>{item.message}</span>
</span>
);
})
) : (
<span className="text-slate-500">等待开播事件…</span>
)}
</div>
</div>
</div>
) : null}
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr] lg:items-stretch">
<section className="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-medium text-slate-100">📊 可视化分析(全平台)</h3>
<div className="flex flex-wrap gap-3 text-xs">
<Link to="/sessions" className="inline-flex items-center gap-1 text-teal-300 hover:underline">
场次明细 <ArrowRight className="h-3 w-3" />
</Link>
<Link to="/groups?tab=analytics" className="inline-flex items-center gap-1 text-amber-300 hover:underline">
YouTube 分析 <ArrowRight className="h-3 w-3" />
</Link>
</div>
</div>
<SessionCharts stats={stats} />
{ytStats?.overview ? (
<div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 px-3 py-2 text-xs text-amber-100/90">
YouTube 单独:场次 {ytStats.overview.sessions ?? 0} · 在播 {ytStats.overview.active_sessions ?? 0} · 累计{" "}
{Number(ytStats.overview.total_hours || 0).toFixed(1)}h · 频道 {ytStats.overview.unique_anchors ?? 0}
<Link to="/groups?tab=analytics" className="ml-2 text-teal-300 hover:underline">
打开图表 →
</Link>
</div>
) : null}
</section>
<section className="glass-panel flex h-full min-h-0 flex-col rounded-2xl p-4">
<div className="mb-3 flex shrink-0 items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">⚡ 最近事件</h3>
<Link to="/events" className="inline-flex items-center gap-1 text-xs text-teal-300 hover:underline">
全部 <ArrowRight className="h-3 w-3" />
</Link>
</div>
<div className="timeline-rail min-h-0 flex-1 space-y-3 overflow-y-auto pl-1">
{events.map((ev) => (
<button
key={ev.id}
type="button"
disabled={!ev.session_id}
onClick={() => void openSessionDetail(ev.session_id)}
className={`relative ml-1 w-full rounded-xl border border-white/5 bg-black/20 px-3 py-2 pl-8 text-left text-sm hover-lift ${
ev.session_id ? "cursor-pointer hover:border-teal-400/30" : "cursor-default"
}`}
>
<span className="absolute left-[6px] top-3 h-3 w-3 rounded-full bg-teal-400/80 ring-4 ring-teal-400/10" />
<div className="flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
<span>{fmtTs(ev.ts)}</span>
<span className="uppercase text-teal-300/80">{ev.kind}</span>
{ev.session_id ? <span className="text-teal-400/70">详情 →</span> : null}
</div>
<div className="mt-1 text-slate-200">{ev.message}</div>
</button>
))}
{!events.length ? (
<div className="rounded-xl border border-dashed border-white/10 px-3 py-8 text-center text-sm text-slate-500">
暂无事件,开播后会出现在这里
</div>
) : null}
</div>
</section>
</div>
<div className="flex flex-wrap gap-3 text-sm">
<Link to="/slots" className="hover-lift glass-panel rounded-xl px-4 py-3 text-rose-200">🕐 开播时段规律</Link>
<Link to="/rooms" className="hover-lift glass-panel rounded-xl px-4 py-3 text-teal-200">🏠 管理直播间</Link>
<Link to="/anchors" className="hover-lift glass-panel rounded-xl px-4 py-3 text-fuchsia-200">👤 主播画像</Link>
<Link to="/covers" className="hover-lift glass-panel rounded-xl px-4 py-3 text-sky-200">🖼️ 浏览截图库</Link>
<Link to="/settings" className="hover-lift glass-panel rounded-xl px-4 py-3 text-amber-200">⚙️ 防风控设置</Link>
</div>
</Shell>
);
}

View File

@ -0,0 +1,636 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Loader2, Plus, RefreshCw, Trash2, Zap } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { Modal } from "@/components/Modal";
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
import { fetchJson, fmtTs } from "@/lib/api";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Room = {
id: string;
url: string;
room_id: string;
note?: string;
tags?: string[];
enabled: boolean;
last_status: string;
last_anchor?: string;
last_title?: string;
last_checked_at?: number;
next_check_at?: number;
last_error?: string;
error_count?: number;
};
export default function RoomsPage() {
const confirm = useConfirm();
const toast = useToast();
const [rooms, setRooms] = useState<Room[]>([]);
const [total, setTotal] = useState(0);
const [allTags, setAllTags] = useState<string[]>([]);
const [urlsText, setUrlsText] = useState("");
const [note, setNote] = useState("");
const [tagsInput, setTagsInput] = useState("");
const [q, setQ] = useState("");
const [status, setStatus] = useState("");
const [enabledFilter, setEnabledFilter] = useState("");
const [tag, setTag] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
const [bulkTags, setBulkTags] = useState("");
const [probeMsg, setProbeMsg] = useState("");
const [overdueOnly, setOverdueOnly] = useState(false);
const [editRoom, setEditRoom] = useState<Room | null>(null);
const [editNote, setEditNote] = useState("");
const [editTags, setEditTags] = useState("");
const [editBusy, setEditBusy] = useState(false);
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);
if (p.get("overdue") === "1") setOverdueOnly(true);
}, []);
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 overdueRooms = useMemo(() => {
const now = Date.now() / 1000;
return rooms.filter((r) => r.enabled && Number(r.next_check_at || 0) > 0 && Number(r.next_check_at) <= now - 60);
}, [rooms]);
const viewRooms = useMemo(
() => (overdueOnly ? overdueRooms : rooms),
[overdueOnly, overdueRooms, rooms],
);
async function openEdit(room: Room) {
setEditRoom(room);
setEditNote(room.note || "");
setEditTags((room.tags || []).join(","));
}
async function saveEdit() {
if (!editRoom) return;
setEditBusy(true);
setError("");
try {
await fetchJson(`/api/rooms/${editRoom.id}`, {
method: "PATCH",
body: JSON.stringify({ note: editNote, tags: editTags }),
});
setMsg(`已更新 ${editRoom.room_id}`);
setEditRoom(null);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setEditBusy(false);
}
}
async function recheckOverdue() {
const ids = overdueRooms.map((r) => r.id);
if (!ids.length) {
setMsg("当前没有积压房间");
return;
}
setBusy("overdue");
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("");
}
}
const query = useMemo(() => {
const p = new URLSearchParams();
if (q.trim()) p.set("q", q.trim());
if (status) p.set("status", status);
if (tag) p.set("tag", tag);
if (enabledFilter === "1") p.set("enabled", "true");
if (enabledFilter === "0") p.set("enabled", "false");
p.set("limit", "500");
return p.toString();
}, [q, status, tag, enabledFilter]);
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const [data, tagsData] = await Promise.all([
fetchJson(`/api/rooms?${query}`),
fetchJson("/api/rooms/tags"),
]);
setRooms(data.rooms || []);
setTotal(Number(data.total) || 0);
setAllTags(tagsData.tags || []);
if (!silent) setSelected(new Set());
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [query]);
useAutoRefresh(load, { intervalMs: 15000 });
async function doAddRooms() {
setBusy("add");
setError("");
setMsg("");
try {
const data = await fetchJson("/api/rooms/batch", {
method: "POST",
body: JSON.stringify({ urls: urlsText, note, enabled: true, tags: tagsInput }),
});
setUrlsText("");
setNote("");
setTagsInput("");
const parts = [`成功 ${data.created_count} 个`];
if (data.skipped_count) {
const reasons = (data.skipped || [])
.slice(0, 5)
.map((s: { url: string; reason: string }) => `${s.url}(${s.reason})`)
.join(";");
parts.push(`跳过 ${data.skipped_count} 个:${reasons}${data.skipped_count > 5 ? "…" : ""}`);
}
setMsg(parts.join(" · "));
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function bulk(action: string) {
const ids = Array.from(selected);
if (!ids.length) return;
if (action === "delete") {
const ok = await confirm({
title: "批量删除直播间",
message: `确定删除选中的 ${ids.length} 个直播间?`,
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
}
setBusy(action);
setError("");
try {
const data = await fetchJson("/api/rooms/bulk", {
method: "POST",
body: JSON.stringify({ action, ids, tags: bulkTags }),
});
setMsg(`批量 ${action}:${data.affected} 个`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function toggle(room: Room) {
setBusy(room.id);
try {
await fetchJson(`/api/rooms/${room.id}`, {
method: "PATCH",
body: JSON.stringify({ enabled: !room.enabled }),
});
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function remove(room: Room) {
const ok = await confirm({
title: "删除直播间",
message: `确定删除 ${room.room_id}?`,
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(room.id);
try {
await fetchJson(`/api/rooms/${room.id}`, { method: "DELETE" });
toast.push("直播间已删除", "ok");
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function checkNow(room: Room) {
setBusy(`check-${room.id}`);
setMsg("");
try {
const data = await fetchJson(`/api/monitor/check/${room.id}`, { method: "POST" });
const r = data.result || {};
setMsg(`检查完成:${r.status || r.error || JSON.stringify(r)}`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
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);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
const statusBadge = (s: string) => {
const map: Record<string, string> = {
live: "bg-rose-500/20 text-rose-200 border-rose-500/30",
offline: "bg-slate-500/20 text-slate-300 border-slate-500/30",
error: "bg-amber-500/20 text-amber-100 border-amber-500/30",
unknown: "bg-white/5 text-slate-400 border-white/10",
};
return map[s] || map.unknown;
};
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">🏠 直播间管理</h2>
<p className="text-sm text-slate-400">批量多行添加、标签分组、多选批量操作、一键拉黑。</p>
</div>
<div className="mb-4 space-y-3 rounded-xl border border-white/10 bg-black/30 p-4">
<label className="block text-xs text-slate-400">
直播间 URL / 房间号(每行一个)
<textarea
value={urlsText}
onChange={(e) => setUrlsText(e.target.value)}
rows={7}
placeholder={`https://live.douyin.com/123456789\n745277409780\n# 注释行忽略`}
className="mt-1 w-full resize-y rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm leading-relaxed"
/>
</label>
<div className="grid gap-3 md:grid-cols-3">
<label className="block text-xs text-slate-400">
统一备注
<input value={note} onChange={(e) => setNote(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
标签(逗号分隔)
<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 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"}
onClick={() => void doAddRooms()}
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d] disabled:opacity-50"
>
{busy === "add" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
批量添加{lineCount > 0 ? `(${lineCount})` : ""}
</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">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="筛选昵称/URL/房间号/标签…" className="w-full max-w-xs rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
<select value={status} onChange={(e) => setStatus(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">全部状态</option>
<option value="live">在播</option>
<option value="offline">离线</option>
<option value="error">错误</option>
<option value="unknown">未知</option>
</select>
<select value={enabledFilter} onChange={(e) => setEnabledFilter(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">启用状态</option>
<option value="1">已启用</option>
<option value="0">已停用</option>
</select>
<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">
<option value="">全部标签</option>
{allTags.map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
<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>
<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>
<button
type="button"
onClick={() => setOverdueOnly((v) => !v)}
className={`inline-flex items-center gap-2 rounded-lg border px-3 py-2 text-sm ${
overdueOnly
? "border-violet-400/40 bg-violet-500/15 text-violet-100"
: "border-white/10 bg-white/5 text-slate-300"
}`}
>
积压{overdueRooms.length ? `(${overdueRooms.length})` : ""}
</button>
<button
type="button"
disabled={busy === "overdue" || overdueRooms.length === 0}
onClick={() => void recheckOverdue()}
className="inline-flex items-center gap-2 rounded-lg border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm text-violet-100 disabled:opacity-40"
>
{busy === "overdue" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
重检积压
</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>
<span className="text-xs text-slate-500">共 {total} 个</span>
</div>
{selected.size > 0 ? (
<div className="mb-3 flex flex-wrap items-center gap-2 rounded-xl border border-teal-500/20 bg-teal-500/5 px-3 py-2 text-sm">
<span className="text-teal-100">已选 {selected.size}</span>
<button type="button" onClick={() => void bulk("enable")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">启用</button>
<button type="button" onClick={() => void bulk("disable")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">停用</button>
<button type="button" onClick={() => void bulk("check_queue")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">加入检查队列</button>
<button type="button" onClick={() => void bulk("delete")} className="rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200">删除</button>
<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}
{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}
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm text-teal-50">{msg}</div> : null}
<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">
<input
type="checkbox"
checked={viewRooms.length > 0 && selected.size === viewRooms.length}
onChange={() => {
if (selected.size === viewRooms.length) setSelected(new Set());
else setSelected(new Set(viewRooms.map((r) => r.id)));
}}
/>
</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>
<th className="px-3 py-3">最近 / 下次</th>
<th className="px-3 py-3">启用</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{viewRooms.map((room) => {
const overdue =
room.enabled && Number(room.next_check_at || 0) > 0 && Number(room.next_check_at) <= Date.now() / 1000 - 60;
return (
<tr key={room.id} className={`border-t border-white/5 ${overdue ? "bg-violet-500/5" : ""}`}>
<td className="px-3 py-3">
<input type="checkbox" checked={selected.has(room.id)} onChange={() => toggleSelect(room.id)} />
</td>
<td className="px-3 py-3">
<span className={`rounded border px-2 py-0.5 text-xs ${statusBadge(room.last_status)}`}>{room.last_status}</span>
{overdue ? <div className="mt-1 text-[10px] text-violet-200">积压</div> : null}
</td>
<td className="px-3 py-3">
<button type="button" onClick={() => void openEdit(room)} className="text-left hover:underline">
{room.last_anchor || "—"}
</button>
</td>
<td className="px-3 py-3">
<a href={room.url} target="_blank" rel="noreferrer" className="font-mono text-xs text-cyan-300 hover:underline">{room.room_id}</a>
{room.note ? <div className="text-[11px] text-slate-500">{room.note}</div> : null}
{room.last_error ? <div className="mt-1 max-w-[16rem] truncate text-[11px] text-amber-300/80">{room.last_error}</div> : null}
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-1">
{(room.tags || []).map((t) => (
<button key={t} type="button" onClick={() => setTag(t)} className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-slate-300 hover:bg-white/10">{t}</button>
))}
{!room.tags?.length ? <span className="text-slate-600">—</span> : null}
</div>
</td>
<td className="whitespace-nowrap px-3 py-3 text-xs text-slate-400">
<div>{fmtTs(room.last_checked_at)}</div>
<div className={overdue ? "text-violet-200" : "text-slate-600"}>下次 {fmtTs(room.next_check_at)}</div>
</td>
<td className="px-3 py-3">
<button type="button" onClick={() => void toggle(room)} className="text-xs text-teal-300 hover:underline">
{room.enabled ? "已启用" : "已停用"}
</button>
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-1">
<button type="button" onClick={() => void openEdit(room)} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">
编辑
</button>
<button type="button" onClick={() => void checkNow(room)} className="inline-flex items-center gap-1 rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">
{busy === `check-${room.id}` ? <Loader2 className="h-3 w-3 animate-spin" /> : <Zap className="h-3 w-3" />}
检查
</button>
<RoomQuickActions
compact
room={{
room_pk: room.id,
room_id: room.room_id,
url: room.url,
anchor_name: room.last_anchor,
tags: room.tags,
}}
favorited={isFavorited(room.tags)}
onDone={() => void load({ silent: true })}
onError={(m) => setError(m)}
/>
<button type="button" onClick={() => void remove(room)} className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200 hover:bg-rose-500/10">
<Trash2 className="h-3 w-3" />
</button>
</div>
</td>
</tr>
);
})}
{!loading && viewRooms.length === 0 ? (
<tr>
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">没有匹配的直播间</td>
</tr>
) : null}
</tbody>
</table>
</div>
<Modal open={Boolean(editRoom)} onClose={() => setEditRoom(null)} panelClassName="max-h-[90vh] w-full max-w-md overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5 shadow-2xl">
{editRoom ? (
<div className="space-y-3">
<div>
<h3 className="text-lg font-semibold text-white">编辑直播间</h3>
<p className="mt-1 font-mono text-xs text-cyan-300">{editRoom.room_id}</p>
<p className="text-sm text-slate-400">{editRoom.last_anchor || editRoom.url}</p>
</div>
<label className="block text-xs text-slate-400">
备注
<input
value={editNote}
onChange={(e) => setEditNote(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
标签(逗号分隔)
<input
value={editTags}
onChange={(e) => setEditTags(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 flex-wrap gap-2">
{["收藏", "重点", "竞品", "高优"].map((t) => {
const cur = editTags.split(/[,,]/).map((x) => x.trim()).filter(Boolean);
const on = cur.includes(t);
return (
<button
key={t}
type="button"
onClick={() => {
const next = on ? cur.filter((x) => x !== t) : [...cur, t];
setEditTags(next.join(","));
}}
className={`rounded-lg border px-2 py-1 text-xs ${
on ? "border-amber-400/40 bg-amber-500/15 text-amber-100" : "border-white/10 bg-white/5 text-slate-300"
}`}
>
{on ? "★ " : ""}
{t}
</button>
);
})}
</div>
<div className="flex justify-end gap-2 pt-2">
<button type="button" onClick={() => setEditRoom(null)} className="rounded-lg border border-white/10 px-3 py-1.5 text-sm">
取消
</button>
<button
type="button"
disabled={editBusy}
onClick={() => void saveEdit()}
className="rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-1.5 text-sm text-teal-100 disabled:opacity-50"
>
{editBusy ? "保存中…" : "保存"}
</button>
</div>
</div>
) : null}
</Modal>
</Shell>
);
}

View File

@ -0,0 +1,431 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Loader2, RefreshCw, Search } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { SessionDetailModal } from "@/components/SessionDetailModal";
import { RoomQuickActions } from "@/components/RoomQuickActions";
import { PlatformBadge } from "@/components/ui";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, detectPlatform } from "@/lib/api";
import { channelLiveRef } from "@/lib/youtubeLive";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Session = {
id: string;
anchor_name?: string;
source_url?: string;
room_id?: string;
room_pk?: string;
title?: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
push_date?: string;
cover_url?: string;
status?: string;
end_reason?: string;
};
export default function SessionsPage() {
const confirm = useConfirm();
const toast = useToast();
const [tab, setTab] = useState<"charts" | "list">("list");
const [q, setQ] = useState("");
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [status, setStatus] = useState("");
const [platform, setPlatform] = 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);
const [offset, setOffset] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<Session | null>(null);
const limit = 50;
useEffect(() => {
if (typeof window === "undefined") return;
const p = new URLSearchParams(window.location.search);
const sq = p.get("q");
if (sq) setQ(sq);
const sf = p.get("date_from");
if (sf) setDateFrom(sf);
const st = p.get("date_to");
if (st) setDateTo(st);
const ss = p.get("status");
if (ss) setStatus(ss);
const pf = p.get("platform");
if (pf) setPlatform(pf);
const tg = p.get("tag");
if (tg) setTag(tg);
const sid = p.get("session");
if (sid) {
void fetchJson(`/api/sessions/${sid}`)
.then((d) => setSelected((d.session || d) as Session))
.catch(() => undefined);
}
}, []);
const queryString = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
if (platform) params.set("platform", platform);
if (tag) params.set("tag", tag);
params.set("limit", String(limit));
params.set("offset", String(offset));
return params.toString();
}, [q, dateFrom, dateTo, status, platform, tag, offset]);
const statsQuery = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
if (platform) params.set("platform", platform);
if (tag) params.set("tag", tag);
params.set("top_anchors", "25");
return params.toString();
}, [q, dateFrom, dateTo, status, platform, tag]);
const exportHref = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
if (platform) params.set("platform", platform);
if (tag) params.set("tag", tag);
params.set("format", "csv");
return `/api/sessions/export?${params.toString()}`;
}, [q, dateFrom, dateTo, status, platform, tag]);
function applyPreset(days: number | "today") {
const to = todayBeijingISO();
const from = days === "today" ? to : shiftBeijingISO(to, -(Number(days) - 1));
setOffset(0);
setDateFrom(from);
setDateTo(to);
}
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const [listData, statsData] = await Promise.all([
fetchJson(`/api/sessions?${queryString}`),
fetchJson(`/api/sessions/stats?${statsQuery}`),
]);
setSessions(listData.sessions || []);
setTotal(Number(listData.total) || 0);
setStats(statsData);
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [queryString, statsQuery]);
useAutoRefresh(load, { intervalMs: 20000 });
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;
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">开播/停播明细、播放时长与截图,支持 CSV 导出。</p>
</div>
<div className="flex gap-2">
<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 hover:bg-white/10"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
<a
href={exportHref}
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 hover:bg-teal-500/20"
>
导出 CSV
</a>
<button
type="button"
onClick={async () => {
const ok = await confirm({
title: "结束全部进行中场次",
message: "确定结束所有当前进行中的场次?",
confirmLabel: "全部结束",
destructive: true,
});
if (!ok) return;
try {
const data = await fetchJson("/api/sessions/end-all-active", { method: "POST" });
setError("");
toast.push(`已结束 ${data.ended || 0} 场`, "ok");
await load();
} catch (e) {
setError((e as Error).message);
toast.push((e as Error).message, "err");
}
}}
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20"
>
⏹ 结束进行中
</button>
</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-6">
<label className="block text-xs text-slate-400 xl:col-span-2">
检索(昵称 / URL / 房间号)
<div className="relative mt-1">
<Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-slate-500" />
<input
value={q}
onChange={(e) => {
setOffset(0);
setQ(e.target.value);
}}
className="w-full rounded-lg border border-white/10 bg-slate-900 py-2 pl-9 pr-3 text-sm"
placeholder="例如:房间号或主播名"
/>
</div>
</label>
<label className="block text-xs text-slate-400">
开始日期
<input type="date" value={dateFrom} onChange={(e) => { setOffset(0); setDateFrom(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
结束日期
<input type="date" value={dateTo} onChange={(e) => { setOffset(0); setDateTo(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
状态
<select value={status} onChange={(e) => { setOffset(0); setStatus(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="active">进行中</option>
<option value="ended">已结束</option>
</select>
</label>
<label className="block text-xs text-slate-400">
平台
<select value={platform} onChange={(e) => { setOffset(0); setPlatform(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="douyin">抖音</option>
<option value="youtube">YouTube</option>
<option value="shorts">Shorts 频道开播</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>
<option value="重点">重点</option>
{tagOptions.filter((t) => 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}
<div className="mb-4 flex gap-2">
<button type="button" onClick={() => setTab("charts")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "charts" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
可视化分析
</button>
<button type="button" onClick={() => setTab("list")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "list" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
场次列表 ({total})
</button>
</div>
{tab === "charts" ? <SessionCharts stats={stats} /> : null}
{tab === "list" ? (
<>
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<div className="overflow-x-auto">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase tracking-wide 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">直播间 URL</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>
<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">
{sessionCoverSrc(session) ? (
// eslint-disable-next-line @next/next/no-img-element
<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>
)}
</td>
<td className="px-3 py-3">
<PlatformBadge platform={detectPlatform(session)} />
</td>
<td className="px-3 py-3 font-medium">
<span className="inline-flex items-center gap-2">
{session.anchor_name || "—"}
{detectPlatform(session) === "youtube" &&
!session.ended_at &&
session.room_id?.startsWith("yt:UC") ? (
<YouTubeLiveBadge refKey={channelLiveRef(session.room_id.slice(3))} compact />
) : null}
</span>
</td>
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
{session.source_url ? (
<a href={session.source_url} target="_blank" rel="noreferrer" className="hover:underline" onClick={(e) => e.stopPropagation()}>
{session.source_url.replace(/^https?:\/\//, "")}
</a>
) : "—"}
</td>
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{fmtTs(session.started_at)}</td>
<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()}>
<div className="flex flex-wrap items-center gap-1.5">
<RoomQuickActions
compact
room={{
room_pk: session.room_pk,
room_id: session.room_id,
source_url: session.source_url,
anchor_name: session.anchor_name,
}}
onDone={() => void load({ silent: true })}
onError={(m) => setError(m)}
/>
{!session.ended_at ? (
<button
type="button"
onClick={async () => {
const ok = await confirm({
title: "结束场次",
message: `确定结束「${session.anchor_name || session.room_id}」这场?`,
confirmLabel: "结束",
destructive: true,
});
if (!ok) return;
try {
await fetchJson(`/api/sessions/${session.id}/end`, { method: "POST" });
toast.push("已结束场次", "ok");
await load();
} catch (e) {
setError((e as Error).message);
toast.push((e as Error).message, "err");
}
}}
className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10"
>
结束
</button>
) : null}
</div>
</td>
</tr>
))}
{!loading && sessions.length === 0 ? (
<tr>
<td colSpan={9} className="px-3 py-10 text-center text-slate-500">暂无场次。添加直播间后,开播会自动记入。</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
<div className="mt-4 flex items-center justify-between text-sm text-slate-400">
<span>共 {total} 条 · 第 {pageIndex}/{pageCount}</span>
<div className="flex gap-2">
<button type="button" disabled={offset <= 0 || loading} onClick={() => setOffset(Math.max(0, offset - limit))} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">上一页</button>
<button type="button" disabled={offset + limit >= total || loading} onClick={() => setOffset(offset + limit)} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">下一页</button>
</div>
</div>
</>
) : null}
{selected ? (
<SessionDetailModal
session={selected}
onClose={() => setSelected(null)}
onUpdated={() => void load()}
/>
) : null}
</Shell>
);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,576 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionDetailModal } from "@/components/SessionDetailModal";
import { RoomQuickActions } from "@/components/RoomQuickActions";
import { EmptyState, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
import { fetchJson, fmtDuration, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, beijingHourFromTs, fmtClock, beijingDateFromTs, beijingParts, detectPlatform } from "@/lib/api";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Session = {
id: string;
anchor_name?: string;
source_url?: string;
room_id?: string;
room_pk?: 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 {
return todayBeijingISO();
}
function shiftDateISO(iso: string, days: number): string {
return shiftBeijingISO(iso, days);
}
function slotIndexFromStartedAt(ts?: number): number | null {
if (!ts) return null;
return Math.min(5, Math.floor(beijingHourFromTs(ts) / 4));
}
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 [platform, setPlatform] = 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);
const pf = params.get("platform");
if (pf) setPlatform(pf);
}, []);
useEffect(() => {
void fetchJson("/api/rooms/tags")
.then((d) => setTagOptions(d.tags || []))
.catch(() => undefined);
}, []);
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const dayParams = new URLSearchParams({
date_from: date,
date_to: date,
limit: "2000",
offset: "0",
});
if (tag) dayParams.set("tag", tag);
if (platform) dayParams.set("platform", platform);
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);
if (platform) rangeParams.set("platform", platform);
const rangeData = await fetchJson(`/api/sessions?${rangeParams}`);
setRangeSessions(rangeData.sessions || []);
} else {
setRangeSessions(dayData.sessions || []);
}
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [date, rangeMode, tag, platform]);
useAutoRefresh(load, { intervalMs: 20000 });
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 || beijingDateFromTs(s.started_at);
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(beijingParts().hour / 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={platform}
onChange={(e) => setPlatform(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="douyin">抖音</option>
<option value="youtube">YouTube</option>
</select>
<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>
<option value="重点">重点</option>
{tagOptions.filter((t) => 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">
<PlatformBadge platform={detectPlatform(session)} />
<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 className="mt-2">
<RoomQuickActions
compact
room={{
room_pk: session.room_pk,
room_id: session.room_id,
source_url: session.source_url,
anchor_name: session.anchor_name,
}}
onDone={() => void load({ silent: true })}
onError={(m) => setError(m)}
/>
</div>
</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

@ -0,0 +1,664 @@
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
Clapperboard,
Eye,
EyeOff,
Loader2,
Link2,
ListVideo,
Plus,
Radio,
RefreshCw,
Save,
Search,
Trash2,
LayoutDashboard,
} from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { fetchJson, fmtTs } from "@/lib/api";
import { shortsLiveRef } from "@/lib/youtubeLive";
type Mode = "manage" | "probe";
type ProbeTab = "channel" | "live" | "video" | "search" | "resolve";
type ManagedChannel = {
id: string;
name?: string;
youtube_channel_id?: string;
enabled?: boolean;
authorized?: boolean;
daily_min?: number;
daily_max?: number;
};
type YtVideo = {
id: string;
title?: string;
description?: string;
privacyStatus?: string;
publishAt?: string;
published_at?: string;
tags?: string[];
statistics?: Record<string, string>;
thumbnails?: any;
url?: string;
shorts_url?: string;
};
export default function YouTubePage() {
const confirm = useConfirm();
const toast = useToast();
const [mode, setMode] = useState<Mode>("manage");
const [channels, setChannels] = useState<ManagedChannel[]>([]);
const [channelPk, setChannelPk] = useState("");
const [dash, setDash] = useState<any>(null);
const [videos, setVideos] = useState<YtVideo[]>([]);
const [playlists, setPlaylists] = useState<any[]>([]);
const [edit, setEdit] = useState<YtVideo | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
// probe
const [tab, setTab] = useState<ProbeTab>("channel");
const [input, setInput] = useState("@MrBeast");
const [result, setResult] = useState<any>(null);
const [svc, setSvc] = useState<any>(null);
const [addBusy, setAddBusy] = useState(false);
const loadChannels = useCallback(async () => {
try {
const data = await fetchJson("/api/youtube/manage/channels");
const list = (data.channels || []).filter((c: ManagedChannel) => c.authorized);
setChannels(list);
if (!channelPk && list[0]?.id) setChannelPk(list[0].id);
} catch (e) {
setError((e as Error).message);
}
}, [channelPk]);
const loadManage = useCallback(async () => {
if (!channelPk) return;
setBusy(true);
setError("");
try {
const [d, v, p] = await Promise.all([
fetchJson(`/api/youtube/manage/${channelPk}/dashboard`),
fetchJson(`/api/youtube/manage/${channelPk}/videos?max_results=25`),
fetchJson(`/api/youtube/manage/${channelPk}/playlists`).catch(() => ({ playlists: [] })),
]);
setDash(d);
setVideos(v.videos || []);
setPlaylists(p.playlists || []);
} catch (e) {
setError((e as Error).message);
setDash(null);
setVideos([]);
} finally {
setBusy(false);
}
}, [channelPk]);
useEffect(() => {
void loadChannels();
}, [loadChannels]);
useEffect(() => {
if (mode === "manage" && channelPk) void loadManage();
}, [mode, channelPk, loadManage]);
async function saveVideo() {
if (!edit || !channelPk) return;
setBusy(true);
setError("");
setMsg("");
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${edit.id}`, {
method: "PATCH",
body: JSON.stringify({
title: edit.title,
description: edit.description,
tags: edit.tags || [],
privacy_status: edit.privacyStatus,
publish_at: edit.publishAt || "",
}),
});
setMsg("视频已更新");
setEdit(null);
await loadManage();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function setPrivacy(videoId: string, privacy: string) {
if (!channelPk) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, {
method: "PATCH",
body: JSON.stringify({ privacy_status: privacy }),
});
setMsg(`已设为 ${privacy}`);
await loadManage();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function removeVideo(videoId: string) {
if (!channelPk) return;
const ok = await confirm({
title: "删除 YouTube 视频",
message: "确定从 YouTube 删除该视频?此操作不可恢复。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" });
toast.push("视频已删除", "ok");
await loadManage();
} catch (e) {
setError((e as Error).message);
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function checkSvc() {
try {
setSvc(await fetchJson("/api/youtube/health"));
} catch (e) {
setSvc({ ok: false, error: (e as Error).message });
}
}
async function runProbe() {
setBusy(true);
setError("");
setMsg("");
setResult(null);
try {
const q = encodeURIComponent(input.trim());
let data: any;
if (tab === "channel") data = await fetchJson(`/api/youtube/channel?url=${q}&videos=1&limit=8`);
else if (tab === "live") data = await fetchJson(`/api/youtube/channel/live?url=${q}`);
else if (tab === "video") data = await fetchJson(`/api/youtube/video?url=${q}`);
else if (tab === "search") data = await fetchJson(`/api/youtube/search?q=${q}&limit=12`);
else data = await fetchJson(`/api/youtube/resolve?url=${q}`);
setResult(data);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function addToGroup(channel: any) {
const channelUrl =
String(channel?.url || "").trim() ||
(channel?.handle ? `https://www.youtube.com/@${String(channel.handle).replace(/^@/, "")}` : "") ||
String(channel?.channel_id || input.trim());
if (!channelUrl) {
setError("缺少频道 URL");
return;
}
setAddBusy(true);
try {
await fetchJson("/api/groups", {
method: "POST",
body: JSON.stringify({
name: String(channel?.title || channel?.handle || "YouTube 频道").slice(0, 80),
channel_url: channelUrl,
platform: "youtube",
enabled: true,
note: "从 YouTube 探测页加入",
}),
});
setMsg("已加入分组监控");
} catch (e) {
setError((e as Error).message);
} finally {
setAddBusy(false);
}
}
const profile = dash?.profile;
const shortsToday = dash?.shorts_today?.by_status || {};
const probeChannel = result?.channel;
const live = result?.live || probeChannel?.live;
const probeVideos = result?.results || probeChannel?.videos || [];
return (
<Shell>
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
<div>
<p className="font-display text-xs uppercase tracking-[0.28em] text-rose-300/80">YouTube Studio Lite</p>
<h2 className="font-display text-3xl font-semibold">▶️ YouTube</h2>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
已授权频道:片库 / 改元数据 / 可见性 / 定时公开 / 删除 / 播放列表只读。探测仍用 InnerTube。
</p>
</div>
<div className="flex flex-wrap gap-2">
<Link to="/shorts" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
Shorts →
</Link>
<Link to="/groups" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
分组监控 →
</Link>
</div>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => setMode("manage")}
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
mode === "manage" ? "bg-rose-500/20 text-rose-50 ring-1 ring-rose-400/30" : "bg-white/5 text-slate-400"
}`}
>
<LayoutDashboard className="h-3.5 w-3.5" />
频道管理(OAuth)
</button>
<button
type="button"
onClick={() => setMode("probe")}
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
mode === "probe" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
}`}
>
<Search className="h-3.5 w-3.5" />
公开探测(InnerTube)
</button>
</div>
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
{mode === "manage" ? (
<>
{channels.length === 0 ? (
<div className="rounded-2xl border border-dashed border-amber-500/30 bg-amber-500/5 px-4 py-10 text-center text-sm text-amber-100">
还没有已授权频道。请先到{" "}
<Link to="/shorts" className="underline">
Shorts
</Link>{" "}
完成 Google 授权。
</div>
) : (
<>
<div className="mb-4 flex flex-wrap items-center gap-2">
<select
value={channelPk}
onChange={(e) => setChannelPk(e.target.value)}
className="min-w-[220px] rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
{channels.map((c) => (
<option key={c.id} value={c.id}>
{c.name} {c.youtube_channel_id ? `(${c.youtube_channel_id.slice(0, 8)}…)` : ""}
</option>
))}
</select>
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} /> : null}
<button
type="button"
onClick={() => void loadManage()}
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
刷新
</button>
</div>
{profile ? (
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-2xl border border-white/10 bg-black/30 p-4 sm:col-span-2">
<div className="flex gap-3">
{profile.thumbnails?.default?.url || profile.thumbnails?.medium?.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={profile.thumbnails?.medium?.url || profile.thumbnails?.default?.url}
alt=""
className="h-14 w-14 rounded-full object-cover"
/>
) : (
<div className="h-14 w-14 rounded-full bg-white/10" />
)}
<div>
<div className="flex flex-wrap items-center gap-2">
<div className="font-display text-xl text-white">{profile.title}</div>
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} compact /> : null}
</div>
<div className="text-xs text-slate-500">{profile.custom_url || profile.youtube_channel_id}</div>
<div className="mt-1 text-xs text-slate-400">
订阅 {profile.statistics?.subscriberCount ?? "—"} · 视频 {profile.statistics?.videoCount ?? "—"} · 播放{" "}
{profile.statistics?.viewCount ?? "—"}
</div>
</div>
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="text-xs text-slate-500">今日 Shorts 流水</div>
<div className="mt-2 space-y-1 text-xs text-slate-300">
{Object.keys(shortsToday).length === 0 ? (
<span className="text-slate-500">无</span>
) : (
Object.entries(shortsToday).map(([k, v]) => (
<div key={k} className="flex justify-between">
<span>{k}</span>
<span>{String(v)}</span>
</div>
))
)}
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="text-xs text-slate-500">播放列表</div>
<div className="mt-2 font-display text-2xl text-white">{playlists.length}</div>
<div className="text-[11px] text-slate-500">只读(当前 OAuth scope)</div>
</div>
</div>
) : null}
<div className="mb-6 grid gap-4 xl:grid-cols-[1.5fr_1fr]">
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-100">近期上传</h3>
<div className="space-y-2">
{videos.length === 0 ? (
<div className="py-8 text-center text-sm text-slate-500">暂无视频或加载失败</div>
) : (
videos.map((v) => (
<div key={v.id} className="flex gap-3 rounded-xl border border-white/10 bg-black/40 p-2.5">
{v.thumbnails?.medium?.url || v.thumbnails?.default?.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={v.thumbnails?.medium?.url || v.thumbnails?.default?.url}
alt=""
className="h-16 w-28 shrink-0 rounded-lg object-cover"
/>
) : (
<div className="h-16 w-28 shrink-0 rounded-lg bg-white/10" />
)}
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-slate-100">{v.title}</div>
<div className="mt-0.5 text-[11px] text-slate-500">
{v.privacyStatus} · 播放 {v.statistics?.viewCount ?? 0} ·{" "}
{v.published_at ? fmtTs(Date.parse(v.published_at) / 1000) : "—"}
{v.publishAt ? ` · 定时 ${v.publishAt}` : ""}
</div>
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => setEdit({ ...v })}
className="rounded-lg bg-white/5 px-2 py-1 text-[11px]"
>
编辑
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "public")}
className="inline-flex items-center gap-1 rounded-lg bg-teal-500/15 px-2 py-1 text-[11px] text-teal-100"
>
<Eye className="h-3 w-3" />
公开
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "unlisted")}
className="rounded-lg bg-amber-500/15 px-2 py-1 text-[11px] text-amber-100"
>
不公开列出
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "private")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px]"
>
<EyeOff className="h-3 w-3" />
私密
</button>
<a
href={v.shorts_url || v.url}
target="_blank"
rel="noreferrer"
className="rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-300"
>
打开
</a>
<button
type="button"
onClick={() => void removeVideo(v.id)}
className="inline-flex items-center gap-1 rounded-lg bg-rose-500/15 px-2 py-1 text-[11px] text-rose-200"
>
<Trash2 className="h-3 w-3" />
删
</button>
</div>
</div>
</div>
))
)}
</div>
</section>
<section className="space-y-4">
{edit ? (
<div className="rounded-2xl border border-rose-500/25 bg-black/40 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-100">编辑视频</h3>
<label className="mb-2 block text-xs text-slate-400">
标题
<input
value={edit.title || ""}
onChange={(e) => setEdit({ ...edit, title: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="mb-2 block text-xs text-slate-400">
描述
<textarea
value={edit.description || ""}
onChange={(e) => setEdit({ ...edit, description: e.target.value })}
rows={5}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="mb-2 block text-xs text-slate-400">
标签(逗号分隔)
<input
value={(edit.tags || []).join(", ")}
onChange={(e) =>
setEdit({
...edit,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="mb-2 block text-xs text-slate-400">
可见性
<select
value={edit.privacyStatus || "public"}
onChange={(e) => setEdit({ ...edit, privacyStatus: 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="public">public</option>
<option value="unlisted">unlisted</option>
<option value="private">private</option>
</select>
</label>
<label className="mb-3 block text-xs text-slate-400">
定时公开(UTC ISO,如 2026-08-10T12:00:00Z;填写后会先设为 private)
<input
value={edit.publishAt || ""}
onChange={(e) => setEdit({ ...edit, publishAt: e.target.value })}
placeholder="2026-08-10T12:00:00Z"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
</label>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={busy}
onClick={() => void saveVideo()}
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
>
<Save className="h-3.5 w-3.5" />
保存
</button>
<button type="button" onClick={() => setEdit(null)} className="rounded-lg bg-white/5 px-3 py-2 text-sm">
取消
</button>
</div>
</div>
) : (
<div className="rounded-2xl border border-dashed border-white/10 px-4 py-8 text-center text-sm text-slate-500">
选择左侧视频点「编辑」可改标题/描述/标签/可见性/定时公开
</div>
)}
<div className="rounded-2xl border border-white/10 bg-black/25 p-4">
<div className="mb-2 flex items-center gap-2 text-sm text-slate-100">
<ListVideo className="h-4 w-4 text-rose-300" />
播放列表
</div>
<div className="max-h-56 space-y-1 overflow-y-auto text-xs text-slate-400">
{playlists.length === 0 ? (
<div>无播放列表</div>
) : (
playlists.map((p) => (
<div key={p.id} className="flex justify-between gap-2 border-b border-white/5 py-1.5">
<span className="truncate text-slate-200">{p.title}</span>
<span>
{p.itemCount ?? 0} · {p.privacyStatus}
</span>
</div>
))
)}
</div>
</div>
</section>
</div>
</>
)}
</>
) : (
<>
<div className="mb-3 flex flex-wrap gap-2">
{(
[
["channel", "频道", <Radio key="a" className="h-3.5 w-3.5" />],
["live", "开播检测", <Clapperboard key="b" className="h-3.5 w-3.5" />],
["video", "视频", <Clapperboard key="c" className="h-3.5 w-3.5" />],
["search", "搜索", <Search key="d" className="h-3.5 w-3.5" />],
["resolve", "解析 URL", <Link2 key="e" className="h-3.5 w-3.5" />],
] as const
).map(([id, label, icon]) => (
<button
key={id}
type="button"
onClick={() => setTab(id)}
className={`inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm ${
tab === id ? "bg-teal-500/20 text-teal-50" : "bg-white/5 text-slate-400"
}`}
>
{icon}
{label}
</button>
))}
<button type="button" onClick={() => void checkSvc()} className="rounded-xl bg-white/5 px-3 py-1.5 text-sm">
检查 youtube-svc {svc ? (svc.ok ? "· 正常" : "· 异常") : ""}
</button>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
className="min-w-[240px] flex-1 rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="@handle / URL / 关键词"
/>
<button
type="button"
disabled={busy}
onClick={() => void runProbe()}
className="inline-flex items-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
探测
</button>
</div>
{probeChannel ? (
<div className="mb-4 rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex flex-wrap items-center gap-2">
<div className="font-display text-xl">{probeChannel.title}</div>
{live?.is_live ? (
<YouTubeLiveBadge
entry={{
is_live: true,
live_url: live.url || live.watch_url,
title: live.title,
}}
/>
) : null}
</div>
<div className="text-xs text-slate-500">{probeChannel.url || probeChannel.handle}</div>
</div>
<button
type="button"
disabled={addBusy}
onClick={() => void addToGroup(probeChannel)}
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
>
<Plus className="h-3.5 w-3.5" />
加入分组
</button>
</div>
</div>
) : null}
{probeVideos?.length ? (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{probeVideos.map((v: any, i: number) => (
<a
key={v.id || v.url || i}
href={v.url || "#"}
target="_blank"
rel="noreferrer"
className="rounded-xl border border-white/10 bg-black/30 p-3 text-sm hover:bg-white/5"
>
<div className="font-medium text-slate-100">{v.title || "video"}</div>
<div className="mt-1 text-xs text-slate-500">{v.id}</div>
</a>
))}
</div>
) : null}
{result && !probeChannel && !probeVideos?.length ? (
<pre className="mt-4 overflow-x-auto rounded-xl border border-white/10 bg-black/40 p-3 text-xs text-slate-400">
{JSON.stringify(result, null, 2)}
</pre>
) : null}
</>
)}
</Shell>
);
}

View File

@ -0,0 +1,313 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--bg0: #071018;
--bg1: #0f1c2e;
--line: rgba(255, 255, 255, 0.08);
--text: #edf3ff;
--muted: #93a4bd;
--accent: #ff2d55;
--teal: #2dd4bf;
--amber: #fbbf24;
}
html,
body {
min-height: 100%;
}
body {
margin: 0;
color: var(--text);
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
background:
radial-gradient(1100px 520px at 8% -8%, rgba(255, 45, 85, 0.2), transparent 55%),
radial-gradient(900px 480px at 92% 0%, rgba(45, 212, 191, 0.14), transparent 52%),
radial-gradient(700px 400px at 50% 100%, rgba(56, 189, 248, 0.06), transparent 60%),
linear-gradient(160deg, #071018 0%, #0f1c2e 45%, #0a1422 100%);
background-attachment: fixed;
}
* {
box-sizing: border-box;
}
::selection {
background: rgba(255, 45, 85, 0.35);
color: #fff;
}
/* ambient drifting orbs */
.ambient-orb {
position: fixed;
border-radius: 9999px;
filter: blur(60px);
pointer-events: none;
z-index: 0;
opacity: 0.45;
animation: orb-drift 18s ease-in-out infinite;
}
.ambient-orb.a {
width: 280px;
height: 280px;
left: -40px;
top: 120px;
background: rgba(255, 45, 85, 0.35);
}
.ambient-orb.b {
width: 220px;
height: 220px;
right: -30px;
top: 40%;
background: rgba(45, 212, 191, 0.28);
animation-delay: -6s;
animation-duration: 22s;
}
.ambient-orb.c {
width: 180px;
height: 180px;
left: 40%;
bottom: -40px;
background: rgba(56, 189, 248, 0.2);
animation-delay: -11s;
animation-duration: 26s;
}
@keyframes orb-drift {
0%,
100% {
transform: translate3d(0, 0, 0) scale(1);
}
50% {
transform: translate3d(24px, -18px, 0) scale(1.08);
}
}
@keyframes fade-up {
from {
opacity: 0;
transform: translateY(14px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes pulse-ring {
0% {
transform: scale(0.85);
opacity: 0.7;
}
70% {
transform: scale(1.55);
opacity: 0;
}
100% {
transform: scale(1.55);
opacity: 0;
}
}
@keyframes live-blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
@keyframes marquee {
from {
transform: translateX(0);
}
to {
transform: translateX(-50%);
}
}
@keyframes float-y {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-6px);
}
}
@keyframes draw-stroke {
from {
stroke-dashoffset: 120;
}
to {
stroke-dashoffset: 0;
}
}
.animate-fade-up {
animation: fade-up 0.55s ease both;
}
.animate-fade-in {
animation: fade-in 0.4s ease both;
}
.stagger > * {
animation: fade-up 0.5s ease both;
}
.stagger > *:nth-child(1) {
animation-delay: 0.02s;
}
.stagger > *:nth-child(2) {
animation-delay: 0.06s;
}
.stagger > *:nth-child(3) {
animation-delay: 0.1s;
}
.stagger > *:nth-child(4) {
animation-delay: 0.14s;
}
.stagger > *:nth-child(5) {
animation-delay: 0.18s;
}
.stagger > *:nth-child(6) {
animation-delay: 0.22s;
}
.stagger > *:nth-child(7) {
animation-delay: 0.26s;
}
.stagger > *:nth-child(8) {
animation-delay: 0.3s;
}
.live-dot {
position: relative;
display: inline-flex;
width: 0.55rem;
height: 0.55rem;
border-radius: 9999px;
background: #ff2d55;
box-shadow: 0 0 0 0 rgba(255, 45, 85, 0.5);
}
.live-dot::after {
content: "";
position: absolute;
inset: -3px;
border-radius: 9999px;
border: 1.5px solid rgba(255, 45, 85, 0.7);
animation: pulse-ring 1.6s ease-out infinite;
}
.glass-panel {
border: 1px solid rgba(255, 255, 255, 0.1);
background: linear-gradient(160deg, rgba(255, 255, 255, 0.07), rgba(255, 255, 255, 0.02));
backdrop-filter: blur(10px);
}
.btn-glow {
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}
.btn-glow:hover {
transform: translateY(-1px);
box-shadow: 0 8px 24px rgba(255, 45, 85, 0.25);
}
.nav-chip {
position: relative;
overflow: hidden;
transition: color 0.2s ease, background 0.2s ease, transform 0.2s ease;
}
.nav-chip:hover {
transform: translateY(-1px);
}
.nav-chip.active::before {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.08), transparent);
background-size: 200% 100%;
animation: shimmer 2.4s linear infinite;
}
.ticker-track {
display: flex;
width: max-content;
animation: marquee 28s linear infinite;
}
.ticker-track:hover {
animation-play-state: paused;
}
.float-slow {
animation: float-y 4.5s ease-in-out infinite;
}
.logo-stroke {
fill: none;
stroke: #2dd4bf;
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
stroke-dasharray: 120;
animation: draw-stroke 1.4s ease forwards;
}
.page-enter {
/* opacity-only: avoid transform so nested `fixed` overlays stay viewport-bound */
animation: fade-in 0.35s ease both;
}
.hover-lift {
transition: transform 0.25s ease, border-color 0.25s ease, background 0.25s ease;
}
.hover-lift:hover {
transform: translateY(-3px);
border-color: rgba(45, 212, 191, 0.35);
}
.timeline-rail {
position: relative;
}
.timeline-rail::before {
content: "";
position: absolute;
left: 11px;
top: 8px;
bottom: 8px;
width: 2px;
background: linear-gradient(180deg, rgba(45, 212, 191, 0.5), rgba(255, 45, 85, 0.15), transparent);
}

3
desktop/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
/// <reference types="vite/client" />
export {};

View File

@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
fontFamily: {
display: ['"Space Grotesk"', '"Noto Sans SC"', "sans-serif"],
body: ['"IBM Plex Sans"', '"Noto Sans SC"', "sans-serif"],
},
},
},
plugins: [],
};

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"lib": ["ES2022"],
"outDir": "dist-electron",
"rootDir": "electron",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"moduleResolution": "node"
},
"include": ["electron/**/*"]
}

22
desktop/tsconfig.json Normal file
View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}

35
desktop/vite.config.ts Normal file
View File

@ -0,0 +1,35 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "node:path";
const apiTarget = process.env.DY_DESKTOP_API || "http://127.0.0.1:8014";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
server: {
host: "127.0.0.1",
port: 5173,
strictPort: true,
proxy: {
"/api": { target: apiTarget, changeOrigin: true },
"/covers": { target: apiTarget, changeOrigin: true },
},
},
build: {
outDir: "dist",
emptyOutDir: true,
rollupOptions: {
output: {
manualChunks: {
echarts: ["echarts"],
vendor: ["react", "react-dom", "react-router-dom"],
},
},
},
},
});

View File

@ -201,7 +201,6 @@ export default function HomePage() {
return !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;
const missedOpens = upcoming.filter(
(u) =>
u.priority &&
@ -515,42 +514,6 @@ export default function HomePage() {
</div>
</section>
{upcomingView.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">
⏰ 预计下次开播{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">
{upcomingView.map((u) => (
<Link
key={`${u.room_id}-${u.anchor_name}`}
href={`/anchors?q=${encodeURIComponent(u.anchor_name || u.room_id || "")}`}
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>
</Link>
))}
</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">
@ -699,7 +662,7 @@ export default function HomePage() {
</div>
) : null}
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr]">
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr] lg:items-stretch">
<section className="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-medium text-slate-100">📊 可视化分析(全平台)</h3>
@ -724,14 +687,14 @@ export default function HomePage() {
) : null}
</section>
<section className="glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<section className="glass-panel flex h-full min-h-0 flex-col rounded-2xl p-4">
<div className="mb-3 flex shrink-0 items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">⚡ 最近事件</h3>
<Link href="/events" className="inline-flex items-center gap-1 text-xs text-teal-300 hover:underline">
全部 <ArrowRight className="h-3 w-3" />
</Link>
</div>
<div className="timeline-rail max-h-[560px] space-y-3 overflow-auto pl-1">
<div className="timeline-rail min-h-0 flex-1 space-y-3 overflow-y-auto pl-1">
{events.map((ev) => (
<button
key={ev.id}

View File

@ -803,7 +803,27 @@ export default function ShortsPage() {
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
{status?.last_error ? (
{status?.upload_quota_blocked ? (
<div className="mb-3 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2.5 text-xs text-rose-50">
<p className="font-medium text-rose-100">YouTube 每日 Video Uploads 配额已用尽</p>
<p className="mt-1 text-rose-100/90">
上传已自动暂停,不会在配额重置前反复重试。太平洋时间 0 点配额恢复后会继续排队上传。
{typeof status.yt_upload_used === "number" && typeof status.yt_upload_limit === "number" ? (
<> 今日已用 {status.yt_upload_used}/{status.yt_upload_limit} 次(太平洋日)。</>
) : null}
{status.upload_quota_blocked_until ? (
<> 预计恢复:{fmtTs(status.upload_quota_blocked_until)}(北京)</>
) : null}
</p>
<p className="mt-1 text-[11px] text-rose-200/70">
官方默认上限 100 次/天/项目;系统保守限制 {status.yt_upload_limit ?? 90} 次以防撞线。可在设置中调整 shorts_yt_daily_upload_limit。
</p>
</div>
) : typeof status?.yt_upload_remaining === "number" && status.yt_upload_remaining <= 10 ? (
<div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50">
YouTube 上传配额即将用尽:今日 {status.yt_upload_used ?? 0}/{status.yt_upload_limit ?? 90} 次(太平洋日),剩余 {status.yt_upload_remaining} 次。
</div>
) : status?.last_error ? (
<div className="mb-3 rounded-xl border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">
最近错误:{status.last_error}
</div>

24
scripts/_api_alone.ps1 Normal file
View File

@ -0,0 +1,24 @@
$ErrorActionPreference = 'SilentlyContinue'
# Kill electron/vite stacks and anything on 8014
Get-Process electron -ErrorAction SilentlyContinue | Stop-Process -Force
Get-CimInstance Win32_Process | Where-Object {
$_.CommandLine -match 'uvicorn app\.main|electron\.cli|vite\\bin\\vite|concurrently.*vite'
} | ForEach-Object { taskkill /F /PID $_.ProcessId 2>$null }
Start-Sleep -Seconds 2
# Free 8014
netstat -ano | Select-String ':8014\s+.*LISTENING\s+(\d+)' | ForEach-Object {
taskkill /F /PID $_.Matches.Groups[1].Value 2>$null
}
$env:DY_AUTH_ENABLED = 'false'
$env:DY_DESKTOP_LIGHT = 'true'
$env:DY_DISABLE_LIVE_MAP_LOOP = 'true'
$env:DY_PB_URL = 'http://127.0.0.1:8090'
$env:DY_S3_ENABLED = 'false'
$env:DY_CORS_ORIGINS = 'http://127.0.0.1:5173,http://localhost:5173'
$env:PYTHONUTF8 = '1'
Set-Location 'c:\Users\admin\Desktop\douyinWEB\backend'
Write-Host 'Starting uvicorn alone...'
python -m uvicorn app.main:app --host 127.0.0.1 --port 8014

11
scripts/_api_port8015.bat Normal file
View File

@ -0,0 +1,11 @@
@echo off
cd /d c:\Users\admin\Desktop\douyinWEB\backend
set DY_AUTH_ENABLED=false
set DY_DESKTOP_LIGHT=true
set DY_DISABLE_LIVE_MAP_LOOP=true
set DY_PB_URL=http://127.0.0.1:8090
set DY_S3_ENABLED=false
set DY_CORS_ORIGINS=http://127.0.0.1:5173,http://localhost:5173
set PYTHONUTF8=1
echo starting api...
python -m uvicorn app.main:app --host 127.0.0.1 --port 8015

4
scripts/_probe.bat Normal file
View File

@ -0,0 +1,4 @@
@echo off
curl.exe -m 5 -s -w " ping http=%%{http_code} t=%%{time_total}\n" http://127.0.0.1:8014/api/ping
curl.exe -m 5 -s -w " health http=%%{http_code} t=%%{time_total}\n" http://127.0.0.1:8014/api/health
curl.exe -m 5 -s -w " shorts http=%%{http_code} t=%%{time_total}\n" http://127.0.0.1:8014/api/shorts/status

View File

@ -0,0 +1,29 @@
# Kill hung diagnostic shells + restart desktop cleanly
$ErrorActionPreference = 'SilentlyContinue'
$killPids = @(3816, 22404, 18992, 10712, 16424)
foreach ($p in $killPids) { Stop-Process -Id $p -Force -ErrorAction SilentlyContinue }
Get-Process electron -ErrorAction SilentlyContinue | Stop-Process -Force
Get-Process -Name 'node' -ErrorAction SilentlyContinue | Where-Object {
$_.Path -like '*douyinWEB*' -or (Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)").CommandLine -match 'douyinWEB\\desktop|vite|electron'
} | Stop-Process -Force -ErrorAction SilentlyContinue
# Kill listeners on key ports
foreach ($port in 8014, 5173) {
netstat -ano | Select-String ":$port\s+.*LISTENING\s+(\d+)" | ForEach-Object {
if ($_.Matches.Groups.Count -gt 1) {
$pidToKill = $_.Matches.Groups[1].Value
if ($pidToKill) { taskkill /F /PID $pidToKill 2>$null }
}
}
}
# Also kill python uvicorn for this project
Get-CimInstance Win32_Process -Filter "Name='python.exe'" | Where-Object {
$_.CommandLine -match 'uvicorn|app\.main'
} | ForEach-Object { taskkill /F /PID $_.ProcessId 2>$null }
Start-Sleep -Seconds 2
Set-Location 'c:\Users\admin\Desktop\douyinWEB\desktop'
npm run build:electron
npm run electron:dev

View File

@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
"""Deploy YouTube Video Uploads quota backoff + project daily budget."""
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
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/timeutil.py",
"backend/app/shorts_upload.py",
"backend/app/shorts_yt_quota.py",
"backend/app/shorts_pipeline.py",
"frontend/src/app/shorts/page.tsx",
]
def run(c, cmd, timeout=420):
print("$", cmd[:180], 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()
text = "".join(buf)
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
print(clean[-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 kill -s SIGKILL douyinweb-api || true; sleep 1; "
"systemctl reset-failed douyinweb-api || true; "
"systemctl start douyinweb-api; sleep 5; systemctl is-active douyinweb-api",
)
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
"\"from app import db; from app.shorts_yt_quota import detect_and_block_from_recent_errors, yt_upload_budget; "
"db.init_db(); blocked, until = detect_and_block_from_recent_errors(); "
"lim, used, rem = yt_upload_budget(); "
"print('blocked', blocked, 'until', until); "
"print('budget', used, '/', lim, 'remaining', rem)\"",
timeout=60,
)
run(
c,
"curl -sS http://127.0.0.1:8014/api/shorts/status | head -c 1200; echo",
timeout=60,
)
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=600) != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl is-active douyinweb-api douyinweb-web")
run(
c,
"curl -sS https://dylive.nomadro.com/api/shorts/status | head -c 800; echo",
timeout=60,
)
c.close()
print("DONE")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,27 @@
@echo off
setlocal
echo Killing electron / python uvicorn / ports 8014 5173 8015...
taskkill /F /IM electron.exe >nul 2>&1
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":8014 .*LISTENING"') do taskkill /F /PID %%p >nul 2>&1
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":8015 .*LISTENING"') do taskkill /F /PID %%p >nul 2>&1
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":5173 .*LISTENING"') do taskkill /F /PID %%p >nul 2>&1
wmic process where "CommandLine like '%%uvicorn app.main%%'" call terminate >nul 2>&1
timeout /t 3 /nobreak >nul
cd /d c:\Users\admin\Desktop\douyinWEB\desktop
call npm run build:electron
if errorlevel 1 exit /b 1
echo Starting electron:dev ...
start "douyin-desktop" cmd /k "cd /d c:\Users\admin\Desktop\douyinWEB\desktop && npm run electron:dev"
timeout /t 12 /nobreak >nul
echo.
echo === /api/ping ===
curl.exe -m 5 -s -w "\nhttp=%%{http_code} t=%%{time_total}\n" http://127.0.0.1:8014/api/ping
echo === /api/health ===
curl.exe -m 5 -s -w "\nhttp=%%{http_code} t=%%{time_total}\n" http://127.0.0.1:8014/api/health
echo.
echo If ping returns ok, open the Electron window and click Shorts.
pause
endlocal

View File

@ -0,0 +1,21 @@
@echo off
setlocal
cd /d "%~dp0.."
echo [1/3] Killing stale Electron / Vite / API on 8014 5173...
taskkill /F /IM electron.exe >nul 2>&1
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":8014 .*LISTENING"') do taskkill /F /PID %%p >nul 2>&1
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":5173 .*LISTENING"') do taskkill /F /PID %%p >nul 2>&1
timeout /t 2 /nobreak >nul
echo [2/3] Starting desktop (local PB + API + UI)...
cd /d "%~dp0..\desktop"
call npm run build:electron
start "douyinWEB-desktop" cmd /k "npm run electron:dev"
echo [3/3] Waiting for API health...
timeout /t 8 /nobreak >nul
curl -s -m 5 http://127.0.0.1:8014/api/health
echo.
echo Done. Use the Electron window; Shorts nav should switch pages immediately.
endlocal

10
scripts/start-desktop.bat Normal file
View File

@ -0,0 +1,10 @@
@echo off
setlocal
cd /d %~dp0\..\desktop
if not exist node_modules (
echo Installing desktop dependencies...
call npm install
)
echo Starting Electron desktop (local FastAPI + PocketBase)...
call npm run electron:dev
endlocal