douyinWEB/backend/app/youtube_neko.py
eric dea036c50d Prefer YouTube receiving/Studio on-air for live-map and sync assign lives to hub.
Tighten http/youtubei live probes, classify Studio encoder_lost vs waiting, and keep dy/dylive public live counts aligned via edge assign_lives.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 22:57:52 -05:00

2948 lines
111 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Per-channel Neko browser (Docker) for YouTube Studio on US VPS.
Aligned with sh2/d2ypp2 lessons, adapted for cloud:
- No ShellClash / WireGuard — browser egress is direct (US IP).
- HTTP stays on 127.0.0.1 behind nginx HTTPS (/neko/{id}/ → :920x).
- WebRTC UDP/TCP mux + EPR published on 0.0.0.0 (nginx cannot proxy WebRTC).
- ICE Lite OFF (sh2 forces 0 for stable remote ICE).
- NAT1TO1 = public VPS IP so clients get reachable ICE candidates.
- Containers created by default; running only when neko_enabled.
"""
from __future__ import annotations
import json
import os
import re
import shutil
import socket
import subprocess
import threading
import urllib.request
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from .config import settings
_lock = threading.RLock()
def _max_instances() -> int:
try:
n = int(getattr(settings, "neko_max_instances", 256) or 256)
except Exception:
n = 256
return max(1, min(n, 1024))
# Back-compat alias used across this module
MAX_INSTANCES = _max_instances()
_nat_ip_cache: str = ""
_nat_ip_cached_at: float = 0.0
_NAT_CACHE_TTL_SEC = 3600.0
_list_cache_at: float = 0.0
_list_cache_count: int = -1
_list_cache_rows: list[dict[str, Any]] = []
_LIST_CACHE_TTL_SEC = 5.0
_list_cache_check_http: bool = False
def _neko_root() -> Path:
p = settings.data_dir / "neko"
p.mkdir(parents=True, exist_ok=True)
(p / "profiles").mkdir(parents=True, exist_ok=True)
return p
def _asset_root() -> Path:
"""Repo-bundled sh2 Neko assets: Tampermonkey seed, policies, browser-launch, live-ops."""
# backend/app/youtube_neko.py → backend/neko/
return Path(__file__).resolve().parent.parent / "neko"
def _neko_browser_proxy_value() -> str:
"""Host-reachable proxy for Chromium inside the container."""
try:
from . import egress_hub
return str(egress_hub.neko_browser_proxy() or "").strip()
except Exception:
return str(os.environ.get("DY_NEKO_BROWSER_PROXY") or "").strip()
def refresh_compose_for_egress() -> dict[str, Any]:
"""Rewrite compose with current NEKO_BROWSER_PROXY and recreate stopped containers."""
with _lock:
try:
desired = max(1, min(_max_instances(), int(_desired_from_db())))
except Exception:
desired = 2
compose = _compose_path()
text = _render_compose(desired)
compose.write_text(text, encoding="utf-8")
# Recreate so env NEKO_BROWSER_PROXY is picked up; keep running set running.
running: set[int] = set()
try:
for idx in range(1, desired + 1):
name = _container_name(idx)
code, out = _run(["docker", "inspect", "-f", "{{.State.Running}}", name], timeout=8)
if code == 0 and "true" in (out or "").lower():
running.add(idx)
except Exception:
pass
code, out = _run(
_compose_cmd("up", "-d", "--force-recreate", "--no-start"),
timeout=900,
)
started: list[int] = []
errors: list[str] = []
if code != 0:
errors.append(out[-500:])
for idx in sorted(running):
c2, o2 = _run(_compose_cmd("start", f"neko{idx}"), timeout=120)
if c2 == 0:
started.append(idx)
else:
errors.append(f"neko{idx}: {o2[-200:]}")
proxy = _neko_browser_proxy_value()
return {
"ok": code == 0 and not errors,
"desired": desired,
"proxy": proxy,
"restarted": started,
"error": "; ".join(errors) if errors else "",
}
def _compose_path() -> Path:
return _neko_root() / "docker-compose.yml"
def _supervisor_conf_name() -> str:
image = str(getattr(settings, "neko_image", "") or "").lower()
if "google-chrome" in image or "chrome" in image:
return "google-chrome.conf"
return "chromium.conf"
def _managed_policies_enabled() -> bool:
raw = str(getattr(settings, "neko_managed_policies", "") or os.environ.get("DY_NEKO_MANAGED_POLICIES") or "0")
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _http_port(instance_id: int) -> int:
return int(getattr(settings, "neko_http_port_base", 9200) or 9200) + instance_id - 1
def _http_bind() -> str:
"""Host bind for Neko HTTP publish.
VPS colocated (nginx/Caddy on same box): 127.0.0.1
Physical (edge TLS on VPS via WireGuard): 0.0.0.0 so 10.8.0.2:920x is reachable
"""
raw = str(os.environ.get("DY_NEKO_HTTP_BIND") or getattr(settings, "neko_http_bind", "") or "").strip()
if raw:
return raw
if str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip():
return "0.0.0.0"
return "127.0.0.1"
def _ensure_browser_launch_exec() -> None:
"""Windows→Linux deploys often drop +x; Chromium supervisor requires executable."""
path = _asset_root() / "browser-launch.sh"
try:
if path.is_file():
os.chmod(path, 0o755)
except OSError:
pass
def _webrtc_mux(instance_id: int) -> int:
return int(getattr(settings, "neko_webrtc_mux_base", 52300) or 52300) + instance_id - 1
def _udp_range(instance_id: int) -> str:
"""Match sh2 default_udp_range — avoid .99 collision patterns."""
idx = int(instance_id)
if idx == 1:
return "52000-52098"
if idx == 2:
return "52101-52199"
if idx == 3:
return "52201-52299"
start = 52400 + ((idx - 4) * 100)
return f"{start}-{start + 99}"
def _container_name(instance_id: int) -> str:
return f"douyinweb-neko-{instance_id}"
def _docker_available() -> bool:
return bool(shutil.which("docker"))
def _run(cmd: list[str], *, timeout: float = 120.0, input_text: str | None = None) -> tuple[int, str]:
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
input=input_text,
)
out = (proc.stdout or "") + (proc.stderr or "")
return proc.returncode, out.strip()
except subprocess.TimeoutExpired:
return 124, "timeout"
except OSError as exc:
return 1, str(exc)
def _public_base() -> str:
base = str(settings.public_base_url or "").strip().rstrip("/")
if base:
return base
for key in ("DY_PUBLIC_BASE_URL", "PUBLIC_BASE"):
alt = str(os.environ.get(key) or "").strip().rstrip("/")
if alt:
return alt
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).
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()
env_ip = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip()
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:
return _nat_ip_cache
cache_file = _neko_root() / "nat1to1.txt"
if cache_file.is_file():
try:
cached = cache_file.read_text(encoding="utf-8").strip()
if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cached):
_nat_ip_cache = cached
_nat_ip_cached_at = now
return cached
except OSError:
pass
ip = ""
proxy = ""
try:
from . import egress_hub
proxy = str(egress_hub.google_http_proxy() or "").strip()
except Exception:
proxy = ""
for url in (
"https://checkip.amazonaws.com",
"https://api.ipify.org",
"https://ifconfig.me/ip",
):
try:
if proxy:
import httpx
with httpx.Client(timeout=6.0, trust_env=False, proxy=proxy) as client:
cand = (client.get(url).text or "").strip()
else:
with urllib.request.urlopen(url, timeout=4) as resp:
cand = (resp.read().decode("utf-8", "replace") or "").strip()
if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cand):
ip = cand
break
except Exception:
continue
if not ip:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(2)
s.connect(("8.8.8.8", 80))
cand = s.getsockname()[0]
s.close()
if cand and not cand.startswith("127."):
ip = cand
except OSError:
pass
if not ip:
# Prefer explicit NAT1TO1; never invent a datacenter IP for the wrong host.
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
try:
cache_file.write_text(ip + "\n", encoding="utf-8")
except OSError:
pass
return ip
def _desired_from_db() -> int:
"""Max assigned neko_instance_id across assign groups (never shrink on single-instance start)."""
try:
from . import yt_assign_db
groups = yt_assign_db.list_groups(include_urls=False)
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
return max(ids) if ids else 0
except Exception:
return 0
def _ensure_profile(instance_id: int) -> Path:
profile = _neko_root() / "profiles" / str(instance_id)
profile.mkdir(parents=True, exist_ok=True)
try:
os.chmod(profile, 0o777)
except OSError:
pass
# Tampermonkey/script seeding is sh2's job: browser-launch.sh + Chrome policies
# (NEKO_MANAGED_POLICIES=1 → ExtensionInstallForcelist + jsonImport from :18080).
return profile
def _ensure_instance_id_file(instance_id: int) -> Path:
"""Per-container file bind-mounted into the live-ops extension for telemetry tagging."""
meta = _neko_root() / "instance-meta" / str(int(instance_id))
meta.mkdir(parents=True, exist_ok=True)
path = meta / "instance_id.txt"
want = f"{int(instance_id)}\n"
try:
if not path.exists() or path.read_text(encoding="utf-8") != want:
path.write_text(want, encoding="utf-8")
except OSError:
pass
return path
_TM_EXT_ID = "dhdgffkkebhmkfjojejmpbldmpobfkfo"
def _q(value: str) -> str:
return json.dumps(str(value), ensure_ascii=False)
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"
)
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "Xiao4669805@")
nat1to1 = _detect_public_ip()
shm = str(getattr(settings, "neko_shm_size", "") or "512mb")
# 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", "")
or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
)
tz = "America/Chicago"
assets = _asset_root()
managed = _managed_policies_enabled()
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_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):
lines.extend(
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"
def _compose_cmd(*args: str) -> list[str]:
path = str(_compose_path())
if shutil.which("docker-compose"):
return ["docker-compose", "-f", path, *args]
code, _ = _run(["docker", "compose", "version"], timeout=15)
if code == 0:
return ["docker", "compose", "-f", path, *args]
raise RuntimeError("未找到 docker-compose 或 docker compose,请安装 Docker Compose")
def _compose_up(*, desired: int, start_instances: set[int]) -> tuple[int, str]:
"""Create all containers stopped; start only requested instances.
Do NOT use --remove-orphans — starting a lower id must never wipe higher instances.
"""
code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600)
if code != 0 and "--no-start" in out.lower():
code, out = _run(_compose_cmd("up", "-d"), timeout=600)
if code != 0:
return code, out
for idx in range(1, desired + 1):
if idx not in start_instances:
_run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
return code, out
if code != 0:
return code, out
for idx in sorted(start_instances):
if 1 <= idx <= desired:
_run(["docker", "start", _container_name(idx)], timeout=60)
return code, out
def _open_firewall(desired: int) -> None:
"""Best-effort UFW rules for WebRTC ports (HTTP stays nginx-only)."""
if not shutil.which("ufw"):
return
mux_lo = _webrtc_mux(1)
mux_hi = _webrtc_mux(max(1, desired))
_run(["ufw", "allow", f"{mux_lo}:{mux_hi}/tcp"], timeout=30)
_run(["ufw", "allow", f"{mux_lo}:{mux_hi}/udp"], timeout=30)
for idx in range(1, desired + 1):
udp = _udp_range(idx)
_run(["ufw", "allow", f"{udp}/udp"], timeout=30)
def _container_state(instance_id: int, *, check_http: bool = False) -> dict[str, Any]:
name = _container_name(instance_id)
port = _http_port(instance_id)
out: dict[str, Any] = {
"id": instance_id,
"container": name,
"http_port": port,
"webrtc_mux": _webrtc_mux(instance_id),
"udp_range": _udp_range(instance_id),
"studio_url": public_studio_url(instance_id),
"exists": False,
"running": False,
"ready": False,
"status": "missing",
"detail": "",
}
if not _docker_available():
out["detail"] = "docker_unavailable"
return out
code, text = _run(
["docker", "inspect", name, "--format", "{{json .State}}"],
timeout=15,
)
if code != 0:
out["detail"] = text[:200]
return out
out["exists"] = True
try:
state = json.loads(text or "{}")
except json.JSONDecodeError:
out["detail"] = text[:200]
return out
running = bool(state.get("Running"))
health = str((state.get("Health") or {}).get("Status") or "")
out["running"] = running
if not running:
out["status"] = "stopped"
else:
out["status"] = health if health else "running"
if running:
if check_http:
# Expensive: subprocess curl per instance — only for explicit readiness probes.
code, text = _run(
["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
timeout=8,
)
out["ready"] = code == 0 and text.strip().endswith("200")
else:
# Hot path (relay status polls): docker health / running is enough.
out["ready"] = health in {"", "healthy", "starting"} or not health
if health == "unhealthy":
out["ready"] = False
return out
def _empty_instance_row(instance_id: int) -> dict[str, Any]:
return {
"id": instance_id,
"container": _container_name(instance_id),
"http_port": _http_port(instance_id),
"webrtc_mux": _webrtc_mux(instance_id),
"udp_range": _udp_range(instance_id),
"studio_url": public_studio_url(instance_id),
"exists": False,
"running": False,
"ready": False,
"status": "missing",
"detail": "",
}
def _batch_container_states(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
"""One `docker ps` for all neko containers — avoids N inspect + N curl on every poll."""
n = max(0, int(count))
rows = [_empty_instance_row(i) for i in range(1, n + 1)]
if n <= 0:
return rows
if not _docker_available():
for r in rows:
r["detail"] = "docker_unavailable"
return rows
code, text = _run(
[
"docker",
"ps",
"-a",
"--filter",
"name=douyinweb-neko-",
"--format",
"{{.Names}}\t{{.State}}\t{{.Status}}",
],
timeout=12,
)
if code != 0:
# Fallback to per-instance inspect without HTTP.
return [_container_state(i, check_http=check_http) for i in range(1, n + 1)]
by_name: dict[str, tuple[str, str]] = {}
for line in (text or "").splitlines():
parts = line.split("\t")
if len(parts) < 2:
continue
name = parts[0].strip().lstrip("/")
state = parts[1].strip().lower()
status = parts[2].strip() if len(parts) > 2 else ""
by_name[name] = (state, status)
for i, row in enumerate(rows, start=1):
name = _container_name(i)
hit = by_name.get(name)
if not hit:
continue
state, status = hit
row["exists"] = True
running = state == "running"
row["running"] = running
status_l = status.lower()
if not running:
row["status"] = "stopped"
row["ready"] = False
elif "(healthy)" in status_l:
row["status"] = "healthy"
row["ready"] = True
elif "(unhealthy)" in status_l:
row["status"] = "unhealthy"
row["ready"] = False
elif "(health: starting)" in status_l:
row["status"] = "starting"
row["ready"] = True
else:
row["status"] = "running"
row["ready"] = True
if running and check_http:
port = int(row["http_port"])
c2, t2 = _run(
["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
timeout=8,
)
row["ready"] = c2 == 0 and t2.strip().endswith("200")
return rows
def ensure_capacity(
desired: int,
*,
start_instances: set[int] | None = None,
reconcile_running: bool = False,
) -> dict[str, Any]:
"""Render compose for `desired` instances; create all, start only requested.
reconcile_running=True (sync_for_groups): stop instances not in start_instances.
reconcile_running=False (single start/restart): never stop siblings.
"""
_ensure_browser_launch_exec()
desired = max(0, min(_max_instances(), int(desired or 0)))
# Never shrink below DB assignment (protects against start(#2) wiping #3+).
desired = max(desired, _desired_from_db())
if desired == 0:
return {"ok": True, "desired": 0, "changed": False, "message": "no_instances"}
if not _docker_available():
return {"ok": False, "desired": desired, "error": "Docker 不可用,请先在服务器安装 Docker"}
start_set = set(start_instances or ())
with _lock:
try:
compose = _compose_path()
text = _render_compose(desired)
changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text
if changed:
# Persist desired compose for next explicit recreate — do NOT force
# `compose up` solely because YAML text changed (that kills keep-warm
# Chrome logins/tabs on every API deploy that touches render).
compose.write_text(text, encoding="utf-8")
missing = [i for i in range(1, desired + 1) if not _container_state(i).get("exists")]
need_up = bool(missing)
out = ""
if need_up:
code, out = _compose_up(desired=desired, start_instances=start_set)
if code != 0:
return {"ok": False, "desired": desired, "error": out[:800] or "compose up failed"}
else:
for idx in sorted(start_set):
if 1 <= idx <= desired and not _container_state(idx).get("running"):
_run(["docker", "start", _container_name(idx)], timeout=60)
stopped: list[int] = []
if reconcile_running:
for idx in range(1, desired + 1):
st = _container_state(idx)
if st.get("running") and idx not in start_set:
_run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
stopped.append(idx)
if changed or need_up:
_open_firewall(desired)
sync_nginx_proxy(desired)
created = sum(1 for i in range(1, desired + 1) if _container_state(i).get("exists"))
return {
"ok": True,
"desired": desired,
"created": created,
"changed": changed,
"compose_up": need_up,
"started": sorted(start_set),
"stopped": stopped,
"nat1to1": _detect_public_ip(),
"detail": (out or "")[:300],
}
except RuntimeError as exc:
return {"ok": False, "desired": desired, "error": str(exc)}
def sync_nginx_proxy(count: int) -> dict[str, Any]:
"""Nginx: /neko/{id}/ → http://127.0.0.1:920x/ (strip prefix; Neko has no path_prefix)."""
caddy = sync_caddy_neko_snippet(count)
base = _public_base()
if not base:
return {"ok": False, "skipped": "no_public_base", "caddy": caddy}
host = urlparse(base).hostname or ""
if not host:
return {"ok": False, "skipped": "no_host", "caddy": caddy}
if not Path("/etc/nginx/conf.d").is_dir():
return {"ok": False, "skipped": "no_nginx", "caddy": caddy}
blocks: list[str] = []
for idx in range(1, max(0, int(count)) + 1):
port = _http_port(idx)
# Trailing slash on proxy_pass strips /neko/{idx}/ → container /
blocks.append(
f"""
location = /neko/{idx} {{
return 301 /neko/{idx}/;
}}
location ^~ /neko/{idx}/ {{
proxy_pass http://127.0.0.1:{port}/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}}"""
)
include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.inc")
try:
include_path.write_text("\n".join(blocks) + "\n", encoding="utf-8")
legacy = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf")
if legacy.is_file():
legacy.unlink()
vhost = Path("/etc/nginx/conf.d/dy-nomadro-live.conf")
if not vhost.is_file():
for p in Path("/etc/nginx/conf.d").glob("*.conf"):
if "nomadro" in p.name or "douyin" in p.name:
vhost = p
break
if vhost.is_file():
raw = vhost.read_text(encoding="utf-8")
marker = f"include {include_path};"
legacy_marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;"
if legacy_marker in raw:
raw = raw.replace(legacy_marker, marker)
elif marker not in raw and "douyinweb-neko-locations" not in raw:
raw = raw.replace(
"location / {",
f" {marker}\n\n location / {{",
1,
)
vhost.write_text(raw, encoding="utf-8")
code, out = _run(["nginx", "-t"], timeout=15)
if code != 0:
return {"ok": False, "error": out[:400] or "nginx -t failed"}
_run(["systemctl", "reload", "nginx"], timeout=15)
return {"ok": True, "instances": count, "caddy": caddy}
except OSError as exc:
return {"ok": False, "error": str(exc), "caddy": caddy}
def sync_caddy_neko_snippet(count: int) -> dict[str, Any]:
"""Write Caddy fragment for edges.
Preferred (unlimited): single `/neko/*` → `{upstream}:{gateway_port}` where the
physical API runs neko_edge_gateway. Legacy per-id blocks still generated as
fallback when DY_NEKO_GATEWAY_ENABLED=0.
"""
n = max(0, min(_max_instances(), int(count or 0)))
upstream_host = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "127.0.0.1").strip() or "127.0.0.1"
gw_port = int(getattr(settings, "neko_gateway_port", 9199) or 9199)
gw_on = True
try:
from . import neko_edge_gateway
gw_on = neko_edge_gateway.gateway_enabled()
except Exception:
gw_on = bool(getattr(settings, "neko_gateway_enabled", True))
lines = [
"# Generated by douyinWEB youtube_neko.sync_caddy_neko_snippet — do not hand-edit",
f"# instances={n} upstream={upstream_host} gateway={gw_on} gw_port={gw_port}",
]
if gw_on:
lines.extend(
[
"handle /neko {",
"\tredir /neko/ 308",
"}",
"@neko path /neko /neko/*",
"handle @neko {",
f"\treverse_proxy {upstream_host}:{gw_port} {{",
"\t\theader_up Host {host}",
"\t\theader_up X-Forwarded-Proto {scheme}",
"\t\theader_up X-Forwarded-Host {host}",
"\t}",
"}",
]
)
else:
for idx in range(1, n + 1):
port = _http_port(idx)
lines.extend(
[
f"handle /neko/{idx} {{",
f"\tredir /neko/{idx}/ 308",
"}",
f"handle_path /neko/{idx}/* {{",
f"\treverse_proxy {upstream_host}:{port} {{",
"\t\theader_up Host {host}",
"\t\theader_up X-Forwarded-Proto {scheme}",
"\t}",
"}",
]
)
out = _neko_root() / "caddy-neko.snippet"
try:
_neko_root().mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(lines) + "\n", encoding="utf-8")
return {
"ok": True,
"path": str(out),
"instances": n,
"upstream": upstream_host,
"gateway": gw_on,
"gateway_port": gw_port,
}
except OSError as exc:
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"}:
raise ValueError(f"不支持的操作: {action}")
if instance_id < 1 or instance_id > _max_instances():
raise ValueError(f"实例编号须在 1–{_max_instances()}")
before = _container_state(instance_id)
message = f"Neko {instance_id}: {before.get('status')}"
# 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", 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", 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", 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} 已重启"
after = _container_state(instance_id)
after["action"] = action
after["message"] = message
after["available"] = _docker_available()
_invalidate_list_cache()
return after
def list_instances(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
"""Read container states; TTL cache for relay status polls (no HTTP curl by default)."""
global _list_cache_at, _list_cache_count, _list_cache_rows, _list_cache_check_http
import time as _time
n = max(0, int(count))
now = _time.time()
if (
_list_cache_rows
and _list_cache_count == n
and _list_cache_check_http == bool(check_http)
and (now - _list_cache_at) < _LIST_CACHE_TTL_SEC
):
return list(_list_cache_rows)
rows = _batch_container_states(n, check_http=bool(check_http))
_list_cache_rows = rows
_list_cache_count = n
_list_cache_check_http = bool(check_http)
_list_cache_at = now
return list(rows)
def _invalidate_list_cache() -> None:
global _list_cache_at
_list_cache_at = 0.0
def _docker_max_instance_id() -> int:
"""Highest douyinweb-neko-N that exists (even if groups table is empty)."""
if not _docker_available():
return 0
code, text = _run(
[
"docker",
"ps",
"-a",
"--filter",
"name=douyinweb-neko-",
"--format",
"{{.Names}}",
],
timeout=12,
)
if code != 0:
return 0
best = 0
for line in (text or "").splitlines():
name = line.strip().lstrip("/")
if not name.startswith("douyinweb-neko-"):
continue
suffix = name[len("douyinweb-neko-") :]
try:
best = max(best, int(suffix))
except ValueError:
continue
return best
def status_summary(*, desired: int) -> dict[str, Any]:
"""Read-only status — does not run compose/nginx."""
desired = max(0, min(_max_instances(), int(desired or 0)))
if desired < 1:
desired = _desired_from_db()
# Physical / ops: show already-created containers even before assign groups exist.
desired = max(desired, _docker_max_instance_id())
instances = list_instances(desired)
running = sum(1 for x in instances if x.get("running"))
assets = _asset_root()
return {
"available": _docker_available(),
"desired": desired,
"running": running,
"instances": instances,
"enabled": bool(getattr(settings, "neko_enabled", True)),
"nat1to1": _detect_public_ip(),
"http_bind": _http_bind(),
# No plaintext passwords in API responses.
"login_hint": "用户名任意;普通密码见 DY_NEKO_USER_PASS;管理员密码见 DY_NEKO_ADMIN_PASS",
"assets": {
"root": str(assets),
"tampermonkey_seed": (assets / "tampermonkey-seed" / "Default" / "Extensions").is_dir(),
"userscript": (assets / "provisioning" / "youtube-studio-auto-dismiss.user.js").is_file(),
"browser_launch": (assets / "browser-launch.sh").is_file(),
"live_ops": (assets / "live-ops-extension" / "manifest.json").is_file(),
"managed_policies": _managed_policies_enabled(),
},
"studio_telemetry": latest_studio_telemetry(limit=8),
}
def sync_for_groups(
groups: list[dict[str, Any]],
*,
reconcile_running: bool = False,
) -> dict[str, Any]:
"""Ensure docker containers exist for all assign groups; start only neko_enabled.
reconcile_running=False (default): create capacity / start enabled — never stop
siblings (physical keep-warm + exclusive-live Studio must survive API boot).
True: stop containers whose groups are not neko_enabled (explicit ops only).
"""
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
desired = max(ids) if ids else 0
if desired == 0:
return {"ok": True, "desired": 0}
start_set = {
int(g.get("neko_instance_id") or 0)
for g in groups
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
}
return ensure_capacity(desired, start_instances=start_set, reconcile_running=reconcile_running)
def stop_instance(instance_id: int) -> dict[str, Any]:
"""Stop one Neko container (time-slot off-duty). Does not change neko_enabled."""
idx = int(instance_id or 0)
if idx < 1:
return {"ok": False, "skipped": "no_instance"}
st = _container_state(idx)
if not st.get("running"):
return {"ok": True, "id": idx, "already_stopped": True}
code, out = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
if code != 0:
return {"ok": False, "id": idx, "error": (out or "stop failed")[:300]}
return {"ok": True, "id": idx, "stopped": True}
def stop_instances_except(keep_instance_id: int) -> list[int]:
"""Stop running Neko containers except `keep_instance_id`. Does not change neko_enabled."""
keep = int(keep_instance_id or 0)
desired = max(_desired_from_db(), keep, 0)
stopped: list[int] = []
for idx in range(1, desired + 1):
if idx == keep:
continue
st = _container_state(idx)
if not st.get("running"):
continue
code, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
if code == 0:
stopped.append(idx)
return stopped
def ensure_instance_running(instance_id: int) -> dict[str, Any]:
"""Ensure one Neko container exists and is running (for exclusive-live winner)."""
_ensure_browser_launch_exec()
idx = int(instance_id or 0)
if idx < 1:
return {"ok": False, "skipped": "no_instance"}
desired = max(_desired_from_db(), idx)
ensure_capacity(desired, start_instances={idx}, reconcile_running=False)
st = _container_state(idx)
if st.get("running"):
return {"ok": True, "id": idx, "already": True}
code, out = _run(["docker", "start", _container_name(idx)], timeout=60)
if code != 0:
return {"ok": False, "id": idx, "error": (out or "start failed")[:300]}
return {"ok": True, "id": idx, "started": True}
def _payload_is_livestreaming(payload: dict[str, Any] | None) -> bool:
body = payload or {}
url = str(body.get("url") or "").lower()
path = str((body.get("signals") or {}).get("path") or "").lower()
return "livestreaming" in url or "livestreaming" in path
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()
if any(
x in text
for x in (
"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",
"待开播",
"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
health = str(body.get("health") or "").strip().lower()
if status == "live":
return True
# 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):
return True
except (TypeError, ValueError):
pass
if any(
x in text
for x in (
"you're live",
"you are live",
"watching now",
"正在直播",
"直播中",
"人正在观看",
)
):
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)
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]:
from urllib.parse import urlparse
urls: list[str] = []
for tab in _cdp_fetch_tabs(instance_id):
u = str(tab.get("url") or "").strip()
try:
p = urlparse(u)
except Exception:
continue
host = (p.netloc or "").lower()
path = (p.path or "").lower()
if host.endswith("studio.youtube.com") and "livestreaming" in path:
urls.append(u)
return urls
_cdp_signal_cache: dict[int, tuple[float, dict[str, Any]]] = {}
def _cdp_studio_page_signals(
instance_id: int,
*,
max_age_sec: float = 45.0,
force: bool = False,
) -> dict[str, Any]:
"""Read-only CDP scrape of Studio Live page text (no tab close / no Chrome restart).
Script is fed via ``docker exec -i … python3 -`` stdin (no docker cp / no Chrome restart).
"""
import time as _time
nid = int(instance_id or 0)
if nid < 1:
return {"ok": False, "error": "bad_id"}
now = _time.time()
cached = _cdp_signal_cache.get(nid)
if (not force) and cached and (now - float(cached[0])) <= max_age_sec:
return dict(cached[1])
name = _container_name(nid)
script = _asset_root() / "cdp_studio_scrape.py"
if not script.is_file():
row = {"ok": False, "error": "scrape_script_missing"}
_cdp_signal_cache[nid] = (now, row)
return row
# Feed script via stdin — avoids docker cp onto read-only overlay mounts.
try:
script_text = script.read_text(encoding="utf-8")
except OSError as exc:
row = {"ok": False, "error": f"read_script:{exc}"}
_cdp_signal_cache[nid] = (now, row)
return row
code, out = _run(
["docker", "exec", "-i", name, "python3", "-"],
timeout=25,
input_text=script_text,
)
row: dict[str, Any] = {"ok": False, "error": "cdp_scrape_failed"}
try:
line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}"
parsed = json.loads(line)
if isinstance(parsed, dict):
row = parsed
except Exception:
row = {"ok": False, "error": (out or f"exit_{code}")[:220]}
_cdp_signal_cache[nid] = (now, row)
return row
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,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"
"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"
" 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=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 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(
*,
max_age_sec: float = 60.0,
since_ts: float = 0.0,
neko_id: int = 0,
) -> dict[str, Any] | None:
"""Newest Studio Control Room telemetry, optionally only after `since_ts`."""
import time as _time
now = _time.time()
since = float(since_ts or 0)
want = int(neko_id or 0)
for ev in _studio_events[:80]:
received = float(ev.get("received_at") or 0)
if since > 0 and received < since:
continue
if now - received > max_age_sec:
continue
payload = ev.get("payload") or {}
if not _payload_is_livestreaming(payload if isinstance(payload, dict) else {}):
continue
ev_nid = int(ev.get("neko_instance_id") or 0)
if want > 0:
# Strict: only events tagged for this instance (never share untagged globally).
if ev_nid == want:
return ev
continue
return ev
return None
def recent_live_studio_seen(*, max_age_sec: float = 120.0, since_ts: float = 0.0) -> bool:
"""True if any recent studio telemetry URL is YouTube Live Control Room."""
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, neko_id: int = 0) -> dict[str, Any]:
"""Detect whether Studio reports a stream is truly on-air (tab open alone is NOT live)."""
ev = latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts, neko_id=neko_id)
if ev:
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
confirmed = _payload_stream_confirmed(payload)
return {
"ok": True,
"live": confirmed,
"page_open": _payload_is_livestreaming(payload),
"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),
"neko_instance_id": int(ev.get("neko_instance_id") or neko_id or 0),
"viewer_count": payload.get("viewer_count"),
"reason": "stream_confirmed" if confirmed else "page_open_not_confirmed_live",
"detect_source": "telemetry",
}
if neko_id > 0:
# Prefer cached CDP DOM (poller / prior lookup); do not treat bare tab URL as on-air.
try:
sig = _cdp_studio_page_signals(int(neko_id), max_age_sec=max(45.0, float(max_age_sec)))
except Exception:
sig = {}
if isinstance(sig, dict) and sig.get("ok"):
on_air = bool(sig.get("on_air"))
return {
"ok": True,
"live": on_air,
"page_open": True,
"live_status": str(sig.get("live_status") or ""),
"health": str(sig.get("health") or ""),
"url": str(sig.get("url") or "")[:200],
"received_at": 0.0,
"neko_instance_id": int(neko_id),
"viewer_count": sig.get("viewer_count"),
"reason": "cdp_dom_on_air" if on_air else "cdp_dom_page_not_on_air",
"detect_source": "cdp_dom",
}
cdp_urls = _cdp_live_studio_urls(neko_id)
if cdp_urls:
return {
"ok": True,
"live": False,
"page_open": True,
"live_status": "cdp_live_tab",
"health": "",
"url": cdp_urls[0][:200],
"received_at": 0.0,
"neko_instance_id": int(neko_id),
"viewer_count": None,
"reason": "cdp_livestreaming_tab_not_confirmed",
"detect_source": "cdp",
}
return {"ok": False, "live": False, "page_open": False, "reason": "no_live_studio_page"}
def wait_instance_ready_for_live(
instance_id: int,
*,
timeout_sec: float = 180.0,
require_live_page: bool = True,
settle_sec: float = 25.0,
strict: bool = True,
) -> dict[str, Any]:
"""Block until Neko is up AND Studio livestreaming page is freshly open + settled.
Time-slot / exclusive mode must pass ``strict=True`` so FFmpeg never starts on a
stale telemetry hit or a soft timeout (that causes YouTube green-loading RTMP).
Telemetry must arrive *after* this wait begins (post exclusive Neko switch).
"""
import time as _time
idx = int(instance_id or 0)
if idx < 1:
return {"ok": True, "skipped": "no_instance"}
started = ensure_instance_running(idx)
if not started.get("ok") and not started.get("already"):
return {"ok": False, "id": idx, "error": started.get("error") or "neko_start_failed"}
# Ignore telemetry from the previous slot/channel (green-loading root cause).
wait_since = _time.time()
settle_need = max(8.0, float(settle_sec))
deadline = wait_since + max(settle_need + 20.0, float(timeout_sec))
ready_at = 0.0
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)
running = bool(last.get("running"))
ready = bool(last.get("ready")) or (
running and str(last.get("status") or "") in {"running", "healthy", "starting"}
)
if not (running and ready):
_time.sleep(2.0)
continue
if not ready_at:
ready_at = _time.time()
if not require_live_page:
return {"ok": True, "id": idx, "ready": True, "live_studio": False, "wait_since": wait_since}
now = _time.time()
page_detected = False
detect_source = ""
detect_url = ""
# 1) Chrome extension telemetry (preferred when ingest works)
# 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, neko_id=idx)
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 = now
settled_for = now - page_first_seen
if settled_for >= settle_need:
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,
"ready": True,
"live_studio": True,
"settled": True,
"settle_sec": round(settled_for, 1),
"wait_since": wait_since,
"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 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,
"id": idx,
"ready": bool(last.get("ready")),
"live_studio": bool(page_open),
"timeout": True,
"wait_since": wait_since,
"error": (
"Neko 已启动,但 YouTube Live 控制页未在时限内稳定打开"
if not page_open
else f"YouTube Live 页已打开,但未稳定满 {int(settle_need)}s(避免绿点无效推流)"
),
"state": last,
"last_event_at": float((last_ev or {}).get("received_at") or 0),
}
return {
"ok": bool(last.get("running")),
"id": idx,
"ready": bool(last.get("ready")),
"live_studio": bool(page_open),
"timeout": True,
"wait_since": wait_since,
"note": "neko_running_after_timeout",
"state": last,
}
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
return sync_for_groups(yt_assign_db.list_groups(include_urls=False))
def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]:
"""Force-recreate every Neko container so bind-mounted assets (browser-launch.sh) refresh."""
desired = _desired_from_db()
if desired <= 0:
return {"ok": True, "desired": 0, "message": "no_instances"}
if not _docker_available():
return {"ok": False, "desired": desired, "error": "Docker 不可用"}
with _lock:
compose = _compose_path()
compose.write_text(_render_compose(desired), encoding="utf-8")
code, out = _run(_compose_cmd("up", "-d", "--force-recreate", "--no-start"), timeout=900)
if code != 0:
return {"ok": False, "desired": desired, "error": (out or "compose recreate failed")[:800]}
started: list[int] = []
if start_enabled:
from . import yt_assign_db
groups = yt_assign_db.list_groups(include_urls=False)
start_set = {
int(g.get("neko_instance_id") or 0)
for g in groups
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
}
for idx in sorted(start_set):
if 1 <= idx <= desired:
_run(["docker", "start", _container_name(idx)], timeout=60)
started.append(idx)
_open_firewall(desired)
sync_nginx_proxy(desired)
return {
"ok": True,
"desired": desired,
"started": started,
"detail": (out or "")[-400:],
}
# --- Studio telemetry ingest (sh2 live-ops extension) ---
_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 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:
nid = int(neko_id or 0)
if nid < 1:
return
try:
path = _minute_report_dir() / f"{nid}.jsonl"
with path.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(report, ensure_ascii=False) + "\n")
except OSError:
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:
root = _minute_report_dir()
except Exception:
return
for path in root.glob("*.jsonl"):
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()
except OSError:
continue
for line in lines[-_STUDIO_MINUTE_MAX :]:
line = (line or "").strip()
if not line:
continue
try:
row = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(row, dict):
rows.append(row)
if not rows:
continue
rows.reverse() # newest first
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:
"""Reload last telemetry after API restart so live-map isn't empty until next Chrome tick."""
global _studio_bootstrapped
if _studio_bootstrapped:
return
_studio_bootstrapped = True
_bootstrap_minute_reports_from_disk()
try:
path = _neko_root() / "studio_telemetry_latest.json"
if not path.exists():
return
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict) or not isinstance(raw.get("payload"), dict):
return
neko_id = int(raw.get("neko_instance_id") or raw["payload"].get("neko_instance_id") or 0)
if neko_id < 1:
neko_id = _resolve_neko_id_for_payload(raw["payload"])
event = {
"id": str(raw.get("id") or "disk"),
"received_at": float(raw.get("received_at") or 0),
"neko_instance_id": neko_id,
"payload": raw["payload"],
}
if event["received_at"] <= 0:
return
_studio_events.insert(0, event)
if neko_id > 0:
_studio_latest_by_neko[neko_id] = event
except Exception:
pass
def _extract_studio_video_id(url: str) -> str:
import re
m = re.search(r"/video/([^/]+)/livestreaming", str(url or ""), re.I)
return str(m.group(1) if m else "").strip()
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_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)
try:
from . import yt_assign_db
for g in yt_assign_db.list_groups(include_urls=False):
try:
nid = int(g.get("neko_instance_id") or 0)
except (TypeError, ValueError):
nid = 0
if nid < 1:
continue
studio = str(g.get("neko_studio_url") or "")
if video_id and video_id in studio:
return "local", f"local:{nid}", nid
if url and studio and (studio.rstrip("/") in url or url.rstrip("/") in studio):
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
return "local", "", 0
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)
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_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 ""),
"health": str(payload.get("health") or ""),
"viewer_count": payload.get("viewer_count"),
"total_views": payload.get("total_views"),
"live_duration": str(payload.get("live_duration") or "")[:16],
"live_duration_sec": payload.get("live_duration_sec"),
"like_count": payload.get("like_count"),
"stream_title": str(payload.get("stream_title") or "")[:120],
"url": str(payload.get("url") or "")[:200],
"source": str(payload.get("source") or "extension")[:32],
}
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 (local or ops-neko)."""
import time as _time
import uuid
_bootstrap_studio_telemetry_from_disk()
body = dict(payload or {})
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
try:
path = _neko_root() / "studio_telemetry_latest.json"
path.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8")
except OSError:
pass
return {
"ok": True,
"event": {
"id": event["id"],
"received_at": event["received_at"],
"neko_instance_id": neko_id,
"neko_ref": ref_key,
"neko_kind": kind,
},
}
def latest_studio_telemetry(*, limit: int = 20) -> list[dict[str, Any]]:
_bootstrap_studio_telemetry_from_disk()
return list(_studio_events[: max(1, min(100, int(limit)))])
def list_studio_minute_reports(neko_id: int = 0, *, limit: int = 30, neko_ref: str = "") -> list[dict[str, Any]]:
_bootstrap_studio_telemetry_from_disk()
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,
*,
max_age_sec: float = 90.0,
allow_cdp: bool = False,
) -> dict[str, Any]:
"""UI-facing Neko Studio feedback: Live page open? On-air? Viewers? Health?"""
import time as _time
nid = int(neko_id or 0)
now = _time.time()
out: dict[str, Any] = {
"neko_instance_id": nid,
"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": "",
# ~90 pts ≈ 1.5h at 1/min — enough for Studio-style viewer timeline chart
"minute_reports": list_studio_minute_reports(nid, limit=90) if nid > 0 else [],
}
if nid < 1:
return out
_bootstrap_studio_telemetry_from_disk()
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 not isinstance(ev, dict):
ev = latest_live_studio_event(max_age_sec=max_age_sec, neko_id=nid)
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
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"),
"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": "telemetry",
}
)
return out
if not allow_cdp:
return out
# CDP fallback when extension ingest is quiet but Chrome still has Live tab.
# Prefer cached DOM signals from the host poller (never force a fresh scrape here).
try:
st = _container_state(nid, check_http=False)
if st.get("running"):
sig = _cdp_studio_page_signals(nid, max_age_sec=90.0)
if isinstance(sig, dict) and sig.get("ok"):
on_air = bool(sig.get("on_air"))
out.update(
{
"live_page_open": True,
"on_air": on_air,
"live_status": str(sig.get("live_status") or ("live" if on_air else "")),
"health": str(sig.get("health") or ""),
"viewer_count": sig.get("viewer_count"),
"total_views": sig.get("total_views"),
"live_duration": str(sig.get("live_duration") or "")[:16],
"live_duration_sec": sig.get("live_duration_sec"),
"url": str(sig.get("url") or "")[:200],
"detect_source": "cdp_dom",
"received_at": now,
"age_sec": 0.0,
}
)
return out
urls = _cdp_live_studio_urls(nid)
if urls:
out.update(
{
"live_page_open": True,
"on_air": False,
"live_status": "cdp_live_tab",
"url": urls[0][:200],
"detect_source": "cdp",
}
)
except Exception:
pass
return out
def studio_on_air_lookup(neko_id: int, *, max_age_sec: float = 120.0) -> dict[str, Any]:
"""Non-destructive live detect: telemetry first, then read-only CDP URL match.
Safe for keep-warm Nekos: never restarts Chrome / never recreates containers.
"""
import time as _time
nid = int(neko_id or 0)
snap = studio_snapshot_for_instance(nid, max_age_sec=max_age_sec, allow_cdp=False)
if snap.get("on_air"):
# Enrich missing Analytics fields from CDP cache (Views / LIVE duration).
if nid > 0 and (snap.get("total_views") is None or not snap.get("live_duration")):
try:
sig = _cdp_studio_page_signals(nid, max_age_sec=90.0)
except Exception:
sig = {}
if isinstance(sig, dict) and sig.get("ok"):
if snap.get("total_views") is None and sig.get("total_views") is not None:
snap["total_views"] = sig.get("total_views")
if not snap.get("live_duration") and sig.get("live_duration"):
snap["live_duration"] = str(sig.get("live_duration") or "")[:16]
snap["live_duration_sec"] = sig.get("live_duration_sec")
if snap.get("viewer_count") is None and sig.get("viewer_count") is not None:
snap["viewer_count"] = sig.get("viewer_count")
return snap
urls: list[str] = []
if nid > 0:
try:
st = _container_state(nid, check_http=False)
if st.get("running"):
urls = _cdp_live_studio_urls(nid)
except Exception:
urls = []
if urls:
snap["live_page_open"] = True
if not snap.get("url"):
snap["url"] = urls[0][:200]
if not snap.get("detect_source"):
snap["detect_source"] = "cdp"
vids = [v for v in (_extract_studio_video_id(u) for u in urls) if v]
if not vids and snap.get("url"):
v0 = _extract_studio_video_id(str(snap.get("url") or ""))
if v0:
vids = [v0]
now = _time.time()
# CDP DOM first — ground truth from the open Studio tab (read-only). Prefer poller cache.
if nid > 0 and urls:
try:
sig = _cdp_studio_page_signals(nid, max_age_sec=55.0)
except Exception:
sig = {}
if isinstance(sig, dict) and sig.get("ok"):
snap["live_page_open"] = True
if sig.get("url"):
snap["url"] = str(sig.get("url") or "")[:200]
snap["live_status"] = str(sig.get("live_status") or "")
snap["health"] = str(sig.get("health") or "")
if sig.get("viewer_count") is not None:
snap["viewer_count"] = sig.get("viewer_count")
if sig.get("total_views") is not None:
snap["total_views"] = sig.get("total_views")
if sig.get("live_duration"):
snap["live_duration"] = str(sig.get("live_duration") or "")[:16]
snap["live_duration_sec"] = sig.get("live_duration_sec")
snap["detect_source"] = "cdp_dom"
snap["received_at"] = now
snap["age_sec"] = 0.0
if sig.get("on_air"):
snap["on_air"] = True
if not snap.get("live_status"):
snap["live_status"] = "live"
return snap
if str(sig.get("live_status") or "") in {"waiting", "ended", "signed_out"}:
snap["on_air"] = False
return snap
if not vids:
return snap
_bootstrap_studio_telemetry_from_disk()
for ev in _studio_events[:60]:
received = float(ev.get("received_at") or 0)
if received and (now - received) > max_age_sec:
continue
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
url = str(payload.get("url") or "")
if not any(v in url for v in vids):
continue
if not _payload_stream_confirmed(payload):
if _payload_is_livestreaming(payload):
snap.setdefault("live_status", str(payload.get("live_status") or ""))
snap.setdefault("health", str(payload.get("health") or ""))
snap["viewer_count"] = payload.get("viewer_count")
snap["received_at"] = received
snap["age_sec"] = round(now - received, 1) if received else None
snap["detect_source"] = "cdp_telemetry_page"
continue
snap.update(
{
"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"),
"like_count": payload.get("like_count"),
"stream_title": str(payload.get("stream_title") or "")[:120],
"url": url[:200],
"received_at": received,
"age_sec": round(now - received, 1) if received else None,
"detect_source": "cdp_telemetry_match",
"neko_instance_id": nid,
}
)
return snap
return snap
def _neko_ids_for_cdp_poll() -> list[int]:
"""Assign groups that keep a Studio Neko warm (enabled + instance id)."""
ids: list[int] = []
try:
from . import yt_assign_db
for g in yt_assign_db.list_groups(include_urls=False):
if not g.get("neko_enabled"):
continue
try:
nid = int(g.get("neko_instance_id") or 0)
except (TypeError, ValueError):
nid = 0
if nid > 0:
ids.append(nid)
except Exception:
return []
return sorted(set(ids))
def _ingest_cdp_signals(neko_id: int, sig: dict[str, Any]) -> dict[str, Any]:
"""Turn a CDP scrape result into the same telemetry / minute-report path as the extension."""
nid = int(neko_id or 0)
if nid < 1 or not isinstance(sig, dict) or not sig.get("ok"):
return {"ok": False, "skipped": True, "neko_instance_id": nid}
url = str(sig.get("url") or "")
live_status = str(sig.get("live_status") or "")
payload: dict[str, Any] = {
"neko_instance_id": nid,
"url": url[:400],
"live_status": live_status,
"health": str(sig.get("health") or ""),
"viewer_count": sig.get("viewer_count"),
"total_views": sig.get("total_views"),
"live_duration": str(sig.get("live_duration") or "")[:16],
"live_duration_sec": sig.get("live_duration_sec"),
"text": str(sig.get("text") or "")[:800],
"source": "cdp",
"signals": {"path": "/livestreaming"} if ("livestreaming" in url.lower() or live_status) else {},
}
if sig.get("on_air") and not payload["live_status"]:
payload["live_status"] = "live"
return ingest_studio_telemetry(payload)
def poll_studio_cdp_once() -> dict[str, Any]:
"""One host-side CDP pass over running Nekos. Never restarts Chrome / never recreates containers."""
import time as _time
ids = _neko_ids_for_cdp_poll()
polled: list[dict[str, Any]] = []
for nid in ids:
try:
st = _container_state(nid, check_http=False)
if not st.get("running"):
polled.append({"neko_instance_id": nid, "skipped": "not_running"})
continue
sig = _cdp_studio_page_signals(nid, force=True)
if isinstance(sig, dict) and sig.get("ok"):
ingest = _ingest_cdp_signals(nid, sig)
polled.append(
{
"neko_instance_id": nid,
"ok": True,
"on_air": bool(sig.get("on_air")),
"live_status": str(sig.get("live_status") or ""),
"viewer_count": sig.get("viewer_count"),
"ingested": bool(ingest.get("ok")),
}
)
else:
polled.append(
{
"neko_instance_id": nid,
"ok": False,
"error": str((sig or {}).get("error") or "cdp_failed")[:120],
}
)
except Exception as exc:
polled.append({"neko_instance_id": nid, "ok": False, "error": str(exc)[:160]})
_time.sleep(1.2)
return {"ok": True, "count": len(polled), "polled": polled}
async def studio_cdp_poll_loop() -> None:
"""Background ~55s CDP backup for Studio on-air + minute reports (extension primary)."""
import asyncio
if str(os.environ.get("DY_DISABLE_STUDIO_CDP_LOOP") or "").strip().lower() in {"1", "true", "yes"}:
return
try:
await asyncio.sleep(50)
except asyncio.CancelledError:
raise
while True:
try:
await asyncio.wait_for(asyncio.to_thread(poll_studio_cdp_once), timeout=240)
except asyncio.CancelledError:
raise
except Exception:
pass
try:
await asyncio.sleep(_CDP_POLL_INTERVAL_SEC)
except asyncio.CancelledError:
raise