Prefer YouTube receiving/Studio on-air for live-map and sync assign lives to hub.

Tighten http/youtubei live probes, classify Studio encoder_lost vs waiting, and keep dy/dylive public live counts aligned via edge assign_lives.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-05 22:57:52 -05:00
parent c06e2b1385
commit dea036c50d
26 changed files with 3434 additions and 502 deletions

View File

@ -349,6 +349,12 @@ def init_db() -> None:
_x_clips_db.ensure_x_clips_tables(conn) _x_clips_db.ensure_x_clips_tables(conn)
_yt_long_db.ensure_yt_long_tables(conn) _yt_long_db.ensure_yt_long_tables(conn)
_yt_assign_db.ensure_yt_assign_tables(conn) _yt_assign_db.ensure_yt_assign_tables(conn)
try:
from . import yt_studio_db as _yt_studio_db
_yt_studio_db.ensure_yt_studio_tables(conn)
except Exception:
pass
_ops_neko_db.ensure_ops_neko_tables(conn) _ops_neko_db.ensure_ops_neko_tables(conn)
_caption_pool.ensure_caption_pool_table(conn) _caption_pool.ensure_caption_pool_table(conn)
_caption_pool.seed_caption_pool(conn) _caption_pool.seed_caption_pool(conn)

View File

