Ship a health-management BMI home for review, keep the nomad hub as hub, and let admin switch platforms.tt.homeVariant live with track/ntfy; fix tt config fetch to api.nomadro.cn/api/config. Co-authored-by: Cursor <cursoragent@cursor.com>
176 lines
6.3 KiB
Python
176 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Deploy Douyin homeVariant A/B: admin SPA + API + seed remote-config."""
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
|
REPO = Path(__file__).resolve().parents[3]
|
|
ADMIN = REPO / "apps" / "admin"
|
|
API_SVC = REPO / "apps" / "api" / "services" / "ebook_svc"
|
|
|
|
|
|
def build_admin() -> Path:
|
|
print("building admin SPA (vite only)…", flush=True)
|
|
# monorepo 根 @types/react@19 会让 tsc -b 炸;生产只需要 vite bundle
|
|
r = subprocess.run(
|
|
["pnpm", "exec", "vite", "build"],
|
|
cwd=ADMIN,
|
|
shell=True,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
)
|
|
if r.returncode != 0:
|
|
print(r.stdout[-2000:] if r.stdout else "")
|
|
print(r.stderr[-2000:] if r.stderr else "")
|
|
raise SystemExit(f"admin build failed: {r.returncode}")
|
|
dist = ADMIN / "dist"
|
|
if not dist.is_dir():
|
|
raise SystemExit("no apps/admin/dist")
|
|
print((r.stdout or "")[-400:], flush=True)
|
|
print("build ok", flush=True)
|
|
return dist
|
|
|
|
|
|
def rewrite_app_imports(src: Path) -> str:
|
|
"""Local monorepo uses ebook_svc.*; production /opt/nomadmini uses app.*."""
|
|
text = src.read_text(encoding="utf-8")
|
|
return text.replace("ebook_svc.", "app.")
|
|
|
|
|
|
REMOTE_SH = r"""
|
|
set -euo pipefail
|
|
cd /tmp
|
|
rm -rf dy-hv-unpack && mkdir dy-hv-unpack
|
|
tar -xzf dy-home-variant.tar.gz -C dy-hv-unpack
|
|
|
|
echo "==> admin SPA"
|
|
sudo rsync -a --delete dy-hv-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
|
|
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
|
|
|
|
echo "==> API files"
|
|
B=/opt/nomadmini/backend/app
|
|
sudo cp dy-hv-unpack/api/douyin_admin.py "$B/routers/douyin_admin.py"
|
|
sudo cp dy-hv-unpack/api/tt_platform_config.py "$B/services/tt_platform_config.py"
|
|
if [ -f dy-hv-unpack/api/track.py ]; then
|
|
sudo cp dy-hv-unpack/api/track.py "$B/services/track.py"
|
|
fi
|
|
sudo chown ubuntu:ubuntu "$B/routers/douyin_admin.py" "$B/services/tt_platform_config.py" "$B/services/track.py" 2>/dev/null || true
|
|
|
|
echo "==> seed homeVariant (keep live modules/book)"
|
|
sudo python3 <<'PY'
|
|
import json
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
p = Path("/var/www/nomadro.cn/data/remote-config.json")
|
|
cfg = json.loads(p.read_text(encoding="utf-8"))
|
|
plats = cfg.setdefault("platforms", {})
|
|
tt = dict(plats.get("tt") or {})
|
|
if tt.get("homeVariant") not in ("bmi", "hub"):
|
|
tt["homeVariant"] = "bmi"
|
|
print("set homeVariant=bmi")
|
|
else:
|
|
print("keep homeVariant", tt.get("homeVariant"))
|
|
# ensure modules skeleton
|
|
mods = tt.setdefault("modules", {})
|
|
for key, title in (("nav", "出海导航"), ("book", "数字游民小册"), ("community", "旅居社群")):
|
|
if key not in mods or not isinstance(mods[key], dict):
|
|
mods[key] = {"enabled": False, "title": title, "tabLabel": title[:2]}
|
|
plats["tt"] = tt
|
|
cfg["platforms"] = plats
|
|
cfg["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
|
# backup
|
|
bak = p.with_suffix(".json.bak-homevariant")
|
|
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
|
|
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print("tt.homeVariant", tt.get("homeVariant"))
|
|
print("tt.mods", {k: (v or {}).get("enabled") for k, v in (tt.get("modules") or {}).items()})
|
|
PY
|
|
|
|
echo "==> restart API"
|
|
sudo systemctl restart nomadmini-api
|
|
sleep 3
|
|
systemctl is-active nomadmini-api
|
|
|
|
echo "==> smoke"
|
|
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
|
|
curl -sk -o /dev/null -w "douyin %{http_code}\n" https://admin.nomadro.cn/douyin
|
|
curl -sk -o /dev/null -w "meta_noauth %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/meta
|
|
|
|
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login \
|
|
-H 'Content-Type: application/json' \
|
|
-d '{"username":"admin","password":"Xiao4669805"}')
|
|
TOKEN=$(echo "$BODY" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
|
|
echo "token_len=${#TOKEN}"
|
|
if [ -n "$TOKEN" ]; then
|
|
curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config \
|
|
| python3 -c 'import sys,json; d=json.load(sys.stdin); c=d.get("config") or {}; print("ok", d.get("ok"), "homeVariant", c.get("homeVariant"), "mods", list((c.get("modules") or {}).keys()))'
|
|
fi
|
|
|
|
# SPA bundle should mention 首页变体 / homeVariant copy
|
|
grep -o '首页变体\|Home A / B\|BMI 健康管理\|homeVariant' /www/wwwroot/admin.nomadro.cn/assets/*.js 2>/dev/null | head -8 || true
|
|
|
|
rm -rf dy-hv-unpack dy-home-variant.tar.gz
|
|
echo DONE
|
|
"""
|
|
|
|
|
|
def main() -> int:
|
|
dist = build_admin()
|
|
|
|
buf = io.BytesIO()
|
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
|
for p in dist.rglob("*"):
|
|
if p.is_file():
|
|
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
|
|
|
|
for name, src in (
|
|
("api/douyin_admin.py", API_SVC / "routers" / "douyin_admin.py"),
|
|
("api/tt_platform_config.py", API_SVC / "services" / "tt_platform_config.py"),
|
|
("api/track.py", API_SVC / "services" / "track.py"),
|
|
):
|
|
data = rewrite_app_imports(src).encode("utf-8")
|
|
info = tarfile.TarInfo(name=name)
|
|
info.size = len(data)
|
|
tar.addfile(info, io.BytesIO(data))
|
|
|
|
buf.seek(0)
|
|
print(f"pack {buf.getbuffer().nbytes} bytes", flush=True)
|
|
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
|
sftp = c.open_sftp()
|
|
with sftp.file("/tmp/dy-home-variant.tar.gz", "wb") as rf:
|
|
rf.write(buf.read())
|
|
sftp.close()
|
|
print("uploaded", flush=True)
|
|
|
|
_, stdout, _ = c.exec_command(REMOTE_SH, timeout=240, get_pty=True)
|
|
while not stdout.channel.exit_status_ready():
|
|
if stdout.channel.recv_ready():
|
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
|
time.sleep(0.05)
|
|
while stdout.channel.recv_ready():
|
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
|
code = stdout.channel.recv_exit_status()
|
|
print(f"[exit {code}]", flush=True)
|
|
c.close()
|
|
return code
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|