douyinWEB/backend/neko/cdp_studio_scrape.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

306 lines
9.6 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 -*-
"""Read-only CDP scrape of YouTube Studio livestreaming page (inside Neko)."""
from __future__ import annotations
import base64
import json
import os
import re
import socket
import struct
import time
import urllib.request
def ws_connect(url: str) -> socket.socket:
assert url.startswith("ws://"), url
hostport, path = url[5:].split("/", 1)
path = "/" + path
host, port_s = hostport.split(":")
port = int(port_s)
key = base64.b64encode(os.urandom(16)).decode()
sock = socket.create_connection((host, port), timeout=6)
req = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {hostport}\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n"
).encode()
sock.sendall(req)
buf = b""
while b"\r\n\r\n" not in buf:
chunk = sock.recv(4096)
if not chunk:
raise RuntimeError("ws handshake closed")
buf += chunk
return sock
def ws_send(sock: socket.socket, payload: dict) -> None:
data = json.dumps(payload).encode()
mask = os.urandom(4)
header = bytearray([0x81])
n = len(data)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header.extend(struct.pack("!H", n))
else:
header.append(0x80 | 127)
header.extend(struct.pack("!Q", n))
header.extend(mask)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
sock.sendall(bytes(header) + masked)
def ws_recv(sock: socket.socket):
def readexact(n: int) -> bytes:
out = b""
while len(out) < n:
chunk = sock.recv(n - len(out))
if not chunk:
raise RuntimeError("ws closed")
out += chunk
return out
hdr = readexact(2)
b1, b2 = hdr[0], hdr[1]
opcode = b1 & 0x0F
masked = (b2 & 0x80) != 0
ln = b2 & 0x7F
if ln == 126:
ln = struct.unpack("!H", readexact(2))[0]
elif ln == 127:
ln = struct.unpack("!Q", readexact(8))[0]
mask = readexact(4) if masked else b""
data = readexact(ln)
if masked:
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
if opcode == 0x8:
return None
if opcode != 0x1:
# ignore non-text frames
return {"id": None}
return json.loads(data.decode())
def main() -> None:
tabs = json.loads(
urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode()
)
live = []
chooser = None
for t in tabs:
u = t.get("url") or ""
try:
from urllib.parse import urlparse
p = urlparse(u)
host = (p.netloc or "").lower()
path = (p.path or "").lower()
except Exception:
continue
if host.endswith("studio.youtube.com") and "livestreaming" in path:
live.append(t)
if "accounts.google.com" in host and chooser is None:
chooser = t
if not live:
if chooser:
print(
json.dumps(
{
"ok": True,
"url": (chooser.get("url") or "")[:200],
"live_status": "signed_out",
"health": "",
"viewer_count": None,
"on_air": False,
"text": "Google accountchooser / signed out",
},
ensure_ascii=False,
)
)
return
print(json.dumps({"ok": False, "error": "no_live_tab"}))
return
tab = live[0]
ws_url = tab.get("webSocketDebuggerUrl") or ""
url = tab.get("url") or ""
if not ws_url:
print(json.dumps({"ok": False, "error": "no_ws", "url": url[:120]}))
return
sock = ws_connect(ws_url)
ws_send(
sock,
{
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": "(document.body && (document.body.innerText||'')).slice(0,12000)",
"returnByValue": True,
},
},
)
deadline = time.time() + 5
text = ""
while time.time() < deadline:
msg = ws_recv(sock)
if not msg:
break
if msg.get("id") == 1:
text = str(((msg.get("result") or {}).get("result") or {}).get("value") or "")
break
try:
sock.close()
except Exception:
pass
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 = ""
if re.search(r"stream ended|直播已结束", lower) and not session_live:
status = "ended"
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"concurrent viewers|watching now|直播中|正在直播|人正在观看",
lower,
):
status = "live"
elif nodata or re.search(
r"connect your encoder|stream offline|not streaming|waiting for you to start|"
r"start sending us your video|待开播|等待你开始",
lower,
):
status = "waiting"
elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower):
status = "waiting"
elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower):
status = "live"
health = ""
if re.search(r"excellent connection|stream is healthy|状况良好|连接状况极佳", lower):
health = "excellent"
elif re.search(r"good connection|healthy|良好", lower):
health = "good"
elif re.search(r"unstable|poor|buffer|warning|不稳定|卡顿", lower):
health = "warning"
# Concurrent viewers (not cumulative Views)
viewers = None
m = re.search(
r"([\d,.]+)\s*(?:watching|concurrent viewers|人正在观看|正在观看)",
text,
re.I,
)
if not m:
m = re.search(
r"(?:concurrent viewers|watching now|同时观看人数)\s*[::]?\s*([\d,.]+)",
text,
re.I,
)
if m:
try:
viewers = int(float(m.group(1).replace(",", "")))
except Exception:
viewers = None
# Analytics cumulative Views (Studio Analytics tab)
total_views = None
m = re.search(r"(?:^|\n)\s*Views\s*\n\s*([\d,.]+)", text, re.I)
if not m:
m = re.search(r"\bViews\b(?!\s*per)(?![^\n]{0,12}concurrent)\s*[::]?\s*([\d,.]+)", text, re.I)
if not m:
m = re.search(r"(?:总观看|观看次数|观看量)\s*[::]?\s*([\d,.]+)", text)
if m:
try:
total_views = int(float(m.group(1).replace(",", "")))
except Exception:
total_views = None
# LIVE pill duration e.g. "LIVE 37:06" / "LIVE 1:19:36"
live_duration = ""
live_duration_sec = None
m = re.search(r"\bLIVE\b\s*(\d{1,2}:\d{2}(?::\d{2})?)", text, re.I)
if not m:
m = re.search(r"(?:直播时长|已直播)\s*[::]?\s*(\d{1,2}:\d{2}(?::\d{2})?)", text)
if m:
live_duration = m.group(1)
try:
parts = [int(x) for x in live_duration.split(":")]
if len(parts) == 3:
live_duration_sec = parts[0] * 3600 + parts[1] * 60 + parts[2]
elif len(parts) == 2:
live_duration_sec = parts[0] * 60 + parts[1]
except Exception:
live_duration_sec = None
if live_duration and not session_live:
session_live = True
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(
json.dumps(
{
"ok": True,
"url": url[:200],
"live_status": status,
"health": health,
"viewer_count": viewers,
"total_views": total_views,
"live_duration": live_duration,
"live_duration_sec": live_duration_sec,
"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],
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()