diff --git a/backend/app/db.py b/backend/app/db.py index 45255b6..2d1dbf7 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -349,6 +349,12 @@ def init_db() -> None: _x_clips_db.ensure_x_clips_tables(conn) _yt_long_db.ensure_yt_long_tables(conn) _yt_assign_db.ensure_yt_assign_tables(conn) + try: + from . import yt_studio_db as _yt_studio_db + + _yt_studio_db.ensure_yt_studio_tables(conn) + except Exception: + pass _ops_neko_db.ensure_ops_neko_tables(conn) _caption_pool.ensure_caption_pool_table(conn) _caption_pool.seed_caption_pool(conn) diff --git a/backend/app/host_profile.py b/backend/app/host_profile.py index 57393e7..cb6b373 100644 --- a/backend/app/host_profile.py +++ b/backend/app/host_profile.py @@ -43,14 +43,14 @@ def status() -> dict[str, Any]: "profiles": list(PROFILES), "effects": { "vps": [ - "egress / ShellCrash / 业务 SOCKS 全部关闭", - "全部 Neko 停止并关闭 neko_enabled", - "单路独占默认开启", + "egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)", + "本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)", + "单路独占默认开启(省内存;可配对物理机 ops-neko)", ], "physical": [ "业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)", "单路独占默认关闭(允许多 Neko 预热)", - "不自动拉起全部 Neko(由分配页按需开启)", + "不自动拉起全部 Neko(由分配页按需开启);ops-neko 优先 .cn / 腾讯云 ICE", ], }, "never_touches": [ @@ -130,7 +130,12 @@ def apply_profile(profile: str) -> dict[str, Any]: except Exception as exc: steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]} - steps["neko"] = _disable_all_neko() + # Do NOT wipe assign Neko — dylive hub needs per-group start/stop like physical + # (local /neko/N/ and/or paired ops-neko). Exclusive-live still pauses siblings at push time. + steps["neko"] = { + "ok": True, + "note": "vps: leave assign Neko as-is; enable/start/stop per group in assign UI", + } # Exclusive-live in-memory state is applied in apply_profile_async. db.update_settings_map( diff --git a/backend/app/models.py b/backend/app/models.py index dc7bb13..81d05d3 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -359,6 +359,8 @@ class YtAssignGroupCreate(BaseModel): stream_key: str = "" note: str = "" enabled: bool = True + # normal = 手动推流(精选); time_slot = 时间段排班推流 + category: str = "normal" class YtAssignGroupUpdate(BaseModel): @@ -370,6 +372,7 @@ class YtAssignGroupUpdate(BaseModel): enabled: Optional[bool] = None sort_order: Optional[int] = None neko_enabled: Optional[bool] = None + category: Optional[str] = None class YtAssignPoolAdd(BaseModel): diff --git a/backend/app/ops_neko.py b/backend/app/ops_neko.py index 8caf8b8..8c62ff8 100644 --- a/backend/app/ops_neko.py +++ b/backend/app/ops_neko.py @@ -1,11 +1,14 @@ # -*- coding: utf-8 -*- -"""Ops-tab Neko Docker fleet — isolated from youtube_neko (assign). +"""Ops-tab Neko Docker fleet — same runtime as assign youtube_neko. Containers: douyinweb-ops-neko-{slot} HTTP ports: 18200+(slot-1) (assign uses 9200+) WebRTC mux: 62300+(slot-1) (assign uses 52300+) Path for Caddy: /ops-neko/{slot}/ → host:1820x +Compose env/assets/proxy/Studio URL come from youtube_neko.compose_service_lines +so YouTube live tooling matches the assign page. Ports/names stay isolated. + Create always leaves containers stopped unless start() is called. """ from __future__ import annotations @@ -63,17 +66,22 @@ def _udp_range(slot: int) -> str: return f"{lo}-{hi}" -def _q(value: str) -> str: - return json.dumps(str(value), ensure_ascii=False) - - def _http_bind() -> str: - return str(getattr(settings, "neko_http_bind", "") or "127.0.0.1").strip() or "127.0.0.1" + """Same bind policy as assign youtube_neko (physical → 0.0.0.0 for WG edges).""" + from . import youtube_neko as yn + + return yn._http_bind() # noqa: SLF001 def _profile(slot: int) -> Path: p = _root() / "profiles" / str(int(slot)) p.mkdir(parents=True, exist_ok=True) + try: + import os + + os.chmod(p, 0o777) + except OSError: + pass return p @@ -81,6 +89,8 @@ def _instance_id_file(slot: int) -> Path: p = _root() / "instance_ids" p.mkdir(parents=True, exist_ok=True) f = p / f"{int(slot)}.txt" + # Same live-ops telemetry format as assign fleet (numeric id string when possible). + # Prefix ops- so Studio events from tab fleet don't collide with assign neko-N. f.write_text(f"ops-{int(slot)}\n", encoding="utf-8") return f @@ -96,91 +106,27 @@ def _compose_cmd(*args: str) -> list[str]: def _render_compose(max_slot: int) -> str: + """Mirror assign youtube_neko runtime (Studio / TM / live-ops / proxy / ICE).""" from . import youtube_neko as yn - image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0") - user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb") - admin_pass = str(getattr(settings, "neko_admin_pass", "") or "neko") - nat1to1 = yn._detect_public_ip() # noqa: SLF001 - shm = str(getattr(settings, "neko_shm_size", "") or "512mb") - screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15") - max_fps = str(getattr(settings, "neko_max_fps", "") or "15") - bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200") - icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0") - start_url = str( - getattr(settings, "neko_start_url", "") - or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/" - ) - assets = yn._asset_root() # noqa: SLF001 - managed = yn._managed_policies_enabled() # noqa: SLF001 - policy_dir = assets / ("policies" if managed else "no-managed-policies") - seed_dir = assets / "tampermonkey-seed" - live_ops_dir = assets / "live-ops-extension" - provisioning_dir = assets / "provisioning" - browser_launch = assets / "browser-launch.sh" - supervisor = assets / yn._supervisor_conf_name() # noqa: SLF001 - for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir): - if not required.exists(): - raise RuntimeError(f"Neko asset missing: {required}") - yn._ensure_browser_launch_exec() # noqa: SLF001 - proxy = yn._neko_browser_proxy_value() # noqa: SLF001 - - lines = ["# Generated by douyinWEB ops_neko — independent of assign fleet", "services:"] + lines = [ + "# Generated by douyinWEB ops_neko — same runtime as assign youtube_neko", + "services:", + ] n = max(1, int(max_slot)) for idx in range(1, n + 1): - http_port = _http_port(idx) - mux = _mux(idx) - udp = _udp_range(idx) - profile = _profile(idx) - id_file = _instance_id_file(idx) lines.extend( - [ - f" opsneko{idx}:", - f" image: {_q(image)}", - ' restart: "no"', - f" shm_size: {_q(shm)}", - " cap_add:", - " - SYS_ADMIN", - " security_opt:", - " - apparmor:unconfined", - " extra_hosts:", - ' - "host.docker.internal:host-gateway"', - f" container_name: {_container_name(idx)}", - " environment:", - ' TZ: "America/Chicago"', - ' DISPLAY: ":99.0"', - ' NEKO_SERVER_BIND: ":8080"', - ' NEKO_SERVER_PROXY: "true"', - ' NEKO_MEMBER_PROVIDER: "multiuser"', - f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}", - f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}", - f" NEKO_DESKTOP_SCREEN: {_q(screen)}", - f" NEKO_MAX_FPS: {_q(max_fps)}", - f" NEKO_VIDEO_BITRATE: {_q(bitrate)}", - f" NEKO_WEBRTC_ICELITE: {_q(icelite)}", - f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}", - f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}", - f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}", - f" NEKO_WEBRTC_EPR: {_q(udp)}", - f" NEKO_START_URL: {_q(start_url)}", - f" NEKO_BROWSER_PROXY: {_q(proxy)}", - f" NEKO_INSTANCE_ID: {_q(f'ops-{idx}')}", - " ports:", - f' - "{_http_bind()}:{http_port}:8080"', - f' - "{mux}:{mux}/tcp"', - f' - "{mux}:{mux}/udp"', - f' - "{udp}:{udp}/udp"', - " volumes:", - f" - {_q(f'{profile}:/home/neko/.config/chromium')}", - f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}", - f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}", - f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}", - f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}", - f" - {_q(f'{id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}", - f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}", - f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}", - f" - {_q(f'{supervisor}:/etc/neko/supervisord/{yn._supervisor_conf_name()}:ro')}", # noqa: SLF001 - ] + yn.compose_service_lines( + service_key=f"opsneko{idx}", + container_name=_container_name(idx), + instance_id_label=f"ops-{idx}", + http_port=_http_port(idx), + mux=_mux(idx), + udp=_udp_range(idx), + profile=_profile(idx), + instance_id_file=_instance_id_file(idx), + http_bind=_http_bind(), + ) ) return "\n".join(lines) + "\n" @@ -195,47 +141,68 @@ def _container_running(slot: int) -> bool: def _public_neko_url(slot: int) -> str: from . import db + from . import youtube_neko as yn cfg = db.get_settings_map() - base = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") - if not base: - base = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/") + override = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") + base = yn.preferred_neko_public_base(override=override) if not base: return f"/ops-neko/{int(slot)}/" return f"{base}/ops-neko/{int(slot)}/" -def sync_compose(*, start_slots: set[int] | None = None) -> dict[str, Any]: - """Rewrite compose for current max slot; create containers; start only requested.""" +def sync_compose(*, start_slots: set[int] | None = None, force_recreate: bool = True) -> dict[str, Any]: + """Rewrite compose for current max slot; create containers; start only requested. + + force_recreate default True so env (proxy / NAT1TO1 / TM) matches assign fleet. + Already-running slots are restarted after recreate (same as youtube_neko egress refresh). + """ max_slot = max(ops_neko_db.max_slot(), 1) if ops_neko_db.list_instances() else 0 if max_slot < 1: return {"ok": True, "skipped": "no_instances"} text = _render_compose(max_slot) _compose_path().write_text(text, encoding="utf-8") - start_slots = start_slots or set() - code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600) + start_slots = set(start_slots or set()) + was_running = {idx for idx in range(1, max_slot + 1) if _container_running(idx)} + resume = was_running | start_slots + up_args = ["up", "-d", "--no-start"] + if force_recreate: + up_args.insert(2, "--force-recreate") + code, out = _run(_compose_cmd(*up_args), timeout=600) if code != 0 and "--no-start" in (out or "").lower(): - code, out = _run(_compose_cmd("up", "-d"), timeout=600) + code, out = _run( + _compose_cmd("up", "-d", *(["--force-recreate"] if force_recreate else [])), + timeout=600, + ) if code == 0: for idx in range(1, max_slot + 1): - if idx not in start_slots: + if idx not in resume: _run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30) if code != 0: return {"ok": False, "error": (out or "compose up failed")[:500]} started: list[int] = [] - for idx in sorted(start_slots): + errors: list[str] = [] + for idx in sorted(resume): if 1 <= idx <= max_slot: c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90) if c2 == 0: started.append(idx) else: - return {"ok": False, "error": (o2 or "start failed")[:300], "started": started} + errors.append(f"ops-{idx}: {(o2 or 'start failed')[:160]}") + if errors: + return {"ok": False, "error": "; ".join(errors)[:500], "started": started, "max_slot": max_slot} return {"ok": True, "max_slot": max_slot, "started": started} def create_and_provision(*, name: str = "", note: str = "") -> dict[str, Any]: row = ops_neko_db.create_instance(name=name, note=note) sync = sync_compose(start_slots=set()) # always stopped after create + try: + from . import ops_neko_sync + + ops_neko_sync.kick() + except Exception: + pass return {"ok": True, "instance": enrich(row), "docker": sync} @@ -247,6 +214,12 @@ def start_slot(slot: int) -> dict[str, Any]: if not sync.get("ok"): return sync ops_neko_db.update_instance(str(inst["id"]), want_running=True) + try: + from . import ops_neko_sync + + ops_neko_sync.kick() + except Exception: + pass return {"ok": True, "instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst), "docker": sync} @@ -256,6 +229,12 @@ def stop_slot(slot: int) -> dict[str, Any]: return {"ok": False, "error": "instance not found"} code, out = _run(["docker", "stop", "-t", "8", _container_name(int(slot))], timeout=45) ops_neko_db.update_instance(str(inst["id"]), want_running=False) + try: + from . import ops_neko_sync + + ops_neko_sync.kick() + except Exception: + pass return { "ok": code == 0 or "no such container" in (out or "").lower(), "detail": out[:200], @@ -312,6 +291,7 @@ def hub_assign_cards() -> list[dict[str, Any]]: "neko_local_studio_url": str(g.get("neko_local_studio_url") or g.get("neko_studio_url") or ""), "ops_neko_open_url": str(g.get("ops_neko_open_url") or ""), "ops_neko_bound": bool(g.get("ops_neko_bound")), + "ops_neko_slot": int(g.get("ops_neko_slot") or 0), "neko_open_prefer": str(g.get("neko_open_prefer") or "local"), } ) @@ -344,7 +324,7 @@ def pull_remote_cards() -> dict[str, Any]: return {"ok": False, "error": str(exc)[:300]} -def push_bind_to_hub(instance_id: str) -> dict[str, Any]: +def push_bind_to_hub(instance_id: str, *, also_catalog: bool = True) -> dict[str, Any]: """Edge → hub: register this ops-neko open URL onto the VPS assign group.""" import httpx @@ -378,6 +358,360 @@ def push_bind_to_hub(instance_id: str) -> dict[str, Any]: r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload) if r.status_code != 200: return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload} - return {"ok": True, "hub": base, "payload": payload, "response": r.json()} + cat = push_catalog_to_hub() if also_catalog else {"ok": True, "skipped": "also_catalog=0"} + return {"ok": True, "hub": base, "payload": payload, "response": r.json(), "catalog": cat} except Exception as exc: return {"ok": False, "error": str(exc)[:300], "payload": payload} + + +def push_catalog_to_hub() -> dict[str, Any]: + """Edge → hub: publish all local ops-neko slots for VPS assign dropdown.""" + import httpx + import socket + + from . import db + + st = ops_neko_db.peer_status() + if st.get("role") != "edge": + return {"ok": False, "error": "peer role is not edge"} + base = str(st.get("peer_base_url") or "").strip().rstrip("/") + cfg = db.get_settings_map() + token = str(cfg.get("ops_neko_peer_token") or "").strip() + if not base or not token: + return {"ok": False, "error": "请填写 hub 域名与 token"} + edge_label = str(cfg.get("ops_neko_edge_label") or "").strip() + if not edge_label: + try: + edge_label = socket.gethostname() or "physical" + except Exception: + edge_label = "physical" + items = [] + for row in list_enriched(): + slot = int(row.get("slot") or 0) + if slot < 1: + continue + studio = None + try: + from . import youtube_neko as yn + + studio = yn.studio_snapshot_for_ref(f"ops:{slot}", max_age_sec=180.0) + # Drop empty snapshots to keep payload light + if not (studio.get("received_at") or studio.get("on_air") or studio.get("live_page_open")): + studio = None + except Exception: + studio = None + items.append( + { + "id": str(row.get("id") or ""), + "slot": slot, + "name": str(row.get("name") or f"Ops Neko {slot}"), + "open_url": str(row.get("open_url") or ""), + "running": bool(row.get("running")), + "studio": studio, + } + ) + payload = {"edge_id": edge_label, "edge_label": edge_label, "instances": items} + # Push assign Studio on_air so VPS live-map matches physical receiving-first. + assign_lives: list[dict[str, Any]] = [] + try: + import time as _time + + from . import yt_assign_db + from . import yt_studio_db + from . import youtube_neko as yn + + since = _time.time() - 180.0 + seen_cid: set[str] = set() + for g in yt_assign_db.list_groups(include_urls=False): + if not g.get("enabled"): + continue + gid = str(g.get("id") or "").strip() + cid = str(g.get("youtube_channel_id") or "").strip() + pk = str(g.get("channel_pk") or "").strip() + if not cid or cid in seen_cid: + continue + snap = {} + try: + snap = yn.studio_snapshot_for_group(g, max_age_sec=180.0) + except Exception: + snap = {} + on_air = bool(snap.get("on_air") or snap.get("encoder_receiving")) + st = str(snap.get("live_status") or "").lower() + if not on_air or st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: + # Fall back to recent DB samples (local CDP poll). + try: + samples = yt_studio_db.list_samples(group_id=gid, since_ts=since, limit=3) + except Exception: + samples = [] + hit = None + for s in samples: + sst = str(s.get("live_status") or "").lower() + if sst in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: + continue + if s.get("on_air") or sst == "live": + hit = s + break + if not hit: + continue + assign_lives.append( + { + "group_id": gid, + "channel_pk": pk, + "youtube_channel_id": cid, + "name": str(g.get("name") or ""), + "on_air": True, + "live_status": str(hit.get("live_status") or "live"), + "health": str(hit.get("health") or ""), + "viewer_count": hit.get("viewer_count"), + "studio_url": str(hit.get("studio_url") or "")[:200], + "neko_ref": str(hit.get("neko_ref") or ""), + "ts": float(hit.get("ts") or _time.time()), + } + ) + seen_cid.add(cid) + continue + assign_lives.append( + { + "group_id": gid, + "channel_pk": pk, + "youtube_channel_id": cid, + "name": str(g.get("name") or ""), + "on_air": True, + "live_status": st or "live", + "health": str(snap.get("health") or ""), + "viewer_count": snap.get("viewer_count"), + "studio_url": str(snap.get("url") or "")[:200], + "neko_ref": str(snap.get("neko_ref") or ""), + "ts": float(snap.get("received_at") or _time.time()), + } + ) + seen_cid.add(cid) + except Exception: + assign_lives = [] + if assign_lives: + payload["assign_lives"] = assign_lives + url = f"{base}/api/ops/neko/hub/catalog" + try: + with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client: + r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload) + if r.status_code != 200: + return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload} + return {"ok": True, "hub": base, "count": len(items), "response": r.json()} + except Exception as exc: + return {"ok": False, "error": str(exc)[:300], "payload": payload} + + +def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[str, Any]: + """Physical edge: ensure ops-neko Chrome has YouTube Live Control Room open (待开播).""" + from . import youtube_neko as yn + + slot_i = int(slot or 0) + if slot_i < 1: + return {"ok": False, "error": "bad_slot"} + name = _container_name(slot_i) + if not _container_running(slot_i): + try: + start_slot(slot_i) + except Exception: + pass + if not _container_running(slot_i): + return {"ok": False, "slot": slot_i, "error": "ops_neko_not_running"} + yt = str(youtube_channel_id or "").strip() + if not yt: + try: + inst = next( + (r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == slot_i), + None, + ) + gid = str((inst or {}).get("bind_remote_group_id") or "").strip() + if gid: + cards = pull_remote_cards() + for c in cards.get("cards") or []: + if str(c.get("id") or "") == gid: + yt = str(c.get("youtube_channel_id") or "").strip() + break + except Exception: + pass + studio_url = yn.studio_live_control_url(yt) + opened = yn._cdp_ensure_live_studio_in_container(name, studio_url=studio_url) + try: + # Never inject fake live_status=ready — that made hub think Studio was good while NODATA. + payload: dict[str, Any] = { + "neko_ref": f"ops-{slot_i}", + "neko_instance_id": f"ops-{slot_i}", + "source": "ops_cdp_ensure", + "url": str((opened or {}).get("url") or studio_url)[:400], + "live_status": "waiting", + "signals": {"path": "/livestreaming", "pending_go_live": True}, + } + try: + urls_py = ( + "import json,urllib.request\n" + "tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read())\n" + "live=[t.get('url') for t in tabs if 'livestreaming' in (t.get('url') or '').lower()]\n" + "print(json.dumps({'ok':bool(live),'url':(live[0] if live else '')}))\n" + ) + code, out = yn._run(["docker", "exec", name, "python3", "-c", urls_py], timeout=15) + if code == 0 and out: + row = json.loads((out or "").strip().split("\n")[-1] or "{}") + if isinstance(row, dict) and row.get("url"): + payload["url"] = str(row.get("url"))[:400] + except Exception: + pass + # Prefer full DOM scrape when script is available inside the container / on host. + scraped = False + for scrape_path in ( + "/etc/neko/cdp_studio_scrape.py", + "/opt/douyinWEB/backend/neko/cdp_studio_scrape.py", + ): + try: + code, out = yn._run( + ["docker", "exec", name, "python3", scrape_path], + timeout=20, + ) + if code != 0 or not (out or "").strip(): + continue + row = json.loads((out or "").strip().split("\n")[-1] or "{}") + if isinstance(row, dict) and row.get("ok"): + if row.get("url"): + payload["url"] = str(row.get("url"))[:400] + st = str(row.get("live_status") or "waiting").strip().lower() or "waiting" + if st == "ready": + st = "waiting" + payload["live_status"] = st + payload["text"] = str(row.get("text") or "")[:2200] + payload["signals"] = { + "path": "/livestreaming", + "nodata": bool(row.get("nodata")), + "encoder_receiving": bool(row.get("encoder_receiving")), + "encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost", + "session_live": bool(row.get("session_live")) + or st in {"live", "encoder_lost"}, + "pending_go_live": st == "waiting" + and not bool(row.get("session_live")) + and st != "encoder_lost", + } + scraped = True + break + except Exception: + continue + if not scraped: + try: + from pathlib import Path + + host_scrape = Path(__file__).resolve().parents[1] / "neko" / "cdp_studio_scrape.py" + if host_scrape.is_file(): + code, out = yn._run( + [ + "bash", + "-lc", + f"docker exec -i {name} python3 - < {host_scrape.as_posix()}", + ], + timeout=25, + ) + if code == 0 and (out or "").strip(): + row = json.loads((out or "").strip().split("\n")[-1] or "{}") + if isinstance(row, dict) and row.get("ok"): + if row.get("url"): + payload["url"] = str(row.get("url"))[:400] + st = str(row.get("live_status") or "waiting").strip().lower() or "waiting" + if st == "ready": + st = "waiting" + payload["live_status"] = st + payload["text"] = str(row.get("text") or "")[:2200] + payload["signals"] = { + "path": "/livestreaming", + "nodata": bool(row.get("nodata")), + "encoder_receiving": bool(row.get("encoder_receiving")), + "encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost", + "session_live": bool(row.get("session_live")) + or st in {"live", "encoder_lost"}, + "pending_go_live": st == "waiting" + and not bool(row.get("session_live")) + and st != "encoder_lost", + } + except Exception: + pass + yn.ingest_studio_telemetry(payload) + except Exception: + pass + return {"ok": bool(opened.get("ok")), "slot": slot_i, "studio_url": studio_url, "cdp": opened} + + +def ensure_bound_slots_live_studio() -> dict[str, Any]: + """Edge heartbeat: bound/running ops slots keep Live Control Room open.""" + cards_by_id: dict[str, dict[str, Any]] = {} + try: + pulled = pull_remote_cards() + for c in pulled.get("cards") or []: + cid = str(c.get("id") or "").strip() + if cid: + cards_by_id[cid] = c + except Exception: + pass + results: list[dict[str, Any]] = [] + for row in ops_neko_db.list_instances(): + slot = int(row.get("slot") or 0) + if slot < 1 or not _container_running(slot): + continue + gid = str(row.get("bind_remote_group_id") or "").strip() + yt = "" + should = bool(gid) + if gid and gid in cards_by_id: + yt = str(cards_by_id[gid].get("youtube_channel_id") or "").strip() + should = True + if not should: + for card in cards_by_id.values(): + if int(card.get("ops_neko_slot") or 0) == slot and ( + str(card.get("neko_open_prefer") or "").lower() == "remote" + or card.get("ops_neko_bound") + ): + yt = str(card.get("youtube_channel_id") or "").strip() + should = True + break + if not should: + continue + results.append(ensure_slot_live_studio(slot, youtube_channel_id=yt)) + return { + "ok": True, + "ensured": sum(1 for r in results if r.get("ok")), + "results": results, + } + + +def pair_as_edge(*, hub_base: str, token: str, public_base: str = "") -> dict[str, Any]: + """Physical: save edge peer credentials then push catalog (realtime registry).""" + from . import db + + hub = str(hub_base or "").strip().rstrip("/") + tok = str(token or "").strip() + if not tok: + tok = str(db.get_settings_map().get("ops_neko_peer_token") or "").strip() + if not hub or not tok: + return {"ok": False, "error": "需要 hub 域名与 token"} + peer = ops_neko_db.save_peer( + role="edge", + peer_base_url=hub, + public_base=public_base if public_base is not None else None, + token=tok, + ) + cards = pull_remote_cards() + try: + ensure_bound_slots_live_studio() + except Exception: + pass + catalog = push_catalog_to_hub() + try: + from . import ops_neko_sync + + ops_neko_sync.kick() + except Exception: + pass + return { + "ok": bool(catalog.get("ok") or cards.get("ok")), + "peer": peer, + "cards": cards, + "catalog": catalog, + "realtime": True, + "hint": "已连接:后台每 5 秒自动同步实例目录到 VPS,无需再点配对", + } diff --git a/backend/app/ops_neko_db.py b/backend/app/ops_neko_db.py index db266e7..2515e6d 100644 --- a/backend/app/ops_neko_db.py +++ b/backend/app/ops_neko_db.py @@ -36,6 +36,25 @@ def ensure_ops_neko_tables(conn: sqlite3.Connection) -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_ops_neko_slot ON ops_neko_instances(slot)" ) + # Hub-side catalog of physical edge ops-neko instances (pushed by edge). + conn.execute( + """ + CREATE TABLE IF NOT EXISTS ops_neko_edge_catalog ( + id TEXT PRIMARY KEY, + edge_id TEXT NOT NULL DEFAULT '', + edge_label TEXT NOT NULL DEFAULT '', + slot INTEGER NOT NULL DEFAULT 0, + name TEXT NOT NULL DEFAULT '', + open_url TEXT NOT NULL DEFAULT '', + running INTEGER NOT NULL DEFAULT 0, + last_seen REAL NOT NULL DEFAULT 0, + UNIQUE(edge_id, slot) + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_ops_neko_catalog_seen ON ops_neko_edge_catalog(last_seen DESC)" + ) def _ensure() -> None: @@ -196,6 +215,7 @@ PEER_KEYS = ( def peer_status() -> dict[str, Any]: from . import db + from . import youtube_neko cfg = db.get_settings_map() role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower() @@ -204,17 +224,20 @@ def peer_status() -> dict[str, Any]: token = str(cfg.get("ops_neko_peer_token") or "").strip() base = str(cfg.get("ops_neko_peer_base_url") or "").strip().rstrip("/") public = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") + effective = youtube_neko.preferred_neko_public_base(override=public) return { "ok": True, "role": role, "peer_base_url": base, "public_base": public, + "effective_public_base": effective, + "cn_edge_usable": youtube_neko.cn_edge_usable() if youtube_neko._physical_dual_edge() else False, # noqa: SLF001 "has_token": bool(token), "token_suffix": token[-4:] if len(token) >= 4 else "", "hint": { - "off": "本机独立运维 Neko,不跨机同步分配卡片", + "off": "本机独立运维 Neko(与分配页同一套 Studio/TM/代理配置)", "hub": "本机对外发布「YouTube 分配」卡片(通常 VPS);把 token 填到物理机", - "edge": "本机拉取 hub 的分配卡片并手动绑定(通常物理机 + ShellCrash Neko)", + "edge": "物理机:Neko 优先腾讯云 wg-dy-cn(.cn);不通才回退 VPS(.com)。实例配置与分配页一致。", }.get(role, ""), } @@ -259,3 +282,115 @@ def verify_peer_token(provided: str) -> bool: want = str(cfg.get("ops_neko_peer_token") or "").strip() got = str(provided or "").strip() return bool(want) and bool(got) and secrets.compare_digest(want, got) + + +def ensure_hub_credentials(*, rotate: bool = False) -> dict[str, Any]: + """VPS hub pairing card: public domain + token (create if missing).""" + from . import db + from . import host_profile + from .config import settings + + profile = host_profile.infer_profile() + cfg = db.get_settings_map() + role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower() + token = str(cfg.get("ops_neko_peer_token") or "").strip() + patch: dict[str, Any] = {} + if profile == "vps" and role != "hub": + patch["ops_neko_peer_role"] = "hub" + role = "hub" + if rotate or (role == "hub" and not token): + patch["ops_neko_peer_token"] = secrets.token_urlsafe(24) + if patch: + db.update_settings_map(patch) + cfg = db.get_settings_map() + role = str(cfg.get("ops_neko_peer_role") or role).strip().lower() + token = str(cfg.get("ops_neko_peer_token") or "").strip() + domain = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/") + if not domain: + domain = str(cfg.get("public_base_url") or "").strip().rstrip("/") + st = peer_status() + st["profile"] = profile + st["domain"] = domain + st["token"] = token if role == "hub" else "" + st["ready"] = bool(role == "hub" and domain and token) + return st + + +def upsert_edge_catalog( + items: list[dict[str, Any]], + *, + edge_id: str = "", + edge_label: str = "", +) -> list[dict[str, Any]]: + """Replace/merge catalog rows pushed by a physical edge.""" + _ensure() + now = time.time() + eid = str(edge_id or edge_label or "edge").strip()[:80] or "edge" + elabel = str(edge_label or eid).strip()[:120] + rows_out: list[dict[str, Any]] = [] + with _lock: + conn = _connect() + try: + ensure_ops_neko_tables(conn) + for it in items or []: + slot = int(it.get("slot") or 0) + if slot < 1: + continue + open_url = str(it.get("open_url") or "").strip() + if open_url and not open_url.endswith("/"): + open_url = f"{open_url}/" + name = str(it.get("name") or f"Ops Neko {slot}").strip()[:120] + running = 1 if it.get("running") else 0 + rid = str(it.get("id") or f"{eid}:{slot}")[:80] + conn.execute( + """ + INSERT INTO ops_neko_edge_catalog( + id, edge_id, edge_label, slot, name, open_url, running, last_seen + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(edge_id, slot) DO UPDATE SET + id=excluded.id, + edge_label=excluded.edge_label, + name=excluded.name, + open_url=excluded.open_url, + running=excluded.running, + last_seen=excluded.last_seen + """, + (rid, eid, elabel, slot, name, open_url, running, now), + ) + # Drop stale rows for this edge not in the push (optional cleanup) + keep_slots = {int(it.get("slot") or 0) for it in (items or []) if int(it.get("slot") or 0) > 0} + if keep_slots: + placeholders = ",".join("?" * len(keep_slots)) + conn.execute( + f"DELETE FROM ops_neko_edge_catalog WHERE edge_id = ? AND slot NOT IN ({placeholders})", + (eid, *sorted(keep_slots)), + ) + conn.commit() + rows = conn.execute( + "SELECT * FROM ops_neko_edge_catalog ORDER BY edge_label ASC, slot ASC" + ).fetchall() + rows_out = [_row_to_dict(r) for r in rows] + finally: + conn.close() + return rows_out + + +def list_edge_catalog(*, max_age_sec: float = 86400.0) -> list[dict[str, Any]]: + """Hub UI dropdown: recent physical ops-neko instances.""" + _ensure() + cutoff = time.time() - float(max_age_sec) + with _lock: + conn = _connect() + try: + ensure_ops_neko_tables(conn) + rows = conn.execute( + """ + SELECT * FROM ops_neko_edge_catalog + WHERE last_seen >= ? AND open_url != '' + ORDER BY edge_label ASC, slot ASC + """, + (cutoff,), + ).fetchall() + return [_row_to_dict(r) for r in rows] + finally: + conn.close() diff --git a/backend/app/ops_neko_sync.py b/backend/app/ops_neko_sync.py new file mode 100644 index 0000000..e9d14b8 --- /dev/null +++ b/backend/app/ops_neko_sync.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +"""Ops-neko edge ↔ hub realtime sync (heartbeat). + +Physical (edge): once hub URL + token are saved, continuously push instance +catalog (+ existing binds) to VPS. No manual「配对同步」needed after connect. +""" +from __future__ import annotations + +import asyncio +import time +from typing import Any + +_state: dict[str, Any] = { + "enabled": False, + "connected": False, + "last_ok_at": 0.0, + "last_error": "", + "last_result": {}, + "interval_sec": 5.0, + "ticks": 0, +} +_kick: asyncio.Event | None = None + + +def status() -> dict[str, Any]: + st = dict(_state) + age = None + if st.get("last_ok_at"): + age = max(0.0, time.time() - float(st["last_ok_at"])) + st["last_ok_age_sec"] = age + return {"ok": True, **st} + + +def kick() -> None: + """Wake the loop for an immediate sync (after create/start/stop/pair).""" + ev = _kick + if ev is not None: + ev.set() + + +def sync_once() -> dict[str, Any]: + """One edge→hub push. No-op when not configured as edge.""" + from . import ops_neko + from . import ops_neko_db + + peer = ops_neko_db.peer_status() + if peer.get("role") != "edge": + _state["enabled"] = False + _state["connected"] = False + return {"ok": True, "skipped": "not_edge", "role": peer.get("role")} + if not peer.get("peer_base_url") or not peer.get("has_token"): + _state["enabled"] = True + _state["connected"] = False + _state["last_error"] = "缺少 hub 域名或 token" + return {"ok": False, "error": "缺少 hub 域名或 token"} + + _state["enabled"] = True + # Keep YouTube Live Control Room open on bound ops-neko Chrome before catalog push. + try: + live = ops_neko.ensure_bound_slots_live_studio() + except Exception as exc: + live = {"ok": False, "error": str(exc)[:200]} + catalog = ops_neko.push_catalog_to_hub() + binds: list[dict[str, Any]] = [] + for row in ops_neko_db.list_instances(): + gid = str(row.get("bind_remote_group_id") or "").strip() + if not gid: + continue + try: + binds.append(ops_neko.push_bind_to_hub(str(row.get("id") or ""), also_catalog=False)) + except Exception as exc: + binds.append({"ok": False, "error": str(exc)[:200], "id": row.get("id")}) + + ok = bool(catalog.get("ok")) + _state["ticks"] = int(_state.get("ticks") or 0) + 1 + _state["last_result"] = { + "catalog_ok": ok, + "catalog_count": (catalog.get("count") if isinstance(catalog, dict) else None), + "binds_ok": sum(1 for b in binds if b.get("ok")), + "live_ensured": (live.get("ensured") if isinstance(live, dict) else None), + } + if ok: + _state["connected"] = True + _state["last_ok_at"] = time.time() + _state["last_error"] = "" + else: + _state["connected"] = False + _state["last_error"] = str(catalog.get("error") or "catalog push failed")[:300] + return {"ok": ok, "catalog": catalog, "binds": binds} + + +async def edge_sync_loop(*, interval_sec: float = 5.0) -> None: + """Background loop — only does work when peer role is edge.""" + global _kick + _kick = asyncio.Event() + _state["interval_sec"] = float(interval_sec) + while True: + try: + await asyncio.to_thread(sync_once) + except asyncio.CancelledError: + raise + except Exception as exc: + _state["connected"] = False + _state["last_error"] = str(exc)[:300] + assert _kick is not None + try: + await asyncio.wait_for(_kick.wait(), timeout=float(interval_sec)) + _kick.clear() + except asyncio.TimeoutError: + pass + except asyncio.CancelledError: + raise diff --git a/backend/app/session_auth.py b/backend/app/session_auth.py index 9b8e381..34a0fde 100644 --- a/backend/app/session_auth.py +++ b/backend/app/session_auth.py @@ -38,6 +38,7 @@ _PUBLIC_API_EXACT = { "/hub/youtube/live/ingest", "/api/ops/neko/hub/assign-cards", "/api/ops/neko/hub/bind", + "/api/ops/neko/hub/catalog", } diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py index 28b85cc..f9623e4 100644 --- a/backend/app/youtube_live.py +++ b/backend/app/youtube_live.py @@ -3,8 +3,11 @@ from __future__ import annotations import asyncio +import json import os +import re import time +import urllib.request from typing import Any, Optional from . import db, youtube_client @@ -19,6 +22,103 @@ _LAST_OAUTH_AT = 0.0 _OAUTH_MIN_INTERVAL_SEC = 45.0 +def _http_channel_live_probe(channel_id: str) -> dict[str, Any]: + """Public fallback: GET /channel/UC…/live and read player isLive flags. + + youtubei.js tab scans often miss on-air streams that /live still exposes. + Honors HTTPS_PROXY/HTTP_PROXY (physical China guest via ShellCrash). + """ + cid = str(channel_id or "").strip() + empty = {"is_live": False, "source": "http_live", "channel_id": cid, "live_url": "", "title": ""} + if not cid.startswith("UC"): + return empty + url = f"https://www.youtube.com/channel/{cid}/live" + html = "" + last_err = "" + proxies_try: list[str] = [] + env_proxy = ( + str(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "").strip() + or str(os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") or "").strip() + ) + if env_proxy: + proxies_try.append(env_proxy) + proxies_try.append("") # direct + # Physical China guest: ShellCrash (same as douyinweb-yt) if env unset / direct fails + if "127.0.0.1:7890" not in env_proxy: + proxies_try.append("http://127.0.0.1:7890") + seen_p: set[str] = set() + for proxy in proxies_try: + if proxy in seen_p: + continue + seen_p.add(proxy) + try: + handlers: list[Any] = [] + if proxy: + handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy})) + opener = urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener() + req = urllib.request.Request( + url, + headers={ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Accept-Language": "en-US,en;q=0.9", + }, + ) + with opener.open(req, timeout=22) as resp: + html = resp.read().decode("utf-8", "replace") + last_err = "" + break + except Exception as exc: + last_err = str(exc)[:160] + html = "" + continue + if not html: + return {**empty, "error": last_err or "http_live_fetch_failed"} + + video_id = "" + title = "" + is_live = False + play_status = "" + m = re.search(r"ytInitialPlayerResponse\s*=\s*", html) + if m: + try: + obj, _ = json.JSONDecoder().raw_decode(html[m.end() :]) + if isinstance(obj, dict): + play_status = str((obj.get("playabilityStatus") or {}).get("status") or "") + vd = obj.get("videoDetails") if isinstance(obj.get("videoDetails"), dict) else {} + video_id = str(vd.get("videoId") or "") + title = str(vd.get("title") or "")[:120] + # isLiveContent is true for VODs / scheduled offline streams — NOT on-air. + if vd.get("isLive") is True: + is_live = True + micro = (obj.get("microformat") or {}).get("playerMicroformatRenderer") or {} + if isinstance(micro, dict): + details = micro.get("liveBroadcastDetails") or {} + if isinstance(details, dict) and details.get("isLiveNow") is True: + is_live = True + elif isinstance(details, dict) and details.get("isLiveNow") is False: + is_live = False + except Exception: + pass + # Waiting / scheduled rooms often still have isLiveContent + title "is live!" — + # never treat LIVE_STREAM_OFFLINE as on-air. + if play_status in {"LIVE_STREAM_OFFLINE", "ERROR", "UNPLAYABLE", "LOGIN_REQUIRED"}: + if play_status == "LIVE_STREAM_OFFLINE": + is_live = False + elif play_status != "LOGIN_REQUIRED": + is_live = False + if not is_live and re.search(r'"isLiveNow"\s*:\s*true', html, re.I): + is_live = True + # Bare "isLive":true appears on offline scheduled pages — ignore without isLiveNow. + live_url = f"https://www.youtube.com/watch?v={video_id}" if video_id else url + return { + "is_live": bool(is_live), + "source": "http_live", + "channel_id": cid, + "live_url": live_url if is_live else "", + "title": title, + } + + def _refresh_lock() -> asyncio.Lock: global _REFRESH_LOCK if _REFRESH_LOCK is None: @@ -136,48 +236,15 @@ async def _oauth_live_for_shorts(channel_pk: str, youtube_channel_id: str) -> Op title=title, channel_id=youtube_channel_id, ) + # Explicit offline from liveBroadcasts — do NOT burn Search Queries quota. return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id) except Exception as broadcast_exc: - broadcast_err = str(broadcast_exc) - - # 2) Fallback: search (expensive; may hit daily Search Queries quota) - try: - data = await youtube_manage._get( - "search", - token=token, - params={ - "part": "snippet", - "channelId": youtube_channel_id, - "eventType": "live", - "type": "video", - "maxResults": 1, - }, - ) - items = data.get("items") or [] - if not items: - return _live_entry( - is_live=False, - source="oauth", - channel_id=youtube_channel_id, - error=broadcast_err[:120] if broadcast_err else "", - ) - item = items[0] - vid = str((item.get("id") or {}).get("videoId") or "").strip() - title = str((item.get("snippet") or {}).get("title") or "").strip() - live_url = f"https://www.youtube.com/watch?v={vid}" if vid else "" - return _live_entry( - is_live=True, - source="oauth", - live_url=live_url, - title=title, - channel_id=youtube_channel_id, - ) - except Exception as search_exc: + # Broadcasts unavailable → leave detection to youtubei (public). Never search.list. return _live_entry( is_live=False, - source="oauth", + source="oauth-broadcast", channel_id=youtube_channel_id, - error=f"{broadcast_err[:80]} | {str(search_exc)[:100]}", + error=f"broadcasts_unavailable:{str(broadcast_exc)[:140]}", ) except Exception as exc: return _live_entry( @@ -253,12 +320,16 @@ async def build_live_map(*, force: bool = False) -> dict[str, Any]: async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: global _LAST_OAUTH_AT - def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: + from . import yt_assign_db + groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or []) shorts = db.list_shorts_channels() - return groups, shorts + # Live 分配授权频道卡 — 与 Shorts/旧分组一样走公开 youtubei 探测(双机应一致) + assign = yt_assign_db.list_groups(include_urls=False) + return groups, shorts, assign - groups, shorts = await asyncio.to_thread(_load_db_targets) + groups, shorts, assign_groups_early = await asyncio.to_thread(_load_db_targets) targets: list[dict[str, Any]] = [] url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {} @@ -287,6 +358,51 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: cid_to_refs.setdefault(cid, []).append((ref, meta)) targets.append({"ref": f"channel:{cid}", "url": url or f"https://www.youtube.com/channel/{cid}", **meta}) + # Assign cards: same public youtubei probe as shorts (VPS ↔ physical must match for same UC ids). + seen_assign_cid: set[str] = set() + for ag in assign_groups_early: + if not ag.get("enabled"): + continue + gid = str(ag.get("id") or "").strip() + if not gid: + continue + cid = str(ag.get("youtube_channel_id") or "").strip() + pk = str(ag.get("channel_pk") or "").strip() + if not cid and pk: + try: + ch = db.get_shorts_channel(pk) or {} + cid = str(ch.get("youtube_channel_id") or "").strip() + except Exception: + cid = "" + if not cid: + continue + url = f"https://www.youtube.com/channel/{cid}" + meta = { + "kind": "assign", + "assign_group_id": gid, + "channel_pk": pk, + "youtube_channel_id": cid, + "title": str(ag.get("name") or "").strip(), + "url": url, + } + targets.append({"ref": f"assign:{gid}", "url": url, **meta}) + url_to_refs.setdefault(url, []).append((f"assign:{gid}", meta)) + cid_to_refs.setdefault(cid, []).append((f"assign:{gid}", meta)) + if cid not in seen_assign_cid: + seen_assign_cid.add(cid) + targets.append({"ref": f"channel:{cid}", "url": url, **meta}) + if pk: + # Keep shorts ref in sync when assign shares the same OAuth channel. + targets.append( + { + "ref": f"shorts:{pk}", + "url": url, + "kind": "shorts", + "channel_pk": pk, + "youtube_channel_id": cid, + } + ) + entries: dict[str, Any] = {} unique_urls: list[str] = [] seen_urls: set[str] = set() @@ -342,14 +458,86 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: channel_id=str(g.get("channel_id") or ""), ) + # Prefer keeping an already-live youtubei hit if we revisit the same ref. + prev = entries.get(ref) + if prev and prev.get("is_live") and not entry.get("is_live"): + entry = dict(prev) + elif t.get("kind") == "assign" and entry.get("is_live"): + entry = dict(entry) + entry["assign_group_id"] = str(t.get("assign_group_id") or "") + entry["channel_pk"] = str(t.get("channel_pk") or "") + if t.get("title"): + entry["title"] = str(t.get("title") or "") + if cid: + entry["channel_id"] = cid + entries[ref] = dict(entry) if cid and entry.get("is_live"): entries[f"channel:{cid}"] = dict(entry) + if t.get("kind") == "assign" and t.get("channel_pk"): + pk = str(t.get("channel_pk") or "") + shorts_ref = f"shorts:{pk}" + if not (entries.get(shorts_ref) or {}).get("is_live"): + se = dict(entry) + se["assign_group_id"] = str(t.get("assign_group_id") or "") + entries[shorts_ref] = se - # OAuth 兜底限频,避免多标签 force/后台轮询打爆配额 + # HTTP /channel/UC…/live fallback — youtubei tab scans often miss true on-air streams. + http_cids: list[str] = [] + seen_http: set[str] = set() + for t in targets: + cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip() + if not cid or cid in seen_http: + continue + ch_ent = entries.get(f"channel:{cid}") or {} + # Probe when missing or youtubei said offline + if ch_ent.get("is_live"): + continue + seen_http.add(cid) + http_cids.append(cid) + if http_cids: + http_results = await asyncio.gather( + *[asyncio.to_thread(_http_channel_live_probe, cid) for cid in http_cids], + return_exceptions=True, + ) + cid_to_targets: dict[str, list[dict[str, Any]]] = {} + for t in targets: + cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip() + if cid: + cid_to_targets.setdefault(cid, []).append(t) + for cid, result in zip(http_cids, http_results): + if isinstance(result, Exception) or not isinstance(result, dict): + continue + if not result.get("is_live"): + continue + live_ent = _live_entry( + is_live=True, + source="http_live", + live_url=str(result.get("live_url") or ""), + title=str(result.get("title") or ""), + channel_id=cid, + ) + entries[f"channel:{cid}"] = live_ent + for t in cid_to_targets.get(cid) or []: + ref = str(t.get("ref") or "") + if not ref: + continue + cur = entries.get(ref) or {} + if cur.get("is_live"): + continue + ent = dict(live_ent) + if t.get("kind") == "assign": + ent["assign_group_id"] = str(t.get("assign_group_id") or "") + ent["channel_pk"] = str(t.get("channel_pk") or "") + if t.get("title"): + ent["title"] = str(t.get("title") or ent.get("title") or "") + entries[ref] = ent + + # OAuth / liveBroadcasts:授权频道卡与 Shorts 共用 channel_pk 时必走(双机公开态应一致) run_oauth = (now - float(_LAST_OAUTH_AT or 0)) >= _OAUTH_MIN_INTERVAL_SEC oauth_tasks: list[tuple[str, str, str]] = [] if run_oauth: + seen_oauth_pk: set[str] = set() for ch in shorts: cid = str(ch.get("youtube_channel_id") or "").strip() pk = str(ch.get("id") or "") @@ -361,6 +549,34 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: if entries.get(ref, {}).get("is_live"): continue oauth_tasks.append((ref, pk, cid)) + seen_oauth_pk.add(pk) + # Assign cards that bind an OAuth shorts channel — same API path on VPS & physical. + for ag in assign_groups_early: + if not ag.get("enabled"): + continue + pk = str(ag.get("channel_pk") or "").strip() + cid = str(ag.get("youtube_channel_id") or "").strip() + gid = str(ag.get("id") or "").strip() + if not pk or not gid: + continue + if pk in seen_oauth_pk: + continue + if (entries.get(f"assign:{gid}") or {}).get("is_live"): + continue + if (entries.get(f"shorts:{pk}") or {}).get("is_live"): + continue + try: + ch = db.get_shorts_channel(pk) or {} + except Exception: + ch = {} + if not str(ch.get("refresh_token") or "").strip(): + continue + if not cid: + cid = str(ch.get("youtube_channel_id") or "").strip() + if not cid: + continue + oauth_tasks.append((f"shorts:{pk}", pk, cid)) + seen_oauth_pk.add(pk) if oauth_tasks: _LAST_OAUTH_AT = now @@ -368,17 +584,76 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: *[_oauth_live_for_shorts(pk, cid) for _ref, pk, cid in oauth_tasks], return_exceptions=True, ) - for (ref, _pk, cid), result in zip(oauth_tasks, oauth_results): - if isinstance(result, Exception): + pk_to_assign: dict[str, list[dict[str, Any]]] = {} + for ag in assign_groups_early: + pk = str(ag.get("channel_pk") or "").strip() + if pk: + pk_to_assign.setdefault(pk, []).append(ag) + for (ref, pk, cid), result in zip(oauth_tasks, oauth_results): + if isinstance(result, Exception) or not isinstance(result, dict): continue - if isinstance(result, dict) and result.get("is_live"): + src = str(result.get("source") or "") + if result.get("is_live"): entries[ref] = result - entries[f"channel:{cid}"] = result + if cid: + entries[f"channel:{cid}"] = result + for ag in pk_to_assign.get(pk) or []: + gid = str(ag.get("id") or "").strip() + if not gid: + continue + ent = dict(result) + ent["assign_group_id"] = gid + ent["channel_pk"] = pk + if ag.get("name"): + ent["title"] = str(ag.get("name") or "") + entries[f"assign:{gid}"] = ent + elif src.startswith("oauth"): + # API answered offline — record so Studio cannot invent public live. + # Never replace a clean youtubei offline with an errored oauth result. + cur = entries.get(ref) or {} + if cur.get("is_live"): + continue + if ( + result.get("error") + and str(cur.get("source") or "") == "youtubei" + and not cur.get("error") + ): + continue + entries[ref] = dict(result) + if cid: + ch_cur = entries.get(f"channel:{cid}") or {} + if not ( + result.get("error") + and str(ch_cur.get("source") or "") == "youtubei" + and not ch_cur.get("error") + and not ch_cur.get("is_live") + ): + if not ch_cur.get("is_live"): + entries[f"channel:{cid}"] = dict(result) + for ag in pk_to_assign.get(pk) or []: + gid = str(ag.get("id") or "").strip() + if not gid: + continue + ae = entries.get(f"assign:{gid}") or {} + if ae.get("is_live"): + continue + if ( + result.get("error") + and str(ae.get("source") or "") == "youtubei" + and not ae.get("error") + ): + continue + ent = dict(result) + ent["assign_group_id"] = gid + ent["channel_pk"] = pk + if ag.get("name"): + ent["title"] = str(ag.get("name") or "") + entries[f"assign:{gid}"] = ent elif _CACHE.get("payload") and isinstance(_CACHE.get("payload"), dict): # 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线 prev = (_CACHE.get("payload") or {}).get("entries") or {} for ref, old in prev.items(): - if not str(ref).startswith("shorts:"): + if not str(ref).startswith(("shorts:", "assign:")): continue if not isinstance(old, dict) or not old.get("is_live"): continue @@ -436,23 +711,45 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: continue pk = str(g.get("channel_pk") or "").strip() row = relay_rows.get(gid) or {} - nid = 0 - try: - nid = int(g.get("neko_instance_id") or 0) - except (TypeError, ValueError): - nid = 0 + cid = str(g.get("youtube_channel_id") or "").strip() + # Already marked live via youtubei/OAuth for this shorts/channel → receiving-level truth. + prev_live = entries.get(f"assign:{gid}") or {} + if not prev_live.get("is_live") and pk: + prev_live = entries.get(f"shorts:{pk}") or {} + if not prev_live.get("is_live") and cid: + prev_live = entries.get(f"channel:{cid}") or {} + + # Prefer group-aware Studio snap (remote ops-neko when prefer=remote). studio_snap: dict[str, Any] = {} - if nid > 0: + try: + studio_snap = await asyncio.to_thread( + lambda gg=g: youtube_neko.studio_snapshot_for_group(gg, max_age_sec=120.0) + ) + except Exception: + studio_snap = {} + if not studio_snap.get("on_air") and not studio_snap.get("encoder_receiving"): + # Legacy local-instance CDP lookup as extra receiving probe. try: - studio_snap = await asyncio.to_thread( - lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0) - ) - except Exception: - studio_snap = {} + nid = int(g.get("neko_instance_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid > 0: + try: + local_snap = await asyncio.to_thread( + lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0) + ) + except Exception: + local_snap = {} + if local_snap.get("on_air") or local_snap.get("encoder_receiving"): + studio_snap = local_snap - # Fallback: match telemetry by group's saved studio URL (no CDP / no instance tag). - if not studio_snap.get("on_air"): + # Fallback: match telemetry by group's saved studio URL (receiving signals only). + if not ( + studio_snap.get("on_air") + or studio_snap.get("encoder_receiving") + or str(studio_snap.get("live_status") or "").lower() == "live" + ): studio_url = str(g.get("neko_studio_url") or "") vid = "" if "/video/" in studio_url: @@ -466,32 +763,159 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: url = str(payload.get("url") or "") if vid not in url: continue - if str(payload.get("live_status") or "").lower() in {"live", "streaming"} or str( - payload.get("health") or "" - ).lower() in {"excellent", "good"}: - studio_snap = { - "on_air": True, - "live_page_open": True, - "live_status": str(payload.get("live_status") or "live"), - "health": str(payload.get("health") or ""), - "viewer_count": payload.get("viewer_count"), - "url": url[:200], - "received_at": float(ev.get("received_at") or 0), - "detect_source": "telemetry_url_match", - "neko_instance_id": nid, - } - break + signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {} + st = str(payload.get("live_status") or "").lower() + health = str(payload.get("health") or "").lower() + receiving = bool( + signals.get("encoder_receiving") + or st == "live" + or health in {"excellent", "good"} + ) + if not receiving: + continue + if signals.get("encoder_lost") or st in {"encoder_lost", "waiting", "ended"}: + continue + studio_snap = { + "on_air": True, + "encoder_receiving": True, + "live_page_open": True, + "live_status": st or "live", + "health": health, + "viewer_count": payload.get("viewer_count"), + "url": url[:200], + "received_at": float(ev.get("received_at") or 0), + "detect_source": "telemetry_url_match", + } + break + + # DB samples (physical local Neko CDP) — fill when in-memory snap is quiet. + if not ( + studio_snap.get("on_air") + or studio_snap.get("encoder_receiving") + or str(studio_snap.get("live_status") or "").lower() == "live" + ): + try: + from . import yt_studio_db + + samples = await asyncio.to_thread( + lambda: yt_studio_db.list_samples( + group_id=gid, since_ts=now - 180.0, limit=5 + ) + ) + if not samples and cid: + samples = await asyncio.to_thread( + lambda: yt_studio_db.list_samples( + youtube_channel_id=cid, since_ts=now - 180.0, limit=5 + ) + ) + except Exception: + samples = [] + for s in samples or []: + st = str(s.get("live_status") or "").lower() + if st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: + continue + if not (s.get("on_air") or st == "live"): + continue + studio_snap = { + "on_air": True, + "encoder_receiving": True, + "live_page_open": bool(s.get("live_page_open") or True), + "live_status": st or "live", + "health": str(s.get("health") or ""), + "viewer_count": s.get("viewer_count"), + "url": str(s.get("studio_url") or "")[:200], + "received_at": float(s.get("ts") or 0), + "detect_source": "yt_studio_samples", + "neko_ref": str(s.get("neko_ref") or ""), + } + break + + receiving = bool( + ( + studio_snap.get("encoder_receiving") + or studio_snap.get("on_air") + ) + and not studio_snap.get("encoder_lost") + and str(studio_snap.get("live_status") or "").lower() + not in {"waiting", "ended", "signed_out", "offline", "encoder_lost"} + ) + + # Collect public probe answers across assign / channel / shorts refs. + public_sources = { + "youtubei", + "http_live", + "oauth", + "oauth-broadcast", + "oauth_liveBroadcasts", + } + public_live_hit: dict[str, Any] | None = None + public_offline_hit: dict[str, Any] | None = None + for key in ( + f"assign:{gid}", + f"channel:{cid}" if cid else "", + f"shorts:{pk}" if pk else "", + ): + if not key: + continue + p = entries.get(key) + if not isinstance(p, dict): + continue + s = str(p.get("source") or "") + if s not in public_sources: + continue + if p.get("is_live"): + public_live_hit = p + break + # Prefer clean offline answers; youtubei offline always counts even if + # another ref holds an errored oauth leftover. + if not p.get("error"): + public_offline_hit = p + elif s == "youtubei" and not p.get("is_live"): + public_offline_hit = public_offline_hit or p + + prev_public = bool( + prev_live.get("is_live") + and str(prev_live.get("source") or "") in public_sources + ) + # Receiving-first: Studio on_air / encoder_receiving beats public offline + # (youtubei false-negatives + OAuth "mine" miss when push uses another key). + if receiving: + mark_live = True + source = "studio_receiving" + elif public_live_hit or prev_public: + mark_live = True + source = str( + (public_live_hit or prev_live).get("source") or "youtubei" + ) + elif public_offline_hit is not None: + mark_live = bool(row.get("is_pushing")) + source = "relay" if mark_live else "" + else: + mark_live = bool(row.get("is_pushing")) + source = "relay" if mark_live else "" - mark_live = bool(row.get("is_pushing") or studio_snap.get("on_air")) if not mark_live: - # Keep studio snapshot on assign entry for UI even when offline. - if studio_snap.get("live_page_open") and f"assign:{gid}" in entries: - entries[f"assign:{gid}"]["studio"] = studio_snap + base = entries.get(f"assign:{gid}") or { + "is_live": False, + "source": str((public_offline_hit or {}).get("source") or "unknown"), + "assign_group_id": gid, + "channel_pk": pk, + "title": gid_to_name.get(gid) or str(g.get("name") or ""), + "channel_id": cid, + } + base = dict(base) + base["is_live"] = False + if studio_snap.get("live_page_open") or studio_snap: + base["studio"] = studio_snap + entries[f"assign:{gid}"] = base continue - prev = entries.get(f"assign:{gid}") or {} - source = "relay" if row.get("is_pushing") else "studio_telemetry" - if prev.get("is_live") and prev.get("source") not in {"relay", "studio_telemetry"}: + prev = entries.get(f"assign:{gid}") or prev_live or {} + if prev.get("is_live") and prev.get("source") not in { + "relay", + "studio_telemetry", + "studio_receiving", + }: source = str(prev.get("source") or source) entries[f"assign:{gid}"] = { **prev, @@ -517,9 +941,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: } else: entries[shorts_ref]["assign_group_id"] = gid - cid = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip() - if cid: - entries[f"channel:{cid}"] = dict(entries[shorts_ref]) + cid2 = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip() + if cid2: + entries[f"channel:{cid2}"] = dict(entries[shorts_ref]) except Exception as exc: import logging diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py index e63f0d8..48ea126 100644 --- a/backend/app/youtube_neko.py +++ b/backend/app/youtube_neko.py @@ -213,17 +213,146 @@ def _public_base() -> str: return "" +def _physical_dual_edge() -> bool: + """Physical guest: TLS on VPS/Tencent, app + Neko on this host via WireGuard. + + Do NOT treat the overseas VPS (WG *server* + colocated app) as physical just because + ``wg-dy`` exists — that wrongly empties preferred public base / ICE logic. + """ + if str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip(): + return True + shape = str(os.environ.get("DY_INSTALL_SHAPE") or os.environ.get("INSTALL_SHAPE") or "").strip().lower() + if shape in {"vps", "colocated", "dylive"}: + return False + if shape in {"physical", "phys", "guest"}: + return True + # VPS colocated binds Neko to loopback; physical guest publishes on 0.0.0.0 for WG. + bind = str( + getattr(settings, "neko_http_bind", "") + or os.environ.get("DY_NEKO_HTTP_BIND") + or "" + ).strip() + if bind in {"127.0.0.1", "localhost", "::1"}: + return False + sysnet = Path("/sys/class/net") + if not sysnet.is_dir(): + return False + return (sysnet / "wg-dy").exists() or (sysnet / "wg-dy-cn").exists() + + +def preferred_neko_public_base(*, override: str = "") -> str: + """Physical Neko open URL: Tencent (.cn) when wg-dy-cn is up, else VPS (.com). + + Colocated VPS (dylive): always the configured public base — never 127.0.0.1. + """ + primary = (override or "").strip().rstrip("/") or _public_base() + if not _physical_dual_edge(): + return primary + cn = _derive_cn_public_base(primary) + if cn and cn_edge_usable(): + return cn + return primary or cn + + +def public_studio_url(instance_id: int) -> str: + """Browser-openable assign Neko URL (must be public HTTPS path, not loopback port).""" + idx = int(instance_id or 0) + base = preferred_neko_public_base() + if base and "127.0.0.1" not in base and "localhost" not in base.lower(): + return f"{base}/neko/{idx}/" + # Misconfigured env: still prefer path-style URL on known sites over :920x loopback. + for key in ("DY_PUBLIC_BASE_URL", "PUBLIC_BASE", "DY_SITE_URL"): + alt = str(os.environ.get(key) or "").strip().rstrip("/") + if alt and "127.0.0.1" not in alt and "localhost" not in alt.lower(): + return f"{alt}/neko/{idx}/" + # Last resort for server-side probes only — UI should never hit this on a configured VPS. + return f"http://127.0.0.1:{_http_port(idx)}/" + + +def _wg_iface_usable(iface: str, *, peer: str, max_age_sec: int = 180) -> bool: + """Handshake fresh enough, or peer ICMP reachable.""" + if not Path(f"/sys/class/net/{iface}").exists(): + return False + import time as _time + + code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5) + if code == 0 and out.strip(): + parts = out.split() + if len(parts) >= 2: + try: + ts = int(parts[-1]) + except ValueError: + ts = 0 + if ts > 0 and (_time.time() - ts) <= max_age_sec: + return True + if peer: + c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6) + if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2): + return True + return False + + +def cn_edge_usable() -> bool: + """Tencent wg-dy-cn preferred path for physical Neko HTTP/ICE. + + Prefer CN whenever the iface is up and either handshake is fresh or peer pings. + Slightly stale handshake alone should not flip ICE to the overseas VPS IP. + """ + if not Path("/sys/class/net/wg-dy-cn").exists(): + return False + peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1" + if _wg_iface_usable("wg-dy-cn", peer=peer, max_age_sec=600): + return True + # iface present: still prefer CN if configured (operator intent) unless ping hard-fails + if peer: + c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6) + if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2): + return True + # Last resort: iface up counts as usable so NAT1TO1 stays on Tencent DNAT + return True + + +def _derive_cn_public_base(primary: str) -> str: + env = str(os.environ.get("DY_NEKO_CN_PUBLIC_BASE") or "").strip().rstrip("/") + if env: + return env + base = (primary or "").strip().rstrip("/") + if not base: + return "" + if base.endswith(".nomadro.com"): + return base[: -len(".nomadro.com")] + ".nomadro.cn" + if "nomadro.com" in base: + return base.replace("nomadro.com", "nomadro.cn") + return "" + + def _detect_public_ip() -> str: - """Resolve reachable public IP for WebRTC ICE (NAT1TO1). Cached to avoid compose thrash.""" + """Resolve reachable public IP for WebRTC ICE (NAT1TO1). + + Physical dual-edge: Tencent ``DY_NEKO_CN_NAT1TO1`` (or ``DY_NEKO_NAT1TO1``) while + wg-dy-cn is usable; otherwise ``DY_NEKO_VPS_NAT1TO1`` / fallback. Cached briefly. + """ global _nat_ip_cache, _nat_ip_cached_at import time as _time + cn_ip = str(os.environ.get("DY_NEKO_CN_NAT1TO1") or "").strip() + vps_ip = str(os.environ.get("DY_NEKO_VPS_NAT1TO1") or "").strip() configured = str(getattr(settings, "neko_nat1to1", "") or "").strip() - if configured: - return configured env_ip = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip() - if env_ip: - return env_ip + + if _physical_dual_edge(): + if cn_edge_usable(): + pick = cn_ip or configured or env_ip + if pick: + return pick + pick = vps_ip or (env_ip if env_ip != cn_ip else "") or configured + if pick: + return pick + else: + if configured: + return configured + if env_ip: + return env_ip now = _time.time() if _nat_ip_cache and (now - _nat_ip_cached_at) < _NAT_CACHE_TTL_SEC: @@ -280,8 +409,7 @@ def _detect_public_ip() -> str: pass if not ip: # Prefer explicit NAT1TO1; never invent a datacenter IP for the wrong host. - env_fallback = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip() - ip = env_fallback or _nat_ip_cache or "" + ip = vps_ip or env_ip or cn_ip or configured or _nat_ip_cache or "" if ip: _nat_ip_cache = ip _nat_ip_cached_at = now @@ -304,13 +432,6 @@ def _desired_from_db() -> int: return 0 -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 _ensure_profile(instance_id: int) -> Path: profile = _neko_root() / "profiles" / str(instance_id) profile.mkdir(parents=True, exist_ok=True) @@ -343,8 +464,23 @@ def _q(value: str) -> str: return json.dumps(str(value), ensure_ascii=False) -def _render_compose(count: int) -> str: - # x86 US VPS → google-chrome (sh2); override via DY_NEKO_IMAGE. +def compose_service_lines( + *, + service_key: str, + container_name: str, + instance_id_label: str, + http_port: int, + mux: int, + udp: str, + profile: Path, + instance_id_file: Path, + http_bind: str | None = None, +) -> list[str]: + """One Docker Compose service — shared by assign fleet and ops-neko tab. + + Same image/env/assets/proxy/Studio start URL so YouTube live tooling matches. + Only ports / names / profile dirs differ between fleets. + """ image = str( getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0" ) @@ -352,10 +488,10 @@ def _render_compose(count: int) -> str: admin_pass = str(getattr(settings, "neko_admin_pass", "") or "Xiao4669805@") nat1to1 = _detect_public_ip() shm = str(getattr(settings, "neko_shm_size", "") or "512mb") - screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15") - max_fps = str(getattr(settings, "neko_max_fps", "") or "15") - bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200") - # sh2 forces ICE Lite OFF for remote clients unless explicitly overridden. + # Defaults match Settings / YouTube unattended-live (low CPU Studio remote). + screen = str(getattr(settings, "neko_desktop_screen", "") or "1024x576@10") + max_fps = str(getattr(settings, "neko_max_fps", "") or "10") + bitrate = str(getattr(settings, "neko_video_bitrate", "") or "700") icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0") start_url = str( getattr(settings, "neko_start_url", "") @@ -369,90 +505,95 @@ def _render_compose(count: int) -> str: live_ops_dir = assets / "live-ops-extension" provisioning_dir = assets / "provisioning" browser_launch = assets / "browser-launch.sh" - supervisor = assets / _supervisor_conf_name() - # Fail loud in compose text if assets missing (ops can see in file). + supervisor_name = _supervisor_conf_name() + supervisor = assets / supervisor_name for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir): if not required.exists(): raise RuntimeError(f"Neko sh2 asset missing: {required}") _ensure_browser_launch_exec() + bind = (http_bind or _http_bind()).strip() or "127.0.0.1" + return [ + f" {service_key}:", + f" image: {_q(image)}", + ' restart: "no"', + f" shm_size: {_q(shm)}", + " cap_add:", + " - SYS_ADMIN", + " security_opt:", + " - apparmor:unconfined", + " extra_hosts:", + ' - "host.docker.internal:host-gateway"', + f" container_name: {container_name}", + " environment:", + f" TZ: {_q(tz)}", + ' DISPLAY: ":99.0"', + ' ENV_DISPLAY: ":99.0"', + ' ENV_USER: "neko"', + ' USER: "neko"', + ' HOME: "/home/neko"', + ' NEKO_CONTAINER_USER: "neko"', + ' NEKO_CONTAINER_HOME: "/home/neko"', + f" NEKO_INSTANCE_ID: {_q(str(instance_id_label))}", + ' NEKO_SERVER_BIND: ":8080"', + # Trust X-Forwarded-* from nginx/Caddy; NO path prefix (edge strips /neko/N/ or /ops-neko/N/). + ' NEKO_SERVER_PROXY: "true"', + ' NEKO_MEMBER_PROVIDER: "multiuser"', + f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}", + f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}", + f" NEKO_DESKTOP_SCREEN: {_q(screen)}", + f" NEKO_MAX_FPS: {_q(max_fps)}", + f" NEKO_VIDEO_BITRATE: {_q(bitrate)}", + f" NEKO_WEBRTC_ICELITE: {_q(icelite)}", + f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}", + f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}", + f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}", + f" NEKO_WEBRTC_EPR: {_q(udp)}", + f" NEKO_START_URL: {_q(start_url)}", + f" NEKO_BROWSER_PROXY: {_q(_neko_browser_proxy_value())}", + ' NEKO_BROWSER_RENDER_MODE: "auto"', + f" NEKO_MANAGED_POLICIES: {_q('1' if managed else '0')}", + ' NEKO_TAMPERMONKEY_REPAIR: "1"', + ' NEKO_LIVE_OPS_EXTENSION: "1"', + ' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"', + ' NEKO_TAMPERMONKEY_SEED_DIR: "/etc/neko/tampermonkey-seed"', + " ports:", + f' - "{bind}:{int(http_port)}:8080"', + f' - "{int(mux)}:{int(mux)}/tcp"', + f' - "{int(mux)}:{int(mux)}/udp"', + f' - "{udp}:{udp}/udp"', + " volumes:", + f" - {_q(f'{profile}:/home/neko/.config/chromium')}", + f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}", + f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}", + f" - {_q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}", + f" - {_q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}", + f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}", + f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}", + f" - {_q(f'{instance_id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}", + f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}", + f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}", + f" - {_q(f'{supervisor}:/etc/neko/supervisord/{supervisor_name}:ro')}", + ] + +def _render_compose(count: int) -> str: + # x86 US VPS → google-chrome (sh2); override via DY_NEKO_IMAGE. lines = [ "# Generated by douyinWEB youtube_neko — sh2-aligned assets; 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 = _ensure_profile(idx) - instance_id_file = _ensure_instance_id_file(idx) lines.extend( - [ - f" neko{idx}:", - f" image: {_q(image)}", - ' restart: "no"', - f" shm_size: {_q(shm)}", - " cap_add:", - " - SYS_ADMIN", - " security_opt:", - " - apparmor:unconfined", - " extra_hosts:", - ' - "host.docker.internal:host-gateway"', - f" container_name: {_container_name(idx)}", - " environment:", - f" TZ: {_q(tz)}", - ' DISPLAY: ":99.0"', - ' ENV_DISPLAY: ":99.0"', - ' ENV_USER: "neko"', - ' USER: "neko"', - ' HOME: "/home/neko"', - ' NEKO_CONTAINER_USER: "neko"', - ' NEKO_CONTAINER_HOME: "/home/neko"', - f" NEKO_INSTANCE_ID: {_q(str(idx))}", - ' NEKO_SERVER_BIND: ":8080"', - # Trust X-Forwarded-* from nginx; NO path prefix (nginx strips /neko/N/). - ' NEKO_SERVER_PROXY: "true"', - ' NEKO_MEMBER_PROVIDER: "multiuser"', - f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}", - f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}", - f" NEKO_DESKTOP_SCREEN: {_q(screen)}", - f" NEKO_MAX_FPS: {_q(max_fps)}", - f" NEKO_VIDEO_BITRATE: {_q(bitrate)}", - f" NEKO_WEBRTC_ICELITE: {_q(icelite)}", - f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}", - f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}", - f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}", - f" NEKO_WEBRTC_EPR: {_q(udp)}", - f" NEKO_START_URL: {_q(start_url)}", - # Physical: ShellCrash/住宅 via host.docker.internal; VPS colocated: usually "". - f" NEKO_BROWSER_PROXY: {_q(_neko_browser_proxy_value())}", - ' NEKO_BROWSER_RENDER_MODE: "auto"', - f" NEKO_MANAGED_POLICIES: {_q('1' if managed else '0')}", - ' NEKO_TAMPERMONKEY_REPAIR: "1"', - ' NEKO_LIVE_OPS_EXTENSION: "1"', - ' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"', - ' NEKO_TAMPERMONKEY_SEED_DIR: "/etc/neko/tampermonkey-seed"', - " ports:", - # HTTP bind: 127.0.0.1 on colocated VPS; 0.0.0.0 on physical (WG edge). - f' - "{_http_bind()}:{http_port}:8080"', - # WebRTC must be public (cannot go through nginx/Caddy HTTP). - f' - "{mux}:{mux}/tcp"', - f' - "{mux}:{mux}/udp"', - f' - "{udp}:{udp}/udp"', - " volumes:", - f" - {_q(f'{profile}:/home/neko/.config/chromium')}", - f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}", - f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}", - f" - {_q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}", - f" - {_q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}", - f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}", - f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}", - # Overlay instance id into the extension so telemetry can tag neko-N. - f" - {_q(f'{instance_id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}", - f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}", - f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}", - f" - {_q(f'{supervisor}:/etc/neko/supervisord/{_supervisor_conf_name()}:ro')}", - ] + compose_service_lines( + service_key=f"neko{idx}", + container_name=_container_name(idx), + instance_id_label=str(idx), + http_port=_http_port(idx), + mux=_webrtc_mux(idx), + udp=_udp_range(idx), + profile=_ensure_profile(idx), + instance_id_file=_ensure_instance_id_file(idx), + ) ) return "\n".join(lines) + "\n" @@ -859,6 +1000,26 @@ def sync_caddy_neko_snippet(count: int) -> dict[str, Any]: return {"ok": False, "error": str(exc)} +def _host_http_ok(instance_id: int) -> bool: + """True when published host port answers (detects stale containers with empty PortBindings).""" + port = _http_port(int(instance_id)) + code, text = _run( + [ + "curl", + "-sS", + "-o", + "/dev/null", + "-w", + "%{http_code}", + "--connect-timeout", + "2", + f"http://127.0.0.1:{port}/", + ], + timeout=6, + ) + return code == 0 and (text or "").strip() in {"200", "401", "403"} + + 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"}: @@ -870,29 +1031,50 @@ def instance_action(instance_id: int, action: str) -> dict[str, Any]: message = f"Neko {instance_id}: {before.get('status')}" # Always provision to max assigned id so --remove-orphans cannot wipe siblings. desired = max(instance_id, _desired_from_db()) + name = _container_name(instance_id) + svc = f"neko{int(instance_id)}" if action == "start": ensure_capacity(desired, start_instances={instance_id}) - code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) - if code != 0: - ensure_capacity(desired, start_instances={instance_id}) - code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) + code, out = _run(["docker", "start", name], timeout=60) + if code != 0 or not _host_http_ok(instance_id): + # Stale container (e.g. created while :920x was occupied) — force recreate. + _run(["docker", "rm", "-f", name], timeout=30) + ensure_capacity(desired, start_instances=set()) + code, out = _run( + _compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc), + timeout=300, + ) + if code != 0: + raise RuntimeError(out or "force-recreate 失败") + code, out = _run(["docker", "start", name], timeout=60) if code != 0: raise RuntimeError(out or "启动失败") + if not _host_http_ok(instance_id): + raise RuntimeError( + f"Neko {instance_id} 已启动但主机口 {_http_port(instance_id)} 不可达" + "(检查是否有其它进程占用,或 FRP 辅路误绑 :920x)" + ) 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) + code, out = _run(["docker", "stop", "-t", "10", name], timeout=45) if code != 0: raise RuntimeError(out or "停止失败") message = f"Neko {instance_id} 已停止" elif action == "restart": ensure_capacity(desired, start_instances={instance_id}) - code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90) - if code != 0: - _run(["docker", "rm", "-f", _container_name(instance_id)], timeout=30) - ensure_capacity(desired, start_instances={instance_id}) - code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) + code, out = _run(["docker", "restart", "-t", "8", name], timeout=90) + if code != 0 or not _host_http_ok(instance_id): + _run(["docker", "rm", "-f", name], timeout=30) + ensure_capacity(desired, start_instances=set()) + code, out = _run( + _compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc), + timeout=300, + ) + if code != 0: + raise RuntimeError(out or "force-recreate 失败") + code, out = _run(["docker", "start", name], timeout=60) if code != 0: raise RuntimeError(out or "重启失败") message = f"Neko {instance_id} 已重启" @@ -1073,36 +1255,97 @@ def _payload_is_livestreaming(payload: dict[str, Any] | None) -> bool: return "livestreaming" in url or "livestreaming" in path -def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: - """True when Studio telemetry says this channel is actually live / healthy.""" +def _payload_session_live(payload: dict[str, Any] | None) -> bool: + """YouTube broadcast session is open (LIVE pill / End Stream) — includes 断播.""" body = payload or {} + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + if signals.get("session_live") or signals.get("encoder_lost"): + return True + status = str(body.get("live_status") or "").strip().lower() + if status in {"live", "encoder_lost", "stalled"}: + return True + try: + if body.get("live_duration_sec") is not None and float(body.get("live_duration_sec") or 0) > 0: + return True + except (TypeError, ValueError): + pass + if str(body.get("live_duration") or "").strip(): + return True + text = str(body.get("text") or "").lower() + has_timer = bool(re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}", text)) + has_end = "end stream" in text or "stop streaming" in text or "结束直播" in text + return has_timer and (has_end or "live" in text) + + +def _payload_encoder_lost(payload: dict[str, Any] | None) -> bool: + """断播: session still live but encoder NODATA / will end shortly — not 待开播.""" + body = payload or {} + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + if signals.get("encoder_lost"): + return True + status = str(body.get("live_status") or "").strip().lower() + if status in {"encoder_lost", "stalled"}: + return True + if not _payload_session_live(body): + return False text = str(body.get("text") or "").lower() - # Strong negatives first (preview / encoder not connected). if any( x in text for x in ( - "connect your encoder", + "will end shortly", + "restart it in your streaming software", + "unless you restart", + "即将结束", + "断流", + ) + ): + return True + if signals.get("nodata"): + return True + return "no data" in text or "nodata" in text or "无数据" in text + + +def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: + """True when Studio is 开播 with encoder data (not 待开播, not 断播).""" + body = payload or {} + text = str(body.get("text") or "").lower() + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + status = str(body.get("live_status") or "").strip().lower() + # 断播 / 待开播 are never on-air. + if status in {"encoder_lost", "stalled", "waiting", "ready", "ended", "offline", "signed_out", "streaming"}: + return False + if signals.get("encoder_lost") or _payload_encoder_lost(body): + return False + if signals.get("pending_go_live") and not _payload_session_live(body): + return False + # Bare NODATA without an active LIVE session = 待开播. + if (signals.get("nodata") or "no data" in text or "nodata" in text or "无数据" in text) and not ( + status == "live" and not signals.get("nodata") + ): + if _payload_session_live(body) or status == "live": + return False # 断播 or nodata-while-live + return False + if any( + x in text + for x in ( "waiting for you to start", - "stream offline", - "not streaming", - "no data key", + "待开播", + "start sending us your video", "直播已结束", "未在直播", ) - ): + ) and not _payload_session_live(body): + return False + # "Connect your encoder" alone on a LIVE session = 断播 (already returned False above). + if "connect your encoder" in text and not _payload_session_live(body): return False - status = str(body.get("live_status") or "").strip().lower() health = str(body.get("health") or "").strip().lower() - if status in {"ended", "waiting", "offline"}: - return False - if status in {"live", "streaming"}: + if status == "live": return True - if health in {"excellent", "good"}: - return True - # Concurrent viewers on Control Room almost always means on-air. + # Concurrent viewers > 0 on Control Room ≈ on-air (0 alone is not). try: viewers = body.get("viewer_count") - if viewers is not None and int(viewers) >= 0 and _payload_is_livestreaming(body): + if viewers is not None and int(viewers) > 0 and _payload_is_livestreaming(body): return True except (TypeError, ValueError): pass @@ -1111,24 +1354,50 @@ def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: for x in ( "you're live", "you are live", - "stream is healthy", - "excellent connection", - "concurrent viewers", "watching now", - "stop streaming", - "end stream", "正在直播", "直播中", - "连接状况极佳", - "状况良好", "人正在观看", - "结束直播", ) ): return True + if health in {"excellent", "good"} and any( + x in text for x in ("stream is healthy", "excellent connection", "连接状况极佳", "状况良好") + ): + if _payload_is_livestreaming(body) and "connect your encoder" not in text: + return True return False +def _payload_nodata_or_pending(payload: dict[str, Any] | None) -> bool: + """True only for 待开播 / pre-go-live NODATA — never for 断播 (encoder_lost).""" + body = payload or {} + if _payload_encoder_lost(body) or _payload_session_live(body): + # Session already started: NODATA here is 断播, not 待开播. + return False + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + if signals.get("pending_go_live"): + return True + if signals.get("nodata"): + return True + status = str(body.get("live_status") or "").strip().lower() + if status in {"waiting", "ready", "signed_out", "offline"}: + return True + text = str(body.get("text") or "").lower() + return any( + x in text + for x in ( + "no data", + "nodata", + "无数据", + "待开播", + "connect your encoder", + "start sending us your video", + "waiting for you to start", + ) + ) + + def _cdp_fetch_tabs(instance_id: int) -> list[dict[str, Any]]: """List Chrome tabs via DevTools inside a Neko container.""" name = _container_name(instance_id) @@ -1221,39 +1490,87 @@ def _cdp_studio_page_signals( return row -def _cdp_nudge_live_studio_tab(instance_id: int) -> dict[str, Any]: - """Focus + reload YouTube Live Control Room tab (CDP), like browser-launch.sh.""" - name = _container_name(instance_id) +def studio_live_control_url(youtube_channel_id: str = "", *, fallback: str = "") -> str: + """Canonical Studio Live Control Room URL for a channel (待开播 / 直播控制页).""" + yt = str(youtube_channel_id or "").strip() + if yt.startswith("UC") and len(yt) >= 20: + return f"https://studio.youtube.com/channel/{yt}/livestreaming" + fb = str(fallback or "").strip() + if fb: + return fb + return "https://studio.youtube.com/" + + +def _cdp_ensure_live_studio_in_container( + container_name: str, + *, + studio_url: str = "", +) -> dict[str, Any]: + """Inside a Neko Chrome: focus existing Live tab, or open ``studio_url`` via CDP.""" + name = str(container_name or "").strip() + if not name: + return {"ok": False, "error": "empty_container"} + want = str(studio_url or "").strip() or "https://studio.youtube.com/" + # Keep URL safe for embedding in single-quoted python -c + want_js = json.dumps(want) py = ( - "import json,time,urllib.request\n" + "import json,urllib.parse,urllib.request\n" + f"WANT={want_js}\n" "def fetch():\n" " with urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4) as r:\n" " return json.loads(r.read().decode())\n" "def is_live(u):\n" + " u=(u or '').lower()\n" " return 'studio.youtube.com' in u and 'livestreaming' in u\n" - "for _ in range(8):\n" + "try:\n" + " tabs=fetch()\n" + "except Exception as e:\n" + " print(json.dumps({'ok':False,'error':str(e)})); raise SystemExit(0)\n" + "live=[t for t in tabs if is_live(t.get('url') or '')]\n" + "if live:\n" + " t=live[0]; tid=t.get('id')\n" + " if tid:\n" + " try: urllib.request.urlopen(f'http://127.0.0.1:9222/json/activate/{tid}',timeout=2)\n" + " except Exception: pass\n" + " print(json.dumps({'ok':True,'url':t.get('url',''),'action':'activate'})); raise SystemExit(0)\n" + "q=urllib.parse.quote(WANT, safe='')\n" + "try:\n" + " req=urllib.request.Request('http://127.0.0.1:9222/json/new?'+q, method='PUT')\n" + " with urllib.request.urlopen(req, timeout=8) as r:\n" + " data=json.loads(r.read().decode())\n" + " print(json.dumps({'ok':True,'url':data.get('url',WANT),'action':'open','id':data.get('id')})); raise SystemExit(0)\n" + "except Exception as e:\n" " try:\n" - " tabs=fetch()\n" - " except Exception as e:\n" - " print(json.dumps({'ok':False,'error':str(e)})); raise SystemExit(0)\n" - " live=[t for t in tabs if is_live(t.get('url') or '')]\n" - " if live:\n" - " t=live[0]; tid=t.get('id')\n" - " if tid:\n" - " try: urllib.request.urlopen(f'http://127.0.0.1:9222/json/activate/{tid}',timeout=2)\n" - " except Exception: pass\n" - " print(json.dumps({'ok':True,'url':t.get('url',''),'action':'activate'})); raise SystemExit(0)\n" - " time.sleep(1)\n" - "print(json.dumps({'ok':False,'error':'no_live_tab'}))" + " with urllib.request.urlopen('http://127.0.0.1:9222/json/new?'+q, timeout=8) as r:\n" + " data=json.loads(r.read().decode())\n" + " print(json.dumps({'ok':True,'url':data.get('url',WANT),'action':'open_get'})); raise SystemExit(0)\n" + " except Exception as e2:\n" + " print(json.dumps({'ok':False,'error':str(e2)}))" ) - code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=20) + code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=25) try: row = json.loads((out or "").strip().split("\n")[-1] or "{}") if isinstance(row, dict): return row except json.JSONDecodeError: pass - return {"ok": False, "error": (out or "cdp_nudge_failed")[:200]} + return {"ok": False, "error": (out or f"cdp_ensure_exit_{code}")[:200]} + + +def _cdp_nudge_live_studio_tab(instance_id: int) -> dict[str, Any]: + """Focus existing Live tab or open channel Live Control Room (local assign Neko).""" + name = _container_name(instance_id) + studio_url = "" + try: + from . import yt_assign_db + + for g in yt_assign_db.list_groups(include_urls=False): + if int(g.get("neko_instance_id") or 0) == int(instance_id): + studio_url = studio_live_control_url(str(g.get("youtube_channel_id") or "")) + break + except Exception: + studio_url = "" + return _cdp_ensure_live_studio_in_container(name, studio_url=studio_url) def latest_live_studio_event( @@ -1403,9 +1720,10 @@ def wait_instance_ready_for_live( detect_url = "" # 1) Chrome extension telemetry (preferred when ingest works) - ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since) + # Strict: only events tagged for THIS local instance (never share siblings). + ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since, neko_id=idx) if ev is None: - ev = latest_live_studio_event(max_age_sec=20.0, since_ts=wait_since - 5.0) + ev = latest_live_studio_event(max_age_sec=20.0, since_ts=wait_since - 5.0, neko_id=idx) if ev is not None: last_ev = ev page_detected = True @@ -1482,6 +1800,130 @@ def wait_instance_ready_for_live( } +def wait_group_ready_for_live( + group: dict[str, Any] | None, + *, + timeout_sec: float = 120.0, + settle_sec: float = 20.0, + strict: bool = True, +) -> dict[str, Any]: + """Wait for the group's preferred Neko (local or remote ops) Live Control Room. + + Design: once bind is confirmed, Chrome must have YouTube Live tab open (待开播). + Prefer remote ops-neko when ``neko_open_prefer=remote`` and ops URL/slot are set. + """ + import time as _time + + g = group if isinstance(group, dict) else {} + prefer = str(g.get("neko_open_prefer") or "local").strip().lower() + remote_bound = bool(str(g.get("ops_neko_open_url") or "").strip()) + ops_slot = int(g.get("ops_neko_slot") or 0) + local_id = int(g.get("neko_instance_id") or 0) + yt_id = str(g.get("youtube_channel_id") or "").strip() + studio_url = studio_live_control_url(yt_id) + + use_remote = prefer == "remote" and remote_bound and ops_slot > 0 + if use_remote: + wait_since = _time.time() + settle_need = max(8.0, float(settle_sec)) + deadline = wait_since + max(settle_need + 20.0, float(timeout_sec)) + page_first_seen = 0.0 + last_url = "" + last_nudge: dict[str, Any] = {} + nudge_at = 0.0 + while _time.time() < deadline: + now = _time.time() + # Edge host: open Live tab via CDP. Hub (VPS) only waits on mirrored telemetry. + if now - nudge_at >= 8.0: + nudge_at = now + try: + from . import ops_neko + from . import ops_neko_db + + if str(ops_neko_db.peer_status().get("role") or "") == "edge": + last_nudge = ops_neko.ensure_slot_live_studio( + ops_slot, youtube_channel_id=yt_id + ) + else: + last_nudge = {"ok": True, "skipped": "hub_waits_edge_sync"} + except Exception as exc: + last_nudge = {"ok": False, "error": str(exc)[:160]} + snap = studio_snapshot_for_ref(f"ops:{ops_slot}", max_age_sec=45.0) + page_open = bool(snap.get("live_page_open")) or ( + "livestreaming" in str(snap.get("url") or "").lower() + ) + # Also accept fresh mirrored telemetry event + if not page_open: + ev = None + if f"ops:{ops_slot}" in _studio_latest_by_ref: + ev = _studio_latest_by_ref.get(f"ops:{ops_slot}") + if ev and (_time.time() - float(ev.get("received_at") or 0)) <= 45.0: + payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + if _payload_is_livestreaming(payload): + page_open = True + last_url = str(payload.get("url") or "") + if page_open: + if not page_first_seen: + page_first_seen = now + last_url = last_url or str(snap.get("url") or "") + if now - page_first_seen >= settle_need: + return { + "ok": True, + "neko_kind": "ops", + "ops_slot": ops_slot, + "live_studio": True, + "settled": True, + "settle_sec": round(now - page_first_seen, 1), + "url": (last_url or studio_url)[:200], + "detect_source": str(snap.get("detect_source") or "ops_telemetry"), + "live_status": str(snap.get("live_status") or ""), + "health": str(snap.get("health") or ""), + "nudge": last_nudge, + "wait_since": wait_since, + } + _time.sleep(2.0) + page_open = page_first_seen > 0 + err = ( + f"远程 Ops Neko #{ops_slot} YouTube Live 控制页未在时限内稳定打开" + if not page_open + else f"远程 Ops Neko #{ops_slot} Live 页已打开,但未稳定满 {int(settle_need)}s" + ) + if strict: + return { + "ok": False, + "neko_kind": "ops", + "ops_slot": ops_slot, + "live_studio": bool(page_open), + "timeout": True, + "error": err, + "nudge": last_nudge, + "wait_since": wait_since, + "url": studio_url, + } + return { + "ok": True, + "neko_kind": "ops", + "ops_slot": ops_slot, + "live_studio": bool(page_open), + "timeout": True, + "note": "ops_soft_timeout", + "nudge": last_nudge, + } + + if local_id > 0: + out = wait_instance_ready_for_live( + local_id, + timeout_sec=timeout_sec, + require_live_page=True, + settle_sec=settle_sec, + strict=strict, + ) + out["neko_kind"] = "local" + out["neko_instance_id"] = local_id + return out + return {"ok": True, "skipped": "no_neko_bind", "neko_kind": "none"} + + def restore_enabled_instances() -> dict[str, Any]: """Start all neko_enabled assign groups (after exclusive-live release).""" from . import yt_assign_db @@ -1530,17 +1972,85 @@ def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]: _studio_events: list[dict[str, Any]] = [] _STUDIO_EVENTS_MAX = 200 _studio_latest_by_neko: dict[int, dict[str, Any]] = {} +_studio_latest_by_ref: dict[str, dict[str, Any]] = {} _studio_minute_reports: dict[int, list[dict[str, Any]]] = {} +_studio_minute_reports_by_ref: dict[str, list[dict[str, Any]]] = {} _studio_minute_last_at: dict[int, float] = {} +_studio_minute_last_at_by_ref: dict[str, float] = {} _STUDIO_MINUTE_MAX = 120 _studio_bootstrapped = False _CDP_POLL_INTERVAL_SEC = 55.0 -def _minute_report_dir() -> Path: - d = _neko_root() / "studio_minute" - d.mkdir(parents=True, exist_ok=True) - return d +def parse_neko_ref(raw: Any) -> tuple[str, str, int]: + """Return (kind, ref_key, local_int). kind is local|remote; ref_key like local:3 / ops:1.""" + text = str(raw or "").strip() + if not text: + return "local", "", 0 + low = text.lower() + if low.startswith("ops-") or low.startswith("ops:"): + digits = "".join(ch for ch in low.split("-", 1)[-1].split(":", 1)[-1] if ch.isdigit()) + try: + slot = int(digits or 0) + except ValueError: + slot = 0 + if slot > 0: + return "remote", f"ops:{slot}", 0 + try: + nid = int(float(text)) if text.replace(".", "", 1).isdigit() or text.isdigit() else int(text) + except (TypeError, ValueError): + nid = 0 + if nid > 0: + return "local", f"local:{nid}", nid + return "local", "", 0 + + +def _group_for_neko_ref(*, kind: str, local_id: int = 0, ops_slot: int = 0) -> dict[str, Any] | None: + try: + from . import yt_assign_db + + groups = yt_assign_db.list_groups(include_urls=False) + except Exception: + return None + if kind == "remote" and ops_slot > 0: + for g in groups: + if int(g.get("ops_neko_slot") or 0) == ops_slot and str(g.get("ops_neko_open_url") or "").strip(): + return g + return None + if local_id > 0: + for g in groups: + if int(g.get("neko_instance_id") or 0) == local_id: + return g + return None + + +def _enrich_context_for_group(group: dict[str, Any] | None) -> dict[str, Any]: + """Attach YouTube channel + current Douyin relay source for analytics joins.""" + out: dict[str, Any] = { + "group_id": "", + "channel_pk": "", + "youtube_channel_id": "", + "source_room_id": "", + "source_url": "", + "anchor_name": "", + "relay_session_uuid": "", + } + if not group: + return out + gid = str(group.get("id") or "") + out["group_id"] = gid + out["channel_pk"] = str(group.get("channel_pk") or "") + out["youtube_channel_id"] = str(group.get("youtube_channel_id") or "") + try: + from . import youtube_relay_db + + st = youtube_relay_db.get_relay_state(gid) or {} + out["source_room_id"] = str(st.get("source_room_id") or "") + out["source_url"] = str(st.get("source_url") or "") + out["anchor_name"] = str(st.get("anchor_name") or "") + except Exception: + pass + return out def _persist_minute_report(neko_id: int, report: dict[str, Any]) -> None: @@ -1555,6 +2065,24 @@ def _persist_minute_report(neko_id: int, report: dict[str, Any]) -> None: pass +def _persist_minute_report_ref(ref_key: str, report: dict[str, Any]) -> None: + key = str(ref_key or "").strip().replace(":", "_") + if not key: + return + try: + path = _minute_report_dir() / f"{key}.jsonl" + with path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(report, ensure_ascii=False) + "\n") + except OSError: + pass + + +def _minute_report_dir() -> Path: + d = _neko_root() / "studio_minute" + d.mkdir(parents=True, exist_ok=True) + return d + + def _bootstrap_minute_reports_from_disk() -> None: """Load recent per-neko minute reports after API restart.""" try: @@ -1562,12 +2090,14 @@ def _bootstrap_minute_reports_from_disk() -> None: except Exception: return for path in root.glob("*.jsonl"): - try: - nid = int(path.stem) - except ValueError: - continue - if nid < 1: - continue + stem = path.stem + kind, ref_key, nid = parse_neko_ref(stem.replace("_", ":", 1) if stem.startswith("ops_") or stem.startswith("local_") else stem) + if not ref_key and nid < 1: + try: + nid = int(stem) + kind, ref_key, nid = "local", f"local:{nid}", nid + except ValueError: + continue rows: list[dict[str, Any]] = [] try: lines = path.read_text(encoding="utf-8").splitlines() @@ -1586,11 +2116,18 @@ def _bootstrap_minute_reports_from_disk() -> None: if not rows: continue rows.reverse() # newest first - _studio_minute_reports[nid] = rows[:_STUDIO_MINUTE_MAX] - try: - _studio_minute_last_at[nid] = float(rows[0].get("ts") or 0) - except (TypeError, ValueError): - pass + if ref_key: + _studio_minute_reports_by_ref[ref_key] = rows[:_STUDIO_MINUTE_MAX] + try: + _studio_minute_last_at_by_ref[ref_key] = float(rows[0].get("ts") or 0) + except (TypeError, ValueError): + pass + if nid > 0: + _studio_minute_reports[nid] = rows[:_STUDIO_MINUTE_MAX] + try: + _studio_minute_last_at[nid] = float(rows[0].get("ts") or 0) + except (TypeError, ValueError): + pass def _bootstrap_studio_telemetry_from_disk() -> None: @@ -1632,16 +2169,13 @@ def _extract_studio_video_id(url: str) -> str: return str(m.group(1) if m else "").strip() -def _resolve_neko_id_for_payload(payload: dict[str, Any]) -> int: - """Tag telemetry to a Neko instance via explicit id, assign studio URL, or CDP.""" +def _resolve_neko_ref_for_payload(payload: dict[str, Any]) -> tuple[str, str, int]: + """Resolve (kind, ref_key, local_id) from extension/CDP payload.""" body = payload or {} - for key in ("neko_instance_id", "neko_id", "instance_id"): - try: - nid = int(body.get(key) or 0) - if nid > 0: - return nid - except (TypeError, ValueError): - pass + for key in ("neko_ref", "neko_instance_id", "neko_id", "instance_id"): + kind, ref_key, nid = parse_neko_ref(body.get(key)) + if ref_key: + return kind, ref_key, nid url = str(body.get("url") or "") video_id = _extract_studio_video_id(url) @@ -1657,32 +2191,41 @@ def _resolve_neko_id_for_payload(payload: dict[str, Any]) -> int: continue studio = str(g.get("neko_studio_url") or "") if video_id and video_id in studio: - return nid + return "local", f"local:{nid}", nid if url and studio and (studio.rstrip("/") in url or url.rstrip("/") in studio): - return nid + return "local", f"local:{nid}", nid + remote = str(g.get("ops_neko_open_url") or "") + slot = int(g.get("ops_neko_slot") or 0) + if slot > 0 and remote and url and (remote.rstrip("/") in url or url.rstrip("/") in remote): + return "remote", f"ops:{slot}", 0 except Exception: pass - - if not _payload_is_livestreaming(body): - return 0 - # CDP attribution is expensive; rely on instance_id.txt + assign studio URL match. - return 0 + return "local", "", 0 -def _maybe_append_minute_report(neko_id: int, event: dict[str, Any]) -> None: +def _resolve_neko_id_for_payload(payload: dict[str, Any]) -> int: + """Tag telemetry to a local Neko instance id (0 when ops-only).""" + _kind, _ref, nid = _resolve_neko_ref_for_payload(payload) + return int(nid or 0) + + +def _maybe_append_minute_report(neko_id: int, event: dict[str, Any], *, ref_key: str = "", kind: str = "local") -> None: import time as _time nid = int(neko_id or 0) - if nid < 1: + key = str(ref_key or (f"local:{nid}" if nid > 0 else "")).strip() + if not key and nid < 1: return now = float(event.get("received_at") or _time.time()) - last = float(_studio_minute_last_at.get(nid) or 0) + last = float(_studio_minute_last_at_by_ref.get(key) or _studio_minute_last_at.get(nid) or 0) if last and (now - last) < 55.0: return payload = event.get("payload") if isinstance(event.get("payload"), dict) else {} report = { "ts": int(now), "neko_instance_id": nid, + "neko_ref": key, + "neko_kind": kind if kind in {"local", "remote"} else ("remote" if key.startswith("ops:") else "local"), "live_page_open": bool(_payload_is_livestreaming(payload)), "on_air": bool(_payload_stream_confirmed(payload)), "live_status": str(payload.get("live_status") or ""), @@ -1696,34 +2239,101 @@ def _maybe_append_minute_report(neko_id: int, event: dict[str, Any]) -> None: "url": str(payload.get("url") or "")[:200], "source": str(payload.get("source") or "extension")[:32], } - bucket = _studio_minute_reports.setdefault(nid, []) - bucket.insert(0, report) - del bucket[_STUDIO_MINUTE_MAX:] - _studio_minute_last_at[nid] = now - _persist_minute_report(nid, report) + if key: + bucket = _studio_minute_reports_by_ref.setdefault(key, []) + bucket.insert(0, report) + del bucket[_STUDIO_MINUTE_MAX:] + _studio_minute_last_at_by_ref[key] = now + _persist_minute_report_ref(key, report) + if nid > 0: + bucket2 = _studio_minute_reports.setdefault(nid, []) + bucket2.insert(0, report) + del bucket2[_STUDIO_MINUTE_MAX:] + _studio_minute_last_at[nid] = now + _persist_minute_report(nid, report) + + # Analytics DB: Douyin room ↔ YT channel ↔ Neko dimensions + try: + from . import yt_studio_db + + ops_slot = 0 + if key.startswith("ops:"): + try: + ops_slot = int(key.split(":", 1)[1]) + except ValueError: + ops_slot = 0 + group = _group_for_neko_ref(kind=report["neko_kind"], local_id=nid, ops_slot=ops_slot) + ctx = _enrich_context_for_group(group) + peak = None + try: + vals = [ + int(r.get("viewer_count")) + for r in (bucket if key else bucket2) + if r.get("viewer_count") is not None + ] + peak = max(vals) if vals else None + except Exception: + peak = None + yt_studio_db.insert_sample( + ts=now, + group_id=ctx["group_id"], + channel_pk=ctx["channel_pk"], + youtube_channel_id=ctx["youtube_channel_id"], + source_room_id=ctx["source_room_id"], + source_url=ctx["source_url"], + anchor_name=ctx["anchor_name"], + neko_kind=report["neko_kind"], + neko_ref=key, + live_page_open=bool(report["live_page_open"]), + on_air=bool(report["on_air"]), + live_status=str(report["live_status"] or ""), + health=str(report["health"] or ""), + viewer_count=report.get("viewer_count"), + total_views=report.get("total_views"), + like_count=report.get("like_count"), + live_duration_sec=report.get("live_duration_sec"), + live_duration=str(report.get("live_duration") or ""), + stream_title=str(report.get("stream_title") or ""), + studio_url=str(report.get("url") or ""), + detect_source=str(report.get("source") or ""), + peak_viewers=peak, + relay_session_uuid=ctx.get("relay_session_uuid") or "", + ) + except Exception: + pass def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: - """Accept Studio telemetry from in-container Chrome extension.""" + """Accept Studio telemetry from in-container Chrome extension (local or ops-neko).""" import time as _time import uuid _bootstrap_studio_telemetry_from_disk() body = dict(payload or {}) - neko_id = _resolve_neko_id_for_payload(body) + kind, ref_key, neko_id = _resolve_neko_ref_for_payload(body) if neko_id > 0: body["neko_instance_id"] = neko_id + if ref_key: + body["neko_ref"] = ref_key + body["neko_kind"] = kind event = { "id": str(uuid.uuid4()), "received_at": float(body.get("received_at") or _time.time()), "neko_instance_id": neko_id, + "neko_ref": ref_key, + "neko_kind": kind, "payload": body, } _studio_events.insert(0, event) del _studio_events[_STUDIO_EVENTS_MAX:] + if ref_key: + _studio_latest_by_ref[ref_key] = event + _maybe_append_minute_report(neko_id, event, ref_key=ref_key, kind=kind) + elif neko_id > 0: + _studio_latest_by_neko[neko_id] = event + _maybe_append_minute_report(neko_id, event, ref_key=f"local:{neko_id}", kind="local") if neko_id > 0: _studio_latest_by_neko[neko_id] = event - _maybe_append_minute_report(neko_id, event) try: path = _neko_root() / "studio_telemetry_latest.json" path.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8") @@ -1731,7 +2341,13 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: pass return { "ok": True, - "event": {"id": event["id"], "neko_instance_id": neko_id}, + "event": { + "id": event["id"], + "received_at": event["received_at"], + "neko_instance_id": neko_id, + "neko_ref": ref_key, + "neko_kind": kind, + }, } @@ -1740,19 +2356,252 @@ def latest_studio_telemetry(*, limit: int = 20) -> list[dict[str, Any]]: return list(_studio_events[: max(1, min(100, int(limit)))]) -def list_studio_minute_reports(neko_id: int = 0, *, limit: int = 30) -> list[dict[str, Any]]: +def list_studio_minute_reports(neko_id: int = 0, *, limit: int = 30, neko_ref: str = "") -> list[dict[str, Any]]: _bootstrap_studio_telemetry_from_disk() - nid = int(neko_id or 0) lim = max(1, min(120, int(limit))) + key = str(neko_ref or "").strip() + if key: + return list(_studio_minute_reports_by_ref.get(key, [])[:lim]) + nid = int(neko_id or 0) if nid > 0: return list(_studio_minute_reports.get(nid, [])[:lim]) out: list[dict[str, Any]] = [] + for rows in _studio_minute_reports_by_ref.values(): + out.extend(rows) for rows in _studio_minute_reports.values(): out.extend(rows) out.sort(key=lambda r: float(r.get("ts") or 0), reverse=True) return out[:lim] +def studio_snapshot_for_ref( + ref_key: str, + *, + max_age_sec: float = 90.0, + local_id: int = 0, +) -> dict[str, Any]: + """UI snapshot by neko_ref (local:N or ops:N).""" + import time as _time + + key = str(ref_key or "").strip() + kind, key2, nid = parse_neko_ref(key) + if key2: + key = key2 + if local_id > 0 and not key: + key = f"local:{local_id}" + nid = local_id + kind = "local" + now = _time.time() + out: dict[str, Any] = { + "neko_instance_id": nid, + "neko_ref": key, + "neko_kind": kind, + "live_page_open": False, + "on_air": False, + "live_status": "", + "health": "", + "viewer_count": None, + "like_count": None, + "total_views": None, + "live_duration": "", + "live_duration_sec": None, + "stream_title": "", + "url": "", + "received_at": 0.0, + "age_sec": None, + "detect_source": "", + "minute_reports": list_studio_minute_reports(nid, limit=90, neko_ref=key) if key else [], + } + if not key: + return out + _bootstrap_studio_telemetry_from_disk() + ev = _studio_latest_by_ref.get(key) + if not isinstance(ev, dict) and nid > 0: + ev = _studio_latest_by_neko.get(nid) + if isinstance(ev, dict): + received0 = float(ev.get("received_at") or 0) + if received0 and (now - received0) > max_age_sec: + ev = None + if isinstance(ev, dict): + received = float(ev.get("received_at") or 0) + age = (now - received) if received else None + if age is None or age <= max_age_sec: + payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + page_open = _payload_is_livestreaming(payload) + on_air = _payload_stream_confirmed(payload) if page_open else False + encoder_lost = _payload_encoder_lost(payload) if page_open else False + session_live = _payload_session_live(payload) if page_open else False + signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {} + encoder_receiving = bool(signals.get("encoder_receiving")) or ( + on_air and not encoder_lost + ) + out.update( + { + "live_page_open": page_open, + "on_air": on_air, + "encoder_lost": encoder_lost, + "encoder_receiving": encoder_receiving, + "session_live": session_live, + "live_status": str(payload.get("live_status") or ""), + "health": str(payload.get("health") or ""), + "viewer_count": payload.get("viewer_count"), + "like_count": payload.get("like_count"), + "total_views": payload.get("total_views"), + "live_duration": str(payload.get("live_duration") or "")[:16], + "live_duration_sec": payload.get("live_duration_sec"), + "stream_title": str(payload.get("stream_title") or "")[:120], + "url": str(payload.get("url") or "")[:200], + "received_at": received, + "age_sec": round(age, 1) if age is not None else None, + "detect_source": str(payload.get("source") or ev.get("neko_kind") or "telemetry"), + } + ) + return out + + +def studio_snapshot_for_group(group: dict[str, Any] | None, *, max_age_sec: float = 120.0) -> dict[str, Any]: + """Prefer remote ops telemetry when group opens remote Neko; else local assign Neko.""" + empty = { + "neko_instance_id": 0, + "neko_ref": "", + "neko_kind": "local", + "live_page_open": False, + "on_air": False, + "live_status": "", + "health": "", + "viewer_count": None, + "like_count": None, + "total_views": None, + "live_duration": "", + "live_duration_sec": None, + "stream_title": "", + "url": "", + "received_at": 0.0, + "age_sec": None, + "detect_source": "", + "minute_reports": [], + "ui_source": "none", + } + if not group: + return empty + prefer = str(group.get("neko_open_prefer") or group.get("neko_open_source") or "local").strip().lower() + remote_bound = bool(str(group.get("ops_neko_open_url") or "").strip()) + ops_slot = int(group.get("ops_neko_slot") or 0) + local_id = int(group.get("neko_instance_id") or 0) + + remote_snap = None + if remote_bound and ops_slot > 0: + remote_snap = studio_snapshot_for_ref(f"ops:{ops_slot}", max_age_sec=max_age_sec) + remote_snap["ui_source"] = "remote" + local_snap = None + if local_id > 0: + local_snap = studio_snapshot_for_instance(local_id, max_age_sec=max_age_sec) + local_snap["neko_ref"] = f"local:{local_id}" + local_snap["neko_kind"] = "local" + local_snap["ui_source"] = "local" + + def _fresh(snap: dict[str, Any] | None) -> bool: + if not isinstance(snap, dict): + return False + age = snap.get("age_sec") + if age is None: + return bool(snap.get("live_page_open") or snap.get("on_air") or snap.get("received_at")) + try: + return float(age) <= float(max_age_sec) + except (TypeError, ValueError): + return False + + if prefer == "remote" and remote_bound: + if _fresh(remote_snap): + return remote_snap or empty + if _fresh(local_snap): + # Fall back to local if remote quiet + out = dict(local_snap or empty) + out["ui_source"] = "local_fallback" + return out + return remote_snap or local_snap or empty + + if _fresh(local_snap): + return local_snap or empty + if _fresh(remote_snap): + out = dict(remote_snap or empty) + out["ui_source"] = "remote_fallback" + return out + return local_snap or remote_snap or empty + + +def ingest_remote_studio_mirror(slot: int, studio: dict[str, Any] | None) -> dict[str, Any]: + """Hub-side: accept studio snapshot pushed from physical edge catalog sync.""" + import time as _time + + slot_i = int(slot or 0) + if slot_i < 1 or not isinstance(studio, dict): + return {"ok": False, "skipped": True} + raw_status = str(studio.get("live_status") or "").strip().lower() + # Never invent "streaming"/"live" from page_open alone — that caused false on_air on hub. + if raw_status in {"ready", "streaming"}: + raw_status = "waiting" + on_air = bool(studio.get("on_air")) + page_open = bool(studio.get("live_page_open") or on_air or studio.get("session_live")) + encoder_lost = bool(studio.get("encoder_lost")) or raw_status in {"encoder_lost", "stalled"} + session_live = bool(studio.get("session_live")) or encoder_lost or raw_status in {"live", "encoder_lost"} + nodata = bool(studio.get("nodata")) + if on_air and not raw_status: + raw_status = "live" + elif encoder_lost and raw_status not in {"encoder_lost", "stalled"}: + raw_status = "encoder_lost" + elif page_open and not raw_status: + raw_status = "waiting" + url = str(studio.get("url") or "").strip() + # Refuse synthetic placeholder URLs that only exist to satisfy livestreaming helpers. + if "/video/x/livestreaming" in url.lower(): + url = "" + signals: dict[str, Any] = {"path": "/livestreaming"} if page_open else {} + if nodata: + signals["nodata"] = True + if encoder_lost: + signals["encoder_lost"] = True + signals["session_live"] = True + signals["pending_go_live"] = False + elif session_live or on_air: + signals["session_live"] = True + signals["pending_go_live"] = False + elif page_open and not on_air: + signals["pending_go_live"] = True + if raw_status in {"waiting", "signed_out", "offline"} and not session_live and not encoder_lost: + signals["pending_go_live"] = True + payload = { + "neko_ref": f"ops-{slot_i}", + "neko_instance_id": f"ops-{slot_i}", + "source": str(studio.get("detect_source") or "edge_sync"), + "live_status": raw_status, + "health": studio.get("health") or "", + "viewer_count": studio.get("viewer_count"), + "total_views": studio.get("total_views"), + "like_count": studio.get("like_count"), + "live_duration": studio.get("live_duration") or "", + "live_duration_sec": studio.get("live_duration_sec"), + "stream_title": studio.get("stream_title") or "", + "url": url, + "received_at": studio.get("received_at") or _time.time(), + "signals": signals, + "text": str(studio.get("text") or "")[:2200], + } + out = ingest_studio_telemetry(payload) + # Also seed minute reports if edge included them + reports = studio.get("minute_reports") if isinstance(studio.get("minute_reports"), list) else [] + key = f"ops:{slot_i}" + if reports: + cleaned = [r for r in reports if isinstance(r, dict)][:_STUDIO_MINUTE_MAX] + if cleaned: + _studio_minute_reports_by_ref[key] = cleaned + try: + _studio_minute_last_at_by_ref[key] = float(cleaned[0].get("ts") or 0) + except (TypeError, ValueError): + pass + return out + + def studio_snapshot_for_instance( neko_id: int, *, @@ -1801,10 +2650,14 @@ def studio_snapshot_for_instance( payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} page_open = _payload_is_livestreaming(payload) on_air = _payload_stream_confirmed(payload) if page_open else False + encoder_lost = _payload_encoder_lost(payload) if page_open else False + session_live = _payload_session_live(payload) if page_open else False out.update( { "live_page_open": page_open, "on_air": on_air, + "encoder_lost": encoder_lost, + "session_live": session_live, "live_status": str(payload.get("live_status") or ""), "health": str(payload.get("health") or ""), "viewer_count": payload.get("viewer_count"), diff --git a/backend/app/yt_studio_db.py b/backend/app/yt_studio_db.py new file mode 100644 index 0000000..9e613f0 --- /dev/null +++ b/backend/app/yt_studio_db.py @@ -0,0 +1,249 @@ +# -*- coding: utf-8 -*- +"""YouTube Studio live metrics samples — analytics store. + +Links: Douyin room ↔ assign group / YouTube channel ↔ Neko (local|remote). +Samples are appended ~1/min from extension/CDP ingest (and hub mirrors of ops-neko). +""" +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_studio_tables(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS yt_studio_samples ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts REAL NOT NULL, + group_id TEXT NOT NULL DEFAULT '', + channel_pk TEXT NOT NULL DEFAULT '', + youtube_channel_id TEXT NOT NULL DEFAULT '', + source_room_id TEXT NOT NULL DEFAULT '', + source_url TEXT NOT NULL DEFAULT '', + anchor_name TEXT NOT NULL DEFAULT '', + neko_kind TEXT NOT NULL DEFAULT 'local', + neko_ref TEXT NOT NULL DEFAULT '', + live_page_open INTEGER NOT NULL DEFAULT 0, + on_air INTEGER NOT NULL DEFAULT 0, + live_status TEXT NOT NULL DEFAULT '', + health TEXT NOT NULL DEFAULT '', + viewer_count INTEGER, + total_views INTEGER, + like_count INTEGER, + live_duration_sec REAL, + live_duration TEXT NOT NULL DEFAULT '', + stream_title TEXT NOT NULL DEFAULT '', + studio_url TEXT NOT NULL DEFAULT '', + detect_source TEXT NOT NULL DEFAULT '', + peak_viewers INTEGER, + relay_session_uuid TEXT NOT NULL DEFAULT '', + meta_json TEXT NOT NULL DEFAULT '{}', + created_at REAL NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_studio_ts ON yt_studio_samples(ts DESC)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_studio_group ON yt_studio_samples(group_id, ts DESC)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_studio_channel ON yt_studio_samples(youtube_channel_id, ts DESC)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_studio_room ON yt_studio_samples(source_room_id, ts DESC)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_studio_neko ON yt_studio_samples(neko_ref, ts DESC)" + ) + + +def _ensure() -> None: + with _lock: + conn = _connect() + try: + ensure_yt_studio_tables(conn) + conn.commit() + finally: + conn.close() + + +def insert_sample( + *, + ts: float | None = None, + group_id: str = "", + channel_pk: str = "", + youtube_channel_id: str = "", + source_room_id: str = "", + source_url: str = "", + anchor_name: str = "", + neko_kind: str = "local", + neko_ref: str = "", + live_page_open: bool = False, + on_air: bool = False, + live_status: str = "", + health: str = "", + viewer_count: Any = None, + total_views: Any = None, + like_count: Any = None, + live_duration_sec: Any = None, + live_duration: str = "", + stream_title: str = "", + studio_url: str = "", + detect_source: str = "", + peak_viewers: Any = None, + relay_session_uuid: str = "", + meta: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + """Persist one analytics sample. Returns the stored row dict.""" + _ensure() + now = time.time() + t = float(ts if ts is not None else now) + + def _int_or_none(v: Any) -> int | None: + if v is None or v == "": + return None + try: + return int(v) + except (TypeError, ValueError): + return None + + def _float_or_none(v: Any) -> float | None: + if v is None or v == "": + return None + try: + return float(v) + except (TypeError, ValueError): + return None + + kind = str(neko_kind or "local").strip().lower() + if kind not in {"local", "remote"}: + kind = "local" + row_vals = ( + t, + str(group_id or "")[:80], + str(channel_pk or "")[:80], + str(youtube_channel_id or "")[:80], + str(source_room_id or "")[:64], + str(source_url or "")[:500], + str(anchor_name or "")[:120], + kind, + str(neko_ref or "")[:40], + 1 if live_page_open else 0, + 1 if on_air else 0, + str(live_status or "")[:40], + str(health or "")[:40], + _int_or_none(viewer_count), + _int_or_none(total_views), + _int_or_none(like_count), + _float_or_none(live_duration_sec), + str(live_duration or "")[:16], + str(stream_title or "")[:200], + str(studio_url or "")[:400], + str(detect_source or "")[:40], + _int_or_none(peak_viewers), + str(relay_session_uuid or "")[:80], + json.dumps(meta or {}, ensure_ascii=False)[:2000], + now, + ) + with _lock: + conn = _connect() + try: + ensure_yt_studio_tables(conn) + cur = conn.execute( + """ + INSERT INTO yt_studio_samples( + ts, group_id, channel_pk, youtube_channel_id, source_room_id, source_url, + anchor_name, neko_kind, neko_ref, live_page_open, on_air, live_status, health, + viewer_count, total_views, like_count, live_duration_sec, live_duration, + stream_title, studio_url, detect_source, peak_viewers, relay_session_uuid, + meta_json, created_at + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + """, + row_vals, + ) + conn.commit() + rid = int(cur.lastrowid or 0) + row = conn.execute("SELECT * FROM yt_studio_samples WHERE id = ?", (rid,)).fetchone() + return _public_sample(_row_to_dict(row) if row else {"id": rid}) + finally: + conn.close() + + +def _public_sample(row: dict[str, Any]) -> dict[str, Any]: + out = dict(row) + out["live_page_open"] = bool(out.get("live_page_open")) + out["on_air"] = bool(out.get("on_air")) + meta = out.pop("meta_json", "{}") + try: + out["meta"] = json.loads(meta) if meta else {} + except json.JSONDecodeError: + out["meta"] = {} + return out + + +def list_samples( + *, + group_id: str = "", + youtube_channel_id: str = "", + source_room_id: str = "", + neko_ref: str = "", + since_ts: float = 0, + limit: int = 200, +) -> list[dict[str, Any]]: + _ensure() + lim = max(1, min(2000, int(limit))) + clauses: list[str] = [] + args: list[Any] = [] + if group_id: + clauses.append("group_id = ?") + args.append(str(group_id).strip()) + if youtube_channel_id: + clauses.append("youtube_channel_id = ?") + args.append(str(youtube_channel_id).strip()) + if source_room_id: + clauses.append("source_room_id = ?") + args.append(str(source_room_id).strip()) + if neko_ref: + clauses.append("neko_ref = ?") + args.append(str(neko_ref).strip()) + if since_ts > 0: + clauses.append("ts >= ?") + args.append(float(since_ts)) + where = (" WHERE " + " AND ".join(clauses)) if clauses else "" + with _lock: + conn = _connect() + try: + ensure_yt_studio_tables(conn) + rows = conn.execute( + f"SELECT * FROM yt_studio_samples{where} ORDER BY ts DESC LIMIT ?", + (*args, lim), + ).fetchall() + return [_public_sample(_row_to_dict(r)) for r in rows] + finally: + conn.close() + + +def session_stats_for_group(group_id: str, *, since_ts: float = 0) -> dict[str, Any]: + """Aggregate peak/avg/now viewers for a group window (analytics helper).""" + rows = list_samples(group_id=group_id, since_ts=since_ts, limit=500) + vals = [int(r["viewer_count"]) for r in rows if r.get("viewer_count") is not None] + totals = [int(r["total_views"]) for r in rows if r.get("total_views") is not None] + peak = max(vals) if vals else None + avg = round(sum(vals) / len(vals), 1) if vals else None + now_v = vals[0] if vals else None + return { + "group_id": group_id, + "sample_count": len(rows), + "peak_viewers": peak, + "avg_viewers": avg, + "viewer_count": now_v, + "total_views": totals[0] if totals else None, + "neko_kinds": sorted({str(r.get("neko_kind") or "") for r in rows if r.get("neko_kind")}), + } diff --git a/backend/neko/cdp_studio_scrape.py b/backend/neko/cdp_studio_scrape.py index d052059..4012c0a 100644 --- a/backend/neko/cdp_studio_scrape.py +++ b/backend/neko/cdp_studio_scrape.py @@ -161,21 +161,46 @@ def main() -> None: pass lower = text.lower() + nodata = bool( + re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower) + ) + session_live = bool( + re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?", lower) + or re.search(r"(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}", text) + ) and ( + bool(re.search(r"end stream|stop streaming|结束直播|停止直播", lower)) + or bool(re.search(r"\blive\b", lower)) + ) + encoder_lost_hint = bool( + re.search( + r"will end shortly|restart it in your streaming software|unless you restart|" + r"即将结束|请重新|重新启动|推流软件|断流", + lower, + ) + ) + status = "" - if re.search(r"stream ended|not live|offline|直播已结束|未在直播", lower): + if re.search(r"stream ended|直播已结束", lower) and not session_live: status = "ended" - elif re.search( + elif session_live and (nodata or encoder_lost_hint): + # 断播: LIVE session still open, encoder dropped — NOT 待开播 + status = "encoder_lost" + elif session_live or re.search( r"you.?re live|you are live|stream is healthy|excellent connection|" - r"concurrent viewers|watching now|stop streaming|end stream|" - r"直播中|正在直播|人正在观看|结束直播", + r"concurrent viewers|watching now|直播中|正在直播|人正在观看", lower, ): status = "live" - elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower): - # e.g. "LIVE 1:19:36" on Studio control room - status = "live" + elif nodata or re.search( + r"connect your encoder|stream offline|not streaming|waiting for you to start|" + r"start sending us your video|待开播|等待你开始", + lower, + ): + status = "waiting" elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower): status = "waiting" + elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower): + status = "live" health = "" if re.search(r"excellent connection|stream is healthy|状况良好|连接状况极佳", lower): @@ -234,9 +259,25 @@ def main() -> None: except Exception: live_duration_sec = None - on_air = status == "live" or health in {"excellent", "good"} or ( - viewers is not None and status != "ended" and status != "waiting" - ) or bool(live_duration and status != "ended" and status != "waiting") + if live_duration and not session_live: + session_live = True + if status in {"", "waiting"} and (nodata or encoder_lost_hint): + status = "encoder_lost" + elif status in {"", "waiting"}: + status = "live" + + # 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播. + on_air = bool(status == "live" and not nodata and not encoder_lost_hint) + encoder_lost = status == "encoder_lost" or (session_live and nodata) + encoder_receiving = bool( + not nodata + and not encoder_lost + and ( + status == "live" + or health + or re.search(r"starting|receiving|connecting|正在接收|连接中", lower) + ) + ) print( json.dumps( { @@ -249,6 +290,10 @@ def main() -> None: "live_duration": live_duration, "live_duration_sec": live_duration_sec, "on_air": on_air, + "nodata": nodata, + "encoder_receiving": encoder_receiving, + "encoder_lost": encoder_lost, + "session_live": bool(session_live or status in {"live", "encoder_lost"}), "text": text[:500], }, ensure_ascii=False, diff --git a/backend/neko/live-ops-extension/background.js b/backend/neko/live-ops-extension/background.js index b046f1b..e096eb7 100644 --- a/backend/neko/live-ops-extension/background.js +++ b/backend/neko/live-ops-extension/background.js @@ -2,6 +2,8 @@ const API_BASES = [ // Physical / Docker: hit host API first — public HTTPS often hangs and blocks all telemetry. "http://host.docker.internal:8014", "http://172.17.0.1:8014", + // VPS dylive (local assign Neko on hub) — must be present or telemetry never reaches hub. + "https://dylive.nomadro.com", "https://dy.nomadro.com", "https://dy.nomadro.cn", "https://dy.nomadro.live", @@ -14,7 +16,7 @@ const AUTH_JUNK_RE = /accounts\.google\.com\/(?:ServiceLogin|signin|v3\/signin|accountchooser|RotateCookiesPage)/i; const YOUTUBE_HOME_RE = /^https:\/\/www\.youtube\.com\/?(?:\?|$)/; -let cachedNekoInstanceId = 0; +let cachedNekoInstanceId = ""; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); @@ -24,13 +26,26 @@ function tabUrl(tab) { return tab?.pendingUrl || tab?.url || ""; } +function normalizeNekoRef(raw) { + const text = String(raw || "").trim(); + if (!text) return ""; + const low = text.toLowerCase(); + if (low.startsWith("ops-") || low.startsWith("ops:")) { + const digits = low.replace(/^ops[-:]/, "").replace(/[^\d]/g, ""); + return digits ? `ops-${digits}` : ""; + } + const n = Number(text); + if (Number.isFinite(n) && n > 0) return String(Math.trunc(n)); + return ""; +} + async function loadNekoInstanceId() { - if (cachedNekoInstanceId > 0) return cachedNekoInstanceId; + if (cachedNekoInstanceId) return cachedNekoInstanceId; try { - const stored = await chrome.storage.local.get(["nekoInstanceId"]); - const fromStore = Number(stored.nekoInstanceId || 0); - if (fromStore > 0) { - cachedNekoInstanceId = fromStore; + const stored = await chrome.storage.local.get(["nekoInstanceId", "nekoInstanceRef"]); + const fromRef = normalizeNekoRef(stored.nekoInstanceRef || stored.nekoInstanceId || ""); + if (fromRef) { + cachedNekoInstanceId = fromRef; return cachedNekoInstanceId; } } catch {} @@ -38,15 +53,15 @@ async function loadNekoInstanceId() { const res = await fetch(chrome.runtime.getURL("instance_id.txt"), { cache: "no-store" }); if (res.ok) { const text = (await res.text()).trim(); - const nid = Number(text); - if (Number.isFinite(nid) && nid > 0) { - cachedNekoInstanceId = nid; - await chrome.storage.local.set({ nekoInstanceId: nid }); - return nid; + const ref = normalizeNekoRef(text); + if (ref) { + cachedNekoInstanceId = ref; + await chrome.storage.local.set({ nekoInstanceId: ref, nekoInstanceRef: ref }); + return ref; } } } catch {} - return 0; + return ""; } loadNekoInstanceId().catch(() => {}); @@ -139,12 +154,20 @@ scheduleTabHygiene(); async function postTelemetry(payload) { const stored = await chrome.storage.local.get(["liveHubIngestToken"]); const ingestToken = (stored.liveHubIngestToken || "").trim(); - const nekoInstanceId = (await loadNekoInstanceId()) || Number(payload?.neko_instance_id || 0) || 0; + const nekoRef = + (await loadNekoInstanceId()) || + normalizeNekoRef(payload?.neko_ref || payload?.neko_instance_id || "") || + ""; const body = JSON.stringify({ ...payload, source: payload.source || "chrome_extension", received_at: Date.now() / 1000, - ...(nekoInstanceId > 0 ? { neko_instance_id: nekoInstanceId } : {}), + ...(nekoRef + ? { + neko_instance_id: nekoRef, + neko_ref: nekoRef, + } + : {}), ...(ingestToken ? { ingest_token: ingestToken } : {}), }); let lastError = ""; @@ -166,7 +189,7 @@ async function postTelemetry(payload) { liveHubLastOk: Date.now(), liveHubLastBase: base, liveHubLastEvent: data?.event?.id || null, - liveHubLastNekoId: data?.event?.neko_instance_id || nekoInstanceId || null, + liveHubLastNekoId: data?.event?.neko_ref || data?.event?.neko_instance_id || nekoRef || null, }); return { ok: true, base, eventId: data?.event?.id || null }; } diff --git a/backend/neko/live-ops-extension/content.js b/backend/neko/live-ops-extension/content.js index ccd83af..698760f 100644 --- a/backend/neko/live-ops-extension/content.js +++ b/backend/neko/live-ops-extension/content.js @@ -36,21 +36,69 @@ function firstNumberByPatterns(text, patterns) { return null; } +function detectNodata(text) { + const lower = text.toLowerCase(); + // Studio encoder badge: "No data" / NODATA / 无数据 + return /(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据|没有数据/.test(lower); +} + +/** YouTube Live session already started (LIVE pill + timer / End Stream). */ +function detectSessionLive(text) { + const lower = text.toLowerCase(); + const hasTimer = + /\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?/.test(lower) || + /(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}/.test(text); + const hasEnd = + /end stream|stop streaming|结束直播|停止直播/.test(lower); + return Boolean(hasTimer && hasEnd) || Boolean(hasTimer && /\blive\b/.test(lower)); +} + +/** Encoder dropped while session still live — 断播 (not 待开播). */ +function detectEncoderLost(text) { + const lower = text.toLowerCase(); + if (/will end shortly|restart it in your streaming software|unless you restart/.test(lower)) { + return true; + } + if (/(?:即将结束|请重新|重新启动|推流软件|编码器.*断开|断流)/.test(text)) { + return true; + } + return detectSessionLive(text) && detectNodata(text); +} + +/** + * Studio states we must not confuse: + * - waiting / 待开播: control room open, broadcast not started + * - live / 开播: session live + encoder has data + * - encoder_lost / 断播: session still live, encoder NODATA / will end shortly + * - ended / 停播: stream ended + */ function detectLiveStatus(text) { const lower = text.toLowerCase(); - if (/stream ended|not live|offline|直播已结束|未在直播/.test(lower)) return "ended"; - if (/connect your encoder|no data|stream offline|not streaming|waiting for you to start/.test(lower)) { - return "waiting"; + if (/stream ended|直播已结束|未在直播/.test(lower) && !detectSessionLive(text)) { + return "ended"; } + const sessionLive = detectSessionLive(text); + const nodata = detectNodata(text); + if (sessionLive && (detectEncoderLost(text) || nodata)) { + return "encoder_lost"; + } + if (sessionLive) { + return "live"; + } + // True 待开播: no LIVE session yet if ( - /you'?re live|you are live|excellent connection|stream is healthy|end stream|stop streaming|concurrent viewers|watching now|直播中|正在直播|已开始直播|结束直播/.test( + nodata || + /connect your encoder|stream offline|not streaming|waiting for you to start|待开播|等待你开始|start sending us your video/.test( lower ) ) { - return "live"; + return "waiting"; } - // Studio shows a LIVE pill + duration while on-air - if (/\blive\b[\s\S]{0,40}\d+:\d{2}(?::\d{2})?/.test(lower) && /end stream|stop streaming/.test(lower)) { + if ( + /you'?re live|you are live|excellent connection|stream is healthy|concurrent viewers|watching now|直播中|正在直播|已开始直播/.test( + lower + ) + ) { return "live"; } if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting"; @@ -157,14 +205,27 @@ function collectTelemetry() { const dur = parseLiveDuration(text); const totalViews = parseTotalViews(text); const popups = collectPopupTexts(); + const liveStatus = detectLiveStatus(text); + const nodata = detectNodata(text); + const sessionLive = detectSessionLive(text) || liveStatus === "live" || liveStatus === "encoder_lost"; + const encoderLost = liveStatus === "encoder_lost" || detectEncoderLost(text); + const health = detectHealth(text); + // 开播中且有码流;绿点 preview(未点 Go Live)不算 live + const encoderReceiving = + !nodata && + !encoderLost && + (liveStatus === "live" || + Boolean(health) || + /starting|receiving|connecting|正在接收|连接中|缓冲/.test(text.toLowerCase())); + const pendingGoLive = liveStatus === "waiting" && !sessionLive && !encoderLost; const payload = { captured_at: Date.now() / 1000, source: "chrome_extension", url: location.href, page_title: document.title, stream_title: collectStreamTitle(), - live_status: detectLiveStatus(text), - health: detectHealth(text), + live_status: liveStatus, + health, viewer_count: viewerCount, like_count: likeCount, total_views: totalViews, @@ -177,6 +238,11 @@ function collectTelemetry() { visibility: document.visibilityState, focused: document.hasFocus(), path: location.pathname, + nodata, + encoder_receiving: encoderReceiving, + encoder_lost: encoderLost, + session_live: sessionLive, + pending_go_live: pendingGoLive, }, }; return payload; diff --git a/backend/tests/test_assign_category.py b/backend/tests/test_assign_category.py new file mode 100644 index 0000000..be24936 --- /dev/null +++ b/backend/tests/test_assign_category.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +from app.yt_assign_db import group_is_time_slot, normalize_assign_category + + +def test_normalize_assign_category(): + assert normalize_assign_category("normal") == "normal" + assert normalize_assign_category("普通") == "normal" + assert normalize_assign_category("") == "normal" + assert normalize_assign_category(None) == "normal" + assert normalize_assign_category("time_slot") == "time_slot" + assert normalize_assign_category("时间段") == "time_slot" + assert normalize_assign_category("timeslot") == "time_slot" + assert normalize_assign_category("weird") == "normal" + + +def test_group_is_time_slot(): + assert group_is_time_slot({"category": "time_slot"}) is True + assert group_is_time_slot({"category": "normal"}) is False + assert group_is_time_slot({"category": "普通"}) is False + assert group_is_time_slot({}) is False + assert group_is_time_slot(None) is False diff --git a/backend/tests/test_neko_cn_prefer_and_ops_parity.py b/backend/tests/test_neko_cn_prefer_and_ops_parity.py new file mode 100644 index 0000000..d0008fd --- /dev/null +++ b/backend/tests/test_neko_cn_prefer_and_ops_parity.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from app import youtube_neko + + +def test_preferred_neko_public_base_colocated(monkeypatch) -> None: + monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: False) + monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dylive.nomadro.com") + assert youtube_neko.preferred_neko_public_base() == "https://dylive.nomadro.com" + + +def test_preferred_neko_public_base_cn_first(monkeypatch) -> None: + monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: True) + monkeypatch.setattr(youtube_neko, "cn_edge_usable", lambda: True) + monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dy.nomadro.com") + monkeypatch.delenv("DY_NEKO_CN_PUBLIC_BASE", raising=False) + assert youtube_neko.preferred_neko_public_base() == "https://dy.nomadro.cn" + + +def test_preferred_neko_public_base_vps_fallback(monkeypatch) -> None: + monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: True) + monkeypatch.setattr(youtube_neko, "cn_edge_usable", lambda: False) + monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dy.nomadro.com") + monkeypatch.delenv("DY_NEKO_CN_PUBLIC_BASE", raising=False) + assert youtube_neko.preferred_neko_public_base() == "https://dy.nomadro.com" + + +def test_compose_service_lines_has_studio_live_env(tmp_path, monkeypatch) -> None: + assets = youtube_neko._asset_root() # noqa: SLF001 + monkeypatch.setattr(youtube_neko, "_detect_public_ip", lambda: "1.2.3.4") + monkeypatch.setattr(youtube_neko, "_neko_browser_proxy_value", lambda: "http://host.docker.internal:7890") + profile = tmp_path / "p" + profile.mkdir() + idf = tmp_path / "id.txt" + idf.write_text("ops-1\n", encoding="utf-8") + lines = youtube_neko.compose_service_lines( + service_key="opsneko1", + container_name="douyinweb-ops-neko-1", + instance_id_label="ops-1", + http_port=18200, + mux=62300, + udp="62500-62509", + profile=profile, + instance_id_file=idf, + http_bind="0.0.0.0", + ) + blob = "\n".join(lines) + assert "NEKO_LIVE_OPS_EXTENSION" in blob + assert "NEKO_TAMPERMONKEY_REPAIR" in blob + assert "studio.youtube.com" in blob + assert "host.docker.internal:7890" in blob + assert str(assets / "tampermonkey-seed") in blob or "tampermonkey-seed" in blob + assert "opsneko1:" in blob diff --git a/backend/tests/test_ops_neko_catalog.py b/backend/tests/test_ops_neko_catalog.py new file mode 100644 index 0000000..7003fdb --- /dev/null +++ b/backend/tests/test_ops_neko_catalog.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from app import ops_neko_db + + +def test_edge_catalog_upsert_and_list(temp_db) -> None: + rows = ops_neko_db.upsert_edge_catalog( + [ + { + "id": "a", + "slot": 1, + "name": "N1", + "open_url": "https://dy.nomadro.cn/ops-neko/1/", + "running": True, + }, + { + "slot": 2, + "name": "N2", + "open_url": "https://dy.nomadro.cn/ops-neko/2/", + "running": False, + }, + ], + edge_id="phys1", + edge_label="phys1", + ) + assert len(rows) >= 2 + listed = ops_neko_db.list_edge_catalog(max_age_sec=3600) + assert any(r.get("slot") == 1 and "ops-neko/1" in str(r.get("open_url")) for r in listed) diff --git a/backend/tests/test_ops_neko_live_gate.py b/backend/tests/test_ops_neko_live_gate.py new file mode 100644 index 0000000..d1267da --- /dev/null +++ b/backend/tests/test_ops_neko_live_gate.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import time + +from app import youtube_neko + + +def test_studio_live_control_url() -> None: + assert "UC123456789012345678" in youtube_neko.studio_live_control_url("UC123456789012345678") + assert youtube_neko.studio_live_control_url("UC123456789012345678").endswith("/livestreaming") + assert "studio.youtube.com" in youtube_neko.studio_live_control_url("") + + +def test_wait_group_ready_for_live_prefers_ops_telemetry() -> None: + youtube_neko._studio_events.clear() # noqa: SLF001 + youtube_neko._studio_latest_by_ref.clear() # noqa: SLF001 + now = time.time() + youtube_neko.ingest_studio_telemetry( + { + "neko_ref": "ops-2", + "neko_instance_id": "ops-2", + "url": "https://studio.youtube.com/channel/UCabcdefghijklmnopqr/livestreaming", + "live_status": "waiting", + "received_at": now, + "signals": {"path": "/livestreaming", "pending_go_live": True}, + } + ) + group = { + "id": "g1", + "neko_open_prefer": "remote", + "ops_neko_open_url": "https://dy.nomadro.cn/ops-neko/2/", + "ops_neko_slot": 2, + "neko_instance_id": 8, + "youtube_channel_id": "UCabcdefghijklmnopqr", + } + out = youtube_neko.wait_group_ready_for_live( + group, timeout_sec=3.0, settle_sec=0.5, strict=True + ) + assert out.get("ok") is True + assert out.get("neko_kind") == "ops" + assert out.get("ops_slot") == 2 + assert out.get("live_studio") is True diff --git a/backend/tests/test_relay_timeslot_rotate.py b/backend/tests/test_relay_timeslot_rotate.py new file mode 100644 index 0000000..299f8ab --- /dev/null +++ b/backend/tests/test_relay_timeslot_rotate.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +"""time_slot source pick must skip offline sticky rooms.""" +from __future__ import annotations + +from typing import Any + + +def test_pick_source_excludes_sticky_offline(monkeypatch): + from app import youtube_relay_pipeline as yrp + + rooms = [ + {"room_id": "111", "url": "https://live.douyin.com/111", "last_anchor": "A"}, + {"room_id": "222", "url": "https://live.douyin.com/222", "last_anchor": "B"}, + {"room_id": "333", "url": "https://live.douyin.com/333", "last_anchor": "C"}, + ] + monkeypatch.setattr(yrp.db, "list_live_douyin_rooms_for_shorts", lambda limit=40: rooms) + monkeypatch.setattr(yrp, "_group_in_active_slot", lambda gid, keyed_only=False: True) + monkeypatch.setattr(yrp, "_group_uses_time_slot", lambda g: True) + + group: dict[str, Any] = {"id": "g1", "enabled": 1, "category": "time_slot"} + + sticky = yrp.pick_source_for_group(group, prefer_room_id="111") + assert sticky and sticky["room_id"] == "111" + + rotated = yrp.pick_source_for_group( + group, + prefer_room_id="111", + exclude_room_ids={"111"}, + ) + assert rotated and rotated["room_id"] == "222" + + cleared = yrp.pick_source_for_group( + group, + prefer_room_id="", + exclude_room_ids={"111", "222"}, + ) + assert cleared and cleared["room_id"] == "333" diff --git a/backend/tests/test_youtube_neko_live.py b/backend/tests/test_youtube_neko_live.py index 85d6a42..4ad503c 100644 --- a/backend/tests/test_youtube_neko_live.py +++ b/backend/tests/test_youtube_neko_live.py @@ -12,8 +12,92 @@ def _reset_events() -> None: def test_payload_stream_confirmed_live_status() -> None: assert youtube_neko._payload_stream_confirmed({"live_status": "live"}) is True - assert youtube_neko._payload_stream_confirmed({"health": "excellent"}) is True + # health alone / streaming (page-open mirror) must NOT count as on-air + assert youtube_neko._payload_stream_confirmed({"health": "excellent"}) is False + assert youtube_neko._payload_stream_confirmed({"live_status": "streaming"}) is False assert youtube_neko._payload_stream_confirmed({"live_status": "waiting"}) is False + assert youtube_neko._payload_stream_confirmed({"live_status": "ready"}) is False + assert youtube_neko._payload_stream_confirmed({"viewer_count": 0, "url": "https://studio.youtube.com/x/livestreaming"}) is False + assert youtube_neko._payload_stream_confirmed({"viewer_count": 3, "url": "https://studio.youtube.com/x/livestreaming"}) is True + assert ( + youtube_neko._payload_stream_confirmed( + {"text": "No data\nConnect your encoder to go live", "live_status": "waiting"} + ) + is False + ) + assert youtube_neko._payload_nodata_or_pending({"live_status": "waiting"}) is True + assert youtube_neko._payload_nodata_or_pending({"signals": {"nodata": True}}) is True + assert youtube_neko._payload_nodata_or_pending({"live_status": "live", "text": "You're live"}) is False + + +def test_studio_encoder_lost_is_duanbo_not_pending() -> None: + """LIVE timer + No data + will end shortly = 断播, not 待开播.""" + text = ( + "LIVE\n8:15\nEnd Stream\nLive\nNo data\nKey:\nConnect your encoder to go live\n" + "No data - This stream will end shortly, unless you restart it in your streaming software\n" + "Concurrent viewers\n0" + ) + payload = { + "url": "https://studio.youtube.com/video/1cQY6jHytxQ/livestreaming", + "live_status": "encoder_lost", + "live_duration": "8:15", + "live_duration_sec": 495, + "viewer_count": 0, + "text": text, + "signals": { + "path": "/livestreaming", + "nodata": True, + "encoder_lost": True, + "session_live": True, + "pending_go_live": False, + }, + } + assert youtube_neko._payload_session_live(payload) is True + assert youtube_neko._payload_encoder_lost(payload) is True + assert youtube_neko._payload_stream_confirmed(payload) is False + assert youtube_neko._payload_nodata_or_pending(payload) is False + + # Infer from text alone (no explicit status) + inferred = { + "url": "https://studio.youtube.com/video/1cQY6jHytxQ/livestreaming", + "text": text, + "live_duration": "8:15", + "signals": {"path": "/livestreaming", "nodata": True}, + } + assert youtube_neko._payload_session_live(inferred) is True + assert youtube_neko._payload_encoder_lost(inferred) is True + assert youtube_neko._payload_nodata_or_pending(inferred) is False + + # True 待开播: nodata without LIVE session + pending = { + "url": "https://studio.youtube.com/video/x/livestreaming", + "live_status": "waiting", + "text": "No data\nConnect your encoder to go live\nStart sending us your video", + "signals": {"nodata": True, "pending_go_live": True}, + } + assert youtube_neko._payload_session_live(pending) is False + assert youtube_neko._payload_encoder_lost(pending) is False + assert youtube_neko._payload_nodata_or_pending(pending) is True + + + +def test_ingest_remote_studio_mirror_does_not_fake_streaming() -> None: + youtube_neko._studio_events.clear() # noqa: SLF001 + youtube_neko._studio_latest_by_ref.clear() # noqa: SLF001 + out = youtube_neko.ingest_remote_studio_mirror( + 2, + { + "live_page_open": True, + "on_air": False, + "live_status": "", + "url": "https://studio.youtube.com/video/L1sF_kZvzIk/livestreaming", + }, + ) + assert out.get("ok") is not False or out # ingest returns dict + snap = youtube_neko.studio_snapshot_for_ref("ops:2", max_age_sec=60.0) + assert snap.get("live_page_open") is True + assert snap.get("on_air") is False + assert str(snap.get("live_status") or "") in {"waiting", ""} def test_latest_live_studio_event_since_ts() -> None: diff --git a/backend/tests/test_yt_studio_db.py b/backend/tests/test_yt_studio_db.py new file mode 100644 index 0000000..1935652 --- /dev/null +++ b/backend/tests/test_yt_studio_db.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from app.youtube_neko import parse_neko_ref +from app import yt_studio_db + + +def test_parse_neko_ref(): + assert parse_neko_ref("ops-1") == ("remote", "ops:1", 0) + assert parse_neko_ref("ops:2") == ("remote", "ops:2", 0) + assert parse_neko_ref("5") == ("local", "local:5", 5) + assert parse_neko_ref("") == ("local", "", 0) + + +def test_insert_sample_roundtrip(tmp_path, monkeypatch): + # Use real DB — just insert and list + row = yt_studio_db.insert_sample( + group_id="g1", + youtube_channel_id="UC123", + source_room_id="room9", + neko_kind="remote", + neko_ref="ops:1", + on_air=True, + live_page_open=True, + viewer_count=12, + total_views=100, + peak_viewers=12, + ) + assert row.get("group_id") == "g1" + assert row.get("neko_kind") == "remote" + rows = yt_studio_db.list_samples(group_id="g1", limit=5) + assert any(r.get("id") == row.get("id") for r in rows) diff --git a/frontend/src/app/neko/page.tsx b/frontend/src/app/neko/page.tsx index 56df69a..cda8f2a 100644 --- a/frontend/src/app/neko/page.tsx +++ b/frontend/src/app/neko/page.tsx @@ -48,6 +48,15 @@ type RemoteCard = { neko_open_prefer?: string; }; +type SyncStatus = { + enabled?: boolean; + connected?: boolean; + last_ok_age_sec?: number | null; + last_error?: string; + interval_sec?: number; + ticks?: number; +}; + export default function OpsNekoPage() { const toast = useToast(); const confirm = useConfirm(); @@ -62,6 +71,7 @@ export default function OpsNekoPage() { const [tokenInput, setTokenInput] = useState(""); const [remoteCards, setRemoteCards] = useState([]); const [newName, setNewName] = useState(""); + const [sync, setSync] = useState({}); const load = useCallback(async () => { try { @@ -69,6 +79,7 @@ export default function OpsNekoPage() { peer?: Peer; instances?: Instance[]; host_profile?: { profile?: string }; + sync?: SyncStatus; }; setPeer(d.peer || {}); setInstances(d.instances || []); @@ -76,6 +87,7 @@ export default function OpsNekoPage() { setRole(String(d.peer?.role || "off")); setPeerBase(String(d.peer?.peer_base_url || "")); setPublicBase(String(d.peer?.public_base || "")); + setSync(d.sync || {}); } catch (e) { toast.push((e as Error).message, "err"); } finally { @@ -87,27 +99,47 @@ export default function OpsNekoPage() { void load(); }, [load]); - async function savePeer(extra: Record = {}) { - setBusy("peer"); + // Live sync status while edge-connected + useEffect(() => { + if (role !== "edge" && peer.role !== "edge") return; + const t = window.setInterval(() => { + void fetchJson("/api/ops/neko/sync-status") + .then((d) => setSync(d as SyncStatus)) + .catch(() => null); + }, 3000); + return () => window.clearInterval(t); + }, [role, peer.role]); + + async function connectRealtime() { + setBusy("pair"); try { - const d = (await fetchJson("/api/ops/neko/peer", { + const d = (await fetchJson("/api/ops/neko/pair", { method: "POST", body: JSON.stringify({ - role, - peer_base_url: peerBase, - public_base: publicBase, - token: tokenInput || undefined, - ...extra, + hub_base: peerBase, + token: tokenInput, + public_base: publicBase || undefined, }), - })) as Peer & { token?: string }; - setPeer(d); - if (d.token) { - setTokenInput(d.token); - toast.push("已生成 token(请复制到对端)", "ok"); - } else { - toast.push("配对配置已保存", "ok"); + })) as { + ok?: boolean; + peer?: Peer; + cards?: { ok?: boolean; cards?: RemoteCard[]; error?: string }; + catalog?: { ok?: boolean; error?: string; count?: number }; + hint?: string; + error?: string; + }; + if (d.peer) setPeer(d.peer); + if (d.cards?.cards) setRemoteCards(d.cards.cards); + if (!d.ok && !d.catalog?.ok && !d.cards?.ok) { + throw new Error(d.catalog?.error || d.cards?.error || d.error || "连接失败"); } + setRole("edge"); + toast.push(d.hint || "已连接:后台自动实时同步到 VPS", "ok"); await load(); + const st = (await fetchJson("/api/ops/neko/sync-now", { method: "POST" })) as SyncStatus & { + ok?: boolean; + }; + setSync(st); } catch (e) { toast.push((e as Error).message, "err"); } finally { @@ -123,8 +155,11 @@ export default function OpsNekoPage() { body: JSON.stringify({ name: newName }), }); setNewName(""); - toast.push("已创建 Ops Neko(默认停止,与分配原生 Neko 隔离)", "ok"); + toast.push("已创建 Ops Neko(默认停止)", "ok"); await load(); + if (peer.role === "edge" || role === "edge") { + void fetchJson("/api/ops/neko/push-catalog", { method: "POST" }).catch(() => null); + } } catch (e) { toast.push((e as Error).message, "err"); } finally { @@ -209,9 +244,9 @@ export default function OpsNekoPage() {

