367 lines
14 KiB
Python
367 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Unified YouTube live status: InnerTube (youtube-svc) first, OAuth / DB fallback."""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
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],
|
||
)
|
||
|
||
|
||
async def build_live_map(*, force: bool = False) -> dict[str, Any]:
|
||
global _LAST_OAUTH_AT
|
||
now = time.time()
|
||
cached = _CACHE.get("payload")
|
||
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
|
||
return cached
|
||
|
||
async with _refresh_lock():
|
||
now = time.time()
|
||
cached = _CACHE.get("payload")
|
||
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
|
||
return cached
|
||
return await _build_live_map_unlocked(now=now)
|
||
|
||
|
||
async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||
global _LAST_OAUTH_AT
|
||
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
|
||
shorts = db.list_shorts_channels()
|
||
|
||
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)
|
||
|
||
live_count = sum(1 for k, v in entries.items() if k.startswith(("group:", "shorts:")) and v.get("is_live"))
|
||
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
|