@ -43,14 +43,14 @@ def status() -> dict[str, Any]:
"profiles": list(PROFILES), "profiles": list(PROFILES),
"effects": { "effects": {
"vps": [ "vps": [
"egress / ShellCrash / 业务 SOCKS 全部关闭", "egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)",
"全部 Neko 停止并关闭 neko_enabled", "本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)",
"单路独占默认开启", "单路独占默认开启(省内存;可配对物理机 ops-neko)",
], ],
"physical": [ "physical": [
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)", "业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
"单路独占默认关闭(允许多 Neko 预热)", "单路独占默认关闭(允许多 Neko 预热)",
"不自动拉起全部 Neko(由分配页按需开启)", "不自动拉起全部 Neko(由分配页按需开启);ops-neko 优先 .cn / 腾讯云 ICE",
], ],
}, },
"never_touches": [ "never_touches": [
@ -130,7 +130,12 @@ def apply_profile(profile: str) -> dict[str, Any]:
except Exception as exc: except Exception as exc:
steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]} steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]}
steps["neko"] = _disable_all_neko() # Do NOT wipe assign Neko — dylive hub needs per-group start/stop like physical
# (local /neko/N/ and/or paired ops-neko). Exclusive-live still pauses siblings at push time.
steps["neko"] = {
"ok": True,
"note": "vps: leave assign Neko as-is; enable/start/stop per group in assign UI",
}
# Exclusive-live in-memory state is applied in apply_profile_async. # Exclusive-live in-memory state is applied in apply_profile_async.
db.update_settings_map( db.update_settings_map(

View File

@ -359,6 +359,8 @@ class YtAssignGroupCreate(BaseModel):
stream_key: str = "" stream_key: str = ""
note: str = "" note: str = ""
enabled: bool = True enabled: bool = True
# normal = 手动推流(精选); time_slot = 时间段排班推流
category: str = "normal"
class YtAssignGroupUpdate(BaseModel): class YtAssignGroupUpdate(BaseModel):
@ -370,6 +372,7 @@ class YtAssignGroupUpdate(BaseModel):
enabled: Optional[bool] = None enabled: Optional[bool] = None
sort_order: Optional[int] = None sort_order: Optional[int] = None
neko_enabled: Optional[bool] = None neko_enabled: Optional[bool] = None
category: Optional[str] = None
class YtAssignPoolAdd(BaseModel): class YtAssignPoolAdd(BaseModel):

View File

@ -1,11 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Ops-tab Neko Docker fleet — isolated from youtube_neko (assign). """Ops-tab Neko Docker fleet — same runtime as assign youtube_neko.
Containers: douyinweb-ops-neko-{slot} Containers: douyinweb-ops-neko-{slot}
HTTP ports: 18200+(slot-1) (assign uses 9200+) HTTP ports: 18200+(slot-1) (assign uses 9200+)
WebRTC mux: 62300+(slot-1) (assign uses 52300+) WebRTC mux: 62300+(slot-1) (assign uses 52300+)
Path for Caddy: /ops-neko/{slot}/ → host:1820x Path for Caddy: /ops-neko/{slot}/ → host:1820x
Compose env/assets/proxy/Studio URL come from youtube_neko.compose_service_lines
so YouTube live tooling matches the assign page. Ports/names stay isolated.
Create always leaves containers stopped unless start() is called. Create always leaves containers stopped unless start() is called.
""" """
from __future__ import annotations from __future__ import annotations
@ -63,17 +66,22 @@ def _udp_range(slot: int) -> str:
return f"{lo}-{hi}" return f"{lo}-{hi}"
def _q(value: str) -> str:
return json.dumps(str(value), ensure_ascii=False)
def _http_bind() -> str: def _http_bind() -> str:
return str(getattr(settings, "neko_http_bind", "") or "127.0.0.1").strip() or "127.0.0.1" """Same bind policy as assign youtube_neko (physical → 0.0.0.0 for WG edges)."""
from . import youtube_neko as yn
return yn._http_bind() # noqa: SLF001
def _profile(slot: int) -> Path: def _profile(slot: int) -> Path:
p = _root() / "profiles" / str(int(slot)) p = _root() / "profiles" / str(int(slot))
p.mkdir(parents=True, exist_ok=True) p.mkdir(parents=True, exist_ok=True)
try:
import os
os.chmod(p, 0o777)
except OSError:
pass
return p return p
@ -81,6 +89,8 @@ def _instance_id_file(slot: int) -> Path:
p = _root() / "instance_ids" p = _root() / "instance_ids"
p.mkdir(parents=True, exist_ok=True) p.mkdir(parents=True, exist_ok=True)
f = p / f"{int(slot)}.txt" f = p / f"{int(slot)}.txt"
# Same live-ops telemetry format as assign fleet (numeric id string when possible).
# Prefix ops- so Studio events from tab fleet don't collide with assign neko-N.
f.write_text(f"ops-{int(slot)}\n", encoding="utf-8") f.write_text(f"ops-{int(slot)}\n", encoding="utf-8")
return f return f
@ -96,91 +106,27 @@ def _compose_cmd(*args: str) -> list[str]:
def _render_compose(max_slot: int) -> str: def _render_compose(max_slot: int) -> str:
"""Mirror assign youtube_neko runtime (Studio / TM / live-ops / proxy / ICE)."""
from . import youtube_neko as yn from . import youtube_neko as yn
image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0") lines = [
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb") "# Generated by douyinWEB ops_neko — same runtime as assign youtube_neko",
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "neko") "services:",
nat1to1 = yn._detect_public_ip() # noqa: SLF001 ]
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")
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/"
)
assets = yn._asset_root() # noqa: SLF001
managed = yn._managed_policies_enabled() # noqa: SLF001
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 / yn._supervisor_conf_name() # noqa: SLF001
for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir):
if not required.exists():
raise RuntimeError(f"Neko asset missing: {required}")
yn._ensure_browser_launch_exec() # noqa: SLF001
proxy = yn._neko_browser_proxy_value() # noqa: SLF001
lines = ["# Generated by douyinWEB ops_neko — independent of assign fleet", "services:"]
n = max(1, int(max_slot)) n = max(1, int(max_slot))
for idx in range(1, n + 1): for idx in range(1, n + 1):
http_port = _http_port(idx)
mux = _mux(idx)
udp = _udp_range(idx)
profile = _profile(idx)
id_file = _instance_id_file(idx)
lines.extend( lines.extend(
[ yn.compose_service_lines(
f" opsneko{idx}:", service_key=f"opsneko{idx}",
f" image: {_q(image)}", container_name=_container_name(idx),
' restart: "no"', instance_id_label=f"ops-{idx}",
f" shm_size: {_q(shm)}", http_port=_http_port(idx),
" cap_add:", mux=_mux(idx),
" - SYS_ADMIN", udp=_udp_range(idx),
" security_opt:", profile=_profile(idx),
" - apparmor:unconfined", instance_id_file=_instance_id_file(idx),
" extra_hosts:", http_bind=_http_bind(),
' - "host.docker.internal:host-gateway"', )
f" container_name: {_container_name(idx)}",
" environment:",
' TZ: "America/Chicago"',
' DISPLAY: ":99.0"',
' NEKO_SERVER_BIND: ":8080"',
' NEKO_SERVER_PROXY: "true"',
' NEKO_MEMBER_PROVIDER: "multiuser"',
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
f" NEKO_MAX_FPS: {_q(max_fps)}",
f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
f" NEKO_WEBRTC_EPR: {_q(udp)}",
f" NEKO_START_URL: {_q(start_url)}",
f" NEKO_BROWSER_PROXY: {_q(proxy)}",
f" NEKO_INSTANCE_ID: {_q(f'ops-{idx}')}",
" ports:",
f' - "{_http_bind()}:{http_port}:8080"',
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'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
f" - {_q(f'{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/{yn._supervisor_conf_name()}:ro')}", # noqa: SLF001
]
) )
return "\n".join(lines) + "\n" return "\n".join(lines) + "\n"
@ -195,47 +141,68 @@ def _container_running(slot: int) -> bool:
def _public_neko_url(slot: int) -> str: def _public_neko_url(slot: int) -> str:
from . import db from . import db
from . import youtube_neko as yn
cfg = db.get_settings_map() cfg = db.get_settings_map()
base = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") override = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/")
if not base: base = yn.preferred_neko_public_base(override=override)
base = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/")
if not base: if not base:
return f"/ops-neko/{int(slot)}/" return f"/ops-neko/{int(slot)}/"
return f"{base}/ops-neko/{int(slot)}/" return f"{base}/ops-neko/{int(slot)}/"
def sync_compose(*, start_slots: set[int] | None = None) -> dict[str, Any]: def sync_compose(*, start_slots: set[int] | None = None, force_recreate: bool = True) -> dict[str, Any]:
"""Rewrite compose for current max slot; create containers; start only requested.""" """Rewrite compose for current max slot; create containers; start only requested.
force_recreate default True so env (proxy / NAT1TO1 / TM) matches assign fleet.
Already-running slots are restarted after recreate (same as youtube_neko egress refresh).
"""
max_slot = max(ops_neko_db.max_slot(), 1) if ops_neko_db.list_instances() else 0 max_slot = max(ops_neko_db.max_slot(), 1) if ops_neko_db.list_instances() else 0
if max_slot < 1: if max_slot < 1:
return {"ok": True, "skipped": "no_instances"} return {"ok": True, "skipped": "no_instances"}
text = _render_compose(max_slot) text = _render_compose(max_slot)
_compose_path().write_text(text, encoding="utf-8") _compose_path().write_text(text, encoding="utf-8")
start_slots = start_slots or set() start_slots = set(start_slots or set())
code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600) was_running = {idx for idx in range(1, max_slot + 1) if _container_running(idx)}
resume = was_running | start_slots
up_args = ["up", "-d", "--no-start"]
if force_recreate:
up_args.insert(2, "--force-recreate")
code, out = _run(_compose_cmd(*up_args), timeout=600)
if code != 0 and "--no-start" in (out or "").lower(): if code != 0 and "--no-start" in (out or "").lower():
code, out = _run(_compose_cmd("up", "-d"), timeout=600) code, out = _run(
_compose_cmd("up", "-d", *(["--force-recreate"] if force_recreate else [])),
timeout=600,
)
if code == 0: if code == 0:
for idx in range(1, max_slot + 1): for idx in range(1, max_slot + 1):
if idx not in start_slots: if idx not in resume:
_run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30) _run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
if code != 0: if code != 0:
return {"ok": False, "error": (out or "compose up failed")[:500]} return {"ok": False, "error": (out or "compose up failed")[:500]}
started: list[int] = [] started: list[int] = []
for idx in sorted(start_slots): errors: list[str] = []
for idx in sorted(resume):
if 1 <= idx <= max_slot: if 1 <= idx <= max_slot:
c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90) c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90)
if c2 == 0: if c2 == 0:
started.append(idx) started.append(idx)
else: else:
return {"ok": False, "error": (o2 or "start failed")[:300], "started": started} errors.append(f"ops-{idx}: {(o2 or 'start failed')[:160]}")
if errors:
return {"ok": False, "error": "; ".join(errors)[:500], "started": started, "max_slot": max_slot}
return {"ok": True, "max_slot": max_slot, "started": started} return {"ok": True, "max_slot": max_slot, "started": started}
def create_and_provision(*, name: str = "", note: str = "") -> dict[str, Any]: def create_and_provision(*, name: str = "", note: str = "") -> dict[str, Any]:
row = ops_neko_db.create_instance(name=name, note=note) row = ops_neko_db.create_instance(name=name, note=note)
sync = sync_compose(start_slots=set()) # always stopped after create sync = sync_compose(start_slots=set()) # always stopped after create
try:
from . import ops_neko_sync
ops_neko_sync.kick()
except Exception:
pass
return {"ok": True, "instance": enrich(row), "docker": sync} return {"ok": True, "instance": enrich(row), "docker": sync}
@ -247,6 +214,12 @@ def start_slot(slot: int) -> dict[str, Any]:
if not sync.get("ok"): if not sync.get("ok"):
return sync return sync
ops_neko_db.update_instance(str(inst["id"]), want_running=True) ops_neko_db.update_instance(str(inst["id"]), want_running=True)
try:
from . import ops_neko_sync
ops_neko_sync.kick()
except Exception:
pass
return {"ok": True, "instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst), "docker": sync} return {"ok": True, "instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst), "docker": sync}
@ -256,6 +229,12 @@ def stop_slot(slot: int) -> dict[str, Any]:
return {"ok": False, "error": "instance not found"} return {"ok": False, "error": "instance not found"}
code, out = _run(["docker", "stop", "-t", "8", _container_name(int(slot))], timeout=45) code, out = _run(["docker", "stop", "-t", "8", _container_name(int(slot))], timeout=45)
ops_neko_db.update_instance(str(inst["id"]), want_running=False) ops_neko_db.update_instance(str(inst["id"]), want_running=False)
try:
from . import ops_neko_sync
ops_neko_sync.kick()
except Exception:
pass
return { return {
"ok": code == 0 or "no such container" in (out or "").lower(), "ok": code == 0 or "no such container" in (out or "").lower(),
"detail": out[:200], "detail": out[:200],
@ -312,6 +291,7 @@ def hub_assign_cards() -> list[dict[str, Any]]:
"neko_local_studio_url": str(g.get("neko_local_studio_url") or g.get("neko_studio_url") or ""), "neko_local_studio_url": str(g.get("neko_local_studio_url") or g.get("neko_studio_url") or ""),
"ops_neko_open_url": str(g.get("ops_neko_open_url") or ""), "ops_neko_open_url": str(g.get("ops_neko_open_url") or ""),
"ops_neko_bound": bool(g.get("ops_neko_bound")), "ops_neko_bound": bool(g.get("ops_neko_bound")),
"ops_neko_slot": int(g.get("ops_neko_slot") or 0),
"neko_open_prefer": str(g.get("neko_open_prefer") or "local"), "neko_open_prefer": str(g.get("neko_open_prefer") or "local"),
} }
) )
@ -344,7 +324,7 @@ def pull_remote_cards() -> dict[str, Any]:
return {"ok": False, "error": str(exc)[:300]} return {"ok": False, "error": str(exc)[:300]}
def push_bind_to_hub(instance_id: str) -> dict[str, Any]: def push_bind_to_hub(instance_id: str, *, also_catalog: bool = True) -> dict[str, Any]:
"""Edge → hub: register this ops-neko open URL onto the VPS assign group.""" """Edge → hub: register this ops-neko open URL onto the VPS assign group."""
import httpx import httpx
@ -378,6 +358,360 @@ def push_bind_to_hub(instance_id: str) -> dict[str, Any]:
r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload) r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload)
if r.status_code != 200: if r.status_code != 200:
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload} return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload}
return {"ok": True, "hub": base, "payload": payload, "response": r.json()} cat = push_catalog_to_hub() if also_catalog else {"ok": True, "skipped": "also_catalog=0"}
return {"ok": True, "hub": base, "payload": payload, "response": r.json(), "catalog": cat}
except Exception as exc: except Exception as exc:
return {"ok": False, "error": str(exc)[:300], "payload": payload} return {"ok": False, "error": str(exc)[:300], "payload": payload}
def push_catalog_to_hub() -> dict[str, Any]:
"""Edge → hub: publish all local ops-neko slots for VPS assign dropdown."""
import httpx
import socket
from . import db
st = ops_neko_db.peer_status()
if st.get("role") != "edge":
return {"ok": False, "error": "peer role is not edge"}
base = str(st.get("peer_base_url") or "").strip().rstrip("/")
cfg = db.get_settings_map()
token = str(cfg.get("ops_neko_peer_token") or "").strip()
if not base or not token:
return {"ok": False, "error": "请填写 hub 域名与 token"}
edge_label = str(cfg.get("ops_neko_edge_label") or "").strip()
if not edge_label:
try:
edge_label = socket.gethostname() or "physical"
except Exception:
edge_label = "physical"
items = []
for row in list_enriched():
slot = int(row.get("slot") or 0)
if slot < 1:
continue
studio = None
try:
from . import youtube_neko as yn
studio = yn.studio_snapshot_for_ref(f"ops:{slot}", max_age_sec=180.0)
# Drop empty snapshots to keep payload light
if not (studio.get("received_at") or studio.get("on_air") or studio.get("live_page_open")):
studio = None
except Exception:
studio = None
items.append(
{
"id": str(row.get("id") or ""),
"slot": slot,
"name": str(row.get("name") or f"Ops Neko {slot}"),
"open_url": str(row.get("open_url") or ""),
"running": bool(row.get("running")),
"studio": studio,
}
)
payload = {"edge_id": edge_label, "edge_label": edge_label, "instances": items}
# Push assign Studio on_air so VPS live-map matches physical receiving-first.
assign_lives: list[dict[str, Any]] = []
try:
import time as _time
from . import yt_assign_db
from . import yt_studio_db
from . import youtube_neko as yn
since = _time.time() - 180.0
seen_cid: set[str] = set()
for g in yt_assign_db.list_groups(include_urls=False):
if not g.get("enabled"):
continue
gid = str(g.get("id") or "").strip()
cid = str(g.get("youtube_channel_id") or "").strip()
pk = str(g.get("channel_pk") or "").strip()
if not cid or cid in seen_cid:
continue
snap = {}
try:
snap = yn.studio_snapshot_for_group(g, max_age_sec=180.0)
except Exception:
snap = {}
on_air = bool(snap.get("on_air") or snap.get("encoder_receiving"))
st = str(snap.get("live_status") or "").lower()
if not on_air or st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}:
# Fall back to recent DB samples (local CDP poll).
try:
samples = yt_studio_db.list_samples(group_id=gid, since_ts=since, limit=3)
except Exception:
samples = []
hit = None
for s in samples:
sst = str(s.get("live_status") or "").lower()
if sst in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}:
continue
if s.get("on_air") or sst == "live":
hit = s
break
if not hit:
continue
assign_lives.append(
{
"group_id": gid,
"channel_pk": pk,
"youtube_channel_id": cid,
"name": str(g.get("name") or ""),
"on_air": True,
"live_status": str(hit.get("live_status") or "live"),
"health": str(hit.get("health") or ""),
"viewer_count": hit.get("viewer_count"),
"studio_url": str(hit.get("studio_url") or "")[:200],
"neko_ref": str(hit.get("neko_ref") or ""),
"ts": float(hit.get("ts") or _time.time()),
}
)
seen_cid.add(cid)
continue
assign_lives.append(
{
"group_id": gid,
"channel_pk": pk,
"youtube_channel_id": cid,
"name": str(g.get("name") or ""),
"on_air": True,
"live_status": st or "live",
"health": str(snap.get("health") or ""),
"viewer_count": snap.get("viewer_count"),
"studio_url": str(snap.get("url") or "")[:200],
"neko_ref": str(snap.get("neko_ref") or ""),
"ts": float(snap.get("received_at") or _time.time()),
}
)
seen_cid.add(cid)
except Exception:
assign_lives = []
if assign_lives:
payload["assign_lives"] = assign_lives
url = f"{base}/api/ops/neko/hub/catalog"
try:
with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client:
r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload)
if r.status_code != 200:
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload}
return {"ok": True, "hub": base, "count": len(items), "response": r.json()}
except Exception as exc:
return {"ok": False, "error": str(exc)[:300], "payload": payload}
def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[str, Any]:
"""Physical edge: ensure ops-neko Chrome has YouTube Live Control Room open (待开播)."""
from . import youtube_neko as yn
slot_i = int(slot or 0)
if slot_i < 1:
return {"ok": False, "error": "bad_slot"}
name = _container_name(slot_i)
if not _container_running(slot_i):
try:
start_slot(slot_i)
except Exception:
pass
if not _container_running(slot_i):
return {"ok": False, "slot": slot_i, "error": "ops_neko_not_running"}
yt = str(youtube_channel_id or "").strip()
if not yt:
try:
inst = next(
(r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == slot_i),
None,
)
gid = str((inst or {}).get("bind_remote_group_id") or "").strip()
if gid:
cards = pull_remote_cards()
for c in cards.get("cards") or []:
if str(c.get("id") or "") == gid:
yt = str(c.get("youtube_channel_id") or "").strip()
break
except Exception:
pass
studio_url = yn.studio_live_control_url(yt)
opened = yn._cdp_ensure_live_studio_in_container(name, studio_url=studio_url)
try:
# Never inject fake live_status=ready — that made hub think Studio was good while NODATA.
payload: dict[str, Any] = {
"neko_ref": f"ops-{slot_i}",
"neko_instance_id": f"ops-{slot_i}",
"source": "ops_cdp_ensure",
"url": str((opened or {}).get("url") or studio_url)[:400],
"live_status": "waiting",
"signals": {"path": "/livestreaming", "pending_go_live": True},
}
try:
urls_py = (
"import json,urllib.request\n"
"tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read())\n"
"live=[t.get('url') for t in tabs if 'livestreaming' in (t.get('url') or '').lower()]\n"
"print(json.dumps({'ok':bool(live),'url':(live[0] if live else '')}))\n"
)
code, out = yn._run(["docker", "exec", name, "python3", "-c", urls_py], timeout=15)
if code == 0 and out:
row = json.loads((out or "").strip().split("\n")[-1] or "{}")
if isinstance(row, dict) and row.get("url"):
payload["url"] = str(row.get("url"))[:400]
except Exception:
pass
# Prefer full DOM scrape when script is available inside the container / on host.
scraped = False
for scrape_path in (
"/etc/neko/cdp_studio_scrape.py",
"/opt/douyinWEB/backend/neko/cdp_studio_scrape.py",
):
try:
code, out = yn._run(
["docker", "exec", name, "python3", scrape_path],
timeout=20,
)
if code != 0 or not (out or "").strip():
continue
row = json.loads((out or "").strip().split("\n")[-1] or "{}")
if isinstance(row, dict) and row.get("ok"):
if row.get("url"):
payload["url"] = str(row.get("url"))[:400]
st = str(row.get("live_status") or "waiting").strip().lower() or "waiting"
if st == "ready":
st = "waiting"
payload["live_status"] = st
payload["text"] = str(row.get("text") or "")[:2200]
payload["signals"] = {
"path": "/livestreaming",
"nodata": bool(row.get("nodata")),
"encoder_receiving": bool(row.get("encoder_receiving")),
"encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost",
"session_live": bool(row.get("session_live"))
or st in {"live", "encoder_lost"},
"pending_go_live": st == "waiting"
and not bool(row.get("session_live"))
and st != "encoder_lost",
}
scraped = True
break
except Exception:
continue
if not scraped:
try:
from pathlib import Path
host_scrape = Path(__file__).resolve().parents[1] / "neko" / "cdp_studio_scrape.py"
if host_scrape.is_file():
code, out = yn._run(
[
"bash",
"-lc",
f"docker exec -i {name} python3 - < {host_scrape.as_posix()}",
],
timeout=25,
)
if code == 0 and (out or "").strip():
row = json.loads((out or "").strip().split("\n")[-1] or "{}")
if isinstance(row, dict) and row.get("ok"):
if row.get("url"):
payload["url"] = str(row.get("url"))[:400]
st = str(row.get("live_status") or "waiting").strip().lower() or "waiting"
if st == "ready":
st = "waiting"
payload["live_status"] = st
payload["text"] = str(row.get("text") or "")[:2200]
payload["signals"] = {
"path": "/livestreaming",
"nodata": bool(row.get("nodata")),
"encoder_receiving": bool(row.get("encoder_receiving")),
"encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost",
"session_live": bool(row.get("session_live"))
or st in {"live", "encoder_lost"},
"pending_go_live": st == "waiting"
and not bool(row.get("session_live"))
and st != "encoder_lost",
}
except Exception:
pass
yn.ingest_studio_telemetry(payload)
except Exception:
pass
return {"ok": bool(opened.get("ok")), "slot": slot_i, "studio_url": studio_url, "cdp": opened}
def ensure_bound_slots_live_studio() -> dict[str, Any]:
"""Edge heartbeat: bound/running ops slots keep Live Control Room open."""
cards_by_id: dict[str, dict[str, Any]] = {}
try:
pulled = pull_remote_cards()
for c in pulled.get("cards") or []:
cid = str(c.get("id") or "").strip()
if cid:
cards_by_id[cid] = c
except Exception:
pass
results: list[dict[str, Any]] = []
for row in ops_neko_db.list_instances():
slot = int(row.get("slot") or 0)
if slot < 1 or not _container_running(slot):
continue
gid = str(row.get("bind_remote_group_id") or "").strip()
yt = ""
should = bool(gid)
if gid and gid in cards_by_id:
yt = str(cards_by_id[gid].get("youtube_channel_id") or "").strip()
should = True
if not should:
for card in cards_by_id.values():
if int(card.get("ops_neko_slot") or 0) == slot and (
str(card.get("neko_open_prefer") or "").lower() == "remote"
or card.get("ops_neko_bound")
):
yt = str(card.get("youtube_channel_id") or "").strip()
should = True
break
if not should:
continue
results.append(ensure_slot_live_studio(slot, youtube_channel_id=yt))
return {
"ok": True,
"ensured": sum(1 for r in results if r.get("ok")),
"results": results,
}
def pair_as_edge(*, hub_base: str, token: str, public_base: str = "") -> dict[str, Any]:
"""Physical: save edge peer credentials then push catalog (realtime registry)."""
from . import db
hub = str(hub_base or "").strip().rstrip("/")
tok = str(token or "").strip()
if not tok:
tok = str(db.get_settings_map().get("ops_neko_peer_token") or "").strip()
if not hub or not tok:
return {"ok": False, "error": "需要 hub 域名与 token"}
peer = ops_neko_db.save_peer(
role="edge",
peer_base_url=hub,
public_base=public_base if public_base is not None else None,
token=tok,
)
cards = pull_remote_cards()
try:
ensure_bound_slots_live_studio()
except Exception:
pass
catalog = push_catalog_to_hub()
try:
from . import ops_neko_sync
ops_neko_sync.kick()
except Exception:
pass
return {
"ok": bool(catalog.get("ok") or cards.get("ok")),
"peer": peer,
"cards": cards,
"catalog": catalog,
"realtime": True,
"hint": "已连接:后台每 5 秒自动同步实例目录到 VPS,无需再点配对",
}

View File

@ -36,6 +36,25 @@ def ensure_ops_neko_tables(conn: sqlite3.Connection) -> None:
conn.execute( conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ops_neko_slot ON ops_neko_instances(slot)" "CREATE INDEX IF NOT EXISTS idx_ops_neko_slot ON ops_neko_instances(slot)"
) )
# Hub-side catalog of physical edge ops-neko instances (pushed by edge).
conn.execute(
"""
CREATE TABLE IF NOT EXISTS ops_neko_edge_catalog (
id TEXT PRIMARY KEY,
edge_id TEXT NOT NULL DEFAULT '',
edge_label TEXT NOT NULL DEFAULT '',
slot INTEGER NOT NULL DEFAULT 0,
name TEXT NOT NULL DEFAULT '',
open_url TEXT NOT NULL DEFAULT '',
running INTEGER NOT NULL DEFAULT 0,
last_seen REAL NOT NULL DEFAULT 0,
UNIQUE(edge_id, slot)
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ops_neko_catalog_seen ON ops_neko_edge_catalog(last_seen DESC)"
)
def _ensure() -> None: def _ensure() -> None:
@ -196,6 +215,7 @@ PEER_KEYS = (
def peer_status() -> dict[str, Any]: def peer_status() -> dict[str, Any]:
from . import db from . import db
from . import youtube_neko
cfg = db.get_settings_map() cfg = db.get_settings_map()
role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower() role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower()
@ -204,17 +224,20 @@ def peer_status() -> dict[str, Any]:
token = str(cfg.get("ops_neko_peer_token") or "").strip() token = str(cfg.get("ops_neko_peer_token") or "").strip()
base = str(cfg.get("ops_neko_peer_base_url") or "").strip().rstrip("/") base = str(cfg.get("ops_neko_peer_base_url") or "").strip().rstrip("/")
public = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") public = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/")
effective = youtube_neko.preferred_neko_public_base(override=public)
return { return {
"ok": True, "ok": True,
"role": role, "role": role,
"peer_base_url": base, "peer_base_url": base,
"public_base": public, "public_base": public,
"effective_public_base": effective,
"cn_edge_usable": youtube_neko.cn_edge_usable() if youtube_neko._physical_dual_edge() else False, # noqa: SLF001
"has_token": bool(token), "has_token": bool(token),
"token_suffix": token[-4:] if len(token) >= 4 else "", "token_suffix": token[-4:] if len(token) >= 4 else "",
"hint": { "hint": {
"off": "本机独立运维 Neko,不跨机同步分配卡片", "off": "本机独立运维 Neko(与分配页同一套 Studio/TM/代理配置)",
"hub": "本机对外发布「YouTube 分配」卡片(通常 VPS);把 token 填到物理机", "hub": "本机对外发布「YouTube 分配」卡片(通常 VPS);把 token 填到物理机",
"edge": "本机拉取 hub 的分配卡片并手动绑定(通常物理机 + ShellCrash Neko)", "edge": "物理机:Neko 优先腾讯云 wg-dy-cn(.cn);不通才回退 VPS(.com)。实例配置与分配页一致。",
}.get(role, ""), }.get(role, ""),
} }
@ -259,3 +282,115 @@ def verify_peer_token(provided: str) -> bool:
want = str(cfg.get("ops_neko_peer_token") or "").strip() want = str(cfg.get("ops_neko_peer_token") or "").strip()
got = str(provided or "").strip() got = str(provided or "").strip()
return bool(want) and bool(got) and secrets.compare_digest(want, got) return bool(want) and bool(got) and secrets.compare_digest(want, got)
def ensure_hub_credentials(*, rotate: bool = False) -> dict[str, Any]:
"""VPS hub pairing card: public domain + token (create if missing)."""
from . import db
from . import host_profile
from .config import settings
profile = host_profile.infer_profile()
cfg = db.get_settings_map()
role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower()
token = str(cfg.get("ops_neko_peer_token") or "").strip()
patch: dict[str, Any] = {}
if profile == "vps" and role != "hub":
patch["ops_neko_peer_role"] = "hub"
role = "hub"
if rotate or (role == "hub" and not token):
patch["ops_neko_peer_token"] = secrets.token_urlsafe(24)
if patch:
db.update_settings_map(patch)
cfg = db.get_settings_map()
role = str(cfg.get("ops_neko_peer_role") or role).strip().lower()
token = str(cfg.get("ops_neko_peer_token") or "").strip()
domain = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/")
if not domain:
domain = str(cfg.get("public_base_url") or "").strip().rstrip("/")
st = peer_status()
st["profile"] = profile
st["domain"] = domain
st["token"] = token if role == "hub" else ""
st["ready"] = bool(role == "hub" and domain and token)
return st
def upsert_edge_catalog(
items: list[dict[str, Any]],
*,
edge_id: str = "",
edge_label: str = "",
) -> list[dict[str, Any]]:
"""Replace/merge catalog rows pushed by a physical edge."""
_ensure()
now = time.time()
eid = str(edge_id or edge_label or "edge").strip()[:80] or "edge"
elabel = str(edge_label or eid).strip()[:120]
rows_out: list[dict[str, Any]] = []
with _lock:
conn = _connect()
try:
ensure_ops_neko_tables(conn)
for it in items or []:
slot = int(it.get("slot") or 0)
if slot < 1:
continue
open_url = str(it.get("open_url") or "").strip()
if open_url and not open_url.endswith("/"):
open_url = f"{open_url}/"
name = str(it.get("name") or f"Ops Neko {slot}").strip()[:120]
running = 1 if it.get("running") else 0
rid = str(it.get("id") or f"{eid}:{slot}")[:80]
conn.execute(
"""
INSERT INTO ops_neko_edge_catalog(
id, edge_id, edge_label, slot, name, open_url, running, last_seen
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(edge_id, slot) DO UPDATE SET
id=excluded.id,
edge_label=excluded.edge_label,
name=excluded.name,
open_url=excluded.open_url,
running=excluded.running,
last_seen=excluded.last_seen
""",
(rid, eid, elabel, slot, name, open_url, running, now),
)
# Drop stale rows for this edge not in the push (optional cleanup)
keep_slots = {int(it.get("slot") or 0) for it in (items or []) if int(it.get("slot") or 0) > 0}
if keep_slots:
placeholders = ",".join("?" * len(keep_slots))
conn.execute(
f"DELETE FROM ops_neko_edge_catalog WHERE edge_id = ? AND slot NOT IN ({placeholders})",
(eid, *sorted(keep_slots)),
)
conn.commit()
rows = conn.execute(
"SELECT * FROM ops_neko_edge_catalog ORDER BY edge_label ASC, slot ASC"
).fetchall()
rows_out = [_row_to_dict(r) for r in rows]
finally:
conn.close()
return rows_out
def list_edge_catalog(*, max_age_sec: float = 86400.0) -> list[dict[str, Any]]:
"""Hub UI dropdown: recent physical ops-neko instances."""
_ensure()
cutoff = time.time() - float(max_age_sec)
with _lock:
conn = _connect()
try:
ensure_ops_neko_tables(conn)
rows = conn.execute(
"""
SELECT * FROM ops_neko_edge_catalog
WHERE last_seen >= ? AND open_url != ''
ORDER BY edge_label ASC, slot ASC
""",
(cutoff,),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()

View File

@ -0,0 +1,112 @@
# -*- coding: utf-8 -*-
"""Ops-neko edge ↔ hub realtime sync (heartbeat).
Physical (edge): once hub URL + token are saved, continuously push instance
catalog (+ existing binds) to VPS. No manual「配对同步」needed after connect.
"""
from __future__ import annotations
import asyncio
import time
from typing import Any
_state: dict[str, Any] = {
"enabled": False,
"connected": False,
"last_ok_at": 0.0,
"last_error": "",
"last_result": {},
"interval_sec": 5.0,
"ticks": 0,
}
_kick: asyncio.Event | None = None
def status() -> dict[str, Any]:
st = dict(_state)
age = None
if st.get("last_ok_at"):
age = max(0.0, time.time() - float(st["last_ok_at"]))
st["last_ok_age_sec"] = age
return {"ok": True, **st}
def kick() -> None:
"""Wake the loop for an immediate sync (after create/start/stop/pair)."""
ev = _kick
if ev is not None:
ev.set()
def sync_once() -> dict[str, Any]:
"""One edge→hub push. No-op when not configured as edge."""
from . import ops_neko
from . import ops_neko_db
peer = ops_neko_db.peer_status()
if peer.get("role") != "edge":
_state["enabled"] = False
_state["connected"] = False
return {"ok": True, "skipped": "not_edge", "role": peer.get("role")}
if not peer.get("peer_base_url") or not peer.get("has_token"):
_state["enabled"] = True
_state["connected"] = False
_state["last_error"] = "缺少 hub 域名或 token"
return {"ok": False, "error": "缺少 hub 域名或 token"}
_state["enabled"] = True
# Keep YouTube Live Control Room open on bound ops-neko Chrome before catalog push.
try:
live = ops_neko.ensure_bound_slots_live_studio()
except Exception as exc:
live = {"ok": False, "error": str(exc)[:200]}
catalog = ops_neko.push_catalog_to_hub()
binds: list[dict[str, Any]] = []
for row in ops_neko_db.list_instances():
gid = str(row.get("bind_remote_group_id") or "").strip()
if not gid:
continue
try:
binds.append(ops_neko.push_bind_to_hub(str(row.get("id") or ""), also_catalog=False))
except Exception as exc:
binds.append({"ok": False, "error": str(exc)[:200], "id": row.get("id")})
ok = bool(catalog.get("ok"))
_state["ticks"] = int(_state.get("ticks") or 0) + 1
_state["last_result"] = {
"catalog_ok": ok,
"catalog_count": (catalog.get("count") if isinstance(catalog, dict) else None),
"binds_ok": sum(1 for b in binds if b.get("ok")),
"live_ensured": (live.get("ensured") if isinstance(live, dict) else None),
}
if ok:
_state["connected"] = True
_state["last_ok_at"] = time.time()
_state["last_error"] = ""
else:
_state["connected"] = False
_state["last_error"] = str(catalog.get("error") or "catalog push failed")[:300]
return {"ok": ok, "catalog": catalog, "binds": binds}
async def edge_sync_loop(*, interval_sec: float = 5.0) -> None:
"""Background loop — only does work when peer role is edge."""
global _kick
_kick = asyncio.Event()
_state["interval_sec"] = float(interval_sec)
while True:
try:
await asyncio.to_thread(sync_once)
except asyncio.CancelledError:
raise
except Exception as exc:
_state["connected"] = False
_state["last_error"] = str(exc)[:300]
assert _kick is not None
try:
await asyncio.wait_for(_kick.wait(), timeout=float(interval_sec))
_kick.clear()
except asyncio.TimeoutError:
pass
except asyncio.CancelledError:
raise

View File

@ -38,6 +38,7 @@ _PUBLIC_API_EXACT = {
"/hub/youtube/live/ingest", "/hub/youtube/live/ingest",
"/api/ops/neko/hub/assign-cards", "/api/ops/neko/hub/assign-cards",
"/api/ops/neko/hub/bind", "/api/ops/neko/hub/bind",
"/api/ops/neko/hub/catalog",
} }

View File

@ -3,8 +3,11 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import json
import os import os
import re
import time import time
import urllib.request
from typing import Any, Optional from typing import Any, Optional
from . import db, youtube_client from . import db, youtube_client
@ -19,6 +22,103 @@ _LAST_OAUTH_AT = 0.0
_OAUTH_MIN_INTERVAL_SEC = 45.0 _OAUTH_MIN_INTERVAL_SEC = 45.0
def _http_channel_live_probe(channel_id: str) -> dict[str, Any]:
"""Public fallback: GET /channel/UC…/live and read player isLive flags.
youtubei.js tab scans often miss on-air streams that /live still exposes.
Honors HTTPS_PROXY/HTTP_PROXY (physical China guest via ShellCrash).
"""
cid = str(channel_id or "").strip()
empty = {"is_live": False, "source": "http_live", "channel_id": cid, "live_url": "", "title": ""}
if not cid.startswith("UC"):
return empty
url = f"https://www.youtube.com/channel/{cid}/live"
html = ""
last_err = ""
proxies_try: list[str] = []
env_proxy = (
str(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "").strip()
or str(os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") or "").strip()
)
if env_proxy:
proxies_try.append(env_proxy)
proxies_try.append("") # direct
# Physical China guest: ShellCrash (same as douyinweb-yt) if env unset / direct fails
if "127.0.0.1:7890" not in env_proxy:
proxies_try.append("http://127.0.0.1:7890")
seen_p: set[str] = set()
for proxy in proxies_try:
if proxy in seen_p:
continue
seen_p.add(proxy)
try:
handlers: list[Any] = []
if proxy:
handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
opener = urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener()
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept-Language": "en-US,en;q=0.9",
},
)
with opener.open(req, timeout=22) as resp:
html = resp.read().decode("utf-8", "replace")
last_err = ""
break
except Exception as exc:
last_err = str(exc)[:160]
html = ""
continue
if not html:
return {**empty, "error": last_err or "http_live_fetch_failed"}
video_id = ""
title = ""
is_live = False
play_status = ""
m = re.search(r"ytInitialPlayerResponse\s*=\s*", html)
if m:
try:
obj, _ = json.JSONDecoder().raw_decode(html[m.end() :])
if isinstance(obj, dict):
play_status = str((obj.get("playabilityStatus") or {}).get("status") or "")
vd = obj.get("videoDetails") if isinstance(obj.get("videoDetails"), dict) else {}
video_id = str(vd.get("videoId") or "")
title = str(vd.get("title") or "")[:120]
# isLiveContent is true for VODs / scheduled offline streams — NOT on-air.
if vd.get("isLive") is True:
is_live = True
micro = (obj.get("microformat") or {}).get("playerMicroformatRenderer") or {}
if isinstance(micro, dict):
details = micro.get("liveBroadcastDetails") or {}
if isinstance(details, dict) and details.get("isLiveNow") is True:
is_live = True
elif isinstance(details, dict) and details.get("isLiveNow") is False:
is_live = False
except Exception:
pass
# Waiting / scheduled rooms often still have isLiveContent + title "is live!" —
# never treat LIVE_STREAM_OFFLINE as on-air.
if play_status in {"LIVE_STREAM_OFFLINE", "ERROR", "UNPLAYABLE", "LOGIN_REQUIRED"}:
if play_status == "LIVE_STREAM_OFFLINE":
is_live = False
elif play_status != "LOGIN_REQUIRED":
is_live = False
if not is_live and re.search(r'"isLiveNow"\s*:\s*true', html, re.I):
is_live = True
# Bare "isLive":true appears on offline scheduled pages — ignore without isLiveNow.
live_url = f"https://www.youtube.com/watch?v={video_id}" if video_id else url
return {
"is_live": bool(is_live),
"source": "http_live",
"channel_id": cid,
"live_url": live_url if is_live else "",
"title": title,
}
def _refresh_lock() -> asyncio.Lock: def _refresh_lock() -> asyncio.Lock:
global _REFRESH_LOCK global _REFRESH_LOCK
if _REFRESH_LOCK is None: if _REFRESH_LOCK is None:
@ -136,48 +236,15 @@ async def _oauth_live_for_shorts(channel_pk: str, youtube_channel_id: str) -> Op
title=title, title=title,
channel_id=youtube_channel_id, channel_id=youtube_channel_id,
) )
# Explicit offline from liveBroadcasts — do NOT burn Search Queries quota.
return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id) return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id)
except Exception as broadcast_exc: except Exception as broadcast_exc:
broadcast_err = str(broadcast_exc) # Broadcasts unavailable → leave detection to youtubei (public). Never search.list.
# 2) Fallback: search (expensive; may hit daily Search Queries quota)
try:
data = await youtube_manage._get(
"search",
token=token,
params={
"part": "snippet",
"channelId": youtube_channel_id,
"eventType": "live",
"type": "video",
"maxResults": 1,
},
)
items = data.get("items") or []
if not items:
return _live_entry( return _live_entry(
is_live=False, is_live=False,
source="oauth", source="oauth-broadcast",
channel_id=youtube_channel_id, channel_id=youtube_channel_id,
error=broadcast_err[:120] if broadcast_err else "", error=f"broadcasts_unavailable:{str(broadcast_exc)[:140]}",
)
item = items[0]
vid = str((item.get("id") or {}).get("videoId") or "").strip()
title = str((item.get("snippet") or {}).get("title") or "").strip()
live_url = f"https://www.youtube.com/watch?v={vid}" if vid else ""
return _live_entry(
is_live=True,
source="oauth",
live_url=live_url,
title=title,
channel_id=youtube_channel_id,
)
except Exception as search_exc:
return _live_entry(
is_live=False,
source="oauth",
channel_id=youtube_channel_id,
error=f"{broadcast_err[:80]} | {str(search_exc)[:100]}",
) )
except Exception as exc: except Exception as exc:
return _live_entry( return _live_entry(
@ -253,12 +320,16 @@ async def build_live_map(*, force: bool = False) -> dict[str, Any]:
async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
global _LAST_OAUTH_AT global _LAST_OAUTH_AT
def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
from . import yt_assign_db
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or []) groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
shorts = db.list_shorts_channels() shorts = db.list_shorts_channels()
return groups, shorts # Live 分配授权频道卡 — 与 Shorts/旧分组一样走公开 youtubei 探测(双机应一致)
assign = yt_assign_db.list_groups(include_urls=False)
return groups, shorts, assign
groups, shorts = await asyncio.to_thread(_load_db_targets) groups, shorts, assign_groups_early = await asyncio.to_thread(_load_db_targets)
targets: list[dict[str, Any]] = [] targets: list[dict[str, Any]] = []
url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {} url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}
@ -287,6 +358,51 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
cid_to_refs.setdefault(cid, []).append((ref, meta)) cid_to_refs.setdefault(cid, []).append((ref, meta))
targets.append({"ref": f"channel:{cid}", "url": url or f"https://www.youtube.com/channel/{cid}", **meta}) targets.append({"ref": f"channel:{cid}", "url": url or f"https://www.youtube.com/channel/{cid}", **meta})
# Assign cards: same public youtubei probe as shorts (VPS ↔ physical must match for same UC ids).
seen_assign_cid: set[str] = set()
for ag in assign_groups_early:
if not ag.get("enabled"):
continue
gid = str(ag.get("id") or "").strip()
if not gid:
continue
cid = str(ag.get("youtube_channel_id") or "").strip()
pk = str(ag.get("channel_pk") or "").strip()
if not cid and pk:
try:
ch = db.get_shorts_channel(pk) or {}
cid = str(ch.get("youtube_channel_id") or "").strip()
except Exception:
cid = ""
if not cid:
continue
url = f"https://www.youtube.com/channel/{cid}"
meta = {
"kind": "assign",
"assign_group_id": gid,
"channel_pk": pk,
"youtube_channel_id": cid,
"title": str(ag.get("name") or "").strip(),
"url": url,
}
targets.append({"ref": f"assign:{gid}", "url": url, **meta})
url_to_refs.setdefault(url, []).append((f"assign:{gid}", meta))
cid_to_refs.setdefault(cid, []).append((f"assign:{gid}", meta))
if cid not in seen_assign_cid:
seen_assign_cid.add(cid)
targets.append({"ref": f"channel:{cid}", "url": url, **meta})
if pk:
# Keep shorts ref in sync when assign shares the same OAuth channel.
targets.append(
{
"ref": f"shorts:{pk}",
"url": url,
"kind": "shorts",
"channel_pk": pk,
"youtube_channel_id": cid,
}
)
entries: dict[str, Any] = {} entries: dict[str, Any] = {}
unique_urls: list[str] = [] unique_urls: list[str] = []
seen_urls: set[str] = set() seen_urls: set[str] = set()
@ -342,14 +458,86 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
channel_id=str(g.get("channel_id") or ""), channel_id=str(g.get("channel_id") or ""),
) )
# Prefer keeping an already-live youtubei hit if we revisit the same ref.
prev = entries.get(ref)
if prev and prev.get("is_live") and not entry.get("is_live"):
entry = dict(prev)
elif t.get("kind") == "assign" and entry.get("is_live"):
entry = dict(entry)
entry["assign_group_id"] = str(t.get("assign_group_id") or "")
entry["channel_pk"] = str(t.get("channel_pk") or "")
if t.get("title"):
entry["title"] = str(t.get("title") or "")
if cid:
entry["channel_id"] = cid
entries[ref] = dict(entry) entries[ref] = dict(entry)
if cid and entry.get("is_live"): if cid and entry.get("is_live"):
entries[f"channel:{cid}"] = dict(entry) entries[f"channel:{cid}"] = dict(entry)
if t.get("kind") == "assign" and t.get("channel_pk"):
pk = str(t.get("channel_pk") or "")
shorts_ref = f"shorts:{pk}"
if not (entries.get(shorts_ref) or {}).get("is_live"):
se = dict(entry)
se["assign_group_id"] = str(t.get("assign_group_id") or "")
entries[shorts_ref] = se
# OAuth 兜底限频,避免多标签 force/后台轮询打爆配额 # HTTP /channel/UC…/live fallback — youtubei tab scans often miss true on-air streams.
http_cids: list[str] = []
seen_http: set[str] = set()
for t in targets:
cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip()
if not cid or cid in seen_http:
continue
ch_ent = entries.get(f"channel:{cid}") or {}
# Probe when missing or youtubei said offline
if ch_ent.get("is_live"):
continue
seen_http.add(cid)
http_cids.append(cid)
if http_cids:
http_results = await asyncio.gather(
*[asyncio.to_thread(_http_channel_live_probe, cid) for cid in http_cids],
return_exceptions=True,
)
cid_to_targets: dict[str, list[dict[str, Any]]] = {}
for t in targets:
cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip()
if cid:
cid_to_targets.setdefault(cid, []).append(t)
for cid, result in zip(http_cids, http_results):
if isinstance(result, Exception) or not isinstance(result, dict):
continue
if not result.get("is_live"):
continue
live_ent = _live_entry(
is_live=True,
source="http_live",
live_url=str(result.get("live_url") or ""),
title=str(result.get("title") or ""),
channel_id=cid,
)
entries[f"channel:{cid}"] = live_ent
for t in cid_to_targets.get(cid) or []:
ref = str(t.get("ref") or "")
if not ref:
continue
cur = entries.get(ref) or {}
if cur.get("is_live"):
continue
ent = dict(live_ent)
if t.get("kind") == "assign":
ent["assign_group_id"] = str(t.get("assign_group_id") or "")
ent["channel_pk"] = str(t.get("channel_pk") or "")
if t.get("title"):
ent["title"] = str(t.get("title") or ent.get("title") or "")
entries[ref] = ent
# OAuth / liveBroadcasts:授权频道卡与 Shorts 共用 channel_pk 时必走(双机公开态应一致)
run_oauth = (now - float(_LAST_OAUTH_AT or 0)) >= _OAUTH_MIN_INTERVAL_SEC run_oauth = (now - float(_LAST_OAUTH_AT or 0)) >= _OAUTH_MIN_INTERVAL_SEC
oauth_tasks: list[tuple[str, str, str]] = [] oauth_tasks: list[tuple[str, str, str]] = []
if run_oauth: if run_oauth:
seen_oauth_pk: set[str] = set()
for ch in shorts: for ch in shorts:
cid = str(ch.get("youtube_channel_id") or "").strip() cid = str(ch.get("youtube_channel_id") or "").strip()
pk = str(ch.get("id") or "") pk = str(ch.get("id") or "")
@ -361,6 +549,34 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
if entries.get(ref, {}).get("is_live"): if entries.get(ref, {}).get("is_live"):
continue continue
oauth_tasks.append((ref, pk, cid)) oauth_tasks.append((ref, pk, cid))
seen_oauth_pk.add(pk)
# Assign cards that bind an OAuth shorts channel — same API path on VPS & physical.
for ag in assign_groups_early:
if not ag.get("enabled"):
continue
pk = str(ag.get("channel_pk") or "").strip()
cid = str(ag.get("youtube_channel_id") or "").strip()
gid = str(ag.get("id") or "").strip()
if not pk or not gid:
continue
if pk in seen_oauth_pk:
continue
if (entries.get(f"assign:{gid}") or {}).get("is_live"):
continue
if (entries.get(f"shorts:{pk}") or {}).get("is_live"):
continue
try:
ch = db.get_shorts_channel(pk) or {}
except Exception:
ch = {}
if not str(ch.get("refresh_token") or "").strip():
continue
if not cid:
cid = str(ch.get("youtube_channel_id") or "").strip()
if not cid:
continue
oauth_tasks.append((f"shorts:{pk}", pk, cid))
seen_oauth_pk.add(pk)
if oauth_tasks: if oauth_tasks:
_LAST_OAUTH_AT = now _LAST_OAUTH_AT = now
@ -368,17 +584,76 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
*[_oauth_live_for_shorts(pk, cid) for _ref, pk, cid in oauth_tasks], *[_oauth_live_for_shorts(pk, cid) for _ref, pk, cid in oauth_tasks],
return_exceptions=True, return_exceptions=True,
) )
for (ref, _pk, cid), result in zip(oauth_tasks, oauth_results): pk_to_assign: dict[str, list[dict[str, Any]]] = {}
if isinstance(result, Exception): for ag in assign_groups_early:
pk = str(ag.get("channel_pk") or "").strip()
if pk:
pk_to_assign.setdefault(pk, []).append(ag)
for (ref, pk, cid), result in zip(oauth_tasks, oauth_results):
if isinstance(result, Exception) or not isinstance(result, dict):
continue continue
if isinstance(result, dict) and result.get("is_live"): src = str(result.get("source") or "")
if result.get("is_live"):
entries[ref] = result entries[ref] = result
if cid:
entries[f"channel:{cid}"] = result entries[f"channel:{cid}"] = result
for ag in pk_to_assign.get(pk) or []:
gid = str(ag.get("id") or "").strip()
if not gid:
continue
ent = dict(result)
ent["assign_group_id"] = gid
ent["channel_pk"] = pk
if ag.get("name"):
ent["title"] = str(ag.get("name") or "")
entries[f"assign:{gid}"] = ent
elif src.startswith("oauth"):
# API answered offline — record so Studio cannot invent public live.
# Never replace a clean youtubei offline with an errored oauth result.
cur = entries.get(ref) or {}
if cur.get("is_live"):
continue
if (
result.get("error")
and str(cur.get("source") or "") == "youtubei"
and not cur.get("error")
):
continue
entries[ref] = dict(result)
if cid:
ch_cur = entries.get(f"channel:{cid}") or {}
if not (
result.get("error")
and str(ch_cur.get("source") or "") == "youtubei"
and not ch_cur.get("error")
and not ch_cur.get("is_live")
):
if not ch_cur.get("is_live"):
entries[f"channel:{cid}"] = dict(result)
for ag in pk_to_assign.get(pk) or []:
gid = str(ag.get("id") or "").strip()
if not gid:
continue
ae = entries.get(f"assign:{gid}") or {}
if ae.get("is_live"):
continue
if (
result.get("error")
and str(ae.get("source") or "") == "youtubei"
and not ae.get("error")
):
continue
ent = dict(result)
ent["assign_group_id"] = gid
ent["channel_pk"] = pk
if ag.get("name"):
ent["title"] = str(ag.get("name") or "")
entries[f"assign:{gid}"] = ent
elif _CACHE.get("payload") and isinstance(_CACHE.get("payload"), dict): elif _CACHE.get("payload") and isinstance(_CACHE.get("payload"), dict):
# 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线 # 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线
prev = (_CACHE.get("payload") or {}).get("entries") or {} prev = (_CACHE.get("payload") or {}).get("entries") or {}
for ref, old in prev.items(): for ref, old in prev.items():
if not str(ref).startswith("shorts:"): if not str(ref).startswith(("shorts:", "assign:")):
continue continue
if not isinstance(old, dict) or not old.get("is_live"): if not isinstance(old, dict) or not old.get("is_live"):
continue continue
@ -436,23 +711,45 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
continue continue
pk = str(g.get("channel_pk") or "").strip() pk = str(g.get("channel_pk") or "").strip()
row = relay_rows.get(gid) or {} row = relay_rows.get(gid) or {}
nid = 0 cid = str(g.get("youtube_channel_id") or "").strip()
# Already marked live via youtubei/OAuth for this shorts/channel → receiving-level truth.
prev_live = entries.get(f"assign:{gid}") or {}
if not prev_live.get("is_live") and pk:
prev_live = entries.get(f"shorts:{pk}") or {}
if not prev_live.get("is_live") and cid:
prev_live = entries.get(f"channel:{cid}") or {}
# Prefer group-aware Studio snap (remote ops-neko when prefer=remote).
studio_snap: dict[str, Any] = {}
try:
studio_snap = await asyncio.to_thread(
lambda gg=g: youtube_neko.studio_snapshot_for_group(gg, max_age_sec=120.0)
)
except Exception:
studio_snap = {}
if not studio_snap.get("on_air") and not studio_snap.get("encoder_receiving"):
# Legacy local-instance CDP lookup as extra receiving probe.
try: try:
nid = int(g.get("neko_instance_id") or 0) nid = int(g.get("neko_instance_id") or 0)
except (TypeError, ValueError): except (TypeError, ValueError):
nid = 0 nid = 0
studio_snap: dict[str, Any] = {}
if nid > 0: if nid > 0:
try: try:
studio_snap = await asyncio.to_thread( local_snap = await asyncio.to_thread(
lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0) lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0)
) )
except Exception: except Exception:
studio_snap = {} local_snap = {}
if local_snap.get("on_air") or local_snap.get("encoder_receiving"):
studio_snap = local_snap
# Fallback: match telemetry by group's saved studio URL (no CDP / no instance tag). # Fallback: match telemetry by group's saved studio URL (receiving signals only).
if not studio_snap.get("on_air"): if not (
studio_snap.get("on_air")
or studio_snap.get("encoder_receiving")
or str(studio_snap.get("live_status") or "").lower() == "live"
):
studio_url = str(g.get("neko_studio_url") or "") studio_url = str(g.get("neko_studio_url") or "")
vid = "" vid = ""
if "/video/" in studio_url: if "/video/" in studio_url:
@ -466,32 +763,159 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
url = str(payload.get("url") or "") url = str(payload.get("url") or "")
if vid not in url: if vid not in url:
continue continue
if str(payload.get("live_status") or "").lower() in {"live", "streaming"} or str( signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {}
payload.get("health") or "" st = str(payload.get("live_status") or "").lower()
).lower() in {"excellent", "good"}: health = str(payload.get("health") or "").lower()
receiving = bool(
signals.get("encoder_receiving")
or st == "live"
or health in {"excellent", "good"}
)
if not receiving:
continue
if signals.get("encoder_lost") or st in {"encoder_lost", "waiting", "ended"}:
continue
studio_snap = { studio_snap = {
"on_air": True, "on_air": True,
"encoder_receiving": True,
"live_page_open": True, "live_page_open": True,
"live_status": str(payload.get("live_status") or "live"), "live_status": st or "live",
"health": str(payload.get("health") or ""), "health": health,
"viewer_count": payload.get("viewer_count"), "viewer_count": payload.get("viewer_count"),
"url": url[:200], "url": url[:200],
"received_at": float(ev.get("received_at") or 0), "received_at": float(ev.get("received_at") or 0),
"detect_source": "telemetry_url_match", "detect_source": "telemetry_url_match",
"neko_instance_id": nid,
} }
break break
mark_live = bool(row.get("is_pushing") or studio_snap.get("on_air")) # DB samples (physical local Neko CDP) — fill when in-memory snap is quiet.
if not (
studio_snap.get("on_air")
or studio_snap.get("encoder_receiving")
or str(studio_snap.get("live_status") or "").lower() == "live"
):
try:
from . import yt_studio_db
samples = await asyncio.to_thread(
lambda: yt_studio_db.list_samples(
group_id=gid, since_ts=now - 180.0, limit=5
)
)
if not samples and cid:
samples = await asyncio.to_thread(
lambda: yt_studio_db.list_samples(
youtube_channel_id=cid, since_ts=now - 180.0, limit=5
)
)
except Exception:
samples = []
for s in samples or []:
st = str(s.get("live_status") or "").lower()
if st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}:
continue
if not (s.get("on_air") or st == "live"):
continue
studio_snap = {
"on_air": True,
"encoder_receiving": True,
"live_page_open": bool(s.get("live_page_open") or True),
"live_status": st or "live",
"health": str(s.get("health") or ""),
"viewer_count": s.get("viewer_count"),
"url": str(s.get("studio_url") or "")[:200],
"received_at": float(s.get("ts") or 0),
"detect_source": "yt_studio_samples",
"neko_ref": str(s.get("neko_ref") or ""),
}
break
receiving = bool(
(
studio_snap.get("encoder_receiving")
or studio_snap.get("on_air")
)
and not studio_snap.get("encoder_lost")
and str(studio_snap.get("live_status") or "").lower()
not in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}
)
# Collect public probe answers across assign / channel / shorts refs.
public_sources = {
"youtubei",
"http_live",
"oauth",
"oauth-broadcast",
"oauth_liveBroadcasts",
}
public_live_hit: dict[str, Any] | None = None
public_offline_hit: dict[str, Any] | None = None
for key in (
f"assign:{gid}",
f"channel:{cid}" if cid else "",
f"shorts:{pk}" if pk else "",
):
if not key:
continue
p = entries.get(key)
if not isinstance(p, dict):
continue
s = str(p.get("source") or "")
if s not in public_sources:
continue
if p.get("is_live"):
public_live_hit = p
break
# Prefer clean offline answers; youtubei offline always counts even if
# another ref holds an errored oauth leftover.
if not p.get("error"):
public_offline_hit = p
elif s == "youtubei" and not p.get("is_live"):
public_offline_hit = public_offline_hit or p
prev_public = bool(
prev_live.get("is_live")
and str(prev_live.get("source") or "") in public_sources
)
# Receiving-first: Studio on_air / encoder_receiving beats public offline
# (youtubei false-negatives + OAuth "mine" miss when push uses another key).
if receiving:
mark_live = True
source = "studio_receiving"
elif public_live_hit or prev_public:
mark_live = True
source = str(
(public_live_hit or prev_live).get("source") or "youtubei"
)
elif public_offline_hit is not None:
mark_live = bool(row.get("is_pushing"))
source = "relay" if mark_live else ""
else:
mark_live = bool(row.get("is_pushing"))
source = "relay" if mark_live else ""
if not mark_live: if not mark_live:
# Keep studio snapshot on assign entry for UI even when offline. base = entries.get(f"assign:{gid}") or {
if studio_snap.get("live_page_open") and f"assign:{gid}" in entries: "is_live": False,
entries[f"assign:{gid}"]["studio"] = studio_snap "source": str((public_offline_hit or {}).get("source") or "unknown"),
"assign_group_id": gid,
"channel_pk": pk,
"title": gid_to_name.get(gid) or str(g.get("name") or ""),
"channel_id": cid,
}
base = dict(base)
base["is_live"] = False
if studio_snap.get("live_page_open") or studio_snap:
base["studio"] = studio_snap
entries[f"assign:{gid}"] = base
continue continue
prev = entries.get(f"assign:{gid}") or {} prev = entries.get(f"assign:{gid}") or prev_live or {}
source = "relay" if row.get("is_pushing") else "studio_telemetry" if prev.get("is_live") and prev.get("source") not in {
if prev.get("is_live") and prev.get("source") not in {"relay", "studio_telemetry"}: "relay",
"studio_telemetry",
"studio_receiving",
}:
source = str(prev.get("source") or source) source = str(prev.get("source") or source)
entries[f"assign:{gid}"] = { entries[f"assign:{gid}"] = {
**prev, **prev,
@ -517,9 +941,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
} }
else: else:
entries[shorts_ref]["assign_group_id"] = gid entries[shorts_ref]["assign_group_id"] = gid
cid = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip() cid2 = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip()
if cid: if cid2:
entries[f"channel:{cid}"] = dict(entries[shorts_ref]) entries[f"channel:{cid2}"] = dict(entries[shorts_ref])
except Exception as exc: except Exception as exc:
import logging import logging

