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>
218 lines
6.9 KiB
Python
218 lines
6.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Continue: CDP page-text scrape for on-air + deploy + probe (non-destructive)."""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
PASS = "4669805"
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
# Minimal CDP Runtime.evaluate via raw WebSocket (stdlib only) — runs INSIDE container.
|
|
CDP_SCRAPE_PY = r'''
|
|
import base64, hashlib, json, os, re, socket, struct, urllib.request
|
|
|
|
def ws_connect(url: str):
|
|
# ws://127.0.0.1:9222/devtools/page/ID
|
|
assert url.startswith("ws://")
|
|
hostport, path = url[5:].split("/", 1)
|
|
path = "/" + path
|
|
host, port_s = hostport.split(":")
|
|
port = int(port_s)
|
|
key = base64.b64encode(os.urandom(16)).decode()
|
|
s = 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()
|
|
s.sendall(req)
|
|
buf = b""
|
|
while b"\r\n\r\n" not in buf:
|
|
chunk = s.recv(4096)
|
|
if not chunk:
|
|
raise RuntimeError("ws handshake closed")
|
|
buf += chunk
|
|
return s
|
|
|
|
def ws_send(s, payload: dict):
|
|
data = json.dumps(payload).encode()
|
|
# client frames must be masked
|
|
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))
|
|
s.sendall(bytes(header) + masked)
|
|
|
|
def ws_recv(s):
|
|
def readexact(n):
|
|
out = b""
|
|
while len(out) < n:
|
|
chunk = s.recv(n - len(out))
|
|
if not chunk:
|
|
raise RuntimeError("ws closed")
|
|
out += chunk
|
|
return out
|
|
b1, b2 = readexact(2)
|
|
opcode = b1[0] & 0x0F
|
|
masked = (b2[0] & 0x80) != 0
|
|
ln = b2[0] & 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
|
|
return json.loads(data.decode())
|
|
|
|
tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode())
|
|
live = [t for t in tabs if "studio.youtube.com" in (t.get("url") or "") and "livestreaming" in (t.get("url") or "")]
|
|
if not live:
|
|
print(json.dumps({"ok": False, "error": "no_live_tab"}))
|
|
raise SystemExit(0)
|
|
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]}))
|
|
raise SystemExit(0)
|
|
s = ws_connect(ws_url)
|
|
ws_send(s, {"id": 1, "method": "Runtime.evaluate", "params": {
|
|
"expression": "(document.body && (document.body.innerText||'')).slice(0,8000)",
|
|
"returnByValue": True,
|
|
}})
|
|
deadline = __import__("time").time() + 5
|
|
text = ""
|
|
while __import__("time").time() < deadline:
|
|
msg = ws_recv(s)
|
|
if not msg:
|
|
break
|
|
if msg.get("id") == 1:
|
|
text = str(((msg.get("result") or {}).get("result") or {}).get("value") or "")
|
|
break
|
|
try:
|
|
s.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|concurrent viewers|watching now|stop streaming|直播中|正在直播|人正在观看", lower):
|
|
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"
|
|
viewers = None
|
|
m = re.search(r"([\d,.]+)\s*(?:watching|viewers|concurrent viewers|人正在观看|正在观看)", text, re.I)
|
|
if m:
|
|
try:
|
|
viewers = int(float(m.group(1).replace(",", "")))
|
|
except Exception:
|
|
viewers = None
|
|
on_air = status == "live" or health in {"excellent", "good"} or viewers is not None
|
|
print(json.dumps({
|
|
"ok": True,
|
|
"url": url[:200],
|
|
"live_status": status,
|
|
"health": health,
|
|
"viewer_count": viewers,
|
|
"on_air": on_air,
|
|
"text": text[:500],
|
|
}, ensure_ascii=False))
|
|
'''
|
|
|
|
|
|
def patch_youtube_neko() -> None:
|
|
"""Insert _cdp_studio_page_signals + wire into studio_on_air_lookup if missing."""
|
|
path = ROOT / "backend/app/youtube_neko.py"
|
|
text = path.read_text(encoding="utf-8")
|
|
if "_cdp_studio_page_signals" in text:
|
|
print("neko already has cdp scrape")
|
|
return
|
|
|
|
insert_after = "def _cdp_live_studio_urls(instance_id: int) -> list[str]:\n"
|
|
idx = text.find(insert_after)
|
|
if idx < 0:
|
|
raise SystemExit("anchor missing")
|
|
# find end of _cdp_live_studio_urls function (next def at same indent)
|
|
rest = text[idx:]
|
|
m_next = None
|
|
import re
|
|
|
|
for m in re.finditer(r"\n\ndef ", rest):
|
|
if m.start() > 20:
|
|
m_next = m
|
|
break
|
|
if not m_next:
|
|
raise SystemExit("next def missing")
|
|
end = idx + m_next.start() + 1
|
|
|
|
helper = '''
|
|
_cdp_signal_cache: dict[int, tuple[float, dict[str, Any]]] = {}
|
|
|
|
|
|
def _cdp_studio_page_signals(instance_id: int, *, max_age_sec: float = 45.0) -> dict[str, Any]:
|
|
"""Read-only CDP scrape of Studio Live page text (no tab close/reload)."""
|
|
import time as _time
|
|
|
|
nid = int(instance_id or 0)
|
|
now = _time.time()
|
|
cached = _cdp_signal_cache.get(nid)
|
|
if cached and (now - float(cached[0])) <= max_age_sec:
|
|
return dict(cached[1])
|
|
|
|
name = _container_name(nid)
|
|
py = r"""''' + CDP_SCRAPE_PY.replace('"""', "'''") + '''"""
|
|
code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=20)
|
|
row: dict[str, Any] = {"ok": False, "error": "cdp_scrape_failed"}
|
|
try:
|
|
line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}"
|
|
parsed = json.loads(line)
|
|
if isinstance(parsed, dict):
|
|
row = parsed
|
|
except Exception:
|
|
row = {"ok": False, "error": (out or "parse_fail")[:200]}
|
|
_cdp_signal_cache[nid] = (now, row)
|
|
return row
|
|
|
|
'''
|
|
# Simpler: write helper to a separate approach - manually StrReplace in file
|
|
|
|
raise SystemExit("use StrReplace instead")
|
|
|
|
|
|
def main() -> int:
|
|
# Upload probe + deploy files via existing pattern after we edit locally with StrReplace
|
|
print("use agent edits")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|