douyinWEB/backend/app/youtube_live.py
eric dea036c50d 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>
2026-09-05 22:57:52 -05:00

995 lines
40 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Unified YouTube live status: InnerTube (youtube-svc) first, OAuth / DB fallback."""
from __future__ import annotations
import asyncio
import json
import os
import re
import time
import urllib.request
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 _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:
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,
)
# Explicit offline from liveBroadcasts — do NOT burn Search Queries quota.
return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id)
except Exception as broadcast_exc:
# Broadcasts unavailable → leave detection to youtubei (public). Never search.list.
return _live_entry(
is_live=False,
source="oauth-broadcast",
channel_id=youtube_channel_id,
error=f"broadcasts_unavailable:{str(broadcast_exc)[:140]}",
)
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]], list[dict[str, Any]]]:
from . import yt_assign_db
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
shorts = db.list_shorts_channels()
# Live 分配授权频道卡 — 与 Shorts/旧分组一样走公开 youtubei 探测(双机应一致)
assign = yt_assign_db.list_groups(include_urls=False)
return groups, shorts, assign
groups, shorts, assign_groups_early = 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})
# 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] = {}
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 ""),
)
# 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)
if cid and entry.get("is_live"):
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
# 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
oauth_tasks: list[tuple[str, str, str]] = []
if run_oauth:
seen_oauth_pk: set[str] = set()
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))
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:
_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,
)
pk_to_assign: dict[str, list[dict[str, Any]]] = {}
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
src = str(result.get("source") or "")
if result.get("is_live"):
entries[ref] = result
if cid:
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):
# 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线
prev = (_CACHE.get("payload") or {}).get("entries") or {}
for ref, old in prev.items():
if not str(ref).startswith(("shorts:", "assign:")):
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 {}
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:
nid = int(g.get("neko_instance_id") or 0)
except (TypeError, ValueError):
nid = 0
if nid > 0:
try:
local_snap = await asyncio.to_thread(
lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0)
)
except Exception:
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 (receiving signals only).
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 "")
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
signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {}
st = str(payload.get("live_status") or "").lower()
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 = {
"on_air": True,
"encoder_receiving": True,
"live_page_open": True,
"live_status": st or "live",
"health": health,
"viewer_count": payload.get("viewer_count"),
"url": url[:200],
"received_at": float(ev.get("received_at") or 0),
"detect_source": "telemetry_url_match",
}
break
# 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:
base = entries.get(f"assign:{gid}") or {
"is_live": False,
"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
prev = entries.get(f"assign:{gid}") or prev_live or {}
if prev.get("is_live") and prev.get("source") not in {
"relay",
"studio_telemetry",
"studio_receiving",
}:
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
cid2 = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip()
if cid2:
entries[f"channel:{cid2}"] = 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