File diff suppressed because it is too large Load Diff

249
backend/app/yt_studio_db.py Normal file
View File

@ -0,0 +1,249 @@
# -*- coding: utf-8 -*-
"""YouTube Studio live metrics samples — analytics store.
Links: Douyin room ↔ assign group / YouTube channel ↔ Neko (local|remote).
Samples are appended ~1/min from extension/CDP ingest (and hub mirrors of ops-neko).
"""
from __future__ import annotations
import json
import sqlite3
import time
from typing import Any, Optional
from .db import _connect, _lock, _row_to_dict
def ensure_yt_studio_tables(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS yt_studio_samples (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts REAL NOT NULL,
group_id TEXT NOT NULL DEFAULT '',
channel_pk TEXT NOT NULL DEFAULT '',
youtube_channel_id TEXT NOT NULL DEFAULT '',
source_room_id TEXT NOT NULL DEFAULT '',
source_url TEXT NOT NULL DEFAULT '',
anchor_name TEXT NOT NULL DEFAULT '',
neko_kind TEXT NOT NULL DEFAULT 'local',
neko_ref TEXT NOT NULL DEFAULT '',
live_page_open INTEGER NOT NULL DEFAULT 0,
on_air INTEGER NOT NULL DEFAULT 0,
live_status TEXT NOT NULL DEFAULT '',
health TEXT NOT NULL DEFAULT '',
viewer_count INTEGER,
total_views INTEGER,
like_count INTEGER,
live_duration_sec REAL,
live_duration TEXT NOT NULL DEFAULT '',
stream_title TEXT NOT NULL DEFAULT '',
studio_url TEXT NOT NULL DEFAULT '',
detect_source TEXT NOT NULL DEFAULT '',
peak_viewers INTEGER,
relay_session_uuid TEXT NOT NULL DEFAULT '',
meta_json TEXT NOT NULL DEFAULT '{}',
created_at REAL NOT NULL
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_yt_studio_ts ON yt_studio_samples(ts DESC)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_yt_studio_group ON yt_studio_samples(group_id, ts DESC)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_yt_studio_channel ON yt_studio_samples(youtube_channel_id, ts DESC)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_yt_studio_room ON yt_studio_samples(source_room_id, ts DESC)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_yt_studio_neko ON yt_studio_samples(neko_ref, ts DESC)"
)
def _ensure() -> None:
with _lock:
conn = _connect()
try:
ensure_yt_studio_tables(conn)
conn.commit()
finally:
conn.close()
def insert_sample(
*,
ts: float | None = None,
group_id: str = "",
channel_pk: str = "",
youtube_channel_id: str = "",
source_room_id: str = "",
source_url: str = "",
anchor_name: str = "",
neko_kind: str = "local",
neko_ref: str = "",
live_page_open: bool = False,
on_air: bool = False,
live_status: str = "",
health: str = "",
viewer_count: Any = None,
total_views: Any = None,
like_count: Any = None,
live_duration_sec: Any = None,
live_duration: str = "",
stream_title: str = "",
studio_url: str = "",
detect_source: str = "",
peak_viewers: Any = None,
relay_session_uuid: str = "",
meta: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""Persist one analytics sample. Returns the stored row dict."""
_ensure()
now = time.time()
t = float(ts if ts is not None else now)
def _int_or_none(v: Any) -> int | None:
if v is None or v == "":
return None
try:
return int(v)
except (TypeError, ValueError):
return None
def _float_or_none(v: Any) -> float | None:
if v is None or v == "":
return None
try:
return float(v)
except (TypeError, ValueError):
return None
kind = str(neko_kind or "local").strip().lower()
if kind not in {"local", "remote"}:
kind = "local"
row_vals = (
t,
str(group_id or "")[:80],
str(channel_pk or "")[:80],
str(youtube_channel_id or "")[:80],
str(source_room_id or "")[:64],
str(source_url or "")[:500],
str(anchor_name or "")[:120],
kind,
str(neko_ref or "")[:40],
1 if live_page_open else 0,
1 if on_air else 0,
str(live_status or "")[:40],
str(health or "")[:40],
_int_or_none(viewer_count),
_int_or_none(total_views),
_int_or_none(like_count),
_float_or_none(live_duration_sec),
str(live_duration or "")[:16],
str(stream_title or "")[:200],
str(studio_url or "")[:400],
str(detect_source or "")[:40],
_int_or_none(peak_viewers),
str(relay_session_uuid or "")[:80],
json.dumps(meta or {}, ensure_ascii=False)[:2000],
now,
)
with _lock:
conn = _connect()
try:
ensure_yt_studio_tables(conn)
cur = conn.execute(
"""
INSERT INTO yt_studio_samples(
ts, group_id, channel_pk, youtube_channel_id, source_room_id, source_url,
anchor_name, neko_kind, neko_ref, live_page_open, on_air, live_status, health,
viewer_count, total_views, like_count, live_duration_sec, live_duration,
stream_title, studio_url, detect_source, peak_viewers, relay_session_uuid,
meta_json, created_at
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",
row_vals,
)
conn.commit()
rid = int(cur.lastrowid or 0)
row = conn.execute("SELECT * FROM yt_studio_samples WHERE id = ?", (rid,)).fetchone()
return _public_sample(_row_to_dict(row) if row else {"id": rid})
finally:
conn.close()
def _public_sample(row: dict[str, Any]) -> dict[str, Any]:
out = dict(row)
out["live_page_open"] = bool(out.get("live_page_open"))
out["on_air"] = bool(out.get("on_air"))
meta = out.pop("meta_json", "{}")
try:
out["meta"] = json.loads(meta) if meta else {}
except json.JSONDecodeError:
out["meta"] = {}
return out
def list_samples(
*,
group_id: str = "",
youtube_channel_id: str = "",
source_room_id: str = "",
neko_ref: str = "",
since_ts: float = 0,
limit: int = 200,
) -> list[dict[str, Any]]:
_ensure()
lim = max(1, min(2000, int(limit)))
clauses: list[str] = []
args: list[Any] = []
if group_id:
clauses.append("group_id = ?")
args.append(str(group_id).strip())
if youtube_channel_id:
clauses.append("youtube_channel_id = ?")
args.append(str(youtube_channel_id).strip())
if source_room_id:
clauses.append("source_room_id = ?")
args.append(str(source_room_id).strip())
if neko_ref:
clauses.append("neko_ref = ?")
args.append(str(neko_ref).strip())
if since_ts > 0:
clauses.append("ts >= ?")
args.append(float(since_ts))
where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
with _lock:
conn = _connect()
try:
ensure_yt_studio_tables(conn)
rows = conn.execute(
f"SELECT * FROM yt_studio_samples{where} ORDER BY ts DESC LIMIT ?",
(*args, lim),
).fetchall()
return [_public_sample(_row_to_dict(r)) for r in rows]
finally:
conn.close()
def session_stats_for_group(group_id: str, *, since_ts: float = 0) -> dict[str, Any]:
"""Aggregate peak/avg/now viewers for a group window (analytics helper)."""
rows = list_samples(group_id=group_id, since_ts=since_ts, limit=500)
vals = [int(r["viewer_count"]) for r in rows if r.get("viewer_count") is not None]
totals = [int(r["total_views"]) for r in rows if r.get("total_views") is not None]
peak = max(vals) if vals else None
avg = round(sum(vals) / len(vals), 1) if vals else None
now_v = vals[0] if vals else None
return {
"group_id": group_id,
"sample_count": len(rows),
"peak_viewers": peak,
"avg_viewers": avg,
"viewer_count": now_v,
"total_views": totals[0] if totals else None,
"neko_kinds": sorted({str(r.get("neko_kind") or "") for r in rows if r.get("neko_kind")}),
}

View File

@ -161,21 +161,46 @@ def main() -> None:
pass pass
lower = text.lower() lower = text.lower()
nodata = bool(
re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower)
)
session_live = bool(
re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?", lower)
or re.search(r"(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}", text)
) and (
bool(re.search(r"end stream|stop streaming|结束直播|停止直播", lower))
or bool(re.search(r"\blive\b", lower))
)
encoder_lost_hint = bool(
re.search(
r"will end shortly|restart it in your streaming software|unless you restart|"
r"即将结束|请重新|重新启动|推流软件|断流",
lower,
)
)
status = "" status = ""
if re.search(r"stream ended|not live|offline|直播已结束|未在直播", lower): if re.search(r"stream ended|直播已结束", lower) and not session_live:
status = "ended" status = "ended"
elif re.search( elif session_live and (nodata or encoder_lost_hint):
# 断播: LIVE session still open, encoder dropped — NOT 待开播
status = "encoder_lost"
elif session_live or re.search(
r"you.?re live|you are live|stream is healthy|excellent connection|" r"you.?re live|you are live|stream is healthy|excellent connection|"
r"concurrent viewers|watching now|stop streaming|end stream|" r"concurrent viewers|watching now|直播中|正在直播|人正在观看",
r"直播中|正在直播|人正在观看|结束直播",
lower, lower,
): ):
status = "live" status = "live"
elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower): elif nodata or re.search(
# e.g. "LIVE 1:19:36" on Studio control room r"connect your encoder|stream offline|not streaming|waiting for you to start|"
status = "live" r"start sending us your video|待开播|等待你开始",
lower,
):
status = "waiting"
elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower): elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower):
status = "waiting" status = "waiting"
elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower):
status = "live"
health = "" health = ""
if re.search(r"excellent connection|stream is healthy|状况良好|连接状况极佳", lower): if re.search(r"excellent connection|stream is healthy|状况良好|连接状况极佳", lower):
@ -234,9 +259,25 @@ def main() -> None:
except Exception: except Exception:
live_duration_sec = None live_duration_sec = None
on_air = status == "live" or health in {"excellent", "good"} or ( if live_duration and not session_live:
viewers is not None and status != "ended" and status != "waiting" session_live = True
) or bool(live_duration and status != "ended" and status != "waiting") if status in {"", "waiting"} and (nodata or encoder_lost_hint):
status = "encoder_lost"
elif status in {"", "waiting"}:
status = "live"
# 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播.
on_air = bool(status == "live" and not nodata and not encoder_lost_hint)
encoder_lost = status == "encoder_lost" or (session_live and nodata)
encoder_receiving = bool(
not nodata
and not encoder_lost
and (
status == "live"
or health
or re.search(r"starting|receiving|connecting|正在接收|连接中", lower)
)
)
print( print(
json.dumps( json.dumps(
{ {
@ -249,6 +290,10 @@ def main() -> None:
"live_duration": live_duration, "live_duration": live_duration,
"live_duration_sec": live_duration_sec, "live_duration_sec": live_duration_sec,
"on_air": on_air, "on_air": on_air,
"nodata": nodata,
"encoder_receiving": encoder_receiving,
"encoder_lost": encoder_lost,
"session_live": bool(session_live or status in {"live", "encoder_lost"}),
"text": text[:500], "text": text[:500],
}, },
ensure_ascii=False, ensure_ascii=False,

View File

@ -2,6 +2,8 @@ const API_BASES = [
// Physical / Docker: hit host API first — public HTTPS often hangs and blocks all telemetry. // Physical / Docker: hit host API first — public HTTPS often hangs and blocks all telemetry.
"http://host.docker.internal:8014", "http://host.docker.internal:8014",
"http://172.17.0.1:8014", "http://172.17.0.1:8014",
// VPS dylive (local assign Neko on hub) — must be present or telemetry never reaches hub.
"https://dylive.nomadro.com",
"https://dy.nomadro.com", "https://dy.nomadro.com",
"https://dy.nomadro.cn", "https://dy.nomadro.cn",
"https://dy.nomadro.live", "https://dy.nomadro.live",
@ -14,7 +16,7 @@ const AUTH_JUNK_RE =
/accounts\.google\.com\/(?:ServiceLogin|signin|v3\/signin|accountchooser|RotateCookiesPage)/i; /accounts\.google\.com\/(?:ServiceLogin|signin|v3\/signin|accountchooser|RotateCookiesPage)/i;
const YOUTUBE_HOME_RE = /^https:\/\/www\.youtube\.com\/?(?:\?|$)/; const YOUTUBE_HOME_RE = /^https:\/\/www\.youtube\.com\/?(?:\?|$)/;
let cachedNekoInstanceId = 0; let cachedNekoInstanceId = "";
function sleep(ms) { function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
@ -24,13 +26,26 @@ function tabUrl(tab) {
return tab?.pendingUrl || tab?.url || ""; return tab?.pendingUrl || tab?.url || "";
} }
function normalizeNekoRef(raw) {
const text = String(raw || "").trim();
if (!text) return "";
const low = text.toLowerCase();
if (low.startsWith("ops-") || low.startsWith("ops:")) {
const digits = low.replace(/^ops[-:]/, "").replace(/[^\d]/g, "");
return digits ? `ops-${digits}` : "";
}
const n = Number(text);
if (Number.isFinite(n) && n > 0) return String(Math.trunc(n));
return "";
}
async function loadNekoInstanceId() { async function loadNekoInstanceId() {
if (cachedNekoInstanceId > 0) return cachedNekoInstanceId; if (cachedNekoInstanceId) return cachedNekoInstanceId;
try { try {
const stored = await chrome.storage.local.get(["nekoInstanceId"]); const stored = await chrome.storage.local.get(["nekoInstanceId", "nekoInstanceRef"]);
const fromStore = Number(stored.nekoInstanceId || 0); const fromRef = normalizeNekoRef(stored.nekoInstanceRef || stored.nekoInstanceId || "");
if (fromStore > 0) { if (fromRef) {
cachedNekoInstanceId = fromStore; cachedNekoInstanceId = fromRef;
return cachedNekoInstanceId; return cachedNekoInstanceId;
} }
} catch {} } catch {}
@ -38,15 +53,15 @@ async function loadNekoInstanceId() {
const res = await fetch(chrome.runtime.getURL("instance_id.txt"), { cache: "no-store" }); const res = await fetch(chrome.runtime.getURL("instance_id.txt"), { cache: "no-store" });
if (res.ok) { if (res.ok) {
const text = (await res.text()).trim(); const text = (await res.text()).trim();
const nid = Number(text); const ref = normalizeNekoRef(text);
if (Number.isFinite(nid) && nid > 0) { if (ref) {
cachedNekoInstanceId = nid; cachedNekoInstanceId = ref;
await chrome.storage.local.set({ nekoInstanceId: nid }); await chrome.storage.local.set({ nekoInstanceId: ref, nekoInstanceRef: ref });
return nid; return ref;
} }
} }
} catch {} } catch {}
return 0; return "";
} }
loadNekoInstanceId().catch(() => {}); loadNekoInstanceId().catch(() => {});
@ -139,12 +154,20 @@ scheduleTabHygiene();
async function postTelemetry(payload) { async function postTelemetry(payload) {
const stored = await chrome.storage.local.get(["liveHubIngestToken"]); const stored = await chrome.storage.local.get(["liveHubIngestToken"]);
const ingestToken = (stored.liveHubIngestToken || "").trim(); const ingestToken = (stored.liveHubIngestToken || "").trim();
const nekoInstanceId = (await loadNekoInstanceId()) || Number(payload?.neko_instance_id || 0) || 0; const nekoRef =
(await loadNekoInstanceId()) ||
normalizeNekoRef(payload?.neko_ref || payload?.neko_instance_id || "") ||
"";
const body = JSON.stringify({ const body = JSON.stringify({
...payload, ...payload,
source: payload.source || "chrome_extension", source: payload.source || "chrome_extension",
received_at: Date.now() / 1000, received_at: Date.now() / 1000,
...(nekoInstanceId > 0 ? { neko_instance_id: nekoInstanceId } : {}), ...(nekoRef
? {
neko_instance_id: nekoRef,
neko_ref: nekoRef,
}
: {}),
...(ingestToken ? { ingest_token: ingestToken } : {}), ...(ingestToken ? { ingest_token: ingestToken } : {}),
}); });
let lastError = ""; let lastError = "";
@ -166,7 +189,7 @@ async function postTelemetry(payload) {
liveHubLastOk: Date.now(), liveHubLastOk: Date.now(),
liveHubLastBase: base, liveHubLastBase: base,
liveHubLastEvent: data?.event?.id || null, liveHubLastEvent: data?.event?.id || null,
liveHubLastNekoId: data?.event?.neko_instance_id || nekoInstanceId || null, liveHubLastNekoId: data?.event?.neko_ref || data?.event?.neko_instance_id || nekoRef || null,
}); });
return { ok: true, base, eventId: data?.event?.id || null }; return { ok: true, base, eventId: data?.event?.id || null };
} }

View File

@ -36,21 +36,69 @@ function firstNumberByPatterns(text, patterns) {
return null; return null;
} }
function detectNodata(text) {
const lower = text.toLowerCase();
// Studio encoder badge: "No data" / NODATA / 无数据
return /(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据|没有数据/.test(lower);
}
/** YouTube Live session already started (LIVE pill + timer / End Stream). */
function detectSessionLive(text) {
const lower = text.toLowerCase();
const hasTimer =
/\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?/.test(lower) ||
/(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}/.test(text);
const hasEnd =
/end stream|stop streaming|结束直播|停止直播/.test(lower);
return Boolean(hasTimer && hasEnd) || Boolean(hasTimer && /\blive\b/.test(lower));
}
/** Encoder dropped while session still live — 断播 (not 待开播). */
function detectEncoderLost(text) {
const lower = text.toLowerCase();
if (/will end shortly|restart it in your streaming software|unless you restart/.test(lower)) {
return true;
}
if (/(?:即将结束|请重新|重新启动|推流软件|编码器.*断开|断流)/.test(text)) {
return true;
}
return detectSessionLive(text) && detectNodata(text);
}
/**
* Studio states we must not confuse:
* - waiting / 待开播: control room open, broadcast not started
* - live / 开播: session live + encoder has data
* - encoder_lost / 断播: session still live, encoder NODATA / will end shortly
* - ended / 停播: stream ended
*/
function detectLiveStatus(text) { function detectLiveStatus(text) {
const lower = text.toLowerCase(); const lower = text.toLowerCase();
if (/stream ended|not live|offline|直播已结束|未在直播/.test(lower)) return "ended"; if (/stream ended|直播已结束|未在直播/.test(lower) && !detectSessionLive(text)) {
if (/connect your encoder|no data|stream offline|not streaming|waiting for you to start/.test(lower)) { return "ended";
return "waiting";
} }
const sessionLive = detectSessionLive(text);
const nodata = detectNodata(text);
if (sessionLive && (detectEncoderLost(text) || nodata)) {
return "encoder_lost";
}
if (sessionLive) {
return "live";
}
// True 待开播: no LIVE session yet
if ( if (
/you'?re live|you are live|excellent connection|stream is healthy|end stream|stop streaming|concurrent viewers|watching now|直播中|正在直播|已开始直播|结束直播/.test( nodata ||
/connect your encoder|stream offline|not streaming|waiting for you to start|待开播|等待你开始|start sending us your video/.test(
lower lower
) )
) { ) {
return "live"; return "waiting";
} }
// Studio shows a LIVE pill + duration while on-air if (
if (/\blive\b[\s\S]{0,40}\d+:\d{2}(?::\d{2})?/.test(lower) && /end stream|stop streaming/.test(lower)) { /you'?re live|you are live|excellent connection|stream is healthy|concurrent viewers|watching now|直播中|正在直播|已开始直播/.test(
lower
)
) {
return "live"; return "live";
} }
if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting"; if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting";
@ -157,14 +205,27 @@ function collectTelemetry() {
const dur = parseLiveDuration(text); const dur = parseLiveDuration(text);
const totalViews = parseTotalViews(text); const totalViews = parseTotalViews(text);
const popups = collectPopupTexts(); const popups = collectPopupTexts();
const liveStatus = detectLiveStatus(text);
const nodata = detectNodata(text);
const sessionLive = detectSessionLive(text) || liveStatus === "live" || liveStatus === "encoder_lost";
const encoderLost = liveStatus === "encoder_lost" || detectEncoderLost(text);
const health = detectHealth(text);
// 开播中且有码流;绿点 preview(未点 Go Live)不算 live
const encoderReceiving =
!nodata &&
!encoderLost &&
(liveStatus === "live" ||
Boolean(health) ||
/starting|receiving|connecting|正在接收|连接中|缓冲/.test(text.toLowerCase()));
const pendingGoLive = liveStatus === "waiting" && !sessionLive && !encoderLost;
const payload = { const payload = {
captured_at: Date.now() / 1000, captured_at: Date.now() / 1000,
source: "chrome_extension", source: "chrome_extension",
url: location.href, url: location.href,
page_title: document.title, page_title: document.title,
stream_title: collectStreamTitle(), stream_title: collectStreamTitle(),
live_status: detectLiveStatus(text), live_status: liveStatus,
health: detectHealth(text), health,
viewer_count: viewerCount, viewer_count: viewerCount,
like_count: likeCount, like_count: likeCount,
total_views: totalViews, total_views: totalViews,
@ -177,6 +238,11 @@ function collectTelemetry() {
visibility: document.visibilityState, visibility: document.visibilityState,
focused: document.hasFocus(), focused: document.hasFocus(),
path: location.pathname, path: location.pathname,
nodata,
encoder_receiving: encoderReceiving,
encoder_lost: encoderLost,
session_live: sessionLive,
pending_go_live: pendingGoLive,
}, },
}; };
return payload; return payload;

