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

116 lines
4.1 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Deploy youtubei+OAuth assign live-map; verify both hosts match."""
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"
VERIFY = r'''
import asyncio, os, sys
os.chdir("/opt/douyinWEB/backend"); sys.path.insert(0, ".")
from app import youtube_live, yt_assign_db, db
async def main():
youtube_live._LAST_OAUTH_AT = 0.0 # force OAuth this tick
gs = [g for g in yt_assign_db.list_groups(include_urls=False) if g.get("enabled")]
with_pk = 0
with_tok = 0
for g in gs:
pk = str(g.get("channel_pk") or "").strip()
cid = str(g.get("youtube_channel_id") or "").strip()
tok = False
if pk:
with_pk += 1
ch = db.get_shorts_channel(pk) or {}
tok = bool(str(ch.get("refresh_token") or "").strip())
if tok:
with_tok += 1
print(f" card {g.get('name')} cid={cid} pk={pk[:8] if pk else '-'} oauth_token={tok}")
print("cards", len(gs), "with_pk", with_pk, "with_oauth_token", with_tok)
m = await youtube_live.build_live_map(force=True)
entries = m.get("entries") or {}
live = [(k, v.get("source"), (v.get("title") or "")[:36]) for k, v in entries.items() if v.get("is_live")]
assign_live = [x for x in live if x[0].startswith("assign:")]
print("live_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:80])
print("assign_live", len(assign_live), "all_live_entries", len(live))
for row in assign_live:
print(" LIVE", row)
# sample offline public answers
n_yt = n_oa = 0
for k, v in entries.items():
if not k.startswith("assign:"):
continue
s = str(v.get("source") or "")
if s == "youtubei":
n_yt += 1
if s.startswith("oauth"):
n_oa += 1
print("assign_entries_youtubei_src", n_yt, "oauth_src", n_oa)
asyncio.run(main())
'''
def run(c, cmd, t=120):
_, o, e = c.exec_command(cmd, timeout=t)
o.channel.settimeout(t)
try:
return (o.read() + e.read()).decode("utf-8", "replace")
except Exception as ex:
return f"ERR {type(ex).__name__}: {ex}"
def deploy(host, port, user, pw, sudo=False):
print(f"\n===== {user}@{host}:{port} =====")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, port, user, pw, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/_yt_live_oa.py", "wb") as f:
f.write(LOCAL.read_bytes())
with sftp.file("/tmp/_verify_oa_live.py", "w") as f:
f.write(VERIFY)
sftp.close()
dst = "/opt/douyinWEB/backend/app/youtube_live.py"
if sudo:
print(run(c, f"echo '{pw}' | sudo -S -p '' bash -lc \"cat /tmp/_yt_live_oa.py > {dst}\"", 30).strip())
run(c, f"echo '{pw}' | sudo -S -p '' systemctl restart douyinweb-api", 45)
else:
print(run(c, f"cat /tmp/_yt_live_oa.py > {dst} && echo OK", 20).strip())
run(c, "systemctl restart douyinweb-api >/tmp/_rst.log 2>&1 &", 10)
for i in range(12):
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", 10).strip()
a = run(c, "systemctl is-active douyinweb-api", 8).strip()
print(f" try{i} {a} {h}")
if h == "200":
break
if "deactivat" in a and i == 5:
run(
c,
"systemctl kill -s SIGKILL douyinweb-api; systemctl reset-failed douyinweb-api; systemctl start douyinweb-api",
30,
)
py = "/opt/douyinWEB/backend/.venv/bin/python /tmp/_verify_oa_live.py"
if sudo:
py = f"echo '{pw}' | sudo -S -p '' {py}"
print(run(c, py, 180)[:3500])
c.close()
def main():
deploy("107.173.30.245", 22, "root", "Xiao4669805", False)
deploy("107.173.30.245", 4014, "eric", "4669805", True)
if __name__ == "__main__":
main()