# -*- coding: utf-8 -*- """YouTube live relay state — Douyin FLV/HLS → RTMPS ingest.""" from __future__ import annotations import json import sqlite3 import time from typing import Any, Optional from .db import _connect, _lock, _row_to_dict def ensure_yt_relay_tables(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS yt_relay_states ( group_id TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'idle', source_url TEXT NOT NULL DEFAULT '', source_room_id TEXT NOT NULL DEFAULT '', anchor_name TEXT NOT NULL DEFAULT '', stream_input TEXT NOT NULL DEFAULT '', ffmpeg_pid INTEGER NOT NULL DEFAULT 0, speed REAL NOT NULL DEFAULT 0, frame INTEGER NOT NULL DEFAULT 0, error TEXT NOT NULL DEFAULT '', started_at REAL NOT NULL DEFAULT 0, updated_at REAL NOT NULL DEFAULT 0, push_seconds REAL NOT NULL DEFAULT 0, recent_log TEXT NOT NULL DEFAULT '[]' ) """ ) try: conn.execute("ALTER TABLE yt_relay_states ADD COLUMN recent_log TEXT NOT NULL DEFAULT '[]'") except sqlite3.OperationalError: pass conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_relay_status ON yt_relay_states(status, updated_at)" ) def _parse_recent_log(raw: Any) -> list[str]: if isinstance(raw, list): return [str(x)[:500] for x in raw][-200:] text = str(raw or "").strip() if not text: return [] try: data = json.loads(text) if isinstance(data, list): return [str(x)[:500] for x in data][-200:] except Exception: pass return [text[:500]] def _serialize_recent_log(lines: list[str] | None) -> str: if not lines: return "[]" return json.dumps([str(x)[:500] for x in lines][-200:], ensure_ascii=False) def get_relay_state(group_id: str) -> dict[str, Any] | None: gid = str(group_id or "").strip() if not gid: return None with _lock: conn = _connect() try: ensure_yt_relay_tables(conn) row = conn.execute("SELECT * FROM yt_relay_states WHERE group_id = ?", (gid,)).fetchone() out = _row_to_dict(row) if row else None if out and "recent_log" in out: out["recent_log"] = _parse_recent_log(out.get("recent_log")) return out finally: conn.close() def list_relay_states() -> list[dict[str, Any]]: with _lock: conn = _connect() try: ensure_yt_relay_tables(conn) rows = conn.execute( "SELECT * FROM yt_relay_states ORDER BY updated_at DESC" ).fetchall() return [_row_to_dict(r) for r in rows] # type: ignore finally: conn.close() def upsert_relay_state(group_id: str, **fields: Any) -> dict[str, Any]: gid = str(group_id or "").strip() now = time.time() with _lock: conn = _connect() try: ensure_yt_relay_tables(conn) existing = conn.execute( "SELECT group_id FROM yt_relay_states WHERE group_id = ?", (gid,) ).fetchone() data = dict(fields) if "recent_log" in data: data["recent_log"] = _serialize_recent_log(_parse_recent_log(data.get("recent_log"))) data["updated_at"] = now if existing: sets = ", ".join(f"{k} = ?" for k in data) conn.execute( f"UPDATE yt_relay_states SET {sets} WHERE group_id = ?", (*data.values(), gid), ) else: cols = ["group_id", *data.keys()] placeholders = ", ".join("?" for _ in cols) conn.execute( f"INSERT INTO yt_relay_states ({', '.join(cols)}) VALUES ({placeholders})", (gid, *data.values()), ) conn.commit() row = conn.execute("SELECT * FROM yt_relay_states WHERE group_id = ?", (gid,)).fetchone() return _row_to_dict(row) or {"group_id": gid} finally: conn.close() def clear_relay_state(group_id: str, *, status: str = "idle", error: str = "") -> None: upsert_relay_state( group_id, status=status, source_url="", source_room_id="", anchor_name="", stream_input="", ffmpeg_pid=0, speed=0, frame=0, error=str(error or "")[:500], started_at=0, push_seconds=0, recent_log="[]", ) def delete_relay_state(group_id: str) -> None: gid = str(group_id or "").strip() if not gid: return with _lock: conn = _connect() try: ensure_yt_relay_tables(conn) conn.execute("DELETE FROM yt_relay_states WHERE group_id = ?", (gid,)) conn.commit() finally: conn.close()