from __future__ import annotations import asyncio import csv import io import time from contextlib import asynccontextmanager from typing import Any, Optional from urllib.parse import quote from fastapi import FastAPI, HTTPException, Query, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse from fastapi.staticfiles import StaticFiles import httpx from . import cookie_loader, db, pb_sync, shorts_oauth, youtube_client from .config import settings from .cover import cover_path_for, ensure_session_cover from .douyin import check_room from .events_bus import bus from .models import ( BlacklistCreate, ChannelGroupBulkAction, ChannelGroupCreate, ChannelGroupUpdate, PurgeEventsBody, RoomBatchCreate, RoomBulkAction, RoomCreate, RoomQuickAction, RoomUpdate, SettingsUpdate, ShortsChannelCreate, ShortsChannelUpdate, ) from .monitor import monitor from .stats import summarize_anchor_schedule, summarize_sessions from .youtube_client import YouTubeSvcError from .youtube_monitor import yt_monitor from .shorts_pipeline import shorts_pipeline from .timeutil import stamp_beijing @asynccontextmanager async def lifespan(_: FastAPI): db.init_db() try: cookie_loader.bootstrap_cookie_into_db() except Exception: pass async def _pb_boot() -> None: try: await pb_sync.ensure_collections() except Exception: pass asyncio.create_task(_pb_boot()) await monitor.start() await yt_monitor.start() # Idle loop when disabled — does not affect monitor try: await shorts_pipeline.start() except Exception: pass yield try: await shorts_pipeline.stop() except Exception: pass await yt_monitor.stop() await monitor.stop() app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan) app.add_middleware( CORSMiddleware, allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) covers_dir = settings.covers_dir covers_dir.mkdir(parents=True, exist_ok=True) app.mount("/covers", StaticFiles(directory=str(covers_dir)), name="covers") @app.get("/api/health") async def health() -> dict[str, Any]: pb = await pb_sync.health() 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 { "ok": True, "time": time.time(), "pocketbase": pb, "s3": s3_info, "youtube": yt, "youtube_monitor": yt_monitor.status(), "monitor": monitor.status(), "shorts": shorts_pipeline.status(), } @app.get("/api/monitor/status") async def monitor_status() -> dict[str, Any]: return monitor.status() @app.post("/api/monitor/start") async def monitor_start() -> dict[str, Any]: db.update_settings_map({"monitor_enabled": True}) await monitor.start() return monitor.status() @app.post("/api/monitor/stop") async def monitor_stop() -> dict[str, Any]: db.update_settings_map({"monitor_enabled": False}) return 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() @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 return status @app.post("/api/youtube-monitor/start") async def youtube_monitor_start() -> dict[str, Any]: db.update_settings_map({"yt_monitor_enabled": True}) await yt_monitor.start() return yt_monitor.status() @app.post("/api/youtube-monitor/stop") async def youtube_monitor_stop() -> dict[str, Any]: db.update_settings_map({"yt_monitor_enabled": False}) return yt_monitor.status() @app.post("/api/youtube-monitor/check/{group_id}") async def youtube_monitor_check(group_id: str) -> dict[str, Any]: try: result = await yt_monitor.check_one(group_id) except ValueError as exc: raise HTTPException(404, str(exc)) from exc except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc return {"result": result, "group": db.get_channel_group(group_id)} def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: """Mask OAuth secrets for API responses; never expose full tokens.""" out = dict(ch) secret = str(out.get("client_secret") or "") refresh = str(out.get("refresh_token") or "") out["has_client_secret"] = bool(secret.strip()) out["has_refresh_token"] = bool(refresh.strip()) out["authorized"] = bool(refresh.strip()) out["client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else ("***" if secret else "") out["refresh_token"] = ("***" + refresh[-4:]) if len(refresh) > 4 else ("***" if refresh else "") return out def _request_public_base(request: Request) -> str: """Prefer reverse-proxy headers for OAuth redirect base.""" proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").split(",")[0].strip() host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "").split(",")[0].strip() if host: return f"{proto}://{host}" return "https://dylive.nomadro.com" @app.get("/api/shorts/status") async def shorts_status() -> dict[str, Any]: st = shorts_pipeline.status() st["oauth_configured"] = shorts_oauth.oauth_client_configured() st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri("https://dylive.nomadro.com") cfg = db.get_settings_map() st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104") return st @app.get("/api/shorts/oauth/start") async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse: try: url = shorts_oauth.build_authorize_url( channel_pk=channel_pk, request_base=_request_public_base(request), ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc return RedirectResponse(url, status_code=302) @app.get("/api/shorts/oauth/callback") async def shorts_oauth_callback( request: Request, code: str = "", state: str = "", error: str = "", ) -> RedirectResponse: base = _request_public_base(request) if error: return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote(error)}", status_code=302) if not code or not state: return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote('缺少 code/state')}", status_code=302) try: result = await shorts_oauth.exchange_code( code=code, state=state, request_base=base, ) title = quote(str(result.get("youtube_title") or "ok")) return RedirectResponse(f"{base}/shorts?oauth=ok&title={title}", status_code=302) except Exception as exc: return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote(str(exc)[:180])}", status_code=302) @app.post("/api/shorts/start") async def shorts_start() -> dict[str, Any]: """Enable Shorts pipeline only — does not touch Douyin/YouTube monitors.""" db.update_settings_map({"shorts_enabled": True}) try: await shorts_pipeline.start() except Exception: pass return shorts_pipeline.status() @app.post("/api/shorts/stop") async def shorts_stop() -> dict[str, Any]: db.update_settings_map({"shorts_enabled": False}) return shorts_pipeline.status() @app.post("/api/shorts/sample-now") async def shorts_sample_now() -> dict[str, Any]: """Manually trigger one live-room sample tick (does not affect monitor).""" from .shorts_pipeline import try_sample_live_rooms cfg = db.get_settings_map() if not cfg.get("shorts_enabled"): raise HTTPException(400, "请先启用 Shorts") n = try_sample_live_rooms(cfg) st = shorts_pipeline.status() st["just_enqueued"] = n return st @app.get("/api/shorts/channels") async def shorts_channels_list(enabled: Optional[bool] = None) -> dict[str, Any]: rows = db.list_shorts_channels(enabled=enabled) return {"channels": [_public_shorts_channel(c) for c in rows]} @app.post("/api/shorts/channels") async def shorts_channels_create(body: ShortsChannelCreate) -> dict[str, Any]: ch = db.create_shorts_channel(**body.model_dump()) return {"channel": _public_shorts_channel(ch)} @app.patch("/api/shorts/channels/{channel_pk}") async def shorts_channels_update(channel_pk: str, body: ShortsChannelUpdate) -> dict[str, Any]: patch = body.model_dump(exclude_none=True) # empty secret fields mean "keep existing" for secret_key in ("client_secret", "refresh_token", "client_id"): if secret_key in patch and not str(patch.get(secret_key) or "").strip(): patch.pop(secret_key, None) if secret_key in patch and str(patch[secret_key]).startswith("***"): patch.pop(secret_key, None) try: ch = db.update_shorts_channel(channel_pk, **patch) except ValueError as exc: raise HTTPException(404, str(exc)) from exc return {"channel": _public_shorts_channel(ch)} @app.delete("/api/shorts/channels/{channel_pk}") async def shorts_channels_delete(channel_pk: str) -> dict[str, Any]: db.delete_shorts_channel(channel_pk) return {"ok": True} @app.get("/api/shorts/jobs") async def shorts_jobs_list( status: str = "", push_date: str = "", channel_pk: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), ) -> dict[str, Any]: return db.list_shorts_jobs( status=status, push_date=push_date, channel_pk=channel_pk, limit=limit, offset=offset ) @app.post("/api/shorts/jobs/{job_id}/retry") async def shorts_job_retry(job_id: str) -> dict[str, Any]: job = db.get_shorts_job(job_id) if not job: raise HTTPException(404, "任务不存在") clip = str(job.get("clip_path") or "").strip() next_status = "recorded" if clip else "pending" updated = db.update_shorts_job( job_id, status=next_status, error="", finished_at=0, youtube_video_id="", youtube_url="", ) return {"job": updated} @app.post("/api/monitor/check/{room_pk}") async def monitor_check_one(room_pk: str) -> dict[str, Any]: room = db.get_room(room_pk) if not room: raise HTTPException(404, "直播间不存在") result = await monitor.check_one(room) return {"result": result, "room": db.get_room(room_pk)} @app.get("/api/settings") async def get_settings() -> dict[str, Any]: return 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) @app.post("/api/settings/sync-cookie") async def sync_cookie_from_sh2() -> dict[str, Any]: """Pull 抖音cookie from sh2 d2ypp2/config/config.ini into settings.""" result = cookie_loader.force_sync_cookie_from_sh2() if not result.get("ok"): raise HTTPException(404, "未找到 sh2 config.ini 中的抖音cookie") cfg = db.get_settings_map() return { **result, "has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()), "monitor": monitor.status(), } @app.get("/api/rooms") async def rooms_list( q: str = "", enabled: Optional[bool] = None, status: str = "", tag: str = "", 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) @app.get("/api/rooms/tags") async def rooms_tags() -> dict[str, Any]: return {"tags": db.list_all_tags()} @app.post("/api/rooms") async def rooms_create(body: RoomCreate) -> dict[str, Any]: try: room = db.create_room(body.url, note=body.note, enabled=body.enabled, tags=body.tags) except ValueError as exc: raise HTTPException(400, str(exc)) from exc try: await pb_sync.sync_room(room) except Exception: pass return {"room": room} @app.post("/api/rooms/batch") async def rooms_batch_create(body: RoomBatchCreate) -> dict[str, Any]: raw_lines = (body.urls or "").replace("\r\n", "\n").replace("\r", "\n").split("\n") lines: list[str] = [] seen: set[str] = set() for line in raw_lines: text = line.strip() if not text or text.startswith("#"): continue token = text.split(",")[0].split()[0].strip() if not token or token in seen: continue seen.add(token) lines.append(token) if not lines: raise HTTPException(400, "没有有效的直播间 URL / 房间号") created: list[dict[str, Any]] = [] skipped: list[dict[str, str]] = [] for item in lines: try: room = db.create_room(item, note=body.note, enabled=body.enabled, tags=body.tags) created.append(room) try: await pb_sync.sync_room(room) except Exception: pass except ValueError as exc: skipped.append({"url": item, "reason": str(exc)}) return { "created": created, "skipped": skipped, "created_count": len(created), "skipped_count": len(skipped), "total_input": len(lines), } @app.post("/api/rooms/bulk") async def rooms_bulk(body: RoomBulkAction) -> dict[str, Any]: try: result = db.bulk_rooms(body.action, body.ids, tags=body.tags) except ValueError as exc: raise HTTPException(400, str(exc)) from exc db.add_event( kind="ops", level="info", message=f"批量 {body.action}:{result.get('affected')} 个直播间", meta={"ids": body.ids[:20]}, ) return result @app.post("/api/rooms/quick") async def rooms_quick(body: RoomQuickAction) -> dict[str, Any]: """Favorite / unfavorite / ban from any UI surface with room_id or url.""" try: result = db.quick_room_action( body.action, room_pk=body.room_pk, room_id=body.room_id, url=body.url, reason=body.reason, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc room = result.get("room") if body.action == "ban": item = result.get("item") or {} db.add_event( kind="blacklist", level="warn", message=f"快捷拉黑:{body.url or body.room_id or body.room_pk}", room_id=str(item.get("room_id") or body.room_id or ""), meta={"disabled_rooms": item.get("disabled_rooms"), "reason": body.reason}, ) else: label = "收藏" if body.action == "favorite" else "取消收藏" db.add_event( kind="ops", level="info", message=f"{label}:{(room or {}).get('last_anchor') or (room or {}).get('room_id') or body.room_id}", room_id=str((room or {}).get("room_id") or body.room_id or ""), room_pk=str((room or {}).get("id") or body.room_pk or ""), anchor_name=str((room or {}).get("last_anchor") or ""), ) try: if room: await pb_sync.sync_room(room) except Exception: pass return result @app.patch("/api/rooms/{room_pk}") async def rooms_update(room_pk: str, body: RoomUpdate) -> dict[str, Any]: try: room = db.update_room( room_pk, url=body.url, note=body.note, enabled=body.enabled, tags=body.tags, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc try: await pb_sync.sync_room(room) except Exception: pass return {"room": room} @app.delete("/api/rooms/{room_pk}") async def rooms_delete(room_pk: str) -> dict[str, str]: db.delete_room(room_pk) return {"ok": "true"} @app.post("/api/rooms/probe") async def rooms_probe(body: RoomCreate) -> dict[str, Any]: cfg = db.get_settings_map() result = await check_room( body.url, cookie=str(cfg.get("dy_cookie") or ""), proxy=str(cfg.get("http_proxy") or "").strip() or None, ) return result @app.get("/api/blacklist") async def blacklist_list() -> dict[str, Any]: items = db.list_blacklist() return {"items": items, "total": len(items)} @app.post("/api/blacklist") async def blacklist_add(body: BlacklistCreate) -> dict[str, Any]: try: item = db.add_blacklist(body.value, reason=body.reason) except ValueError as exc: raise HTTPException(400, str(exc)) from exc db.add_event( kind="blacklist", level="warn", message=f"加入黑名单:{body.value}", room_id=item.get("room_id") or "", meta={"disabled_rooms": item.get("disabled_rooms"), "reason": body.reason}, ) return {"item": item} @app.delete("/api/blacklist/{item_id}") async def blacklist_delete(item_id: str) -> dict[str, str]: db.delete_blacklist(item_id) return {"ok": "true"} @app.get("/api/groups") async def groups_list( q: str = "", platform: str = "", enabled: Optional[bool] = None, limit: int = Query(200, ge=1, le=2000), offset: int = Query(0, ge=0), ) -> dict[str, Any]: return db.list_channel_groups(q=q, platform=platform, enabled=enabled, limit=limit, offset=offset) @app.get("/api/groups/export") async def groups_export() -> StreamingResponse: rows = db.export_channel_groups_rows() buf = io.StringIO() writer = csv.writer(buf) writer.writerow( ["id", "name", "platform", "channel_url", "channel_key", "handle", "url_count", "urls", "note", "enabled", "updated_at"] ) for g in rows: urls = g.get("urls") or [] if isinstance(urls, list): urls_s = "\n".join(urls) else: urls_s = str(urls) writer.writerow( [ g.get("id", ""), g.get("name", ""), g.get("platform", ""), g.get("channel_url", ""), g.get("channel_key", ""), g.get("handle", ""), g.get("url_count", 0), urls_s, g.get("note", ""), 1 if g.get("enabled") else 0, g.get("updated_at", ""), ] ) buf.seek(0) return StreamingResponse( iter([buf.getvalue()]), media_type="text/csv; charset=utf-8", headers={"Content-Disposition": 'attachment; filename="channel_groups.csv"'}, ) @app.post("/api/groups") async def groups_create(body: ChannelGroupCreate) -> dict[str, Any]: try: group = db.create_channel_group( name=body.name, channel_url=body.channel_url, urls=body.urls, note=body.note, platform=body.platform, enabled=body.enabled, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc try: await pb_sync.sync_channel_group(group) except Exception: pass return {"group": group} @app.get("/api/groups/{group_id}") async def groups_get(group_id: str) -> dict[str, Any]: group = db.get_channel_group(group_id) if not group: raise HTTPException(404, "分组不存在") return {"group": group} @app.patch("/api/groups/{group_id}") async def groups_update(group_id: str, body: ChannelGroupUpdate) -> dict[str, Any]: try: group = db.update_channel_group( group_id, name=body.name, channel_url=body.channel_url, urls=body.urls, note=body.note, platform=body.platform, enabled=body.enabled, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc try: await pb_sync.sync_channel_group(group) except Exception: pass return {"group": group} @app.delete("/api/groups/{group_id}") async def groups_delete(group_id: str) -> dict[str, str]: if not db.delete_channel_group(group_id): raise HTTPException(404, "分组不存在") try: await pb_sync.delete_channel_group(group_id) except Exception: pass return {"ok": "true"} @app.post("/api/groups/bulk") async def groups_bulk(body: ChannelGroupBulkAction) -> dict[str, Any]: try: result = db.bulk_channel_groups(body.action, body.ids) except ValueError as exc: raise HTTPException(400, str(exc)) from exc for gid in result.get("ids") or []: try: if body.action == "delete": await pb_sync.delete_channel_group(gid) else: g = db.get_channel_group(gid) if g: await pb_sync.sync_channel_group(g) except Exception: pass return result @app.post("/api/groups/{group_id}/probe") async def groups_probe(group_id: str) -> dict[str, Any]: """Immediate poll via youtube monitor (emits live/offline events on edge).""" try: result = await yt_monitor.check_one(group_id) except ValueError as exc: raise HTTPException(404, str(exc)) from exc except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc group = db.get_channel_group(group_id) if group: try: await pb_sync.sync_channel_group(group) except Exception: pass return {"group": group, "probe": result, "result": result} @app.get("/api/youtube/health") async def youtube_health() -> dict[str, Any]: return await youtube_client.health() @app.get("/api/youtube/resolve") async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]: try: return await youtube_client.resolve(url) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.get("/api/youtube/channel") async def youtube_channel( url: str = Query(..., min_length=1), videos: bool = False, limit: int = Query(8, ge=1, le=30), ) -> dict[str, Any]: try: return await youtube_client.channel(url, videos=videos, limit=limit) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.get("/api/youtube/channel/live") async def youtube_channel_live(url: str = Query(..., min_length=1)) -> dict[str, Any]: try: return await youtube_client.channel_live(url) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.get("/api/youtube/video") async def youtube_video(url: str = Query(..., min_length=1)) -> dict[str, Any]: try: return await youtube_client.video(url) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.get("/api/youtube/search") async def youtube_search( q: str = Query(..., min_length=1), limit: int = Query(12, ge=1, le=30), ) -> dict[str, Any]: try: return await youtube_client.search(q, limit=limit) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.post("/api/youtube/batch/live") async def youtube_batch_live(body: dict[str, Any]) -> dict[str, Any]: items = body.get("items") or body.get("urls") or [] if not isinstance(items, list): raise HTTPException(400, "items 必须是数组") try: return await youtube_client.batch_live([str(x) for x in items]) except YouTubeSvcError as exc: raise HTTPException(exc.status_code or 400, str(exc)) from exc @app.get("/api/events") async def events_list( kind: str = "", q: str = "", platform: str = "", 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) @app.get("/api/events/stream") async def events_stream(): async def gen(): q = await bus.subscribe() try: yield 'event: hello\ndata: {"ok":true}\n\n' while True: try: item = await asyncio.wait_for(q.get(), timeout=20) yield bus.encode(item) except asyncio.TimeoutError: yield ": keepalive\n\n" finally: await bus.unsubscribe(q) return StreamingResponse( gen(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, ) @app.post("/api/events/purge") async def events_purge(body: PurgeEventsBody) -> dict[str, Any]: deleted = db.purge_events(older_than_days=body.older_than_days, kind=body.kind) db.add_event(kind="ops", level="info", message=f"清理事件 {deleted} 条(>{body.older_than_days}天)") return {"deleted": deleted} @app.get("/api/events/export") async def events_export( kind: str = "", q: str = "", platform: str = "", format: str = Query("csv", pattern="^(csv|json)$"), ) -> Any: rows = db.export_events_rows(kind=kind, q=q, platform=platform, limit=5000) if format == "json": return {"events": rows, "total": len(rows)} buf = io.StringIO() writer = csv.writer(buf) writer.writerow(["id", "ts", "level", "kind", "room_id", "anchor_name", "message", "session_id"]) for e in rows: writer.writerow( [ e.get("id"), e.get("ts"), e.get("level"), e.get("kind"), e.get("room_id"), e.get("anchor_name"), e.get("message"), e.get("session_id"), ] ) buf.seek(0) filename = f"events_{stamp_beijing()}.csv" return StreamingResponse( iter(["\ufeff" + buf.getvalue()]), media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"}, ) @app.get("/api/sessions/active") async def sessions_active() -> dict[str, Any]: items = db.list_active_sessions() return {"sessions": items, "total": len(items)} @app.post("/api/sessions/end-all-active") async def sessions_end_all_active() -> dict[str, Any]: n = db.end_all_active_sessions(end_reason="manual") db.add_event(kind="ops", level="warn", message=f"手动结束全部进行中场次:{n}") return {"ended": n} @app.post("/api/sessions/{session_id}/end") async def sessions_end_one(session_id: str) -> dict[str, Any]: session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") if session.get("ended_at"): return {"session": session, "already_ended": True} ended = db.end_session(session_id, end_reason="manual") if not ended: raise HTTPException(404, "场次不存在") db.add_event( kind="ops", level="warn", message=f"手动结束场次:{ended.get('anchor_name') or ended.get('room_id') or session_id}", room_id=str(ended.get("room_id") or ""), session_id=session_id, anchor_name=str(ended.get("anchor_name") or ""), ) try: await pb_sync.sync_session(ended) except Exception: pass return {"session": ended, "already_ended": False} @app.post("/api/sessions/reconcile-stale") async def sessions_reconcile_stale() -> dict[str, Any]: result = db.reconcile_stale_active_sessions() if result.get("closed"): db.add_event( kind="ops", level="warn", message=f"对账关闭僵尸场次:{result['closed']}(保留 {result['kept']})", meta=result, ) return result @app.get("/api/anchors") async def anchors_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]: return {"anchors": db.list_anchors(limit=limit)} @app.get("/api/anchors/upcoming") async def anchors_upcoming( limit: int = Query(20, ge=1, le=50), priority_only: bool = False, ) -> dict[str, Any]: items = db.list_upcoming_opens(limit=limit, priority_only=priority_only) return {"items": items, "total": len(items)} @app.get("/api/anchors/{key}") async def anchors_detail(key: str) -> dict[str, Any]: profile = db.anchor_profile(key) if not profile: raise HTTPException(404, "未找到主播画像") profile["schedule"] = summarize_anchor_schedule(profile.get("sessions") or []) return profile @app.post("/api/notify/test") async def notify_test() -> dict[str, Any]: from .notify import send_webhook cfg = db.get_settings_map() url = str(cfg.get("notify_webhook_url") or "").strip() if not url: raise HTTPException(400, "未配置 Webhook URL") await send_webhook( "ops", { "message": "【测试】DouyinWEB Webhook 连通性检查", "test": True, "time": time.time(), }, ) return {"ok": True, "webhook": url} @app.get("/api/rooms/export") async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any: rows = db.export_rooms_rows() if format == "json": return {"rooms": rows, "total": len(rows)} buf = io.StringIO() writer = csv.writer(buf) writer.writerow(["id", "room_id", "url", "note", "tags", "enabled", "last_status", "last_anchor", "last_checked_at"]) for r in rows: writer.writerow( [ r.get("id"), r.get("room_id"), r.get("url"), r.get("note"), ",".join(r.get("tags") or []), 1 if r.get("enabled") else 0, r.get("last_status"), r.get("last_anchor"), r.get("last_checked_at"), ] ) buf.seek(0) filename = f"rooms_{stamp_beijing()}.csv" return StreamingResponse( iter(["\ufeff" + buf.getvalue()]), media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"}, ) @app.get("/api/sessions") async def sessions_list( q: str = "", date_from: str = "", date_to: str = "", status: str = "", tag: str = "", platform: str = "", limit: int = Query(50, ge=1, le=2000), offset: int = Query(0, ge=0), ) -> dict[str, Any]: return db.list_sessions( q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, platform=platform, limit=limit, offset=offset, ) @app.get("/api/sessions/stats") async def sessions_stats( q: str = "", date_from: str = "", date_to: str = "", status: str = "", tag: str = "", platform: str = "", top_anchors: int = Query(25, ge=1, le=50), ) -> dict[str, Any]: return summarize_sessions( q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, platform=platform, top_anchors=top_anchors, ) @app.get("/api/sessions/export") async def sessions_export( q: str = "", date_from: str = "", date_to: str = "", status: str = "", tag: str = "", platform: str = "", format: str = Query("csv", pattern="^(csv|json)$"), ) -> Any: rows = db.export_sessions_rows( q=q, date_from=date_from, date_to=date_to, status=status, tag=tag, platform=platform, limit=5000, ) if format == "json": return {"sessions": rows, "total": len(rows)} buf = io.StringIO() writer = csv.writer(buf) writer.writerow( ["id", "anchor_name", "room_id", "source_url", "title", "started_at", "ended_at", "duration_seconds", "push_date", "status", "end_reason"] ) for s in rows: writer.writerow( [ s.get("id"), s.get("anchor_name"), s.get("room_id"), s.get("source_url"), s.get("title"), s.get("started_at"), s.get("ended_at") or "", s.get("duration_seconds"), s.get("push_date"), s.get("status"), s.get("end_reason"), ] ) buf.seek(0) filename = f"sessions_{stamp_beijing()}.csv" return StreamingResponse( iter([buf.getvalue()]), media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="{filename}"'}, ) @app.get("/api/sessions/missing-covers") async def sessions_missing_covers(limit: int = Query(100, ge=1, le=500)) -> dict[str, Any]: items = db.list_sessions_missing_cover(limit=limit) return {"sessions": items, "total": len(items)} @app.get("/api/sessions/{session_id}") async def sessions_detail(session_id: str) -> dict[str, Any]: session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") return {"session": session} @app.get("/api/sessions/{session_id}/cover") async def sessions_cover(session_id: str): session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") cp = str(session.get("cover_path") or "") cache_headers = { "Cache-Control": "public, max-age=86400, immutable", } if cp.startswith("http://") or cp.startswith("https://"): # Fast path: redirect to public object URL (s3/feiniu) instead of proxying bytes. public_bases = [ str(settings.s3_public_base or "").rstrip("/"), "https://s3.nomadro.com", "https://feiniu.nomadro.com", ] if any(cp.startswith(b) for b in public_bases if b): return RedirectResponse(url=cp, status_code=302, headers=cache_headers) # Private bucket fallback: signed fetch via S3 API, then stream once. try: from . import s3_storage if s3_storage.s3_enabled() and settings.s3_bucket in cp: key = cp.split(f"/{settings.s3_bucket}/", 1)[-1] client = s3_storage._client() # noqa: SLF001 obj = client.get_object(Bucket=settings.s3_bucket, Key=key) body = obj["Body"].read() return StreamingResponse(iter([body]), media_type="image/jpeg", headers=cache_headers) except Exception: pass try: async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client: resp = await client.get(cp) if resp.status_code < 300 and resp.content: return StreamingResponse( iter([resp.content]), media_type="image/jpeg", headers=cache_headers ) except Exception: pass raise HTTPException(404, "远程封面不可用") path = cover_path_for(session_id) if not path: raise HTTPException(404, "无截图") return FileResponse(path, media_type="image/jpeg", headers=cache_headers) @app.post("/api/sessions/active/recapture-covers") async def recapture_active_covers() -> dict[str, Any]: """Capture covers for all currently active sessions (and upload to SeaweedFS if enabled).""" cfg = db.get_settings_map() cookie = str(cfg.get("dy_cookie") or "") proxy = str(cfg.get("http_proxy") or "").strip() or None items = db.list_active_sessions() ok = 0 fail = 0 results: list[dict[str, Any]] = [] for s in items: room = db.get_room(str(s.get("room_pk") or "")) if not room: fail += 1 results.append({"id": s.get("id"), "ok": False, "error": "no room"}) continue try: probed = await check_room(room["url"], cookie=cookie, proxy=proxy) outcome = await ensure_session_cover( str(s["id"]), stream_url=str(probed.get("stream_url") or ""), cover_image=str(probed.get("cover_image") or ""), ) if outcome.get("ok") and not outcome.get("skipped"): ok += 1 results.append({"id": s.get("id"), **outcome}) elif outcome.get("skipped"): results.append({"id": s.get("id"), "ok": True, "skipped": True}) else: fail += 1 results.append({"id": s.get("id"), **outcome}) except Exception as exc: fail += 1 results.append({"id": s.get("id"), "ok": False, "error": str(exc)}) await asyncio.sleep(1.2) return {"ok": ok, "fail": fail, "results": results} @app.post("/api/sessions/backfill-covers") async def backfill_missing_covers(limit: int = Query(40, ge=1, le=200)) -> dict[str, Any]: """ Backfill thumbnails for sessions missing cover_path. Uses live stream when still live; otherwise room cover / avatar image. """ cfg = db.get_settings_map() cookie = str(cfg.get("dy_cookie") or "") proxy = str(cfg.get("http_proxy") or "").strip() or None missing = db.list_sessions_missing_cover(limit=limit) ok = 0 fail = 0 results: list[dict[str, Any]] = [] for s in missing: room = db.get_room(str(s.get("room_pk") or "")) if not room: rid = str(s.get("room_id") or "") if rid: found = db.list_rooms(q=rid, limit=20) rooms = found.get("rooms") if isinstance(found, dict) else found for cand in rooms or []: if str(cand.get("room_id") or "") == rid: room = cand break if not room: fail += 1 results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), "ok": False, "error": "no room"}) continue try: probed = await check_room(room["url"], cookie=cookie, proxy=proxy) outcome = await ensure_session_cover( str(s["id"]), stream_url=str(probed.get("stream_url") or ""), cover_image=str(probed.get("cover_image") or ""), ) if outcome.get("ok") and not outcome.get("skipped"): ok += 1 elif not outcome.get("ok"): fail += 1 results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), **outcome}) except Exception as exc: fail += 1 results.append({"id": s.get("id"), "anchor": s.get("anchor_name"), "ok": False, "error": str(exc)}) await asyncio.sleep(1.0) return {"ok": ok, "fail": fail, "attempted": len(missing), "results": results} @app.post("/api/sessions/{session_id}/recapture") async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]: session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") stream_url = "" cover_image = "" if body: stream_url = str(body.get("stream_url") or "") cover_image = str(body.get("cover_image") or "") if not stream_url or not cover_image: room = db.get_room(session.get("room_pk") or "") if room: cfg = db.get_settings_map() result = await check_room( room["url"], cookie=str(cfg.get("dy_cookie") or ""), proxy=str(cfg.get("http_proxy") or "").strip() or None, ) stream_url = stream_url or str(result.get("stream_url") or "") cover_image = cover_image or str(result.get("cover_image") or "") # Force recapture even if cover exists outcome = await ensure_session_cover( session_id, stream_url=stream_url, cover_image=cover_image, force=True, ) if not outcome.get("ok"): raise HTTPException(400, outcome.get("error") or "无法获取封面(可能已停播且无房间封面)") return {"cover_url": f"/api/sessions/{session_id}/cover", **outcome} @app.post("/api/pb/bootstrap") async def pb_bootstrap() -> dict[str, Any]: return await pb_sync.ensure_collections() @app.post("/api/pb/sync-sessions") async def pb_sync_sessions(limit: int = Query(500, ge=1, le=5000)) -> dict[str, Any]: """Push recent SQLite sessions (incl. S3 cover_url) into PocketBase.""" await pb_sync.ensure_collections() rows = db.list_sessions(limit=limit, offset=0).get("sessions") or [] ok = 0 fail = 0 with_cover = 0 for s in rows: try: await pb_sync.sync_session(s) ok += 1 if str(s.get("cover_path") or "").startswith("http"): with_cover += 1 except Exception: fail += 1 return {"ok": ok, "fail": fail, "with_s3_cover": with_cover, "attempted": len(rows)} @app.post("/api/pb/sync-rooms") async def pb_sync_rooms(limit: int = Query(2000, ge=1, le=5000)) -> dict[str, Any]: await pb_sync.ensure_collections() rooms = (db.list_rooms(limit=limit, offset=0).get("rooms") or []) ok = 0 fail = 0 for r in rooms: try: await pb_sync.sync_room(r) ok += 1 except Exception: fail += 1 return {"ok": ok, "fail": fail, "attempted": len(rooms)} @app.post("/api/pb/sync-groups") async def pb_sync_groups(limit: int = Query(2000, ge=1, le=5000)) -> dict[str, Any]: """Push YouTube channel groups into PocketBase yt_groups.""" await pb_sync.ensure_collections() groups = (db.list_channel_groups(limit=limit, offset=0).get("groups") or []) ok = 0 fail = 0 for g in groups: try: rid = await pb_sync.sync_channel_group(g) if rid: ok += 1 else: fail += 1 except Exception: fail += 1 return {"ok": ok, "fail": fail, "attempted": len(groups), "collection": "yt_groups"} @app.post("/api/demo/seed") async def demo_seed() -> dict[str, Any]: created_rooms = [] samples = [ ("https://live.douyin.com/123456789012", "示例直播间 A", "demo"), ("https://live.douyin.com/234567890123", "示例直播间 B", "demo"), ("https://live.douyin.com/345678901234", "示例直播间 C", "demo"), ] for url, note, tags in samples: try: created_rooms.append(db.create_room(url, note=note, enabled=True, tags=tags)) except ValueError: pass now = time.time() if created_rooms: for i, room in enumerate(created_rooms[:2]): sid = db.start_session( room_pk=room["id"], room_id=room["room_id"], source_url=room["url"], anchor_name=f"示例主播{i+1}", title="演示场次", ) with db._lock: conn = db._connect() try: started = now - (3600 * (i + 2)) - (i * 86400) ended = started + 3600 * (1.5 + i) conn.execute( """ UPDATE sessions SET started_at = ?, ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = 'demo', push_date = date(?, 'unixepoch', '+8 hours'), updated_at = ? WHERE id = ? """, (started, ended, ended - started, started, now, sid["id"]), ) conn.execute( "UPDATE rooms SET active_session_id = '', last_status = 'offline', last_anchor = ?, updated_at = ? WHERE id = ?", (f"示例主播{i+1}", now, room["id"]), ) conn.commit() finally: conn.close() db.add_event( kind="demo", level="info", message=f"演示场次:示例主播{i+1}", room_id=room["room_id"], room_pk=room["id"], session_id=sid["id"], anchor_name=f"示例主播{i+1}", ) return {"rooms": created_rooms, "message": "已写入演示数据"}