3794 lines
131 KiB
Python
3794 lines
131 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import csv
|
||
import io
|
||
import json
|
||
import os
|
||
import subprocess
|
||
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, WebSocket, WebSocketDisconnect
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
import httpx
|
||
|
||
from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage
|
||
from . import yt_assign_db
|
||
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,
|
||
ShortsJobsBulkBody,
|
||
TikTokChannelCreate,
|
||
TikTokChannelUpdate,
|
||
TikTokJobsBulkBody,
|
||
TikTokOAuthConfig,
|
||
TikTokSessionBody,
|
||
TikTokSocksProfilesBody,
|
||
TikTokUploadNowBody,
|
||
X2IngestBody,
|
||
YouTubeVideoUpdate,
|
||
YtAssignFeaturedAdd,
|
||
YtAssignFeaturedSet,
|
||
YtAssignSlotAdd,
|
||
YtAssignSlotSet,
|
||
YtAssignAutoFillBody,
|
||
YtAssignGroupCreate,
|
||
YtAssignGroupUpdate,
|
||
YtAssignPoolAdd,
|
||
YtAssignPoolUpdate,
|
||
)
|
||
from .monitor import monitor
|
||
from .stats import summarize_anchor_schedule, summarize_sessions
|
||
from .youtube_client import YouTubeSvcError
|
||
from . import douyin_live, youtube_live
|
||
from .auth import ApiKeyMiddleware
|
||
from .session_auth import (
|
||
SessionAuthMiddleware,
|
||
clear_session_cookie,
|
||
change_admin_password,
|
||
session_user_from_request,
|
||
set_session_cookie,
|
||
verify_admin,
|
||
_request_secure,
|
||
)
|
||
from .youtube_monitor import yt_monitor
|
||
from .shorts_pipeline import shorts_pipeline
|
||
from .tiktok_pipeline import tiktok_pipeline
|
||
from .x_clips_pipeline import x_clips_pipeline
|
||
from .yt_long_pipeline import yt_long_pipeline
|
||
from . import tiktok_session
|
||
from .timeutil import stamp_beijing
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(_: FastAPI):
|
||
await asyncio.to_thread(db.init_db)
|
||
try:
|
||
from .session_auth import ensure_default_admin_credentials
|
||
|
||
await asyncio.to_thread(ensure_default_admin_credentials)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
from .yt_channel_meta import ensure_default_brand_hints
|
||
|
||
await asyncio.to_thread(ensure_default_brand_hints)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await asyncio.to_thread(cookie_loader.bootstrap_cookie_into_db)
|
||
except Exception:
|
||
pass
|
||
|
||
async def _pb_boot() -> None:
|
||
try:
|
||
await pb_sync.ensure_collections()
|
||
except Exception:
|
||
pass
|
||
|
||
_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:
|
||
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 asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await asyncio.sleep(30)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
|
||
if not _desktop_light:
|
||
asyncio.create_task(_live_map_refresh_loop())
|
||
|
||
async def _ops_background_loops() -> None:
|
||
if _desktop_light:
|
||
return
|
||
from .db_backup import backup_loop
|
||
from .ops_alerts import alert_loop
|
||
|
||
asyncio.create_task(backup_loop())
|
||
asyncio.create_task(alert_loop())
|
||
|
||
asyncio.create_task(_ops_background_loops())
|
||
|
||
async def _start_workers() -> None:
|
||
if _desktop_light:
|
||
return
|
||
|
||
async def _boot(name: str, starter) -> None:
|
||
try:
|
||
await starter()
|
||
except Exception as exc:
|
||
try:
|
||
db.add_event(
|
||
kind="ops",
|
||
level="error",
|
||
message=f"worker 启动失败:{name} — {str(exc)[:160]}",
|
||
meta={"worker": name, "error": str(exc)[:240]},
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
await _boot("monitor", monitor.start)
|
||
await _boot("yt_monitor", yt_monitor.start)
|
||
await _boot("shorts", shorts_pipeline.start)
|
||
await _boot("tiktok", tiktok_pipeline.start)
|
||
await _boot("x_clips", x_clips_pipeline.start)
|
||
await _boot("yt_long", yt_long_pipeline.start)
|
||
|
||
asyncio.create_task(_start_workers())
|
||
yield
|
||
try:
|
||
await yt_long_pipeline.stop()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await x_clips_pipeline.stop()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await tiktok_pipeline.stop()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await shorts_pipeline.stop()
|
||
except Exception:
|
||
pass
|
||
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)
|
||
|
||
_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=["*"],
|
||
)
|
||
|
||
# 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]:
|
||
"""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(),
|
||
"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["yt_long"] = await asyncio.to_thread(yt_long_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]}
|
||
|
||
def _s3() -> dict[str, Any]:
|
||
from . import s3_storage
|
||
|
||
enabled = s3_storage.s3_enabled()
|
||
info: dict[str, Any] = {
|
||
"enabled": enabled,
|
||
"ok": False,
|
||
"endpoint": settings.s3_endpoint,
|
||
"bucket": settings.s3_bucket,
|
||
"public_base": settings.s3_public_base,
|
||
}
|
||
if not enabled:
|
||
return info
|
||
try:
|
||
s3_storage._client().head_bucket(Bucket=settings.s3_bucket) # noqa: SLF001
|
||
info["ok"] = True
|
||
except Exception as exc:
|
||
info["error"] = str(exc)[:120]
|
||
return info
|
||
|
||
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]}
|
||
try:
|
||
out["s3"] = await asyncio.wait_for(asyncio.to_thread(_s3), timeout=1.0)
|
||
except Exception as exc:
|
||
out["s3"] = {"enabled": False, "ok": False, "error": str(exc)[:120]}
|
||
return out
|
||
|
||
|
||
@app.get("/api/auth/status")
|
||
async def auth_status(request: Request) -> dict[str, Any]:
|
||
from .authz import session_payload_from_request, session_role_from_request, readonly_enabled
|
||
|
||
user = session_user_from_request(request)
|
||
role = session_role_from_request(request) if user else ""
|
||
return {
|
||
"api_key_required": bool(str(settings.api_key or "").strip()),
|
||
"auth_enabled": bool(settings.auth_enabled),
|
||
"authenticated": bool(user),
|
||
"username": user or "",
|
||
"role": role or ("admin" if user else ""),
|
||
"readonly_enabled": readonly_enabled(),
|
||
}
|
||
|
||
|
||
@app.get("/api/auth/me")
|
||
async def auth_me(request: Request) -> dict[str, Any]:
|
||
from .authz import session_role_from_request
|
||
|
||
user = session_user_from_request(request)
|
||
if not user and settings.auth_enabled:
|
||
raise HTTPException(401, "未登录")
|
||
return {
|
||
"ok": True,
|
||
"username": user or settings.admin_username,
|
||
"role": session_role_from_request(request) or "admin",
|
||
}
|
||
|
||
|
||
@app.post("/api/auth/login")
|
||
async def auth_login(request: Request, body: dict[str, Any]) -> JSONResponse:
|
||
from .authz import verify_readonly
|
||
|
||
username = str(body.get("username") or body.get("user") or "").strip()
|
||
password = str(body.get("password") or "")
|
||
role = "admin"
|
||
if verify_admin(username, password):
|
||
role = "admin"
|
||
elif verify_readonly(username, password):
|
||
role = "readonly"
|
||
else:
|
||
raise HTTPException(401, "用户名或密码错误")
|
||
resp = JSONResponse({"ok": True, "username": username, "role": role})
|
||
set_session_cookie(resp, username, secure=_request_secure(request), role=role)
|
||
return resp
|
||
|
||
|
||
@app.post("/api/auth/logout")
|
||
async def auth_logout() -> JSONResponse:
|
||
resp = JSONResponse({"ok": True})
|
||
clear_session_cookie(resp)
|
||
return resp
|
||
|
||
|
||
@app.post("/api/auth/change-password")
|
||
async def auth_change_password(request: Request, body: dict[str, Any]) -> dict[str, Any]:
|
||
user = session_user_from_request(request)
|
||
if not user and settings.auth_enabled:
|
||
raise HTTPException(401, "未登录")
|
||
current = str(body.get("current_password") or body.get("current") or "")
|
||
new_pw = str(body.get("new_password") or body.get("new") or "")
|
||
confirm = str(body.get("confirm_password") or body.get("confirm") or "")
|
||
if new_pw != confirm:
|
||
raise HTTPException(400, "两次输入的新密码不一致")
|
||
try:
|
||
change_admin_password(username=str(user or ""), current_password=current, new_password=new_pw)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
return {"ok": True, "message": "密码已更新,请重新登录"}
|
||
|
||
|
||
@app.get("/api/monitor/status")
|
||
async def monitor_status() -> dict[str, Any]:
|
||
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]:
|
||
await _db(db.update_settings_map, {"monitor_enabled": True})
|
||
await monitor.start()
|
||
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]:
|
||
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()
|
||
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]:
|
||
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
|
||
|
||
|
||
@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 "")
|
||
client_id = str(out.get("client_id") or "").strip()
|
||
profile_id = str(out.get("oauth_profile_id") or "").strip().upper()
|
||
out["oauth_profile_id"] = profile_id
|
||
out["has_client_id"] = bool(client_id)
|
||
out["has_client_secret"] = bool(secret.strip())
|
||
out["has_refresh_token"] = bool(refresh.strip())
|
||
out["authorized"] = bool(refresh.strip())
|
||
oauth_meta = shorts_oauth.resolve_oauth_client(ch)
|
||
out["oauth_client_source"] = str(oauth_meta.get("source") or "none")
|
||
out["has_custom_oauth"] = out["oauth_client_source"] in {"profile", "channel"}
|
||
out["can_authorize"] = shorts_oauth.channel_can_authorize(ch)
|
||
prof = shorts_oauth.get_oauth_profile(profile_id) if profile_id else None
|
||
out["oauth_profile_label"] = str((prof or {}).get("label") or "") if prof else ""
|
||
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 "")
|
||
out["client_id"] = client_id
|
||
try:
|
||
out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1)
|
||
except Exception:
|
||
out["oauth_ok"] = -1
|
||
out["oauth_checked_at"] = float(out.get("oauth_checked_at") or 0)
|
||
out["oauth_error"] = str(out.get("oauth_error") or "")
|
||
return out
|
||
|
||
|
||
def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]:
|
||
"""Mask OAuth secrets in settings API responses."""
|
||
from . import shorts_socks
|
||
|
||
out = dict(cfg)
|
||
secret = str(out.get("shorts_oauth_client_secret") or "")
|
||
if secret and not str(secret).startswith("***"):
|
||
out["shorts_oauth_client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else "***"
|
||
out["shorts_oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
|
||
out["shorts_upload_socks_profiles"] = shorts_socks.list_socks_profiles(cfg, public=True)
|
||
out["shorts_upload_socks_enabled"] = bool(cfg.get("shorts_upload_socks_enabled"))
|
||
out["shorts_upload_socks_profile_id"] = str(cfg.get("shorts_upload_socks_profile_id") or "")
|
||
from . import yt_studio_auth
|
||
|
||
out["yt_studio_cookies_by_profile"] = yt_studio_auth.public_studio_cookies_by_profile(cfg)
|
||
tt_secret = str(out.get("tiktok_oauth_client_secret") or "")
|
||
if tt_secret and not tt_secret.startswith("***"):
|
||
out["tiktok_oauth_client_secret"] = ("***" + tt_secret[-4:]) if len(tt_secret) > 4 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"
|
||
|
||
|
||
def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
|
||
if not job:
|
||
return None
|
||
from pathlib import Path
|
||
|
||
from .job_errors import enrich_job_error
|
||
from .title_assist import title_candidates
|
||
|
||
out = dict(job)
|
||
clip = str(out.get("clip_path") or "").strip()
|
||
out["clip_ready"] = bool(clip) and Path(clip).is_file()
|
||
ch = db.get_shorts_channel(str(out.get("channel_pk") or "")) or {}
|
||
if ch:
|
||
out["channel_name"] = str(ch.get("name") or out.get("channel_name") or "")
|
||
out["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
|
||
else:
|
||
out.setdefault("channel_name", "")
|
||
out.setdefault("oauth_profile_id", "")
|
||
out = enrich_job_error(out, platform="shorts") or out
|
||
out["title_candidates"] = title_candidates(
|
||
platform="shorts",
|
||
anchor=str(out.get("anchor_name") or ""),
|
||
url=str(out.get("source_url") or ""),
|
||
template=str(ch.get("title_template") or ""),
|
||
)
|
||
return out
|
||
|
||
|
||
def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
|
||
from pathlib import Path
|
||
|
||
job = db.get_shorts_job(job_id)
|
||
if not job:
|
||
raise ValueError("任务不存在")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if clip and Path(clip).is_file():
|
||
from .shorts_schedule import pick_upload_at
|
||
|
||
cfg = db.get_settings_map()
|
||
upload_at = pick_upload_at(
|
||
channel_pk=str(job.get("channel_pk") or ""),
|
||
push_date=str(job.get("push_date") or ""),
|
||
cfg=cfg,
|
||
)
|
||
return db.update_shorts_job(
|
||
job_id,
|
||
status="scheduled",
|
||
error="",
|
||
finished_at=0,
|
||
youtube_video_id="",
|
||
youtube_url="",
|
||
upload_at=upload_at,
|
||
)
|
||
return db.update_shorts_job(
|
||
job_id,
|
||
status="pending",
|
||
clip_path="",
|
||
clip_seconds=0,
|
||
error="成片已丢失,已重新排队录制" if clip else "",
|
||
finished_at=0,
|
||
youtube_video_id="",
|
||
youtube_url="",
|
||
upload_at=0,
|
||
)
|
||
|
||
|
||
@app.get("/api/shorts/status")
|
||
async def shorts_status() -> dict[str, Any]:
|
||
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 = await _db(db.get_settings_map)
|
||
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
||
st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
|
||
return st
|
||
|
||
|
||
@app.get("/api/shorts/live-analytics")
|
||
async def shorts_live_analytics(
|
||
date_from: str = "",
|
||
date_to: str = "",
|
||
top_anchors: int = Query(25, ge=1, le=50),
|
||
) -> dict[str, Any]:
|
||
"""Shorts 上传频道自身开播分析(live-map 轮询写入的 sessions)。"""
|
||
stats = summarize_sessions(
|
||
date_from=date_from,
|
||
date_to=date_to,
|
||
platform="shorts",
|
||
top_anchors=top_anchors,
|
||
)
|
||
channels = db.shorts_live_channel_stats(date_from=date_from, date_to=date_to)
|
||
ypp_by_shorts: dict[str, int] = {}
|
||
try:
|
||
from . import yt_long_db, youtube_manage
|
||
|
||
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
|
||
enriched = []
|
||
for c in channels:
|
||
row = dict(c)
|
||
pk = str(row.get("id") or "")
|
||
if pk:
|
||
ch = db.get_shorts_channel(pk) or {}
|
||
row["yt_profile"] = youtube_manage._snippet_from_channel_row(ch)
|
||
row["authorized"] = bool(str(ch.get("refresh_token") or "").strip())
|
||
row["oauth_ok"] = ch.get("oauth_ok")
|
||
row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
|
||
row["ypp_ok"] = ypp_by_shorts.get(pk, -1)
|
||
enriched.append(row)
|
||
channels = enriched
|
||
except Exception:
|
||
pass
|
||
recent = db.list_sessions(platform="shorts", limit=20, offset=0)
|
||
live_now = sum(1 for c in channels if int(c.get("active") or 0) > 0 or str(c.get("last_status") or "") == "live")
|
||
return {
|
||
"ok": True,
|
||
"platform": "shorts",
|
||
"stats": stats,
|
||
"channels": channels,
|
||
"recent_sessions": recent.get("sessions") or [],
|
||
"recent_total": recent.get("total") or 0,
|
||
"live_now": live_now,
|
||
}
|
||
|
||
|
||
@app.get("/api/shorts/oauth/start")
|
||
async def shorts_oauth_start(channel_pk: str, request: Request, return_to: str = "") -> RedirectResponse:
|
||
try:
|
||
await shorts_oauth.prepare_reauthorize(channel_pk)
|
||
ret = str(return_to or request.query_params.get("return_to") or "").strip()
|
||
url = shorts_oauth.build_authorize_url(
|
||
channel_pk=channel_pk,
|
||
request_base=_request_public_base(request),
|
||
return_to=ret,
|
||
)
|
||
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"))
|
||
handle = quote(str(result.get("youtube_handle") or ""))
|
||
ret = str(result.get("return_to") or "").strip()
|
||
if ret:
|
||
sep = "&" if "?" in ret else "?"
|
||
return RedirectResponse(
|
||
f"{base}{ret}{sep}oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
|
||
status_code=302,
|
||
)
|
||
return RedirectResponse(
|
||
f"{base}/shorts?oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
|
||
status_code=302,
|
||
)
|
||
except Exception as exc:
|
||
ret = str(request.query_params.get("return_to") or "").strip()
|
||
msg = quote(str(exc)[:320])
|
||
if ret and ret.startswith("/") and not ret.startswith("//"):
|
||
sep = "&" if "?" in ret else "?"
|
||
return RedirectResponse(f"{base}{ret}{sep}oauth=error&msg={msg}", status_code=302)
|
||
return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote(str(exc)[:320])}", 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 sample current Douyin lives and start recording immediately."""
|
||
from .shorts_pipeline import sample_live_now
|
||
|
||
cfg = db.get_settings_map()
|
||
if not cfg.get("shorts_enabled"):
|
||
raise HTTPException(400, "请先启用 Shorts")
|
||
result = await asyncio.to_thread(sample_live_now, cfg)
|
||
recording = await shorts_pipeline.kick_pending_records(list(result.get("job_ids") or []))
|
||
st = shorts_pipeline.status()
|
||
st["just_enqueued"] = int(result.get("enqueued") or 0)
|
||
st["just_sampled"] = int(result.get("enqueued") or 0)
|
||
st["just_quota_filled"] = 0
|
||
st["live_count"] = int(result.get("live_count") or 0)
|
||
st["skipped_dedupe"] = int(result.get("skipped_dedupe") or 0)
|
||
st["recording"] = recording
|
||
st["reason"] = str(result.get("reason") or "")
|
||
return st
|
||
|
||
|
||
@app.post("/api/shorts/fill-quota")
|
||
async def shorts_fill_quota() -> dict[str, Any]:
|
||
"""Manually trigger Beijing-day quota fill toward daily_max per channel."""
|
||
from .shorts_pipeline import try_fill_daily_quota
|
||
|
||
cfg = db.get_settings_map()
|
||
if not cfg.get("shorts_enabled"):
|
||
raise HTTPException(400, "请先启用 Shorts")
|
||
qn = try_fill_daily_quota(cfg)
|
||
st = shorts_pipeline.status()
|
||
st["just_quota_filled"] = qn
|
||
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]:
|
||
stats = db.delete_shorts_channel(channel_pk)
|
||
return {"ok": True, **stats}
|
||
|
||
|
||
@app.get("/api/shorts/jobs")
|
||
async def shorts_jobs_list(
|
||
status: str = "",
|
||
push_date: str = "",
|
||
channel_pk: str = "",
|
||
session_id: str = "",
|
||
room_id: str = "",
|
||
limit: int = Query(100, ge=1, le=500),
|
||
offset: int = Query(0, ge=0),
|
||
) -> dict[str, Any]:
|
||
data = db.list_shorts_jobs(
|
||
status=status,
|
||
push_date=push_date,
|
||
channel_pk=channel_pk,
|
||
session_id=session_id,
|
||
room_id=room_id,
|
||
limit=limit,
|
||
offset=offset,
|
||
)
|
||
data["jobs"] = [_enrich_shorts_job(j) for j in data.get("jobs") or []]
|
||
return data
|
||
|
||
|
||
@app.post("/api/shorts/jobs/{job_id}/retry")
|
||
async def shorts_job_retry(job_id: str) -> dict[str, Any]:
|
||
try:
|
||
updated = _retry_shorts_job_record(job_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(404, str(exc)) from exc
|
||
return {"job": _enrich_shorts_job(updated)}
|
||
|
||
|
||
@app.get("/api/shorts/jobs/{job_id}")
|
||
async def shorts_job_get(job_id: str) -> dict[str, Any]:
|
||
job = _enrich_shorts_job(db.get_shorts_job(job_id))
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
ch = db.get_shorts_channel(str(job.get("channel_pk") or ""))
|
||
if ch:
|
||
anchor = str(job.get("anchor_name") or job.get("room_id") or "live")
|
||
url = str(job.get("source_url") or "")
|
||
title_tpl = str(ch.get("title_template") or "{anchor} #Shorts")
|
||
desc_tpl = str(ch.get("description_template") or "")
|
||
job["preview_title"] = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
||
job["preview_description"] = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
||
job["channel_name"] = ch.get("name") or ""
|
||
return {"job": job}
|
||
|
||
|
||
@app.get("/api/shorts/jobs/{job_id}/clip")
|
||
async def shorts_job_clip(job_id: str):
|
||
from pathlib import Path
|
||
|
||
job = db.get_shorts_job(job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if not clip:
|
||
raise HTTPException(404, "无成片")
|
||
path = Path(clip).resolve()
|
||
clips_root = settings.clips_dir.resolve()
|
||
try:
|
||
path.relative_to(clips_root)
|
||
except ValueError as exc:
|
||
raise HTTPException(403, "非法路径") from exc
|
||
if not path.is_file():
|
||
raise HTTPException(404, "成片文件不存在")
|
||
return FileResponse(
|
||
path,
|
||
media_type="video/mp4",
|
||
filename=f"{job_id}.mp4",
|
||
headers={"Cache-Control": "private, max-age=300"},
|
||
)
|
||
|
||
|
||
@app.post("/api/shorts/jobs/bulk")
|
||
async def shorts_jobs_bulk(body: ShortsJobsBulkBody) -> dict[str, Any]:
|
||
action = (body.action or "retry").strip().lower()
|
||
if action not in {"retry", "upload_now"}:
|
||
raise HTTPException(400, "action 须为 retry 或 upload_now")
|
||
ids = [str(x).strip() for x in (body.job_ids or []) if str(x).strip()][:30]
|
||
if not ids:
|
||
raise HTTPException(400, "job_ids 为空")
|
||
results: list[dict[str, Any]] = []
|
||
ok = 0
|
||
for jid in ids:
|
||
try:
|
||
if action == "retry":
|
||
job = _enrich_shorts_job(_retry_shorts_job_record(jid))
|
||
results.append({"id": jid, "ok": True, "status": job.get("status") if job else ""})
|
||
ok += 1
|
||
else:
|
||
job = await shorts_pipeline.upload_job_now(jid)
|
||
results.append({"id": jid, "ok": True, "status": str(job.get("status") or "")})
|
||
ok += 1
|
||
except ValueError as exc:
|
||
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||
except Exception as exc:
|
||
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||
return {"ok_count": ok, "total": len(ids), "results": results}
|
||
|
||
|
||
@app.post("/api/shorts/reconcile")
|
||
async def shorts_reconcile() -> dict[str, Any]:
|
||
orphans = db.purge_orphan_shorts_jobs(limit=500)
|
||
missing = db.reconcile_missing_shorts_clips(limit=200)
|
||
healed = db.reconcile_false_failed_shorts(limit=200)
|
||
stale = db.reclaim_stale_shorts_uploads(max_age_sec=900)
|
||
return {
|
||
"orphan_jobs": orphans.get("jobs", 0),
|
||
"orphan_clips": orphans.get("clips", 0),
|
||
"missing_clips": missing,
|
||
"false_failed": healed,
|
||
"stale_uploads": stale,
|
||
}
|
||
|
||
|
||
@app.get("/api/shorts/stats/history")
|
||
async def shorts_stats_history(days: int = Query(7, ge=1, le=30)) -> dict[str, Any]:
|
||
return db.shorts_stats_history(days=days)
|
||
|
||
|
||
@app.get("/api/shorts/failed-groups")
|
||
async def shorts_failed_groups(
|
||
push_date: str = "",
|
||
limit: int = Query(40, ge=1, le=200),
|
||
) -> dict[str, Any]:
|
||
return db.shorts_failed_groups(push_date=push_date, limit=limit)
|
||
|
||
|
||
@app.get("/api/shorts/stats/channels")
|
||
async def shorts_stats_channels(days: int = Query(7, ge=1, le=30)) -> dict[str, Any]:
|
||
return db.shorts_channel_performance(days=days)
|
||
|
||
|
||
@app.post("/api/shorts/jobs/retry-all-failed")
|
||
async def shorts_retry_all_failed(
|
||
push_date: str = "",
|
||
limit: int = Query(50, ge=1, le=100),
|
||
) -> dict[str, Any]:
|
||
"""Re-queue recent failed jobs (re-record if clip missing, else reschedule)."""
|
||
ids = db.list_failed_shorts_job_ids(push_date=push_date, limit=limit)
|
||
ok = 0
|
||
results: list[dict[str, Any]] = []
|
||
for jid in ids:
|
||
try:
|
||
job = _enrich_shorts_job(_retry_shorts_job_record(jid))
|
||
results.append({"id": jid, "ok": True, "status": job.get("status") if job else ""})
|
||
ok += 1
|
||
except ValueError as exc:
|
||
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||
except Exception as exc:
|
||
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||
return {"ok_count": ok, "total": len(ids), "results": results}
|
||
|
||
|
||
@app.get("/api/shorts/stats/heatmap")
|
||
async def shorts_stats_heatmap(days: int = Query(1, ge=1, le=14)) -> dict[str, Any]:
|
||
return db.shorts_upload_heatmap(days=days)
|
||
|
||
|
||
@app.post("/api/shorts/oauth/probe")
|
||
async def shorts_oauth_probe(channel_pk: str = "") -> dict[str, Any]:
|
||
"""Probe one channel or all enabled channels' refresh tokens."""
|
||
if channel_pk.strip():
|
||
ch = db.get_shorts_channel(channel_pk.strip())
|
||
if not ch:
|
||
raise HTTPException(404, "频道不存在")
|
||
result = await shorts_oauth.probe_channel_oauth(ch)
|
||
return {"ok": bool(result.get("ok")), **result, "channel": _public_shorts_channel(db.get_shorts_channel(channel_pk.strip()) or ch)}
|
||
data = await shorts_oauth.probe_all_enabled_channels()
|
||
return data
|
||
|
||
|
||
@app.post("/api/shorts/jobs/{job_id}/upload-now")
|
||
async def shorts_job_upload_now(job_id: str) -> dict[str, Any]:
|
||
"""Upload a recorded/scheduled clip immediately (bypass staggered slot)."""
|
||
try:
|
||
job = await shorts_pipeline.upload_job_now(job_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
return {"ok": True, "job": _enrich_shorts_job(job)}
|
||
|
||
|
||
@app.get("/api/shorts/schedule")
|
||
async def shorts_schedule() -> dict[str, Any]:
|
||
from .shorts_schedule import schedule_board
|
||
|
||
return schedule_board(limit=40)
|
||
|
||
|
||
# ---------- X2 (Twitter/X ops agent ingest) ----------
|
||
|
||
@app.post("/api/x2/ingest")
|
||
async def x2_ingest(request: Request, body: X2IngestBody) -> dict[str, Any]:
|
||
"""Receive heartbeats / accounts / jobs from X2 Agent or Chrome extension."""
|
||
from . import x2_db
|
||
|
||
token = (
|
||
(request.headers.get("X-X2-Token") or "")
|
||
or (request.headers.get("x-x2-token") or "")
|
||
or (request.headers.get("X-API-Key") or "")
|
||
or (request.query_params.get("token") or "")
|
||
).strip()
|
||
if not x2_db.verify_ingest_token(token):
|
||
raise HTTPException(401, "无效 X2 Token(请求头 X-X2-Token)")
|
||
payload = body.model_dump()
|
||
return await _db(x2_db.ingest_payload, payload)
|
||
|
||
|
||
@app.get("/api/x2/status")
|
||
async def x2_status() -> dict[str, Any]:
|
||
from . import x2_db
|
||
|
||
snap = await _db(x2_db.status_snapshot)
|
||
token = await _db(x2_db.ensure_ingest_token)
|
||
snap["ingest_token"] = token
|
||
snap["ingest_url"] = "/api/x2/ingest"
|
||
return snap
|
||
|
||
|
||
@app.post("/api/x2/token/rotate")
|
||
async def x2_token_rotate() -> dict[str, Any]:
|
||
from . import db as _dbmod
|
||
from . import x2_db
|
||
import secrets as _secrets
|
||
|
||
token = _secrets.token_urlsafe(24)
|
||
await _db(_dbmod.update_settings_map, {"x2_ingest_token": token})
|
||
return {"ok": True, "ingest_token": token}
|
||
|
||
|
||
@app.get("/api/x2/jobs")
|
||
async def x2_jobs_list(
|
||
agent_id: str = "",
|
||
limit: int = Query(40, ge=1, le=200),
|
||
) -> dict[str, Any]:
|
||
from . import x2_db
|
||
|
||
jobs = await _db(x2_db.list_jobs, limit=limit, agent_id=agent_id)
|
||
return {"jobs": jobs}
|
||
|
||
|
||
@app.get("/api/x2/accounts")
|
||
async def x2_accounts_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
|
||
from . import x2_db
|
||
|
||
rows = await _db(x2_db.list_accounts, limit=limit)
|
||
return {"accounts": rows}
|
||
|
||
|
||
@app.post("/api/x2/jobs")
|
||
async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
||
"""Web console creates a job; Chrome extension claims & executes it."""
|
||
from . import x2_db
|
||
from .x2_ws import hub
|
||
|
||
kind = str(body.get("kind") or "").strip()
|
||
params = body.get("params") if isinstance(body.get("params"), dict) else {}
|
||
try:
|
||
job = await _db(x2_db.create_web_job, kind, params)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
# Push to idle WebSocket helpers immediately (poll fallback still works)
|
||
try:
|
||
await hub.dispatch_queued()
|
||
except Exception:
|
||
pass
|
||
return {"ok": True, "job": job}
|
||
|
||
|
||
@app.post("/api/x2/media/upload")
|
||
async def x2_media_upload(request: Request) -> dict[str, Any]:
|
||
"""Upload image/video to S3 staging for engage.post; local temp deleted after upload."""
|
||
from . import x2_media
|
||
|
||
form = await request.form()
|
||
upload = form.get("file")
|
||
if upload is None:
|
||
raise HTTPException(400, "缺少 file")
|
||
filename = str(getattr(upload, "filename", None) or "media.bin")
|
||
content_type = str(getattr(upload, "content_type", None) or "")
|
||
try:
|
||
data = await upload.read() # type: ignore[attr-defined]
|
||
except Exception as exc:
|
||
raise HTTPException(400, f"读取文件失败: {exc}") from exc
|
||
try:
|
||
return await asyncio.to_thread(
|
||
x2_media.upload_media_bytes,
|
||
data,
|
||
filename=filename,
|
||
content_type=content_type,
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"上传失败: {exc}") from exc
|
||
|
||
|
||
@app.post("/api/x2/media/cleanup")
|
||
async def x2_media_cleanup(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
"""Manual cleanup of staged S3 keys (also runs automatically when job ends)."""
|
||
from . import x2_media
|
||
|
||
payload = body if isinstance(body, dict) else {}
|
||
keys = payload.get("keys") if isinstance(payload.get("keys"), list) else []
|
||
return x2_media.cleanup_media_keys([str(k) for k in keys])
|
||
|
||
|
||
# ---------- X live clips (isolated auto text+video from Douyin live) ----------
|
||
|
||
|
||
@app.get("/api/x-clips/status")
|
||
async def x_clips_status() -> dict[str, Any]:
|
||
return await asyncio.to_thread(x_clips_pipeline.status)
|
||
|
||
|
||
@app.post("/api/x-clips/start")
|
||
async def x_clips_start() -> dict[str, Any]:
|
||
db.update_settings_map({"x_clips_enabled": True})
|
||
try:
|
||
await x_clips_pipeline.start()
|
||
except Exception:
|
||
pass
|
||
return x_clips_pipeline.status()
|
||
|
||
|
||
@app.post("/api/x-clips/stop")
|
||
async def x_clips_stop() -> dict[str, Any]:
|
||
db.update_settings_map({"x_clips_enabled": False})
|
||
return x_clips_pipeline.status()
|
||
|
||
|
||
@app.post("/api/x-clips/settings")
|
||
async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
patch: dict[str, Any] = {}
|
||
raw = body or {}
|
||
if "x_clips_clip_sec" in raw:
|
||
try:
|
||
patch["x_clips_clip_sec"] = max(15, min(20, int(raw["x_clips_clip_sec"])))
|
||
except Exception:
|
||
raise HTTPException(400, "clip_sec 无效") from None
|
||
if "x_clips_daily_max" in raw:
|
||
try:
|
||
patch["x_clips_daily_max"] = max(1, min(100, int(raw["x_clips_daily_max"])))
|
||
except Exception:
|
||
raise HTTPException(400, "daily_max 无效") from None
|
||
if "x_clips_caption_template" in raw:
|
||
# User custom (+1); empty means pool-only (100 English captions in DB)
|
||
patch["x_clips_caption_template"] = str(raw.get("x_clips_caption_template") or "").strip()[:200]
|
||
if "x_clips_account_username" in raw:
|
||
patch["x_clips_account_username"] = str(raw.get("x_clips_account_username") or "").strip().lstrip("@")[:80]
|
||
if "x_clips_trigger" in raw:
|
||
t = str(raw.get("x_clips_trigger") or "tagged").strip().lower()
|
||
if t not in {"tagged", "all", "favorite"}:
|
||
raise HTTPException(400, "trigger 无效")
|
||
patch["x_clips_trigger"] = t
|
||
if "x_clips_tag" in raw:
|
||
patch["x_clips_tag"] = str(raw.get("x_clips_tag") or "x").strip()[:40] or "x"
|
||
for k in (
|
||
"x_clips_live_sample",
|
||
"x_clips_sample_any_live",
|
||
"x_clips_auto_post",
|
||
"x_clips_upload_spread",
|
||
"x_clips_delete_clip_after_post",
|
||
"x_clips_dedupe_room_day",
|
||
):
|
||
if k in raw:
|
||
patch[k] = bool(raw[k])
|
||
if "x_clips_live_sample_interval_sec" in raw:
|
||
try:
|
||
patch["x_clips_live_sample_interval_sec"] = max(
|
||
60, min(3600, int(raw["x_clips_live_sample_interval_sec"]))
|
||
)
|
||
except Exception:
|
||
raise HTTPException(400, "sample_interval 无效") from None
|
||
if "x_clips_live_sample_batch" in raw:
|
||
try:
|
||
patch["x_clips_live_sample_batch"] = max(1, min(5, int(raw["x_clips_live_sample_batch"])))
|
||
except Exception:
|
||
raise HTTPException(400, "sample_batch 无效") from None
|
||
if "x_clips_upload_min_gap_sec" in raw:
|
||
try:
|
||
patch["x_clips_upload_min_gap_sec"] = max(120, min(7200, int(raw["x_clips_upload_min_gap_sec"])))
|
||
except Exception:
|
||
raise HTTPException(400, "upload_min_gap 无效") from None
|
||
if patch:
|
||
db.update_settings_map(patch)
|
||
return x_clips_pipeline.status()
|
||
|
||
|
||
@app.post("/api/x-clips/sample-now")
|
||
async def x_clips_sample_now() -> dict[str, Any]:
|
||
from .x_clips_pipeline import sample_live_now
|
||
|
||
result = await asyncio.to_thread(sample_live_now)
|
||
recording = await x_clips_pipeline.kick_pending_records(list(result.get("job_ids") or []))
|
||
return {
|
||
"ok": True,
|
||
"enqueued": int(result.get("enqueued") or 0),
|
||
"live_count": int(result.get("live_count") or 0),
|
||
"skipped_dedupe": int(result.get("skipped_dedupe") or 0),
|
||
"recording": recording,
|
||
"reason": str(result.get("reason") or ""),
|
||
"status": x_clips_pipeline.status(),
|
||
}
|
||
|
||
|
||
@app.post("/api/x-clips/fill-quota")
|
||
async def x_clips_fill_quota() -> dict[str, Any]:
|
||
from . import x_clips_db
|
||
from .x_clips_pipeline import try_fill_daily_quota
|
||
|
||
result = await asyncio.to_thread(try_fill_daily_quota)
|
||
pending = await _db(x_clips_db.list_pending_x_clip_jobs, limit=20)
|
||
recording = await x_clips_pipeline.kick_pending_records([str(j.get("id")) for j in pending])
|
||
return {
|
||
"ok": True,
|
||
**result,
|
||
"recording": recording,
|
||
"status": x_clips_pipeline.status(),
|
||
}
|
||
|
||
|
||
@app.get("/api/x-clips/jobs")
|
||
async def x_clips_jobs_list(
|
||
status: str = "",
|
||
push_date: str = "",
|
||
session_id: str = "",
|
||
room_id: str = "",
|
||
account_username: str = "",
|
||
limit: int = Query(50, ge=1, le=500),
|
||
offset: int = Query(0, ge=0),
|
||
) -> dict[str, Any]:
|
||
from . import x_clips_db
|
||
|
||
return await _db(
|
||
x_clips_db.list_x_clip_jobs,
|
||
status=status,
|
||
push_date=push_date,
|
||
session_id=session_id,
|
||
room_id=room_id,
|
||
account_username=account_username,
|
||
limit=limit,
|
||
offset=offset,
|
||
)
|
||
|
||
|
||
@app.get("/api/x-clips/jobs/{job_id}")
|
||
async def x_clips_job_detail(job_id: str) -> dict[str, Any]:
|
||
from . import x_clips_db
|
||
|
||
job = await _db(x_clips_db.get_x_clip_job, job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
return {"job": job}
|
||
|
||
|
||
@app.post("/api/x-clips/jobs/{job_id}/post-now")
|
||
async def x_clips_job_post_now(job_id: str) -> dict[str, Any]:
|
||
from .x2_ws import hub
|
||
|
||
try:
|
||
job = await x_clips_pipeline.post_job_now(job_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
try:
|
||
await hub.dispatch_queued()
|
||
except Exception:
|
||
pass
|
||
return {"ok": True, "job": job}
|
||
|
||
|
||
@app.post("/api/x-clips/jobs/{job_id}/retry")
|
||
async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
|
||
from pathlib import Path
|
||
|
||
from . import x_clips_db
|
||
from .x_clips_schedule import pick_upload_at
|
||
|
||
job = await _db(x_clips_db.get_x_clip_job, job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
st = str(job.get("status") or "")
|
||
if st not in {"failed", "skipped"}:
|
||
raise HTTPException(400, "仅失败/跳过任务可重试")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if clip and Path(clip).is_file():
|
||
cfg = db.get_settings_map()
|
||
upload_at = pick_upload_at(push_date=str(job.get("push_date") or ""), cfg=cfg)
|
||
updated = x_clips_db.update_x_clip_job(
|
||
job_id,
|
||
status="scheduled",
|
||
upload_at=upload_at,
|
||
error="",
|
||
finished_at=0,
|
||
x2_job_id="",
|
||
)
|
||
else:
|
||
updated = x_clips_db.update_x_clip_job(
|
||
job_id,
|
||
status="pending",
|
||
error="",
|
||
finished_at=0,
|
||
started_at=0,
|
||
x2_job_id="",
|
||
media_key="",
|
||
media_url="",
|
||
)
|
||
if updated:
|
||
await x_clips_pipeline.kick_pending_records([job_id])
|
||
return {"ok": True, "job": updated or job}
|
||
|
||
|
||
# ── YouTube long-form 9:16 (isolated; default disabled) ──────────────────────
|
||
|
||
|
||
@app.get("/api/yt-long/status")
|
||
async def yt_long_status() -> dict[str, Any]:
|
||
return await asyncio.to_thread(yt_long_pipeline.status)
|
||
|
||
|
||
@app.post("/api/yt-long/start")
|
||
async def yt_long_start() -> dict[str, Any]:
|
||
db.update_settings_map({"yt_long_enabled": True})
|
||
try:
|
||
await yt_long_pipeline.start()
|
||
except Exception:
|
||
pass
|
||
return yt_long_pipeline.status()
|
||
|
||
|
||
@app.post("/api/yt-long/stop")
|
||
async def yt_long_stop() -> dict[str, Any]:
|
||
db.update_settings_map({"yt_long_enabled": False})
|
||
try:
|
||
await yt_long_pipeline.stop()
|
||
except Exception:
|
||
pass
|
||
return yt_long_pipeline.status()
|
||
|
||
|
||
@app.post("/api/yt-long/settings")
|
||
async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
patch: dict[str, Any] = {}
|
||
raw = body or {}
|
||
for k in (
|
||
"yt_long_with_shorts",
|
||
"yt_long_auto_upload",
|
||
"yt_long_dedupe_room_day",
|
||
"yt_long_delete_clip_after_upload",
|
||
"yt_long_live_sample",
|
||
"yt_long_landscape_16x9",
|
||
"clip_cascade_enabled",
|
||
"yt_long_auto_match_source",
|
||
"yt_long_monetize_when_ypp",
|
||
):
|
||
if k in raw:
|
||
patch[k] = bool(raw[k])
|
||
if "clips_max_age_hours" in raw:
|
||
try:
|
||
patch["clips_max_age_hours"] = max(1, min(168, float(raw["clips_max_age_hours"])))
|
||
except Exception:
|
||
raise HTTPException(400, "clips_max_age_hours 无效") from None
|
||
if "clips_min_free_gb" in raw:
|
||
try:
|
||
patch["clips_min_free_gb"] = max(4, min(40, float(raw["clips_min_free_gb"])))
|
||
except Exception:
|
||
raise HTTPException(400, "clips_min_free_gb 无效") from None
|
||
if "yt_long_daily_max" in raw:
|
||
try:
|
||
patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"])))
|
||
except Exception:
|
||
raise HTTPException(400, "daily_max 无效") from None
|
||
if "yt_long_source_daily_max" in raw:
|
||
try:
|
||
patch["yt_long_source_daily_max"] = max(0, min(300, int(raw["yt_long_source_daily_max"])))
|
||
except Exception:
|
||
raise HTTPException(400, "source_daily_max 无效") from None
|
||
if "yt_long_source_cap" in raw:
|
||
try:
|
||
patch["yt_long_source_cap"] = max(42, min(300, int(raw["yt_long_source_cap"])))
|
||
except Exception:
|
||
raise HTTPException(400, "source_cap 无效") from None
|
||
if "yt_long_channel_daily_max" in raw:
|
||
try:
|
||
patch["yt_long_channel_daily_max"] = max(0, min(50, int(raw["yt_long_channel_daily_max"])))
|
||
except Exception:
|
||
raise HTTPException(400, "channel_daily_max 无效") from None
|
||
if "yt_long_min_sec" in raw:
|
||
try:
|
||
patch["yt_long_min_sec"] = max(180, min(480, int(raw["yt_long_min_sec"])))
|
||
except Exception:
|
||
raise HTTPException(400, "min_sec 无效") from None
|
||
if "yt_long_max_sec" in raw:
|
||
try:
|
||
patch["yt_long_max_sec"] = max(180, min(480, int(raw["yt_long_max_sec"])))
|
||
except Exception:
|
||
raise HTTPException(400, "max_sec 无效") from None
|
||
if "yt_long_upload_min_gap_sec" in raw:
|
||
try:
|
||
patch["yt_long_upload_min_gap_sec"] = max(60, min(7200, int(raw["yt_long_upload_min_gap_sec"])))
|
||
except Exception:
|
||
raise HTTPException(400, "upload_min_gap 无效") from None
|
||
if "yt_long_title_template" in raw:
|
||
patch["yt_long_title_template"] = str(raw.get("yt_long_title_template") or "").strip()[:200]
|
||
if "yt_long_description_template" in raw:
|
||
patch["yt_long_description_template"] = str(raw.get("yt_long_description_template") or "").strip()[:2000]
|
||
if patch:
|
||
# Keep min <= max
|
||
cfg = {**db.get_settings_map(), **patch}
|
||
lo = int(cfg.get("yt_long_min_sec") or 180)
|
||
hi = int(cfg.get("yt_long_max_sec") or 480)
|
||
if lo > hi:
|
||
patch["yt_long_max_sec"] = lo
|
||
db.update_settings_map(patch)
|
||
return yt_long_pipeline.status()
|
||
|
||
|
||
@app.post("/api/yt-long/sample-now")
|
||
async def yt_long_sample_now() -> dict[str, Any]:
|
||
from .yt_long_pipeline import sample_live_now
|
||
|
||
result = await asyncio.to_thread(sample_live_now)
|
||
recording = await yt_long_pipeline.kick_pending_records(list(result.get("job_ids") or []))
|
||
return {"ok": True, **result, "recording": recording, "status": yt_long_pipeline.status()}
|
||
|
||
|
||
@app.post("/api/yt-long/fill-quota")
|
||
async def yt_long_fill_quota() -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
from .yt_long_pipeline import try_fill_daily_quota
|
||
|
||
result = await asyncio.to_thread(try_fill_daily_quota)
|
||
pending = await _db(yt_long_db.list_pending_yt_long_jobs, limit=20)
|
||
recording = await yt_long_pipeline.kick_pending_records([str(j.get("id")) for j in pending])
|
||
return {"ok": True, **result, "recording": recording, "status": yt_long_pipeline.status()}
|
||
|
||
|
||
@app.get("/api/yt-long/jobs")
|
||
async def yt_long_jobs_list(
|
||
status: str = "",
|
||
push_date: str = "",
|
||
channel_pk: str = "",
|
||
limit: int = Query(50, ge=1, le=200),
|
||
offset: int = Query(0, ge=0),
|
||
) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
return await _db(
|
||
yt_long_db.list_yt_long_jobs_page,
|
||
status=status,
|
||
push_date=push_date,
|
||
channel_pk=channel_pk,
|
||
limit=limit,
|
||
offset=offset,
|
||
)
|
||
|
||
|
||
@app.get("/api/yt-long/channels")
|
||
async def yt_long_channels_list(enabled: Optional[bool] = None) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
await _db(yt_long_db.sync_channels_from_shorts)
|
||
rows = await _db(yt_long_db.list_yt_long_channels, enabled=enabled)
|
||
return {"channels": [yt_long_db.public_yt_long_channel(c) for c in rows]}
|
||
|
||
|
||
@app.post("/api/yt-long/channels/import-shorts")
|
||
async def yt_long_channels_import_shorts() -> dict[str, Any]:
|
||
"""Full sync copy of Shorts channels into yt_long_channels (Shorts untouched)."""
|
||
from . import yt_long_db
|
||
|
||
result = await _db(yt_long_db.sync_channels_from_shorts)
|
||
return {"ok": True, **result}
|
||
|
||
|
||
@app.post("/api/yt-long/channels/probe-ypp")
|
||
async def yt_long_channels_probe_ypp(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
|
||
"""Refresh YPP flags for yt_long channels linked to Shorts OAuth."""
|
||
from .yt_long_monetize import refresh_all_ypp_from_shorts
|
||
|
||
return await refresh_all_ypp_from_shorts(limit=limit)
|
||
|
||
|
||
@app.post("/api/yt-long/channels")
|
||
async def yt_long_channels_create(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
raw = body or {}
|
||
ch = await _db(
|
||
yt_long_db.create_yt_long_channel,
|
||
name=str(raw.get("name") or ""),
|
||
youtube_channel_id=str(raw.get("youtube_channel_id") or ""),
|
||
oauth_profile_id=str(raw.get("oauth_profile_id") or "A"),
|
||
client_id=str(raw.get("client_id") or ""),
|
||
client_secret=str(raw.get("client_secret") or ""),
|
||
refresh_token=str(raw.get("refresh_token") or ""),
|
||
enabled=bool(raw.get("enabled", True)),
|
||
daily_max=int(raw.get("daily_max") or 1),
|
||
title_template=str(raw.get("title_template") or "{anchor} street food live"),
|
||
description_template=str(raw.get("description_template") or ""),
|
||
privacy=str(raw.get("privacy") or "public"),
|
||
note=str(raw.get("note") or ""),
|
||
)
|
||
return {"channel": yt_long_db.public_yt_long_channel(ch)}
|
||
|
||
|
||
@app.patch("/api/yt-long/channels/{channel_pk}")
|
||
async def yt_long_channels_update(channel_pk: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
patch = dict(body or {})
|
||
for secret_key in ("client_secret", "refresh_token", "client_id"):
|
||
if secret_key in patch and (
|
||
not str(patch.get(secret_key) or "").strip() or str(patch[secret_key]).startswith("***")
|
||
):
|
||
patch.pop(secret_key, None)
|
||
try:
|
||
ch = await _db(yt_long_db.update_yt_long_channel, channel_pk, **patch)
|
||
except ValueError as exc:
|
||
raise HTTPException(404, str(exc)) from exc
|
||
return {"channel": yt_long_db.public_yt_long_channel(ch)}
|
||
|
||
|
||
@app.delete("/api/yt-long/channels/{channel_pk}")
|
||
async def yt_long_channels_delete(channel_pk: str) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
stats = await _db(yt_long_db.delete_yt_long_channel, channel_pk)
|
||
return {"ok": True, **stats}
|
||
|
||
|
||
@app.get("/api/yt-long/events")
|
||
async def yt_long_events_list(
|
||
limit: int = Query(50, ge=1, le=200),
|
||
offset: int = Query(0, ge=0),
|
||
) -> dict[str, Any]:
|
||
from . import yt_long_db
|
||
|
||
return await _db(yt_long_db.list_yt_long_events, limit=limit, offset=offset)
|
||
|
||
|
||
@app.post("/api/yt-long/jobs/{job_id}/retry")
|
||
async def yt_long_job_retry(job_id: str) -> dict[str, Any]:
|
||
from pathlib import Path
|
||
|
||
from . import yt_long_db
|
||
|
||
job = await _db(yt_long_db.get_yt_long_job, job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
st = str(job.get("status") or "")
|
||
if st not in {"failed", "skipped"}:
|
||
raise HTTPException(400, "仅失败/跳过任务可重试")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if clip and Path(clip).is_file():
|
||
updated = yt_long_db.update_yt_long_job(
|
||
job_id,
|
||
status="scheduled",
|
||
upload_at=time.time() + 30,
|
||
error="",
|
||
finished_at=0,
|
||
)
|
||
else:
|
||
updated = yt_long_db.update_yt_long_job(
|
||
job_id,
|
||
status="pending",
|
||
error="",
|
||
finished_at=0,
|
||
started_at=0,
|
||
clip_path="",
|
||
)
|
||
return {"ok": True, "job": updated or job}
|
||
|
||
|
||
@app.post("/api/x2/jobs/{job_id}/cancel")
|
||
async def x2_jobs_cancel(job_id: str) -> dict[str, Any]:
|
||
from . import x2_db
|
||
from .x2_ws import hub
|
||
|
||
job = await _db(x2_db.cancel_job, job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
try:
|
||
await hub.notify_cancel(job_id, agent_id=str(job.get("agent_id") or ""))
|
||
except Exception:
|
||
pass
|
||
return {"ok": True, "job": job}
|
||
|
||
|
||
@app.post("/api/x2/extension/poll")
|
||
async def x2_extension_poll(request: Request, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
"""Legacy fallback: heartbeat + claim. Prefer /api/x2/extension/ws."""
|
||
from . import x2_db
|
||
|
||
token = (
|
||
(request.headers.get("X-X2-Token") or "")
|
||
or (request.headers.get("x-x2-token") or "")
|
||
or (request.query_params.get("token") or "")
|
||
).strip()
|
||
if not x2_db.verify_ingest_token(token):
|
||
raise HTTPException(401, "无效 Token")
|
||
payload = body if isinstance(body, dict) else {}
|
||
agent_id = str(payload.get("agent_id") or "dylive-helper").strip() or "dylive-helper"
|
||
label = str(payload.get("label") or "dylive Helper").strip() or "dylive Helper"
|
||
accounts = payload.get("accounts") if isinstance(payload.get("accounts"), list) else None
|
||
await _db(
|
||
x2_db.ingest_payload,
|
||
{
|
||
"agent_id": agent_id,
|
||
"label": label,
|
||
"event": "heartbeat",
|
||
"extension_connected": True,
|
||
"source": "dylive-helper",
|
||
"accounts": accounts,
|
||
"message": "poll",
|
||
"meta": {"transport": "poll"},
|
||
},
|
||
)
|
||
cancel_ids = await _db(x2_db.list_cancel_requested, agent_id)
|
||
busy = bool(payload.get("busy"))
|
||
job = None
|
||
if not busy:
|
||
job = await _db(x2_db.claim_next_job, agent_id)
|
||
return {"ok": True, "job": job, "cancel_ids": cancel_ids}
|
||
|
||
|
||
@app.websocket("/api/x2/extension/ws")
|
||
async def x2_extension_ws(websocket: WebSocket) -> None:
|
||
"""Chrome extension realtime channel. Auth: ?token= or header Sec not available — query token."""
|
||
import time as _time
|
||
|
||
from . import x2_db
|
||
from .x2_ws import ExtClient, hub
|
||
|
||
token = (websocket.query_params.get("token") or "").strip()
|
||
if not token or not x2_db.verify_ingest_token(token):
|
||
await websocket.close(code=4401)
|
||
return
|
||
|
||
agent_id = (websocket.query_params.get("agent_id") or "dylive-helper").strip() or "dylive-helper"
|
||
label = (websocket.query_params.get("label") or "dylive Helper").strip() or "dylive Helper"
|
||
|
||
await websocket.accept()
|
||
client = ExtClient(
|
||
ws=websocket,
|
||
agent_id=agent_id,
|
||
label=label,
|
||
busy=False,
|
||
connected_at=_time.time(),
|
||
)
|
||
await hub.register(client)
|
||
|
||
async def _heartbeat(accounts: list | None = None, message: str = "ws") -> None:
|
||
await _db(
|
||
x2_db.ingest_payload,
|
||
{
|
||
"agent_id": agent_id,
|
||
"label": label,
|
||
"event": "heartbeat",
|
||
"extension_connected": True,
|
||
"source": "dylive-helper",
|
||
"accounts": accounts,
|
||
"message": message,
|
||
"meta": {"transport": "ws"},
|
||
},
|
||
)
|
||
|
||
try:
|
||
await _heartbeat(message="ws.connected")
|
||
await hub.send_json(client, {"type": "hello.ok", "agent_id": agent_id})
|
||
# Offer any queued work right away
|
||
await hub.dispatch_queued()
|
||
|
||
while True:
|
||
raw = await websocket.receive_text()
|
||
try:
|
||
msg = json.loads(raw)
|
||
except Exception:
|
||
continue
|
||
if not isinstance(msg, dict):
|
||
continue
|
||
mtype = str(msg.get("type") or "")
|
||
if mtype in {"ping", "heartbeat", "hello"}:
|
||
accounts = msg.get("accounts") if isinstance(msg.get("accounts"), list) else None
|
||
if "busy" in msg:
|
||
await hub.set_busy(client, bool(msg.get("busy")))
|
||
await _heartbeat(accounts, message=mtype)
|
||
await hub.send_json(client, {"type": "pong", "t": _time.time()})
|
||
cancel_ids = await _db(x2_db.list_cancel_requested, agent_id)
|
||
if cancel_ids:
|
||
await hub.send_json(client, {"type": "job.cancel", "ids": cancel_ids})
|
||
if not client.busy:
|
||
await hub.dispatch_queued()
|
||
elif mtype == "busy":
|
||
await hub.set_busy(client, bool(msg.get("busy")))
|
||
if not client.busy:
|
||
await hub.dispatch_queued()
|
||
elif mtype == "ready":
|
||
await hub.set_busy(client, False)
|
||
await hub.dispatch_queued()
|
||
elif mtype == "job.ack":
|
||
# client accepted job.exec
|
||
await hub.set_busy(client, True)
|
||
except WebSocketDisconnect:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
await hub.unregister(client)
|
||
try:
|
||
await _db(
|
||
x2_db.ingest_payload,
|
||
{
|
||
"agent_id": agent_id,
|
||
"label": label,
|
||
"event": "heartbeat",
|
||
"extension_connected": False,
|
||
"source": "dylive-helper",
|
||
"message": "ws.disconnected",
|
||
"meta": {"transport": "ws"},
|
||
},
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ---------- TikTok (fully isolated from Shorts) ----------
|
||
|
||
def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None:
|
||
if not ch:
|
||
return None
|
||
from . import tiktok_socks
|
||
|
||
out = dict(ch)
|
||
for k in ("client_secret", "refresh_token", "access_token"):
|
||
v = str(out.get(k) or "")
|
||
out[f"has_{k}"] = bool(v.strip())
|
||
if v:
|
||
out[k] = ("***" + v[-4:]) if len(v) > 4 else "***"
|
||
out["authorized"] = tiktok_session.channel_has_session(ch)
|
||
out["auth_mode"] = "cookie" if out["authorized"] else ""
|
||
out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1)
|
||
out["socks_enabled"] = bool(int(out.get("socks_enabled") or 0))
|
||
out["socks_profile_id"] = str(out.get("socks_profile_id") or "").strip()
|
||
prof = tiktok_socks.get_socks_profile(out["socks_profile_id"])
|
||
out["socks_profile_label"] = str((prof or {}).get("label") or "") if out["socks_enabled"] else ""
|
||
out["platform_limit_at"] = float(out.get("platform_limit_at") or 0)
|
||
out["platform_limit_msg"] = str(out.get("platform_limit_msg") or "")
|
||
out["platform_limit_probe_at"] = float(out.get("platform_limit_probe_at") or 0)
|
||
out["platform_limited"] = out["platform_limit_at"] > 0
|
||
out.update(tiktok_session.cookie_age_info(ch, persist_backfill=True))
|
||
out["tiktok_uid"] = str(out.get("tiktok_uid") or "")
|
||
out["nickname"] = str(out.get("nickname") or "")
|
||
out["avatar_url"] = str(out.get("avatar_url") or "")
|
||
out["follower_count"] = int(out.get("follower_count") or 0)
|
||
out["following_count"] = int(out.get("following_count") or 0)
|
||
out["video_count"] = int(out.get("video_count") or 0)
|
||
out["heart_count"] = int(out.get("heart_count") or 0)
|
||
out["profile_fetched_at"] = float(out.get("profile_fetched_at") or 0)
|
||
out["profile_error"] = str(out.get("profile_error") or "")
|
||
return out
|
||
|
||
|
||
def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
|
||
if not job:
|
||
return None
|
||
from pathlib import Path
|
||
|
||
from . import tiktok_db
|
||
from .job_errors import enrich_job_error
|
||
from .title_assist import title_candidates
|
||
|
||
out = dict(job)
|
||
clip = str(out.get("clip_path") or "").strip()
|
||
out["clip_ready"] = bool(clip) and Path(clip).is_file()
|
||
ch = tiktok_db.get_tiktok_channel(str(out.get("channel_pk") or "")) or {}
|
||
if ch:
|
||
out["channel_name"] = ch.get("name") or ch.get("tiktok_username") or ""
|
||
else:
|
||
out["channel_name"] = ""
|
||
out["channel_pending"] = not bool(str(out.get("channel_pk") or "").strip())
|
||
out = enrich_job_error(out, platform="tiktok") or out
|
||
out["title_candidates"] = title_candidates(
|
||
platform="tiktok",
|
||
anchor=str(out.get("anchor_name") or ""),
|
||
url=str(out.get("source_url") or ""),
|
||
template=str(ch.get("title_template") or ""),
|
||
)
|
||
return out
|
||
|
||
|
||
@app.get("/api/tiktok/status")
|
||
async def tiktok_status() -> dict[str, Any]:
|
||
st = await asyncio.to_thread(tiktok_pipeline.status)
|
||
cfg = await _db(db.get_settings_map)
|
||
setup = tiktok_session.setup_checklist(cfg)
|
||
st["auth_mode"] = "cookie"
|
||
st["session_ready"] = bool(setup.get("steps") and setup["steps"][-1].get("done"))
|
||
st["setup"] = setup
|
||
st["channels"] = [_public_tiktok_channel(c) for c in (await _db(tiktok_db.list_tiktok_channels))]
|
||
from . import tiktok_socks
|
||
|
||
st["socks_profiles"] = tiktok_socks.list_socks_profiles(cfg, public=True)
|
||
return st
|
||
|
||
|
||
@app.post("/api/tiktok/fill-quota")
|
||
async def tiktok_fill_quota() -> dict[str, Any]:
|
||
"""Manually trigger Beijing-day quota fill toward each TikTok channel daily_max."""
|
||
from .tiktok_pipeline import try_fill_daily_quota
|
||
|
||
cfg = db.get_settings_map()
|
||
if not cfg.get("tiktok_enabled"):
|
||
raise HTTPException(400, "请先启用 TikTok")
|
||
qn = await asyncio.to_thread(try_fill_daily_quota, cfg)
|
||
st = await asyncio.to_thread(tiktok_pipeline.status)
|
||
st["just_quota_filled"] = qn
|
||
return st
|
||
|
||
|
||
@app.get("/api/tiktok/setup")
|
||
async def tiktok_setup() -> dict[str, Any]:
|
||
cfg = await _db(db.get_settings_map)
|
||
return tiktok_session.setup_checklist(cfg)
|
||
|
||
|
||
@app.post("/api/tiktok/channels/{channel_pk}/session")
|
||
async def tiktok_channel_session(channel_pk: str, body: TikTokSessionBody) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
ch = tiktok_db.get_tiktok_channel(channel_pk)
|
||
if not ch:
|
||
raise HTTPException(404, "账号不存在")
|
||
try:
|
||
updated = await asyncio.to_thread(
|
||
tiktok_session.save_session_from_values,
|
||
channel_pk,
|
||
sessionid=str(body.sessionid or "").strip(),
|
||
dc_id=str(body.dc_id or "").strip(),
|
||
username=str(body.tiktok_username or "").strip(),
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
return {"ok": True, "channel": _public_tiktok_channel(updated)}
|
||
|
||
|
||
@app.post("/api/tiktok/channels/{channel_pk}/profile/refresh")
|
||
async def tiktok_channel_profile_refresh(channel_pk: str) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
from . import tiktok_profile
|
||
|
||
ch = tiktok_db.get_tiktok_channel(channel_pk)
|
||
if not ch:
|
||
raise HTTPException(404, "账号不存在")
|
||
try:
|
||
result = await asyncio.to_thread(tiktok_profile.fetch_profile_for_channel, channel_pk)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(400, str(exc) or "拉取资料失败") from exc
|
||
channel = (result or {}).get("channel") or tiktok_db.get_tiktok_channel(channel_pk)
|
||
return {"ok": True, "channel": _public_tiktok_channel(channel), "profile": (result or {}).get("profile")}
|
||
|
||
|
||
@app.delete("/api/tiktok/channels/{channel_pk}/session")
|
||
async def tiktok_channel_session_delete(channel_pk: str) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
ch = tiktok_db.get_tiktok_channel(channel_pk)
|
||
if not ch:
|
||
raise HTTPException(404, "账号不存在")
|
||
await asyncio.to_thread(tiktok_session.delete_session_cookies, channel_pk)
|
||
updated = await _db(
|
||
tiktok_db.update_tiktok_channel,
|
||
channel_pk,
|
||
oauth_ok=0,
|
||
oauth_error="Cookie 已清除",
|
||
refresh_token="",
|
||
cookie_saved_at=0,
|
||
)
|
||
return {"ok": True, "channel": _public_tiktok_channel(updated)}
|
||
|
||
|
||
@app.post("/api/tiktok/oauth/probe")
|
||
async def tiktok_oauth_probe(channel_pk: str = "") -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
if channel_pk.strip():
|
||
ch = tiktok_db.get_tiktok_channel(channel_pk.strip())
|
||
if not ch:
|
||
raise HTTPException(404, "账号不存在")
|
||
return await asyncio.to_thread(tiktok_session.probe_channel_session, ch)
|
||
results = []
|
||
for ch in tiktok_db.list_tiktok_channels(enabled=True):
|
||
results.append(await asyncio.to_thread(tiktok_session.probe_channel_session, ch))
|
||
return {"checked": len(results), "results": results}
|
||
|
||
|
||
@app.get("/api/tiktok/oauth/callback/tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt")
|
||
async def tiktok_url_prefix_verify_file() -> FileResponse:
|
||
"""TikTok URL prefix ownership verification (legacy)."""
|
||
from pathlib import Path
|
||
|
||
path = Path(__file__).resolve().parent.parent / "tiktok_verify" / "tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt"
|
||
if not path.is_file():
|
||
raise HTTPException(404, "verification file missing")
|
||
return FileResponse(path, media_type="text/plain")
|
||
|
||
|
||
@app.post("/api/tiktok/start")
|
||
async def tiktok_start() -> dict[str, Any]:
|
||
db.update_settings_map({"tiktok_enabled": True})
|
||
try:
|
||
await tiktok_pipeline.start()
|
||
except Exception:
|
||
pass
|
||
return tiktok_pipeline.status()
|
||
|
||
|
||
@app.post("/api/tiktok/stop")
|
||
async def tiktok_stop() -> dict[str, Any]:
|
||
db.update_settings_map({"tiktok_enabled": False})
|
||
return tiktok_pipeline.status()
|
||
|
||
|
||
@app.post("/api/tiktok/sample-now")
|
||
async def tiktok_sample_now() -> dict[str, Any]:
|
||
from .tiktok_pipeline import sample_live_now
|
||
|
||
result = await asyncio.to_thread(sample_live_now)
|
||
recording = await tiktok_pipeline.kick_pending_records(list(result.get("job_ids") or []))
|
||
return {
|
||
"ok": True,
|
||
"enqueued": int(result.get("enqueued") or 0),
|
||
"live_count": int(result.get("live_count") or 0),
|
||
"skipped_dedupe": int(result.get("skipped_dedupe") or 0),
|
||
"recording": recording,
|
||
"reason": str(result.get("reason") or ""),
|
||
"status": tiktok_pipeline.status(),
|
||
}
|
||
|
||
|
||
@app.get("/api/tiktok/channels")
|
||
async def tiktok_channels_list() -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
rows = await _db(tiktok_db.list_tiktok_channels)
|
||
return {"channels": [_public_tiktok_channel(c) for c in rows]}
|
||
|
||
|
||
@app.post("/api/tiktok/channels")
|
||
async def tiktok_channels_create(body: TikTokChannelCreate) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
ch = await _db(
|
||
tiktok_db.create_tiktok_channel,
|
||
name=body.name,
|
||
enabled=body.enabled,
|
||
title_template=body.title_template,
|
||
description_template=body.description_template,
|
||
privacy_level=body.privacy_level,
|
||
note=body.note,
|
||
socks_enabled=bool(body.socks_enabled),
|
||
socks_profile_id=str(body.socks_profile_id or ""),
|
||
)
|
||
return {"ok": True, "channel": _public_tiktok_channel(ch)}
|
||
|
||
|
||
@app.patch("/api/tiktok/channels/{channel_pk}")
|
||
async def tiktok_channels_update(channel_pk: str, body: TikTokChannelUpdate) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
patch = body.model_dump(exclude_none=True)
|
||
if not patch:
|
||
raise HTTPException(400, "无更新字段")
|
||
ch = await _db(tiktok_db.update_tiktok_channel, channel_pk, **patch)
|
||
if not ch:
|
||
raise HTTPException(404, "账号不存在")
|
||
return {"ok": True, "channel": _public_tiktok_channel(ch)}
|
||
|
||
|
||
@app.put("/api/tiktok/socks-profiles")
|
||
async def tiktok_socks_profiles_put(body: TikTokSocksProfilesBody) -> dict[str, Any]:
|
||
"""Save TikTok SOCKS profile pool (used by per-account selection)."""
|
||
from . import tiktok_socks
|
||
|
||
profiles = await _db(tiktok_socks.save_socks_profiles, body.profiles or [])
|
||
return {"ok": True, "socks_profiles": profiles}
|
||
|
||
|
||
@app.delete("/api/tiktok/channels/{channel_pk}")
|
||
async def tiktok_channels_delete(channel_pk: str) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
await asyncio.to_thread(tiktok_session.delete_session_cookies, channel_pk)
|
||
ok = await _db(tiktok_db.delete_tiktok_channel, channel_pk)
|
||
if not ok:
|
||
raise HTTPException(404, "账号不存在")
|
||
return {"ok": True}
|
||
|
||
|
||
@app.get("/api/tiktok/jobs")
|
||
async def tiktok_jobs_list(
|
||
status: str = "",
|
||
push_date: str = "",
|
||
channel_pk: str = "",
|
||
session_id: str = "",
|
||
room_id: str = "",
|
||
limit: int = Query(50, ge=1, le=500),
|
||
offset: int = Query(0, ge=0),
|
||
) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
data = await _db(
|
||
tiktok_db.list_tiktok_jobs,
|
||
status=status,
|
||
push_date=push_date,
|
||
channel_pk=channel_pk,
|
||
session_id=session_id,
|
||
room_id=room_id,
|
||
limit=limit,
|
||
offset=offset,
|
||
)
|
||
data["jobs"] = [_enrich_tiktok_job(j) for j in data.get("jobs") or []]
|
||
return data
|
||
|
||
|
||
@app.get("/api/tiktok/jobs/{job_id}")
|
||
async def tiktok_job_detail(job_id: str) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
|
||
job = await _db(tiktok_db.get_tiktok_job, job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
return {"job": _enrich_tiktok_job(job)}
|
||
|
||
|
||
@app.get("/api/tiktok/jobs/{job_id}/clip")
|
||
async def tiktok_job_clip(job_id: str) -> FileResponse:
|
||
from . import tiktok_db
|
||
|
||
job = tiktok_db.get_tiktok_job(job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if not clip or not os.path.isfile(clip):
|
||
raise HTTPException(404, "成片不存在")
|
||
return FileResponse(clip, media_type="video/mp4", filename=os.path.basename(clip))
|
||
|
||
|
||
@app.post("/api/tiktok/jobs/{job_id}/retry")
|
||
async def tiktok_job_retry(job_id: str) -> dict[str, Any]:
|
||
from . import tiktok_db
|
||
from .tiktok_schedule import pick_upload_at
|
||
|
||
job = tiktok_db.get_tiktok_job(job_id)
|
||
if not job:
|
||
raise HTTPException(404, "任务不存在")
|
||
clip = str(job.get("clip_path") or "").strip()
|
||
if clip and os.path.isfile(clip):
|
||
updated = tiktok_db.update_tiktok_job(
|
||
job_id,
|
||
status="scheduled",
|
||
upload_at=pick_upload_at(channel_pk=str(job.get("channel_pk") or "")),
|
||
error="",
|
||
finished_at=0,
|
||
)
|
||
else:
|
||
updated = tiktok_db.update_tiktok_job(job_id, status="pending", error="", finished_at=0, clip_path="")
|
||
return {"ok": True, "job": _enrich_tiktok_job(updated)}
|
||
|
||
|
||
@app.post("/api/tiktok/jobs/{job_id}/upload-now")
|
||
async def tiktok_job_upload_now(job_id: str, body: TikTokUploadNowBody | None = None) -> dict[str, Any]:
|
||
channel_pk = str((body.channel_pk if body else "") or "").strip()
|
||
try:
|
||
job = await tiktok_pipeline.upload_job_now(job_id, channel_pk=channel_pk)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(400, str(exc) or "上传失败") from exc
|
||
return {"ok": True, "job": _enrich_tiktok_job(job)}
|
||
|
||
|
||
@app.get("/api/tiktok/schedule")
|
||
async def tiktok_schedule_api() -> dict[str, Any]:
|
||
from .tiktok_schedule import schedule_board
|
||
|
||
return schedule_board(limit=40)
|
||
|
||
|
||
@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]:
|
||
cfg = await asyncio.to_thread(db.get_settings_map)
|
||
return _public_settings(cfg)
|
||
|
||
|
||
@app.get("/api/dashboard/jobs")
|
||
async def dashboard_jobs(
|
||
limit: int = Query(60, ge=1, le=200),
|
||
status: str = "",
|
||
) -> dict[str, Any]:
|
||
from .platform_dashboard import list_recent_jobs
|
||
|
||
return await asyncio.to_thread(list_recent_jobs, limit=limit, status=status)
|
||
|
||
|
||
@app.get("/api/youtube/oauth-health")
|
||
async def youtube_oauth_health() -> dict[str, Any]:
|
||
from .platform_dashboard import oauth_health_board
|
||
|
||
return await asyncio.to_thread(oauth_health_board)
|
||
|
||
|
||
@app.post("/api/youtube/oauth-health/probe")
|
||
async def youtube_oauth_health_probe(request: Request) -> dict[str, Any]:
|
||
from .authz import assert_write_access
|
||
from .platform_dashboard import oauth_health_probe_all
|
||
|
||
assert_write_access(request)
|
||
return await oauth_health_probe_all()
|
||
|
||
|
||
@app.get("/api/ops/backups")
|
||
async def ops_list_backups(limit: int = Query(20, ge=1, le=100)) -> dict[str, Any]:
|
||
from .db_backup import list_backups
|
||
|
||
return {"backups": list_backups(limit=limit)}
|
||
|
||
|
||
@app.post("/api/ops/backups/run")
|
||
async def ops_run_backup(request: Request) -> dict[str, Any]:
|
||
from .authz import assert_write_access
|
||
from .db_backup import run_backup
|
||
|
||
assert_write_access(request)
|
||
return await asyncio.to_thread(run_backup, label="manual")
|
||
|
||
|
||
@app.get("/api/ops/alerts/metrics")
|
||
async def ops_alert_metrics() -> dict[str, Any]:
|
||
from .ops_alerts import collect_metrics
|
||
|
||
return await asyncio.to_thread(collect_metrics)
|
||
|
||
|
||
@app.post("/api/ops/alerts/check")
|
||
async def ops_alert_check(request: Request) -> dict[str, Any]:
|
||
from .authz import assert_write_access
|
||
from .ops_alerts import check_and_alert
|
||
|
||
assert_write_access(request)
|
||
return await check_and_alert()
|
||
|
||
|
||
@app.get("/api/archive/{platform}/{job_id}")
|
||
async def archive_meta(platform: str, job_id: str) -> dict[str, Any]:
|
||
from .clip_archive import get_archive_meta
|
||
|
||
meta = get_archive_meta(platform, job_id)
|
||
return {"ok": bool(meta), "archive": meta}
|
||
|
||
|
||
@app.post("/api/archive/{platform}/{job_id}/replay")
|
||
async def archive_replay(platform: str, job_id: str, request: Request) -> dict[str, Any]:
|
||
from .authz import assert_write_access
|
||
from .clip_archive import replay_from_archive
|
||
|
||
assert_write_access(request)
|
||
return await replay_from_archive(platform, job_id)
|
||
|
||
|
||
@app.get("/api/events/audit")
|
||
async def settings_audit_events(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
|
||
rows = db.list_events(kind="settings_audit", limit=limit)
|
||
return {"events": rows.get("events") or [], "total": int(rows.get("total") or 0)}
|
||
|
||
|
||
@app.patch("/api/settings")
|
||
async def patch_settings(body: SettingsUpdate, request: Request) -> dict[str, Any]:
|
||
patch = body.model_dump(exclude_none=True)
|
||
if "shorts_oauth_client_secret" in patch:
|
||
sec = str(patch.get("shorts_oauth_client_secret") or "").strip()
|
||
if (not sec) or sec.startswith("***"):
|
||
patch.pop("shorts_oauth_client_secret", None)
|
||
if "shorts_oauth_profiles" in patch:
|
||
existing = await asyncio.to_thread(db.get_settings_map)
|
||
patch["shorts_oauth_profiles"] = shorts_oauth.merge_oauth_profiles_patch(
|
||
patch.get("shorts_oauth_profiles"), existing
|
||
)
|
||
if "shorts_upload_socks_profiles" in patch:
|
||
from . import shorts_socks
|
||
|
||
existing = await asyncio.to_thread(db.get_settings_map)
|
||
patch["shorts_upload_socks_profiles"] = shorts_socks.merge_socks_profiles_patch(
|
||
patch.get("shorts_upload_socks_profiles"), existing
|
||
)
|
||
if "yt_studio_cookies_by_profile" in patch:
|
||
from . import yt_studio_auth
|
||
|
||
existing = await asyncio.to_thread(db.get_settings_map)
|
||
patch["yt_studio_cookies_by_profile"] = yt_studio_auth.merge_studio_cookies_patch(
|
||
patch.get("yt_studio_cookies_by_profile"), existing
|
||
)
|
||
if "readonly_password" in patch:
|
||
from .session_auth import hash_password
|
||
|
||
existing = await asyncio.to_thread(db.get_settings_map)
|
||
user = str(patch.pop("readonly_username", None) or existing.get("readonly_username") or "").strip()
|
||
pw = str(patch.pop("readonly_password", None) or "").strip()
|
||
if pw and not pw.startswith("***"):
|
||
patch["readonly_username"] = user
|
||
patch["readonly_password_hash"] = hash_password(pw)
|
||
elif user and "readonly_username" in body.model_dump(exclude_none=True):
|
||
patch["readonly_username"] = user
|
||
cfg = await asyncio.to_thread(
|
||
db.update_settings_map, patch, audit_actor=str(session_user_from_request(request) or "")
|
||
)
|
||
return _public_settings(cfg)
|
||
|
||
|
||
@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 await _db(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.get("/api/rooms/recommend")
|
||
async def rooms_recommend(
|
||
limit: int = Query(20, ge=1, le=100),
|
||
lookback_days: int = Query(14, ge=3, le=60),
|
||
) -> dict[str, Any]:
|
||
from .room_recommend import recommend_rooms
|
||
|
||
return recommend_rooms(limit=limit, lookback_days=lookback_days)
|
||
|
||
|
||
@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,
|
||
clip_sec=body.clip_sec,
|
||
)
|
||
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/analytics")
|
||
async def groups_analytics(
|
||
date_from: str = "",
|
||
date_to: str = "",
|
||
top_anchors: int = Query(25, ge=1, le=50),
|
||
) -> dict[str, Any]:
|
||
"""YouTube live-session analytics (same pipeline as Douyin /sessions/stats)."""
|
||
stats = summarize_sessions(
|
||
date_from=date_from,
|
||
date_to=date_to,
|
||
platform="youtube",
|
||
top_anchors=top_anchors,
|
||
)
|
||
channels = db.youtube_group_channel_stats(date_from=date_from, date_to=date_to)
|
||
recent = db.list_sessions(platform="youtube", limit=20, offset=0)
|
||
return {
|
||
"ok": True,
|
||
"platform": "youtube",
|
||
"stats": stats,
|
||
"channels": channels,
|
||
"recent_sessions": recent.get("sessions") or [],
|
||
"recent_total": recent.get("total") or 0,
|
||
"monitor": yt_monitor.status(),
|
||
}
|
||
|
||
|
||
@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/manage/channels")
|
||
async def youtube_manage_channels() -> dict[str, Any]:
|
||
return {"channels": youtube_manage.list_managed_channels()}
|
||
|
||
|
||
@app.get("/api/youtube/manage/profiles")
|
||
async def youtube_manage_profiles() -> dict[str, Any]:
|
||
return {"profiles": youtube_manage.list_yt_profile_caches()}
|
||
|
||
|
||
@app.post("/api/youtube/manage/profiles/refresh")
|
||
async def youtube_manage_profiles_refresh(
|
||
max_age_sec: float = Query(0, ge=0, le=86400 * 365),
|
||
limit: int = Query(50, ge=1, le=100),
|
||
) -> dict[str, Any]:
|
||
"""Manual only: refresh channel cards + mirror avatars to S3. Default force all."""
|
||
return await youtube_manage.refresh_stale_yt_profiles(max_age_sec=max_age_sec, limit=limit)
|
||
|
||
|
||
@app.get("/api/youtube/manage/{channel_pk}/profile")
|
||
async def youtube_manage_profile(channel_pk: str) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.fetch_channel_profile(channel_pk)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/youtube/manage/{channel_pk}/dashboard")
|
||
async def youtube_manage_dashboard(channel_pk: str) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.channel_dashboard(channel_pk)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/youtube/manage/{channel_pk}/videos")
|
||
async def youtube_manage_videos(
|
||
channel_pk: str,
|
||
max_results: int = Query(25, ge=1, le=50),
|
||
page_token: str = "",
|
||
) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.list_my_videos(channel_pk, max_results=max_results, page_token=page_token)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||
async def youtube_manage_video_get(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.get_video(channel_pk, video_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.patch("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||
async def youtube_manage_video_update(channel_pk: str, video_id: str, body: YouTubeVideoUpdate) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.update_video(
|
||
channel_pk,
|
||
video_id,
|
||
title=body.title,
|
||
description=body.description,
|
||
tags=body.tags,
|
||
category_id=body.category_id,
|
||
privacy_status=body.privacy_status,
|
||
publish_at=body.publish_at,
|
||
embeddable=body.embeddable,
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.delete("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||
async def youtube_manage_video_delete(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.delete_video(channel_pk, video_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/youtube/manage/{channel_pk}/playlists")
|
||
async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]:
|
||
try:
|
||
return await youtube_manage.list_playlists(channel_pk)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
# ── YouTube assign: channel + stream key → pool → featured ──────────────────
|
||
|
||
|
||
@app.get("/api/youtube/assign/groups")
|
||
async def yt_assign_list_groups() -> dict[str, Any]:
|
||
try:
|
||
yt_assign_db.ensure_default_assign_data()
|
||
except Exception:
|
||
pass
|
||
return {"groups": yt_assign_db.list_groups(include_urls=True)}
|
||
|
||
|
||
@app.get("/api/youtube/assign/schedule")
|
||
async def yt_assign_schedule() -> dict[str, Any]:
|
||
try:
|
||
yt_assign_db.ensure_default_assign_data()
|
||
except Exception:
|
||
pass
|
||
return yt_assign_db.build_rotation_schedule(include_urls=True)
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups")
|
||
async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
|
||
try:
|
||
g = yt_assign_db.create_group(
|
||
name=body.name,
|
||
channel_pk=body.channel_pk,
|
||
youtube_channel_id=body.youtube_channel_id,
|
||
stream_key=body.stream_key,
|
||
note=body.note,
|
||
enabled=body.enabled,
|
||
)
|
||
return {"ok": True, "group": g}
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/youtube/assign/groups/{group_id}")
|
||
async def yt_assign_get_group(group_id: str) -> dict[str, Any]:
|
||
g = yt_assign_db.get_group(group_id)
|
||
if not g:
|
||
raise HTTPException(404, "分组不存在")
|
||
return {"group": g}
|
||
|
||
|
||
@app.patch("/api/youtube/assign/groups/{group_id}")
|
||
async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> dict[str, Any]:
|
||
try:
|
||
g = yt_assign_db.update_group(
|
||
group_id,
|
||
**body.model_dump(exclude_unset=True),
|
||
)
|
||
return {"ok": True, "group": g}
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.delete("/api/youtube/assign/groups/{group_id}")
|
||
async def yt_assign_delete_group(group_id: str) -> dict[str, Any]:
|
||
return yt_assign_db.delete_group(group_id)
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/pool")
|
||
async def yt_assign_add_pool(group_id: str, body: YtAssignPoolAdd) -> dict[str, Any]:
|
||
urls = list(body.urls or [])
|
||
if body.url and str(body.url).strip():
|
||
urls.append(str(body.url).strip())
|
||
try:
|
||
return yt_assign_db.add_pool_urls(
|
||
group_id,
|
||
urls,
|
||
note=body.note,
|
||
text=body.text,
|
||
items=list(body.items or []),
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.patch("/api/youtube/assign/pool/{pool_url_id}")
|
||
async def yt_assign_update_pool(pool_url_id: str, body: YtAssignPoolUpdate) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.update_pool_url(pool_url_id, **body.model_dump(exclude_unset=True))
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.delete("/api/youtube/assign/pool/{pool_url_id}")
|
||
async def yt_assign_delete_pool(pool_url_id: str) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.delete_pool_url(pool_url_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/featured")
|
||
async def yt_assign_add_featured(group_id: str, body: YtAssignFeaturedAdd) -> dict[str, Any]:
|
||
ids = list(body.pool_url_ids or [])
|
||
if body.pool_url_id and str(body.pool_url_id).strip():
|
||
ids.append(str(body.pool_url_id).strip())
|
||
try:
|
||
return yt_assign_db.add_featured(group_id, ids)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.put("/api/youtube/assign/groups/{group_id}/featured")
|
||
async def yt_assign_set_featured(group_id: str, body: YtAssignFeaturedSet) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.set_featured_order(group_id, body.pool_url_ids or [])
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/dedupe")
|
||
async def yt_assign_dedupe(group_id: str) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.dedupe_group(group_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/purge-blacklist")
|
||
async def yt_assign_purge_blacklist(group_id: str) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.purge_blacklisted(group_id, from_pool=True, from_featured=True)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/pool/{pool_url_id}/ban")
|
||
async def yt_assign_ban_pool(pool_url_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
raw = body or {}
|
||
try:
|
||
return yt_assign_db.ban_pool_url(
|
||
pool_url_id,
|
||
reason=str(raw.get("reason") or "分配页拉黑"),
|
||
remove_from_lists=bool(raw.get("remove_from_lists", True)),
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.delete("/api/youtube/assign/featured/{featured_id}")
|
||
async def yt_assign_remove_featured(featured_id: str) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.remove_featured(featured_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/slots")
|
||
async def yt_assign_add_slots(group_id: str, body: YtAssignSlotAdd) -> dict[str, Any]:
|
||
ids = list(body.pool_url_ids or [])
|
||
if body.pool_url_id and str(body.pool_url_id).strip():
|
||
ids.append(str(body.pool_url_id).strip())
|
||
try:
|
||
return yt_assign_db.add_slot(group_id, ids)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.put("/api/youtube/assign/groups/{group_id}/slots")
|
||
async def yt_assign_set_slots(group_id: str, body: YtAssignSlotSet) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.set_slot_order(group_id, body.pool_url_ids or [])
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.delete("/api/youtube/assign/slots/{slot_id}")
|
||
async def yt_assign_remove_slot(slot_id: str) -> dict[str, Any]:
|
||
try:
|
||
return yt_assign_db.remove_slot(slot_id)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/groups/{group_id}/slots/auto-fill")
|
||
async def yt_assign_auto_fill_group(
|
||
group_id: str,
|
||
body: YtAssignAutoFillBody | None = None,
|
||
) -> dict[str, Any]:
|
||
raw = body or YtAssignAutoFillBody()
|
||
try:
|
||
return yt_assign_db.auto_fill_slots_from_live(
|
||
group_id=group_id,
|
||
limit=int(raw.limit or 24),
|
||
all_groups=False,
|
||
force=bool(raw.force),
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@app.post("/api/youtube/assign/schedule/auto-fill")
|
||
async def yt_assign_auto_fill_all(body: YtAssignAutoFillBody | None = None) -> dict[str, Any]:
|
||
raw = body or YtAssignAutoFillBody()
|
||
try:
|
||
return yt_assign_db.auto_fill_slots_from_live(
|
||
group_id="",
|
||
limit=int(raw.limit or 24),
|
||
all_groups=True,
|
||
force=bool(raw.force),
|
||
)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
|
||
|
||
@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/youtube/live-map")
|
||
async def youtube_live_map(force: bool = Query(False)) -> dict[str, Any]:
|
||
"""Unified live status for all YouTube groups + Shorts channels (InnerTube first)."""
|
||
try:
|
||
return await youtube_live.build_live_map(force=force)
|
||
except Exception as exc:
|
||
raise HTTPException(500, str(exc)) from exc
|
||
|
||
|
||
@app.get("/api/douyin/live-map")
|
||
async def douyin_live_map(
|
||
room_ids: str = Query(""),
|
||
force: bool = Query(False),
|
||
) -> dict[str, Any]:
|
||
"""Douyin room live status from monitor DB; SSE live/offline triggers client refresh."""
|
||
ids = [x.strip() for x in room_ids.split(",") if x.strip()] if room_ids.strip() else None
|
||
try:
|
||
return await asyncio.to_thread(douyin_live.build_live_map, room_ids=ids, force=force)
|
||
except Exception as exc:
|
||
raise HTTPException(500, 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 await _db(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(platform: str = "") -> dict[str, Any]:
|
||
items = await _db(db.list_active_sessions, dedupe=not _DESKTOP_LIGHT, platform=platform)
|
||
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 = await _db(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 . import ops_panel
|
||
from .notify import NTFY_TOPIC, send_webhook
|
||
|
||
cfg = db.get_settings_map()
|
||
url = str(cfg.get("notify_webhook_url") or "").strip()
|
||
ntfy_ok = bool(ops_panel.ntfy_config().get("configured"))
|
||
if not url and not ntfy_ok:
|
||
raise HTTPException(400, "未配置 Webhook URL 或 ntfy")
|
||
await send_webhook(
|
||
"ops",
|
||
{
|
||
"message": "【测试】DouyinWEB 通知连通性检查",
|
||
"test": True,
|
||
"time": time.time(),
|
||
},
|
||
)
|
||
return {"ok": True, "webhook": url or None, "ntfy_topic": NTFY_TOPIC if ntfy_ok else None}
|
||
|
||
|
||
@app.get("/api/ops")
|
||
async def ops_snapshot() -> dict[str, Any]:
|
||
"""Umami / ntfy / DNS / systemd health snapshot for the ops control page."""
|
||
from . import ops_panel
|
||
|
||
return await asyncio.to_thread(ops_panel.snapshot)
|
||
|
||
|
||
@app.get("/api/ops/analytics")
|
||
async def ops_analytics(
|
||
domain: str = Query(""),
|
||
range: str = Query("7d"), # noqa: A002 — API query name
|
||
) -> dict[str, Any]:
|
||
"""GA-like Umami visit stats for the ops web UI (read-only)."""
|
||
from . import ops_panel
|
||
|
||
range_key = (range or "7d").strip().lower()
|
||
if range_key not in {"24h", "7d", "30d", "90d"}:
|
||
raise HTTPException(400, "range 支持 24h/7d/30d/90d")
|
||
domain = (domain or "").strip().lower()
|
||
try:
|
||
if not domain:
|
||
return await asyncio.to_thread(ops_panel.analytics_overview, range_key)
|
||
umami = ops_panel.umami_config()
|
||
wid = ""
|
||
for s in ops_panel.SITES:
|
||
if s["domain"] == domain and s.get("umami_key"):
|
||
wid = umami["sites"].get(s["umami_key"], "")
|
||
break
|
||
if not wid:
|
||
raise HTTPException(404, f"未找到站点 {domain} 的 Umami website id")
|
||
data = await asyncio.to_thread(ops_panel.website_analytics, wid, range_key)
|
||
data["domain"] = domain
|
||
return data
|
||
except HTTPException:
|
||
raise
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"读取分析失败: {exc}") from exc
|
||
|
||
|
||
@app.post("/api/ops/ntfy")
|
||
async def ops_ntfy_send(body: dict[str, Any]) -> dict[str, Any]:
|
||
from . import ops_panel
|
||
|
||
title = str(body.get("title") or "DouyinWEB").strip()[:120]
|
||
message = str(body.get("message") or "").strip()
|
||
if not message:
|
||
raise HTTPException(400, "message 不能为空")
|
||
priority = str(body.get("priority") or "default").strip() or "default"
|
||
tags = str(body.get("tags") or "bell").strip() or "bell"
|
||
topic = body.get("topic")
|
||
topic_s = str(topic).strip() if topic else None
|
||
try:
|
||
return await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, topic_s)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"发送失败: {exc}") from exc
|
||
|
||
|
||
@app.post("/api/ops/healthcheck")
|
||
async def ops_run_healthcheck() -> dict[str, Any]:
|
||
from . import ops_panel
|
||
|
||
try:
|
||
return await asyncio.to_thread(ops_panel.run_healthcheck_script)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"健康检查失败: {exc}") from exc
|
||
|
||
|
||
@app.get("/api/downloads")
|
||
async def downloads_catalog() -> dict[str, Any]:
|
||
from . import downloads as downloads_mod
|
||
|
||
return await _db(downloads_mod.catalog)
|
||
|
||
|
||
@app.get("/api/caption-pool")
|
||
async def caption_pool_status(platform: str = "") -> dict[str, Any]:
|
||
"""DB-backed English street-food caption pools (100 per platform + user custom at upload)."""
|
||
from . import caption_pool
|
||
|
||
stats = await _db(caption_pool.pool_stats)
|
||
plat = str(platform or "").strip().lower()
|
||
if plat in {"shorts", "tiktok", "x", "x_clips", "yt_long", "yt_long_desc"}:
|
||
key = "x" if plat == "x_clips" else plat
|
||
samples = await _db(lambda: caption_pool.list_captions(key, limit=5))
|
||
return {**stats, "platform": key, "samples": [s.get("body") for s in samples]}
|
||
return stats
|
||
|
||
|
||
@app.post("/api/caption-pool/reseed")
|
||
async def caption_pool_reseed() -> dict[str, Any]:
|
||
"""Force re-insert 100 English captions per platform (admin)."""
|
||
from . import caption_pool
|
||
from . import db as _dbmod
|
||
|
||
def _run() -> dict[str, int]:
|
||
with _dbmod._lock: # noqa: SLF001
|
||
conn = _dbmod._connect() # noqa: SLF001
|
||
try:
|
||
counts = caption_pool.seed_caption_pool(conn, force=True)
|
||
conn.commit()
|
||
return counts
|
||
finally:
|
||
conn.close()
|
||
|
||
counts = await _db(_run)
|
||
return {"ok": True, "counts": counts}
|
||
|
||
|
||
@app.get("/api/clash")
|
||
async def clash_catalog() -> dict[str, Any]:
|
||
from . import clash_dl
|
||
|
||
return await _db(clash_dl.catalog)
|
||
|
||
|
||
@app.post("/api/clash/sync")
|
||
async def clash_sync(force: bool = Query(False)) -> dict[str, Any]:
|
||
"""Pull latest Clash Verge Rev Win x64 from GitHub and publish clash.yaml to S3."""
|
||
from . import clash_dl
|
||
|
||
try:
|
||
installer = await asyncio.to_thread(clash_dl.sync_clash_verge_installer, force=force)
|
||
if installer.get("skipped"):
|
||
yaml_res = await asyncio.to_thread(clash_dl.publish_clash_yaml)
|
||
installer = {**installer, "yaml": yaml_res}
|
||
return installer
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"同步失败: {exc}") from exc
|
||
|
||
|
||
@app.post("/api/clash/publish-yaml")
|
||
async def clash_publish_yaml() -> dict[str, Any]:
|
||
from . import clash_dl
|
||
|
||
try:
|
||
return await asyncio.to_thread(clash_dl.publish_clash_yaml)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"上传失败: {exc}") from exc
|
||
|
||
|
||
@app.get("/api/clash/config.yaml")
|
||
async def clash_config_yaml() -> Response:
|
||
"""Serve local clash.yaml for browser download (also mirrored on S3)."""
|
||
from . import clash_dl
|
||
|
||
try:
|
||
text = await asyncio.to_thread(clash_dl.local_yaml_text)
|
||
except FileNotFoundError as exc:
|
||
raise HTTPException(404, str(exc)) from exc
|
||
return Response(
|
||
content=text,
|
||
media_type="text/yaml; charset=utf-8",
|
||
headers={"Content-Disposition": 'attachment; filename="clash.yaml"'},
|
||
)
|
||
|
||
|
||
@app.post("/api/downloads/sync-chrome")
|
||
async def downloads_sync_chrome(force: bool = Query(False)) -> dict[str, Any]:
|
||
from . import downloads as downloads_mod
|
||
|
||
try:
|
||
return await asyncio.to_thread(downloads_mod.sync_chrome_installer, force=force)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"同步 Chrome 失败: {exc}") from exc
|
||
|
||
|
||
@app.post("/api/downloads/publish-extension")
|
||
async def downloads_publish_extension() -> dict[str, Any]:
|
||
"""Build extensions/dylive-helper and upload latest zip to S3."""
|
||
from . import downloads as downloads_mod
|
||
|
||
try:
|
||
return await asyncio.to_thread(downloads_mod.build_and_publish_extension)
|
||
except ValueError as exc:
|
||
raise HTTPException(400, str(exc)) from exc
|
||
except subprocess.CalledProcessError as exc:
|
||
tail = (exc.stderr or exc.stdout or str(exc))[-800:]
|
||
raise HTTPException(500, f"插件构建失败: {tail}") from exc
|
||
except Exception as exc:
|
||
raise HTTPException(500, f"发布插件失败: {exc}") from exc
|
||
|
||
|
||
@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 await _db(
|
||
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 await _db(
|
||
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, "场次不存在")
|
||
shorts = db.list_shorts_jobs(session_id=session_id, limit=30, offset=0)
|
||
from . import tiktok_db
|
||
|
||
tiktok = tiktok_db.list_tiktok_jobs(session_id=session_id, limit=30, offset=0)
|
||
return {
|
||
"session": session,
|
||
"shorts_jobs": [_enrich_shorts_job(j) for j in shorts.get("jobs") or []],
|
||
"tiktok_jobs": [_enrich_tiktok_job(j) for j in tiktok.get("jobs") or []],
|
||
}
|
||
|
||
|
||
@app.post("/api/watch-remind/check")
|
||
async def watch_remind_check() -> dict[str, Any]:
|
||
from .watch_remind import check_and_notify
|
||
|
||
return await check_and_notify()
|
||
|
||
|
||
@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.get("/api/pb/health")
|
||
async def pb_sync_health() -> dict[str, Any]:
|
||
"""Compare SQLite vs PocketBase record counts + connection status."""
|
||
return await pb_sync.sync_health()
|
||
|
||
|
||
@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": "已写入演示数据"}
|