# -*- coding: utf-8 -*- """Recover Google accountchooser with CDP mouse click + open Studio Live.""" from __future__ import annotations import json import subprocess import time 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", } # Runs inside each Neko container via stdin. INNER = r''' import base64, json, os, socket, struct, time, urllib.parse, urllib.request studio_url = STUDIO_URL 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=8) 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("handshake") 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("closed") o += c return o while True: hdr = re(2) b1, b2 = hdr[0], hdr[1] op = b1 & 0x0F masked = (b2 & 0x80) != 0 ln = b2 & 0x7F if ln == 126: ln = struct.unpack("!H", re(2))[0] elif ln == 127: ln = struct.unpack("!Q", re(8))[0] if masked: mask = re(4) data = re(ln) if masked: data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) if op == 0x8: return None if op == 0x1: return json.loads(data.decode()) # ignore ping/pong/binary _id = 0 def cdp(s, method, params=None): global _id _id += 1 msg = {"id": _id, "method": method} if params is not None: msg["params"] = params ws_send(s, msg) deadline = time.time() + 8 while time.time() < deadline: m = ws_recv(s) if not m: break if m.get("id") == _id: return m return None def tabs(): return json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode()) def find_chooser(tabs): for t in tabs: u = t.get("url") or "" if "accounts.google.com" in u and t.get("webSocketDebuggerUrl"): return t return None def find_studio(tabs): for t in tabs: u = t.get("url") or "" p = urllib.parse.urlparse(u) if (p.netloc or "").lower().endswith("studio.youtube.com") and "livestreaming" in (p.path or "").lower(): return t return None # Already good? tlist = tabs() if find_studio(tlist): print("already_studio", find_studio(tlist).get("url","")[:100]) raise SystemExit(0) ch = find_chooser(tlist) if not ch: # open studio directly req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + studio_url, method="PUT") urllib.request.urlopen(req, timeout=10).read() time.sleep(5) tlist = tabs() ch = find_chooser(tlist) st = find_studio(tlist) if st: print("studio_ok", st.get("url","")[:100]) raise SystemExit(0) if not ch: print("no_chooser") raise SystemExit(1) ws = ch["webSocketDebuggerUrl"] s = ws_connect(ws) # Activate page tid = ch.get("id") if tid: try: urllib.request.urlopen("http://127.0.0.1:9222/json/activate/%s" % tid, timeout=3).read() except Exception: pass time.sleep(0.5) # Inspect account tiles info = cdp(s, "Runtime.evaluate", { "expression": """(() => { const out = []; const nodes = document.querySelectorAll('[data-identifier], li[data-identifier], div[data-email], div[data-authuser]'); nodes.forEach((n,i) => { const r = n.getBoundingClientRect(); if (r.width < 10 || r.height < 10) return; out.push({ i, id: n.getAttribute('data-identifier') || n.getAttribute('data-email') || '', text: (n.innerText||'').slice(0,60).replace(/\\n/g,' '), x: r.x + r.width/2, y: r.y + r.height/2, w: r.width, h: r.height }); }); // fallback: any clickable list row if (!out.length) { document.querySelectorAll('ul li, [role="link"], [role="button"]').forEach((n,i) => { const r = n.getBoundingClientRect(); const t = (n.innerText||'').trim(); if (r.width>40 && r.height>20 && t.length>3 && /@|google|youtube|gmail/i.test(t+n.className)) { out.push({i, id:'fb'+i, text:t.slice(0,60), x:r.x+r.width/2, y:r.y+r.height/2, w:r.width, h:r.height}); } }); } return {title: document.title, href: location.href.slice(0,120), count: out.length, nodes: out.slice(0,5)}; })()""", "returnByValue": True, }) val = (((info or {}).get("result") or {}).get("result") or {}).get("value") or {} print("inspect", json.dumps(val, ensure_ascii=False)[:400]) nodes = val.get("nodes") or [] if not nodes: # try continue URL from query cont = urllib.parse.parse_qs(urllib.parse.urlparse(ch.get("url") or "").query).get("continue", [""])[0] print("no_tiles continue=", cont[:100]) if cont: cdp(s, "Page.navigate", {"url": cont}) time.sleep(6) else: # Real mouse click on first account tile n0 = nodes[0] x, y = float(n0["x"]), float(n0["y"]) print("click_xy", x, y, n0.get("id"), n0.get("text")) for typ in ("mousePressed", "mouseReleased"): cdp(s, "Input.dispatchMouseEvent", { "type": typ, "x": x, "y": y, "button": "left", "clickCount": 1, }) time.sleep(6) try: s.close() except Exception: pass # After chooser, open studio live req = urllib.request.Request("http://127.0.0.1:9222/json/new?" + studio_url, method="PUT") try: urllib.request.urlopen(req, timeout=10).read() except Exception as e: print("open_err", e) time.sleep(8) tlist = tabs() st = find_studio(tlist) if st: print("studio_ok", st.get("url","")[:120]) else: # dump current pages for t in tlist: if t.get("type") == "page": print("page", (t.get("url") or "")[:120]) ''' def main(): for idx, studio_url in URLS.items(): name = f"douyinweb-neko-{idx}" code = INNER.replace("STUDIO_URL", json.dumps(studio_url)) print("===", name, "===") p = subprocess.run( ["docker", "exec", "-i", name, "python3", "-"], input=code, capture_output=True, text=True, timeout=120, ) out = (p.stdout or "") + (p.stderr or "") print(out[-900:] if out else f"rc={p.returncode} empty") time.sleep(1) print("ALL_DONE") if __name__ == "__main__": main()