View File

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from app.yt_assign_db import group_is_time_slot, normalize_assign_category
def test_normalize_assign_category():
assert normalize_assign_category("normal") == "normal"
assert normalize_assign_category("普通") == "normal"
assert normalize_assign_category("") == "normal"
assert normalize_assign_category(None) == "normal"
assert normalize_assign_category("time_slot") == "time_slot"
assert normalize_assign_category("时间段") == "time_slot"
assert normalize_assign_category("timeslot") == "time_slot"
assert normalize_assign_category("weird") == "normal"
def test_group_is_time_slot():
assert group_is_time_slot({"category": "time_slot"}) is True
assert group_is_time_slot({"category": "normal"}) is False
assert group_is_time_slot({"category": "普通"}) is False
assert group_is_time_slot({}) is False
assert group_is_time_slot(None) is False

View File

@ -0,0 +1,54 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from app import youtube_neko
def test_preferred_neko_public_base_colocated(monkeypatch) -> None:
monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: False)
monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dylive.nomadro.com")
assert youtube_neko.preferred_neko_public_base() == "https://dylive.nomadro.com"
def test_preferred_neko_public_base_cn_first(monkeypatch) -> None:
monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: True)
monkeypatch.setattr(youtube_neko, "cn_edge_usable", lambda: True)
monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dy.nomadro.com")
monkeypatch.delenv("DY_NEKO_CN_PUBLIC_BASE", raising=False)
assert youtube_neko.preferred_neko_public_base() == "https://dy.nomadro.cn"
def test_preferred_neko_public_base_vps_fallback(monkeypatch) -> None:
monkeypatch.setattr(youtube_neko, "_physical_dual_edge", lambda: True)
monkeypatch.setattr(youtube_neko, "cn_edge_usable", lambda: False)
monkeypatch.setattr(youtube_neko, "_public_base", lambda: "https://dy.nomadro.com")
monkeypatch.delenv("DY_NEKO_CN_PUBLIC_BASE", raising=False)
assert youtube_neko.preferred_neko_public_base() == "https://dy.nomadro.com"
def test_compose_service_lines_has_studio_live_env(tmp_path, monkeypatch) -> None:
assets = youtube_neko._asset_root() # noqa: SLF001
monkeypatch.setattr(youtube_neko, "_detect_public_ip", lambda: "1.2.3.4")
monkeypatch.setattr(youtube_neko, "_neko_browser_proxy_value", lambda: "http://host.docker.internal:7890")
profile = tmp_path / "p"
profile.mkdir()
idf = tmp_path / "id.txt"
idf.write_text("ops-1\n", encoding="utf-8")
lines = youtube_neko.compose_service_lines(
service_key="opsneko1",
container_name="douyinweb-ops-neko-1",
instance_id_label="ops-1",
http_port=18200,
mux=62300,
udp="62500-62509",
profile=profile,
instance_id_file=idf,
http_bind="0.0.0.0",
)
blob = "\n".join(lines)
assert "NEKO_LIVE_OPS_EXTENSION" in blob
assert "NEKO_TAMPERMONKEY_REPAIR" in blob
assert "studio.youtube.com" in blob
assert "host.docker.internal:7890" in blob
assert str(assets / "tampermonkey-seed") in blob or "tampermonkey-seed" in blob
assert "opsneko1:" in blob

