From 00205593077f24538773e2e68dcc41be7b0cb4c4 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 1 Sep 2026 11:41:13 -0500 Subject: [PATCH] Add CDP fallback when Neko extension telemetry is missing. Detect YouTube Live tab via Chrome DevTools inside the container when ingest heartbeats never arrive; nudge tab focus every 10s. Fixes time-slot relay stuck at starting while Neko UI already shows Live page. Co-authored-by: Cursor --- backend/app/youtube_neko.py | 159 ++++++++++++++++++++++---- backend/app/youtube_relay_pipeline.py | 18 ++- scripts/_deploy_neko_live_wait.py | 22 ++-- 3 files changed, 156 insertions(+), 43 deletions(-) diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py index 2e17506..ee8537e 100644 --- a/backend/app/youtube_neko.py +++ b/backend/app/youtube_neko.py @@ -856,6 +856,71 @@ def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool: return False +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) + py = ( + "import json,urllib.request\n" + "try:\n" + " r=urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4)\n" + " print(r.read().decode())\n" + "except Exception:\n" + " print('[]')" + ) + code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=15) + if code != 0: + return [] + try: + data = json.loads(out or "[]") + return data if isinstance(data, list) else [] + except json.JSONDecodeError: + return [] + + +def _cdp_live_studio_urls(instance_id: int) -> list[str]: + urls: list[str] = [] + for tab in _cdp_fetch_tabs(instance_id): + u = str(tab.get("url") or "").strip() + if "studio.youtube.com" in u and "livestreaming" in u: + urls.append(u) + return urls + + +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) + py = ( + "import json,time,urllib.request\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" + " 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" + " time.sleep(1)\n" + "print(json.dumps({'ok':False,'error':'no_live_tab'}))" + ) + code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=20) + 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]} + + def latest_live_studio_event( *, max_age_sec: float = 60.0, @@ -884,22 +949,36 @@ def recent_live_studio_seen(*, max_age_sec: float = 120.0, since_ts: float = 0.0 return latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts) is not None -def youtube_live_confirmed(*, max_age_sec: float = 45.0, since_ts: float = 0.0) -> dict[str, Any]: +def youtube_live_confirmed(*, max_age_sec: float = 45.0, since_ts: float = 0.0, neko_id: int = 0) -> dict[str, Any]: """Detect whether Studio reports 1 live stream is truly on-air.""" ev = latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts) - if not ev: - return {"ok": False, "live": False, "reason": "no_live_studio_page"} - payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} - confirmed = _payload_stream_confirmed(payload) - return { - "ok": True, - "live": confirmed, - "live_status": str(payload.get("live_status") or ""), - "health": str(payload.get("health") or ""), - "url": str(payload.get("url") or "")[:200], - "received_at": float(ev.get("received_at") or 0), - "reason": "stream_confirmed" if confirmed else "page_open_not_confirmed_live", - } + if ev: + payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + confirmed = _payload_stream_confirmed(payload) + return { + "ok": True, + "live": confirmed, + "live_status": str(payload.get("live_status") or ""), + "health": str(payload.get("health") or ""), + "url": str(payload.get("url") or "")[:200], + "received_at": float(ev.get("received_at") or 0), + "reason": "stream_confirmed" if confirmed else "page_open_not_confirmed_live", + "detect_source": "telemetry", + } + if neko_id > 0: + cdp_urls = _cdp_live_studio_urls(neko_id) + if cdp_urls: + return { + "ok": True, + "live": True, + "live_status": "cdp_live_tab", + "health": "", + "url": cdp_urls[0][:200], + "received_at": 0.0, + "reason": "cdp_livestreaming_tab", + "detect_source": "cdp", + } + return {"ok": False, "live": False, "reason": "no_live_studio_page"} def wait_instance_ready_for_live( @@ -933,6 +1012,8 @@ def wait_instance_ready_for_live( page_first_seen = 0.0 last: dict[str, Any] = {} last_ev: dict[str, Any] | None = None + last_cdp_url = "" + nudge_at = 0.0 while _time.time() < deadline: last = _container_state(idx, check_http=False) @@ -948,19 +1029,44 @@ def wait_instance_ready_for_live( if not require_live_page: return {"ok": True, "id": idx, "ready": True, "live_studio": False, "wait_since": wait_since} - # Fresh Control Room heartbeat after exclusive switch / this wait started. + now = _time.time() + page_detected = False + detect_source = "" + detect_url = "" + + # 1) Chrome extension telemetry (preferred when ingest works) ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since) if ev is None: - # Also accept very fresh events that slightly overlap ensure_instance_running. ev = latest_live_studio_event(max_age_sec=20.0, since_ts=wait_since - 5.0) if ev is not None: last_ev = ev + page_detected = True + detect_source = "telemetry" + payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + detect_url = str(payload.get("url") or "") + + # 2) CDP inside container — extension ingest often fails from Docker + if not page_detected: + cdp_urls = _cdp_live_studio_urls(idx) + if cdp_urls: + page_detected = True + detect_source = "cdp" + detect_url = cdp_urls[0] + last_cdp_url = detect_url + elif now - nudge_at >= 10.0: + nudge_at = now + _cdp_nudge_live_studio_tab(idx) + + if page_detected: if not page_first_seen: - page_first_seen = float(ev.get("received_at") or _time.time()) - settled_for = _time.time() - page_first_seen - # Keep getting heartbeat during settle so the tab is alive, not a one-shot flash. + page_first_seen = now + settled_for = now - page_first_seen if settled_for >= settle_need: - payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {} + live_status = "" + health = "" + if last_ev and isinstance(last_ev.get("payload"), dict): + live_status = str(last_ev["payload"].get("live_status") or "") + health = str(last_ev["payload"].get("health") or "") return { "ok": True, "id": idx, @@ -969,14 +1075,17 @@ def wait_instance_ready_for_live( "settled": True, "settle_sec": round(settled_for, 1), "wait_since": wait_since, - "live_status": str(payload.get("live_status") or ""), - "health": str(payload.get("health") or ""), - "url": str(payload.get("url") or "")[:200], - "note": "live_studio_page_settled", + "live_status": live_status, + "health": health, + "url": (detect_url or last_cdp_url)[:200], + "detect_source": detect_source, + "note": f"live_studio_{detect_source}_settled", } _time.sleep(2.0) - page_open = page_first_seen > 0 or recent_live_studio_seen(max_age_sec=45.0, since_ts=wait_since) + page_open = page_first_seen > 0 or bool(_cdp_live_studio_urls(idx)) + if not page_open: + page_open = recent_live_studio_seen(max_age_sec=45.0, since_ts=wait_since) if strict and require_live_page: return { "ok": False, diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py index 3f609ed..bdf198d 100644 --- a/backend/app/youtube_relay_pipeline.py +++ b/backend/app/youtube_relay_pipeline.py @@ -286,7 +286,15 @@ class YoutubeRelayPipeline: try: from . import youtube_neko - payload["studio_live"] = youtube_neko.youtube_live_confirmed(max_age_sec=60.0) + winner_neko = 0 + if self._exclusive_winner: + for g in groups: + if str(g.get("id") or "") == self._exclusive_winner: + winner_neko = int(g.get("neko_instance_id") or 0) + break + payload["studio_live"] = youtube_neko.youtube_live_confirmed( + max_age_sec=60.0, neko_id=winner_neko + ) except Exception: payload["studio_live"] = {"ok": False, "live": False, "reason": "unavailable"} self._status_cache = payload @@ -875,9 +883,9 @@ class YoutubeRelayPipeline: neko_wait = await asyncio.to_thread( youtube_neko.wait_instance_ready_for_live, neko_id, - timeout_sec=180.0, + timeout_sec=120.0, require_live_page=True, - settle_sec=25.0, + settle_sec=20.0, strict=True, ) if not neko_wait.get("ok") or not neko_wait.get("live_studio"): @@ -894,8 +902,8 @@ class YoutubeRelayPipeline: ) return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait} boot_log.append( - f"[relay] neko Live 页就绪 settled={bool(neko_wait.get('settled'))} " - f"settle={neko_wait.get('settle_sec')}s " + f"[relay] neko Live 页就绪 src={neko_wait.get('detect_source') or 'telemetry'} " + f"settled={bool(neko_wait.get('settled'))} settle={neko_wait.get('settle_sec')}s " f"live_status={neko_wait.get('live_status') or '-'} " f"health={neko_wait.get('health') or '-'} " f"url={(neko_wait.get('url') or '-')[:80]}" diff --git a/scripts/_deploy_neko_live_wait.py b/scripts/_deploy_neko_live_wait.py index 6013b04..d2165e9 100644 --- a/scripts/_deploy_neko_live_wait.py +++ b/scripts/_deploy_neko_live_wait.py @@ -24,19 +24,15 @@ set -euo pipefail systemctl restart douyinweb-api sleep 5 systemctl is-active douyinweb-api -curl -sS http://127.0.0.1:8014/api/youtube/relay/status | python3 -c " -import sys,json -d=json.load(sys.stdin) -print('slot', d.get('settings',{}).get('youtube_relay_time_slot_mode')) -print('studio_live', d.get('studio_live')) -for g in d.get('groups',[]): - if g.get('is_pushing') or 'Evan' in str(g.get('name','')): - print('---', g.get('name'), g.get('business_status'), g.get('status')) - rl=g.get('recent_log') - if isinstance(rl,list): - for line in rl[-5:]: - print(' ', line[:180]) -" +python3 <<'PY' +import sys +sys.path.insert(0,'/opt/douyinWEB/backend') +from app import youtube_neko +urls = youtube_neko._cdp_live_studio_urls(3) +print('cdp_urls', urls[:1]) +n = youtube_neko._cdp_nudge_live_studio_tab(3) +print('nudge', n) +PY echo DONE """