diff --git a/AGENTS.md b/AGENTS.md index 3537778..969d615 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ Follow `.cursor/rules/*.mdc`. 根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:api` / `typecheck` / `clean`。 -Remote config: `/api/config` + offline defaults. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`). +Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`). **全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。 diff --git a/README.md b/README.md index 64bf90a..a33f256 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,10 @@ pnpm dev:api - **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config` - **禁止**再引入已删垂直树(见 `AGENTS.md`) - **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准 -- 审核冻结分支:`pre4`(**微信审核包,勿在本分支继续功能迭代**) +- 审核冻结分支:`pre4`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`** - `pre5`:承接 pre4 之后的功能(含游民社区 `/social`) -- `test5` / `test6`:游民社区实时层与 H5 初版(已合入后续分支) -- **当前开发分支:`test8`**(从 `test7` 拉出);发版线 `test7` 已含 H5 深优 +- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`) +- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`) ### 游民社区(`/social`) @@ -182,9 +182,31 @@ pnpm dev:api - **Meetup**:活动卡保留参与者头像 + 声纹条 - **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social` -## test8(当前开发) +## test8 -从 `test7` 切出,承接后续 `/social` 与门户迭代。后续还可做:课时资料后台可视化、桥接 UX、真机网络/域名排查。 +从 `test7` 切出;原生 weapp 游民社区、SRS 直播、加群支付等已合入 `test9`。 + +## test9 · tag `2026-11-02`(微信提审包) + +从 `test8` / `f204063` 线切出并定版,准备上传微信审核与上线。 + +| 项 | 说明 | +|---|---| +| 分支 / Tag | `test9` · **`2026-11-02`** | +| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) | +| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` | +| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 audit 正文(失联才包内兜底);关则正式 nomad | +| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` | +| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` | +| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) | + +提审上传: + +```bash +pnpm build:weapp +# 微信开发者工具打开 apps/miniprogram/weapp(miniprogramRoot=dist/)→ 上传 +# 后台按需打开「数字游民」提审;socket 合法域名含 api.nomadro.cn +``` ## pre3 摘要(已合入) @@ -197,6 +219,4 @@ pnpm dev:api 构建微信包:`pnpm build:weapp` / `pnpm dev:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。 -微信启动首页为 **`pages/home/index`**(官方话题/体验码同路径;视觉对齐 **`20261011`**;路径 **`20261011b`**;**审核包 tag `20261011-2`**)。`pages/index/index` 仅作兼容:`reLaunch` → home(勿与 home 共用组件入口,否则页面 wxss 缺失)。详见 `apps/miniprogram/weapp/README.md`。 - -提审上传:本地 `pnpm build:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)→ 上传体验版;后台「数字游民」提审开关按需开启。 +微信启动首页为 **`pages/home/index`**。历史审核 tag:`20261011` / `20261011b` / `20261011-2`;**本轮提审 tag:`2026-11-02`(分支 `test9`)**。`pages/index/index` 仅兼容 `reLaunch` → home。详见 `apps/miniprogram/weapp/README.md`。 diff --git a/apps/admin/deploy/_check_book_audit.py b/apps/admin/deploy/_check_book_audit.py new file mode 100644 index 0000000..4f7ba58 --- /dev/null +++ b/apps/admin/deploy/_check_book_audit.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +import json +import sys +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +url = "https://api.nomadro.cn/api/ebook/config" +with urllib.request.urlopen(url, timeout=15) as r: + d = json.loads(r.read().decode("utf-8", "replace")) +cfg = d.get("config") or {} +flags = cfg.get("flags") or {} +copy = cfg.get("copy") or {} +plat = ((cfg.get("platforms") or {}).get("weapp") or {}) +print("flags.reviewMode / bookAudit =", {k: flags.get(k) for k in flags if "audit" in k.lower() or "review" in k.lower()}) +print("copy keys sample", [k for k in copy if "audit" in k.lower() or "book" in k.lower() or "review" in k.lower()]) +print("weapp keys", list(plat.keys())[:20]) +# dump relevant +import pprint +pprint.pp({k: flags[k] for k in sorted(flags) if k in flags}) diff --git a/apps/admin/deploy/_fix_audit_book_api.py b/apps/admin/deploy/_fix_audit_book_api.py new file mode 100644 index 0000000..c212356 --- /dev/null +++ b/apps/admin/deploy/_fix_audit_book_api.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +"""Fix audit book API 500 (missing chapter order) + deploy read_policy/store.""" +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +FILES = [ + ( + REPO / "apps/api/services/ebook_svc/domains/books/read_policy.py", + "/opt/nomadmini/backend/app/domains/books/read_policy.py", + ), + ( + REPO / "apps/api/services/ebook_svc/services/store.py", + "/opt/nomadmini/backend/app/services/store.py", + ), +] + + +def main() -> int: + 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() + for src, dest in FILES: + data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8") + tmp = f"/tmp/{Path(dest).name}" + with sftp.file(tmp, "wb") as rf: + rf.write(data) + print("upload", src.name, flush=True) + sftp.close() + + cmd = r""" +set -e +sudo cp /tmp/read_policy.py /opt/nomadmini/backend/app/domains/books/read_policy.py +sudo cp /tmp/store.py /opt/nomadmini/backend/app/services/store.py + +python3 - <<'PY' +import json, sqlite3, time +db='/opt/nomadmini/data/nomadmini.db' +con=sqlite3.connect(db) +row=con.execute("select chapters_json from books where id='audit'").fetchone() +if row: + ch=json.loads(row[0] or '[]') + fixed=[] + for i,c in enumerate(ch if isinstance(ch,list) else []): + if not isinstance(c, dict): + continue + c=dict(c) + c['id']=str(c.get('id') or f'ch-{i+1}') + c['title']=str(c.get('title') or f'章节 {i+1}') + c['order']=int(c['order']) if c.get('order') is not None else i+1 + c['content']=str(c.get('content') or '') + fixed.append(c) + if not fixed: + fixed=[{ + 'id':'01-audit','title':'欢迎阅读','order':1, + 'content':'# 数字游民·提审版\n\n这是微信提审用的独立内容,与会员正式书无关。\n' + }] + con.execute( + "update books set title=?, subtitle=?, unlock_percent=100, price_fen=0, product_id='', chapters_json=?, updated_at=? where id='audit'", + ('数字游民·提审版','微信提审专用 · 与正式会员书无关', json.dumps(fixed, ensure_ascii=False), time.time()) + ) + con.commit() + print('fixed chapters', len(fixed), 'orders', [x['order'] for x in fixed]) +else: + print('no audit row') +PY + +sudo systemctl restart nomadmini-api +sleep 2 +systemctl is-active nomadmini-api +curl -sk -o /tmp/audit.json -w "books/audit %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit" +python3 - <<'PY' +import json +d=json.load(open('/tmp/audit.json',encoding='utf-8')) +print('title', d.get('title'), 'chapters', len(d.get('chapters') or []), 'free', d.get('is_free')) +print('ch0', (d.get('chapters') or [{}])[0]) +PY +curl -sk -o /tmp/audit_read.json -w "books/audit/read %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit/read" +python3 - <<'PY' +import json +d=json.load(open('/tmp/audit_read.json',encoding='utf-8')) +chs=d.get('chapters') or [] +print('read chapters', len(chs), 'title', (d.get('book') or {}).get('title')) +if chs: + print('body', (chs[0].get('content') or '')[:120].replace('\n',' ')) +PY +rm -f /tmp/read_policy.py /tmp/store.py /tmp/audit.json /tmp/audit_read.json +""" + _, stdout, _ = c.exec_command(cmd, timeout=120, 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()) diff --git a/apps/admin/deploy/_fix_audit_read_anon.py b/apps/admin/deploy/_fix_audit_read_anon.py new file mode 100644 index 0000000..591307b --- /dev/null +++ b/apps/admin/deploy/_fix_audit_read_anon.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" +FILES = [ + (REPO / "apps/api/services/ebook_svc/core/deps.py", "/opt/nomadmini/backend/app/core/deps.py"), + (REPO / "apps/api/services/ebook_svc/routers/books.py", "/opt/nomadmini/backend/app/routers/books.py"), +] + + +def main() -> int: + 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() + for src, dest in FILES: + data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8") + with sftp.file(f"/tmp/{Path(dest).name}", "wb") as rf: + rf.write(data) + sftp.close() + cmd = r""" +set -e +sudo cp /tmp/deps.py /opt/nomadmini/backend/app/core/deps.py +sudo cp /tmp/books.py /opt/nomadmini/backend/app/routers/books.py +sudo systemctl restart nomadmini-api +sleep 2 +curl -sk -o /tmp/r.json -w "read %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit/read +python3 - <<'PY' +import json +d=json.load(open('/tmp/r.json',encoding='utf-8')) +print('title', (d.get('book') or {}).get('title')) +print('chapters', len(d.get('chapters') or [])) +body=((d.get('chapters') or [{}])[0].get('content') or '')[:100] +print('body', body.replace('\n',' ')) +PY +""" + _, stdout, _ = c.exec_command(cmd, timeout=90, 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() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_fix_config_ws_nginx.py b/apps/admin/deploy/_fix_config_ws_nginx.py new file mode 100644 index 0000000..d93a030 --- /dev/null +++ b/apps/admin/deploy/_fix_config_ws_nginx.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +REMOTE = r""" +set -e +ls -la /www/server/panel/vhost/nginx/*api* 2>/dev/null || true +echo ---CONF--- +CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf +if [ -f "$CONF" ]; then + grep -n 'config/ws\|proxy_pass\|location /' "$CONF" | head -80 +else + echo missing_conf + ls /www/server/panel/vhost/nginx/ | head +fi +echo ---DIRECT--- +curl -sk -i -N --max-time 3 \ + -H 'Connection: Upgrade' \ + -H 'Upgrade: websocket' \ + -H 'Sec-WebSocket-Version: 13' \ + -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \ + http://127.0.0.1:8010/api/config/ws | head -30 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False) + _, stdout, _ = c.exec_command(REMOTE, timeout=60) + print(stdout.read().decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/apps/admin/deploy/_fix_config_ws_nginx2.py b/apps/admin/deploy/_fix_config_ws_nginx2.py new file mode 100644 index 0000000..ef8e7f6 --- /dev/null +++ b/apps/admin/deploy/_fix_config_ws_nginx2.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +REMOTE = r""" +set -e +echo '=== find api host conf ===' +sudo grep -RIl 'api.nomadro.cn' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30 +echo '=== find 8010 ===' +sudo grep -RIl '8010' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30 +echo '=== our bak? ===' +ls -la /www/server/panel/vhost/nginx/api.nomadro.cn.conf* 2>/dev/null || true +ls -la /www/server/panel/vhost/nginx/*.bak-config-ws 2>/dev/null || true +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False) + _, stdout, _ = c.exec_command(REMOTE, timeout=90) + print(stdout.read().decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/apps/admin/deploy/_fix_nginx_ws3.py b/apps/admin/deploy/_fix_nginx_ws3.py new file mode 100644 index 0000000..0aff50c --- /dev/null +++ b/apps/admin/deploy/_fix_nginx_ws3.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import paramiko + +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +REMOTE = r""" +CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf +sudo sed -n '1,220p' "$CONF" +echo '===== WS LOC =====' +sudo grep -n 'config/ws\|Upgrade\|location ' "$CONF" | head -80 +""" + + +def main() -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False) + _, stdout, _ = c.exec_command(REMOTE, timeout=60) + print(stdout.read().decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + main() diff --git a/apps/admin/deploy/_fix_nginx_ws_ssl.py b/apps/admin/deploy/_fix_nginx_ws_ssl.py new file mode 100644 index 0000000..ad28b2d --- /dev/null +++ b/apps/admin/deploy/_fix_nginx_ws_ssl.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +"""Patch api.nomadro.cn 443 block for /api/config/ws Upgrade.""" +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +PATCHER = r''' +from pathlib import Path +import shutil +p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf") +text = p.read_text(encoding="utf-8") +marker = "location /api/config/ws" +parts = text.split("listen 443") +if len(parts) < 2: + raise SystemExit("no 443 block") +if marker in parts[1]: + print("ssl_ws_already") + raise SystemExit(0) +lines = [ + "", + " location /api/config/ws {", + " proxy_pass http://127.0.0.1:8010;", + " proxy_http_version 1.1;", + " proxy_set_header Upgrade $http_upgrade;", + ' proxy_set_header Connection "upgrade";', + " proxy_set_header Host $host;", + " proxy_set_header X-Real-IP $remote_addr;", + " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;", + " proxy_set_header X-Forwarded-Proto $scheme;", + " proxy_read_timeout 3600s;", + " proxy_send_timeout 3600s;", + " proxy_buffering off;", + " }", + " location /api/ebook/config/ws {", + " proxy_pass http://127.0.0.1:8010;", + " proxy_http_version 1.1;", + " proxy_set_header Upgrade $http_upgrade;", + ' proxy_set_header Connection "upgrade";', + " proxy_set_header Host $host;", + " proxy_set_header X-Real-IP $remote_addr;", + " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;", + " proxy_set_header X-Forwarded-Proto $scheme;", + " proxy_read_timeout 3600s;", + " proxy_send_timeout 3600s;", + " proxy_buffering off;", + " }", + "", +] +snippet = "\n".join(lines) +ssl = parts[1] +idx = ssl.find("location / {") +if idx < 0: + raise SystemExit("no location / in 443") +ssl2 = ssl[:idx] + snippet + "\n" + ssl[idx:] +out = parts[0] + "listen 443" + ssl2 +shutil.copy2(p, str(p) + ".bak-ws-ssl") +p.write_text(out, encoding="utf-8") +print("ssl_ws_patched") +''' + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/patch_ws_ssl.py", "w") as rf: + rf.write(PATCHER) + sftp.close() + cmd = "sudo python3 /tmp/patch_ws_ssl.py && sudo nginx -t && sudo nginx -s reload && rm -f /tmp/patch_ws_ssl.py && echo DONE" + _, stdout, _ = c.exec_command(cmd, timeout=90, 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() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_admin_crud.py b/apps/admin/deploy/_push_admin_crud.py new file mode 100644 index 0000000..c92efa1 --- /dev/null +++ b/apps/admin/deploy/_push_admin_crud.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +"""Deploy admin SPA + CRUD APIs (stats series, social ugc, community, memo/books/orders). + +- Never wipe catalogs unless catalog PUT is called by operator +- Snapshot /api/config version before/after +- Set SOCIAL_DB_PATH + fix social.db perms for www +""" +from __future__ import annotations + +import io +import json +import subprocess +import tarfile +import time +import urllib.request +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +ADMIN = REPO / "apps/admin" +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +API_FILES = [ + ("apps/api/services/ebook_svc/services/store.py", "services/store.py"), + ("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"), + ("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"), + ("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"), + ("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"), + ("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"), + ("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"), + ("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"), + ("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"), + ("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"), +] + + +def rewrite(text: str) -> str: + return text.replace("ebook_svc.", "app.") + + +def snapshot() -> dict: + req = urllib.request.Request( + "https://api.nomadro.cn/api/config", + headers={"User-Agent": "nomadro-admin-crud-deploy"}, + ) + with urllib.request.urlopen(req, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + cfg = data.get("config") if isinstance(data.get("config"), dict) else {} + mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {} + return { + "version": cfg.get("version"), + "social": mods.get("social"), + "source": data.get("source"), + } + + +def build_admin() -> None: + print("vite build…", flush=True) + r = subprocess.run( + ["pnpm", "exec", "vite", "build"], + cwd=ADMIN, + shell=True, + capture_output=True, + encoding="utf-8", + errors="replace", + ) + if r.returncode != 0: + print(r.stdout) + print(r.stderr) + raise SystemExit(r.returncode) + + +def pack() -> bytes: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for rel, dest in API_FILES: + src = REPO / rel + text = rewrite(src.read_text(encoding="utf-8")) + if "ebook_svc" in text and dest != "main.py": + # main may mention ebook only in comments; services must be clean + if "ebook_svc." in text: + raise SystemExit(f"rewrite failed: {rel}") + data = text.encode("utf-8") + info = tarfile.TarInfo(name="api/" + dest) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + dist = ADMIN / "dist" + for p in dist.rglob("*"): + if p.is_file(): + tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix()) + buf.seek(0) + blob = buf.read() + print("pack", len(blob), flush=True) + return blob + + +def main() -> int: + before = snapshot() + print("BEFORE", before, flush=True) + build_admin() + blob = pack() + + 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/admin-crud.tar.gz", "wb") as rf: + rf.write(blob) + sftp.close() + + cmd = r""" +set -e +cd /tmp +rm -rf admin-crud && mkdir admin-crud +tar -xzf admin-crud.tar.gz -C admin-crud + +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 +B=$API_ROOT/app +if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi +echo B=$B +TS=$(date -u +%Y%m%dT%H%M%SZ) + +sudo mkdir -p "$B/services" "$B/routers" "$B/schemas" +for f in \ + services/store.py \ + services/social_ugc.py \ + services/memo_store.py \ + services/shop_store.py \ + schemas/admin.py \ + routers/admin.py \ + routers/social_ugc_admin.py \ + routers/community_admin.py \ + routers/memo_admin.py \ + routers/shop_admin.py +do + if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi + sudo cp "admin-crud/api/$f" "$B/$f" +done + +# Patch main.py to include new routers (idempotent) +python3 - <<'PY' +from pathlib import Path +p = Path("/opt/nomadmini/backend/app/main.py") +text = p.read_text(encoding="utf-8") +changed = False +if "social_ugc_admin" not in text: + needle = "from app.routers import social_ops_admin" + if needle in text: + text = text.replace( + needle, + needle + + "\nfrom app.routers import social_ugc_admin # noqa: E402\nfrom app.routers import community_admin # noqa: E402", + 1, + ) + changed = True +if "include_router(social_ugc_admin.router)" not in text: + needle2 = "include_router(social_ops_admin.router)" + if needle2 in text: + text = text.replace( + needle2, + needle2 + + "\napp.include_router(social_ugc_admin.router)\napp.include_router(community_admin.router)", + 1, + ) + changed = True +if changed: + p.write_text(text, encoding="utf-8") + print("patched_main") +else: + print("main_ok") +PY + +# social db perms + env for nomadmini-api +sudo mkdir -p /var/www/nomadro-data/social /var/www/nomadro-data/community +if [ -f /var/www/nomadro-data/social/social.db ]; then + sudo chown www:www /var/www/nomadro-data/social/social.db || true + sudo chmod 664 /var/www/nomadro-data/social/social.db || true + sudo chown www:www /var/www/nomadro-data/social || true +fi +sudo mkdir -p /etc/systemd/system/nomadmini-api.service.d +sudo tee /etc/systemd/system/nomadmini-api.service.d/social-db.conf >/dev/null <<'EOF' +[Service] +Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db +Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json +EOF +sudo systemctl daemon-reload + +sudo rsync -a --delete /tmp/admin-crud/admin-dist/ /www/wwwroot/admin.nomadro.cn/ +sudo chown -R www:www /www/wwwroot/admin.nomadro.cn +echo admin_synced + +sudo systemctl restart nomadmini-api +sleep 3 +systemctl is-active nomadmini-api + +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',''))") +AUTH="Authorization: Bearer $TOK" + +echo -n 'stats ' +curl -sk -o /tmp/st.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats +python3 - <<'PY' +import json +d=json.load(open('/tmp/st.json',encoding='utf-8')) +assert 'series' in d, d +print('series_ok', len(d['series'].get('revenue',[])), 'top', len(d.get('topEvents') or [])) +PY + +echo -n 'social_ugc ' +curl -sk -o /tmp/su.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/social/ugc/overview +python3 - <<'PY' +import json +d=json.load(open('/tmp/su.json',encoding='utf-8')) +print('ugc', d.get('exists'), d.get('writable'), d.get('counts')) +PY + +echo -n 'community ' +curl -sk -o /tmp/co.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/community/overview + +for u in /wechat /wechat/social/data /wechat/community /wechat/books; do + curl -sk -o /dev/null -w "admin$u %{http_code}\n" "https://admin.nomadro.cn$u" +done + +curl -sk https://api.nomadro.cn/api/config -o /tmp/cfg-after.json +python3 - <<'PY' +import json +d=json.load(open('/tmp/cfg-after.json',encoding='utf-8')) +social=d.get('config',{}).get('modules',{}).get('social') +print('live_social', social) +assert isinstance(social, dict) and social.get('enabled') is True +print('config_ok') +PY + +rm -rf /tmp/admin-crud /tmp/admin-crud.tar.gz /tmp/st.json /tmp/su.json /tmp/co.json /tmp/cfg-after.json +""" + _, stdout, _ = c.exec_command(cmd, 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() + + after = snapshot() + print("AFTER", after, flush=True) + if after.get("version") != before.get("version") or after.get("social") != before.get("social"): + print("FAIL config drifted", flush=True) + return 3 + print(f"[exit {code}] admin CRUD deployed; version {after.get('version')}", flush=True) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_api_backend.py b/apps/admin/deploy/_push_api_backend.py new file mode 100644 index 0000000..50e766b --- /dev/null +++ b/apps/admin/deploy/_push_api_backend.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +"""Deploy pending ebook API backend only (no admin SPA). + +- Rewrite ebook_svc.* → app.* +- Hot-copy into /opt/nomadmini/backend/app +- Restart nomadmini-api only +- Snapshot /api/config version before/after (must not drift) +""" +from __future__ import annotations + +import io +import json +import tarfile +import time +import urllib.request +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +API_FILES = [ + ("apps/api/services/ebook_svc/services/store.py", "services/store.py"), + ("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"), + ("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"), + ("apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"), + ("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"), + ("apps/api/services/ebook_svc/services/social_ops.py", "services/social_ops.py"), + ( + "apps/api/services/ebook_svc/services/public_config_snapshot.py", + "services/public_config_snapshot.py", + ), + ("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"), + ("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"), + ("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"), + ("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"), + ("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"), + ("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"), + ("apps/api/services/ebook_svc/routers/social_ops_admin.py", "routers/social_ops_admin.py"), + ("apps/api/services/ebook_svc/routers/public_config.py", "routers/public_config.py"), +] + + +def rewrite(text: str) -> str: + return text.replace("ebook_svc.", "app.") + + +def snapshot() -> dict: + req = urllib.request.Request( + "https://api.nomadro.cn/api/config", + headers={"User-Agent": "nomadro-api-backend-deploy"}, + ) + with urllib.request.urlopen(req, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + cfg = data.get("config") if isinstance(data.get("config"), dict) else {} + mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {} + return { + "version": cfg.get("version"), + "social": mods.get("social"), + "book": mods.get("book"), + "source": data.get("source"), + } + + +def pack() -> bytes: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for rel, dest in API_FILES: + src = REPO / rel + if not src.is_file(): + raise SystemExit(f"missing {rel}") + text = rewrite(src.read_text(encoding="utf-8")) + if "ebook_svc." in text: + raise SystemExit(f"rewrite failed: {rel}") + data = text.encode("utf-8") + info = tarfile.TarInfo(name="api/" + dest) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + buf.seek(0) + blob = buf.read() + print("pack", len(blob), "files", len(API_FILES), flush=True) + return blob + + +def main() -> int: + before = snapshot() + print("BEFORE", before, flush=True) + blob = pack() + + 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/api-backend.tar.gz", "wb") as rf: + rf.write(blob) + sftp.close() + + cmd = r""" +set -e +cd /tmp +rm -rf api-backend && mkdir api-backend +tar -xzf api-backend.tar.gz -C api-backend + +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 +B=$API_ROOT/app +if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi +echo B=$B +TS=$(date -u +%Y%m%dT%H%M%SZ) + +sudo mkdir -p "$B/services" "$B/routers" "$B/schemas" +for f in \ + services/store.py \ + services/memo_store.py \ + services/shop_store.py \ + services/weapp_switches.py \ + services/social_ugc.py \ + services/social_ops.py \ + services/public_config_snapshot.py \ + schemas/admin.py \ + routers/admin.py \ + routers/memo_admin.py \ + routers/shop_admin.py \ + routers/social_ugc_admin.py \ + routers/community_admin.py \ + routers/social_ops_admin.py \ + routers/public_config.py +do + if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi + sudo cp "api-backend/api/$f" "$B/$f" + echo copied $f +done + +# Ensure main.py registers new admin routers (idempotent) +python3 - <<'PY' +from pathlib import Path +candidates = [ + Path("/opt/nomadmini/backend/app/main.py"), +] +for p in candidates: + if not p.is_file(): + continue + text = p.read_text(encoding="utf-8") + changed = False + imports = [ + ("social_ops_admin", "from app.routers import social_ops_admin # noqa: E402"), + ("social_ugc_admin", "from app.routers import social_ugc_admin # noqa: E402"), + ("community_admin", "from app.routers import community_admin # noqa: E402"), + ] + for key, line in imports: + if key not in text: + # append near other router imports + anchor = "from app.routers import" + idx = text.rfind(anchor) + if idx >= 0: + end = text.find("\n", idx) + text = text[: end + 1] + line + "\n" + text[end + 1 :] + changed = True + else: + text = line + "\n" + text + changed = True + includes = [ + ("social_ops_admin.router", "app.include_router(social_ops_admin.router)"), + ("social_ugc_admin.router", "app.include_router(social_ugc_admin.router)"), + ("community_admin.router", "app.include_router(community_admin.router)"), + ] + for key, line in includes: + if key not in text: + # after last include_router + needle = "app.include_router(" + idx = text.rfind(needle) + if idx >= 0: + end = text.find("\n", idx) + text = text[: end + 1] + line + "\n" + text[end + 1 :] + changed = True + if changed: + p.write_text(text, encoding="utf-8") + print("patched_main", p) + else: + print("main_ok", p) +PY + +cd "$API_ROOT" +if [ -x .venv/bin/python ]; then + .venv/bin/python - <<'PY' +from app.services.weapp_switches import read_weapp_switches +from app.services import public_config_snapshot +print("import_ok", read_weapp_switches().get("bookAudit")) +print("snapshot_cls", public_config_snapshot.PublicConfigSnapshot) +PY +fi + +sudo systemctl restart nomadmini-api +sleep 4 +systemctl is-active nomadmini-api +curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health +curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config +curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta + +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',''))") +echo token_len=${#TOK} +AUTH="Authorization: Bearer $TOK" +curl -sk -o /dev/null -w "switches %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/weapp/switches +curl -sk -o /dev/null -w "stats %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats + +rm -rf /tmp/api-backend /tmp/api-backend.tar.gz +""" + _, stdout, _ = c.exec_command(cmd, 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() + + after = snapshot() + print("AFTER", after, flush=True) + if after.get("version") != before.get("version") or after.get("social") != before.get("social"): + print("FAIL config drifted", flush=True) + return 3 + print(f"[exit {code}] api backend deployed; version {after.get('version')}", flush=True) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_config_post.py b/apps/admin/deploy/_push_config_post.py new file mode 100644 index 0000000..a055944 --- /dev/null +++ b/apps/admin/deploy/_push_config_post.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" +SRC = REPO / "apps/api/services/ebook_svc/routers/public_config.py" + + +def main() -> int: + text = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.") + if "ebook_svc." in text: + raise SystemExit("rewrite failed") + 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/public_config.py", "w") as rf: + rf.write(text) + sftp.close() + cmd = r""" +set -e +sudo cp /tmp/public_config.py /opt/nomadmini/backend/app/routers/public_config.py +sudo systemctl restart nomadmini-api +sleep 3 +systemctl is-active nomadmini-api +curl -sk -X POST https://api.nomadro.cn/api/config/pull -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);c=d['config'];print('POST_PULL',c.get('version'),c.get('modules',{}).get('nav'))" +curl -sk -X POST https://api.nomadro.cn/api/config -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);print('POST_CFG',d['config'].get('version'))" +rm -f /tmp/public_config.py +""" + _, stdout, _ = c.exec_command(cmd, timeout=90, 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() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_config_realtime.py b/apps/admin/deploy/_push_config_realtime.py new file mode 100644 index 0000000..c9ddf66 --- /dev/null +++ b/apps/admin/deploy/_push_config_realtime.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +"""Deploy config SSE/WebSocket realtime to api.nomadro.cn (nomadmini-api).""" +from __future__ import annotations + +import io +import json +import tarfile +import time +import urllib.request +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + +FILES = [ + ( + "apps/api/services/ebook_svc/services/config_live.py", + "services/config_live.py", + ), + ( + "apps/api/services/ebook_svc/routers/public_config.py", + "routers/public_config.py", + ), + ( + "apps/api/services/ebook_svc/services/weapp_switches.py", + "services/weapp_switches.py", + ), +] + + +def rewrite(text: str) -> str: + return text.replace("ebook_svc.", "app.") + + +def main() -> int: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for rel, dest in FILES: + src = REPO / rel + text = rewrite(src.read_text(encoding="utf-8")) + if "ebook_svc." in text: + raise SystemExit(f"rewrite failed {rel}") + data = text.encode("utf-8") + info = tarfile.TarInfo(name=dest) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + blob = buf.getvalue() + print("pack", len(blob), 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/config-rt.tar.gz", "wb") as rf: + rf.write(blob) + sftp.close() + + cmd = r""" +set -e +cd /tmp +rm -rf config-rt && mkdir config-rt +tar -xzf config-rt.tar.gz -C config-rt +B=/opt/nomadmini/backend/app +TS=$(date -u +%Y%m%dT%H%M%SZ) +sudo mkdir -p "$B/services" "$B/routers" +for f in services/config_live.py routers/public_config.py services/weapp_switches.py; do + if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi + sudo cp "config-rt/$f" "$B/$f" + echo copied $f +done + +# nginx websocket:写到 /tmp 再 sudo 覆盖 +sudo python3 - <<'PY' +from pathlib import Path +import shutil +src = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf") +if not src.is_file(): + print("nginx_ws_skip_no_conf") + raise SystemExit(0) +text = src.read_text(encoding="utf-8") +if "location /api/config/ws" in text: + print("nginx_ws_ok") + raise SystemExit(0) +upstream = "http://127.0.0.1:8000" +for line in text.splitlines(): + s = line.strip() + if s.startswith("proxy_pass ") and "127.0.0.1" in s: + upstream = s.split("proxy_pass", 1)[1].strip().rstrip(";") + break +snippet = ( + "\n location /api/config/ws {\n" + f" proxy_pass {upstream};\n" + " proxy_http_version 1.1;\n" + " proxy_set_header Upgrade $http_upgrade;\n" + ' proxy_set_header Connection "upgrade";\n' + " proxy_set_header Host $host;\n" + " proxy_set_header X-Real-IP $remote_addr;\n" + " proxy_read_timeout 3600s;\n" + " proxy_send_timeout 3600s;\n" + " }\n" + " location /api/ebook/config/ws {\n" + f" proxy_pass {upstream};\n" + " proxy_http_version 1.1;\n" + " proxy_set_header Upgrade $http_upgrade;\n" + ' proxy_set_header Connection "upgrade";\n' + " proxy_set_header Host $host;\n" + " proxy_set_header X-Real-IP $remote_addr;\n" + " proxy_read_timeout 3600s;\n" + " proxy_send_timeout 3600s;\n" + " }\n" +) +idx = text.find("location /") +if idx < 0: + idx = text.rfind("}") +if idx <= 0: + print("nginx_ws_skip") + raise SystemExit(0) +out = text[:idx] + snippet + "\n" + text[idx:] +bak = src.with_suffix(src.suffix + ".bak-config-ws") +shutil.copy2(src, bak) +src.write_text(out, encoding="utf-8") +print("nginx_ws_patched", upstream) +PY +sudo nginx -t && sudo nginx -s reload || true + +cd /opt/nomadmini/backend +.venv/bin/python - <<'PY' +from app.services import config_live +from app.routers import public_config +print("import_ok", config_live.read_config_meta()) +PY + +sudo systemctl restart nomadmini-api +sleep 4 +systemctl is-active nomadmini-api +curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health +curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config +curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta +# SSE hello (2s) +timeout 3 curl -sk -N -H 'Accept: text/event-stream' https://api.nomadro.cn/api/config/stream | head -c 400 || true +echo +rm -rf /tmp/config-rt /tmp/config-rt.tar.gz +""" + _, stdout, _ = c.exec_command(cmd, timeout=180, 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() + + # local meta check + meta = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config/meta", timeout=15).read()) + print("META", meta, flush=True) + print(f"[exit {code}] config realtime deployed", flush=True) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_weapp_switches.py b/apps/admin/deploy/_push_weapp_switches.py new file mode 100644 index 0000000..8959ab6 --- /dev/null +++ b/apps/admin/deploy/_push_weapp_switches.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +"""Deploy weapp switches API + admin SPA.""" +from __future__ import annotations + +import subprocess +import tarfile +import time +from io import BytesIO +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" + +API_FILES = [ + (REPO / "apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"), + (REPO / "apps/api/services/ebook_svc/routers/weapp_switches_admin.py", "routers/weapp_switches_admin.py"), + (REPO / "apps/api/services/ebook_svc/services/store.py", "services/store.py"), + (REPO / "apps/api/services/ebook_svc/main.py", "main.py"), +] + + +def to_app(src: Path) -> bytes: + return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8") + + +def main() -> int: + print("vite build…", flush=True) + r = subprocess.run( + ["pnpm", "exec", "vite", "build"], + cwd=ROOT, + shell=True, + capture_output=True, + encoding="utf-8", + errors="replace", + ) + if r.returncode != 0: + print(r.stdout) + print(r.stderr) + return r.returncode + + dist = ROOT / "dist" + buf = 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 src, rel in API_FILES: + data = to_app(src) + info = tarfile.TarInfo(name="api/" + rel.replace("/", "__")) + info.size = len(data) + tar.addfile(info, BytesIO(data)) + buf.seek(0) + print("pack", buf.getbuffer().nbytes, 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/weapp-switches.tar.gz", "wb") as rf: + rf.write(buf.read()) + sftp.close() + + cmd = r""" +set -e +cd /tmp +rm -rf sw-unpack && mkdir sw-unpack +tar -xzf weapp-switches.tar.gz -C sw-unpack +sudo rsync -a --delete sw-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/ +sudo chown -R www:www /www/wwwroot/admin.nomadro.cn +B=/opt/nomadmini/backend/app +sudo mkdir -p "$B/services" "$B/routers" +sudo cp sw-unpack/api/services__weapp_switches.py "$B/services/weapp_switches.py" +sudo cp sw-unpack/api/routers__weapp_switches_admin.py "$B/routers/weapp_switches_admin.py" +sudo cp sw-unpack/api/services__store.py "$B/services/store.py" +sudo cp sw-unpack/api/main.py "$B/../main.py" 2>/dev/null || sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py +# main may live as app package entry +if [ -f /opt/nomadmini/backend/app/main.py ]; then + sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/app/main.py +elif [ -f /opt/nomadmini/backend/main.py ]; then + sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py +fi +cd /opt/nomadmini/backend +.venv/bin/python - <<'PY' +from app.services.weapp_switches import read_weapp_switches +from app.routers import weapp_switches_admin +from app.services.store import store +assert hasattr(store, "ensure_book") +print("ok", "switches", list(read_weapp_switches().get("modules", {}).keys())[:3]) +PY +sudo systemctl restart nomadmini-api +sleep 3 +systemctl is-active nomadmini-api +curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/switches +curl -sk -o /dev/null -w "api %{http_code}\n" https://api.nomadro.cn/health +rm -rf sw-unpack weapp-switches.tar.gz +""" + _, stdout, _ = c.exec_command(cmd, timeout=180, 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()) diff --git a/apps/admin/deploy/_push_weapp_switches_svc.py b/apps/admin/deploy/_push_weapp_switches_svc.py new file mode 100644 index 0000000..ab44b77 --- /dev/null +++ b/apps/admin/deploy/_push_weapp_switches_svc.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import time +from pathlib import Path + +import paramiko + +REPO = Path(__file__).resolve().parents[3] +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" +SRC = REPO / "apps/api/services/ebook_svc/services/weapp_switches.py" + + +def main() -> int: + data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8") + 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/weapp_switches.py", "wb") as rf: + rf.write(data) + sftp.close() + cmd = r""" +set -e +sudo cp /tmp/weapp_switches.py /opt/nomadmini/backend/app/services/weapp_switches.py +cd /opt/nomadmini/backend +.venv/bin/python -c 'from app.services.weapp_switches import read_weapp_switches; print("ok", read_weapp_switches()["bookAudit"])' +sudo systemctl restart nomadmini-api +sleep 2 +systemctl is-active nomadmini-api +rm -f /tmp/weapp_switches.py +""" + _, stdout, _ = c.exec_command(cmd, timeout=90, 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() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_seed_audit_book.py b/apps/admin/deploy/_seed_audit_book.py new file mode 100644 index 0000000..faa2c44 --- /dev/null +++ b/apps/admin/deploy/_seed_audit_book.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +"""Write WeChat-safe digital-nomad audit booklet into prod DB.""" +from __future__ import annotations + +import json +import re +import time +from pathlib import Path + +import paramiko + +HERE = Path(__file__).resolve().parent +MD = (HERE / "audit_book_seed.md").read_text(encoding="utf-8") +HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" + + +def split_markdown_chapters(md: str) -> list[dict]: + text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip() + if not text: + return [] + parts = re.split(r"(?m)^(#{1} .+)$", text) + chapters: list[dict] = [] + preamble = (parts[0] or "").strip() + order = 1 + if preamble and len(parts) == 1: + return [{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}] + if preamble: + chapters.append({"id": "c0", "title": "前言", "order": order, "content": preamble + "\n"}) + order += 1 + i = 1 + while i < len(parts): + heading = parts[i].strip() + body = parts[i + 1] if i + 1 < len(parts) else "" + title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章" + content = f"{heading}\n{body}".strip() + "\n" + chapters.append({"id": f"c{order}", "title": title, "order": order, "content": content}) + order += 1 + i += 2 + return chapters + + +def main() -> int: + chapters = split_markdown_chapters(MD) + assert chapters, "no chapters" + payload = { + "title": "数字游民入门指南", + "subtitle": "远程办公 · 自律生活 · 稳健成长", + "description": "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。", + "chapters": chapters, + } + raw = json.dumps(payload, ensure_ascii=False).encode("utf-8") + + 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/audit_book_seed.json", "wb") as rf: + rf.write(raw) + sftp.close() + + cmd = r""" +set -e +python3 <<'PY' +import json, sqlite3, time +data=json.load(open('/tmp/audit_book_seed.json',encoding='utf-8')) +chapters=data['chapters'] +con=sqlite3.connect('/opt/nomadmini/data/nomadmini.db') +now=time.time() +row=con.execute("select id from books where id='audit'").fetchone() +meta=( + data['title'], data['subtitle'], '', '📗', data['description'], + json.dumps(['数字游民','远程办公','生活方式'], ensure_ascii=False), + 0, '', 100, 5.0, json.dumps(chapters, ensure_ascii=False), now, +) +if row: + con.execute( + 'UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?,' + ' price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=?', + meta + ('audit',), + ) +else: + con.execute( + 'INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,' + 'price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) ' + "VALUES ('audit',?,?,?,?,?,?,?,?,?,?,?,?)", + meta, + ) +con.commit() +print('chapters', len(chapters)) +print('titles', [c['title'] for c in chapters]) +print('words', sum(len(c.get('content') or '') for c in chapters)) +PY +curl -sk -o /tmp/audit_check.json -w "audit %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit +python3 <<'PY' +import json +d=json.load(open('/tmp/audit_check.json',encoding='utf-8')) +print('api', d.get('title'), d.get('chapter_count'), d.get('is_free')) +print('toc', [c.get('title') for c in (d.get('chapters') or [])]) +PY +rm -f /tmp/audit_book_seed.json /tmp/audit_check.json +""" + _, stdout, _ = c.exec_command(cmd, timeout=90, 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()) diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx index 9495d2b..3f5d19f 100644 --- a/apps/admin/src/App.tsx +++ b/apps/admin/src/App.tsx @@ -4,6 +4,10 @@ import Login from './pages/Login' import PlatformSelect from './pages/PlatformSelect' import Dashboard from './pages/Dashboard' import Switches from './pages/Switches' +import Social from './pages/Social' +import SocialData from './pages/SocialData' +import Community from './pages/Community' +import Books from './pages/Books' import BookEdit from './pages/BookEdit' import './pages/BookEdit.css' import Orders from './pages/Orders' @@ -69,6 +73,10 @@ export default function App() { > } /> } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/apps/admin/src/components/Layout.tsx b/apps/admin/src/components/Layout.tsx index b9a49aa..2473ba6 100644 --- a/apps/admin/src/components/Layout.tsx +++ b/apps/admin/src/components/Layout.tsx @@ -30,6 +30,19 @@ const NAV_GROUPS: NavGroup[] = [ label: '内容', items: [ { to: '/wechat/nav', ico: '🧭', label: '导航' }, + { + kind: 'branch', + id: 'social', + ico: '💕', + label: '游民社区', + match: ['/wechat/social'], + defaultTo: '/wechat/social/data', + children: [ + { to: '/wechat/social/data', ico: '🗄️', label: 'UGC 数据' }, + { to: '/wechat/social', end: true, ico: '⏻', label: '开关文案' }, + ], + }, + { to: '/wechat/community', ico: '🌍', label: '门户社区' }, { kind: 'branch', id: 'vip', @@ -46,8 +59,9 @@ const NAV_GROUPS: NavGroup[] = [ ico: '📖', label: '电子书', match: ['/wechat/vip/ebooks', '/wechat/books'], - defaultTo: '/wechat/vip/ebooks/nomad', + defaultTo: '/wechat/books', children: [ + { to: '/wechat/books', end: true, ico: '📚', label: '小册列表' }, { to: '/wechat/vip/ebooks/nomad', ico: '🌍', label: '数字游民' }, { to: '/wechat/vip/ebooks/cloudphone', ico: '📱', label: '云手机' }, { to: '/wechat/books/default', ico: '▶️', label: 'youtube运营笔记' }, diff --git a/apps/admin/src/components/WxCharts.tsx b/apps/admin/src/components/WxCharts.tsx new file mode 100644 index 0000000..b6828ae --- /dev/null +++ b/apps/admin/src/components/WxCharts.tsx @@ -0,0 +1,115 @@ +/** Lightweight SVG charts — no chart lib dependency. */ + +type Point = { date: string; value: number } + +function niceMax(n: number) { + if (n <= 0) return 1 + const p = 10 ** Math.floor(Math.log10(n)) + return Math.ceil(n / p) * p +} + +export function WxSparkBars({ + title, + subtitle, + points, + format = (v) => String(v), + accent = '#5ec478', +}: { + title: string + subtitle?: string + points: Point[] + format?: (v: number) => string + accent?: string +}) { + const w = 560 + const h = 160 + const pad = { t: 12, r: 8, b: 28, l: 8 } + const max = niceMax(Math.max(...points.map((p) => p.value), 0)) + const bw = points.length + ? (w - pad.l - pad.r) / points.length + : 0 + const innerH = h - pad.t - pad.b + + return ( +
+
+
+ {title} + {subtitle ? {subtitle} : null} +
+ 峰值 {format(max)} +
+ + {points.map((p, i) => { + const barH = max ? (p.value / max) * innerH : 0 + const x = pad.l + i * bw + bw * 0.15 + const y = pad.t + innerH - barH + const showLabel = i === 0 || i === points.length - 1 || i % 3 === 0 + return ( + + 0 ? 2 : 0)} + rx={3} + fill={accent} + opacity={0.85} + > + + {p.date}: {format(p.value)} + + + {showLabel ? ( + + {p.date.slice(5)} + + ) : null} + + ) + })} + +
+ ) +} + +export function WxRankList({ + title, + items, +}: { + title: string + items: Array<{ name: string; count: number }> +}) { + const max = Math.max(...items.map((i) => i.count), 1) + return ( +
+
+ {title} +
+
    + {items.length ? ( + items.map((it) => ( +
  • +
    + {it.name || '(empty)'} + {it.count} +
    +
    + +
    +
  • + )) + ) : ( +
  • 暂无数据
  • + )} +
+
+ ) +} diff --git a/apps/admin/src/components/wxUi.tsx b/apps/admin/src/components/wxUi.tsx index e926330..09ac15c 100644 --- a/apps/admin/src/components/wxUi.tsx +++ b/apps/admin/src/components/wxUi.tsx @@ -25,21 +25,25 @@ export function WxHead({ export function WxToast({ kind, + tone, children, onClose, }: { - kind: 'ok' | 'err' | 'info' + kind?: 'ok' | 'err' | 'info' + /** @deprecated use kind */ + tone?: 'ok' | 'err' | 'info' children: ReactNode onClose?: () => void }) { + const k = kind || tone || 'info' useEffect(() => { - if (!onClose || kind === 'err') return + if (!onClose || k === 'err') return const t = window.setTimeout(onClose, 4200) return () => window.clearTimeout(t) - }, [children, kind, onClose]) + }, [children, k, onClose]) return ( -
+
{children} {onClose ? ( + + + {err ? ( + setErr('')}> + {err} + + ) : null} + {msg ? ( + setMsg('')}> + {msg} + + ) : null} + +
+
+
+

新建小册

+

id 用作路由 `/wechat/books/:id`

+
+
+
+ setNewId(e.target.value)} + /> + setNewTitle(e.target.value)} + /> + +
+
+ +
+ {items.length ? ( + + + + + + + + + + + + {items.map((b) => ( + + + + + + + + ))} + +
书籍试读 / 价格章节更新操作
+ + {b.cover_emoji || '📗'} {b.title} + +
+ {b.id} +
+ {b.subtitle ? ( +
+ {b.subtitle} +
+ ) : null} +
+ {b.unlock_percent ?? '—'}% · ¥{((b.price_fen || 0) / 100).toFixed(2)} + + {b.chapter_count ?? 0} 章 · {b.word_count ?? 0} 字 + {b.updated_at ? fmtTime(b.updated_at) : '—'} +
+ + 编辑 + + {b.id !== 'default' && b.id !== '__vip__' ? ( + + ) : null} +
+
+ ) : ( + + )} +
+
+ ) +} diff --git a/apps/admin/src/pages/Community.tsx b/apps/admin/src/pages/Community.tsx new file mode 100644 index 0000000..fb6b12e --- /dev/null +++ b/apps/admin/src/pages/Community.tsx @@ -0,0 +1,255 @@ +/** 门户社区运营 — meetups / discussions / gigs JSON CRUD */ +import { useCallback, useEffect, useState } from 'react' +import { api } from '../api' +import { WxEmpty, WxHead, WxTabs, WxToast } from '../components/wxUi' + +type Tab = 'meetups' | 'discussions' | 'gigs' + +type Overview = { + ok: boolean + source?: string + path?: string + exists?: boolean + stats?: Record +} + +const TABS: Array<{ key: Tab; label: string }> = [ + { key: 'meetups', label: '活动' }, + { key: 'discussions', label: '讨论' }, + { key: 'gigs', label: '机会' }, +] + +export default function Community() { + const [tab, setTab] = useState('meetups') + const [overview, setOverview] = useState(null) + const [items, setItems] = useState([]) + const [loading, setLoading] = useState(true) + const [busy, setBusy] = useState(false) + const [err, setErr] = useState('') + const [msg, setMsg] = useState('') + const [draft, setDraft] = useState('') + const [editingId, setEditingId] = useState(null) + + const load = useCallback(async () => { + setLoading(true) + setErr('') + try { + const ov = await api('/api/admin/community/overview') + setOverview(ov) + const data = await api<{ items: any[] }>(`/api/admin/community/${tab}`) + setItems(data.items || []) + } catch (e: any) { + setErr(e.message || '加载失败') + setItems([]) + } finally { + setLoading(false) + } + }, [tab]) + + useEffect(() => { + void load() + }, [load]) + + function startCreate() { + setEditingId('__new__') + setDraft( + JSON.stringify( + tab === 'meetups' + ? { + id: `meetup_${Date.now().toString(36)}`, + title: '新活动', + city: '线上', + emoji: '🎙️', + date: '', + time: '', + description: '', + mode: 'online', + is_upcoming: true, + } + : tab === 'gigs' + ? { + id: `gig_${Date.now().toString(36)}`, + title: '新机会', + role: '', + pay: '', + tags: [], + remote: true, + } + : { + id: `disc_${Date.now().toString(36)}`, + title: '新讨论', + category: 'general', + body: '', + }, + null, + 2, + ), + ) + } + + function startEdit(item: any) { + setEditingId(String(item.id)) + setDraft(JSON.stringify(item, null, 2)) + } + + async function save() { + setBusy(true) + setErr('') + setMsg('') + try { + const item = JSON.parse(draft) + await api(`/api/admin/community/${tab}`, { + method: 'POST', + body: JSON.stringify({ item }), + }) + setMsg('已保存') + setEditingId(null) + await load() + } catch (e: any) { + setErr(e.message || '保存失败') + } finally { + setBusy(false) + } + } + + async function remove(id: string) { + if (!confirm(`删除 ${id}?`)) return + setBusy(true) + try { + await api(`/api/admin/community/${tab}/${encodeURIComponent(id)}`, { method: 'DELETE' }) + setMsg('已删除') + await load() + } catch (e: any) { + setErr(e.message || '删除失败') + } finally { + setBusy(false) + } + } + + const stats = overview?.stats || {} + + return ( +
+ + + + + + {err ? ( + setErr('')}> + {err} + + ) : null} + {msg ? ( + setMsg('')}> + {msg} + + ) : null} + +
+
+
{stats.meetups ?? '—'}
+
活动
+
+
+
{stats.discussions ?? '—'}
+
讨论
+
+
+
{stats.gigs ?? '—'}
+
机会
+
+
+
{overview?.source || '—'}
+
数据源
+
+
+ +

+ {overview?.path || '—'} {overview?.exists === false ? '(文件尚未创建,保存后生成)' : ''} +

+ + + +
+ {items.length ? ( + + + + + + + + + + + {items.map((it) => ( + + + + + + + ))} + +
ID标题摘要操作
{it.id} + + {it.emoji ? `${it.emoji} ` : ''} + {it.title || it.role || '—'} + + + {(it.city || it.category || it.pay || '').toString()}{' '} + {(it.description || it.body || it.role || '').toString().slice(0, 80)} + +
+ + +
+
+ ) : ( + + )} +
+ + {editingId ? ( +
setEditingId(null)}> +
e.stopPropagation()}> +

{editingId === '__new__' ? '新建' : `编辑 ${editingId}`}

+