"""无人直播系统统一 API:仪表盘、配置中心;业务写操作经 API 落盘,前端不直接访问文件。""" from __future__ import annotations import asyncio import json import sqlite3 import time from pathlib import Path from typing import Any, Callable, Optional from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field, field_validator from src.android_control import adb_available, list_android_devices from src.control_plane import ( load_hardware_profile, network_iface_stats, query_services, recent_pm2_log_lines, stack_stream_probes, stack_summary, system_snapshot, ) from src.douyin_source_display import extract_douyin_source_meta from src.live_config import business_config, load_hub_config_snapshot, services_config_list from src.process_runtime_status import coerce_declared_process_status, summarize_process_activity from src.web_process_backend import WebProcessBackend from src.youtube_config_paths import resolve_youtube_style_config_paths from src.wireguard_config import ( WireGuardConfigError, apply_wireguard_config, configure_neko_browser_proxy, configure_neko_wireguard_access, read_imported_wireguard_config, save_imported_wireguard_config, wireguard_runtime_status, ) from src.youtube_ini_sync import write_youtube_ini_stream_key from src.redroid_control import redroid_runtime_summary from src.hdmi_control import hdmi_capture_summary from src.neko_capacity import ensure_neko_capacity_for_youtube_channels from src.youtube_pro_runtime import normalize_youtube_pro_channels from src.youtube_live_store import ( close_live_event, get_live_event, ingest_browser_telemetry, list_live_events, youtube_live_summary, ) router = APIRouter(prefix="/hub", tags=["无人直播系统"]) _process_backend: WebProcessBackend | None = None _monitor_entries: list[dict[str, Any]] = [] _monitor_entries_provider: Callable[[], list[dict[str, Any]] | tuple[dict[str, Any], ...]] | None = None _repo_root: Path | None = None _DASHBOARD_CACHE_TTL_SECONDS = 1.0 _dashboard_cache: tuple[float, dict[str, Any]] | None = None _TAIL_READ_CHUNK_BYTES = 16 * 1024 _TAIL_READ_MAX_BYTES = 192 * 1024 def configure_hub( process_backend: WebProcessBackend, monitor_entries: list[dict[str, Any]] | Callable[[], list[dict[str, Any]] | tuple[dict[str, Any], ...]], repo_root: Optional[Path] = None, ) -> None: global _process_backend, _monitor_entries, _monitor_entries_provider, _repo_root, _dashboard_cache _process_backend = process_backend if callable(monitor_entries): _monitor_entries_provider = monitor_entries _monitor_entries = list(monitor_entries()) else: _monitor_entries_provider = None _monitor_entries = list(monitor_entries) _repo_root = repo_root.resolve() if repo_root is not None else None _dashboard_cache = None def hub_monitor_entries() -> list[dict[str, Any]]: if _monitor_entries_provider is not None: try: return list(_monitor_entries_provider()) except Exception: return list(_monitor_entries) return list(_monitor_entries) async def _dashboard_or(awaitable, default: Any, timeout: float) -> Any: try: return await asyncio.wait_for(awaitable, timeout=timeout) except Exception: return default def _coerce_hub_process_info(pb: WebProcessBackend, entry: dict[str, Any], info: dict[str, Any]) -> dict[str, Any]: next_status = coerce_declared_process_status( pb.mode, str(info.get("process_status") or ""), bool(entry.get("script")), ) if next_status == str(info.get("process_status") or "").lower(): return info coerced = dict(info) coerced["process_status"] = next_status return coerced def _tail_file_lines(path: str | None, max_lines: int, max_age_seconds: int | None = None) -> list[str]: if not path or max_lines <= 0: return [] file_path = Path(path) try: stat = file_path.stat() if not file_path.is_file(): return [] if max_age_seconds is not None and max(0, time.time() - stat.st_mtime) > max_age_seconds: return [] if stat.st_size <= 0: return [] max_bytes = min(stat.st_size, _TAIL_READ_MAX_BYTES) chunks: list[bytes] = [] bytes_read = 0 position = stat.st_size newline_count = 0 with file_path.open("rb") as handle: while position > 0 and bytes_read < max_bytes: chunk_size = min(_TAIL_READ_CHUNK_BYTES, position, max_bytes - bytes_read) position -= chunk_size handle.seek(position) chunk = handle.read(chunk_size) if not chunk: break chunks.append(chunk) bytes_read += len(chunk) newline_count += chunk.count(b"\n") if newline_count >= max_lines + 1: break except OSError: return [] if not chunks: return [] decoded_lines = b"".join(reversed(chunks)).decode("utf-8", errors="ignore").splitlines() if position > 0 and decoded_lines: decoded_lines = decoded_lines[1:] lines = [line.rstrip() for line in decoded_lines if line.strip()] return lines[-max_lines:] if len(lines) > max_lines else lines def _tail_file_text(path: str | None, max_lines: int, max_age_seconds: int | None = None) -> str: lines = _tail_file_lines(path, max_lines, max_age_seconds=max_age_seconds) return "\n".join(lines) def _is_youtube_monitor_entry(entry: dict[str, Any]) -> bool: script = str(entry.get("script") or "").strip() pm2 = str(entry.get("pm2") or "").strip().lower() stem = Path(script).stem.lower() if script else "" return stem.startswith("youtube") or stem.startswith("douyin_youtube") or pm2.startswith("youtube2__") def _youtube_url_lines_for_process(name: str) -> str: if _repo_root is None: return "" try: _, url_path = resolve_youtube_style_config_paths(_repo_root, name) return url_path.read_text(encoding="utf-8", errors="ignore") if url_path.is_file() else "" except OSError: return "" def _newest_log_age_seconds(*paths: str | None) -> float | None: newest_mtime: float | None = None for path in paths: if not path: continue try: stat = Path(path).stat() except OSError: continue newest_mtime = stat.st_mtime if newest_mtime is None else max(newest_mtime, stat.st_mtime) if newest_mtime is None: return None return max(0.0, time.time() - newest_mtime) def fallback_live_event_lines(process_rows: list[dict[str, Any]], max_lines: int = 16) -> list[str]: lines: list[str] = [] each_limit = max(2, max_lines // 2) for row in process_rows: label = str(row.get("label") or row.get("pm2") or "process") status = str(row.get("process_status") or "").lower() max_age_seconds = None if status in {"online", "running"} else 180 for stream_name, key in (("stderr", "err_path"), ("stdout", "out_path")): for line in _tail_file_lines(row.get(key), each_limit, max_age_seconds=max_age_seconds): lines.append(f"[{label} {stream_name}] {line}") return lines[-max_lines:] if len(lines) > max_lines else lines class BusinessDouyinPatch(BaseModel): streams: Optional[dict[str, str]] = None ffmpeg: Optional[dict[str, Any]] = None sync_youtube_ini: Optional[bool] = None class YoutubeProChannelsBody(BaseModel): channels: list[dict[str, Any]] = Field(default_factory=list) force: bool = False @field_validator("channels", mode="after") @classmethod def _validate_channels(cls, v: list[Any]) -> list[dict[str, Any]]: if len(v) > 64: raise ValueError("at most 64 channels") return normalize_youtube_pro_channels(v) class WireGuardImportBody(BaseModel): content: str = Field(min_length=1, max_length=131072) name: Optional[str] = None route_mode: str = Field(default="preserve", pattern="^(preserve|overlay)$") apply: Optional[bool] = False class WireGuardNekoAccessBody(BaseModel): mode: str = Field(default="lan", pattern="^(lan|remote)$") restart: bool = True class NekoBrowserProxyBody(BaseModel): enabled: bool restart: bool = True class YoutubeLiveCloseBody(BaseModel): reason: str = Field(default="manual", max_length=200) @router.get("/dashboard") async def hub_dashboard() -> dict[str, Any]: global _dashboard_cache now = time.monotonic() if _dashboard_cache and now - _dashboard_cache[0] <= _DASHBOARD_CACHE_TTL_SECONDS: return _dashboard_cache[1] snap = system_snapshot() services = await _dashboard_or(query_services(timeout=3.0), [], 3.5) if adb_available(): devices = await _dashboard_or(list_android_devices(), [], 1.5) else: devices = [] stack = stack_summary() try: probes = await _dashboard_or(stack_stream_probes(), {"srs": {}, "neko": {}, "error": "probe_timeout"}, 2.0) except Exception: probes = {"srs": {}, "neko": {}, "error": "probe_failed"} live_status: dict[str, Any] = { "processes": [], "backend_mode": "unknown", "hint": "PM2 or local registry", } pb = _process_backend if pb is not None: await pb.ensure_mode() live_status["backend_mode"] = pb.mode entries = [entry for entry in hub_monitor_entries() if str(entry.get("pm2", "")).strip()] info_map = await pb.process_infos(str(entry.get("pm2", "")).strip() for entry in entries) async def build_live_row(entry: dict[str, Any]) -> dict[str, Any]: name = str(entry.get("pm2", "")).strip() info = dict(info_map.get(name) or {}) if not info: info = {"process_status": "not_found", "out_path": None, "err_path": None, "pid": 0} info = _coerce_hub_process_info(pb, entry, info) status = str(info.get("process_status") or "").lower() online = status in {"online", "running", "launching"} if online: recent_log, recent_error = await asyncio.gather( asyncio.to_thread(_tail_file_text, info.get("out_path"), 48), asyncio.to_thread(_tail_file_text, info.get("err_path"), 32), ) ffmpeg_pids = await pb.live_ffmpeg_pids(name, info) else: recent_log = "" recent_error = "" ffmpeg_pids = [] activity = summarize_process_activity( name, str(info.get("process_status") or ""), recent_log, recent_error, log_age_seconds=_newest_log_age_seconds(info.get("out_path"), info.get("err_path")), ffmpeg_pids=ffmpeg_pids, ) source_meta = ( extract_douyin_source_meta(_youtube_url_lines_for_process(name), recent_log) if _is_youtube_monitor_entry(entry) else {} ) return { "pm2": name, "label": entry.get("label", name), "script": entry.get("script", ""), **info, **activity, **source_meta, } results = await asyncio.gather(*(build_live_row(entry) for entry in entries), return_exceptions=True) for entry, result in zip(entries, results): if isinstance(result, Exception): live_status["processes"].append( { "pm2": str(entry.get("pm2", "")).strip(), "label": entry.get("label", entry.get("pm2", "")), "script": entry.get("script", ""), "process_status": "error", "business_status": "error", "business_note": str(result), } ) else: live_status["processes"].append(result) pm2_tail = recent_pm2_log_lines(16) if not pm2_tail: pm2_tail = fallback_live_event_lines(live_status.get("processes") or [], 16) net_stats = network_iface_stats() hardware = await _dashboard_or(load_hardware_profile(False), {}, 2.0) redroid = await _dashboard_or(redroid_runtime_summary(), {}, 2.0) hdmi = await _dashboard_or(hdmi_capture_summary(), {}, 2.0) payload = { "snapshot": snap, "hardware": hardware, "stack": stack, "redroid": redroid, "hdmi": hdmi, "probes": probes, "services": services, "android": { "adb_available": adb_available(), "devices": devices, }, "live": live_status, "netdata": snap.get("netdata"), "network": net_stats, "live_events": { "pm2_tail": pm2_tail, "process_digest": [ { "pm2": str(p.get("pm2", "")), "label": str(p.get("label", "") or p.get("pm2", "")), "status": str(p.get("process_status", "") or ""), "business_status": str(p.get("business_status", "") or ""), } for p in live_status.get("processes") or [] ], }, } _dashboard_cache = (time.monotonic(), payload) return payload @router.get("/config") async def hub_config_read() -> dict[str, Any]: return load_hub_config_snapshot() @router.post("/network/wireguard/import") async def hub_network_wireguard_import(body: WireGuardImportBody) -> dict[str, Any]: return await hub_network_wireguard_save(body) @router.post("/network/wireguard/save") async def hub_network_wireguard_save(body: WireGuardImportBody) -> dict[str, Any]: repo_root = _repo_root or Path.cwd() try: if body.apply: result = await asyncio.to_thread( apply_wireguard_config, body.content, name=body.name, repo_root=repo_root, route_mode=body.route_mode or "overlay", ) status = result.get("status") if isinstance(result.get("status"), dict) else None access = (status or {}).get("neko_access") if isinstance((status or {}).get("neko_access"), dict) else None if access and access.get("mode") == "remote": result["neko_access"] = await asyncio.to_thread( configure_neko_wireguard_access, repo_root=repo_root, mode="remote", restart=True, status=status, ) else: result = await asyncio.to_thread( save_imported_wireguard_config, body.content, name=body.name, repo_root=repo_root, route_mode=body.route_mode, ) except WireGuardConfigError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except OSError as exc: raise HTTPException(status_code=500, detail=f"failed to save WireGuard config: {exc}") from exc return {"message": "applied" if body.apply else "saved", "wireguard": result} @router.post("/network/wireguard/apply") async def hub_network_wireguard_apply(body: WireGuardImportBody) -> dict[str, Any]: next_body = body.model_copy(update={"apply": True, "route_mode": body.route_mode or "overlay"}) return await hub_network_wireguard_save(next_body) @router.get("/network/wireguard/status") async def hub_network_wireguard_status() -> dict[str, Any]: repo_root = _repo_root or Path.cwd() status = await asyncio.to_thread(wireguard_runtime_status, repo_root=repo_root) return {"wireguard": status} @router.post("/network/wireguard/neko_access") async def hub_network_wireguard_neko_access(body: WireGuardNekoAccessBody) -> dict[str, Any]: repo_root = _repo_root or Path.cwd() try: access = await asyncio.to_thread( configure_neko_wireguard_access, repo_root=repo_root, mode=body.mode, restart=body.restart, ) except WireGuardConfigError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return {"message": "ok", "neko_access": access} @router.post("/network/neko_browser_proxy") async def hub_network_neko_browser_proxy(body: NekoBrowserProxyBody) -> dict[str, Any]: repo_root = _repo_root or Path.cwd() result = await asyncio.to_thread( configure_neko_browser_proxy, repo_root=repo_root, enabled=body.enabled, restart=body.restart, ) return {"message": "ok", "neko_browser_proxy": result} @router.get("/network/wireguard/config/{name}") async def hub_network_wireguard_config(name: str) -> dict[str, Any]: repo_root = _repo_root or Path.cwd() try: return await asyncio.to_thread(read_imported_wireguard_config, name, repo_root=repo_root) except WireGuardConfigError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc @router.get("/youtube_pro_channels") async def hub_youtube_pro_channels_read() -> dict[str, Any]: from src.hub_kv_store import get_youtube_pro_channels return {"channels": get_youtube_pro_channels()} @router.post("/youtube_pro_channels") async def hub_youtube_pro_channels_write(body: YoutubeProChannelsBody) -> dict[str, Any]: from src.hub_kv_store import get_youtube_pro_channels, merge_youtube_pro_channels, set_youtube_pro_channels try: if body.force: set_youtube_pro_channels(body.channels) channels = get_youtube_pro_channels() else: channels = merge_youtube_pro_channels(body.channels) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except sqlite3.Error as exc: raise HTTPException( status_code=500, detail=f"多频道状态数据库写入失败: {exc}; 请确认 config 目录归 live 用户可写", ) from exc capacity = await asyncio.to_thread(ensure_neko_capacity_for_youtube_channels, _repo_root, channels) return {"message": "ok", "channels": channels, "neko": capacity} @router.get("/youtube/live/summary") async def hub_youtube_live_summary() -> dict[str, Any]: return await asyncio.to_thread(youtube_live_summary) @router.get("/youtube/live/events") async def hub_youtube_live_events( status: str = "", process: str = "", limit: int = 50, offset: int = 0, ) -> dict[str, Any]: return await asyncio.to_thread( list_live_events, status=status, process=process, limit=limit, offset=offset, ) @router.get("/youtube/live/events/{event_id}") async def hub_youtube_live_event_detail(event_id: str) -> dict[str, Any]: event = await asyncio.to_thread(get_live_event, event_id) if not event: raise HTTPException(status_code=404, detail="live event not found") return {"event": event} @router.post("/youtube/live/events/{event_id}/close") async def hub_youtube_live_event_close(event_id: str, body: YoutubeLiveCloseBody) -> dict[str, Any]: result = await asyncio.to_thread(close_live_event, event_id, reason=body.reason) if not result: raise HTTPException(status_code=404, detail="live event not found") return result @router.post("/youtube/live/ingest") async def hub_youtube_live_ingest(payload: dict[str, Any]) -> dict[str, Any]: return await asyncio.to_thread(ingest_browser_telemetry, payload) @router.get("/services/declared") async def hub_services_declared() -> dict[str, Any]: return {"services": services_config_list()} @router.get("/business/douyinyoutube") async def hub_business_douyin_read() -> dict[str, Any]: return business_config("douyinyoutube") @router.post("/business/douyinyoutube") async def hub_business_douyin_patch(body: BusinessDouyinPatch) -> dict[str, str]: from src.live_config.loader import get_config_root root = get_config_root() path = root / "business" / "douyinyoutube.json" path.parent.mkdir(parents=True, exist_ok=True) current: dict = {} if path.is_file(): try: current = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: pass if body.streams is not None: cur_streams = current.get("streams") if isinstance(current.get("streams"), dict) else {} cur_streams.update({k: v for k, v in body.streams.items() if v is not None}) current["streams"] = cur_streams if body.ffmpeg is not None: cur_ff = current.get("ffmpeg") if isinstance(current.get("ffmpeg"), dict) else {} cur_ff.update(body.ffmpeg) current["ffmpeg"] = cur_ff path.write_text(json.dumps(current, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") msg = "business/douyinyoutube.json updated" if body.sync_youtube_ini and _repo_root is not None: streams = current.get("streams") if isinstance(current.get("streams"), dict) else {} raw_key = streams.get("youtube_rtmp_key") key_val = raw_key.strip() if isinstance(raw_key, str) else "" if key_val: msg = f"{msg}; {write_youtube_ini_stream_key(_repo_root, key_val)}" else: msg = f"{msg}; sync_youtube_ini skipped (no youtube_rtmp_key)" elif body.sync_youtube_ini and _repo_root is None: msg = f"{msg}; sync_youtube_ini skipped (repo root not configured)" return {"message": msg}