nomadro/apps/admin/deploy/deploy_vip_admin.py
Eric 9779b80d25 Ship WeChat admin UX overhaul and VIP content library.
Restructure /wechat nav (VIP submenu for ebooks/course/shop/memo), rebuild ops pages with shared wx UI, and wire vip-library remote content end-to-end with README paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 09:59:57 +08:00

260 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""Deploy WeChat VIP admin UI + API (additive; does not wipe remote-config / orders / users).
- Admin SPA → /www/wwwroot/admin.nomadro.cn
- New vip_admin / vip_config + patch main.py (idempotent)
- remote-config: ONLY add missing keys (joinGroupAction=popup, game.enabled=false)
never overwrite existing flags/modules/platforms/copy values
- Restart nomadmini-api (fast); does not touch SQLite / ebook content
"""
from __future__ import annotations
import io
import subprocess
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1] # apps/admin
REPO = ROOT.parents[1]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf vip-unpack && mkdir vip-unpack
tar -xzf vip-release.tar.gz -C vip-unpack
# --- admin SPA (static only) ---
if [ -d vip-unpack/admin-dist ]; then
sudo rsync -a --delete vip-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
# --- API additive files ---
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then
API_ROOT=/opt/nomadmini/backend
fi
echo API_ROOT=$API_ROOT
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
sudo mkdir -p "$B/routers" "$B/services"
sudo cp vip-unpack/backend/routers/vip_admin.py "$B/routers/"
sudo cp vip-unpack/backend/services/vip_config.py "$B/services/"
sudo cp vip-unpack/backend/services/vip_content.py "$B/services/"
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
# ensure import
if "vip_admin" not in t:
for old, new in (
(
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track, vip_admin",
),
(
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track, vip_admin",
),
(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, pay, track, vip_admin",
),
):
if old in t:
t = t.replace(old, new, 1)
changed = True
break
if "vip_admin" not in t:
raise SystemExit("failed to patch vip_admin import")
# ensure include_router
if "include_router(vip_admin.router)" not in t:
for needle in (
"app.include_router(join_group_admin.router)",
"app.include_router(public_config.router)",
"app.include_router(douyin_admin.router)",
):
if needle in t:
t = t.replace(needle, needle + "\napp.include_router(vip_admin.router)", 1)
changed = True
break
if "include_router(vip_admin.router)" not in t:
raise SystemExit("failed to patch vip_admin include_router")
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
# remote-config: ADDITIVE ONLY — defaults closed; never overwrite existing values
for CFG in /var/www/nomadro.cn/data/remote-config.json /www/wwwroot/nomadro.cn/data/remote-config.json; do
if [ -f "$CFG" ]; then
echo "seed $CFG"
sudo python3 <<PY
import json
from pathlib import Path
p = Path("$CFG")
cfg = json.loads(p.read_text(encoding="utf-8"))
flags = cfg.setdefault("flags", {})
modules = cfg.setdefault("modules", {})
changed = False
if "joinGroupAction" not in flags:
flags["joinGroupAction"] = "popup"
changed = True
game = modules.get("game")
if not isinstance(game, dict):
modules["game"] = {"enabled": False, "title": "Nomad Day 3D", "note": "default hidden"}
changed = True
elif "enabled" not in game:
game = dict(game)
game["enabled"] = False
modules["game"] = game
changed = True
vip = modules.get("vip")
if not isinstance(vip, dict):
modules["vip"] = {"enabled": False, "title": "会员中心"}
changed = True
# do NOT flip existing vip.enabled — preserves online if already on
if changed:
cfg["flags"] = flags
cfg["modules"] = modules
try:
cfg["version"] = int(cfg.get("version") or 1) + 1
except Exception:
cfg["version"] = 2
bak = p.with_suffix(p.suffix + ".bak-vip-seed")
try:
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
except Exception:
pass
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("remote-config additive seed ok")
else:
print("remote-config already has keys; untouched values")
print("joinGroupAction=", flags.get("joinGroupAction"), "game=", modules.get("game"), "vip=", modules.get("vip"))
PY
fi
done
sudo systemctl restart nomadmini-api
sleep 4
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 "wechat_vip_page %{http_code}\n" https://admin.nomadro.cn/wechat/vip
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" || true)
echo "token_len=${#TOK}"
if [ -n "$TOK" ]; then
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip | python3 -c "
import sys,json
d=json.load(sys.stdin)
vc=d.get('vipContent') or {}
print('vip_api', d.get('ok'), d.get('vipOfferKey'), d.get('vipCta'), d.get('vipProductId'), d.get('is_free'))
print('vipContent', bool(vc), 'topics', len(vc.get('topics') or []), 'showCta', vc.get('showCta'), 'hero', (vc.get('heroTitleAccent') or '')[:12])
print('price_untouched', d.get('vipPriceFen'), d.get('vipProductId'))
"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/product-offers | python3 -c "import sys,json; d=json.load(sys.stdin); print('offers', len(d.get('items') or []))"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/stats | python3 -c "import sys,json; d=json.load(sys.stdin); print('stats_ok', 'users' in d, 'paid_orders' in d)"
# platforms.tt must still exist if present; public config must expose platforms
curl -sk https://api.nomadro.cn/api/config | python3 -c "
import sys,json
d=json.load(sys.stdin)
cfg=d.get('config') or d
plats=cfg.get('platforms') or {}
print('public_platforms', sorted(plats.keys()), 'weapp_vip', isinstance((plats.get('weapp') or {}).get('vipContent'), dict) or 'weapp' not in plats)
print('tt_present', 'tt' in plats)
print('copy_vipPriceFen', (cfg.get('copy') or {}).get('vipPriceFen'))
"
fi
rm -rf vip-unpack vip-release.tar.gz
echo DONE
"""
def main() -> int:
print("building admin (vite only; skip tsc type friction)…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
out = (r.stdout or "").encode("ascii", "replace").decode("ascii")
print(out[-800:], flush=True)
if r.returncode != 0:
err = (r.stderr or "").encode("ascii", "replace").decode("ascii")
print(err, flush=True)
return r.returncode or 1
dist = ROOT / "dist"
if not (dist / "index.html").exists():
print("missing admin dist")
return 1
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 (
("backend/routers/vip_admin.py", EBOOK / "routers" / "vip_admin.py"),
("backend/services/vip_config.py", EBOOK / "services" / "vip_config.py"),
("backend/services/vip_content.py", EBOOK / "services" / "vip_content.py"),
):
text = to_app_pkg(src.read_text(encoding="utf-8")).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(text)
tar.addfile(info, io.BytesIO(text))
payload = buf.getvalue()
print(f"pack {len(payload)/1024:.1f} KB", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/vip-release.tar.gz", "wb") as rf:
rf.write(payload)
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()
c.close()
print(f"[exit {code}]", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())