douyinWEB/backend/app/youtube_neko.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

2095 lines
77 KiB
Python
Raw 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 _detect_public_ip() -> str:
"""Resolve reachable public IP for WebRTC ICE (NAT1TO1). Cached to avoid compose thrash."""
global _nat_ip_cache, _nat_ip_cached_at
import time as _time
configured = str(getattr(settings, "neko_nat1to1", "") or "").strip()
if configured:
return configured
env_ip = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip()
if env_ip:
return env_ip
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.
env_fallback = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip()
ip = env_fallback 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 public_studio_url(instance_id: int) -> str:
base = _public_base()
if base:
return f"{base}/neko/{instance_id}/"
return f"http://127.0.0.1:{_http_port(instance_id)}/"
def _ensure_profile(instance_id: int) -> Path:
profile = _neko_root() / "profiles" / str(instance_id)
profile.mkdir(parents=True, exist_ok=True)
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 _render_compose(count: int) -> str:
# x86 US VPS → google-chrome (sh2); override via DY_NEKO_IMAGE.
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")
screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15")
max_fps = str(getattr(settings, "neko_max_fps", "") or "15")
bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200")
# sh2 forces ICE Lite OFF for remote clients unless explicitly overridden.
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 = assets / _supervisor_conf_name()
# Fail loud in compose text if assets missing (ops can see in file).
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()
lines = [
"# Generated by douyinWEB youtube_neko — sh2-aligned assets; do not edit",
"services:",
]
for idx in range(1, count + 1):
http_port = _http_port(idx)
mux = _webrtc_mux(idx)
udp = _udp_range(idx)
profile = _ensure_profile(idx)
instance_id_file = _ensure_instance_id_file(idx)
lines.extend(
[
f" neko{idx}:",
f" image: {_q(image)}",
' restart: "no"',
f" shm_size: {_q(shm)}",
" cap_add:",
" - SYS_ADMIN",
" security_opt:",
" - apparmor:unconfined",
" extra_hosts:",
' - "host.docker.internal:host-gateway"',
f" container_name: {_container_name(idx)}",
" environment:",
f" TZ: {_q(tz)}",
' DISPLAY: ":99.0"',
' ENV_DISPLAY: ":99.0"',
' ENV_USER: "neko"',
' USER: "neko"',
' HOME: "/home/neko"',
' NEKO_CONTAINER_USER: "neko"',
' NEKO_CONTAINER_HOME: "/home/neko"',
f" NEKO_INSTANCE_ID: {_q(str(idx))}",
' NEKO_SERVER_BIND: ":8080"',
# Trust X-Forwarded-* from nginx; NO path prefix (nginx strips /neko/N/).
' NEKO_SERVER_PROXY: "true"',
' NEKO_MEMBER_PROVIDER: "multiuser"',
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
f" NEKO_MAX_FPS: {_q(max_fps)}",
f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
f" NEKO_WEBRTC_EPR: {_q(udp)}",
f" NEKO_START_URL: {_q(start_url)}",
# Physical: ShellCrash/住宅 via host.docker.internal; VPS colocated: usually "".
f" NEKO_BROWSER_PROXY: {_q(_neko_browser_proxy_value())}",
' NEKO_BROWSER_RENDER_MODE: "auto"',
f" NEKO_MANAGED_POLICIES: {_q('1' if managed else '0')}",
' NEKO_TAMPERMONKEY_REPAIR: "1"',
' NEKO_LIVE_OPS_EXTENSION: "1"',
' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"',
' NEKO_TAMPERMONKEY_SEED_DIR: "/etc/neko/tampermonkey-seed"',
" ports:",
# HTTP bind: 127.0.0.1 on colocated VPS; 0.0.0.0 on physical (WG edge).
f' - "{_http_bind()}:{http_port}:8080"',
# WebRTC must be public (cannot go through nginx/Caddy HTTP).
f' - "{mux}:{mux}/tcp"',
f' - "{mux}:{mux}/udp"',
f' - "{udp}:{udp}/udp"',
" volumes:",
f" - {_q(f'{profile}:/home/neko/.config/chromium')}",
f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}",
f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
f" - {_q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}",
f" - {_q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}",
f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
# Overlay instance id into the extension so telemetry can tag neko-N.
f" - {_q(f'{instance_id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}",
f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}",
f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}",
f" - {_q(f'{supervisor}:/etc/neko/supervisord/{_supervisor_conf_name()}:ro')}",
]
)
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 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())
if action == "start":
ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
if code != 0:
ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
if code != 0:
raise RuntimeError(out or "启动失败")
message = f"Neko {instance_id} 已启动"
elif action == "stop":
if before.get("exists"):
code, out = _run(["docker", "stop", "-t", "10", _container_name(instance_id)], timeout=45)
if code != 0:
raise RuntimeError(out or "停止失败")
message = f"Neko {instance_id} 已停止"
elif action == "restart":
ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90)
if code != 0:
_run(["docker", "rm", "-f", _container_name(instance_id)], timeout=30)
ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
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_stream_confirmed(payload: dict[str, Any] | None) -> bool:
"""True when Studio telemetry says this channel is actually live / healthy."""
body = payload or {}
text = str(body.get("text") or "").lower()
# Strong negatives first (preview / encoder not connected).
if any(
x in text
for x in (
"connect your encoder",
"waiting for you to start",
"stream offline",
"not streaming",
"no data key",
"直播已结束",
"未在直播",
)
):
return False
status = str(body.get("live_status") or "").strip().lower()
health = str(body.get("health") or "").strip().lower()
if status in {"ended", "waiting", "offline"}:
return False
if status in {"live", "streaming"}:
return True
if health in {"excellent", "good"}:
return True
# Concurrent viewers on Control Room almost always means on-air.
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",
"stream is healthy",
"excellent connection",
"concurrent viewers",
"watching now",
"stop streaming",
"end stream",
"正在直播",
"直播中",
"连接状况极佳",
"状况良好",
"人正在观看",
"结束直播",
)
):
return True
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]:
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 _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,
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)
ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since)
if ev is None:
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 = 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 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_minute_reports: dict[int, list[dict[str, Any]]] = {}
_studio_minute_last_at: dict[int, float] = {}
_STUDIO_MINUTE_MAX = 120
_studio_bootstrapped = False
_CDP_POLL_INTERVAL_SEC = 55.0
def _minute_report_dir() -> Path:
d = _neko_root() / "studio_minute"
d.mkdir(parents=True, exist_ok=True)
return d
def _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 _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"):
try:
nid = int(path.stem)
except ValueError:
continue
if nid < 1:
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
_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_id_for_payload(payload: dict[str, Any]) -> int:
"""Tag telemetry to a Neko instance via explicit id, assign studio URL, or CDP."""
body = payload or {}
for key in ("neko_instance_id", "neko_id", "instance_id"):
try:
nid = int(body.get(key) or 0)
if nid > 0:
return nid
except (TypeError, ValueError):
pass
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 nid
if url and studio and (studio.rstrip("/") in url or url.rstrip("/") in studio):
return nid
except Exception:
pass
if not _payload_is_livestreaming(body):
return 0
# CDP attribution is expensive; rely on instance_id.txt + assign studio URL match.
return 0
def _maybe_append_minute_report(neko_id: int, event: dict[str, Any]) -> None:
import time as _time
nid = int(neko_id or 0)
if nid < 1:
return
now = float(event.get("received_at") or _time.time())
last = float(_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,
"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],
}
bucket = _studio_minute_reports.setdefault(nid, [])
bucket.insert(0, report)
del bucket[_STUDIO_MINUTE_MAX:]
_studio_minute_last_at[nid] = now
_persist_minute_report(nid, report)
def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
"""Accept Studio telemetry from in-container Chrome extension."""
import time as _time
import uuid
_bootstrap_studio_telemetry_from_disk()
body = dict(payload or {})
neko_id = _resolve_neko_id_for_payload(body)
if neko_id > 0:
body["neko_instance_id"] = neko_id
event = {
"id": str(uuid.uuid4()),
"received_at": float(body.get("received_at") or _time.time()),
"neko_instance_id": neko_id,
"payload": body,
}
_studio_events.insert(0, event)
del _studio_events[_STUDIO_EVENTS_MAX:]
if neko_id > 0:
_studio_latest_by_neko[neko_id] = event
_maybe_append_minute_report(neko_id, event)
try:
path = _neko_root() / "studio_telemetry_latest.json"
path.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8")
except OSError:
pass
return {
"ok": True,
"event": {"id": event["id"], "neko_instance_id": neko_id},
}
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) -> list[dict[str, Any]]:
_bootstrap_studio_telemetry_from_disk()
nid = int(neko_id or 0)
lim = max(1, min(120, int(limit)))
if nid > 0:
return list(_studio_minute_reports.get(nid, [])[:lim])
out: list[dict[str, Any]] = []
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_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
out.update(
{
"live_page_open": page_open,
"on_air": on_air,
"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