View File

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from app import ops_neko_db
def test_edge_catalog_upsert_and_list(temp_db) -> None:
rows = ops_neko_db.upsert_edge_catalog(
[
{
"id": "a",
"slot": 1,
"name": "N1",
"open_url": "https://dy.nomadro.cn/ops-neko/1/",
"running": True,
},
{
"slot": 2,
"name": "N2",
"open_url": "https://dy.nomadro.cn/ops-neko/2/",
"running": False,
},
],
edge_id="phys1",
edge_label="phys1",
)
assert len(rows) >= 2
listed = ops_neko_db.list_edge_catalog(max_age_sec=3600)
assert any(r.get("slot") == 1 and "ops-neko/1" in str(r.get("open_url")) for r in listed)

View File

@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from app import youtube_neko
def test_studio_live_control_url() -> None:
assert "UC123456789012345678" in youtube_neko.studio_live_control_url("UC123456789012345678")
assert youtube_neko.studio_live_control_url("UC123456789012345678").endswith("/livestreaming")
assert "studio.youtube.com" in youtube_neko.studio_live_control_url("")
def test_wait_group_ready_for_live_prefers_ops_telemetry() -> None:
youtube_neko._studio_events.clear() # noqa: SLF001
youtube_neko._studio_latest_by_ref.clear() # noqa: SLF001
now = time.time()
youtube_neko.ingest_studio_telemetry(
{
"neko_ref": "ops-2",
"neko_instance_id": "ops-2",
"url": "https://studio.youtube.com/channel/UCabcdefghijklmnopqr/livestreaming",
"live_status": "waiting",
"received_at": now,
"signals": {"path": "/livestreaming", "pending_go_live": True},
}
)
group = {
"id": "g1",
"neko_open_prefer": "remote",
"ops_neko_open_url": "https://dy.nomadro.cn/ops-neko/2/",
"ops_neko_slot": 2,
"neko_instance_id": 8,
"youtube_channel_id": "UCabcdefghijklmnopqr",
}
out = youtube_neko.wait_group_ready_for_live(
group, timeout_sec=3.0, settle_sec=0.5, strict=True
)
assert out.get("ok") is True
assert out.get("neko_kind") == "ops"
assert out.get("ops_slot") == 2
assert out.get("live_studio") is True

