#!/usr/bin/env python3 """Inspect stream-keys + assign key coverage; sync registry dy→dylive if needed.""" from __future__ import annotations 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() SSH_PASS = "Xiao4669805" APP_PASS = "Xiao4669805@" def http_login(base: str): cj = CookieJar() op = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(cj), urllib.request.HTTPSHandler(context=CTX), ) req = urllib.request.Request( f"{base}/api/auth/login", data=json.dumps({"username": "hackrobot", "password": APP_PASS}).encode(), headers={"Content-Type": "application/json"}, method="POST", ) op.open(req, timeout=45).read() return op def get_json(op, url: str): with op.open(url, timeout=45) as r: return r.status, json.loads(r.read().decode()) def ssh(host: str): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for i in range(8): try: c.connect( host, 22, "root", SSH_PASS, timeout=50, allow_agent=False, look_for_keys=False, banner_timeout=180, ) return c except Exception as e: print("ssh_retry", host, i, e, flush=True) time.sleep(2 + i) raise SystemExit(f"ssh fail {host}") def run(c, cmd: str, t: int = 120) -> str: _i, o, e = c.exec_command(cmd, timeout=t) return (o.read() + e.read()).decode("utf-8", "replace") def summarize(label: str, base: str): print(f"\n=== HTTP {label} ===", flush=True) op = http_login(base) st, sk = get_json(op, f"{base}/api/youtube/stream-keys") print("stream-keys keys:", sorted(sk.keys()) if isinstance(sk, dict) else type(sk), "status", st) entries = [] if isinstance(sk, dict): for k in ("entries", "items", "keys", "data"): if isinstance(sk.get(k), list): entries = sk[k] break if not entries and all(isinstance(v, dict) for v in sk.values()): entries = list(sk.values()) print(f" entries={len(entries)}") for e in entries[:3]: if isinstance(e, dict): print( " sample", e.get("title") or e.get("channel_title") or e.get("label"), "cid=", (e.get("youtube_channel_id") or "")[:24], "sk_len=", len(str(e.get("stream_key") or "")), ) st, ag = get_json(op, f"{base}/api/youtube/assign/groups") groups = ag.get("groups") if isinstance(ag, dict) else [] print(f"assign groups={len(groups)} status={st}") missing = [] for g in groups: skv = str(g.get("stream_key") or "") title = g.get("title") or g.get("channel_title") or g.get("id") print( f" - {(title or '')[:40]!s} sk_len={len(skv)} cid={(g.get('youtube_channel_id') or '')[:20]}" ) if len(skv) < 12: missing.append(title) print("missing_or_short:", missing) return entries, groups dy_entries, dy_groups = summarize("dy", "https://dy.nomadro.live") dl_entries, dl_groups = summarize("dylive", "https://dylive.nomadro.com") # export registry from dy via SSH (authoritative) print("\n=== SSH export dy registry ===", flush=True) dy = ssh("108.174.50.68") out = run( dy, r""" cd /opt/douyinWEB/backend ./.venv/bin/python - <<'PY' import json from app import yt_stream_key_db, yt_assign_db exp = yt_stream_key_db.export_all() print('REG_START') print(json.dumps(exp, ensure_ascii=False)) print('REG_END') gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) print('ASSIGN_START') print(json.dumps([{ 'id': g.get('id'), 'name': g.get('name'), 'title': g.get('title') or g.get('name'), 'youtube_channel_id': g.get('youtube_channel_id'), 'stream_key': g.get('stream_key'), 'stream_key_len': len(str(g.get('stream_key') or '')), } for g in gs], ensure_ascii=False)) print('ASSIGN_END') print('reg_count', len((exp.get('items') or exp.get('entries') or []))) PY """, ) dy.close() print(out[-3000:], flush=True) a = out.find("REG_START") b = out.find("REG_END") assert a >= 0 and b > a reg = json.loads(out[a + len("REG_START") : b].strip()) c0 = out.find("ASSIGN_START") c1 = out.find("ASSIGN_END") assign_rows = json.loads(out[c0 + len("ASSIGN_START") : c1].strip()) # import to dylive print("\n=== import registry + fill missing assign keys on dylive ===", flush=True) dl = ssh("107.173.30.245") sftp = dl.open_sftp() with sftp.file("/tmp/dy_stream_key_export.json", "w") as f: f.write(json.dumps(reg, ensure_ascii=False)) with sftp.file("/tmp/dy_assign_keys.json", "w") as f: f.write(json.dumps(assign_rows, ensure_ascii=False)) sftp.close() print( run( dl, r""" cd /opt/douyinWEB/backend ./.venv/bin/python - <<'PY' import json from app import yt_stream_key_db, yt_assign_db with open('/tmp/dy_stream_key_export.json', encoding='utf-8') as f: reg = json.load(f) items = reg.get('items') or reg.get('entries') or [] print('import_result', yt_stream_key_db.import_payload(items, replace=False)) with open('/tmp/dy_assign_keys.json', encoding='utf-8') as f: rows = json.load(f) by_cid = {str(r.get('youtube_channel_id') or ''): r for r in rows if r.get('youtube_channel_id')} by_title = {str(r.get('title') or ''): r for r in rows} by_name = {str(r.get('name') or ''): r for r in rows} gs = yt_assign_db.list_groups(include_urls=False, include_secret=True) filled = 0 for g in gs: sk = str(g.get('stream_key') or '') if len(sk) >= 12: continue src = ( by_cid.get(str(g.get('youtube_channel_id') or '')) or by_title.get(str(g.get('title') or '')) or by_name.get(str(g.get('name') or '')) ) if not src or len(str(src.get('stream_key') or '')) < 12: print('NO_SRC', g.get('name') or g.get('title'), g.get('youtube_channel_id')) continue gid = g['id'] new_sk = src['stream_key'] try: yt_assign_db.update_group(gid, stream_key=new_sk) filled += 1 print('FILLED', g.get('name') or g.get('title'), 'len', len(new_sk)) except Exception as e: print('FAIL', g.get('name'), e) listed = yt_stream_key_db.list_entries(include_secret=True) print('registry_total', listed.get('total'), 'items', len(listed.get('items') or [])) print('filled', filled) gs2 = yt_assign_db.list_groups(include_urls=False, include_secret=True) full = sum(1 for g in gs2 if len(str(g.get('stream_key') or '')) >= 12) print('assign_full', full, 'of', len(gs2)) for g in gs2: print(' ', (g.get('name') or g.get('title') or '')[:36], 'sk', len(str(g.get('stream_key') or ''))) PY """, t=180, ), flush=True, ) dl.close() print("DONE")