From e3d7d7a81312e4808c775db31b9253dbbe1e5a13 Mon Sep 17 00:00:00 2001 From: eric Date: Mon, 31 Aug 2026 02:01:25 -0500 Subject: [PATCH] feat: per-channel Neko studio in YouTube assign Pro panel --- backend/app/config.py | 9 + backend/app/db.py | 13 +- backend/app/main.py | 168 +++++- backend/app/models.py | 1 + backend/app/shorts_oauth.py | 22 +- backend/app/tiktok_oauth.py | 21 +- backend/app/youtube_neko.py | 367 +++++++++++++ backend/app/youtube_relay.py | 337 ++++++++++++ backend/app/youtube_relay_db.py | 157 ++++++ backend/app/youtube_relay_pipeline.py | 446 ++++++++++++++++ backend/app/youtube_relay_sessions.py | 330 ++++++++++++ backend/app/youtube_relay_status.py | 267 ++++++++++ backend/app/yt_assign_db.py | 71 ++- frontend/src/app/shorts/page.tsx | 4 +- frontend/src/app/youtube-relay-log/page.tsx | 436 ++++++++++++++++ .../src/components/GoogleOauthSetupWizard.tsx | 12 +- frontend/src/components/YtAssignPanel.tsx | 188 ++++++- .../src/components/YtRelayLiveLogCard.tsx | 106 ++++ .../src/components/YtRelayProStatusPanel.tsx | 297 +++++++++++ frontend/src/lib/ffmpegMetrics.ts | 120 +++++ frontend/src/lib/ytRelayStatus.ts | 86 ++++ frontend/src/lib/ytRelayUi.ts | 9 + scripts/_deploy_dy_nomadro.py | 487 ++++++++++++++++++ scripts/_deploy_yt_neko.py | 102 ++++ scripts/_finish_dy_deploy.py | 169 ++++++ 25 files changed, 4186 insertions(+), 39 deletions(-) create mode 100644 backend/app/youtube_neko.py create mode 100644 backend/app/youtube_relay.py create mode 100644 backend/app/youtube_relay_db.py create mode 100644 backend/app/youtube_relay_pipeline.py create mode 100644 backend/app/youtube_relay_sessions.py create mode 100644 backend/app/youtube_relay_status.py create mode 100644 frontend/src/app/youtube-relay-log/page.tsx create mode 100644 frontend/src/components/YtRelayLiveLogCard.tsx create mode 100644 frontend/src/components/YtRelayProStatusPanel.tsx create mode 100644 frontend/src/lib/ffmpegMetrics.ts create mode 100644 frontend/src/lib/ytRelayStatus.ts create mode 100644 frontend/src/lib/ytRelayUi.ts create mode 100644 scripts/_deploy_dy_nomadro.py create mode 100644 scripts/_deploy_yt_neko.py create mode 100644 scripts/_finish_dy_deploy.py diff --git a/backend/app/config.py b/backend/app/config.py index ce468f9..527966f 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -63,6 +63,15 @@ class Settings(BaseSettings): admin_password: str = "Xiao4669805@" session_secret: str = "douyinweb-session-2026" + # Neko browser (per YouTube assign group) — US VPS direct, no ShellClash + neko_enabled: bool = True + neko_http_port_base: int = 9200 + neko_webrtc_mux_base: int = 52300 + neko_user_pass: str = "douyinweb" + neko_admin_pass: str = "Xiao4669805@" + neko_image: str = "ghcr.io/m1k1o/neko/chromium:3.0.0" + neko_nat1to1: str = "" + class Config: env_prefix = "DY_" env_file = ".env" diff --git a/backend/app/db.py b/backend/app/db.py index 088fa8f..bacdd78 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -417,6 +417,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "yt_live_interval_sec": 90.0, "yt_batch_size": 8, "yt_request_gap_sec": 2.0, + # YouTube Douyin→YT live relay (FFmpeg RTMPS) + "youtube_relay_enabled": False, + "youtube_relay_bitrate": 2500, + "youtube_relay_use_rtmps": True, + "youtube_relay_respect_schedule": True, # Shorts pipeline "shorts_enabled": False, "shorts_clip_sec": 15, @@ -442,7 +447,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "shorts_oauth_redirect_uri": ( f"{str(settings.public_base_url or '').strip().rstrip('/')}/api/shorts/oauth/callback" if str(settings.public_base_url or "").strip() - else "https://dylive.nomadro.com/api/shorts/oauth/callback" + else "" ), # Named OAuth apps A/B/C/D — configure once in settings; channels pick a profile "shorts_oauth_profiles": [ @@ -543,7 +548,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "tiktok_oauth_check_interval_sec": 3600, "tiktok_oauth_client_key": "", "tiktok_oauth_client_secret": "", - "tiktok_oauth_redirect_uri": "https://dylive.nomadro.com/api/tiktok/oauth/callback/", + "tiktok_oauth_redirect_uri": ( + f"{str(settings.public_base_url or '').strip().rstrip('/')}/api/tiktok/oauth/callback/" + if str(settings.public_base_url or "").strip() + else "" + ), # Ops / audit / archive (all off by default — no behavior change on existing installs) "settings_audit_enabled": True, "db_backup_enabled": False, diff --git a/backend/app/main.py b/backend/app/main.py index 9fc6ef6..a9b252f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -84,6 +84,9 @@ 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 .youtube_relay_pipeline import youtube_relay_pipeline +from . import youtube_relay_sessions as relay_sessions +from . import youtube_neko from . import tiktok_session from .timeutil import stamp_beijing @@ -175,9 +178,14 @@ async def lifespan(_: FastAPI): await _boot("tiktok", tiktok_pipeline.start) await _boot("x_clips", x_clips_pipeline.start) await _boot("yt_long", yt_long_pipeline.start) + await _boot("youtube_relay", youtube_relay_pipeline.start) asyncio.create_task(_start_workers()) yield + try: + await youtube_relay_pipeline.stop() + except Exception: + pass try: await yt_long_pipeline.stop() except Exception: @@ -267,6 +275,7 @@ async def health() -> dict[str, Any]: 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) + out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status) except Exception as exc: out["status_error"] = str(exc)[:120] @@ -581,10 +590,10 @@ def _retry_shorts_job_record(job_id: str) -> dict[str, Any]: @app.get("/api/shorts/status") -async def shorts_status() -> dict[str, Any]: +async def shorts_status(request: Request) -> 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_redirect_uri"] = shorts_oauth.resolve_redirect_uri(_request_public_base(request)) 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") @@ -2803,15 +2812,170 @@ async def yt_assign_get_group(group_id: str) -> dict[str, Any]: @app.patch("/api/youtube/assign/groups/{group_id}") async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> dict[str, Any]: try: + prev = yt_assign_db.get_group(group_id) g = yt_assign_db.update_group( group_id, **body.model_dump(exclude_unset=True), ) + if prev and prev.get("enabled") and not g.get("enabled"): + await youtube_relay_pipeline.stop_group(group_id) return {"ok": True, "group": g} except ValueError as exc: raise HTTPException(400, str(exc)) from exc +@app.get("/api/youtube/relay/status") +async def youtube_relay_status() -> dict[str, Any]: + return await asyncio.to_thread(youtube_relay_pipeline.status) + + +@app.post("/api/youtube/relay/start") +async def youtube_relay_start() -> dict[str, Any]: + db.update_settings_map({"youtube_relay_enabled": True}) + await youtube_relay_pipeline.start() + return await asyncio.to_thread(youtube_relay_pipeline.status) + + +@app.post("/api/youtube/relay/stop") +async def youtube_relay_stop() -> dict[str, Any]: + db.update_settings_map({"youtube_relay_enabled": False}) + await youtube_relay_pipeline.stop() + return await asyncio.to_thread(youtube_relay_pipeline.status) + + +@app.post("/api/youtube/relay/groups/{group_id}/start") +async def youtube_relay_group_start(group_id: str) -> dict[str, Any]: + try: + return await youtube_relay_pipeline.start_group(group_id) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + +@app.post("/api/youtube/relay/groups/{group_id}/stop") +async def youtube_relay_group_stop(group_id: str) -> dict[str, Any]: + return await youtube_relay_pipeline.stop_group(group_id) + + +@app.post("/api/youtube/relay/groups/{group_id}/restart") +async def youtube_relay_group_restart(group_id: str) -> dict[str, Any]: + try: + return await youtube_relay_pipeline.restart_group(group_id) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + +@app.get("/api/youtube/relay/process_monitor") +async def youtube_relay_process_monitor() -> dict[str, Any]: + """PM2-compatible process monitor snapshot (cloud pipeline).""" + return await asyncio.to_thread(youtube_relay_pipeline.status) + + +@app.get("/api/youtube/relay/sessions") +async def youtube_relay_sessions_list( + group_id: str = "", + process: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + limit: int = 50, + offset: int = 0, +) -> dict[str, Any]: + gid = (group_id or process or "").strip() + return await asyncio.to_thread( + relay_sessions.list_sessions, + group_id=gid, + q=q, + date_from=date_from, + date_to=date_to, + status=status, + limit=limit, + offset=offset, + ) + + +@app.get("/api/youtube/relay/sessions/stats") +async def youtube_relay_sessions_stats( + group_id: str = "", + process: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + top_anchors: int = 20, +) -> dict[str, Any]: + gid = (group_id or process or "").strip() + return await asyncio.to_thread( + relay_sessions.summarize_sessions, + group_id=gid, + q=q, + date_from=date_from, + date_to=date_to, + status=status, + top_anchors=top_anchors, + ) + + +@app.get("/api/youtube/relay/sessions/{session_id}") +async def youtube_relay_session_detail(session_id: int) -> dict[str, Any]: + row = await asyncio.to_thread(relay_sessions.get_session, session_id) + if not row: + raise HTTPException(404, "会话不存在") + return row + + +@app.get("/api/youtube/neko/status") +async def youtube_neko_status() -> dict[str, Any]: + groups = await asyncio.to_thread(yt_assign_db.list_groups, False) + ids = [int(g.get("neko_instance_id") or 0) for g in groups] + desired = max(ids) if ids else 0 + return await asyncio.to_thread(youtube_neko.status_summary, desired=desired) + + +@app.post("/api/youtube/neko/instances/{instance_id}/{action}") +async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: + try: + result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action) + return {"ok": True, **result} + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except RuntimeError as exc: + raise HTTPException(500, str(exc)) from exc + + +@app.post("/api/youtube/assign/groups/{group_id}/neko") +async def youtube_assign_group_neko(group_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + """Toggle Neko for one assign group; optional action start|stop|restart.""" + body = body or {} + g = yt_assign_db.get_group(group_id) + if not g: + raise HTTPException(404, "分组不存在") + instance_id = int(g.get("neko_instance_id") or 0) + if instance_id < 1: + raise HTTPException(400, "该分组未分配 Neko 实例") + + if "enabled" in body: + g = yt_assign_db.update_group(group_id, neko_enabled=bool(body.get("enabled"))) + + action = str(body.get("action") or "").strip().lower() + neko_result: dict[str, Any] | None = None + if action in {"start", "stop", "restart"}: + if action == "start" and not g.get("neko_enabled"): + g = yt_assign_db.update_group(group_id, neko_enabled=True) + try: + neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action) + except (ValueError, RuntimeError) as exc: + raise HTTPException(400, str(exc)) from exc + elif g.get("neko_enabled"): + try: + neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, "start") + except RuntimeError: + neko_result = None + + inst = await asyncio.to_thread(youtube_neko._container_state, instance_id) + return {"ok": True, "group": g, "neko": neko_result or inst} + + @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) diff --git a/backend/app/models.py b/backend/app/models.py index 437cd7c..dc7bb13 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -369,6 +369,7 @@ class YtAssignGroupUpdate(BaseModel): note: Optional[str] = None enabled: Optional[bool] = None sort_order: Optional[int] = None + neko_enabled: Optional[bool] = None class YtAssignPoolAdd(BaseModel): diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index c9dbc77..938293a 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -165,17 +165,23 @@ def oauth_client_configured() -> bool: def resolve_redirect_uri(request_base: str = "") -> str: cfg = _cfg() - custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip() - if custom: - return custom.rstrip("/") - base = (request_base or "").rstrip("/") - if base: - return f"{base}/api/shorts/oauth/callback" + from urllib.parse import urlparse + from .config import settings as app_settings pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/") - if pub: - return f"{pub}/api/shorts/oauth/callback" + base = pub or (request_base or "").rstrip("/") + derived = f"{base}/api/shorts/oauth/callback" if base else "" + + custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip().rstrip("/") + if custom and pub: + if urlparse(custom).netloc == urlparse(pub).netloc: + return custom + return derived or custom + if custom: + return custom + if derived: + return derived return "https://dylive.nomadro.com/api/shorts/oauth/callback" diff --git a/backend/app/tiktok_oauth.py b/backend/app/tiktok_oauth.py index 7b7a310..03461f0 100644 --- a/backend/app/tiktok_oauth.py +++ b/backend/app/tiktok_oauth.py @@ -35,13 +35,22 @@ def oauth_configured(cfg: dict[str, Any] | None = None) -> bool: def resolve_redirect_uri(request_base: str = "") -> str: cfg = _cfg() - custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip() + from urllib.parse import urlparse + + from .config import settings as app_settings + + pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/") + base = pub or (request_base or "").rstrip("/") + derived = f"{base}/api/tiktok/oauth/callback/" if base else "" + + custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip().rstrip("/") if custom: - uri = custom.rstrip("/") + "/" - return uri - base = (request_base or "").rstrip("/") - if base: - return f"{base}/api/tiktok/oauth/callback/" + custom_uri = custom.rstrip("/") + "/" + if pub and urlparse(custom_uri).netloc != urlparse(pub).netloc: + return derived or custom_uri + return custom_uri + if derived: + return derived return "https://dylive.nomadro.com/api/tiktok/oauth/callback/" diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py new file mode 100644 index 0000000..b72f067 --- /dev/null +++ b/backend/app/youtube_neko.py @@ -0,0 +1,367 @@ +# -*- coding: utf-8 -*- +"""Per-channel Neko browser (Docker) for YouTube Studio — no ShellClash/WireGuard.""" +from __future__ import annotations + +import json +import shutil +import subprocess +import threading +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +from .config import settings + +_lock = threading.RLock() +MAX_INSTANCES = 32 +MIN_UDP_PORT = 52000 + + +def _neko_root() -> Path: + p = settings.data_dir / "neko" + p.mkdir(parents=True, exist_ok=True) + (p / "profiles").mkdir(parents=True, exist_ok=True) + return p + + +def _compose_path() -> Path: + return _neko_root() / "docker-compose.yml" + + +def _http_port(instance_id: int) -> int: + return int(getattr(settings, "neko_http_port_base", 9200) or 9200) + instance_id - 1 + + +def _webrtc_mux(instance_id: int) -> int: + return int(getattr(settings, "neko_webrtc_mux_base", 52300) or 52300) + instance_id - 1 + + +def _udp_range(instance_id: int) -> str: + base = MIN_UDP_PORT + (instance_id - 1) * 100 + return f"{base}-{base + 98}" + + +def _container_name(instance_id: int) -> str: + return f"douyinweb-neko-{instance_id}" + + +def _docker_available() -> bool: + return bool(shutil.which("docker")) + + +def _run(cmd: list[str], *, timeout: float = 120.0) -> tuple[int, str]: + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + out = (proc.stdout or "") + (proc.stderr or "") + return proc.returncode, out.strip() + except subprocess.TimeoutExpired: + return 124, "timeout" + except OSError as exc: + return 1, str(exc) + + +def _public_base() -> str: + return str(settings.public_base_url or "").strip().rstrip("/") + + +def public_studio_url(instance_id: int) -> str: + base = _public_base() + if base: + return f"{base}/neko/{instance_id}/" + return f"http://127.0.0.1:{_http_port(instance_id)}/" + + +def _render_compose(count: int) -> str: + image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/chromium:3.0.0") + user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb") + admin_pass = str(getattr(settings, "neko_admin_pass", "") or "douyinweb") + nat1to1 = str(getattr(settings, "neko_nat1to1", "") or "").strip() + start_url = "https://studio.youtube.com/" + root = _neko_root() + lines = ["# Generated by douyinWEB — do not edit", "services:"] + for idx in range(1, count + 1): + http_port = _http_port(idx) + mux = _webrtc_mux(idx) + udp = _udp_range(idx) + profile = root / "profiles" / str(idx) + profile.mkdir(parents=True, exist_ok=True) + lines.extend( + [ + f" neko{idx}:", + f" image: {image}", + " restart: unless-stopped", + " shm_size: 512mb", + " cap_add:", + " - SYS_ADMIN", + " security_opt:", + " - apparmor:unconfined", + f" container_name: {_container_name(idx)}", + " environment:", + " TZ: America/Chicago", + ' NEKO_SERVER_BIND: ":8080"', + ' NEKO_MEMBER_PROVIDER: "multiuser"', + f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {user_pass}", + f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {admin_pass}", + " NEKO_DESKTOP_SCREEN: 1280x720@15", + " NEKO_MAX_FPS: 15", + " NEKO_VIDEO_BITRATE: 1200", + " NEKO_WEBRTC_ICELITE: 1", + f" NEKO_WEBRTC_NAT1TO1: {nat1to1}", + f" NEKO_WEBRTC_TCPMUX: {mux}", + f" NEKO_WEBRTC_UDPMUX: {mux}", + f" NEKO_WEBRTC_EPR: {udp}", + f" NEKO_START_URL: {start_url}", + " NEKO_BROWSER_PROXY: ''", + " ports:", + f' - "127.0.0.1:{http_port}:8080"', + f' - "127.0.0.1:{mux}:{mux}/tcp"', + f' - "127.0.0.1:{mux}:{mux}/udp"', + f' - "127.0.0.1:{udp}:{udp}/udp"', + " volumes:", + f' - "{profile}:/home/neko/.config/chromium"', + f' - "{profile}:/home/neko/.config/google-chrome"', + ] + ) + return "\n".join(lines) + "\n" + + +def _compose_cmd(*args: str) -> list[str]: + return ["docker", "compose", "-f", str(_compose_path()), *args] + + +def _container_state(instance_id: int) -> dict[str, Any]: + name = _container_name(instance_id) + port = _http_port(instance_id) + out: dict[str, Any] = { + "id": instance_id, + "container": name, + "http_port": port, + "studio_url": public_studio_url(instance_id), + "exists": False, + "running": False, + "ready": False, + "status": "missing", + "detail": "", + } + if not _docker_available(): + out["detail"] = "docker_unavailable" + return out + code, text = _run( + ["docker", "inspect", name, "--format", "{{json .State}}"], + timeout=15, + ) + if code != 0: + out["detail"] = text[:200] + return out + out["exists"] = True + try: + state = json.loads(text or "{}") + except json.JSONDecodeError: + out["detail"] = text[:200] + return out + running = bool(state.get("Running")) + health = str((state.get("Health") or {}).get("Status") or "") + out["running"] = running + out["status"] = health if health else ("running" if running else str(state.get("Status") or "stopped")) + if running: + hc, _ = _run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"], timeout=8) + out["ready"] = hc == 200 + return out + + +def ensure_capacity(desired: int, *, start_instances: set[int] | None = None) -> dict[str, Any]: + """Render compose for `desired` instances; create containers (optionally start subset).""" + desired = max(0, min(MAX_INSTANCES, int(desired or 0))) + if desired == 0: + return {"ok": True, "desired": 0, "changed": False, "message": "no_instances"} + if not _docker_available(): + return {"ok": False, "desired": desired, "error": "Docker 不可用,请先在服务器安装 Docker"} + + with _lock: + compose = _compose_path() + text = _render_compose(desired) + changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text + if changed: + compose.write_text(text, encoding="utf-8") + + code, out = _run(_compose_cmd("up", "-d", "--remove-orphans"), timeout=300) + if code != 0: + return {"ok": False, "desired": desired, "error": out[:500] or "compose up failed"} + + started: list[int] = [] + stopped: list[int] = [] + for idx in range(1, desired + 1): + should_run = start_instances is None or idx in start_instances + if should_run: + c, _ = _run(["docker", "start", _container_name(idx)], timeout=45) + if c == 0: + started.append(idx) + else: + c, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=30) + if c == 0: + stopped.append(idx) + + sync_nginx_proxy(desired) + return { + "ok": True, + "desired": desired, + "changed": changed, + "started": started, + "stopped": stopped, + "detail": out[:300], + } + + +def sync_nginx_proxy(count: int) -> dict[str, Any]: + """Write nginx reverse-proxy snippets for /neko/{id}/ → local ports.""" + base = _public_base() + if not base: + return {"ok": False, "skipped": "no_public_base"} + host = urlparse(base).hostname or "" + if not host: + return {"ok": False, "skipped": "no_host"} + conf_path = Path("/etc/nginx/conf.d/douyinweb-neko.conf") + if not conf_path.parent.is_dir(): + return {"ok": False, "skipped": "no_nginx"} + + blocks: list[str] = [] + for idx in range(1, max(0, int(count)) + 1): + port = _http_port(idx) + mux = _webrtc_mux(idx) + blocks.append( + f""" + location ^~ /neko/{idx}/ {{ + proxy_pass http://127.0.0.1:{port}/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + }} + location ^~ /neko/{idx}/ws {{ + proxy_pass http://127.0.0.1:{port}/ws; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 3600s; + }} + location ^~ /neko/{idx}/mux/ {{ + proxy_pass http://127.0.0.1:{mux}/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + }}""" + ) + body = f"""# douyinWEB Neko reverse proxy — auto-generated +server {{ + listen 80; + server_name {host}; +{''.join(blocks)} +}} +""" + # Merge into existing ssl server via include pattern + include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf") + loc_body = "\n".join(blocks) + try: + include_path.write_text(loc_body + "\n", encoding="utf-8") + # Patch main vhost if snippet marker missing + vhost = Path(f"/etc/nginx/conf.d/dy-nomadro-live.conf") + if not vhost.is_file(): + for p in Path("/etc/nginx/conf.d").glob("*.conf"): + if "nomadro" in p.name or "douyin" in p.name: + vhost = p + break + if vhost.is_file(): + raw = vhost.read_text(encoding="utf-8") + marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;" + if marker not in raw and "douyinweb-neko-locations" not in raw: + raw = raw.replace( + "location / {", + f" {marker}\n\n location / {{", + 1, + ) + vhost.write_text(raw, encoding="utf-8") + _run(["nginx", "-t"], timeout=15) + _run(["systemctl", "reload", "nginx"], timeout=15) + return {"ok": True, "instances": count} + except OSError as exc: + return {"ok": False, "error": str(exc)} + + +def instance_action(instance_id: int, action: str) -> dict[str, Any]: + action = str(action or "").strip().lower() + if action not in {"status", "start", "stop", "restart"}: + raise ValueError(f"不支持的操作: {action}") + if instance_id < 1 or instance_id > MAX_INSTANCES: + raise ValueError(f"实例编号须在 1–{MAX_INSTANCES}") + + before = _container_state(instance_id) + message = f"Neko {instance_id}: {before.get('status')}" + + if action == "start": + ensure_capacity(instance_id, start_instances={instance_id}) + code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) + if code != 0 and not before.get("exists"): + ensure_capacity(instance_id, start_instances={instance_id}) + code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) + if code != 0: + raise RuntimeError(out or "启动失败") + message = f"Neko {instance_id} 已启动" + elif action == "stop": + if before.get("exists"): + code, out = _run(["docker", "stop", "-t", "10", _container_name(instance_id)], timeout=45) + if code != 0: + raise RuntimeError(out or "停止失败") + message = f"Neko {instance_id} 已停止" + elif action == "restart": + ensure_capacity(instance_id, start_instances={instance_id}) + code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90) + if code != 0: + raise RuntimeError(out or "重启失败") + message = f"Neko {instance_id} 已重启" + + after = _container_state(instance_id) + after["action"] = action + after["message"] = message + after["available"] = _docker_available() + return after + + +def list_instances(count: int) -> list[dict[str, Any]]: + return [_container_state(i) for i in range(1, max(0, int(count)) + 1)] + + +def status_summary(*, desired: int) -> dict[str, Any]: + desired = max(0, min(MAX_INSTANCES, int(desired or 0))) + instances = list_instances(desired) + running = sum(1 for x in instances if x.get("running")) + return { + "available": _docker_available(), + "desired": desired, + "running": running, + "instances": instances, + "enabled": bool(getattr(settings, "neko_enabled", True)), + } + + +def sync_for_groups(groups: list[dict[str, Any]]) -> dict[str, Any]: + """Ensure docker capacity matches assign groups; start only neko_enabled groups.""" + ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0] + desired = max(ids) if ids else 0 + if desired == 0: + return {"ok": True, "desired": 0} + start_set = { + int(g.get("neko_instance_id") or 0) + for g in groups + if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0 + } + return ensure_capacity(desired, start_instances=start_set) diff --git a/backend/app/youtube_relay.py b/backend/app/youtube_relay.py new file mode 100644 index 0000000..1bba379 --- /dev/null +++ b/backend/app/youtube_relay.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- +"""FFmpeg Douyin live → YouTube RTMPS relay (cloud server, no ShellCrash/Neko).""" +from __future__ import annotations + +import re +import subprocess +import threading +import time +from dataclasses import dataclass, field +from typing import Any, Callable + +from .config import settings + + +class RelayStreamEnded(Exception): + """Source ended (anchor offline).""" + + +class RelaySourceStalled(Exception): + """No progress from FFmpeg — try another source URL.""" + + +MAX_RELAY_LOG_LINES = 200 + + +@dataclass +class RelayStats: + speed: float = 0.0 + frame: int = 0 + pid: int = 0 + running: bool = False + last_line: str = "" + recent_log: list[str] = field(default_factory=list) + + +def _headers_arg() -> str: + return ( + "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) " + "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1\r\n" + "Referer: https://live.douyin.com/\r\n" + ) + + +def _bitrate_triplet(kbps: int) -> tuple[str, str, str]: + n = max(1500, min(int(kbps), 9000)) + s = f"{n}k" + return s, s, f"{n * 2}k" + + +def _parse_ffmpeg_line(line: str) -> tuple[float | None, int | None]: + speed = None + frame = None + m = re.search(r"speed=\s*([\d.]+)x", line) + if m: + try: + speed = float(m.group(1)) + except ValueError: + pass + m2 = re.search(r"frame=\s*(\d+)", line) + if m2: + try: + frame = int(m2.group(1)) + except ValueError: + pass + return speed, frame + + +def build_youtube_rtmp_url(stream_key: str, *, use_rtmps: bool = True) -> str: + key = str(stream_key or "").strip() + if not key: + raise ValueError("缺少 YouTube 直播 KEY") + if key.startswith("rtmp"): + return key + base = "rtmps://a.rtmps.youtube.com/live2/" if use_rtmps else "rtmp://a.rtmp.youtube.com/live2/" + return f"{base}{key}" + + +def build_ffmpeg_relay_cmd( + input_url: str, + youtube_rtmp: str, + *, + bitrate_kbps: int = 4000, + ffmpeg_bin: str | None = None, +) -> list[str]: + b_v, maxrate, bufsize = _bitrate_triplet(bitrate_kbps) + ff = str(ffmpeg_bin or settings.ffmpeg_bin or "ffmpeg") + vf = ( + "fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear," + "pad=720:1280:(ow-iw)/2:(oh-ih)/2:black" + ) + is_flv = ".flv" in input_url.lower() or "pull-" in input_url.lower() + input_args: list[str] = [] + if is_flv: + input_args = ["-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "30"] + return [ + ff, + "-y", + "-loglevel", + "info", + "-nostdin", + "-stats", + "-rw_timeout", + "50000000", + *input_args, + "-fflags", + "+genpts+discardcorrupt", + "-thread_queue_size", + "2048", + "-headers", + _headers_arg(), + "-re", + "-i", + input_url, + "-vf", + vf, + "-c:v", + "libx264", + "-preset", + "veryfast", + "-tune", + "zerolatency", + "-profile:v", + "high", + "-level", + "4.0", + "-b:v", + b_v, + "-minrate", + b_v, + "-maxrate", + maxrate, + "-bufsize", + bufsize, + "-g", + "60", + "-keyint_min", + "60", + "-r", + "30", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-b:a", + "128k", + "-ar", + "48000", + "-ac", + "2", + "-af", + "aresample=async=1:first_pts=0", + "-flags", + "+global_header", + "-flvflags", + "no_duration_filesize", + "-f", + "flv", + youtube_rtmp, + ] + + +def _terminate_proc(proc: subprocess.Popen | None) -> None: + if not proc: + return + try: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + except Exception: + pass + + +class RelayPushSession: + """One FFmpeg push subprocess with stderr monitoring.""" + + STALE_SEC = 90.0 + + def __init__( + self, + *, + group_id: str, + input_url: str, + youtube_rtmp: str, + anchor_name: str = "", + source_url: str = "", + room_id: str = "", + bitrate_kbps: int = 4000, + on_stats: Callable[[RelayStats], None] | None = None, + ) -> None: + self.group_id = group_id + self.input_url = input_url + self.youtube_rtmp = youtube_rtmp + self.anchor_name = anchor_name + self.source_url = source_url + self.room_id = room_id + self.bitrate_kbps = bitrate_kbps + self.on_stats = on_stats + self._proc: subprocess.Popen | None = None + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self.stats = RelayStats() + + def start(self) -> None: + if self._thread and self._thread.is_alive(): + return + self._stop.clear() + self._thread = threading.Thread(target=self._run, name=f"yt-relay-{self.group_id}", daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + _terminate_proc(self._proc) + if self._thread: + self._thread.join(timeout=8) + self.stats.running = False + + def _run(self) -> None: + cmd = build_ffmpeg_relay_cmd( + self.input_url, + self.youtube_rtmp, + bitrate_kbps=self.bitrate_kbps, + ) + import queue as _queue + + q: _queue.Queue[str | None] = _queue.Queue() + self.stats.recent_log.append(f"[ffmpeg] cmd={cmd[0]} bitrate={self.bitrate_kbps}k") + self.stats.recent_log.append(f"[ffmpeg] -i {self.input_url[:180]}") + + def _reader() -> None: + proc = self._proc + if not proc or not proc.stderr: + q.put(None) + return + try: + for line in proc.stderr: + if self._stop.is_set(): + break + q.put(line.rstrip("\n")) + except Exception as exc: + q.put(f"[ffmpeg] reader error: {exc}") + finally: + q.put(None) + + while not self._stop.is_set(): + try: + self._proc = subprocess.Popen( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + bufsize=1, + ) + except FileNotFoundError: + self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found") + self.stats.running = False + if self.on_stats: + try: + self.on_stats(self.stats) + except Exception: + pass + return + except Exception as exc: + self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}") + self.stats.running = False + if self.on_stats: + try: + self.on_stats(self.stats) + except Exception: + pass + return + + self.stats.pid = int(self._proc.pid or 0) + self.stats.running = True + self.stats.recent_log.append(f"[ffmpeg] pid={self.stats.pid} started") + if self.on_stats: + try: + self.on_stats(self.stats) + except Exception: + pass + last_out = time.time() + reader = threading.Thread(target=_reader, daemon=True) + reader.start() + + while not self._stop.is_set(): + try: + line = q.get(timeout=2.0) + except _queue.Empty: + if time.time() - last_out > self.STALE_SEC: + self.stats.recent_log.append("[ffmpeg] stale: no stderr for 90s, restarting") + _terminate_proc(self._proc) + break + continue + if line is None: + break + last_out = time.time() + self.stats.last_line = line[:240] + self.stats.recent_log.append(line[:500]) + if len(self.stats.recent_log) > MAX_RELAY_LOG_LINES: + self.stats.recent_log = self.stats.recent_log[-MAX_RELAY_LOG_LINES:] + sp, fr = _parse_ffmpeg_line(line) + if sp is not None: + self.stats.speed = sp + if fr is not None: + self.stats.frame = fr + if self.on_stats: + try: + self.on_stats(self.stats) + except Exception: + pass + low = line.lower() + if "end of file" in low or "stream ended" in low: + _terminate_proc(self._proc) + break + if "404 not found" in low or "403 forbidden" in low: + _terminate_proc(self._proc) + break + + code = self._proc.poll() if self._proc else None + self.stats.recent_log.append(f"[ffmpeg] exited code={code}") + if self.on_stats: + try: + self.on_stats(self.stats) + except Exception: + pass + _terminate_proc(self._proc) + self.stats.running = False + if self._stop.is_set(): + return + time.sleep(3) + if self._stop.is_set(): + return + + self.stats.running = False diff --git a/backend/app/youtube_relay_db.py b/backend/app/youtube_relay_db.py new file mode 100644 index 0000000..1d363c7 --- /dev/null +++ b/backend/app/youtube_relay_db.py @@ -0,0 +1,157 @@ +# -*- 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() diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py new file mode 100644 index 0000000..9a7723a --- /dev/null +++ b/backend/app/youtube_relay_pipeline.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +"""Background worker: Douyin live → YouTube RTMPS relay per assign group.""" +from __future__ import annotations + +import asyncio +import time +from typing import Any + +from . import db +from . import yt_assign_db +from . import youtube_relay_db +from .shorts_clip import resolve_stream_candidates +from . import youtube_relay_sessions as relay_sessions +from .youtube_relay import RelayPushSession, RelayStats, build_youtube_rtmp_url +from .youtube_relay_status import log_age_seconds, summarize_relay_group, _key_suffix + + +def _live_room_ids() -> set[str]: + rows = db.list_live_douyin_rooms_for_shorts(limit=500) + return {str(r.get("room_id") or "").strip() for r in rows if r.get("room_id")} + + +def pick_source_for_group(group: dict[str, Any], *, respect_schedule: bool = True) -> dict[str, str] | None: + """Choose Douyin source from 精选列表 only; prefer live rooms, then list order.""" + gid = str(group.get("id") or "") + if not gid or not group.get("enabled"): + return None + if respect_schedule: + sched = yt_assign_db.build_rotation_schedule(include_urls=False) + active_map = { + str(c.get("group_id") or ""): bool(c.get("active")) + for c in (sched.get("channels") or []) + } + if active_map and gid in active_map and not active_map[gid]: + return None + + live_ids = _live_room_ids() + candidates: list[dict[str, Any]] = [] + for idx, item in enumerate(group.get("featured") or []): + if item.get("blacklisted"): + continue + url = str(item.get("url") or "").strip() + if not url: + continue + rid = str(item.get("room_id") or "").strip() + live = rid in live_ids if rid else False + candidates.append( + { + "url": url, + "room_id": rid, + "title": str(item.get("title") or item.get("pool_note") or "").strip(), + "live": live, + "idx": idx, + } + ) + candidates.sort(key=lambda x: (0 if x["live"] else 1, x["idx"])) + for c in candidates: + return { + "source_url": c["url"], + "room_id": c["room_id"], + "anchor_name": c["title"], + } + return None + + +class YoutubeRelayPipeline: + def __init__(self) -> None: + self._task: asyncio.Task | None = None + self._stop = asyncio.Event() + self._sessions: dict[str, RelayPushSession] = {} + # Manual Start holds the lane even outside schedule until Stop / auto window reclaim. + self._manual_hold: set[str] = set() + self.last_error = "" + self.processed = 0 + + def status(self) -> dict[str, Any]: + cfg = db.get_settings_map() + groups = yt_assign_db.list_groups(include_urls=False) + groups_full = {str(g.get("id") or ""): g for g in yt_assign_db.list_groups(include_urls=True)} + states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()} + relay_groups: list[dict[str, Any]] = [] + entries: list[dict[str, Any]] = [] + pushing = 0 + pipeline_enabled = bool(cfg.get("youtube_relay_enabled")) + now = time.time() + for g in groups: + gid = str(g.get("id") or "") + gf = groups_full.get(gid) or g + st = dict(states.get(gid) or {}) + sess = self._sessions.get(gid) + running = bool(sess and sess.stats.running) + recent_log = list( + sess.stats.recent_log if sess else youtube_relay_db._parse_recent_log(st.get("recent_log")) + ) + st["recent_log"] = recent_log + monitor = summarize_relay_group( + group=gf, + st=st, + session_running=running, + pipeline_enabled=pipeline_enabled, + log_age_seconds=log_age_seconds(st, now), + ) + if monitor.get("is_pushing"): + pushing += 1 + row = { + "group_id": gid, + "name": g.get("name"), + "channel_pk": g.get("channel_pk"), + "enabled": bool(g.get("enabled")), + "status": "pushing" if running else str(st.get("status") or "idle"), + "error": st.get("error") or "", + "manual_hold": gid in self._manual_hold, + **monitor, + } + relay_groups.append(row) + entries.append({**monitor, "channel_pk": g.get("channel_pk"), "manual_hold": gid in self._manual_hold}) + schedule = yt_assign_db.build_rotation_schedule(include_urls=True) + return { + "running": bool(self._task and not self._task.done()), + "enabled": pipeline_enabled, + "pushing_count": pushing, + "group_count": len(groups), + "enabled_groups": sum(1 for g in groups if g.get("enabled")), + "last_error": self.last_error, + "douyin_live_count": len(_live_room_ids()), + "process_backend": "cloud_pipeline", + "family": "youtube", + "light": True, + "entries": entries, + "settings": { + "youtube_relay_enabled": pipeline_enabled, + "youtube_relay_bitrate": int(cfg.get("youtube_relay_bitrate") or 2500), + "youtube_relay_use_rtmps": bool(cfg.get("youtube_relay_use_rtmps", True)), + "youtube_relay_respect_schedule": bool(cfg.get("youtube_relay_respect_schedule", True)), + }, + "groups": relay_groups, + "schedule": schedule, + } + + async def start(self) -> None: + if self._task and not self._task.done(): + return + self._stop.clear() + self._task = asyncio.create_task(self._loop(), name="youtube-relay-pipeline") + + async def stop(self) -> None: + self._stop.set() + for sess in list(self._sessions.values()): + await asyncio.to_thread(sess.stop) + self._sessions.clear() + self._manual_hold.clear() + if self._task: + try: + await asyncio.wait_for(self._task, timeout=8) + except Exception: + self._task.cancel() + self._task = None + + async def start_group(self, group_id: str) -> dict[str, Any]: + """Manual Start — always ignores schedule (like sh2 Pro Start).""" + gid = str(group_id or "").strip() + g = yt_assign_db.get_group(gid) + if not g: + raise ValueError("分配组不存在") + if not g.get("enabled"): + raise ValueError("该组已停用") + if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"): + raise ValueError("请先配置 YouTube 直播 KEY") + featured = [x for x in (g.get("featured") or []) if str(x.get("url") or "").strip() and not x.get("blacklisted")] + if not featured: + raise ValueError("直播地址列表(精选)为空,请先加入抖音房间") + + self._manual_hold.add(gid) + result = await self._ensure_group_relay(g, force=True, respect_schedule=False) + if not result.get("ok"): + self._manual_hold.discard(gid) + raise ValueError(str(result.get("error") or "启动推流失败")) + return {"ok": True, "group_id": gid, **result} + + async def _halt_session(self, group_id: str, *, reason: str = "stopped") -> None: + """Stop FFmpeg for a group without clearing manual_hold.""" + gid = str(group_id or "").strip() + sess = self._sessions.pop(gid, None) + if sess: + await asyncio.to_thread(sess.stop) + youtube_relay_db.clear_relay_state(gid, status="stopped") + await asyncio.to_thread(relay_sessions.end_session, gid, reason=reason) + + async def stop_group(self, group_id: str) -> dict[str, Any]: + gid = str(group_id or "").strip() + self._manual_hold.discard(gid) + await self._halt_session(gid, reason="stopped") + return {"ok": True, "group_id": gid} + + async def restart_group(self, group_id: str) -> dict[str, Any]: + gid = str(group_id or "").strip() + await self.stop_group(gid) + return await self.start_group(gid) + + async def _loop(self) -> None: + while not self._stop.is_set(): + try: + cfg = db.get_settings_map() + if not cfg.get("youtube_relay_enabled"): + # Auto off: leave manual-hold sessions alone; stop orphan auto sessions. + for gid in list(self._sessions.keys()): + if gid not in self._manual_hold: + await self.stop_group(gid) + await asyncio.sleep(2.0) + continue + respect = bool(cfg.get("youtube_relay_respect_schedule", True)) + groups = yt_assign_db.list_groups(include_urls=True) + active_ids: set[str] = set() + for g in groups: + gid = str(g.get("id") or "") + if not gid or not g.get("enabled"): + if gid: + await self.stop_group(gid) + continue + if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"): + await self.stop_group(gid) + continue + manual = gid in self._manual_hold + src = pick_source_for_group(g, respect_schedule=False if manual else respect) + if not src: + if manual and gid in self._sessions: + # Keep manual push; still tick stats. + active_ids.add(gid) + continue + await self.stop_group(gid) + continue + active_ids.add(gid) + await self._ensure_group_relay( + g, + source=src, + cfg=cfg, + respect_schedule=False if manual else respect, + ) + for gid in list(self._sessions.keys()): + if gid not in active_ids and gid not in self._manual_hold: + await self.stop_group(gid) + await self._tick_stats() + except Exception as exc: + self.last_error = str(exc)[:240] + await asyncio.sleep(4.0) + + async def _stop_all_sessions(self) -> None: + for gid in list(self._sessions.keys()): + await self.stop_group(gid) + + async def _ensure_group_relay( + self, + group: dict[str, Any], + *, + source: dict[str, str] | None = None, + cfg: dict[str, Any] | None = None, + force: bool = False, + respect_schedule: bool | None = None, + ) -> dict[str, Any]: + cfg = cfg or db.get_settings_map() + gid = str(group.get("id") or "") + if respect_schedule is None: + respect_schedule = bool(cfg.get("youtube_relay_respect_schedule", True)) + if force: + respect_schedule = False + + src = source or pick_source_for_group(group, respect_schedule=respect_schedule) + if not src: + # Distinguish schedule block vs empty featured for diagnostics. + any_src = pick_source_for_group(group, respect_schedule=False) + if any_src and respect_schedule: + err = "当前不在分配时段,自动推流已跳过(手动「开始」可强制推流)" + else: + err = "直播地址列表为空或没有可用抖音源" + youtube_relay_db.upsert_relay_state( + gid, + status="idle", + error=err, + recent_log=[f"[relay] skip: {err}"], + ) + if force: + return {"ok": False, "error": err} + # Auto path: stop if running. + if gid in self._sessions and gid not in self._manual_hold: + await self.stop_group(gid) + return {"ok": False, "error": err} + + existing = self._sessions.get(gid) + if existing and existing.stats.running and not force: + if existing.source_url == src.get("source_url"): + return {"ok": True, "group_id": gid, "reused": True} + await self._halt_session(gid, reason="source_switch") + elif existing and force: + await self._halt_session(gid, reason="restart") + + if force: + self._manual_hold.add(gid) + + stream_key = str(group.get("stream_key") or "").strip() + if not stream_key: + raw = yt_assign_db.get_group(gid) + stream_key = str((raw or {}).get("stream_key") or "").strip() + if not stream_key: + err = "缺少 stream key" + youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=[f"[relay] {err}"]) + return {"ok": False, "error": err} + + boot_log = [ + f"[relay] resolve {src.get('source_url') or ''}", + f"[relay] room={src.get('room_id') or '-'} anchor={src.get('anchor_name') or '-'}", + ] + youtube_relay_db.upsert_relay_state( + gid, + status="starting", + source_url=src.get("source_url") or "", + source_room_id=src.get("room_id") or "", + anchor_name=src.get("anchor_name") or "", + error="", + recent_log=boot_log, + ) + + cookie = str(cfg.get("douyin_cookie") or "") + cands = await resolve_stream_candidates( + source_url=src["source_url"], + cookie=cookie, + prefer_fresh=True, + ) + if not cands: + err = "无法解析抖音直播流(房间未开播或 Cookie 失效)" + boot_log.append(f"[relay] ERROR {err}") + youtube_relay_db.upsert_relay_state( + gid, + status="error", + error=err, + source_url=src.get("source_url") or "", + source_room_id=src.get("room_id") or "", + anchor_name=src.get("anchor_name") or "", + recent_log=boot_log, + ) + return {"ok": False, "error": err} + + try: + rtmp = build_youtube_rtmp_url( + stream_key, + use_rtmps=bool(cfg.get("youtube_relay_use_rtmps", True)), + ) + except ValueError as exc: + err = str(exc) + boot_log.append(f"[relay] ERROR {err}") + youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=boot_log) + return {"ok": False, "error": err} + + now = time.time() + boot_log.append(f"[relay] input {cands[0][:160]}") + boot_log.append(f"[relay] output {rtmp.split('/')[-1][:8]}… via {'rtmps' if 'rtmps' in rtmp else 'rtmp'}") + boot_log.append("[relay] starting ffmpeg…") + + def _on_stats(st: RelayStats) -> None: + youtube_relay_db.upsert_relay_state( + gid, + status="pushing", + speed=float(st.speed), + frame=int(st.frame), + ffmpeg_pid=int(st.pid), + recent_log=st.recent_log, + ) + + old = self._sessions.pop(gid, None) + if old: + await asyncio.to_thread(old.stop) + await asyncio.to_thread(relay_sessions.end_session, gid, reason="restart") + + sess = RelayPushSession( + group_id=gid, + input_url=cands[0], + youtube_rtmp=rtmp, + anchor_name=src.get("anchor_name") or "", + source_url=src.get("source_url") or "", + room_id=src.get("room_id") or "", + bitrate_kbps=int(cfg.get("youtube_relay_bitrate") or 4000), + on_stats=_on_stats, + ) + # Seed in-memory log so UI sees lines before first ffmpeg frame + sess.stats.recent_log = list(boot_log) + self._sessions[gid] = sess + youtube_relay_db.upsert_relay_state( + gid, + status="starting", + source_url=src.get("source_url") or "", + source_room_id=src.get("room_id") or "", + anchor_name=src.get("anchor_name") or "", + stream_input=cands[0][:500], + started_at=now, + error="", + recent_log=boot_log, + ) + await asyncio.to_thread(sess.start) + # Give reader a brief moment to attach + await asyncio.sleep(0.4) + sk = _key_suffix(ginfo if (ginfo := yt_assign_db.get_group(gid)) else group) + await asyncio.to_thread( + relay_sessions.start_session, + gid, + channel_name=str((ginfo or group).get("name") or ""), + anchor_name=src.get("anchor_name") or "", + source_url=src.get("source_url") or "", + source_room_id=src.get("room_id") or "", + youtube_key_suffix=sk, + metadata={"stream_input": cands[0][:240]}, + ) + self.processed += 1 + return { + "ok": True, + "group_id": gid, + "source_url": src.get("source_url") or "", + "ffmpeg_pid": int(sess.stats.pid or 0), + "manual_hold": gid in self._manual_hold, + } + + async def _tick_stats(self) -> None: + now = time.time() + for gid, sess in list(self._sessions.items()): + if sess.stats.running: + st = youtube_relay_db.get_relay_state(gid) or {} + started = float(st.get("started_at") or now) + youtube_relay_db.upsert_relay_state( + gid, + status="pushing", + speed=float(sess.stats.speed), + frame=int(sess.stats.frame), + ffmpeg_pid=int(sess.stats.pid), + push_seconds=max(0.0, now - started), + recent_log=sess.stats.recent_log, + ) + elif gid in self._sessions: + st = youtube_relay_db.get_relay_state(gid) or {} + if str(st.get("status") or "") == "pushing": + youtube_relay_db.upsert_relay_state( + gid, + status="reconnecting", + error=(sess.stats.last_line or "推流中断")[:500], + recent_log=sess.stats.recent_log, + ) + + +youtube_relay_pipeline = YoutubeRelayPipeline() diff --git a/backend/app/youtube_relay_sessions.py b/backend/app/youtube_relay_sessions.py new file mode 100644 index 0000000..147c715 --- /dev/null +++ b/backend/app/youtube_relay_sessions.py @@ -0,0 +1,330 @@ +# -*- coding: utf-8 -*- +"""YouTube relay session history — cloud pipeline (group_id as process key).""" +from __future__ import annotations + +import json +import sqlite3 +import time +import uuid +from datetime import datetime +from typing import Any + +from .db import _connect, _lock, _row_to_dict + +_ACTIVE: dict[str, int] = {} + + +def ensure_yt_relay_sessions(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS yt_relay_sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_uuid TEXT NOT NULL UNIQUE, + group_id TEXT NOT NULL DEFAULT '', + channel_name TEXT NOT NULL DEFAULT '', + anchor_name TEXT NOT NULL DEFAULT '', + source_url TEXT NOT NULL DEFAULT '', + source_room_id TEXT NOT NULL DEFAULT '', + stream_title TEXT NOT NULL DEFAULT '', + youtube_key_suffix TEXT NOT NULL DEFAULT '', + started_at REAL NOT NULL, + ended_at REAL, + duration_seconds REAL NOT NULL DEFAULT 0, + push_date TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'active', + end_reason TEXT NOT NULL DEFAULT '', + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at REAL NOT NULL, + updated_at REAL NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_group ON yt_relay_sessions(group_id, started_at DESC)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_date ON yt_relay_sessions(push_date DESC, started_at DESC)" + ) + + +def _push_date(ts: float) -> str: + try: + return datetime.fromtimestamp(ts).strftime("%Y-%m-%d") + except (OSError, ValueError, OverflowError): + return "" + + +def _row_session(row: dict[str, Any]) -> dict[str, Any]: + out = dict(row) + meta = out.pop("metadata_json", "{}") + try: + out["metadata"] = json.loads(meta) if meta else {} + except json.JSONDecodeError: + out["metadata"] = {} + started = float(out.get("started_at") or 0) + ended = out.get("ended_at") + stored = float(out.get("duration_seconds") or 0) + if ended: + out["duration_seconds"] = int(max(0, float(ended) - started)) if started else int(stored) + elif stored > 0: + out["duration_seconds"] = int(stored) + elif started > 0: + out["duration_seconds"] = int(max(0, time.time() - started)) + else: + out["duration_seconds"] = 0 + out["process"] = out.get("group_id") or "" + return out + + +def start_session( + group_id: str, + *, + channel_name: str = "", + anchor_name: str = "", + source_url: str = "", + source_room_id: str = "", + youtube_key_suffix: str = "", + metadata: dict[str, Any] | None = None, +) -> dict[str, Any]: + gid = str(group_id or "").strip() + now = time.time() + with _lock: + conn = _connect() + try: + ensure_yt_relay_sessions(conn) + open_row = conn.execute( + "SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1", + (gid,), + ).fetchone() + if open_row: + sid = int(open_row[0]) + _ACTIVE[gid] = sid + row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone() + return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid}) + for other_gid, sid in list(_ACTIVE.items()): + if other_gid == gid: + continue + open_others = conn.execute( + "SELECT id, group_id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL", + (gid,), + ).fetchall() + for r in open_others: + _close(conn, int(r[0]), ended_at=now, reason="source_switch") + session_uuid = str(uuid.uuid4()) + conn.execute( + """ + INSERT INTO yt_relay_sessions( + session_uuid, group_id, channel_name, anchor_name, source_url, source_room_id, + stream_title, youtube_key_suffix, started_at, duration_seconds, push_date, + status, end_reason, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, '', ?, ?, 0, ?, 'active', '', ?, ?, ?) + """, + ( + session_uuid, + gid, + channel_name[:200], + anchor_name[:200], + source_url[:500], + source_room_id[:64], + youtube_key_suffix[:32], + now, + _push_date(now), + json.dumps(metadata or {}, ensure_ascii=False), + now, + now, + ), + ) + sid = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0]) + conn.commit() + _ACTIVE[gid] = sid + row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone() + return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid}) + finally: + conn.close() + + +def end_session(group_id: str, *, reason: str = "stopped", ended_at: float | None = None) -> dict[str, Any] | None: + gid = str(group_id or "").strip() + with _lock: + conn = _connect() + try: + ensure_yt_relay_sessions(conn) + row = conn.execute( + "SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1", + (gid,), + ).fetchone() + if not row: + _ACTIVE.pop(gid, None) + return None + sid = int(row[0]) + session = _close(conn, sid, ended_at=ended_at, reason=reason) + conn.commit() + _ACTIVE.pop(gid, None) + return session + finally: + conn.close() + + +def _close( + conn: sqlite3.Connection, + session_id: int, + *, + ended_at: float | None = None, + reason: str = "", +) -> dict[str, Any]: + now = float(ended_at or time.time()) + row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone() + if not row: + return {"id": session_id} + data = _row_to_dict(row) or {} + started = float(data.get("started_at") or now) + duration = max(0.0, now - started) + conn.execute( + """ + UPDATE yt_relay_sessions SET + ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = ?, updated_at = ? + WHERE id = ? + """, + (now, duration, str(reason or "")[:200], now, session_id), + ) + updated = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone() + return _row_session(_row_to_dict(updated) or data) + + +def list_sessions( + *, + group_id: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + limit: int = 50, + offset: int = 0, +) -> dict[str, Any]: + clauses: list[str] = [] + params: list[Any] = [] + if group_id.strip(): + clauses.append("group_id = ?") + params.append(group_id.strip()) + if status == "active": + clauses.append("ended_at IS NULL") + elif status == "ended": + clauses.append("ended_at IS NOT NULL") + if date_from.strip(): + clauses.append("push_date >= ?") + params.append(date_from.strip()) + if date_to.strip(): + clauses.append("push_date <= ?") + params.append(date_to.strip()) + if q.strip(): + like = f"%{q.strip()}%" + clauses.append( + "(anchor_name LIKE ? OR source_url LIKE ? OR source_room_id LIKE ? OR channel_name LIKE ?)" + ) + params.extend([like, like, like, like]) + where = ("WHERE " + " AND ".join(clauses)) if clauses else "" + lim = max(1, min(int(limit), 200)) + off = max(0, int(offset)) + with _lock: + conn = _connect() + try: + ensure_yt_relay_sessions(conn) + rows = conn.execute( + f"SELECT * FROM yt_relay_sessions {where} ORDER BY started_at DESC LIMIT ? OFFSET ?", + (*params, lim, off), + ).fetchall() + total = conn.execute(f"SELECT COUNT(*) FROM yt_relay_sessions {where}", params).fetchone()[0] + return { + "sessions": [_row_session(_row_to_dict(r) or {}) for r in rows], + "total": int(total or 0), + "limit": lim, + "offset": off, + } + finally: + conn.close() + + +def summarize_sessions( + *, + group_id: str = "", + q: str = "", + date_from: str = "", + date_to: str = "", + status: str = "", + top_anchors: int = 20, +) -> dict[str, Any]: + data = list_sessions(group_id=group_id, q=q, date_from=date_from, date_to=date_to, status=status, limit=5000, offset=0) + sessions = data.get("sessions") or [] + now = time.time() + by_anchor: dict[str, dict[str, Any]] = {} + by_date: dict[str, dict[str, Any]] = {} + by_hour = [0] * 24 + total_duration = 0.0 + active_count = 0 + duration_values: list[float] = [] + + for s in sessions: + dur = float(s.get("duration_seconds") or 0) + if not s.get("ended_at") and s.get("started_at"): + dur = max(dur, now - float(s["started_at"])) + active_count += 1 + total_duration += dur + duration_values.append(dur) + anchor = str(s.get("anchor_name") or "未知").strip() or "未知" + ac = by_anchor.setdefault(anchor, {"anchor_name": anchor, "sessions": 0, "duration_seconds": 0.0}) + ac["sessions"] += 1 + ac["duration_seconds"] += dur + pd = str(s.get("push_date") or "") + if pd: + d = by_date.setdefault(pd, {"date": pd, "sessions": 0, "duration_seconds": 0.0, "anchors": set()}) + d["sessions"] += 1 + d["duration_seconds"] += dur + d["anchors"].add(anchor) + started = float(s.get("started_at") or 0) + if started > 0: + try: + by_hour[datetime.fromtimestamp(started).hour] += 1 + except (OSError, ValueError, OverflowError): + pass + + top = sorted(by_anchor.values(), key=lambda x: (-x["sessions"], -x["duration_seconds"]))[: max(1, top_anchors)] + for t in top: + t["hours_total"] = round(t["duration_seconds"] / 3600, 2) + + dates_sorted = sorted(by_date.values(), key=lambda x: x["date"]) + by_date_out = [ + { + "date": d["date"], + "sessions": d["sessions"], + "hours": round(d["duration_seconds"] / 3600, 2), + "unique_anchors": len(d["anchors"]), + } + for d in dates_sorted[-60:] + ] + + avg_d = total_duration / len(sessions) if sessions else 0 + return { + "overview": { + "sessions": len(sessions), + "unique_anchors": len(by_anchor), + "active_sessions": active_count, + "total_hours": round(total_duration / 3600, 2), + "avg_duration_seconds": int(avg_d), + "date_from": dates_sorted[0]["date"] if dates_sorted else "", + "date_to": dates_sorted[-1]["date"] if dates_sorted else "", + }, + "top_anchors": top, + "by_hour": {"starts": by_hour, "labels": [f"{h:02d}:00" for h in range(24)]}, + "by_date": by_date_out, + } + + +def get_session(session_id: int) -> dict[str, Any] | None: + with _lock: + conn = _connect() + try: + ensure_yt_relay_sessions(conn) + row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (int(session_id),)).fetchone() + return _row_session(_row_to_dict(row) or {}) if row else None + finally: + conn.close() diff --git a/backend/app/youtube_relay_status.py b/backend/app/youtube_relay_status.py new file mode 100644 index 0000000..defa6f9 --- /dev/null +++ b/backend/app/youtube_relay_status.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +"""Relay business/process status — adapted from sh2 process_runtime_status (cloud, no PM2).""" +from __future__ import annotations + +import re +import time +from typing import Any + +_FFMPEG_PROGRESS_RE = re.compile( + r"frame=\s*(?P\d+).*?" + r"(?:fps=\s*(?P[\d.]+)\s*)?" + r"(?:time=(?P\d+):(?P\d+):(?P\d+(?:\.\d+)?).*?)?" + r"bitrate=\s*(?P[\d.]+\s*kbits/s)?.*?" + r"speed=\s*(?P\d+(?:\.\d+)?)x", + re.IGNORECASE, +) + +_ERROR_HINTS = ( + "error", + "failed", + "403 forbidden", + "404 not found", + "unauthorized", + "forbidden", + "io error", + "error opening output", +) + + +def _norm_log(text: str) -> str: + return (text or "").replace("\r\n", "\n").replace("\r", "\n") + + +def _has_any(text: str, patterns: tuple[str, ...]) -> bool: + low = text.lower() + return any(p in low for p in patterns) + + +def _looks_like_youtube_key_rejected(tail: str) -> bool: + if not _has_any(tail, ("rtmps://a.rtmps.youtube.com/live2/", "rtmp://a.rtmp.youtube.com/live2/")): + return False + if not _has_any(tail, ("error opening output", "error opening output file")): + return False + return _has_any(tail, ("io error", "401", "403", "unauthorized", "forbidden", "input/output error")) + + +def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]: + samples: list[dict[str, float | int]] = [] + for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""): + try: + frame = int(match.group("frame")) + speed = float(match.group("speed")) + media_time = 0.0 + if match.group("h") is not None: + media_time = ( + int(match.group("h")) * 3600 + + int(match.group("m")) * 60 + + float(match.group("s") or 0) + ) + row: dict[str, float | int] = {"frame": frame, "time": media_time, "speed": speed} + if match.group("fps"): + row["fps"] = float(match.group("fps")) + br = match.group("bitrate") or "" + m = re.search(r"([\d.]+)", br) + if m: + row["bitrate"] = float(m.group(1)) + samples.append(row) + except (TypeError, ValueError): + continue + return samples[-8:] + + +def _progress_stalled(samples: list[dict[str, float | int]]) -> bool: + if len(samples) < 3: + return False + tail = samples[-3:] + frames = {int(r["frame"]) for r in tail} + times = {round(float(r["time"]), 2) for r in tail} + return len(frames) == 1 and len(times) == 1 + + +def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -> bool: + if len(samples) < 4: + return False + tail = samples[-4:] + if not all(float(r["speed"]) < threshold for r in tail): + return False + return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"]) + + +def split_relay_logs(lines: list[str] | None) -> tuple[str, str]: + out: list[str] = [] + err: list[str] = [] + for line in lines or []: + low = line.lower() + if any(h in low for h in _ERROR_HINTS): + err.append(line) + else: + out.append(line) + return "\n".join(out), "\n".join(err) + + +def summarize_relay_group( + *, + group: dict[str, Any], + st: dict[str, Any], + session_running: bool, + pipeline_enabled: bool, + log_age_seconds: float | None = None, +) -> dict[str, Any]: + """Build process_monitor-style row for one assign group.""" + gid = str(group.get("id") or st.get("group_id") or "") + has_key = bool(group.get("has_stream_key") or str(group.get("stream_key") or "").strip()) + enabled = bool(group.get("enabled", True)) + featured = group.get("featured") or [] + featured_urls = [str(x.get("url") or "").strip() for x in featured if str(x.get("url") or "").strip()] + douyin_count = sum(1 for u in featured_urls if "douyin" in u.lower()) + + recent_log_lines = st.get("recent_log") if isinstance(st.get("recent_log"), list) else [] + if not recent_log_lines and isinstance(st.get("recent_log"), str): + recent_log_lines = [st["recent_log"]] + recent_log, recent_error = split_relay_logs(recent_log_lines) + tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower() + + raw_status = str(st.get("status") or "idle").lower() + if session_running: + process_status = "online" + elif not enabled: + process_status = "stopped" + elif has_key and pipeline_enabled: + process_status = "configured" if raw_status in {"idle", "stopped"} else raw_status + elif has_key: + process_status = "configured" + else: + process_status = "stopped" + + pids: list[int] = [] + pid = int(st.get("ffmpeg_pid") or 0) + if pid > 0: + pids = [pid] + + progress_samples = _ffmpeg_progress_samples(tail) + latest = progress_samples[-1] if progress_samples else {} + progress_stalled = _progress_stalled(progress_samples) + speed_low = _speed_low(progress_samples) + has_progress = "frame=" in tail and "speed=" in tail + log_recent = log_age_seconds is None or log_age_seconds <= 20 + has_worker = bool(pids) or session_running + + business_status = "inactive" + business_note = "未运行" + if not has_key: + business_status = "misconfigured" + business_note = "缺少 YouTube 直播 KEY" + elif not enabled: + business_status = "inactive" + business_note = "频道已停用" + elif not featured_urls: + business_status = "misconfigured" + business_note = "直播地址列表(精选)为空" + elif _looks_like_youtube_key_rejected(tail): + business_status = "youtube_key_rejected" + business_note = "YouTube 拒绝了 RTMPS 推流,请检查直播 KEY 或网络" + elif raw_status == "error" and st.get("error"): + business_status = "error" + business_note = str(st.get("error") or "")[:240] + elif session_running and has_progress and log_recent and progress_stalled: + business_status = "source_stalled" + business_note = "FFmpeg 在运行但帧/时间进度停滞" + elif session_running and has_progress and log_recent and speed_low: + business_status = "relay_slow" + business_note = "推流速度低于实时" + elif session_running and has_progress and log_recent: + business_status = "streaming" + business_note = "正在推流到 YouTube" + elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://")): + business_status = "relay_starting" + business_note = "FFmpeg 已启动,等待进度上报" + elif pipeline_enabled and enabled and has_key and not session_running: + if raw_status == "reconnecting": + business_status = "relay_starting" + business_note = "推流中断,正在重连" + elif log_age_seconds is not None and log_age_seconds > 180 and has_worker: + business_status = "stale" + business_note = "进程在线但日志心跳过期" + else: + live_ids_hint = bool(st.get("source_room_id")) + if live_ids_hint and not session_running: + business_status = "waiting_source" + business_note = "等待可用抖音源或 Worker 调度" + else: + business_status = "monitoring" + business_note = "Worker 运行中,等待推流" + elif has_key and featured_urls and pipeline_enabled: + business_status = "ready" + business_note = "已配置,等待自动推流" + elif process_status == "configured": + business_status = "ready" + business_note = "已配置(未推流)" + + is_pushing = business_status in {"streaming", "relay_slow"} or ( + business_status == "source_stalled" and has_progress and has_worker + ) + + speed = latest.get("speed") + if speed is None and st.get("speed"): + try: + speed = float(st.get("speed")) + except (TypeError, ValueError): + speed = None + + frame = latest.get("frame") + if frame is None and st.get("frame"): + try: + frame = int(st.get("frame")) + except (TypeError, ValueError): + frame = None + + return { + "group_id": gid, + "label": group.get("name") or gid, + "process_status": process_status, + "business_status": business_status, + "business_note": business_note, + "is_pushing": is_pushing, + "ffmpeg_active": has_worker, + "ffmpeg_pids": pids, + "ffmpeg_pid": pids[0] if pids else 0, + "ffmpeg_speed": speed, + "ffmpeg_frame": frame, + "ffmpeg_fps": latest.get("fps"), + "ffmpeg_bitrate_kbps": latest.get("bitrate"), + "ffmpeg_time_seconds": latest.get("time"), + "ffmpeg_progress_stalled": progress_stalled, + "ffmpeg_speed_low": speed_low, + "log_age_seconds": log_age_seconds, + "recent_log": recent_log, + "recent_error": recent_error, + "source_title": st.get("anchor_name") or "", + "source_room_id": st.get("source_room_id") or st.get("room_id") or "", + "source_url": st.get("source_url") or "", + "source_display": st.get("anchor_name") or "", + "url_count": len(featured_urls), + "douyin_count": douyin_count, + "has_stream_key": has_key, + "stream_key_suffix": _key_suffix(group), + "push_seconds": float(st.get("push_seconds") or 0), + "started_at": float(st.get("started_at") or 0), + "updated_at": float(st.get("updated_at") or 0), + } + + +def _key_suffix(group: dict[str, Any]) -> str: + sk = str(group.get("stream_key") or "").strip() + if len(sk) >= 4: + return sk[-4:] + masked = str(group.get("stream_key_masked") or "") + if masked.startswith("***") and len(masked) > 3: + return masked[3:] + return "" + + +def log_age_seconds(st: dict[str, Any], now: float | None = None) -> float | None: + updated = float(st.get("updated_at") or 0) + if updated <= 0: + return None + return max(0.0, (now or time.time()) - updated) diff --git a/backend/app/yt_assign_db.py b/backend/app/yt_assign_db.py index 27e8b83..15d96cc 100644 --- a/backend/app/yt_assign_db.py +++ b/backend/app/yt_assign_db.py @@ -93,6 +93,25 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_assign_slot_group ON yt_assign_slot_urls(group_id, sort_order)" ) + gcols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_assign_groups)").fetchall()} + for col, ddl in [ + ("neko_instance_id", "INTEGER NOT NULL DEFAULT 0"), + ("neko_enabled", "INTEGER NOT NULL DEFAULT 0"), + ]: + if col not in gcols: + conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}") + orphans = conn.execute( + "SELECT id FROM yt_assign_groups WHERE COALESCE(neko_instance_id, 0) = 0 ORDER BY sort_order ASC, created_at ASC" + ).fetchall() + if orphans: + max_row = conn.execute("SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups").fetchone() + next_id = int(max_row["m"] if max_row else 0) + for row in orphans: + next_id += 1 + conn.execute( + "UPDATE yt_assign_groups SET neko_instance_id = ? WHERE id = ?", + (next_id, str(row["id"])), + ) def parse_pool_line(raw: str) -> dict[str, str]: @@ -227,6 +246,9 @@ def _beijing_hour_fraction(ts: float | None = None) -> float: def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None) -> dict[str, Any]: out = dict(row) out["enabled"] = bool(out.get("enabled")) + out["neko_enabled"] = bool(out.get("neko_enabled")) + neko_id = int(out.get("neko_instance_id") or 0) + out["neko_instance_id"] = neko_id sk = str(out.get("stream_key") or "") out["has_stream_key"] = bool(sk.strip()) out["stream_key_masked"] = ("***" + sk[-4:]) if len(sk) > 6 else ("***" if sk else "") @@ -236,6 +258,13 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li out["featured"] = featured if slots is not None: out["slots"] = slots + if neko_id > 0: + try: + from . import youtube_neko + + out["neko_studio_url"] = youtube_neko.public_studio_url(neko_id) + except Exception: + out["neko_studio_url"] = "" return out @@ -352,12 +381,17 @@ def create_group( ensure_yt_assign_tables(conn) max_ord = conn.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_groups").fetchone() sort_order = int(max_ord["m"] if max_ord else 0) + 1 + max_neko = conn.execute( + "SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups" + ).fetchone() + neko_instance_id = int(max_neko["m"] if max_neko else 0) + 1 conn.execute( """ INSERT INTO yt_assign_groups( id, name, channel_pk, youtube_channel_id, stream_key, note, - enabled, sort_order, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + enabled, sort_order, neko_instance_id, neko_enabled, + created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( gid, @@ -368,6 +402,8 @@ def create_group( str(note or "").strip()[:500], 1 if enabled else 0, sort_order, + neko_instance_id, + 0, now, now, ), @@ -375,7 +411,14 @@ def create_group( conn.commit() finally: conn.close() - return get_group(gid) or {"id": gid} + group = get_group(gid) or {"id": gid} + try: + from . import youtube_neko + + youtube_neko.sync_for_groups(list_groups(include_urls=False)) + except Exception: + pass + return group def update_group(group_id: str, **fields: Any) -> dict[str, Any]: @@ -389,6 +432,7 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]: "note", "enabled", "sort_order", + "neko_enabled", } patch: dict[str, Any] = {} for k, v in fields.items(): @@ -396,6 +440,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]: continue if k == "enabled": patch[k] = 1 if v else 0 + elif k == "neko_enabled": + patch[k] = 1 if v else 0 elif k == "sort_order": try: patch[k] = int(v) @@ -445,7 +491,15 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]: conn.commit() finally: conn.close() - return get_group(group_id) or {} + group = get_group(group_id) or {} + if "neko_enabled" in patch: + try: + from . import youtube_neko + + youtube_neko.sync_for_groups(list_groups(include_urls=False)) + except Exception: + pass + return group def delete_group(group_id: str) -> dict[str, Any]: @@ -458,9 +512,16 @@ def delete_group(group_id: str) -> dict[str, Any]: n_pool = conn.execute("DELETE FROM yt_assign_pool_urls WHERE group_id = ?", (group_id,)).rowcount n = conn.execute("DELETE FROM yt_assign_groups WHERE id = ?", (group_id,)).rowcount conn.commit() - return {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)} + result = {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)} finally: conn.close() + try: + from . import youtube_neko + + youtube_neko.sync_for_groups(list_groups(include_urls=False)) + except Exception: + pass + return result def add_pool_urls( diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 4094c74..74ff01b 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -21,7 +21,7 @@ import { EnableSwitch } from "@/components/EnableSwitch"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; -import { GoogleOauthSetupWizard } from "@/components/GoogleOauthSetupWizard"; +import { GoogleOauthSetupWizard, defaultShortsRedirectUri } from "@/components/GoogleOauthSetupWizard"; import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge"; import { ShortsJobDetailModal } from "@/components/ShortsJobDetailModal"; import { @@ -736,7 +736,7 @@ export default function ShortsPage() { {showWizard || !status?.oauth_configured ? ( void load()} /> diff --git a/frontend/src/app/youtube-relay-log/page.tsx b/frontend/src/app/youtube-relay-log/page.tsx new file mode 100644 index 0000000..599840d --- /dev/null +++ b/frontend/src/app/youtube-relay-log/page.tsx @@ -0,0 +1,436 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; +import { fetchJson, fmtDuration, fmtTs } from "@/lib/api"; +import { useAutoRefresh } from "@/lib/realtime"; + +type RelaySession = { + id: number; + session_uuid?: string; + group_id?: string; + process?: string; + channel_name?: string; + anchor_name?: string; + source_url?: string; + source_room_id?: string; + stream_title?: string; + youtube_key_suffix?: string; + started_at?: number; + ended_at?: number | null; + duration_seconds?: number; + push_date?: string; + status?: string; + end_reason?: string; + metadata?: Record; +}; + +type AssignGroup = { id: string; name?: string }; + +function douyinUrl(session: RelaySession): string { + if (session.source_url?.includes("live.douyin.com")) return session.source_url; + if (session.source_room_id) return `https://live.douyin.com/${session.source_room_id}`; + return session.source_url || ""; +} + +export default function YoutubeRelayLogPage() { + const [groupId, setGroupId] = useState(""); + const [q, setQ] = useState(""); + const [dateFrom, setDateFrom] = useState(""); + const [dateTo, setDateTo] = useState(""); + const [status, setStatus] = useState(""); + const [sessions, setSessions] = useState([]); + const [stats, setStats] = useState(null); + const [total, setTotal] = useState(0); + const [offset, setOffset] = useState(0); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [selected, setSelected] = useState(null); + const [tab, setTab] = useState<"charts" | "list">("charts"); + const [groups, setGroups] = useState([]); + const limit = 50; + + useEffect(() => { + if (typeof window === "undefined") return; + const p = new URLSearchParams(window.location.search); + const gid = p.get("group_id") || p.get("process") || ""; + if (gid) setGroupId(gid); + const sq = p.get("q"); + if (sq) setQ(sq); + const sf = p.get("date_from"); + if (sf) setDateFrom(sf); + const st = p.get("date_to"); + if (st) setDateTo(st); + const ss = p.get("status"); + if (ss) setStatus(ss); + const sid = p.get("session"); + if (sid) { + void fetchJson(`/api/youtube/relay/sessions/${sid}`) + .then((d) => setSelected(d as RelaySession)) + .catch(() => undefined); + } + }, []); + + useEffect(() => { + void fetchJson("/api/youtube/assign/groups") + .then((d) => setGroups((d.groups || d) as AssignGroup[])) + .catch(() => undefined); + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (groupId.trim()) params.set("group_id", groupId.trim()); + if (q.trim()) params.set("q", q.trim()); + if (dateFrom) params.set("date_from", dateFrom); + if (dateTo) params.set("date_to", dateTo); + if (status) params.set("status", status); + return params; + }, [groupId, q, dateFrom, dateTo, status]); + + const queryString = useMemo(() => { + const params = new URLSearchParams(filterParams); + params.set("limit", String(limit)); + params.set("offset", String(offset)); + return params.toString(); + }, [filterParams, offset]); + + const statsQuery = useMemo(() => { + const params = new URLSearchParams(filterParams); + params.set("top_anchors", "25"); + return params.toString(); + }, [filterParams]); + + const load = useCallback(async () => { + setLoading(true); + setError(""); + try { + const [listData, statsData] = await Promise.all([ + fetchJson(`/api/youtube/relay/sessions?${queryString}`), + fetchJson(`/api/youtube/relay/sessions/stats?${statsQuery}`), + ]); + setSessions(listData.sessions || []); + setTotal(Number(listData.total) || 0); + setStats(statsData); + } catch (e) { + setError((e as Error).message); + } finally { + setLoading(false); + } + }, [queryString, statsQuery]); + + useAutoRefresh(load, { intervalMs: 20000 }); + + const pageCount = Math.max(1, Math.ceil(total / limit)); + const pageIndex = Math.floor(offset / limit) + 1; + + return ( + +
+
+

