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

145 lines
4.4 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Deploy shared-Neko Studio attribution gate (false 「频道在播」 fix). Prefer dy; also dylive."""
from __future__ import annotations
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
LOCAL = ROOT / "backend" / "app" / "youtube_live.py"
DST = "/opt/douyinWEB/backend/app/youtube_live.py"
PASS = "Xiao4669805"
HOSTS = [
("dy", "108.174.50.68"),
("dylive", "107.173.30.245"),
]
VERIFY = r'''
import asyncio, os, sys, json
os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".")
from app import youtube_live
youtube_live._CACHE["at"] = 0.0
youtube_live._CACHE["payload"] = None
youtube_live._LAST_OAUTH_AT = 0.0
WATCH = {
"UCtVfMFdLTN4ap__8g7MFtVw": "nomad_vlog_space",
"UCO9wMc9tj9mD221Gu0rLBeA": "nomadvlog_timeslot",
}
async def main():
m = await youtube_live.build_live_map(force=True)
ents = m.get("entries") or {}
print("live_count", m.get("live_count"))
for k, v in sorted(ents.items()):
if not isinstance(v, dict) or not v.get("is_live"):
continue
if not (str(k).startswith("assign:") or str(k).startswith("channel:")):
continue
cid = str(v.get("channel_id") or "")
tag = WATCH.get(cid, "")
print(
"LIVE",
tag or "-",
k[:48],
"src=" + str(v.get("source") or ""),
"title=" + str(v.get("title") or "")[:40],
)
# Explicit offline check for nomad vlog (space card) if present
for k, v in ents.items():
if not isinstance(v, dict):
continue
if str(v.get("channel_id") or "") != "UCtVfMFdLTN4ap__8g7MFtVw":
continue
print(
"CHECK_nomad_vlog",
k[:56],
"is_live=" + str(bool(v.get("is_live"))),
"src=" + str(v.get("source") or ""),
)
asyncio.run(main())
'''
def connect(host: str):
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=90,
)
return c
except Exception as e:
print(f"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:
_, o, e = c.exec_command(cmd, timeout=t)
try:
return (o.read() + e.read()).decode("utf-8", "replace")
except Exception as ex:
return f"ERR {type(ex).__name__}: {ex}"
def deploy(label: str, host: str):
print(f"\n===== {label} {host} =====", flush=True)
c = connect(host)
sftp = c.open_sftp()
with sftp.file("/tmp/_youtube_live.py", "wb") as f:
f.write(LOCAL.read_bytes())
with sftp.file("/tmp/_verify_shared_neko.py", "w") as f:
f.write(VERIFY)
sftp.close()
print(run(c, f"cp -a {DST} {DST}.bak_shared_neko && cat /tmp/_youtube_live.py > {DST} && echo PUT_OK", 30).strip(), flush=True)
print(
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
"\"from app.youtube_live import _studio_snap_belongs_to_assign_group; print('import_ok', _studio_snap_belongs_to_assign_group)\"",
40,
).strip(),
flush=True,
)
run(c, "systemctl restart douyinweb-api >/tmp/_api_restart.txt 2>&1 &", 15)
for i in range(18):
time.sleep(2)
h = run(c, "curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x").strip()
print(f" health try{i} {h}", flush=True)
if h == "200":
break
if i == 8:
run(
c,
"systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api",
40,
)
print(run(c, "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_shared_neko.py", 240)[:3000], flush=True)
c.close()
def main():
if not LOCAL.is_file():
raise SystemExit(f"missing {LOCAL}")
for label, host in HOSTS:
deploy(label, host)
if __name__ == "__main__":
main()