# -*- coding: utf-8 -*- """Deploy recent bugfix pack to physical guest (FRP :4014) and rebuild Next.""" from __future__ import annotations import sys import time from pathlib import Path import httpx import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = Path(__file__).resolve().parents[1] VPS = "107.173.30.245" PASS = "4669805" FILES = [ ("backend/app/yt_assign_db.py", "/opt/douyinWEB/backend/app/yt_assign_db.py", "_bf_yt_assign_db.py"), ("backend/app/youtube_neko.py", "/opt/douyinWEB/backend/app/youtube_neko.py", "_bf_youtube_neko.py"), ("backend/app/shorts_oauth.py", "/opt/douyinWEB/backend/app/shorts_oauth.py", "_bf_shorts_oauth.py"), ("backend/app/shorts_upload.py", "/opt/douyinWEB/backend/app/shorts_upload.py", "_bf_shorts_upload.py"), ("backend/app/yt_long_upload.py", "/opt/douyinWEB/backend/app/yt_long_upload.py", "_bf_yt_long_upload.py"), ("backend/app/config.py", "/opt/douyinWEB/backend/app/config.py", "_bf_config.py"), ("backend/app/main.py", "/opt/douyinWEB/backend/app/main.py", "_bf_main.py"), ( "frontend/src/components/YtAssignPanel.tsx", "/opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx", "_bf_YtAssignPanel.tsx", ), ( "frontend/src/components/YtRelayProStatusPanel.tsx", "/opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx", "_bf_YtRelayProStatusPanel.tsx", ), ( "frontend/src/app/shorts/page.tsx", "/opt/douyinWEB/frontend/src/app/shorts/page.tsx", "_bf_shorts_page.tsx", ), ] REMOTE_SH = r"""#!/bin/bash set -euo pipefail TS=$(date +%s) install_one() { local src="$1" dst="$2" cp -a "$dst" "${dst}.bak-bugfix-${TS}" 2>/dev/null || true install -m 644 "$src" "$dst" } install_one /tmp/_bf_yt_assign_db.py /opt/douyinWEB/backend/app/yt_assign_db.py install_one /tmp/_bf_youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py install_one /tmp/_bf_shorts_oauth.py /opt/douyinWEB/backend/app/shorts_oauth.py install_one /tmp/_bf_shorts_upload.py /opt/douyinWEB/backend/app/shorts_upload.py install_one /tmp/_bf_yt_long_upload.py /opt/douyinWEB/backend/app/yt_long_upload.py install_one /tmp/_bf_config.py /opt/douyinWEB/backend/app/config.py install_one /tmp/_bf_main.py /opt/douyinWEB/backend/app/main.py install_one /tmp/_bf_YtAssignPanel.tsx /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx install_one /tmp/_bf_YtRelayProStatusPanel.tsx /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx install_one /tmp/_bf_shorts_page.tsx /opt/douyinWEB/frontend/src/app/shorts/page.tsx cd /opt/douyinWEB/backend .venv/bin/python -m py_compile \ app/yt_assign_db.py app/youtube_neko.py app/shorts_oauth.py \ app/shorts_upload.py app/yt_long_upload.py app/config.py app/main.py echo COMPILE_OK SVC=/etc/systemd/system/douyinweb-api.service cp -a "$SVC" "$SVC.bak-bugfix-${TS}" sed -i '/Environment=DY_NEKO_GATEWAY_ENABLED=/d' "$SVC" sed -i '/Environment=DY_NEKO_MAX_INSTANCES=/d' "$SVC" # Insert after [Service] so unit picks preferred native-edge defaults. awk ' {print} /^\[Service\]$/ && !done { print "Environment=DY_NEKO_GATEWAY_ENABLED=0" print "Environment=DY_NEKO_MAX_INSTANCES=64" done=1 } ' "$SVC" > /tmp/_api.unit.bugfix install -m 644 /tmp/_api.unit.bugfix "$SVC" systemctl daemon-reload systemctl restart douyinweb-api sleep 4 systemctl is-active douyinweb-api systemctl stop douyinweb-web || true cd /opt/douyinWEB/frontend npm run build systemctl start douyinweb-web sleep 3 systemctl is-active douyinweb-web echo BUILD_OK """ AUDIT_PY = r''' import sqlite3, json p="/opt/douyinWEB/backend/data/monitor.db" con=sqlite3.connect(f"file:{p}?mode=ro", uri=True) con.row_factory=sqlite3.Row print("=== shorts youtube_channel_id dups ===") rows=con.execute(""" SELECT youtube_channel_id, COUNT(*) n, GROUP_CONCAT(id,'|') ids, GROUP_CONCAT(name,'|') names FROM shorts_channels WHERE youtube_channel_id IS NOT NULL AND trim(youtube_channel_id)!='' GROUP BY youtube_channel_id HAVING n>1 """).fetchall() print(json.dumps([dict(r) for r in rows], ensure_ascii=False, indent=2)) print("=== yt_long orphans (no matching shorts id) ===") rows=con.execute(""" SELECT yl.id, yl.name, yl.youtube_channel_id, yl.source_shorts_channel_pk FROM yt_long_channels yl WHERE yl.source_shorts_channel_pk IS NOT NULL AND trim(yl.source_shorts_channel_pk)!='' AND NOT EXISTS (SELECT 1 FROM shorts_channels s WHERE s.id=yl.source_shorts_channel_pk) """).fetchall() print(json.dumps([dict(r) for r in rows], ensure_ascii=False, indent=2)) print("=== assign groups ===") r=con.execute( "SELECT COUNT(*) AS groups, COALESCE(MAX(neko_instance_id),0) AS max_neko FROM yt_assign_groups" ).fetchone() print(dict(r)) ''' def ssh(tries: int = 12): last = None for i in range(tries): try: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( VPS, 4014, "eric", PASS, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False, ) return c except Exception as ex: last = ex print(f"ssh fail{i} {type(ex).__name__}", flush=True) time.sleep(2 + i) raise last # type: ignore[misc] def run(c, cmd: str, timeout: int = 300) -> str: _, o, e = c.exec_command(cmd, timeout=timeout) out = (o.read() + e.read()).decode("utf-8", "replace") print(out[-12000:] if len(out) > 12000 else out, flush=True) return out def main() -> int: missing = [rel for rel, _, _ in FILES if not (ROOT / rel).is_file()] if missing: raise SystemExit(f"missing local files: {missing}") g = ssh() sftp = g.open_sftp() for rel, _remote, tmp_name in FILES: data = (ROOT / rel).read_text(encoding="utf-8") with sftp.file(f"/tmp/{tmp_name}", "w") as f: f.write(data) print(f"uploaded {rel}", flush=True) with sftp.file("/tmp/_bugfix_physical.sh", "w") as f: f.write(REMOTE_SH) with sftp.file("/tmp/_bugfix_audit.py", "w") as f: f.write(AUDIT_PY) sftp.close() print("=== install + compile + restart api + npm build ===", flush=True) out = run( g, f"echo '{PASS}' | sudo -S -p '' bash /tmp/_bugfix_physical.sh", timeout=900, ) if "COMPILE_OK" not in out or "BUILD_OK" not in out: print("DEPLOY INCOMPLETE", flush=True) g.close() return 1 print("=== audit ===", flush=True) run(g, f"echo '{PASS}' | sudo -S -p '' python3 /tmp/_bugfix_audit.py", timeout=60) g.close() print("=== public health ===", flush=True) for url in ( "https://dy.nomadro.com/api/health", "https://dy.nomadro.cn/api/health", ): try: r = httpx.get(url, timeout=25) print(url, r.status_code, r.text[:220], flush=True) except Exception as ex: print(url, type(ex).__name__, ex, flush=True) print("DONE — hard refresh dy.nomadro.com / dy.nomadro.cn", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())