📋 YouTube 推流日志

+

+ 云管道 FFmpeg 推流历史:每位主播的开播频率、时段规律与累计时长;列表保留逐场明细,便于追溯。 +

+
+
+ + ← 分配 / 转播 + + +
+
+ +
+ + + + + +
+ + {error ? ( +
+ {error} +
+ ) : null} + +
+ + +
+ + {tab === "charts" ? : null} + + {tab === "list" ? ( + <> +
+
+ + + + + + + + + + + + + + + {sessions.map((session) => { + const url = douyinUrl(session); + return ( + setSelected(session)} + > + + + + + + + + + + ); + })} + {!loading && sessions.length === 0 ? ( + + + + ) : null} + +
主播昵称直播间 URL推流开始推流结束总时长推流日期YT 密钥频道
{session.anchor_name || "—"} + {url ? ( + e.stopPropagation()} + > + {url.replace(/^https?:\/\//, "")} + + ) : ( + "—" + )} + {fmtTs(session.started_at)} + {session.ended_at ? fmtTs(session.ended_at) : "进行中"} + + {fmtDuration(session.duration_seconds)} + {session.push_date || "—"} + {session.youtube_key_suffix ? `…${session.youtube_key_suffix}` : "—"} + + {session.channel_name || session.process || "—"} +
+ 暂无推流记录。在分配页开启自动推流并开始转播后,会话将自动写入此处。 +
+
+
+ +
+ + 共 {total} 条 · 第 {pageIndex}/{pageCount} + +
+ + +
+
+ + ) : null} + + {selected ? ( +
setSelected(null)} + > +
e.stopPropagation()} + > +
+
+

{selected.anchor_name || "推流详情"}

+

{selected.stream_title || selected.channel_name || "—"}

+
+ +
+
+
+
直播间 URL
+
+ {douyinUrl(selected) ? ( + + {douyinUrl(selected)} + + ) : ( + "—" + )} +
+
+
+
房间号
+
{selected.source_room_id || "—"}
+
+
+
推流开始
+
{fmtTs(selected.started_at)}
+
+
+
推流结束
+
{selected.ended_at ? fmtTs(selected.ended_at) : "进行中"}
+
+
+
总时长
+
{fmtDuration(selected.duration_seconds)}
+
+
+
推流日期
+
{selected.push_date || "—"}
+
+
+
频道 / 进程
+
+ {selected.channel_name ? `${selected.channel_name} · ` : ""} + {selected.group_id || selected.process || "—"} +
+
+
+
结束原因
+
{selected.end_reason || "—"}
+
+
+
YouTube 推流密钥(后几位)
+
{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}
+
+
+
+
+ ) : null} +
+ ); +} diff --git a/frontend/src/components/GoogleOauthSetupWizard.tsx b/frontend/src/components/GoogleOauthSetupWizard.tsx index c868e3d..3346698 100644 --- a/frontend/src/components/GoogleOauthSetupWizard.tsx +++ b/frontend/src/components/GoogleOauthSetupWizard.tsx @@ -6,7 +6,15 @@ import { Check, Copy, ExternalLink } from "lucide-react"; import { fetchJson } from "@/lib/api"; const DEFAULT_PROJECT = "live-473104"; -const DEFAULT_REDIRECT = "https://dylive.nomadro.com/api/shorts/oauth/callback"; + +function defaultShortsRedirectUri(): string { + if (typeof window !== "undefined" && window.location?.origin) { + return `${window.location.origin}/api/shorts/oauth/callback`; + } + return ""; +} + +export { defaultShortsRedirectUri }; function gcpLinks(projectId: string) { const p = encodeURIComponent(projectId || DEFAULT_PROJECT); @@ -31,7 +39,7 @@ export function GoogleOauthSetupWizard({ initialProjectId = DEFAULT_PROJECT, initialClientId = "", initialClientSecret = "", - redirectUri = DEFAULT_REDIRECT, + redirectUri = defaultShortsRedirectUri(), configured = false, onSaved, }: Props) { diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index 4e02ef6..598e41a 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -17,6 +17,10 @@ import { } from "lucide-react"; import { DouyinLiveBadge } from "@/components/DouyinLiveBadge"; +import { YtRelayLiveLogCard } from "@/components/YtRelayLiveLogCard"; +import { YtRelayProStatusPanel } from "@/components/YtRelayProStatusPanel"; +import { businessStatusLabel, isLivePushingRow, type RelayMonitorRow } from "@/lib/ytRelayStatus"; +import { EnableSwitch } from "@/components/EnableSwitch"; import { useConfirm } from "@/components/ConfirmDialog"; import { ImageLightbox } from "@/components/ImageLightbox"; import { useToast } from "@/components/Toast"; @@ -81,6 +85,9 @@ type AssignGroup = { has_stream_key?: boolean; note?: string; enabled?: boolean; + neko_instance_id?: number; + neko_enabled?: boolean; + neko_studio_url?: string; pool?: PoolUrl[]; featured?: FeaturedUrl[]; slots?: SlotUrl[]; @@ -104,6 +111,33 @@ type RotationSchedule = { channels?: ScheduleChannel[]; }; +type RelayGroup = { + group_id: string; + status?: string; + anchor_name?: string; + source_url?: string; + room_id?: string; + speed?: number; + frame?: number; + ffmpeg_pid?: number; + error?: string; + started_at?: number; + push_seconds?: number; + recent_log?: string[]; + has_stream_key?: boolean; + enabled?: boolean; +}; + +type RelayStatus = { + running?: boolean; + enabled?: boolean; + pushing_count?: number; + douyin_live_count?: number; + last_error?: string; + groups?: RelayGroup[]; + entries?: RelayMonitorRow[]; +}; + function formatExportLine(url: string, title?: string): string { const u = String(url || "").trim(); const t = String(title || "").trim(); @@ -240,6 +274,9 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>( null ); + const [relayStatus, setRelayStatus] = useState(null); + const [relayBusy, setRelayBusy] = useState(false); + const [relayKickId, setRelayKickId] = useState(""); const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]); const featuredIds = useMemo( @@ -276,6 +313,24 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { return m; }, [channels]); + const relayByGroupId = useMemo(() => { + const m: Record = {}; + for (const g of relayStatus?.groups || []) { + if (g.group_id) m[g.group_id] = g; + } + return m; + }, [relayStatus?.groups]); + + const relayEntries = useMemo( + () => (relayStatus?.entries || relayStatus?.groups || []) as RelayMonitorRow[], + [relayStatus?.entries, relayStatus?.groups] + ); + + const selectedMonitor = useMemo( + () => relayEntries.find((e) => e.group_id === groupId), + [relayEntries, groupId] + ); + function profileFor(pk: string): YtProfileSnippet | undefined { if (profiles[pk]) return profiles[pk]; const ch = channelById[pk]; @@ -300,6 +355,15 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { } }, []); + const loadRelay = useCallback(async () => { + try { + const st = await fetchJson("/api/youtube/relay/status"); + setRelayStatus(st as RelayStatus); + } catch { + // relay API may fail when logged out; keep last state + } + }, []); + const loadGroups = useCallback(async () => { setBusy(true); try { @@ -359,7 +423,49 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { useEffect(() => { void loadGroups(); void loadAllProfiles(); - }, [loadGroups, loadAllProfiles]); + void loadRelay(); + const t = setInterval(() => void loadRelay(), 3500); + return () => clearInterval(t); + }, [loadGroups, loadAllProfiles, loadRelay]); + + async function toggleRelayPipeline(on: boolean) { + if (!on) { + const ok = await confirm({ + title: "关闭自动推流?", + message: "关闭后将停止所有 FFmpeg 推流,不再向 YouTube Live 转播。", + confirmLabel: "关闭", + destructive: true, + }); + if (!ok) return; + } + setRelayBusy(true); + try { + await fetchJson(on ? "/api/youtube/relay/start" : "/api/youtube/relay/stop", { method: "POST" }); + toast.push(on ? "自动推流已开启" : "自动推流已关闭", "ok"); + await loadRelay(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setRelayBusy(false); + } + } + + async function kickRelayGroup(gid: string, action: "start" | "stop" | "restart") { + setRelayKickId(gid); + try { + const path = + action === "restart" + ? `/api/youtube/relay/groups/${gid}/restart` + : `/api/youtube/relay/groups/${gid}/${action}`; + await fetchJson(path, { method: "POST" }); + toast.push(action === "start" ? "已触发推流" : action === "stop" ? "已停止推流" : "已重新开始", "ok"); + await loadRelay(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setRelayKickId(""); + } + } useEffect(() => { if (!selected) { @@ -693,10 +799,18 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {

转播分配

- 频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。 + 频道 + 直播 KEY → 抖音 URL 池 → 直播地址列表(精选)。开启自动推流后 FFmpeg 仅转播精选列表到 YouTube Live。

-
+
+ void toggleRelayPipeline(v)} + />
+
+ {[ + { label: "抖音在播", value: relayStatus?.douyin_live_count ?? "—" }, + { label: "推流中", value: relayStatus?.pushing_count ?? 0 }, + { label: "Worker", value: relayStatus?.running ? "运行" : "停" }, + { label: "时段", value: schedule?.now_label || "—" }, + ].map((item) => ( +
+
{item.label}
+
{item.value}
+
+ ))} +
+ {relayStatus?.last_error ? ( +
{relayStatus.last_error}
+ ) : null} +