# -*- 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() status = "" if re.search(r"stream ended|not live|offline|直播已结束|未在直播", lower): status = "ended" elif re.search( r"you.?re live|you are live|stream is healthy|excellent connection|" r"concurrent viewers|watching now|stop streaming|end stream|" r"直播中|正在直播|人正在观看|结束直播", lower, ): status = "live" elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower): # e.g. "LIVE 1:19:36" on Studio control room status = "live" elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower): status = "waiting" 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 on_air = status == "live" or health in {"excellent", "good"} or ( viewers is not None and status != "ended" and status != "waiting" ) or bool(live_duration and status != "ended" and status != "waiting") 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, "text": text[:500], }, ensure_ascii=False, ) ) if __name__ == "__main__": main()