Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP. Co-authored-by: Cursor <cursoragent@cursor.com>
571 lines
22 KiB
Python
571 lines
22 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Unified YouTube live status: InnerTube (youtube-svc) first, OAuth / DB fallback."""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import os
|
||
import time
|
||
from typing import Any, Optional
|
||
|
||
from . import db, youtube_client
|
||
from .models import normalize_youtube_channel_url
|
||
from .youtube_client import YouTubeSvcError
|
||
|
||
_CACHE: dict[str, Any] = {"at": 0.0, "payload": None}
|
||
_CACHE_TTL_SEC = 15.0
|
||
_BATCH_SIZE = 20
|
||
_REFRESH_LOCK: Optional[asyncio.Lock] = None
|
||
_LAST_OAUTH_AT = 0.0
|
||
_OAUTH_MIN_INTERVAL_SEC = 45.0
|
||
|
||
|
||
def _refresh_lock() -> asyncio.Lock:
|
||
global _REFRESH_LOCK
|
||
if _REFRESH_LOCK is None:
|
||
_REFRESH_LOCK = asyncio.Lock()
|
||
return _REFRESH_LOCK
|
||
|
||
|
||
def _channel_url_for_group(group: dict[str, Any]) -> str:
|
||
cid = str(group.get("channel_id") or "").strip()
|
||
if cid:
|
||
return f"https://www.youtube.com/channel/{cid}"
|
||
url = str(group.get("channel_url") or "").strip()
|
||
if url:
|
||
return normalize_youtube_channel_url(url)
|
||
handle = str(group.get("handle") or "").strip()
|
||
if handle:
|
||
h = handle if handle.startswith("@") else f"@{handle}"
|
||
return f"https://www.youtube.com/{h}"
|
||
key = str(group.get("channel_key") or "").strip()
|
||
if key.startswith("UC"):
|
||
return f"https://www.youtube.com/channel/{key}"
|
||
if key.startswith("@"):
|
||
return f"https://www.youtube.com/{key}"
|
||
return url or key
|
||
|
||
|
||
def _channel_url_for_shorts(ch: dict[str, Any]) -> str:
|
||
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||
if cid:
|
||
return f"https://www.youtube.com/channel/{cid}"
|
||
return ""
|
||
|
||
|
||
def _live_entry(
|
||
*,
|
||
is_live: bool,
|
||
source: str,
|
||
live_url: str = "",
|
||
title: str = "",
|
||
channel_id: str = "",
|
||
error: str = "",
|
||
) -> dict[str, Any]:
|
||
out: dict[str, Any] = {"is_live": bool(is_live), "source": source}
|
||
if is_live:
|
||
if live_url:
|
||
out["live_url"] = live_url
|
||
if title:
|
||
out["title"] = title
|
||
if channel_id:
|
||
out["channel_id"] = channel_id
|
||
if error:
|
||
out["error"] = error
|
||
return out
|
||
|
||
|
||
def _parse_batch_result(row: dict[str, Any]) -> dict[str, Any]:
|
||
if not row.get("ok"):
|
||
return _live_entry(is_live=False, source="youtubei", error=str(row.get("error") or "probe failed"))
|
||
live = row.get("live") if isinstance(row.get("live"), dict) else {}
|
||
live_url = str(live.get("url") or live.get("watch_url") or "").strip()
|
||
if not live_url:
|
||
vid = str(live.get("video_id") or live.get("id") or "").strip()
|
||
if vid:
|
||
live_url = f"https://www.youtube.com/watch?v={vid}"
|
||
title = str(live.get("title") or row.get("title") or "").strip()
|
||
cid = str(row.get("channel_id") or "").strip()
|
||
return _live_entry(
|
||
is_live=bool(row.get("is_live")),
|
||
source="youtubei",
|
||
live_url=live_url,
|
||
title=title,
|
||
channel_id=cid,
|
||
)
|
||
|
||
|
||
async def _oauth_live_for_shorts(channel_pk: str, youtube_channel_id: str) -> Optional[dict[str, Any]]:
|
||
"""Detect whether this OAuth-owned channel is currently live.
|
||
|
||
Prefer liveBroadcasts.list (mine + active) — 1 quota unit, no Search Queries pool.
|
||
Fall back to search.list only if broadcasts API is unavailable.
|
||
"""
|
||
try:
|
||
from . import youtube_manage
|
||
|
||
token, _ch = await youtube_manage._access_for_channel(channel_pk)
|
||
|
||
# 1) Own-channel liveBroadcasts (correct for Shorts upload channels)
|
||
# Note: broadcastStatus + mine can be rejected as incompatible; list mine then filter.
|
||
try:
|
||
data = await youtube_manage._get(
|
||
"liveBroadcasts",
|
||
token=token,
|
||
params={
|
||
"part": "id,snippet,status",
|
||
"mine": "true",
|
||
"maxResults": 25,
|
||
},
|
||
)
|
||
items = data.get("items") or []
|
||
live_items = [
|
||
it
|
||
for it in items
|
||
if str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower() == "live"
|
||
]
|
||
if live_items:
|
||
item = live_items[0]
|
||
sn = item.get("snippet") or {}
|
||
vid = str(item.get("id") or "").strip()
|
||
title = str(sn.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-broadcast",
|
||
live_url=live_url,
|
||
title=title,
|
||
channel_id=youtube_channel_id,
|
||
)
|
||
return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id)
|
||
except Exception as broadcast_exc:
|
||
broadcast_err = str(broadcast_exc)
|
||
|
||
# 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(
|
||
is_live=False,
|
||
source="oauth",
|
||
channel_id=youtube_channel_id,
|
||
error=broadcast_err[:120] if broadcast_err else "",
|
||
)
|
||
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:
|
||
return _live_entry(
|
||
is_live=False,
|
||
source="oauth",
|
||
channel_id=youtube_channel_id,
|
||
error=str(exc)[:200],
|
||
)
|
||
|
||
|
||
_REFRESH_TASK: Optional[asyncio.Task] = None
|
||
|
||
|
||
def _empty_live_map(*, now: float, refreshing: bool = False) -> dict[str, Any]:
|
||
return {
|
||
"ok": True,
|
||
"checked_at": int(now),
|
||
"live_count": 0,
|
||
"source": "none",
|
||
"entries": {},
|
||
"groups_total": 0,
|
||
"shorts_total": 0,
|
||
"poll_sec": 20,
|
||
"cache_ttl_sec": _CACHE_TTL_SEC,
|
||
"refreshing": refreshing,
|
||
}
|
||
|
||
|
||
def _schedule_live_map_refresh() -> None:
|
||
"""Kick a background rebuild; never block HTTP handlers on youtube-svc."""
|
||
global _REFRESH_TASK
|
||
if str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"}:
|
||
# Desktop UI must stay clickable; live-map refresh is opt-in via force loop elsewhere
|
||
return
|
||
lock = _refresh_lock()
|
||
if lock.locked():
|
||
return
|
||
task = _REFRESH_TASK
|
||
if task is not None and not task.done():
|
||
return
|
||
|
||
async def _run() -> None:
|
||
try:
|
||
async with _refresh_lock():
|
||
await _build_live_map_unlocked(now=time.time())
|
||
except Exception:
|
||
pass
|
||
|
||
_REFRESH_TASK = asyncio.create_task(_run())
|
||
|
||
|
||
async def build_live_map(*, force: bool = False) -> dict[str, Any]:
|
||
now = time.time()
|
||
cached = _CACHE.get("payload")
|
||
fresh = bool(cached) and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC
|
||
|
||
# force=True must actually rebuild (homepage/ops probes rely on this).
|
||
if force:
|
||
async with _refresh_lock():
|
||
return await _build_live_map_unlocked(now=time.time())
|
||
|
||
if cached and fresh:
|
||
return cached
|
||
if cached:
|
||
_schedule_live_map_refresh()
|
||
return cached
|
||
|
||
# No cache yet: return empty immediately and refresh in background
|
||
_schedule_live_map_refresh()
|
||
return _empty_live_map(now=now, refreshing=True)
|
||
|
||
|
||
async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||
global _LAST_OAUTH_AT
|
||
|
||
def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
|
||
shorts = db.list_shorts_channels()
|
||
return groups, shorts
|
||
|
||
groups, shorts = await asyncio.to_thread(_load_db_targets)
|
||
|
||
targets: list[dict[str, Any]] = []
|
||
url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}
|
||
cid_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}
|
||
|
||
for g in groups:
|
||
url = _channel_url_for_group(g)
|
||
ref = f"group:{g['id']}"
|
||
meta = {"kind": "group", "group": g, "url": url}
|
||
targets.append({"ref": ref, "url": url, **meta})
|
||
if url:
|
||
url_to_refs.setdefault(url, []).append((ref, meta))
|
||
cid = str(g.get("channel_id") or "").strip()
|
||
if cid:
|
||
cid_to_refs.setdefault(cid, []).append((ref, meta))
|
||
|
||
for ch in shorts:
|
||
url = _channel_url_for_shorts(ch)
|
||
ref = f"shorts:{ch['id']}"
|
||
meta = {"kind": "shorts", "channel_pk": ch["id"], "youtube_channel_id": ch.get("youtube_channel_id"), "url": url}
|
||
targets.append({"ref": ref, "url": url, **meta})
|
||
if url:
|
||
url_to_refs.setdefault(url, []).append((ref, meta))
|
||
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||
if cid:
|
||
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})
|
||
|
||
entries: dict[str, Any] = {}
|
||
unique_urls: list[str] = []
|
||
seen_urls: set[str] = set()
|
||
for t in targets:
|
||
url = str(t.get("url") or "").strip()
|
||
if not url or url in seen_urls:
|
||
continue
|
||
seen_urls.add(url)
|
||
unique_urls.append(url)
|
||
|
||
probe_by_url: dict[str, dict[str, Any]] = {}
|
||
svc_error = ""
|
||
if unique_urls:
|
||
try:
|
||
for i in range(0, len(unique_urls), _BATCH_SIZE):
|
||
chunk = unique_urls[i : i + _BATCH_SIZE]
|
||
data = await youtube_client.batch_live(chunk)
|
||
for row in data.get("results") or []:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
key = str(row.get("input") or "").strip()
|
||
if key:
|
||
probe_by_url[key] = _parse_batch_result(row)
|
||
cid = str(row.get("channel_id") or "").strip()
|
||
if cid:
|
||
probe_by_url[f"cid:{cid}"] = _parse_batch_result(row)
|
||
except YouTubeSvcError as exc:
|
||
svc_error = str(exc)
|
||
|
||
for t in targets:
|
||
ref = str(t["ref"])
|
||
url = str(t.get("url") or "").strip()
|
||
entry = probe_by_url.get(url) if url else None
|
||
cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip()
|
||
|
||
if entry is None and cid:
|
||
entry = probe_by_url.get(f"cid:{cid}")
|
||
|
||
if entry is None and svc_error:
|
||
entry = _live_entry(is_live=False, source="youtubei", error=svc_error)
|
||
|
||
if entry is None:
|
||
entry = _live_entry(is_live=False, source="unknown")
|
||
|
||
if t.get("kind") == "group" and not entry.get("is_live") and not svc_error:
|
||
g = t.get("group") or {}
|
||
if str(g.get("last_status") or "") == "live":
|
||
entry = _live_entry(
|
||
is_live=True,
|
||
source="monitor",
|
||
live_url=str(g.get("last_live_url") or ""),
|
||
title=str(g.get("last_title") or ""),
|
||
channel_id=str(g.get("channel_id") or ""),
|
||
)
|
||
|
||
entries[ref] = dict(entry)
|
||
if cid and entry.get("is_live"):
|
||
entries[f"channel:{cid}"] = dict(entry)
|
||
|
||
# OAuth 兜底限频,避免多标签 force/后台轮询打爆配额
|
||
run_oauth = (now - float(_LAST_OAUTH_AT or 0)) >= _OAUTH_MIN_INTERVAL_SEC
|
||
oauth_tasks: list[tuple[str, str, str]] = []
|
||
if run_oauth:
|
||
for ch in shorts:
|
||
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||
pk = str(ch.get("id") or "")
|
||
if not cid or not pk:
|
||
continue
|
||
if not str(ch.get("refresh_token") or "").strip():
|
||
continue
|
||
ref = f"shorts:{pk}"
|
||
if entries.get(ref, {}).get("is_live"):
|
||
continue
|
||
oauth_tasks.append((ref, pk, cid))
|
||
|
||
if oauth_tasks:
|
||
_LAST_OAUTH_AT = now
|
||
oauth_results = await asyncio.gather(
|
||
*[_oauth_live_for_shorts(pk, cid) for _ref, pk, cid in oauth_tasks],
|
||
return_exceptions=True,
|
||
)
|
||
for (ref, _pk, cid), result in zip(oauth_tasks, oauth_results):
|
||
if isinstance(result, Exception):
|
||
continue
|
||
if isinstance(result, dict) and result.get("is_live"):
|
||
entries[ref] = result
|
||
entries[f"channel:{cid}"] = result
|
||
elif _CACHE.get("payload") and isinstance(_CACHE.get("payload"), dict):
|
||
# 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线
|
||
prev = (_CACHE.get("payload") or {}).get("entries") or {}
|
||
for ref, old in prev.items():
|
||
if not str(ref).startswith("shorts:"):
|
||
continue
|
||
if not isinstance(old, dict) or not old.get("is_live"):
|
||
continue
|
||
if str(old.get("source") or "").startswith("oauth"):
|
||
cur = entries.get(ref) or {}
|
||
if not cur.get("is_live"):
|
||
entries[ref] = dict(old)
|
||
cid = str(old.get("channel_id") or "").strip()
|
||
if cid:
|
||
entries[f"channel:{cid}"] = dict(old)
|
||
|
||
# Mirror live Shorts → Live 分配;FFmpeg 转推 / Studio 遥测补洞
|
||
try:
|
||
from . import yt_assign_db
|
||
from . import youtube_neko
|
||
from .youtube_relay_pipeline import youtube_relay_pipeline
|
||
|
||
assign_groups = await asyncio.to_thread(
|
||
lambda: yt_assign_db.list_groups(include_urls=False)
|
||
)
|
||
relay_payload = await asyncio.to_thread(youtube_relay_pipeline.status)
|
||
relay_rows = {
|
||
str(r.get("group_id") or ""): r for r in (relay_payload.get("groups") or [])
|
||
}
|
||
pk_to_gid: dict[str, str] = {}
|
||
gid_to_name: dict[str, str] = {}
|
||
for g in assign_groups:
|
||
pk = str(g.get("channel_pk") or "").strip()
|
||
gid = str(g.get("id") or "").strip()
|
||
if pk and gid:
|
||
pk_to_gid[pk] = gid
|
||
gid_to_name[gid] = str(g.get("name") or "").strip()
|
||
|
||
for ref, ent in list(entries.items()):
|
||
if not str(ref).startswith("shorts:"):
|
||
continue
|
||
if not isinstance(ent, dict) or not ent.get("is_live"):
|
||
continue
|
||
pk = str(ref).split(":", 1)[1]
|
||
gid = pk_to_gid.get(pk)
|
||
if not gid:
|
||
continue
|
||
ent["assign_group_id"] = gid
|
||
assign_ent = dict(ent)
|
||
assign_ent["source"] = "assign"
|
||
assign_ent["assign_group_id"] = gid
|
||
assign_ent["channel_pk"] = pk
|
||
if gid_to_name.get(gid):
|
||
assign_ent["title"] = gid_to_name[gid]
|
||
entries[f"assign:{gid}"] = assign_ent
|
||
|
||
for g in assign_groups:
|
||
gid = str(g.get("id") or "").strip()
|
||
if not gid:
|
||
continue
|
||
pk = str(g.get("channel_pk") or "").strip()
|
||
row = relay_rows.get(gid) or {}
|
||
nid = 0
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
|
||
studio_snap: dict[str, Any] = {}
|
||
if nid > 0:
|
||
try:
|
||
studio_snap = await asyncio.to_thread(
|
||
lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0)
|
||
)
|
||
except Exception:
|
||
studio_snap = {}
|
||
|
||
# Fallback: match telemetry by group's saved studio URL (no CDP / no instance tag).
|
||
if not studio_snap.get("on_air"):
|
||
studio_url = str(g.get("neko_studio_url") or "")
|
||
vid = ""
|
||
if "/video/" in studio_url:
|
||
try:
|
||
vid = studio_url.split("/video/", 1)[1].split("/", 1)[0]
|
||
except Exception:
|
||
vid = ""
|
||
if vid:
|
||
for ev in youtube_neko.latest_studio_telemetry(limit=40):
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
url = str(payload.get("url") or "")
|
||
if vid not in url:
|
||
continue
|
||
if str(payload.get("live_status") or "").lower() in {"live", "streaming"} or str(
|
||
payload.get("health") or ""
|
||
).lower() in {"excellent", "good"}:
|
||
studio_snap = {
|
||
"on_air": True,
|
||
"live_page_open": True,
|
||
"live_status": str(payload.get("live_status") or "live"),
|
||
"health": str(payload.get("health") or ""),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"url": url[:200],
|
||
"received_at": float(ev.get("received_at") or 0),
|
||
"detect_source": "telemetry_url_match",
|
||
"neko_instance_id": nid,
|
||
}
|
||
break
|
||
|
||
mark_live = bool(row.get("is_pushing") or studio_snap.get("on_air"))
|
||
if not mark_live:
|
||
# Keep studio snapshot on assign entry for UI even when offline.
|
||
if studio_snap.get("live_page_open") and f"assign:{gid}" in entries:
|
||
entries[f"assign:{gid}"]["studio"] = studio_snap
|
||
continue
|
||
|
||
prev = entries.get(f"assign:{gid}") or {}
|
||
source = "relay" if row.get("is_pushing") else "studio_telemetry"
|
||
if prev.get("is_live") and prev.get("source") not in {"relay", "studio_telemetry"}:
|
||
source = str(prev.get("source") or source)
|
||
entries[f"assign:{gid}"] = {
|
||
**prev,
|
||
"is_live": True,
|
||
"source": source,
|
||
"assign_group_id": gid,
|
||
"channel_pk": pk,
|
||
"title": gid_to_name.get(gid) or prev.get("title") or str(g.get("name") or ""),
|
||
"live_url": str(studio_snap.get("url") or prev.get("live_url") or ""),
|
||
"studio": studio_snap or prev.get("studio") or {},
|
||
}
|
||
if pk:
|
||
shorts_ref = f"shorts:{pk}"
|
||
shorts_prev = entries.get(shorts_ref) or {}
|
||
if not shorts_prev.get("is_live"):
|
||
entries[shorts_ref] = {
|
||
**shorts_prev,
|
||
"is_live": True,
|
||
"source": source,
|
||
"assign_group_id": gid,
|
||
"title": shorts_prev.get("title") or gid_to_name.get(gid) or "",
|
||
"live_url": str(studio_snap.get("url") or shorts_prev.get("live_url") or ""),
|
||
}
|
||
else:
|
||
entries[shorts_ref]["assign_group_id"] = gid
|
||
cid = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip()
|
||
if cid:
|
||
entries[f"channel:{cid}"] = dict(entries[shorts_ref])
|
||
except Exception as exc:
|
||
import logging
|
||
|
||
logging.getLogger(__name__).warning("live-map assign/studio mirror failed: %s", exc)
|
||
|
||
live_count = 0
|
||
seen_assign: set[str] = set()
|
||
for k, v in entries.items():
|
||
if not k.startswith("assign:") or not v.get("is_live"):
|
||
continue
|
||
live_count += 1
|
||
seen_assign.add(k.split(":", 1)[1])
|
||
for k, v in entries.items():
|
||
if not v.get("is_live"):
|
||
continue
|
||
if k.startswith("shorts:"):
|
||
gid = str(v.get("assign_group_id") or "")
|
||
if gid and gid in seen_assign:
|
||
continue
|
||
live_count += 1
|
||
elif k.startswith("group:"):
|
||
live_count += 1
|
||
sources = {str(v.get("source") or "") for v in entries.values() if v.get("is_live")}
|
||
primary_source = "youtubei" if "youtubei" in sources else (next(iter(sources)) if sources else "none")
|
||
|
||
payload = {
|
||
"ok": True,
|
||
"checked_at": int(now),
|
||
"live_count": live_count,
|
||
"source": primary_source,
|
||
"entries": entries,
|
||
"groups_total": len(groups),
|
||
"shorts_total": len(shorts),
|
||
"poll_sec": 20,
|
||
"cache_ttl_sec": _CACHE_TTL_SEC,
|
||
}
|
||
if svc_error:
|
||
payload["svc_error"] = svc_error
|
||
|
||
# Shorts 上传频道开播/停播 → sessions,供 /shorts 数据分析
|
||
try:
|
||
payload["shorts_live_sync"] = db.sync_shorts_channel_lives_from_map(entries)
|
||
except Exception as exc:
|
||
payload["shorts_live_sync"] = {"error": str(exc)[:160]}
|
||
|
||
_CACHE["at"] = now
|
||
_CACHE["payload"] = payload
|
||
return payload
|