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>
223 lines
7.3 KiB
Python
223 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""Copy rooms (+ blacklist) from dylive.nomadro.com → physical dy.nomadro.com via API.
|
|
|
|
Also tries SSH dump as fallback for core tables.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
SRC = "https://dylive.nomadro.com"
|
|
DST = "https://dy.nomadro.com"
|
|
# known admin combos used on this fleet
|
|
CREDS = [
|
|
("hackrobot", "Xiao4669805@"),
|
|
("hackrobot", "Xiao4669805@!"),
|
|
("admin", "Xiao4669805@"),
|
|
("admin", "Xiao4669805"),
|
|
("eric", "4669805"),
|
|
]
|
|
|
|
|
|
def login(base: str) -> httpx.Client:
|
|
last = None
|
|
for user, pw in CREDS:
|
|
c = httpx.Client(base_url=base, timeout=60, follow_redirects=True)
|
|
try:
|
|
r = c.post("/api/auth/login", json={"username": user, "password": pw})
|
|
if r.status_code == 200 and "dy_session" in c.cookies:
|
|
print(f"login ok {base} as {user}", flush=True)
|
|
return c
|
|
last = f"{user}:{r.status_code} {r.text[:120]}"
|
|
except Exception as ex:
|
|
last = f"{user}:{ex}"
|
|
c.close()
|
|
raise SystemExit(f"login failed {base}: {last}")
|
|
|
|
|
|
def ssh_retry(host, port, user, pw, tries=8):
|
|
last = None
|
|
for i in range(tries):
|
|
try:
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect(
|
|
host,
|
|
port,
|
|
user,
|
|
pw,
|
|
timeout=60,
|
|
banner_timeout=120,
|
|
allow_agent=False,
|
|
look_for_keys=False,
|
|
)
|
|
return c
|
|
except Exception as ex:
|
|
last = ex
|
|
print(f"ssh {host}:{port} try{i} {type(ex).__name__}", flush=True)
|
|
time.sleep(2 + i)
|
|
raise last # type: ignore[misc]
|
|
|
|
|
|
def run(c, cmd, t=120):
|
|
_, o, e = c.exec_command(cmd, timeout=t)
|
|
return (o.read() + e.read()).decode("utf-8", "replace")
|
|
|
|
|
|
def export_via_api(src: httpx.Client) -> dict:
|
|
rooms = src.get("/api/rooms/export", params={"format": "json"})
|
|
rooms.raise_for_status()
|
|
data = rooms.json()
|
|
bl = src.get("/api/blacklist", params={"limit": 5000})
|
|
blacklist = []
|
|
if bl.status_code == 200:
|
|
j = bl.json()
|
|
blacklist = j.get("items") or j.get("blacklist") or j.get("rows") or []
|
|
if isinstance(j, list):
|
|
blacklist = j
|
|
# health / counts
|
|
h = src.get("/api/health")
|
|
print("src health", h.status_code, flush=True)
|
|
print("src rooms", data.get("total"), "blacklist", len(blacklist), flush=True)
|
|
return {"rooms": data.get("rooms") or [], "blacklist": blacklist}
|
|
|
|
|
|
def import_rooms(dst: httpx.Client, rooms: list[dict]) -> None:
|
|
# Prefer batch URL paste for idempotent ensure_in_live_pool
|
|
lines = []
|
|
for r in rooms:
|
|
url = (r.get("url") or "").strip()
|
|
if not url and r.get("room_id"):
|
|
url = f"https://live.douyin.com/{r['room_id']}"
|
|
if not url:
|
|
continue
|
|
note = (r.get("note") or r.get("last_anchor") or r.get("name") or "").strip()
|
|
tags = r.get("tags") or []
|
|
if isinstance(tags, list):
|
|
tag_s = ",".join(str(t) for t in tags if t)
|
|
else:
|
|
tag_s = str(tags or "")
|
|
# format understood by parse_douyin_line roughly: url + optional note
|
|
if note:
|
|
lines.append(f"{url} 主播:{note}")
|
|
else:
|
|
lines.append(url)
|
|
|
|
# chunk to avoid huge body
|
|
chunk = 80
|
|
created = updated = skipped = 0
|
|
for i in range(0, len(lines), chunk):
|
|
part = lines[i : i + chunk]
|
|
# tags from first room in chunk if uniform — send empty; per-room tags via patch later
|
|
r = dst.post(
|
|
"/api/rooms/batch",
|
|
json={"urls": "\n".join(part), "note": "", "enabled": True, "tags": ""},
|
|
)
|
|
print(f"batch {i}-{i+len(part)} -> {r.status_code}", flush=True)
|
|
if r.status_code != 200:
|
|
print(r.text[:400], flush=True)
|
|
continue
|
|
j = r.json()
|
|
created += int(j.get("created_count") or 0)
|
|
updated += int(j.get("updated_count") or 0)
|
|
skipped += int(j.get("skipped_count") or 0)
|
|
print(f"import rooms done created={created} updated={updated} skipped={skipped}", flush=True)
|
|
|
|
# patch tags/enabled/note for fidelity
|
|
existing = dst.get("/api/rooms", params={"limit": 5000}).json()
|
|
by_rid = {}
|
|
for r in existing.get("rooms") or []:
|
|
rid = str(r.get("room_id") or "")
|
|
if rid:
|
|
by_rid[rid] = r
|
|
patched = 0
|
|
for src_r in rooms:
|
|
rid = str(src_r.get("room_id") or "")
|
|
cur = by_rid.get(rid)
|
|
if not cur:
|
|
continue
|
|
tags = src_r.get("tags") or []
|
|
if isinstance(tags, str):
|
|
tags = [t for t in tags.split(",") if t]
|
|
body = {
|
|
"note": src_r.get("note") or cur.get("note") or "",
|
|
"enabled": bool(src_r.get("enabled", True)),
|
|
"tags": tags if isinstance(tags, list) else [],
|
|
}
|
|
pr = dst.patch(f"/api/rooms/{cur['id']}", json=body)
|
|
if pr.status_code == 200:
|
|
patched += 1
|
|
print(f"patched metadata {patched}", flush=True)
|
|
|
|
|
|
def import_blacklist(dst: httpx.Client, items: list) -> None:
|
|
if not items:
|
|
print("no blacklist", flush=True)
|
|
return
|
|
n = 0
|
|
for it in items:
|
|
if isinstance(it, str):
|
|
val = it
|
|
reason = "from dylive"
|
|
else:
|
|
val = str(it.get("value") or it.get("room_id") or it.get("url") or "").strip()
|
|
reason = str(it.get("reason") or "from dylive")
|
|
if not val:
|
|
continue
|
|
r = dst.post("/api/blacklist", json={"value": val, "reason": reason})
|
|
if r.status_code in (200, 201):
|
|
n += 1
|
|
elif r.status_code == 409:
|
|
n += 1
|
|
else:
|
|
# try alternate shapes
|
|
r2 = dst.post("/api/blacklist", json={"room_id": val, "reason": reason})
|
|
if r2.status_code in (200, 201, 409):
|
|
n += 1
|
|
print(f"blacklist upserted ~{n}/{len(items)}", flush=True)
|
|
|
|
|
|
def verify(dst: httpx.Client) -> None:
|
|
h = dst.get("/api/health").json()
|
|
rooms = dst.get("/api/rooms", params={"limit": 1}).json()
|
|
print("dst health counts", h.get("counts") or h.get("db"), flush=True)
|
|
print("dst rooms total", rooms.get("total"), flush=True)
|
|
|
|
|
|
def main() -> int:
|
|
print("=== export from dylive ===", flush=True)
|
|
src = login(SRC)
|
|
payload = export_via_api(src)
|
|
out = Path(__file__).resolve().parents[1] / "backend" / "data" / "_dylive_rooms_export.json"
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print("saved", out, "rooms", len(payload["rooms"]), flush=True)
|
|
src.close()
|
|
|
|
if not payload["rooms"]:
|
|
raise SystemExit("no rooms exported")
|
|
|
|
print("=== import to physical dy.nomadro.com ===", flush=True)
|
|
dst = login(DST)
|
|
before = dst.get("/api/rooms", params={"limit": 1}).json()
|
|
print("dst rooms before", before.get("total"), flush=True)
|
|
import_rooms(dst, payload["rooms"])
|
|
import_blacklist(dst, payload.get("blacklist") or [])
|
|
verify(dst)
|
|
dst.close()
|
|
print("DONE", flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|