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>
280 lines
8.9 KiB
Python
280 lines
8.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Recover Studio sessions: click Google accountchooser then open Live URLs."""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
PASS = "4669805"
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
SH = r'''#!/bin/bash
|
|
set -euo pipefail
|
|
python3 - <<'PY'
|
|
import base64, json, os, socket, struct, subprocess, time, 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",
|
|
}
|
|
|
|
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 "")
|
|
|
|
def ws_connect(url: str):
|
|
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)
|
|
s.sendall((
|
|
f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\n"
|
|
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
|
|
).encode())
|
|
buf = b""
|
|
while b"\r\n\r\n" not in buf:
|
|
chunk = s.recv(4096)
|
|
if not chunk:
|
|
raise RuntimeError("handshake fail")
|
|
buf += chunk
|
|
return s
|
|
|
|
def ws_send(s, payload):
|
|
data = json.dumps(payload).encode()
|
|
mask = os.urandom(4)
|
|
header = bytearray([0x81, 0x80 | len(data)])
|
|
if len(data) >= 126:
|
|
raise RuntimeError("payload too large")
|
|
header.extend(mask)
|
|
s.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
|
|
|
|
def ws_recv(s):
|
|
def readexact(n):
|
|
out = b""
|
|
while len(out) < n:
|
|
c = s.recv(n - len(out))
|
|
if not c:
|
|
raise RuntimeError("closed")
|
|
out += c
|
|
return out
|
|
hdr = readexact(2)
|
|
b1, b2 = hdr[0], hdr[1]
|
|
opcode = b1 & 0x0F
|
|
ln = b2 & 0x7F
|
|
if ln == 126:
|
|
ln = struct.unpack("!H", readexact(2))[0]
|
|
data = readexact(ln)
|
|
if opcode == 0x8:
|
|
return None
|
|
if opcode != 0x1:
|
|
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:
|
|
msg = ws_recv(s)
|
|
if not msg:
|
|
break
|
|
if msg.get("id") == 1:
|
|
val = ((msg.get("result") or {}).get("result") or {}).get("value")
|
|
break
|
|
try:
|
|
s.close()
|
|
except Exception:
|
|
pass
|
|
return val
|
|
|
|
CLICK_JS = r'''
|
|
(() => {
|
|
const nodes = [
|
|
...document.querySelectorAll('[data-identifier]'),
|
|
...document.querySelectorAll('div[data-authuser]'),
|
|
...document.querySelectorAll('li[data-identifier]'),
|
|
];
|
|
const el = nodes.find(n => n && n.offsetParent !== null) || document.querySelector('[data-identifier]');
|
|
if (el) { el.click(); return 'clicked:' + (el.getAttribute('data-identifier') || el.textContent || '').slice(0,80); }
|
|
const btn = document.querySelector('button, div[role="link"], div[role="button"]');
|
|
if (btn) { btn.click(); return 'clicked-fallback'; }
|
|
return 'no-target';
|
|
})()
|
|
'''
|
|
|
|
for idx, studio_url in URLS.items():
|
|
name = f"douyinweb-neko-{idx}"
|
|
# list tabs
|
|
py_list = "import json,urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read().decode())"
|
|
code, out = run(["docker", "exec", name, "python3", "-c", py_list])
|
|
try:
|
|
tabs = json.loads(out.strip() or "[]")
|
|
except Exception:
|
|
tabs = []
|
|
# click accountchooser if present
|
|
for t in tabs:
|
|
u = t.get("url") or ""
|
|
ws = t.get("webSocketDebuggerUrl") or ""
|
|
if "accounts.google.com" in u and ws:
|
|
# run click inside container via embedded python is hard; use host-side? WS is 127.0.0.1 inside container only.
|
|
pass
|
|
|
|
# Inside-container recovery script
|
|
py = f'''
|
|
import base64, json, os, socket, struct, time, urllib.request
|
|
from urllib.parse import urlparse
|
|
|
|
studio_url = {studio_url!r}
|
|
CLICK_JS = {CLICK_JS!r}
|
|
|
|
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((f"GET {{path}} HTTP/1.1\\r\\nHost: {{hostport}}\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Key: {{key}}\\r\\nSec-WebSocket-Version: 13\\r\\n\\r\\n").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, 0x80 | len(data)])
|
|
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
|
|
b1,b2=re(2)
|
|
op=b1[0]&0x0F; ln=b2[0]&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:
|
|
r=eval_js(ws, CLICK_JS)
|
|
print("click", r)
|
|
clicked=True
|
|
except Exception as e:
|
|
print("click_err", e)
|
|
if clicked:
|
|
time.sleep(4)
|
|
|
|
# open studio live URL
|
|
req=urllib.request.Request("http://127.0.0.1:9222/json/new?" + studio_url, method="PUT")
|
|
try:
|
|
body=urllib.request.urlopen(req, timeout=10).read().decode()
|
|
print("opened", body[:60])
|
|
except Exception as e:
|
|
print("open_err", e)
|
|
time.sleep(6)
|
|
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)
|
|
if (p.netloc or "").lower().endswith("studio.youtube.com") and "livestreaming" in (p.path or "").lower():
|
|
print("studio_ok", u[:100]); break
|
|
if "accounts.google.com" in u:
|
|
print("still_chooser", u[:80])
|
|
'''
|
|
code, out = run(["docker", "exec", name, "python3", "-c", py], timeout=60)
|
|
print("===", name, "===")
|
|
print((out or "").strip()[-500:])
|
|
|
|
print("RECOVER_DONE")
|
|
PY
|
|
|
|
sleep 8
|
|
python3 /tmp/_list_neko_tabs.py
|
|
echo SCRAPE
|
|
python3 /tmp/_scrape_all_nekos.py
|
|
echo PROBE
|
|
/opt/douyinWEB/backend/.venv/bin/python /tmp/_probe_telemetry_detail.py
|
|
'''
|
|
|
|
|
|
def main() -> int:
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
for i in range(10):
|
|
try:
|
|
c.connect(
|
|
"107.173.30.245",
|
|
4014,
|
|
"eric",
|
|
PASS,
|
|
timeout=60,
|
|
banner_timeout=120,
|
|
allow_agent=False,
|
|
look_for_keys=False,
|
|
)
|
|
break
|
|
except Exception as ex:
|
|
print("ssh", i, type(ex).__name__)
|
|
time.sleep(2)
|
|
else:
|
|
return 1
|
|
sftp = c.open_sftp()
|
|
for rel, tmp in [
|
|
("scripts/_list_neko_tabs.py", "_list_neko_tabs.py"),
|
|
("scripts/_scrape_all_nekos.py", "_scrape_all_nekos.py"),
|
|
("scripts/_probe_telemetry_detail.py", "_probe_telemetry_detail.py"),
|
|
]:
|
|
with sftp.file(f"/tmp/{tmp}", "wb") as f:
|
|
f.write((ROOT / rel).read_bytes())
|
|
with sftp.file("/tmp/_recover_chooser.sh", "w") as f:
|
|
f.write(SH)
|
|
sftp.close()
|
|
_, o, e = c.exec_command(f"echo '{PASS}' | sudo -S -p '' bash /tmp/_recover_chooser.sh", timeout=600)
|
|
print((o.read() + e.read()).decode("utf-8", "replace"))
|
|
c.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|