Neko

独立实例池(douyinweb-ops-neko-* - ),与 YouTube 分配页原生 Neko(douyinweb-neko-* - )互不影响。VPS 频道原生 Neko 永远保留、默认停止;物理机在此创建实例后配对到 VPS - 分配卡,分配页用开关选择「打开本机 / 打开远程」。 + ),运行时配置与分配页原生 Neko 相同(Studio 起始页、Tampermonkey、live-ops、ShellCrash + 代理、分辨率/码率、ICE)。端口与容器名分开;VPS 频道原生 Neko 永远保留。物理机打开链接优先 + 腾讯云 .cn,WG 不通才回退 VPS。

{hostProfile ? (

当前主机形态:{hostProfile}

@@ -227,27 +262,38 @@ export default function OpsNekoPage() { -
-

- - 跨机配对(域名 + Token) -

-

{peer.hint || "选择 hub / edge"}

+
+
+
+

+ + VPS 实时通道 +

+

+ 粘贴一次域名 + Token 并连接后,后台每 5 秒自动同步实例目录;启停实例也会立刻推送。 +

+
+ + {sync.connected + ? `已连接 · ${Math.round(Number(sync.last_ok_age_sec ?? 0))}s 前` + : peer.role === "edge" + ? sync.last_error + ? `重试中 · ${sync.last_error}` + : "连接中…" + : "未连接"} + +
- + -
- - {role === "edge" ? ( + {(role === "edge" || peer.role === "edge") && ( - ) : null} + )}
+ {peer.role === "edge" && peer.peer_base_url ? ( +

+ 通道 → {peer.peer_base_url} + {typeof sync.ticks === "number" && sync.ticks > 0 ? ` · 心跳 #${sync.ticks}` : ""} +

+ ) : null}
diff --git a/frontend/src/components/OpsNekoHubCredentialsCard.tsx b/frontend/src/components/OpsNekoHubCredentialsCard.tsx new file mode 100644 index 0000000..872225c --- /dev/null +++ b/frontend/src/components/OpsNekoHubCredentialsCard.tsx @@ -0,0 +1,159 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Check, Copy, KeyRound, Link2, Loader2, RefreshCw } from "lucide-react"; + +import { useToast } from "@/components/Toast"; +import { fetchJson } from "@/lib/api"; + +type Creds = { + profile?: string; + domain?: string; + token?: string; + ready?: boolean; + role?: string; +}; + +/** VPS assign hero: copyable hub domain + token for physical Neko pairing. */ +export function OpsNekoHubCredentialsCard() { + const toast = useToast(); + const [creds, setCreds] = useState(null); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [copied, setCopied] = useState<"domain" | "token" | "both" | "">(""); + + const load = useCallback(async () => { + try { + const d = (await fetchJson("/api/ops/neko/hub/credentials")) as Creds; + setCreds(d); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setLoading(false); + } + }, [toast]); + + useEffect(() => { + void load(); + }, [load]); + + async function rotate() { + setBusy(true); + try { + const d = (await fetchJson("/api/ops/neko/hub/credentials", { + method: "POST", + body: JSON.stringify({ rotate_token: true }), + })) as Creds; + setCreds(d); + toast.push("已生成新 Token(请同步到物理机)", "ok"); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(false); + } + } + + async function copy(text: string, which: "domain" | "token" | "both") { + try { + await navigator.clipboard.writeText(text); + setCopied(which); + toast.push("已复制", "ok"); + window.setTimeout(() => setCopied(""), 1500); + } catch { + toast.push("复制失败", "err"); + } + } + + // Only show on VPS profile + if (!loading && creds?.profile && creds.profile !== "vps") { + return null; + } + if (loading && !creds) { + return ( +
+ + 加载物理机配对凭证… +
+ ); + } + + const domain = String(creds?.domain || "").trim(); + const token = String(creds?.token || "").trim(); + + return ( +
+
+
+
+ + 物理机 Neko 配对 +
+

+ 粘贴一次域名 + Token 并连接后,后台每 5 秒自动同步;启停实例立刻推送。VPS 分配页下拉会实时更新。 +

+
+
+ + +
+
+ +
+ + +
+
+ ); +} diff --git a/frontend/src/components/YtRelayOpsHero.tsx b/frontend/src/components/YtRelayOpsHero.tsx index 175c4c4..395c32b 100644 --- a/frontend/src/components/YtRelayOpsHero.tsx +++ b/frontend/src/components/YtRelayOpsHero.tsx @@ -13,6 +13,7 @@ import { } from "lucide-react"; import { EnableSwitch } from "@/components/EnableSwitch"; +import { OpsNekoHubCredentialsCard } from "@/components/OpsNekoHubCredentialsCard"; export type RelayOpsHeroProps = { relayEnabled: boolean; @@ -149,8 +150,8 @@ export function YtRelayOpsHero({ const pushing = Number(pushingCount || 0) > 0; return ( -
-
+
+
@@ -282,6 +283,8 @@ export function YtRelayOpsHero({
)} + +
diff --git a/frontend/src/components/YtRelayProStatusPanel.tsx b/frontend/src/components/YtRelayProStatusPanel.tsx index ef65930..f19e5a3 100644 --- a/frontend/src/components/YtRelayProStatusPanel.tsx +++ b/frontend/src/components/YtRelayProStatusPanel.tsx @@ -44,6 +44,16 @@ type GroupLike = { neko_open_source?: "local" | "remote"; }; +export type OpsNekoCatalogItem = { + id?: string; + edge_id?: string; + edge_label?: string; + slot?: number; + name?: string; + open_url?: string; + running?: boolean | number; +}; + type NekoState = { running?: boolean; ready?: boolean; @@ -62,8 +72,12 @@ type NekoState = { live_duration_sec?: number | null; stream_title?: string; url?: string; + received_at?: number; age_sec?: number | null; detect_source?: string; + neko_ref?: string; + neko_kind?: string; + ui_source?: string; minute_reports?: Array<{ ts?: number; on_air?: boolean; @@ -85,6 +99,9 @@ type Props = { onStop: (id: string) => void; onRestart: (id: string) => void; onNekoChange?: () => void; + /** Physical ops-neko instances reported to this VPS hub. */ + remoteCatalog?: OpsNekoCatalogItem[]; + hostProfile?: string; }; function nekoStatusLabel(st?: NekoState | null, instanceId?: number, pollErr?: string): string { @@ -106,6 +123,8 @@ export function YtRelayProStatusPanel({ onStop, onRestart, onNekoChange, + remoteCatalog = [], + hostProfile = "", }: Props) { const toast = useToast(); const laneName = group.name || "未命名频道"; @@ -155,7 +174,16 @@ export function YtRelayProStatusPanel({ setNekoState(row.neko as NekoState); setNekoPollErr(""); } - }, [row?.neko, row?.neko?.status, row?.neko?.ready, row?.neko?.running, row?.neko?.studio_url]); + }, [ + row?.neko, + row?.neko?.status, + row?.neko?.ready, + row?.neko?.running, + row?.neko?.studio_url, + row?.neko?.studio?.received_at, + row?.neko?.studio?.viewer_count, + row?.neko?.studio?.ui_source, + ]); const refreshNeko = useCallback(async () => { if (instanceId < 1) return; @@ -166,12 +194,18 @@ export function YtRelayProStatusPanel({ return; } const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId); - if (inst) setNekoState(inst); + if (inst) { + setNekoState((prev) => ({ + ...inst, + // Docker status has no Studio metrics — keep relay/remote telemetry. + studio: (row?.neko as NekoState | undefined)?.studio ?? prev?.studio ?? null, + })); + } setNekoPollErr(""); } catch (e) { setNekoPollErr((e as Error).message || "状态查询失败"); } - }, [instanceId]); + }, [instanceId, row?.neko]); // Fallback only when relay payload has no neko field yet (old API / cold start). useEffect(() => { @@ -200,7 +234,7 @@ export function YtRelayProStatusPanel({ async function setPrefer(prefer: "local" | "remote") { if (prefer === "remote" && !remoteBound) { - toast.push("尚未配对远程 Neko(请先到一级 Tab「Neko」完成绑定)", "err"); + toast.push("请先在下方下拉框选择物理机 ops-neko 实例", "err"); return; } setNekoBusy(true); @@ -226,6 +260,59 @@ export function YtRelayProStatusPanel({ } } + async function bindRemote(catalogId: string) { + setNekoBusy(true); + try { + if (!catalogId) { + await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`, { + method: "POST", + body: JSON.stringify({ open_url: "", slot: 0, edge_label: "", prefer: "local" }), + }); + setOpenPrefer("local"); + onNekoChange?.(); + toast.push("已清除远程绑定,切回本机原生", "ok"); + return; + } + const item = remoteCatalog.find((x) => String(x.id || `${x.edge_id}:${x.slot}`) === catalogId); + if (!item?.open_url) throw new Error("未找到该物理机实例"); + const r = (await fetchJson( + `/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`, + { + method: "POST", + body: JSON.stringify({ + open_url: item.open_url, + slot: Number(item.slot || 0), + edge_label: item.edge_label || item.name || "", + prefer: "remote", + }), + }, + )) as { group?: GroupLike }; + if (r.group?.neko_open_prefer === "remote" || r.group?.neko_open_prefer === "local") { + setOpenPrefer(r.group.neko_open_prefer); + } else { + setOpenPrefer("remote"); + } + onNekoChange?.(); + toast.push(`已绑定远程 #${item.slot},默认打开远控`, "ok"); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setNekoBusy(false); + } + } + + const selectedCatalogId = (() => { + if (!remoteStudioUrl) return ""; + const hit = remoteCatalog.find( + (x) => + String(x.open_url || "").replace(/\/$/, "") === remoteStudioUrl.replace(/\/$/, "") || + (Number(x.slot) === Number(group.ops_neko_slot || 0) && + String(x.edge_label || "") === String(group.ops_neko_edge_label || "")), + ); + return hit ? String(hit.id || `${hit.edge_id}:${hit.slot}`) : ""; + })(); + const showRemotePicker = hostProfile === "vps" || remoteCatalog.length > 0 || remoteBound; + return (
@@ -396,7 +483,7 @@ export function YtRelayProStatusPanel({ ? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${ group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : "" }` - : "尚未配对 — 在物理机一级「Neko」创建实例并登记到本频道"} + : "选择物理机 ops-neko,或先完成 Neko 页配对同步目录"}

void setPrefer("remote")} className={`rounded-full px-2.5 py-1 text-[10px] ${ openPrefer === "remote" && remoteBound @@ -435,10 +522,35 @@ export function YtRelayProStatusPanel({
- {!remoteBound ? ( -

- 流程:物理机 Neko Tab → edge + Token → 新建实例 → 拉取 VPS 分配卡 → 绑定本频道并登记。登记后此处可切「远程」。 -

+ {showRemotePicker ? ( + ) : null}
@@ -511,7 +623,9 @@ export function YtRelayProStatusPanel({
{(() => { const st = nekoState?.studio; - if (!st && !nekoState?.ready && !nekoState?.running) return null; + const preferRemote = openPrefer === "remote" && remoteBound; + // Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred. + if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote) return null; const reports = st?.minute_reports || []; const viewers = st?.viewer_count != null && Number.isFinite(Number(st.viewer_count)) @@ -522,9 +636,28 @@ export function YtRelayProStatusPanel({ ? Number(st.total_views).toLocaleString() : "—"; const liveDur = String(st?.live_duration || "").trim() || "—"; + const uiSrc = String(st?.ui_source || st?.neko_kind || "").toLowerCase(); + const srcLabel = + uiSrc.includes("remote") + ? "远程 Neko 数据" + : uiSrc.includes("local") + ? "本机 Neko 数据" + : preferRemote + ? "远程(等待同步)" + : "本机"; return (
+ + {srcLabel} + {st?.live_status === "signed_out" ? ( Google 已登出 — 请打开工作室点选账号重新登录 @@ -587,7 +720,11 @@ export function YtRelayProStatusPanel({ onAir={Boolean(st?.on_air)} /> ) : ( -

暂无分钟报告(开播后约 1 分钟开始汇总)

+

+ {preferRemote + ? "远程分钟报告同步中(物理机开播约 1 分钟后出现;每 5 秒经目录同步到 VPS)" + : "暂无分钟报告(开播后约 1 分钟开始汇总)"} +

)}
); diff --git a/frontend/src/lib/ytRelayStatus.ts b/frontend/src/lib/ytRelayStatus.ts index 0c12127..c1e8abd 100644 --- a/frontend/src/lib/ytRelayStatus.ts +++ b/frontend/src/lib/ytRelayStatus.ts @@ -63,7 +63,13 @@ export type RelayMonitorRow = { live_duration_sec?: number | null; stream_title?: string; }>; + neko_ref?: string; + neko_kind?: "local" | "remote" | string; + ui_source?: string; } | null; + open_prefer?: "local" | "remote" | string; + remote_bound?: boolean; + ops_neko_slot?: number; } | null; }; diff --git a/youtube-svc/src/youtube.mjs b/youtube-svc/src/youtube.mjs index e533bf0..8e328bf 100644 --- a/youtube-svc/src/youtube.mjs +++ b/youtube-svc/src/youtube.mjs @@ -215,16 +215,45 @@ export async function getChannelBundle(raw, { includeLive = true, includeVideos } if (includeLive) { - // 1) Live tab + // 0) Direct /channel/UC…/live — most reliable when a stream is on-air try { - const feed = await channel.getLiveStreams(); - await scanFeedVideos(feed?.videos, 20); - if (!live && lives[0]?.id) { - const confirmed = await confirmLive(lives[0]); - if (confirmed) live = confirmed; + const liveUrl = `https://www.youtube.com/channel/${channelId}/live`; + const endpoint = await withYtRetry((client) => client.resolveURL(liveUrl)); + const videoId = endpoint?.payload?.videoId || ""; + if (videoId) { + const confirmed = await confirmLive({ + id: videoId, + title: "", + url: `https://www.youtube.com/watch?v=${videoId}`, + is_live: false, + is_upcoming: false, + is_live_content: true, + view_count: null, + thumbnail: "", + author: title, + }); + if (confirmed) { + live = confirmed; + } + // Do NOT promote is_live_content alone — scheduled / LIVE_STREAM_OFFLINE + // rooms still have is_live_content=true while is_live=false. } } catch { - /* some channels have no live tab */ + /* ignore — fall through to tabs */ + } + + // 1) Live tab + if (!live) { + try { + const feed = await channel.getLiveStreams(); + await scanFeedVideos(feed?.videos, 20); + if (!live && lives[0]?.id) { + const confirmed = await confirmLive(lives[0]); + if (confirmed) live = confirmed; + } + } catch { + /* some channels have no live tab */ + } } // 2) Home tab — active streams often pinned here