View File

@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
"""time_slot source pick must skip offline sticky rooms."""
from __future__ import annotations
from typing import Any
def test_pick_source_excludes_sticky_offline(monkeypatch):
from app import youtube_relay_pipeline as yrp
rooms = [
{"room_id": "111", "url": "https://live.douyin.com/111", "last_anchor": "A"},
{"room_id": "222", "url": "https://live.douyin.com/222", "last_anchor": "B"},
{"room_id": "333", "url": "https://live.douyin.com/333", "last_anchor": "C"},
]
monkeypatch.setattr(yrp.db, "list_live_douyin_rooms_for_shorts", lambda limit=40: rooms)
monkeypatch.setattr(yrp, "_group_in_active_slot", lambda gid, keyed_only=False: True)
monkeypatch.setattr(yrp, "_group_uses_time_slot", lambda g: True)
group: dict[str, Any] = {"id": "g1", "enabled": 1, "category": "time_slot"}
sticky = yrp.pick_source_for_group(group, prefer_room_id="111")
assert sticky and sticky["room_id"] == "111"
rotated = yrp.pick_source_for_group(
group,
prefer_room_id="111",
exclude_room_ids={"111"},
)
assert rotated and rotated["room_id"] == "222"
cleared = yrp.pick_source_for_group(
group,
prefer_room_id="",
exclude_room_ids={"111", "222"},
)
assert cleared and cleared["room_id"] == "333"

View File

@ -12,8 +12,92 @@ def _reset_events() -> None:
def test_payload_stream_confirmed_live_status() -> None: def test_payload_stream_confirmed_live_status() -> None:
assert youtube_neko._payload_stream_confirmed({"live_status": "live"}) is True assert youtube_neko._payload_stream_confirmed({"live_status": "live"}) is True
assert youtube_neko._payload_stream_confirmed({"health": "excellent"}) is True # health alone / streaming (page-open mirror) must NOT count as on-air
assert youtube_neko._payload_stream_confirmed({"health": "excellent"}) is False
assert youtube_neko._payload_stream_confirmed({"live_status": "streaming"}) is False
assert youtube_neko._payload_stream_confirmed({"live_status": "waiting"}) is False assert youtube_neko._payload_stream_confirmed({"live_status": "waiting"}) is False
assert youtube_neko._payload_stream_confirmed({"live_status": "ready"}) is False
assert youtube_neko._payload_stream_confirmed({"viewer_count": 0, "url": "https://studio.youtube.com/x/livestreaming"}) is False
assert youtube_neko._payload_stream_confirmed({"viewer_count": 3, "url": "https://studio.youtube.com/x/livestreaming"}) is True
assert (
youtube_neko._payload_stream_confirmed(
{"text": "No data\nConnect your encoder to go live", "live_status": "waiting"}
)
is False
)
assert youtube_neko._payload_nodata_or_pending({"live_status": "waiting"}) is True
assert youtube_neko._payload_nodata_or_pending({"signals": {"nodata": True}}) is True
assert youtube_neko._payload_nodata_or_pending({"live_status": "live", "text": "You're live"}) is False
def test_studio_encoder_lost_is_duanbo_not_pending() -> None:
"""LIVE timer + No data + will end shortly = 断播, not 待开播."""
text = (
"LIVE\n8:15\nEnd Stream\nLive\nNo data\nKey:\nConnect your encoder to go live\n"
"No data - This stream will end shortly, unless you restart it in your streaming software\n"
"Concurrent viewers\n0"
)
payload = {
"url": "https://studio.youtube.com/video/1cQY6jHytxQ/livestreaming",
"live_status": "encoder_lost",
"live_duration": "8:15",
"live_duration_sec": 495,
"viewer_count": 0,
"text": text,
"signals": {
"path": "/livestreaming",
"nodata": True,
"encoder_lost": True,
"session_live": True,
"pending_go_live": False,
},
}
assert youtube_neko._payload_session_live(payload) is True
assert youtube_neko._payload_encoder_lost(payload) is True
assert youtube_neko._payload_stream_confirmed(payload) is False
assert youtube_neko._payload_nodata_or_pending(payload) is False
# Infer from text alone (no explicit status)
inferred = {
"url": "https://studio.youtube.com/video/1cQY6jHytxQ/livestreaming",
"text": text,
"live_duration": "8:15",
"signals": {"path": "/livestreaming", "nodata": True},
}
assert youtube_neko._payload_session_live(inferred) is True
assert youtube_neko._payload_encoder_lost(inferred) is True
assert youtube_neko._payload_nodata_or_pending(inferred) is False
# True 待开播: nodata without LIVE session
pending = {
"url": "https://studio.youtube.com/video/x/livestreaming",
"live_status": "waiting",
"text": "No data\nConnect your encoder to go live\nStart sending us your video",
"signals": {"nodata": True, "pending_go_live": True},
}
assert youtube_neko._payload_session_live(pending) is False
assert youtube_neko._payload_encoder_lost(pending) is False
assert youtube_neko._payload_nodata_or_pending(pending) is True
def test_ingest_remote_studio_mirror_does_not_fake_streaming() -> None:
youtube_neko._studio_events.clear() # noqa: SLF001
youtube_neko._studio_latest_by_ref.clear() # noqa: SLF001
out = youtube_neko.ingest_remote_studio_mirror(
2,
{
"live_page_open": True,
"on_air": False,
"live_status": "",
"url": "https://studio.youtube.com/video/L1sF_kZvzIk/livestreaming",
},
)
assert out.get("ok") is not False or out # ingest returns dict
snap = youtube_neko.studio_snapshot_for_ref("ops:2", max_age_sec=60.0)
assert snap.get("live_page_open") is True
assert snap.get("on_air") is False
assert str(snap.get("live_status") or "") in {"waiting", ""}
def test_latest_live_studio_event_since_ts() -> None: def test_latest_live_studio_event_since_ts() -> None:

