nomadro/apps/admin/deploy/deploy_memo.py
Eric 3f7528f824 Add VIP knowledge community and device shop with native weapp UX.
Document memo/shop admin routes, deploy scripts, and cache-first feed performance in README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 16:58:17 +08:00

206 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Deploy VIP 社群 (memo feed) admin + API to 82.157.112.245."""
from __future__ import annotations
import io
import subprocess
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
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.")
def _remote_script() -> str:
return r'''#!/bin/bash
set -euo pipefail
cd /tmp
rm -rf memo-unpack && mkdir memo-unpack
tar -xzf memo-release.tar.gz -C memo-unpack
if [ -d memo-unpack/admin-dist ]; then
sudo rsync -a --delete memo-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
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 memo-unpack/backend/routers/memo.py "$B/routers/"
sudo cp memo-unpack/backend/routers/memo_admin.py "$B/routers/"
sudo cp memo-unpack/backend/services/memo_store.py "$B/services/"
MAIN="$B/main.py"
export MAIN
sudo -E python3 <<'PY'
from pathlib import Path
import os, re
p = Path(os.environ["MAIN"])
t = p.read_text(encoding="utf-8")
changed = False
m = re.search(r"from app\.routers import ([^\n]+)", t)
if not m:
raise SystemExit("no routers import")
line = m.group(0)
names = m.group(1)
parts = [x.strip() for x in names.split(",")]
for mod in ("memo", "memo_admin"):
if mod not in parts:
names = names.rstrip() + f", {mod}"
changed = True
print("import +", mod)
newt = f"from app.routers import {names}"
if newt != line:
t = t.replace(line, newt, 1)
changed = True
if "include_router(memo.router" not in t:
if re.search(r"app\.include_router\(shop\.router,\s*prefix=_api_prefix\)", t):
t = re.sub(
r"(app\.include_router\(shop\.router,\s*prefix=_api_prefix\))",
r"\1\n app.include_router(memo.router, prefix=_api_prefix)",
t,
count=1,
)
changed = True
print("memo in _api_prefix loop")
elif re.search(r"app\.include_router\(track\.router,\s*prefix=_api_prefix\)", t):
t = re.sub(
r"(app\.include_router\(track\.router,\s*prefix=_api_prefix\))",
r"\1\n app.include_router(memo.router, prefix=_api_prefix)",
t,
count=1,
)
changed = True
print("memo after track loop")
else:
raise SystemExit("failed memo include in loop")
if "include_router(memo_admin.router)" not in t:
for a in (
"app.include_router(shop_admin.router)",
"app.include_router(vip_admin.router)",
"app.include_router(admin.router)",
):
if a in t:
t = t.replace(a, a + "\napp.include_router(memo_admin.router)", 1)
changed = True
print("memo_admin after", a)
break
if "include_router(memo_admin.router)" not in t:
raise SystemExit("failed memo_admin include")
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
sudo systemctl restart nomadmini-api
sleep 5
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 "memo_page %{http_code}\n" https://admin.nomadro.cn/wechat/memo
curl -sk http://127.0.0.1:8010/health; echo
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/memo | python3 -c "import sys,json; d=json.load(sys.stdin); print('memo_admin', d.get('ok'), d.get('stats'), (d.get('settings') or {}).get('canPost'))"
fi
curl -sk http://127.0.0.1:8010/openapi.json | python3 -c "import sys,json; p=json.load(sys.stdin).get('paths') or {}; ks=[k for k in p if 'memo' in k]; print('memo_paths', len(ks), ks[:10])"
rm -rf memo-unpack memo-release.tar.gz
echo DONE
'''
def main() -> int:
print("building admin…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
print((r.stdout or "")[-600:], flush=True)
if r.returncode != 0:
print(r.stderr or "", flush=True)
return r.returncode or 1
dist = ROOT / "dist"
if not (dist / "index.html").exists():
print("missing admin dist")
return 1
files = (
("backend/routers/memo.py", EBOOK / "routers" / "memo.py"),
("backend/routers/memo_admin.py", EBOOK / "routers" / "memo_admin.py"),
("backend/services/memo_store.py", EBOOK / "services" / "memo_store.py"),
)
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 files:
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)
remote = _remote_script()
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/memo-release.tar.gz", "wb") as rf:
rf.write(payload)
with sftp.file("/tmp/memo-deploy.sh", "w") as sf:
sf.write(remote.replace("\r\n", "\n"))
sftp.chmod("/tmp/memo-deploy.sh", 0o755)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command("bash /tmp/memo-deploy.sh", timeout=300, 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())