douyinWEB/scripts/_fix_dual_neko_panel_parity.py
2026-09-13 22:10:49 -05:00

256 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Verify dual VPS source parity + explain Neko panel state diff."""
from __future__ import annotations
import hashlib
import json
import ssl
import sys
import time
import urllib.request
from http.cookiejar import CookieJar
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
CTX = ssl.create_default_context()
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
PASS = "Xiao4669805"
HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")]
FILES = [
"backend/app/douyin.py",
"backend/app/session_auth.py",
"backend/app/youtube_neko.py",
"frontend/src/components/YtRelayProStatusPanel.tsx",
"frontend/src/lib/api.js",
"frontend/src/components/YtAssignPanel.tsx",
]
def connect(host):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(10):
try:
c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120)
return c
except Exception as e:
print("retry", host, e, flush=True)
time.sleep(2 + i)
raise SystemExit("ssh fail " + host)
def run(c, cmd, timeout=120):
_i, o, e = c.exec_command(cmd, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def put(c, data: bytes, remote: str):
sftp = c.open_sftp()
with sftp.file(remote, "wb") as f:
f.write(data)
sftp.close()
local = {}
print("LOCAL", flush=True)
for rel in FILES:
p = ROOT / rel.replace("/", "\\")
h = hashlib.sha256(p.read_bytes()).hexdigest()[:12]
local[rel] = h
print(h, rel, flush=True)
remote_hashes = {}
for label, host in HOSTS:
print(f"\n######## {label} {host} ########", flush=True)
c = connect(host)
out = run(
c,
"python3 - <<'PY'\n"
"import hashlib, pathlib\n"
f"files={FILES!r}\n"
"root=pathlib.Path('/opt/douyinWEB')\n"
"for rel in files:\n"
" p=root/rel\n"
" print(('MISSING' if not p.exists() else hashlib.sha256(p.read_bytes()).hexdigest()[:12]), rel)\n"
"PY\n"
"echo '--- panel markers ---'\n"
"grep -n '双 VPS\\|Live 页\\|本机 Neko 数据\\|物理机' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -20\n"
"echo '--- next build ---'\n"
"stat -c '%y' /opt/douyinWEB/frontend/.next/BUILD_ID 2>/dev/null || echo no_build_id\n"
"echo '--- neko docker ---'\n"
"docker ps --filter name=neko --format '{{.Names}} {{.Status}}' 2>/dev/null\n",
)
print(out, flush=True)
remote_hashes[label] = {}
for line in out.splitlines():
parts = line.strip().split(None, 1)
if len(parts) == 2 and parts[1] in local:
remote_hashes[label][parts[1]] = parts[0]
c.close()
print("\n=== HASH DIFF vs LOCAL ===", flush=True)
need_sync = False
for label, hm in remote_hashes.items():
for rel, lh in local.items():
rh = hm.get(rel, "MISSING")
ok = rh == lh
if not ok:
need_sync = True
print(f"{label:7} {'OK' if ok else 'DIFF'} {rel} local={lh} remote={rh}", flush=True)
# Force sync if any DIFF
if need_sync:
print("\n=== FORCE SYNC BOTH ===", flush=True)
# Build src tar locally conceptually by uploading each file
for label, host in HOSTS:
c = connect(host)
for rel in FILES:
p = ROOT / rel.replace("/", "\\")
put(c, p.read_bytes(), f"/opt/douyinWEB/{rel}")
print("put", label, rel, flush=True)
print(
run(
c,
r"""
set -e
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app.douyin import pick_stream_candidates
room={"stream_url":{"flv_pull_url":{"ORIGIN":"http://x/a_uhd.flv","HD1":"http://x/a_hd.flv"}}}
assert 'a_hd.flv' in pick_stream_candidates(room)[0]
print('douyin_pick_ok')
PY
systemctl restart douyinweb-api
sleep 1
systemctl is-active douyinweb-api
""",
timeout=60,
),
flush=True,
)
c.close()
# FE: build on dy, sync .next to dylive
print("=== FE build on dy + sync ===", flush=True)
c = connect("108.174.50.68")
print(
run(
c,
r"""
set -e
cd /opt/douyinWEB/frontend
export NODE_OPTIONS=--max-old-space-size=3072
npm run build 2>&1 | tail -20
systemctl restart douyinweb-web
tar -C /opt/douyinWEB/frontend -czf /tmp/next-panel-sync.tgz .next
ls -lh /tmp/next-panel-sync.tgz
""",
timeout=700,
),
flush=True,
)
sftp = c.open_sftp()
sftp.get("/tmp/next-panel-sync.tgz", str(ROOT / "scripts/_next-panel-sync.tgz"))
sftp.close()
c.close()
c = connect("107.173.30.245")
put(c, (ROOT / "scripts/_next-panel-sync.tgz").read_bytes(), "/tmp/next-panel-sync.tgz")
print(
run(
c,
r"""
set -e
systemctl stop douyinweb-web || true
rm -rf /opt/douyinWEB/frontend/.next.bak_panel
mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_panel 2>/dev/null || true
tar -C /opt/douyinWEB/frontend -xzf /tmp/next-panel-sync.tgz
systemctl start douyinweb-web
sleep 2
systemctl is-active douyinweb-web
""",
timeout=90,
),
flush=True,
)
c.close()
# API studio/neko state comparison for focused groups
print("\n=== RUNTIME STATE (not source) ===", flush=True)
def login_opener(site):
cj = CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=CTX),
urllib.request.HTTPCookieProcessor(cj),
)
body = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode()
req = urllib.request.Request(
site + "/api/auth/login",
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
with opener.open(req, timeout=30) as r:
r.read()
return opener
for site in ("https://dylive.nomadro.com", "https://dy.nomadro.live"):
print(f"\n--- {site} ---", flush=True)
try:
op = login_opener(site)
with op.open(site + "/api/youtube/assign/groups", timeout=40) as r:
groups = json.loads(r.read().decode()).get("groups") or []
# find nomad street food / nice street food
for g in groups:
name = str(g.get("name") or "")
if "street" not in name.lower() and "Street" not in name:
continue
print(
{
"name": name,
"neko_id": g.get("neko_instance_id"),
"neko_enabled": g.get("neko_enabled"),
"prefer": g.get("neko_open_prefer") or g.get("ops_neko_prefer"),
},
flush=True,
)
nid = int(g.get("neko_instance_id") or 0)
if nid:
try:
with op.open(site + f"/api/youtube/neko/{nid}/status", timeout=20) as r:
st = json.loads(r.read().decode())
print(" neko_status", {k: st.get(k) for k in ("running", "ready", "url", "error", "container")}, flush=True)
except Exception as e:
print(" neko_status_err", e, flush=True)
# studio samples / status endpoint variants
for path in (
"/api/youtube/studio/samples",
"/api/youtube/assign/studio-status",
"/api/youtube/relay/status",
):
try:
with op.open(site + path, timeout=25) as r:
data = json.loads(r.read().decode())
if path.endswith("relay/status"):
ents = data.get("entries") or data.get("items") or []
if isinstance(ents, list):
for e in ents[:8]:
if not isinstance(e, dict):
continue
if e.get("is_pushing") or str(e.get("status") or "").find("push") >= 0:
print(" relay", {k: e.get(k) for k in ("name", "group_id", "status", "is_pushing", "source_url")}, flush=True)
else:
print(path, "keys", list(data.keys())[:12] if isinstance(data, dict) else type(data), flush=True)
except Exception as e:
print(path, "ERR", e, flush=True)
except Exception as e:
print("SITE_ERR", e, flush=True)
print("ALL_DONE", flush=True)