View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
from app.youtube_neko import parse_neko_ref
from app import yt_studio_db
def test_parse_neko_ref():
assert parse_neko_ref("ops-1") == ("remote", "ops:1", 0)
assert parse_neko_ref("ops:2") == ("remote", "ops:2", 0)
assert parse_neko_ref("5") == ("local", "local:5", 5)
assert parse_neko_ref("") == ("local", "", 0)
def test_insert_sample_roundtrip(tmp_path, monkeypatch):
# Use real DB — just insert and list
row = yt_studio_db.insert_sample(
group_id="g1",
youtube_channel_id="UC123",
source_room_id="room9",
neko_kind="remote",
neko_ref="ops:1",
on_air=True,
live_page_open=True,
viewer_count=12,
total_views=100,
peak_viewers=12,
)
assert row.get("group_id") == "g1"
assert row.get("neko_kind") == "remote"
rows = yt_studio_db.list_samples(group_id="g1", limit=5)
assert any(r.get("id") == row.get("id") for r in rows)

View File

@ -48,6 +48,15 @@ type RemoteCard = {
neko_open_prefer?: string; neko_open_prefer?: string;
}; };
type SyncStatus = {
enabled?: boolean;
connected?: boolean;
last_ok_age_sec?: number | null;
last_error?: string;
interval_sec?: number;
ticks?: number;
};
export default function OpsNekoPage() { export default function OpsNekoPage() {
const toast = useToast(); const toast = useToast();
const confirm = useConfirm(); const confirm = useConfirm();
@ -62,6 +71,7 @@ export default function OpsNekoPage() {
const [tokenInput, setTokenInput] = useState(""); const [tokenInput, setTokenInput] = useState("");
const [remoteCards, setRemoteCards] = useState<RemoteCard[]>([]); const [remoteCards, setRemoteCards] = useState<RemoteCard[]>([]);
const [newName, setNewName] = useState(""); const [newName, setNewName] = useState("");
const [sync, setSync] = useState<SyncStatus>({});
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
@ -69,6 +79,7 @@ export default function OpsNekoPage() {
peer?: Peer; peer?: Peer;
instances?: Instance[]; instances?: Instance[];
host_profile?: { profile?: string }; host_profile?: { profile?: string };
sync?: SyncStatus;
}; };
setPeer(d.peer || {}); setPeer(d.peer || {});
setInstances(d.instances || []); setInstances(d.instances || []);
@ -76,6 +87,7 @@ export default function OpsNekoPage() {
setRole(String(d.peer?.role || "off")); setRole(String(d.peer?.role || "off"));
setPeerBase(String(d.peer?.peer_base_url || "")); setPeerBase(String(d.peer?.peer_base_url || ""));
setPublicBase(String(d.peer?.public_base || "")); setPublicBase(String(d.peer?.public_base || ""));
setSync(d.sync || {});
} catch (e) { } catch (e) {
toast.push((e as Error).message, "err"); toast.push((e as Error).message, "err");
} finally { } finally {
@ -87,27 +99,47 @@ export default function OpsNekoPage() {
void load(); void load();
}, [load]); }, [load]);
async function savePeer(extra: Record<string, unknown> = {}) { // Live sync status while edge-connected
setBusy("peer"); useEffect(() => {
if (role !== "edge" && peer.role !== "edge") return;
const t = window.setInterval(() => {
void fetchJson("/api/ops/neko/sync-status")
.then((d) => setSync(d as SyncStatus))
.catch(() => null);
}, 3000);
return () => window.clearInterval(t);
}, [role, peer.role]);
async function connectRealtime() {
setBusy("pair");
try { try {
const d = (await fetchJson("/api/ops/neko/peer", { const d = (await fetchJson("/api/ops/neko/pair", {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
role, hub_base: peerBase,
peer_base_url: peerBase, token: tokenInput,
public_base: publicBase, public_base: publicBase || undefined,
token: tokenInput || undefined,
...extra,
}), }),
})) as Peer & { token?: string }; })) as {
setPeer(d); ok?: boolean;
if (d.token) { peer?: Peer;
setTokenInput(d.token); cards?: { ok?: boolean; cards?: RemoteCard[]; error?: string };
toast.push("已生成 token(请复制到对端)", "ok"); catalog?: { ok?: boolean; error?: string; count?: number };
} else { hint?: string;
toast.push("配对配置已保存", "ok"); error?: string;
};
if (d.peer) setPeer(d.peer);
if (d.cards?.cards) setRemoteCards(d.cards.cards);
if (!d.ok && !d.catalog?.ok && !d.cards?.ok) {
throw new Error(d.catalog?.error || d.cards?.error || d.error || "连接失败");
} }
setRole("edge");
toast.push(d.hint || "已连接:后台自动实时同步到 VPS", "ok");
await load(); await load();
const st = (await fetchJson("/api/ops/neko/sync-now", { method: "POST" })) as SyncStatus & {
ok?: boolean;
};
setSync(st);
} catch (e) { } catch (e) {
toast.push((e as Error).message, "err"); toast.push((e as Error).message, "err");
} finally { } finally {
@ -123,8 +155,11 @@ export default function OpsNekoPage() {
body: JSON.stringify({ name: newName }), body: JSON.stringify({ name: newName }),
}); });
setNewName(""); setNewName("");
toast.push("已创建 Ops Neko(默认停止,与分配原生 Neko 隔离)", "ok"); toast.push("已创建 Ops Neko(默认停止)", "ok");
await load(); await load();
if (peer.role === "edge" || role === "edge") {
void fetchJson("/api/ops/neko/push-catalog", { method: "POST" }).catch(() => null);
}
} catch (e) { } catch (e) {
toast.push((e as Error).message, "err"); toast.push((e as Error).message, "err");
} finally { } finally {
@ -209,9 +244,9 @@ export default function OpsNekoPage() {
<h1 className="font-display text-2xl font-semibold text-white">Neko</h1> <h1 className="font-display text-2xl font-semibold text-white">Neko</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400"> <p className="mt-1 max-w-2xl text-sm text-slate-400">
独立实例池(<span className="font-mono text-slate-300">douyinweb-ops-neko-*</span> 独立实例池(<span className="font-mono text-slate-300">douyinweb-ops-neko-*</span>
),与 YouTube 分配页原生 Neko(<span className="font-mono text-slate-300">douyinweb-neko-*</span> ),运行时配置与分配页原生 Neko 相同(Studio 起始页、Tampermonkey、live-ops、ShellCrash
)互不影响。VPS 频道原生 Neko 永远保留、默认停止;物理机在此创建实例后配对到 VPS 代理、分辨率/码率、ICE)。端口与容器名分开;VPS 频道原生 Neko 永远保留。物理机打开链接优先
分配卡,分配页用开关选择「打开本机 / 打开远程」。 腾讯云 <span className="font-mono text-slate-300">.cn</span>,WG 不通才回退 VPS。
</p> </p>
{hostProfile ? ( {hostProfile ? (
<p className="mt-1 text-[11px] text-slate-500">当前主机形态:{hostProfile}</p> <p className="mt-1 text-[11px] text-slate-500">当前主机形态:{hostProfile}</p>
@ -227,27 +262,38 @@ export default function OpsNekoPage() {
</button> </button>
</header> </header>
<section className="rounded-2xl border border-white/10 bg-white/[0.03] p-4"> <section className="rounded-2xl border border-teal-500/25 bg-teal-500/[0.06] p-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 className="flex items-center gap-2 text-sm font-medium text-white"> <h2 className="flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-teal-300" /> <Server className="h-4 w-4 text-teal-300" />
跨机配对(域名 + Token) VPS 实时通道
</h2> </h2>
<p className="mt-1 text-[11px] text-slate-500">{peer.hint || "选择 hub / edge"}</p> <p className="mt-1 text-[11px] text-slate-500">
粘贴一次域名 + Token 并连接后,后台每 5 秒自动同步实例目录;启停实例也会立刻推送。
</p>
</div>
<span
className={`rounded-full px-2.5 py-1 text-[10px] font-medium ${
sync.connected
? "bg-emerald-500/20 text-emerald-100 ring-1 ring-emerald-400/30"
: peer.role === "edge"
? "bg-amber-500/20 text-amber-100 ring-1 ring-amber-400/30"
: "bg-white/5 text-slate-400 ring-1 ring-white/10"
}`}
>
{sync.connected
? `已连接 · ${Math.round(Number(sync.last_ok_age_sec ?? 0))}s 前`
: peer.role === "edge"
? sync.last_error
? `重试中 · ${sync.last_error}`
: "连接中…"
: "未连接"}
</span>
</div>
<div className="mt-3 grid gap-3 sm:grid-cols-2"> <div className="mt-3 grid gap-3 sm:grid-cols-2">
<label className="block text-[11px] text-slate-400"> <label className="block text-[11px] text-slate-400">
角色 VPS 域名(Hub)
<select
value={role}
onChange={(e) => setRole(e.target.value)}
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
>
<option value="off">off(本机独立)</option>
<option value="hub">hub(通常 VPS:发布分配卡)</option>
<option value="edge">edge(通常物理机:建 Neko 并登记)</option>
</select>
</label>
<label className="block text-[11px] text-slate-400">
Hub 域名(edge 填 VPS,如 https://dylive.nomadro.com)
<input <input
value={peerBase} value={peerBase}
onChange={(e) => setPeerBase(e.target.value)} onChange={(e) => setPeerBase(e.target.value)}
@ -256,7 +302,16 @@ export default function OpsNekoPage() {
/> />
</label> </label>
<label className="block text-[11px] text-slate-400"> <label className="block text-[11px] text-slate-400">
本机 Neko 公网根(edge 建议 .cn,如 https://dy.nomadro.cn) Token
<input
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-sm text-white"
placeholder={peer.has_token ? `已保存 …${peer.token_suffix}(改则覆盖)` : "粘贴 VPS Token"}
/>
</label>
<label className="block text-[11px] text-slate-400 sm:col-span-2">
本机 Neko 公网根(可选,建议 https://dy.nomadro.cn)
<input <input
value={publicBase} value={publicBase}
onChange={(e) => setPublicBase(e.target.value)} onChange={(e) => setPublicBase(e.target.value)}
@ -264,45 +319,34 @@ export default function OpsNekoPage() {
placeholder="https://dy.nomadro.cn" placeholder="https://dy.nomadro.cn"
/> />
</label> </label>
<label className="block text-[11px] text-slate-400">
Token{peer.has_token ? `(已有 …${peer.token_suffix})` : ""}
<input
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-sm text-white"
placeholder="hub 生成后粘贴到 edge"
/>
</label>
</div> </div>
<div className="mt-3 flex flex-wrap gap-2"> <div className="mt-3 flex flex-wrap gap-2">
<button <button
type="button" type="button"
disabled={Boolean(busy)} disabled={Boolean(busy) || !peerBase.trim() || (!tokenInput.trim() && !peer.has_token)}
onClick={() => void savePeer()} onClick={() => void connectRealtime()}
className="rounded-xl bg-teal-500/20 px-3 py-2 text-xs text-teal-100 ring-1 ring-teal-400/30" className="inline-flex items-center gap-1 rounded-xl bg-teal-500/25 px-3 py-2 text-xs text-teal-50 ring-1 ring-teal-400/40 disabled:opacity-40"
> >
保存配对 {busy === "pair" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Link2 className="h-3.5 w-3.5" />}
{sync.connected ? "重新连接" : "连接并保持实时同步"}
</button> </button>
<button {(role === "edge" || peer.role === "edge") && (
type="button"
disabled={Boolean(busy)}
onClick={() => void savePeer({ rotate_token: true })}
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300"
>
生成新 Token(hub)
</button>
{role === "edge" ? (
<button <button
type="button" type="button"
disabled={Boolean(busy)} disabled={Boolean(busy)}
onClick={() => void pullCards()} onClick={() => void pullCards()}
className="inline-flex items-center gap-1 rounded-xl border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-xs text-violet-100" className="inline-flex items-center gap-1 rounded-xl border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-xs text-violet-100"
> >
<Link2 className="h-3.5 w-3.5" />
拉取 VPS 分配卡片 拉取 VPS 分配卡片
</button> </button>
) : null} )}
</div> </div>
{peer.role === "edge" && peer.peer_base_url ? (
<p className="mt-2 text-[11px] text-teal-200/80">
通道 → {peer.peer_base_url}
{typeof sync.ticks === "number" && sync.ticks > 0 ? ` · 心跳 #${sync.ticks}` : ""}
</p>
) : null}
</section> </section>
<section className="rounded-2xl border border-white/10 bg-white/[0.03] p-4"> <section className="rounded-2xl border border-white/10 bg-white/[0.03] p-4">

View File

@ -0,0 +1,159 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Check, Copy, KeyRound, Link2, Loader2, RefreshCw } from "lucide-react";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
type Creds = {
profile?: string;
domain?: string;
token?: string;
ready?: boolean;
role?: string;
};
/** VPS assign hero: copyable hub domain + token for physical Neko pairing. */
export function OpsNekoHubCredentialsCard() {
const toast = useToast();
const [creds, setCreds] = useState<Creds | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState<"domain" | "token" | "both" | "">("");
const load = useCallback(async () => {
try {
const d = (await fetchJson("/api/ops/neko/hub/credentials")) as Creds;
setCreds(d);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
async function rotate() {
setBusy(true);
try {
const d = (await fetchJson("/api/ops/neko/hub/credentials", {
method: "POST",
body: JSON.stringify({ rotate_token: true }),
})) as Creds;
setCreds(d);
toast.push("已生成新 Token(请同步到物理机)", "ok");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function copy(text: string, which: "domain" | "token" | "both") {
try {
await navigator.clipboard.writeText(text);
setCopied(which);
toast.push("已复制", "ok");
window.setTimeout(() => setCopied(""), 1500);
} catch {
toast.push("复制失败", "err");
}
}
// Only show on VPS profile
if (!loading && creds?.profile && creds.profile !== "vps") {
return null;
}
if (loading && !creds) {
return (
<div className="rounded-2xl border border-teal-500/20 bg-teal-500/[0.06] px-3.5 py-3 text-xs text-slate-400">
<Loader2 className="mr-1 inline h-3.5 w-3.5 animate-spin" />
加载物理机配对凭证…
</div>
);
}
const domain = String(creds?.domain || "").trim();
const token = String(creds?.token || "").trim();
return (
<div className="rounded-2xl border border-teal-500/25 bg-gradient-to-br from-teal-500/[0.12] to-black/30 px-3.5 py-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<div className="flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.16em] text-teal-200/80">
<KeyRound className="h-3.5 w-3.5" />
物理机 Neko 配对
</div>
<p className="mt-0.5 text-xs text-slate-400">
粘贴一次域名 + Token 并连接后,后台每 5 秒自动同步;启停实例立刻推送。VPS 分配页下拉会实时更新。
</p>
</div>
<div className="flex flex-wrap gap-1.5">
<button
type="button"
disabled={busy || !domain || !token}
onClick={() => void copy(`${domain}\n${token}`, "both")}
className="inline-flex items-center gap-1 rounded-lg border border-teal-400/30 bg-teal-500/15 px-2.5 py-1.5 text-[11px] text-teal-50 hover:bg-teal-500/25 disabled:opacity-40"
>
{copied === "both" ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
复制全部
</button>
<button
type="button"
disabled={busy}
onClick={() => void rotate()}
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
>
{busy ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
换 Token
</button>
</div>
</div>
<div className="mt-3 grid gap-2 sm:grid-cols-2">
<label className="block min-w-0">
<span className="text-[10px] text-slate-500">域名(Hub)</span>
<div className="mt-1 flex gap-1.5">
<input
readOnly
value={domain}
className="min-w-0 flex-1 truncate rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs text-slate-100"
/>
<button
type="button"
disabled={!domain}
onClick={() => void copy(domain, "domain")}
className="shrink-0 rounded-xl border border-white/10 bg-white/5 px-2.5 text-slate-300 hover:bg-white/10"
title="复制域名"
>
{copied === "domain" ? <Check className="h-3.5 w-3.5" /> : <Link2 className="h-3.5 w-3.5" />}
</button>
</div>
</label>
<label className="block min-w-0">
<span className="text-[10px] text-slate-500">Token</span>
<div className="mt-1 flex gap-1.5">
<input
readOnly
value={token}
className="min-w-0 flex-1 truncate rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs text-slate-100"
/>
<button
type="button"
disabled={!token}
onClick={() => void copy(token, "token")}
className="shrink-0 rounded-xl border border-white/10 bg-white/5 px-2.5 text-slate-300 hover:bg-white/10"
title="复制 Token"
>
{copied === "token" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</div>
</label>
</div>
</div>
);
}

View File

@ -13,6 +13,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { EnableSwitch } from "@/components/EnableSwitch"; import { EnableSwitch } from "@/components/EnableSwitch";
import { OpsNekoHubCredentialsCard } from "@/components/OpsNekoHubCredentialsCard";
export type RelayOpsHeroProps = { export type RelayOpsHeroProps = {
relayEnabled: boolean; relayEnabled: boolean;
@ -149,8 +150,8 @@ export function YtRelayOpsHero({
const pushing = Number(pushingCount || 0) > 0; const pushing = Number(pushingCount || 0) > 0;
return ( return (
<section className="animate-fade-up overflow-hidden rounded-[1.35rem] border border-white/10 bg-gradient-to-br from-[#121a28]/95 via-[#0c1420]/90 to-[#101828]/92 shadow-[0_24px_80px_-48px_rgba(0,0,0,0.9)]"> <section className="animate-fade-up rounded-[1.35rem] border border-white/10 bg-gradient-to-br from-[#121a28]/95 via-[#0c1420]/90 to-[#101828]/92 shadow-[0_24px_80px_-48px_rgba(0,0,0,0.9)]">
<div className="relative border-b border-white/[0.06] px-4 py-4 sm:px-5"> <div className="relative overflow-hidden rounded-t-[1.35rem] border-b border-white/[0.06] px-4 py-4 sm:px-5">
<div className="pointer-events-none absolute inset-0 bg-[radial-gradient(680px_180px_at_12%_-20%,rgba(255,45,85,0.16),transparent_55%),radial-gradient(520px_160px_at_88%_0%,rgba(45,212,191,0.12),transparent_50%)]" /> <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(680px_180px_at_12%_-20%,rgba(255,45,85,0.16),transparent_55%),radial-gradient(520px_160px_at_88%_0%,rgba(45,212,191,0.12),transparent_50%)]" />
<div className="relative flex flex-wrap items-start justify-between gap-3"> <div className="relative flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 max-w-2xl"> <div className="min-w-0 max-w-2xl">
@ -282,6 +283,8 @@ export function YtRelayOpsHero({
</div> </div>
)} )}
<OpsNekoHubCredentialsCard />
<div className="rounded-2xl border border-white/10 bg-black/30 px-3.5 py-3"> <div className="rounded-2xl border border-white/10 bg-black/30 px-3.5 py-3">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">

View File

@ -44,6 +44,16 @@ type GroupLike = {
neko_open_source?: "local" | "remote"; neko_open_source?: "local" | "remote";
}; };
export type OpsNekoCatalogItem = {
id?: string;
edge_id?: string;
edge_label?: string;
slot?: number;
name?: string;
open_url?: string;
running?: boolean | number;
};
type NekoState = { type NekoState = {
running?: boolean; running?: boolean;
ready?: boolean; ready?: boolean;
@ -62,8 +72,12 @@ type NekoState = {
live_duration_sec?: number | null; live_duration_sec?: number | null;
stream_title?: string; stream_title?: string;
url?: string; url?: string;
received_at?: number;
age_sec?: number | null; age_sec?: number | null;
detect_source?: string; detect_source?: string;
neko_ref?: string;
neko_kind?: string;
ui_source?: string;
minute_reports?: Array<{ minute_reports?: Array<{
ts?: number; ts?: number;
on_air?: boolean; on_air?: boolean;
@ -85,6 +99,9 @@ type Props = {
onStop: (id: string) => void; onStop: (id: string) => void;
onRestart: (id: string) => void; onRestart: (id: string) => void;
onNekoChange?: () => void; onNekoChange?: () => void;
/** Physical ops-neko instances reported to this VPS hub. */
remoteCatalog?: OpsNekoCatalogItem[];
hostProfile?: string;
}; };
function nekoStatusLabel(st?: NekoState | null, instanceId?: number, pollErr?: string): string { function nekoStatusLabel(st?: NekoState | null, instanceId?: number, pollErr?: string): string {
@ -106,6 +123,8 @@ export function YtRelayProStatusPanel({
onStop, onStop,
onRestart, onRestart,
onNekoChange, onNekoChange,
remoteCatalog = [],
hostProfile = "",
}: Props) { }: Props) {
const toast = useToast(); const toast = useToast();
const laneName = group.name || "未命名频道"; const laneName = group.name || "未命名频道";
@ -155,7 +174,16 @@ export function YtRelayProStatusPanel({
setNekoState(row.neko as NekoState); setNekoState(row.neko as NekoState);
setNekoPollErr(""); setNekoPollErr("");
} }
}, [row?.neko, row?.neko?.status, row?.neko?.ready, row?.neko?.running, row?.neko?.studio_url]); }, [
row?.neko,
row?.neko?.status,
row?.neko?.ready,
row?.neko?.running,
row?.neko?.studio_url,
row?.neko?.studio?.received_at,
row?.neko?.studio?.viewer_count,
row?.neko?.studio?.ui_source,
]);
const refreshNeko = useCallback(async () => { const refreshNeko = useCallback(async () => {
if (instanceId < 1) return; if (instanceId < 1) return;
@ -166,12 +194,18 @@ export function YtRelayProStatusPanel({
return; return;
} }
const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId); const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId);
if (inst) setNekoState(inst); if (inst) {
setNekoState((prev) => ({
...inst,
// Docker status has no Studio metrics — keep relay/remote telemetry.
studio: (row?.neko as NekoState | undefined)?.studio ?? prev?.studio ?? null,
}));
}
setNekoPollErr(""); setNekoPollErr("");
} catch (e) { } catch (e) {
setNekoPollErr((e as Error).message || "状态查询失败"); setNekoPollErr((e as Error).message || "状态查询失败");
} }
}, [instanceId]); }, [instanceId, row?.neko]);
// Fallback only when relay payload has no neko field yet (old API / cold start). // Fallback only when relay payload has no neko field yet (old API / cold start).
useEffect(() => { useEffect(() => {
@ -200,7 +234,7 @@ export function YtRelayProStatusPanel({
async function setPrefer(prefer: "local" | "remote") { async function setPrefer(prefer: "local" | "remote") {
if (prefer === "remote" && !remoteBound) { if (prefer === "remote" && !remoteBound) {
toast.push("尚未配对远程 Neko(请先到一级 Tab「Neko」完成绑定)", "err"); toast.push("请先在下方下拉框选择物理机 ops-neko 实例", "err");
return; return;
} }
setNekoBusy(true); setNekoBusy(true);
@ -226,6 +260,59 @@ export function YtRelayProStatusPanel({
} }
} }
async function bindRemote(catalogId: string) {
setNekoBusy(true);
try {
if (!catalogId) {
await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`, {
method: "POST",
body: JSON.stringify({ open_url: "", slot: 0, edge_label: "", prefer: "local" }),
});
setOpenPrefer("local");
onNekoChange?.();
toast.push("已清除远程绑定,切回本机原生", "ok");
return;
}
const item = remoteCatalog.find((x) => String(x.id || `${x.edge_id}:${x.slot}`) === catalogId);
if (!item?.open_url) throw new Error("未找到该物理机实例");
const r = (await fetchJson(
`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`,
{
method: "POST",
body: JSON.stringify({
open_url: item.open_url,
slot: Number(item.slot || 0),
edge_label: item.edge_label || item.name || "",
prefer: "remote",
}),
},
)) as { group?: GroupLike };
if (r.group?.neko_open_prefer === "remote" || r.group?.neko_open_prefer === "local") {
setOpenPrefer(r.group.neko_open_prefer);
} else {
setOpenPrefer("remote");
}
onNekoChange?.();
toast.push(`已绑定远程 #${item.slot},默认打开远控`, "ok");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setNekoBusy(false);
}
}
const selectedCatalogId = (() => {
if (!remoteStudioUrl) return "";
const hit = remoteCatalog.find(
(x) =>
String(x.open_url || "").replace(/\/$/, "") === remoteStudioUrl.replace(/\/$/, "") ||
(Number(x.slot) === Number(group.ops_neko_slot || 0) &&
String(x.edge_label || "") === String(group.ops_neko_edge_label || "")),
);
return hit ? String(hit.id || `${hit.edge_id}:${hit.slot}`) : "";
})();
const showRemotePicker = hostProfile === "vps" || remoteCatalog.length > 0 || remoteBound;
return ( return (
<div className="overflow-hidden rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.09] via-[#0a121c]/80 to-violet-500/[0.05] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ring-1 ring-white/[0.03] transition duration-300 hover:border-cyan-400/30"> <div className="overflow-hidden rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.09] via-[#0a121c]/80 to-violet-500/[0.05] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ring-1 ring-white/[0.03] transition duration-300 hover:border-cyan-400/30">
<div className="flex flex-wrap items-center justify-between gap-2"> <div className="flex flex-wrap items-center justify-between gap-2">
@ -396,7 +483,7 @@ export function YtRelayProStatusPanel({
? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${ ? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${
group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : "" group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : ""
}` }`
: "尚未配对 — 在物理机一级「Neko」创建实例并登记到本频道"} : "选择物理机 ops-neko,或先完成 Neko 页配对同步目录"}
</p> </p>
</div> </div>
<Link <Link
@ -422,7 +509,7 @@ export function YtRelayProStatusPanel({
<button <button
type="button" type="button"
disabled={nekoBusy || !remoteBound} disabled={nekoBusy || !remoteBound}
title={remoteBound ? "打开物理机配对实例" : "请先完成远程配对"} title={remoteBound ? "打开物理机配对实例" : "请先选择远程实例"}
onClick={() => void setPrefer("remote")} onClick={() => void setPrefer("remote")}
className={`rounded-full px-2.5 py-1 text-[10px] ${ className={`rounded-full px-2.5 py-1 text-[10px] ${
openPrefer === "remote" && remoteBound openPrefer === "remote" && remoteBound
@ -435,10 +522,35 @@ export function YtRelayProStatusPanel({
</button> </button>
</div> </div>
</div> </div>
{!remoteBound ? ( {showRemotePicker ? (
<p className="text-[10px] leading-relaxed text-slate-500"> <label className="block text-[10px] text-slate-400">
流程:物理机 Neko Tab → edge + Token → 新建实例 → 拉取 VPS 分配卡 → 绑定本频道并登记。登记后此处可切「远程」。 物理机实例
</p> <select
disabled={nekoBusy}
value={selectedCatalogId}
onChange={(e) => void bindRemote(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-2.5 py-2 text-[11px] text-slate-100 outline-none focus:ring-1 focus:ring-teal-400/40"
>
<option value="">— 不绑定(本机原生)—</option>
{remoteCatalog.map((it) => {
const id = String(it.id || `${it.edge_id}:${it.slot}`);
const run = Boolean(it.running);
return (
<option key={id} value={id}>
{(it.edge_label || "edge") +
` · #${it.slot}` +
(it.name ? ` ${it.name}` : "") +
(run ? " · 运行中" : " · 已停")}
</option>
);
})}
</select>
{remoteCatalog.length === 0 ? (
<span className="mt-1 block text-[10px] text-slate-500">
目录为空:请在物理机 Neko 页填入上方域名/Token 并点「配对」。
</span>
) : null}
</label>
) : null} ) : null}
</div> </div>
@ -511,7 +623,9 @@ export function YtRelayProStatusPanel({
</div> </div>
{(() => { {(() => {
const st = nekoState?.studio; const st = nekoState?.studio;
if (!st && !nekoState?.ready && !nekoState?.running) return null; const preferRemote = openPrefer === "remote" && remoteBound;
// Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred.
if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote) return null;
const reports = st?.minute_reports || []; const reports = st?.minute_reports || [];
const viewers = const viewers =
st?.viewer_count != null && Number.isFinite(Number(st.viewer_count)) st?.viewer_count != null && Number.isFinite(Number(st.viewer_count))
@ -522,9 +636,28 @@ export function YtRelayProStatusPanel({
? Number(st.total_views).toLocaleString() ? Number(st.total_views).toLocaleString()
: "—"; : "—";
const liveDur = String(st?.live_duration || "").trim() || "—"; const liveDur = String(st?.live_duration || "").trim() || "—";
const uiSrc = String(st?.ui_source || st?.neko_kind || "").toLowerCase();
const srcLabel =
uiSrc.includes("remote")
? "远程 Neko 数据"
: uiSrc.includes("local")
? "本机 Neko 数据"
: preferRemote
? "远程(等待同步)"
: "本机";
return ( return (
<div className="mt-3 space-y-2 rounded-lg border border-white/10 bg-black/25 px-2.5 py-2"> <div className="mt-3 space-y-2 rounded-lg border border-white/10 bg-black/25 px-2.5 py-2">
<div className="flex flex-wrap items-center gap-1.5 text-[10px]"> <div className="flex flex-wrap items-center gap-1.5 text-[10px]">
<span
className={`rounded-md px-1.5 py-0.5 ring-1 ${
uiSrc.includes("remote")
? "bg-teal-500/15 text-teal-100 ring-teal-400/30"
: "bg-violet-500/15 text-violet-100 ring-violet-400/25"
}`}
title={st?.neko_ref || ""}
>
{srcLabel}
</span>
{st?.live_status === "signed_out" ? ( {st?.live_status === "signed_out" ? (
<span className="rounded-md bg-amber-500/20 px-1.5 py-0.5 text-amber-100 ring-1 ring-amber-400/30"> <span className="rounded-md bg-amber-500/20 px-1.5 py-0.5 text-amber-100 ring-1 ring-amber-400/30">
Google 已登出 — 请打开工作室点选账号重新登录 Google 已登出 — 请打开工作室点选账号重新登录
@ -587,7 +720,11 @@ export function YtRelayProStatusPanel({
onAir={Boolean(st?.on_air)} onAir={Boolean(st?.on_air)}
/> />
) : ( ) : (
<p className="text-[10px] text-slate-600">暂无分钟报告(开播后约 1 分钟开始汇总)</p> <p className="text-[10px] text-slate-600">
{preferRemote
? "远程分钟报告同步中(物理机开播约 1 分钟后出现;每 5 秒经目录同步到 VPS)"
: "暂无分钟报告(开播后约 1 分钟开始汇总)"}
</p>
)} )}
</div> </div>
); );

View File

@ -63,7 +63,13 @@ export type RelayMonitorRow = {
live_duration_sec?: number | null; live_duration_sec?: number | null;
stream_title?: string; stream_title?: string;
}>; }>;
neko_ref?: string;
neko_kind?: "local" | "remote" | string;
ui_source?: string;
} | null; } | null;
open_prefer?: "local" | "remote" | string;
remote_bound?: boolean;
ops_neko_slot?: number;
} | null; } | null;
}; };

View File

@ -215,7 +215,35 @@ export async function getChannelBundle(raw, { includeLive = true, includeVideos
} }
if (includeLive) { if (includeLive) {
// 0) Direct /channel/UC…/live — most reliable when a stream is on-air
try {
const liveUrl = `https://www.youtube.com/channel/${channelId}/live`;
const endpoint = await withYtRetry((client) => client.resolveURL(liveUrl));
const videoId = endpoint?.payload?.videoId || "";
if (videoId) {
const confirmed = await confirmLive({
id: videoId,
title: "",
url: `https://www.youtube.com/watch?v=${videoId}`,
is_live: false,
is_upcoming: false,
is_live_content: true,
view_count: null,
thumbnail: "",
author: title,
});
if (confirmed) {
live = confirmed;
}
// Do NOT promote is_live_content alone — scheduled / LIVE_STREAM_OFFLINE
// rooms still have is_live_content=true while is_live=false.
}
} catch {
/* ignore — fall through to tabs */
}
// 1) Live tab // 1) Live tab
if (!live) {
try { try {
const feed = await channel.getLiveStreams(); const feed = await channel.getLiveStreams();
await scanFeedVideos(feed?.videos, 20); await scanFeedVideos(feed?.videos, 20);
@ -226,6 +254,7 @@ export async function getChannelBundle(raw, { includeLive = true, includeVideos
} catch { } catch {
/* some channels have no live tab */ /* some channels have no live tab */
} }
}
// 2) Home tab — active streams often pinned here // 2) Home tab — active streams often pinned here
if (!live) { if (!live) {