douyinWEB/backend/neko/cdp_end_stream.py
2026-09-13 22:10:49 -05:00

342 lines
12 KiB
Python

# -*- coding: utf-8 -*-
"""CDP: click YouTube Studio End Stream (+ confirm dialog End) inside Neko Chrome.
Handles the modal:
End Stream
Your stream will stop immediately...
[Not yet] [End]
Run via: docker exec -i <neko> python3 - < this file
Prints one JSON line to stdout.
"""
from __future__ import annotations
import base64
import json
import os
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=8)
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:
return {"id": None}
return json.loads(data.decode())
def eval_js(sock: socket.socket, expression: str, *, req_id: int, timeout: float = 6.0):
ws_send(
sock,
{
"id": req_id,
"method": "Runtime.evaluate",
"params": {
"expression": expression,
"returnByValue": True,
"awaitPromise": True,
},
},
)
deadline = time.time() + timeout
while time.time() < deadline:
msg = ws_recv(sock)
if not msg:
break
if msg.get("id") == req_id:
return ((msg.get("result") or {}).get("result") or {}).get("value")
return None
CLICK_JS = r"""
(() => {
const END_RE = /^(end stream|stop streaming|结束直播|停止直播)$/i;
const CANCEL_RE = /not yet|not now|cancel|keep|继续|取消|还没有/i;
function visible(el) {
if (!el || !el.getBoundingClientRect) return false;
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return false;
const st = window.getComputedStyle ? getComputedStyle(el) : null;
if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false;
return true;
}
function* deepNodes(root) {
const stack = [root];
while (stack.length) {
const n = stack.pop();
if (!n) continue;
yield n;
if (n.shadowRoot) stack.push(n.shadowRoot);
if (n.children) {
for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]);
}
}
}
function labelOf(el) {
return String(
el.getAttribute?.('aria-label') || el.innerText || el.textContent || el.value || ''
).replace(/\s+/g, ' ').trim();
}
function fireClick(el) {
try { el.focus?.(); } catch (_) {}
try {
el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window}));
} catch (_) {}
try { el.click(); } catch (_) {}
}
for (const el of deepNodes(document)) {
if (!el || !el.tagName) continue;
const tag = String(el.tagName || '').toLowerCase();
const role = String(el.getAttribute?.('role') || '').toLowerCase();
const ok =
tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' ||
tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button';
if (!ok || !visible(el)) continue;
const t = labelOf(el);
if (!t || t.length > 48) continue;
if (CANCEL_RE.test(t)) continue;
if (!END_RE.test(t)) continue;
fireClick(el);
return {ok: true, text: t.slice(0, 40), needConfirm: true};
}
return {ok: false, error: 'not_found'};
})()
"""
CONFIRM_JS = r"""
(() => {
// Dialog only: [Not yet] [End] — NEVER match header "End Stream"
const CONFIRM_EXACT = /^(end|结束)$/i;
const CANCEL_RE = /not yet|not now|cancel|keep|go back|还没有|取消|继续|稍后再说|end stream|结束直播|stop streaming/i;
function visible(el) {
if (!el || !el.getBoundingClientRect) return false;
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return false;
const st = window.getComputedStyle ? getComputedStyle(el) : null;
if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false;
return true;
}
function* deepNodes(root) {
const stack = [root];
while (stack.length) {
const n = stack.pop();
if (!n) continue;
yield n;
if (n.shadowRoot) stack.push(n.shadowRoot);
if (n.children) {
for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]);
}
}
}
function labelOf(el) {
return String(
el.getAttribute?.('aria-label') || el.innerText || el.textContent || ''
).replace(/\s+/g, ' ').trim();
}
function isClickable(el) {
if (!el || !el.tagName) return false;
const tag = String(el.tagName || '').toLowerCase();
const role = String(el.getAttribute?.('role') || '').toLowerCase();
return (
tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' ||
tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button'
);
}
function fireClick(el) {
try { el.focus?.(); } catch (_) {}
try {
el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window}));
el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window}));
} catch (_) {}
try { el.click(); } catch (_) {}
}
let roots = [document];
for (const el of deepNodes(document)) {
const role = String(el.getAttribute?.('role') || '').toLowerCase();
const tag = String(el.tagName || '').toLowerCase();
if (role === 'dialog' || tag.includes('dialog')) {
roots.unshift(el);
if (el.shadowRoot) roots.unshift(el.shadowRoot);
}
}
const exactHits = [];
for (const root of roots) {
for (const el of deepNodes(root)) {
if (!isClickable(el) || !visible(el)) continue;
const t = labelOf(el);
if (!t || t.length > 64) continue;
// Reject any control whose label contains End Stream / Not yet noise.
if (/end stream|结束直播|stop streaming|not yet/i.test(t) && !CONFIRM_EXACT.test(t.trim())) continue;
const compact = t.replace(/\s+/g, ' ').trim();
if (CONFIRM_EXACT.test(compact)) exactHits.push([el, compact, 'label']);
else {
const leaf = String(el.innerText || '').replace(/\s+/g, ' ').trim();
if (leaf && CONFIRM_EXACT.test(leaf) && leaf.length <= 8) exactHits.push([el, leaf, 'leaf']);
}
}
}
// Prefer hits found under a dialog root.
const pick = exactHits[0];
if (!pick) return {ok: false, error: 'confirm_not_found', dialog_hint: roots.length > 1};
fireClick(pick[0]);
return {ok: true, text: pick[1].slice(0, 40), via: pick[2]};
})()
"""
def main() -> None:
tabs = json.loads(
urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode()
)
live = []
for t in tabs:
u = (t.get("url") or "").lower()
if "studio.youtube.com" in u and "livestreaming" in u:
live.append(t)
if not live:
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)
try:
eval_js(sock, "true", req_id=1, timeout=3)
def _is_dialog_end(row: dict) -> bool:
return bool(row.get("ok")) and str(row.get("text") or "").strip().lower() in {
"end",
"结束",
}
# 1) Dialog already open → click exact "End" only (never header End Stream).
pre = eval_js(sock, CONFIRM_JS, req_id=2, timeout=8) or {}
if not isinstance(pre, dict):
pre = {"ok": False, "error": "bad_pre_confirm"}
first: dict = {"ok": False, "skipped": True}
confirm: dict = {"ok": False, "skipped": True}
if _is_dialog_end(pre):
confirm = pre
else:
# 2) Click header End Stream, then dialog End (retries).
first = eval_js(sock, CLICK_JS, req_id=3, timeout=8) or {}
if not isinstance(first, dict):
first = {"ok": False, "error": "bad_eval"}
if first.get("ok"):
confirm = {"ok": False, "error": "pending"}
for attempt, req_id in enumerate((4, 5, 6, 7), start=1):
time.sleep(1.6 if attempt == 1 else 1.0)
confirm = eval_js(sock, CONFIRM_JS, req_id=req_id, timeout=8) or {}
if not isinstance(confirm, dict):
confirm = {"ok": False, "error": "bad_confirm_eval"}
confirm["attempt"] = attempt
if _is_dialog_end(confirm):
break
confirm["ok"] = False
print(
json.dumps(
{
"ok": bool((first.get("ok") or _is_dialog_end(pre)) and _is_dialog_end(confirm)),
"url": url[:200],
"pre_confirm": pre,
"end_click": first,
"confirm_click": confirm,
},
ensure_ascii=False,
)
)
finally:
try:
sock.close()
except Exception:
pass
if __name__ == "__main__":
main()