nomadro/apps/admin/deploy/deploy.py
Eric de75f41816 Update WeChat miniprogram AppID and AppSecret to wx11f6afc44ea1532f.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 08:58:53 +08:00

176 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""Deploy nomadmini backend + admin to remote Ubuntu server."""
from __future__ import annotations
import io
import os
import stat
import sys
import tarfile
import tempfile
from pathlib import Path
import paramiko
from scp import SCPClient
ROOT = Path(__file__).resolve().parents[1]
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = os.environ.get("NOMADMINI_SSH_PASSWORD", "Xiao4669805")
REMOTE = "/opt/nomadmini"
def safe_print(text: str) -> None:
data = (text.rstrip() + "\n").encode("utf-8", errors="replace")
try:
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
except Exception:
print(data.decode("utf-8", errors="replace"), end="")
def run(client: paramiko.SSHClient, cmd: str, check: bool = True) -> tuple[int, str, str]:
print(f"$ {cmd}")
_, stdout, stderr = client.exec_command(cmd, get_pty=True)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
code = stdout.channel.recv_exit_status()
if out.strip():
safe_print(out)
if err.strip():
safe_print(err)
if check and code != 0:
raise RuntimeError(f"Command failed ({code}): {cmd}")
return code, out, err
def build_tarball() -> Path:
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
def should_skip(path: Path) -> bool:
skip_names = {".venv", "__pycache__", "node_modules", ".git", "dist"}
if any(p in skip_names for p in path.parts):
return True
if path.suffix in {".pyc", ".pyo"}:
return True
return False
with tarfile.open(tar_path, "w:gz") as tar:
backend = ROOT / "backend"
for p in backend.rglob("*"):
if p.is_file() and not should_skip(p.relative_to(backend)):
tar.add(p, arcname=f"backend/{p.relative_to(backend).as_posix()}")
admin_dist = ROOT / "dist"
if not admin_dist.exists():
raise FileNotFoundError("dist not found (run pnpm build in apps/admin), run npm run build first")
for p in admin_dist.rglob("*"):
if p.is_file():
tar.add(p, arcname=f"admin/dist/{p.relative_to(admin_dist).as_posix()}")
deploy = ROOT / "deploy"
for name in [
"nginx.nomadro.conf",
"nomadmini-api.service",
"remote-setup.sh",
"api.nomadro.cn.conf",
"admin.nomadro.cn.conf",
]:
p = deploy / name
if not p.exists():
continue
data = p.read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=f"deploy/{name}")
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
tar.addfile(tarfile.TarInfo(name="data/.keep"))
print(f"Created tarball: {tar_path} ({tar_path.stat().st_size // 1024} KB)")
return tar_path
def main() -> None:
tar_path = build_tarball()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(f"Connecting to {USER}@{HOST} ...")
client.connect(HOST, username=USER, password=PASSWORD, timeout=30)
try:
run(client, f"sudo mkdir -p {REMOTE} && sudo chown -R ubuntu:ubuntu {REMOTE}")
with SCPClient(client.get_transport()) as scp:
scp.put(str(tar_path), f"{REMOTE}/release.tar.gz")
run(
client,
f"cd {REMOTE} && rm -rf backend app deploy admin/dist && "
f"mkdir -p backend admin/dist data deploy && "
f"tar -xzf release.tar.gz && rm release.tar.gz",
)
env_content = """WX_APPID=wx11f6afc44ea1532f
WX_SECRET=04214ecc910dca4526781c90bae94da1
WX_OFFER_ID=1450642200
WX_APP_KEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
WX_SANDBOX_APP_KEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_PAY_ENV=0
JWT_SECRET=nomadro-jwt-prod-2026
ADMIN_USERNAME=hackrobot
ADMIN_PASSWORD=Xiao4669805@
PB_URL=http://127.0.0.1:8090
PB_ADMIN_EMAIL=admin@nomadro.cn
PB_ADMIN_PASSWORD=Xiao4669805
USE_POCKETBASE=false
DEBUG=false
PUBLIC_API_BASE=https://api.nomadro.cn
ADMIN_ORIGIN=https://admin.nomadro.cn
CORS_ORIGINS=https://admin.nomadro.cn,https://api.nomadro.cn
DEFAULT_PRODUCT_ID=ebook_unlock_default
DEFAULT_PRICE_FEN=18800
DEFAULT_UNLOCK_PERCENT=30
SQLITE_PATH=/opt/nomadmini/data/nomadmini.db
WX_PUSH_TOKEN=hackrobot
WX_PUSH_ENCODING_AES_KEY=ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI
WX_ALLOW_DEVTOOLS_LOGIN=true
"""
sftp = client.open_sftp()
with sftp.file(f"{REMOTE}/backend/.env", "w") as f:
f.write(env_content)
try:
sftp.chmod(f"{REMOTE}/deploy/remote-setup.sh", stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
except OSError:
pass
sftp.close()
run(
client,
"command -v nginx >/dev/null 2>&1 || "
"(sudo apt-get update -y && sudo DEBIAN_FRONTEND=noninteractive "
"apt-get install -y nginx python3-venv python3-pip curl)",
check=False,
)
run(client, f"bash {REMOTE}/deploy/remote-setup.sh")
_, out, _ = run(
client,
"curl -s http://127.0.0.1:8010/health || curl -s http://127.0.0.1:8000/health",
check=False,
)
print("Health:", out.strip())
finally:
client.close()
tar_path.unlink(missing_ok=True)
print("\nDeployed:")
print(" API: https://api.nomadro.cn")
print(" Admin: https://admin.nomadro.cn")
if __name__ == "__main__":
main()