Pairs Android devices over WSS for TikTok/YouTube preview and go-live from monitored Douyin sources; also spreads TikTok uploads across the Beijing day with per-channel claim cooldown. Co-authored-by: Cursor <cursoragent@cursor.com>
131 lines
6.8 KiB
Python
131 lines
6.8 KiB
Python
"""Deploy only Xposed files, preserving remote changes and live runtime data.
|
|
|
|
Credentials are supplied through DY_DEPLOY_HOST/USER/PASSWORD, never written to code.
|
|
Frontend is built in a staging directory and switched only after a successful build.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shlex
|
|
import sys
|
|
import time
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
REMOTE = "/opt/douyinWEB"
|
|
STAMP = time.strftime("%Y%m%d-%H%M%S")
|
|
STAGE = f"/opt/douyinweb-xposed-stage-{STAMP}"
|
|
BACKUP = f"/opt/douyinweb-xposed-backup-{STAMP}"
|
|
|
|
|
|
def run(client, command, timeout=900):
|
|
_, stdout, stderr = client.exec_command(command, timeout=timeout)
|
|
# Read stdout/stderr concurrently to avoid a full SSH pipe on a long Next build.
|
|
channel = stdout.channel
|
|
start = time.monotonic()
|
|
while not channel.exit_status_ready() or channel.recv_ready() or channel.recv_stderr_ready():
|
|
if channel.recv_ready():
|
|
print(channel.recv(32768).decode("utf-8", "replace"), end="", flush=True)
|
|
if channel.recv_stderr_ready():
|
|
print(channel.recv_stderr(32768).decode("utf-8", "replace"), end="", flush=True)
|
|
if time.monotonic()-start > timeout:
|
|
raise TimeoutError("Remote command timeout; inspect stage before retrying")
|
|
time.sleep(0.15)
|
|
code = channel.recv_exit_status()
|
|
if code:
|
|
raise RuntimeError(f"Remote command exited {code}")
|
|
|
|
|
|
def main():
|
|
client = paramiko.SSHClient()
|
|
client.load_system_host_keys()
|
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
client.connect(os.environ["DY_DEPLOY_HOST"], username=os.environ.get("DY_DEPLOY_USER", "root"),
|
|
password=os.environ["DY_DEPLOY_PASSWORD"], timeout=25, allow_agent=False, look_for_keys=False)
|
|
print("Backup:", BACKUP, "Stage:", STAGE, flush=True)
|
|
run(client, f"mkdir -p {shlex.quote(STAGE)}/backend/app {shlex.quote(STAGE)}/frontend/src/app/xposed {shlex.quote(STAGE)}/frontend/src/lib {shlex.quote(BACKUP)}")
|
|
sftp = client.open_sftp()
|
|
# Patch the live versions rather than copying local main/auth/nav files over remote work.
|
|
original = {}
|
|
for rel in ("backend/app/main.py", "backend/app/session_auth.py", "backend/app/auth.py", "frontend/src/lib/shellNav.ts"):
|
|
with sftp.open(f"{REMOTE}/{rel}", "rb") as f:
|
|
original[rel] = f.read()
|
|
contents = {k: v.decode("utf-8") for k, v in original.items()}
|
|
entry = contents["backend/app/main.py"]
|
|
if "app.include_router(xposed_router)" not in entry:
|
|
marker = 'app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)'
|
|
if entry.count(marker) != 1:
|
|
raise RuntimeError("Unexpected live FastAPI entrypoint; refusing blind replacement")
|
|
contents["backend/app/main.py"] = entry.replace(marker, marker + "\nfrom .xposed_control import router as xposed_router\napp.include_router(xposed_router)", 1)
|
|
for rel, marker in (("backend/app/session_auth.py", "_PUBLIC_API_EXACT = {"), ("backend/app/auth.py", "_PUBLIC_PATHS = {")):
|
|
if '"/api/xposed/device/enroll"' not in contents[rel]:
|
|
if contents[rel].count(marker) != 1:
|
|
raise RuntimeError("Unexpected auth middleware")
|
|
contents[rel] = contents[rel].replace(marker, marker + '\n "/api/xposed/device/enroll",\n "/api/xposed/device/source",\n "/api/xposed/device/ws",', 1)
|
|
nav = contents["frontend/src/lib/shellNav.ts"]
|
|
if 'href: "/xposed"' not in nav:
|
|
marker = ' { href: "/rooms", label: "直播间", emoji: "🏠" },'
|
|
if nav.count(marker) != 1:
|
|
raise RuntimeError("Unexpected live navigation")
|
|
contents["frontend/src/lib/shellNav.ts"] = nav.replace(marker, marker + '\n { href: "/xposed", label: "Xposed", emoji: "📱" },', 1)
|
|
for rel, value in contents.items():
|
|
with sftp.open(f"{STAGE}/{rel}", "wb") as f:
|
|
f.write(value.encode("utf-8"))
|
|
sftp.put(str(ROOT / "backend/app/xposed_control.py"), f"{STAGE}/backend/app/xposed_control.py")
|
|
sftp.put(str(ROOT / "frontend/src/app/xposed/page.tsx"), f"{STAGE}/frontend/src/app/xposed/page.tsx")
|
|
# Build a copy of the SERVER frontend so unrelated live UI fixes are preserved.
|
|
remote_script = f"""
|
|
set -eu
|
|
cp -a {REMOTE}/frontend/package.json {REMOTE}/frontend/package-lock.json {REMOTE}/frontend/next.config.mjs {REMOTE}/frontend/tsconfig.json {REMOTE}/frontend/tailwind.config.js {REMOTE}/frontend/postcss.config.js {STAGE}/frontend/
|
|
cp -a {REMOTE}/frontend/public {STAGE}/frontend/
|
|
cp -a {REMOTE}/frontend/src {STAGE}/frontend/server-src
|
|
cp -a {STAGE}/frontend/src/app/xposed {STAGE}/frontend/server-src/app/
|
|
cp -a {STAGE}/frontend/src/lib/shellNav.ts {STAGE}/frontend/server-src/lib/shellNav.ts
|
|
mv {STAGE}/frontend/src {STAGE}/frontend/patch-src
|
|
mv {STAGE}/frontend/server-src {STAGE}/frontend/src
|
|
ln -s {REMOTE}/frontend/node_modules {STAGE}/frontend/node_modules
|
|
cd {STAGE}/frontend
|
|
NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=1536 npm run build
|
|
"""
|
|
with sftp.open(f"{STAGE}/build.sh", "w") as f: f.write(remote_script)
|
|
sftp.close()
|
|
run(client, f"bash {STAGE}/build.sh")
|
|
|
|
# Exact remote backup of code and a consistent SQLite backup before additive schema writes.
|
|
commit_script = f"""
|
|
import pathlib, shutil, sqlite3, sys
|
|
root=pathlib.Path({REMOTE!r}); stage=pathlib.Path({STAGE!r}); backup=pathlib.Path({BACKUP!r})
|
|
sys.path.insert(0,str(root/'backend'))
|
|
from app.config import settings
|
|
source=sqlite3.connect(str(settings.sqlite_path)); target=sqlite3.connect(str(backup/'monitor.db'))
|
|
source.backup(target); target.close(); source.close()
|
|
files={list(contents)!r}+['backend/app/xposed_control.py','frontend/src/app/xposed/page.tsx']
|
|
for rel in files:
|
|
src=root/rel; dst=backup/rel; dst.parent.mkdir(parents=True,exist_ok=True)
|
|
if src.exists(): shutil.copy2(src,dst)
|
|
src.parent.mkdir(parents=True,exist_ok=True)
|
|
shutil.copy2(stage/rel,src.with_name(src.name+'.xposed-new'))
|
|
src.with_name(src.name+'.xposed-new').replace(src)
|
|
shutil.move(str(root/'frontend/.next'),str(backup/'frontend.next'))
|
|
shutil.move(str(stage/'frontend/.next'),str(root/'frontend/.next'))
|
|
print('Backups saved; Xposed code installed')
|
|
"""
|
|
sftp = client.open_sftp()
|
|
with sftp.open(f"{STAGE}/commit.py", "w") as f: f.write(commit_script)
|
|
sftp.close()
|
|
# Python env file is read from backend working directory.
|
|
run(client, f"cd {REMOTE}/backend && .venv/bin/python {STAGE}/commit.py")
|
|
run(client, f"cd {REMOTE}/backend && .venv/bin/python -m py_compile app/xposed_control.py app/main.py app/session_auth.py app/auth.py")
|
|
run(client, "systemctl restart douyinweb-api douyinweb-web && systemctl is-active douyinweb-api douyinweb-web")
|
|
client.close()
|
|
print("Deployed; validate HTTPS before removing stage/backup.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|