# -*- 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() MAX_INSTANCES = 32 _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 _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 _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) -> tuple[int, str]: try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False, ) out = (proc.stdout or "") + (proc.stderr or "") return proc.returncode, out.strip() except subprocess.TimeoutExpired: return 124, "timeout" except OSError as exc: return 1, str(exc) def _public_base() -> str: 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 = "" for url in ( "https://checkip.amazonaws.com", "https://api.ipify.org", "https://ifconfig.me/ip", ): try: 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: ip = _nat_ip_cache or "108.174.50.68" _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 _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}") 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) 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"', ' 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)}", # US VPS: direct egress, no ShellClash. ' NEKO_BROWSER_PROXY: ""', ' 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 only localhost — HTTPS via nginx /neko/{id}/ f' - "127.0.0.1:{http_port}:8080"', # WebRTC must be public (cannot go through nginx). 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')}", 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. """ 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: 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 = changed or 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).""" base = _public_base() if not base: return {"ok": False, "skipped": "no_public_base"} host = urlparse(base).hostname or "" if not host: return {"ok": False, "skipped": "no_host"} if not Path("/etc/nginx/conf.d").is_dir(): return {"ok": False, "skipped": "no_nginx"} blocks: list[str] = [] for idx in range(1, max(0, int(count)) + 1): port = _http_port(idx) # 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} 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 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() 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(), # 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]]) -> dict[str, Any]: """Ensure docker containers exist for all assign groups; start only neko_enabled.""" 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=True) 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).""" 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 recent_live_studio_seen(*, max_age_sec: float = 120.0) -> bool: """True if any recent studio telemetry URL is YouTube Live Control Room.""" import time as _time now = _time.time() for ev in _studio_events[:40]: age = now - float(ev.get("received_at") or 0) if age > max_age_sec: continue payload = ev.get("payload") or {} url = str(payload.get("url") or "").lower() path = str((payload.get("signals") or {}).get("path") or "").lower() if "livestreaming" in url or "livestreaming" in path: return True return False def wait_instance_ready_for_live( instance_id: int, *, timeout_sec: float = 90.0, require_live_page: bool = True, ) -> dict[str, Any]: """Block until Neko is running/ready and (optionally) Studio livestreaming is open. In exclusive mode only one Neko runs, so global livestreaming telemetry is enough. """ 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"} deadline = _time.time() + max(15.0, float(timeout_sec)) ready_at = 0.0 last: dict[str, Any] = {} 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 running and ready: if not ready_at: ready_at = _time.time() if not require_live_page: return {"ok": True, "id": idx, "ready": True, "live_studio": False} if recent_live_studio_seen(max_age_sec=180.0): return {"ok": True, "id": idx, "ready": True, "live_studio": True} # Give extension/browser time to land on livestreaming after container ready. if ready_at and (_time.time() - ready_at) >= 25.0: return { "ok": True, "id": idx, "ready": True, "live_studio": False, "note": "neko_ready_waited_for_live_page", } _time.sleep(2.0) if last.get("running"): return { "ok": True, "id": idx, "ready": bool(last.get("ready")), "live_studio": recent_live_studio_seen(max_age_sec=180.0), "timeout": True, "note": "neko_running_after_timeout", } return {"ok": False, "id": idx, "error": "Neko 未在时限内启动成功", "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 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 body = dict(payload or {}) event = { "id": str(uuid.uuid4()), "received_at": float(body.get("received_at") or _time.time()), "payload": body, } _studio_events.insert(0, event) del _studio_events[_STUDIO_EVENTS_MAX:] 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"]}} def latest_studio_telemetry(*, limit: int = 20) -> list[dict[str, Any]]: return list(_studio_events[: max(1, min(100, int(limit)))])