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

234 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Deploy latest project sources to BOTH VPS (dy + dylive): backend critical + FE rebuild sync."""
from __future__ import annotations
import hashlib
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805"
# Full set of files that must match local workspace on both hosts.
SYNC_FILES = [
"backend/app/douyin.py",
"backend/app/session_auth.py",
"backend/app/youtube_neko.py",
"backend/app/youtube_relay_pipeline.py",
"backend/app/youtube_relay_status.py",
"backend/app/pb_sync.py",
"backend/app/main.py",
"backend/app/yt_assign_db.py",
"backend/tests/test_prefer_non_uhd_stream.py",
"frontend/src/lib/api.js",
"frontend/src/components/YtRelayProStatusPanel.tsx",
"frontend/src/components/OpsNekoHubCredentialsCard.tsx",
"frontend/src/components/YtAssignPanel.tsx",
"README.md",
]
def connect(host: str):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(12):
try:
c.connect(
host,
22,
"root",
PASS,
timeout=45,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
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, script: str, timeout: int = 900) -> str:
_i, o, e = c.exec_command(script, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def put_file(c, local: Path, remote: str):
sftp = c.open_sftp()
# ensure parent
remote_dir = "/".join(remote.split("/")[:-1])
run(c, f"mkdir -p {remote_dir}", timeout=30)
with sftp.file(remote, "wb") as f:
f.write(local.read_bytes())
sftp.close()
def sha12(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()[:12]
print("LOCAL hashes:", flush=True)
for rel in SYNC_FILES:
p = ROOT / rel.replace("/", "\\")
if not p.exists():
print("MISSING_LOCAL", rel, flush=True)
continue
print(f" {sha12(p)} {rel}", flush=True)
# --- DY first: upload + pytest + API restart + FE build ---
print("\n######## DEPLOY dy 108.174.50.68 ########", flush=True)
c = connect(DY)
for rel in SYNC_FILES:
p = ROOT / rel.replace("/", "\\")
if not p.exists():
continue
put_file(c, p, f"/opt/douyinWEB/{rel}")
print("put", 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",
"FULL_HD1":"http://x/a_fhd.flv",
}}}
c=pick_stream_candidates(room)
print('pick0', c[0])
assert 'a_hd.flv' in c[0], c
assert '_uhd' in c[-1] or 'uhd' in c[-1]
print('non_uhd_ok')
PY
systemctl restart douyinweb-api
sleep 2
systemctl is-active douyinweb-api
cd /opt/douyinWEB/frontend
export NODE_OPTIONS=--max-old-space-size=3072
npm run build 2>&1 | tail -30
systemctl restart douyinweb-web
sleep 2
systemctl is-active douyinweb-web
tar -C /opt/douyinWEB/frontend -czf /tmp/next-dual-sync.tgz .next
tar -C /opt/douyinWEB -czf /tmp/src-dual-sync.tgz \
backend/app/douyin.py \
backend/app/session_auth.py \
backend/app/youtube_neko.py \
backend/app/youtube_relay_pipeline.py \
backend/app/youtube_relay_status.py \
backend/app/pb_sync.py \
backend/app/main.py \
backend/app/yt_assign_db.py \
backend/tests/test_prefer_non_uhd_stream.py \
frontend/src/lib/api.js \
frontend/src/components/YtRelayProStatusPanel.tsx \
frontend/src/components/OpsNekoHubCredentialsCard.tsx \
frontend/src/components/YtAssignPanel.tsx \
README.md
ls -lh /tmp/next-dual-sync.tgz /tmp/src-dual-sync.tgz
""",
timeout=900,
),
flush=True,
)
sftp = c.open_sftp()
sftp.get("/tmp/next-dual-sync.tgz", str(ROOT / "scripts/_next-dual-sync.tgz"))
sftp.get("/tmp/src-dual-sync.tgz", str(ROOT / "scripts/_src-dual-sync.tgz"))
sftp.close()
c.close()
# --- DYLIVE: extract src + .next, restart ---
print("\n######## DEPLOY dylive 107.173.30.245 ########", flush=True)
c = connect(DYLIVE)
put_file(c, ROOT / "scripts/_src-dual-sync.tgz", "/tmp/src-dual-sync.tgz")
put_file(c, ROOT / "scripts/_next-dual-sync.tgz", "/tmp/next-dual-sync.tgz")
print(
run(
c,
r"""
set -e
tar -C /opt/douyinWEB -xzf /tmp/src-dual-sync.tgz
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('inline_ok')
PY
systemctl restart douyinweb-api
systemctl stop douyinweb-web || true
rm -rf /opt/douyinWEB/frontend/.next.bak_dual
mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_dual 2>/dev/null || true
tar -C /opt/douyinWEB/frontend -xzf /tmp/next-dual-sync.tgz
systemctl start douyinweb-web
sleep 2
systemctl is-active douyinweb-api douyinweb-web
python3 - <<'PY'
import hashlib, pathlib
for rel in [
'backend/app/douyin.py',
'backend/app/session_auth.py',
'backend/app/youtube_neko.py',
'frontend/src/lib/api.js',
'frontend/src/components/YtRelayProStatusPanel.tsx',
]:
p=pathlib.Path('/opt/douyinWEB')/rel
print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel)
PY
# show ladder comment present
grep -n 'Prefer non-UHD\|HD1 → FULL_HD1\|prefer \*\*non-UHD\*\*' /opt/douyinWEB/backend/app/douyin.py | head -5
""",
timeout=180,
),
flush=True,
)
c.close()
# verify hashes match local
print("\n######## HASH VERIFY ########", flush=True)
local = {rel: sha12(ROOT / rel.replace("/", "\\")) for rel in SYNC_FILES if (ROOT / rel.replace("/", "\\")).exists()}
for label, host in [("dy", DY), ("dylive", DYLIVE)]:
c = connect(host)
out = run(
c,
"python3 - <<'PY'\n"
"import hashlib, pathlib\n"
"files=" + repr([r for r in SYNC_FILES if r.startswith('backend/') or r.startswith('frontend/')]) + "\n"
"root=pathlib.Path('/opt/douyinWEB')\n"
"for rel in files:\n"
" p=root/rel\n"
" print(hashlib.sha256(p.read_bytes()).hexdigest()[:12] if p.exists() else 'MISSING', rel)\n"
"PY",
timeout=60,
)
print(label, flush=True)
mismatch = 0
for line in out.splitlines():
parts = line.strip().split(None, 1)
if len(parts) != 2:
continue
h, rel = parts
exp = local.get(rel)
ok = exp and h == exp
if exp and not ok:
mismatch += 1
print(f" MISMATCH {rel} remote={h} local={exp}", flush=True)
else:
print(f" OK {h} {rel}", flush=True)
print(f" mismatches={mismatch}", flush=True)
c.close()
print("ALL_DONE", flush=True)