douyinWEB/scripts/_recover_chooser_inner.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
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>
2026-09-04 22:42:40 -05:00

163 lines
4.9 KiB
Python

# -*- coding: utf-8 -*-
"""Inside each Neko: click Google accountchooser + open Studio Live URL."""
from __future__ import annotations
import base64
import json
import os
import socket
import struct
import subprocess
import time
import urllib.request
from urllib.parse import urlparse
URLS = {
1: "https://studio.youtube.com/video/9tMkUp0iUH8/livestreaming",
2: "https://studio.youtube.com/video/zHthtNjrbeo/livestreaming",
3: "https://studio.youtube.com/video/8NeMVAjx0r4/livestreaming",
4: "https://studio.youtube.com/video/-kkCblUC8XM/livestreaming",
5: "https://studio.youtube.com/video/31s_VgR215k/livestreaming",
6: "https://studio.youtube.com/video/IKGJwKAZGWM/livestreaming",
7: "https://studio.youtube.com/video/i6szUMA25RM/livestreaming",
}
CLICK_JS = "(document.querySelector('[data-identifier]')||document.querySelector('li div[role=link]')||document.querySelector('div[data-authuser]')).click()||'clicked'"
def run(cmd, timeout=40):
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return p.returncode, (p.stdout or "") + (p.stderr or "")
INNER = r'''
import base64, json, os, socket, struct, time, urllib.request
from urllib.parse import urlparse
studio_url = STUDIO_URL
CLICK_JS = CLICK_JS_VAL
def ws_connect(url):
hostport, path = url[5:].split("/", 1)
path = "/" + path
host, port_s = hostport.split(":")
key = base64.b64encode(os.urandom(16)).decode()
s = socket.create_connection((host, int(port_s)), timeout=6)
s.sendall((
"GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, hostport, key)
).encode())
buf = b""
while b"\r\n\r\n" not in buf:
chunk = s.recv(4096)
if not chunk:
raise RuntimeError("hs")
buf += chunk
return s
def ws_send(s, payload):
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)
s.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
def ws_recv(s):
def re(n):
o = b""
while len(o) < n:
c = s.recv(n - len(o))
if not c:
raise RuntimeError("x")
o += c
return o
hdr = re(2)
b1, b2 = hdr[0], hdr[1]
op = b1 & 0x0F
ln = b2 & 0x7F
if ln == 126:
ln = struct.unpack("!H", re(2))[0]
data = re(ln)
if op != 1:
return {"id": None}
return json.loads(data.decode())
def eval_js(ws_url, expression):
s = ws_connect(ws_url)
ws_send(s, {"id": 1, "method": "Runtime.evaluate", "params": {"expression": expression, "returnByValue": True}})
deadline = time.time() + 5
val = None
while time.time() < deadline:
m = ws_recv(s)
if m and m.get("id") == 1:
val = ((m.get("result") or {}).get("result") or {}).get("value")
break
try:
s.close()
except Exception:
pass
return val
tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode())
clicked = False
for t in tabs:
u = t.get("url") or ""
ws = t.get("webSocketDebuggerUrl") or ""
if "accounts.google.com" in u and ws:
try:
print("click", eval_js(ws, CLICK_JS))
clicked = True
except Exception as e:
print("click_err", e)
if clicked:
time.sleep(5)
req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + studio_url, method="PUT")
try:
print("opened", urllib.request.urlopen(req, timeout=10).read()[:40])
except Exception as e:
print("open_err", e)
time.sleep(8)
tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode())
for t in tabs:
u = t.get("url") or ""
p = urlparse(u)
host = (p.netloc or "").lower()
path = (p.path or "").lower()
if host.endswith("studio.youtube.com") and "livestreaming" in path:
print("studio_ok", u[:110])
break
if "accounts.google.com" in host:
print("still_chooser")
'''
def main():
for idx, studio_url in URLS.items():
name = f"douyinweb-neko-{idx}"
code = INNER.replace("STUDIO_URL", json.dumps(studio_url)).replace(
"CLICK_JS_VAL", json.dumps(CLICK_JS)
)
print("===", name, "===")
p = subprocess.run(
["docker", "exec", "-i", name, "python3", "-"],
input=code,
capture_output=True,
text=True,
timeout=90,
)
print((p.stdout or p.stderr or "")[-600:])
print("RECOVER_DONE")
if __name__ == "__main__":
main()