# -*- coding: utf-8 -*- """Per-channel Neko browser (Docker) for YouTube Studio — no ShellClash/WireGuard.""" from __future__ import annotations import json import shutil import subprocess import threading from pathlib import Path from typing import Any from urllib.parse import urlparse from .config import settings _lock = threading.RLock() MAX_INSTANCES = 32 MIN_UDP_PORT = 52000 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 _compose_path() -> Path: return _neko_root() / "docker-compose.yml" 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: base = MIN_UDP_PORT + (instance_id - 1) * 100 return f"{base}-{base + 98}" 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: return str(settings.public_base_url or "").strip().rstrip("/") 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 _render_compose(count: int) -> str: image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/chromium:3.0.0") user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb") admin_pass = str(getattr(settings, "neko_admin_pass", "") or "douyinweb") nat1to1 = str(getattr(settings, "neko_nat1to1", "") or "").strip() start_url = "https://studio.youtube.com/" root = _neko_root() lines = ["# Generated by douyinWEB — 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 = root / "profiles" / str(idx) profile.mkdir(parents=True, exist_ok=True) lines.extend( [ f" neko{idx}:", f" image: {image}", " restart: unless-stopped", " shm_size: 512mb", " cap_add:", " - SYS_ADMIN", " security_opt:", " - apparmor:unconfined", f" container_name: {_container_name(idx)}", " environment:", " TZ: America/Chicago", ' NEKO_SERVER_BIND: ":8080"', ' NEKO_MEMBER_PROVIDER: "multiuser"', f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {user_pass}", f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {admin_pass}", " NEKO_DESKTOP_SCREEN: 1280x720@15", " NEKO_MAX_FPS: 15", " NEKO_VIDEO_BITRATE: 1200", " NEKO_WEBRTC_ICELITE: 1", f" NEKO_WEBRTC_NAT1TO1: {nat1to1}", f" NEKO_WEBRTC_TCPMUX: {mux}", f" NEKO_WEBRTC_UDPMUX: {mux}", f" NEKO_WEBRTC_EPR: {udp}", f" NEKO_START_URL: {start_url}", " NEKO_BROWSER_PROXY: ''", " ports:", f' - "127.0.0.1:{http_port}:8080"', f' - "127.0.0.1:{mux}:{mux}/tcp"', f' - "127.0.0.1:{mux}:{mux}/udp"', f' - "127.0.0.1:{udp}:{udp}/udp"', " volumes:", f' - "{profile}:/home/neko/.config/chromium"', f' - "{profile}:/home/neko/.config/google-chrome"', ] ) return "\n".join(lines) + "\n" def _compose_cmd(*args: str) -> list[str]: return ["docker", "compose", "-f", str(_compose_path()), *args] def _container_state(instance_id: int) -> 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, "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 out["status"] = health if health else ("running" if running else str(state.get("Status") or "stopped")) if running: hc, _ = _run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"], timeout=8) out["ready"] = hc == 200 return out def ensure_capacity(desired: int, *, start_instances: set[int] | None = None) -> dict[str, Any]: """Render compose for `desired` instances; create containers (optionally start subset).""" desired = max(0, min(MAX_INSTANCES, int(desired or 0))) 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"} with _lock: 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") code, out = _run(_compose_cmd("up", "-d", "--remove-orphans"), timeout=300) if code != 0: return {"ok": False, "desired": desired, "error": out[:500] or "compose up failed"} started: list[int] = [] stopped: list[int] = [] for idx in range(1, desired + 1): should_run = start_instances is None or idx in start_instances if should_run: c, _ = _run(["docker", "start", _container_name(idx)], timeout=45) if c == 0: started.append(idx) else: c, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=30) if c == 0: stopped.append(idx) sync_nginx_proxy(desired) return { "ok": True, "desired": desired, "changed": changed, "started": started, "stopped": stopped, "detail": out[:300], } def sync_nginx_proxy(count: int) -> dict[str, Any]: """Write nginx reverse-proxy snippets for /neko/{id}/ → local ports.""" 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"} conf_path = Path("/etc/nginx/conf.d/douyinweb-neko.conf") if not conf_path.parent.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) mux = _webrtc_mux(idx) blocks.append( f""" 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_read_timeout 3600s; }} location ^~ /neko/{idx}/ws {{ proxy_pass http://127.0.0.1:{port}/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 3600s; }} location ^~ /neko/{idx}/mux/ {{ proxy_pass http://127.0.0.1:{mux}/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}""" ) body = f"""# douyinWEB Neko reverse proxy — auto-generated server {{ listen 80; server_name {host}; {''.join(blocks)} }} """ # Merge into existing ssl server via include pattern include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf") loc_body = "\n".join(blocks) try: include_path.write_text(loc_body + "\n", encoding="utf-8") # Patch main vhost if snippet marker missing vhost = Path(f"/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 = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;" if 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") _run(["nginx", "-t"], timeout=15) _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')}" if action == "start": ensure_capacity(instance_id, start_instances={instance_id}) code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60) if code != 0 and not before.get("exists"): ensure_capacity(instance_id, 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(instance_id, start_instances={instance_id}) code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90) 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() return after def list_instances(count: int) -> list[dict[str, Any]]: return [_container_state(i) for i in range(1, max(0, int(count)) + 1)] def status_summary(*, desired: int) -> dict[str, Any]: desired = max(0, min(MAX_INSTANCES, int(desired or 0))) instances = list_instances(desired) running = sum(1 for x in instances if x.get("running")) return { "available": _docker_available(), "desired": desired, "running": running, "instances": instances, "enabled": bool(getattr(settings, "neko_enabled", True)), } def sync_for_groups(groups: list[dict[str, Any]]) -> dict[str, Any]: """Ensure docker capacity matches assign groups; start only neko_enabled groups.""" 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)