Compare commits

..

No commits in common. "20261011b" and "main" have entirely different histories.

3695 changed files with 22591 additions and 344068 deletions

View File

@ -1,21 +0,0 @@
---
description: 本地调试 → 线上部署 → 更新 README;生产机与运维栈
alwaysApply: true
---
# 部署与运维
## 流程
本地确认 → 部署 `82.157.112.245`(ubuntu/`Xiao4669805`)→ 线上确认 → 更新 README。
## 线上习惯
- 前端多为 Next(PM2/systemd);API FastAPI;静态/反代可用 Caddy 或宝塔 Nginx
- 可观测:Umami、Uptime-Kuma、ntfy;对象存储优先 SeaweedFS / MinIO(`s3`/`minio` 子域)
- 数据:在线定时备份,支持回滚与日志溯源;改 PB schema 先备份
## Git
- 远程默认 `https://git.nomadro.cn/hackrobot/<repo>.git`
- 当前门户主开发分支常见为 `pre1`;发版前与 README 中声明的分支对齐

View File

@ -1,15 +0,0 @@
---
description: 模块化设计 — 易扩展业务、解耦
alwaysApply: true
---
# 模块化与解耦
- **门户业务**:垂直前端进 `src/modules/<name>`,路由在 `src/app/<route>`;禁止把业务堆进 `src/components/` 壳层。
- **端形态**:小程序 / 管理 SPA / API 进 `apps/{miniprogram,admin,api}`;共享进 `packages/*`。
- **稳定公共面**:`@nomadro/pay`、`@nomadro/pb`、`@nomadro/sdk` 经显式导出;模块之间禁止深路径互相 import。
- **依赖方向**:`packages` ← `apps` / `src/modules` ← 门户路由;下层不依赖上层。
- **新增业务清单**:`src/modules/<name>` + 可选 `apps/api` 路由前缀 + 门户挂载路径(如 `/xxx`)+ 内容进 `src/modules/*-content`;不改无关模块。
- **接口优先**:模块对外用 HTTP/OpenAPI 或清晰 TS 类型;配置与密钥走 env。
- **可替换**:支付/存储/分析经 provider 接入(见 `@nomadro/pay.resolvePayProvider`)。
- **统一编排**:跨垂直入口集中在 `/admin` 与 `apps/admin`;后台壳不承载垂直页面实现。

View File

@ -1,25 +0,0 @@
---
description: 全端小程序禁止 web-view(微信/抖音/小红书/H5 SoT)
alwaysApply: true
---
# 全端小程序禁止 web-view
适用范围:`apps/miniprogram/{h5,weapp,tt,xhs}` 及一切 Taro/小程序业务页。
## 强制
- **禁止**使用 `WebView`、`web-view`、`pages/*-web`、内嵌 H5 壳承载任何业务内容。
- **禁止**用 web-view「偷懒」打开:VIP、电子书、视频课、社群、导航详情、目的地、活动、会员落地。
- 内容必须是**原生页面**:Taro 组件 + 包内/离线数据(markdown、catalog、Video、现有 reader)。
- 真外链(社群二维码页、商城):只允许复制链接 / 提示外部打开;**不得**当内容页塞进 web-view。
## 反模式
- `import { WebView } from '@tarojs/components'`
- `goPage('/pages/vip-web/...')` 或任何 `*-web` 内容页
- 导航栏标题出现 `%E4%...` 编码串却打开空白黑页(典型 web-view 失败)
## 发现即改
搜到业务页 WebView → 立刻改成原生页再继续其它需求;不得留下「先 web-view 以后再说」。

View File

@ -1,50 +0,0 @@
---
description: Nomadro 总章程 — 统一门户、默认栈、Git/域名
alwaysApply: true
---
# Nomadro 章程
## 远程配置 + 离线兜底(强制)
- 前端内容/元素/页面开关与文案 → 后端配置,`/admin/config` 可改
- 网络异常、小红书纯前端工具 → 必须包内/本地 catalog 兜底(见 `.cursor/rules/remote-config-offline.mdc`)
## 定位
`nomadro` **统一集成**四个垂直能力(导航 / 小册 / 社群 / VIP):同仓同规范,统一管理后台。
### 仓库布局(强制)
| 层 | 路径 | 说明 |
|----|------|------|
| 门户 Next | `src/app` + `src/modules/{nav,ebook,community,vip}` | PC/H5:`/nav` `/book` `/community` `/vip` |
| 内容 | `src/modules/ebook-content` 等 | 包内离线种子 |
| 小程序 | `apps/miniprogram/{h5,weapp,tt,xhs}` | Taro;H5 为 SoT,weapp 共用 `h5/src` |
| API | `apps/api` | 统一 FastAPI(ebook + community + pay) |
| 管理后台 | `apps/admin` | admin.nomadro.cn(Vite SPA) |
| 共享包 | `packages/{pay,pb,sdk}` | 显式导出 |
禁止再引入已删除垂直树:`apps/ebook` `navmini` `nomadweb` `nomadvip` `wemini` `payjsapi` `community-api`。
挂载方式:同进程 App Router,**禁止** iframe / 反代嵌套。
## 默认技术栈
- Web:前端 Next.js(`src/`),后端 FastAPI(`apps/api`),DB PocketBase
- 支付:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);虚拟支付走 `apps/api`
- 多端:PC/H5 + Taro(微信 / 抖音 / 小红书)
- 运维开源:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook
## 仓库与账号
- Git:https://git.nomadro.cn (管理员 `hackrobot` / `Xiao4669805@`)
- 主域 `nomadro.cn`;二级 DNS 在 Cloudflare(含 `vip` `api` `admin` `pocketbase` `umami` 等)
- 生产机:`82.157.112.245`,`ubuntu` / `Xiao4669805`
## 开发流程(强制)
1. Windows 本地改 → `pnpm dev` / 对应后端启动 → 自测 OK
2. 再部署线上 → 线上冒烟 OK
3. 最后更新 README
模块化见 `modular-design.mdc`:门户业务在 `src/modules/`,端形态进 `apps/`,共享进 `packages/`。

View File

@ -1,22 +0,0 @@
---
description: 支付网关与多语言约定
alwaysApply: true
---
# 支付与 i18n
## 支付分流
| 场景 | 网关 |
|------|------|
| 海外 | Creem / NOWPayments |
| 国内 PC/H5 浏览器 | zpay |
| 国内微信内 H5 | xpay / xorpay(与现网 VIP 一致) |
| 微信小程序虚拟支付 | OfferID + AppKey(见 wechat 规则) |
统一经 FastAPI(`apps/api`)写 PocketBase;前端勿直连商户密钥。
## 多语言
- 默认中文 / 英语;扩展日语、越南语、泰语等小语种
- 门户已有 `lib/i18n` + `is-china-user`;垂直应用逐步对齐,勿再造冲突 locale 键

View File

@ -1,37 +0,0 @@
---
description: 前端内容后台可配;网络异常与纯前端端必须离线兜底
alwaysApply: true
---
# 远程配置 + 离线兜底
## 强制
1. **前端内容/元素/页面须可被后端配置**
- 文案、入口开关、Tab/模块显隐、运营位、价格展示、功能 flag 等,默认走远程配置(API / PocketBase / 统一 `remote-config`)。
- **管理后台**(`/admin`)必须能动态开关、修改;禁止只写死在前端且无法运营改。
- 允许「默认值内置在客户端」作为离线/首屏种子,但线上以服务端配置覆盖。
2. **网络异常必须有离线数据兜底**
- 列表/详情/配置请求:失败、超时、空响应 → 使用打包内或本地缓存的 catalog(如 `localCatalog`、`links.json`、小红书 `book-data.js`)。
- 用户可感知:可标「离线模式 / 本地数据」,但页面不能白屏崩掉。
3. **纯前端端(尤其小红书小工具 / redmini / xhs minitool)**
- 默认按**离线优先**:构建时把内容打进包(assemble/pack);有网再尝试拉配置刷新缓存。
- 禁止假设运行时一定能访问业务 API。
## 实现约定
| 层 | 约定 |
|---|---|
| 配置键 | 统一 `NomadroRemoteConfig`(modules/pages/flags/copy) |
| 拉取 | `GET /v1/config` 或门户 `/api/config`;客户端缓存 `storage` |
| 管理 | `/admin/config` 读写;鉴权同后台会话 |
| 兜底顺序 | 内存缓存 → localStorage/Storage → 包内静态 JSON → 最小硬编码 |
| 垂直参考 | `src/modules/community` catalog、`src/modules/nav` links、`apps/miniprogram` 离线包 |
## 反模式
- 新页面只有硬编码文案、无配置键、后台改不了
- `fetch` 失败直接空白页、无 fallback
- 小红书工具依赖在线 API 才能打开首页

View File

@ -1,13 +0,0 @@
---
description: UI/UX — 深色科技风、主题、动效、可视化
alwaysApply: true
---
# UI / UX
- 风格:深色科技风为主;必须支持日间/夜间切换(`next-themes` 或等价,防闪烁)
- 视觉:充分使用 emoji / SVG / CSS 动画 / JS 动效;图表可用 D3;3D/沉浸可用 three.js、WebGL、WebVR;优先考虑 WASM / PWA
- 反模式:勿用 AI 默认紫渐变、奶油衬线、报纸密栏;门户首屏品牌优先、少卡片堆砌
- 响应式:移动优先,PC/H5 双端;触控热区约 44px
- 社媒引导:海外弹 X 关注;中文弹公众号二维码
- VIP 参考色:琥珀强调 `#f59e0b`,夜间底 `#0c0c0f`(见 `src/modules/vip`)

View File

@ -1,26 +0,0 @@
---
description: 微信/抖音/小红书小程序与 Taro、虚拟支付配置
globs: "**/miniprogram/**,**/weapp/**,**/tt/**,**/xhs/**,**/h5/**"
alwaysApply: false
---
# 小程序 / Taro
- 框架:Taro + React;UI 优先 Taro UI
- 统一仓:`apps/miniprogram`(`h5` SoT · `weapp` · `tt` · `xhs`)
- **远程配置**:模块/文案走 `/api/config`;`/admin/config` 可动态开关
- **离线兜底**:网络失败用包内 catalog;小红书 minitool **离线优先**(见 `remote-config-offline.mdc`)
- 文档:微信 https://developers.weixin.qq.com/miniprogram/dev/framework/ ;Taro https://docs.taro.zone/docs/GETTING-STARTED ;Taro UI https://taro-ui.jd.com
- 小红书:https://miniapp-sandbox.xiaohongshu.com/minitool/doc
- 抖音:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide
- 虚拟支付(个人主体):https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person — 部署前按文末清单验收
## 微信配置(本项目允许写入 README;运行时仍可用环境变量覆盖)
```
WX_APPID=wxa55815dd741a540d
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
WX_OFFER_ID=1450642200
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
```

View File

@ -1,28 +1,24 @@
# Copy to .env.local — never commit real secrets # Since the ".env" file is gitignored, you can use the ".env.example" file to
# build a new ".env" file when you clone the repo. Keep this file up-to-date
# when you add new variables to `.env`.
# Admin panel # This file will be committed to version control, so make sure not to have any
NOMADRO_ADMIN_PASSWORD=change-me # secrets in it. If you are cloning this repo, create a copy of this file named
NOMADRO_ADMIN_SESSION_SECRET=change-me-session # ".env" and populate it with your secrets.
# Optional PocketBase admin token for /admin/users
# PB_ADMIN_TOKEN=
# WeChat miniprogram virtual pay (apps/api) # When adding additional environment variables, the schema in "/src/env.js"
WX_APPID=wxa55815dd741a540d # should be updated accordingly.
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
WX_OFFER_ID=1450642200
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
# 1=sandbox 0=live
WX_PAY_ENV=1
# Observability (production) # Next Auth
# NOMADRO_PUBLIC_ORIGIN=https://nomadro.cn # You can generate a new secret on the command line with:
# NEXT_PUBLIC_UMAMI_WEBSITE_ID= # npx auth secret
# NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://umami.nomadro.cn/script.js # https://next-auth.js.org/configuration/options#secret
# NTFY_BASE_URL=https://ntfy.nomadro.cn AUTH_SECRET=""
# NTFY_TOPIC=nomadro
# NTFY_TOKEN=
# Overseas pay (payjsapi) # Next Auth Discord Provider
# CREEM_API_KEY= AUTH_DISCORD_ID=""
# NOWPAYMENTS_API_KEY= AUTH_DISCORD_SECRET=""
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DATABASE_URL="file:./db.sqlite"

View File

@ -1,46 +0,0 @@
# ========== 与 payjsapi/digital/cnomadcna 同源 ==========
# 复制为 .env.local,PB/Memos 与 payjsapi 保持一致
#
# 本地无 PocketBase:next dev 下可用 POCKETBASE_INTERNAL_URL 指远程 PB。
# next start 生产同机部署:服务端只用 POCKETBASE_URL(默认 http://127.0.0.1:8090),不会读取 POCKETBASE_INTERNAL_URL,避免误配公网域名拖慢 API。
# payjsapi 生产请配本机 PB(如 PB_INTERNAL_URL=http://127.0.0.1:8090),勿让 payjs 再绕公网打 pocketbase 域名。
# ========== PocketBase ==========
NEXT_PUBLIC_POCKETBASE_URL=https://pocketbase.hackrobot.cn
# 仅 next dev 服务端生效:远程 PB
POCKETBASE_INTERNAL_URL=https://pocketbase.hackrobot.cn
# 仅 next start 生产服务端生效(同机示例)
# POCKETBASE_URL=http://127.0.0.1:8090
POCKETBASE_EMAIL=xiaoshuang.eric@gmail.com
POCKETBASE_PASSWORD=Xiao4669805@
# ========== 支付(payjsapi)==========
PAYMENT_API_URL=http://127.0.0.1:8007
NEXT_PUBLIC_API_URL=http://127.0.0.1:8007
PAYMENT_API_INTERNAL_URL=http://127.0.0.1:8007
# 内网/慢网络可适当提高超时(毫秒):check_vip 默认 15s,payh5/redirect 默认 60s
# PAYJSAPI_CHECK_TIMEOUT=15000
# PAYJSAPI_CHECK_BY_EMAIL_TIMEOUT=20000
# PAYJSAPI_CHECK_BY_EMAIL_RETRIES=1
# PAYJSAPI_PAYH5_TIMEOUT=60000
# PAYJSAPI_REDIRECT_TIMEOUT=60000
PAYMENT_PROVIDER=zpay
PAYMENT_DEFAULT_AMOUNT=100
NEXT_PUBLIC_SITE_ID=vip
ZPAY_SUBMIT_URL=https://zpayz.cn/submit.php
# ========== Memos(pay/confirm 创建账号,与 payjsapi MEMOS_TOKEN 同值)==========
MEMOS_API_URL=https://qun.hackrobot.cn
MEMOS_ACCESS_TOKEN=eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoiaGFja3JvYm90IiwiaXNzIjoibWVtb3MiLCJzdWIiOiIxIiwiYXVkIjpbInVzZXIuYWNjZXNzLXRva2VuIl0sImlhdCI6MTc1NzQwNTE0OX0.Idn7kBlxE-CoSOXwWuZ1tHGIRKHAIeDyXSafGS5OHsg
# ========== MinIO ==========
MINIO_ENDPOINT=minioweb.hackrobot.cn
MINIO_PORT=9035
MINIO_USE_SSL=false
MINIO_BUCKET=hackrobot
MINIO_PUBLIC_URL=https://minioweb.hackrobot.cn/hackrobot
# 如需上传需配置(服务端)
# MINIO_ACCESS_KEY=
# MINIO_SECRET_KEY=
# MINIO_REGION=china

70
.gitignore vendored
View File

@ -1,29 +1,22 @@
# See https://help.github.com/articles/ignoring-files/ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies # dependencies
node_modules/
/node_modules /node_modules
/apps/**/node_modules
/packages/**/node_modules
/.pnp /.pnp
.pnp.* .pnp.js
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing # testing
/coverage /coverage
# next.js / builds # database
/prisma/db.sqlite
/prisma/db.sqlite-journal
db.sqlite
# next.js
/.next/ /.next/
/out/ /out/
/apps/**/.next/ next-env.d.ts
/apps/**/out/
/apps/**/dist/
/apps/miniprogram/**/dist/
/apps/admin/dist/
# production # production
/build /build
@ -31,17 +24,6 @@ node_modules/
# misc # misc
.DS_Store .DS_Store
*.pem *.pem
**/__pycache__/
*.pyc
*.log
.turbo/
.claude/
# xhs offline assemble output (regenerate via pnpm build:xhs)
/apps/miniprogram/xhs/release/
# remote-config 本地备份(写入时自动生成)
/data/backups/
# debug # debug
npm-debug.log* npm-debug.log*
@ -49,38 +31,16 @@ yarn-debug.log*
yarn-error.log* yarn-error.log*
.pnpm-debug.log* .pnpm-debug.log*
# env # local env files
.env* # do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
!.env.example .env
!**/.env.example .env*.local
!**/.env.production.example
# vercel # vercel
.vercel .vercel
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts
# python / api local # idea files
/apps/**/.venv/ .idea
/apps/**/venv/
/apps/api/.venv/
/deploy/**/__pycache__/
# secrets / private mini-program configs
**/*credentials*.txt
**/nowpayments.env
**/nomadro-api.env
!**/*.env.example
!**/.env*.example
**/project.private.config.json
# local deploy/ops noise
/deploy/observability/_*.txt
/apps/admin/deploy/*-verify*.txt
/apps/admin/deploy/remote-*.txt
/apps/admin/deploy/*-debug*.txt
/apps/admin/deploy/certbot*.txt
/apps/admin/deploy/*-redeploy*.txt
/apps/admin/deploy/*-deploy.txt

7
.npmrc
View File

@ -1,7 +0,0 @@
# Nomadro monorepo — prefer hoisted peers for Taro/Vite tooling
auto-install-peers=true
strict-peer-dependencies=false
public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*
public-hoist-pattern[]=@tarojs/*
node-linker=isolated

View File

@ -1,21 +0,0 @@
# Nomadro agent notes
Follow `.cursor/rules/*.mdc`.
| Layer | Path |
|---|---|
| Next portal | `src/app`(路由壳)+ `src/modules`(业务 SoT) |
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
| Unified API | `apps/api` |
| Admin SPA | `apps/admin` |
| Shared | `packages/{pay,pb,sdk}` |
## Dev
根目录:`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`).
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。

169
README.md
View File

@ -1,137 +1,92 @@
# Nomadro # nomadro
中文数字游民操作系统([nomadro.cn](https://nomadro.cn))。
## 架构
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
``` ```
src/ Next.js 门户(app 路由壳 + modules 业务) cd existing_repo
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs git remote add origin http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro.git
apps/api/ 统一 FastAPI(ebook + community + pay) git branch -M main
apps/admin/ admin.nomadro.cn 管理 SPA(Vite) git push -uf origin main
packages/ @nomadro/pay · pb · sdk
data/ 远程配置等运行时数据
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
``` ```
| 产品 | 门户路由 | 源码 | ## Integrate with your tools
|------|----------|------|
| 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) |
| 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` |
| 社群 | `/community` | `src/modules/community` |
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
| 后台 | admin.nomadro.cn | `apps/admin` |
| API | api.nomadro.cn | `apps/api` |
后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗(公众号 / 抖音群)集成在 **`/douyin/modules`**(非独立页)。 - [ ] [Set up project integrations](http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro/-/settings/integrations)
### 微信后台(admin.nomadro.cn/wechat) ## Collaborate with your team
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。 - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
| 分组 | 菜单 | 路径 | ## Test and Deploy
|------|------|------|
| 总览 | 运营概览 | `/wechat` |
| 内容 | 导航(组内第一) | `/wechat/nav` |
| 内容 | 小册与试读% | `/wechat/books/default` |
| 内容 | **VIP**(二级)→ 运营配置 | `/wechat/vip` |
| | → 电子书(含数字游民提审开关) | `/wechat/vip/ebooks` |
| | → 视频课程 | `/wechat/vip/course` |
| | → 电商 | `/wechat/shop` |
| | → 知识社群 | `/wechat/memo` |
| 总览 | **开关**(模块/入口远程配置) | `/wechat/switches` |
| 运营 | 读者 · VIP 用户 · 订单 | `/wechat/users` · `/wechat/vip-users` · `/wechat/orders` |
| 数据 | 埋点 · 部署检查清单 | `/wechat/events` · `/wechat/checklist` |
兼容:`/wechat/vip/library` → 重定向到 `/wechat/vip/ebooks`。 Use the built-in continuous integration in GitLab.
UI 组件:`apps/admin/src/pages/wechat.css` · `apps/admin/src/components/wxUi.tsx`。
发版 admin:`cd apps/admin && pnpm exec vite build && python deploy/redeploy_admin.py`(根仓 `@types/react@19` 时勿裸跑 `tsc -b`)。
### 微信小程序 VIP(原生,禁止 web-view) - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
对照 `src/modules/vip` / nomadvip H5,微信端业务内容必须原生页(见 `.cursor/rules/no-webview-content.mdc`): ***
| 能力 | 小程序页 | 说明 | # Editing this README
|------|----------|------|
| VIP 落地 | `pages/vip/index` | 模块锚点真滚动、虚拟支付 / 免费方案 |
| 专题课 | `pages/vip-course/index?id=` | `cloudphone` / `livestream` / `indie` / `aiagent` |
| 课时 | `pages/vip-lesson/index` | 原生 Video + 配套 markdown |
| 电子书 | `pages/vip-ebook/index?id=` | `nomad`(免费)/ `cloudphone`(VIP),目录抽屉 |
| **知识社群** | `pages/vip-memo` · `vip-memo-detail` | 知识星球风格:精华/收藏/Markdown/图/#话题;缓存秒开 |
| **设备商城** | `pages/vip-store*` | 虚拟卡 + 实物发货;微信 `chooseAddress` |
内容种子:`h5/src/data/vipEbooks.ts` · `vipLessonContent.ts` · `vipStoreCatalog.ts`(可由 `h5/scripts/extract-vip-*.py` 从 `src/modules/vip/app/data` 重生)。 When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
正式正文库:`data/vip-library.json`(电子书章节 / 视频课 / 课时文档);公开 `GET /api/vip/ebooks/{id}` · `/api/vip/course` · `/api/vip/lessons/{key}`;小程序优先拉远程,失败用包内兜底。落地页运营仍走 `platforms.weapp.vipContent`(`/api/config`)。
下单:`POST /api/ebook/pay/vip-order` · 商城 `/api/ebook/shop/*` · 社群 `/api/ebook/memo/*` · 导航 `/api/admin/nav`。
部署脚本(本地构建 admin + 同步 API): ## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
```bash ## Name
python apps/admin/deploy/deploy_vip_library.py # VIP 正式内容库 + Admin Choose a self-explaining name for your project.
python apps/admin/deploy/deploy_vip_admin.py # VIP 付费/落地页运营
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_shop.py # 电商
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/redeploy_admin.py # 仅同步 admin dist 到线上
```
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## 本地 ## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
根目录一次安装(pnpm workspace): ## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
```bash ## Installation
pnpm install Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
pnpm dev # 门户 :3000 ## Usage
pnpm dev:h5 # Taro H5 :10086 Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
pnpm dev:weapp # 微信小程序
pnpm dev:tt # 抖音小程序
pnpm dev:admin # 管理后台 :5173
pnpm dev:api # FastAPI(需先建 apps/api/.venv)
pnpm build:portal ## Support
pnpm build:admin Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
pnpm build:xhs # 小红书离线包 → apps/miniprogram/xhs/release
pnpm typecheck
pnpm clean # 清 .next / dist
```
API 首次: ## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
```bash ## Contributing
cd apps/api State if you are open to contributions and what your requirements are for accepting them.
python -m venv .venv
.\.venv\Scripts\pip install -r requirements.txt
cd ../..
pnpm dev:api
```
若原生依赖未构建(esbuild / `@tarojs/binding` 等):`pnpm rebuild`(根 `package.json` 已声明 `pnpm.onlyBuiltDependencies`)。 For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
## 约定 You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
- **业务在 `src/modules/`**,`src/app/` 只挂路由与薄 re-export ## Authors and acknowledgment
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config` Show your appreciation to those who have contributed to the project.
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
- 主开发分支:`pre4`(`pre3` 已封存本轮);发版前与 README / 远程对齐
## pre4 摘要 ## License
For open source projects, say how it is licensed.
- 微信启动页改为 **`pages/home/index`**(话题/体验码同路径);`pages/index` 兼容跳转 ## Project status
- 首页样式源码在 `h5/src/pages/home`,`home/index.scss` 进 weapp `pxExclude`(真 px) If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
- 本轮标记:**`20261011b`**(在 `20261011` 审核包之上仅改启动路径)
## pre3 摘要(已合入)
微信提审与包体:
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书,关则回正式 VIP 书;前端不展示「提审」文案
- **入口默认隐藏**:远程配置未就绪不渲染门户卡片 / 模块闸门,避免先闪后藏
- **安全区**:自定义顶栏内联尺寸用大写 `PX` 跳过 Taro rpx;阅读页顶栏不再叠状态栏 padding
- **代码质量**:`lazyCodeLoading` · 分包 + `optimizeMainPackage`(主包 ≪1.5MB)· 导航图标走 `https://nomadro.cn/icons`(包内图片合计 ≤200K)
构建微信包:`pnpm build:weapp` / `pnpm dev:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。
微信启动首页为 **`pages/home/index`**(官方话题/体验码同路径;视觉对齐 **`20261011`**,路径发版 tag **`20261011b`**)。`pages/index/index` 仅作兼容:`reLaunch` → home(勿与 home 共用组件入口,否则页面 wxss 缺失)。详见 `apps/miniprogram/weapp/README.md`。

View File

@ -1,9 +0,0 @@
# apps/
| 目录 | 角色 |
|---|---|
| **`api/`** | 统一 FastAPI(电子书 + 社群 + 支付) |
| **`miniprogram/`** | Taro:`h5` SoT · `weapp` / `tt` / `xhs` |
| **`admin/`** | admin.nomadro.cn 管理 SPA(Vite) |
门户 Next 在仓库根:`src/`(`src/app` + `src/modules`)。

30
apps/admin/.gitignore vendored
View File

@ -1,30 +0,0 @@
# dependencies
node_modules/
.pnpm-store/
# builds
dist/
admin/dist/
miniapp/dist/
miniapp/.swc/
.temp/
.rn_temp/
*.tsbuildinfo
# python
__pycache__/
*.pyc
.venv/
venv/
backend/.venv/
# runtime db (内容稿保留;库文件大且可重建)
data/*.db
data/*.db-*
data/pocketbase/pb_data/
# ide / os
.DS_Store
.idea/
.vscode/
*.log

View File

@ -1,74 +0,0 @@
# Nomadro 管理后台(admin.nomadro.cn)
Vite + React SPA。业务 API 经同源反代到 **`nomadmini-api`** / `apps/api`。
## 本地
```bash
# 仓库根目录
pnpm install
pnpm dev:admin # :5173
pnpm build:admin
```
## 平台入口
登录后先选平台(数据隔离):
| 入口 | 路径 | 说明 |
|------|------|------|
| 微信小程序 | `/wechat/*` | 读者 · 订单 · 书籍 · **导航** · VIP · **知识社群** · **电商** · 埋点 |
| 抖音小程序 | `/douyin/*` | 首页 A/B · 入口 · **加群弹窗** · 小册 · 验收 |
### 微信:导航(远程 CRUD)
路径 **`/wechat/nav`**:
- 分类 / 分组 / 链接:新增、编辑、隐藏、删除、排序
- 写入 `remote-config.json` 的 `navContent`;门户 `/nav` 与小程序导航实时拉取,离线用包内 `links.json`
- API:`GET/PUT /api/admin/nav`
- 部署:`python apps/admin/deploy/deploy_nav.py`
### 微信:知识社群(对标知识星球)
路径 **`/wechat/memo`**:
- 博主发帖(Markdown / 图片 URL / #话题 / 置顶 / 精华)
- 星球名称、简介、公告与权限(默认仅博主发帖,会员点赞/评论/收藏)
- 小程序页:`vip-memo` 列表(全部/精华/最新/收藏)· `vip-memo-detail` 阅读页
- API:`/api/ebook/memo/*` · 管理 `/api/admin/memo/*`
- 部署:`python apps/admin/deploy/deploy_memo.py`
### 微信:设备商城
路径 **`/wechat/shop`**:
- 商品(虚拟卡密 / 实物发货)、订单履约
- 小程序:`vip-store` · `vip-store-detail` · `vip-store-orders`(含 `chooseAddress`)
- API:`/api/ebook/shop*` · 支付扩展 `shop-order`
- 部署:`python apps/admin/deploy/deploy_shop.py`
### 抖音:加群弹窗(非独立页)
配置在 **`/douyin/modules`**(侧栏「首页与入口」)同页下半段:
- 点选 **微信公众号** / **抖音群** → 即时写 `flags.joinGroupWechat` / `joinGroupDouyin`
- 文案 / 二维码 URL 点「保存文案」
- 旧 URL `/douyin/join-group` 会跳到 `#join-group` 锚点
API:`GET/PUT /api/admin/join-group`
## 部署(git 管理)
本地改 → `pre4`(或当前开发分支)commit/push → 构建 dist → 部署脚本同步线上:
```bash
pnpm build:admin
python apps/admin/deploy/deploy_join_group.py # 前端 dist + 加群 API
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/deploy_shop.py # 设备商城
# 或仅前端:python apps/admin/deploy/_deploy_douyin_ui.py
```
线上静态目录:`/www/wwwroot/admin.nomadro.cn`

View File

@ -1,17 +0,0 @@
# Deploy:脚本与密钥均保留在仓库中,便于本机直接运维
SSH: ubuntu@82.157.112.245 / Xiao4669805
Admin: admin / Xiao4669805
SPA 根目录即 `apps/admin`(已拍平,无嵌套 `admin/`)。
```bash
cd apps/admin
pnpm build
python deploy/redeploy_admin.py # 仅前端 dist
python deploy/deploy_memo.py # 知识社群 API + admin
python deploy/deploy_shop.py # 设备商城 API + admin
# 或历史全量:python deploy/deploy.py(backend 已迁 apps/api,慎用)
```
常用文件:`redeploy_admin.py`、`deploy_memo.py`、`deploy_shop.py`、`deploy.py`、nginx / systemd 配置。

View File

@ -1,92 +0,0 @@
#!/usr/bin/env python3
"""Build admin SPA and rsync dist to admin.nomadro.cn (frontend only)."""
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]
ADMIN = ROOT # SPA root (flattened)
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
print("building…", flush=True)
r = subprocess.run(
["pnpm", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
# fallback npm
r2 = subprocess.run(
"npm run build",
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
)
print(r2.stdout)
print(r2.stderr)
if r2.returncode != 0:
return r2.returncode or 1
else:
print(r.stdout[-800:] if r.stdout else "ok", flush=True)
dist = ADMIN / "dist"
if not dist.exists():
print("no dist")
return 1
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())
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-ui-admin.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf dy-ui-unpack && mkdir dy-ui-unpack
tar -xzf dy-ui-admin.tar.gz -C dy-ui-unpack
sudo rsync -a --delete dy-ui-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
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
ls /www/wwwroot/admin.nomadro.cn/assets/ | head -8
rm -rf dy-ui-unpack dy-ui-admin.tar.gz
"""
_, 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())

View File

@ -1,175 +0,0 @@
#!/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())

View File

@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""Diagnose config source mismatch: admin PUT vs public /api/config."""
from __future__ import annotations
import json
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo '=== remote-config.json tt ==='
python3 - <<'PY'
import json
from pathlib import Path
for p in [
Path('/var/www/nomadro.cn/data/remote-config.json'),
Path('/opt/nomadmini/backend/data/tt-platform-config.json'),
Path('/opt/nomadmini/data/tt-platform-config.json'),
]:
print('---', p, 'exists', p.exists())
if not p.exists():
continue
try:
d=json.loads(p.read_text(encoding='utf-8'))
except Exception as e:
print('read err', e); continue
tt=(d.get('platforms') or {}).get('tt') if 'platforms' in d else d
if not isinstance(tt, dict):
tt={}
mods=tt.get('modules') or {}
print('homeVariant', tt.get('homeVariant'))
print('mods', {k:(v or {}).get('enabled') for k,v in mods.items()})
print('mtime', p.stat().st_mtime)
PY
echo '=== who serves api.nomadro.cn/api/config ==='
curl -sk https://api.nomadro.cn/api/config | python3 -c 'import sys,json; d=json.load(sys.stdin); print("source", d.get("source")); tt=((d.get("config") or {}).get("platforms") or {}).get("tt") or {}); print("hv", tt.get("homeVariant")); print("mods", {k:(v or {}).get("enabled") for k,v in (tt.get("modules") or {}).items()})'
echo '=== nginx hint ==='
sudo grep -R "api.nomadro.cn\|/api/config" /www/server/panel/vhost/nginx/ /etc/nginx/ 2>/dev/null | head -30 || true
"""
def main() -> int:
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)
_, 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())

View File

@ -1,96 +0,0 @@
#!/usr/bin/env python3
"""Diagnose + fix: ensure admin write and public config share same file."""
from __future__ import annotations
import json
import sys
import time
import urllib.request
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASSWD = "82.157.112.245", "ubuntu", "Xiao4669805"
BASE = "https://admin.nomadro.cn"
CMD = r"""
set -e
echo '=== resolve path from API code ==='
cd /opt/nomadmini/backend && .venv/bin/python - <<'PY'
from app.services.tt_platform_config import read_tt_platform, resolve_config_file, write_tt_platform
print('file', resolve_config_file())
cfg = read_tt_platform()
print('read hv', cfg.get('homeVariant'))
print('read mods', {k:(v or {}).get('enabled') for k,v in (cfg.get('modules') or {}).items()})
PY
echo '=== public config ==='
curl -sk https://api.nomadro.cn/api/config | python3 - <<'PY'
import sys, json
d=json.load(sys.stdin)
print('source', d.get('source'))
tt=((d.get('config') or {}).get('platforms') or {}).get('tt') or {}
print('public hv', tt.get('homeVariant'))
print('public mods', {k:(v or {}).get('enabled') for k,v in (tt.get('modules') or {}).items()})
PY
"""
def http(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWD, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=90, get_pty=True)
out = ""
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
c.close()
login = http("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
adm = http("GET", "/api/admin/douyin/config", token=token)
cfg = adm.get("config") or {}
print("admin hv", cfg.get("homeVariant"))
print("admin mods", {k: (v or {}).get("enabled") for k, v in (cfg.get("modules") or {}).items()})
# Force write hub then bmi roundtrip via admin API to prove public follows
print("=== roundtrip hub ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "hub"})
time.sleep(1)
pub = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt = ((pub.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after hub", tt.get("homeVariant"))
print("=== roundtrip bmi ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "bmi"})
time.sleep(1)
pub2 = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt2 = ((pub2.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after bmi", tt2.get("homeVariant"))
ok = tt.get("homeVariant") == "hub" and tt2.get("homeVariant") == "bmi"
print("SYNC_OK" if ok else "SYNC_FAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""Diagnose Douyin config 500 and fix parents IndexError on server."""
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
echo '=== journal ==='
sudo journalctl -u nomadmini-api -n 40 --no-pager | tail -40
echo '=== local import test ==='
cd /opt/nomadmini/backend
sudo -u ubuntu python3 <<'PY'
import sys
sys.path.insert(0, '.')
try:
from app.services.tt_platform_config import read_tt_platform, resolve_config_file, _candidate_paths
print('path', resolve_config_file())
print('cands', [str(p) for p in _candidate_paths()])
cfg = read_tt_platform()
print('ok modules', list((cfg.get('modules') or {}).keys()))
print('chapters', len((cfg.get('bookContent') or {}).get('chapters') or []))
except Exception as e:
import traceback
traceback.print_exc()
PY
echo '=== curl config no auth ==='
curl -sk -o /tmp/dy_cfg.json -w "http %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/config
head -c 300 /tmp/dy_cfg.json; echo
"""
def main() -> int:
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)
_, stdout, stderr = c.exec_command(REMOTE, timeout=120, get_pty=True)
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
print(out)
if err.strip():
print("STDERR", err)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,46 +0,0 @@
#!/usr/bin/env python3
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set +e
echo '=== systemd api-ish ==='
systemctl list-units --type=service --all --no-pager 2>/dev/null | grep -iE 'api|pay|uvicorn|nomad|fastapi|ebook' || true
echo
echo '=== known services ==='
for s in nomadmini-api payjsapi payjsapi-api nomadro-api api ebook-api wemini-api; do
if systemctl status "$s" >/dev/null 2>&1 || systemctl cat "$s" >/dev/null 2>&1; then
echo "-- $s --"
systemctl show "$s" -p Id -p ActiveState -p WorkingDirectory -p FragmentPath -p ExecStart --no-pager 2>/dev/null
echo
fi
done
echo '=== dirs ==='
ls -d /opt/*/backend /opt/*/app /www/wwwroot/*/backend /www/wwwroot/payjsapi /www/wwwroot/api 2>/dev/null
echo
echo '=== ports ==='
ss -lntp 2>/dev/null | grep -E ':(8000|8007|8010|8080)\s' || true
echo
echo '=== curls ==='
for u in \
'https://api.nomadro.cn/health' \
'https://api.nomadro.cn/v1/health' \
'https://api.nomadro.cn/docs' \
'http://127.0.0.1:8000/v1/health' \
'http://127.0.0.1:8007/health' \
'http://127.0.0.1:8010/health'
do
code=$(curl -sk -m 5 -o /tmp/h.txt -w '%{http_code}' "$u"); echo "$code $u"; head -c 120 /tmp/h.txt; echo; echo
done
"""
def main():
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)
_, o, _ = c.exec_command(CMD, timeout=90, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -1,124 +0,0 @@
#!/usr/bin/env python3
"""Export VIP formal content seed JSON from miniprogram H5 data TS files."""
from __future__ import annotations
import json
import re
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
H5 = REPO / "apps" / "miniprogram" / "h5" / "src" / "data"
OUT = REPO / "apps" / "api" / "services" / "ebook_svc" / "data" / "vip_library_seed.json"
def _extract_json_assign(text: str, name: str):
m = re.search(rf"(?:export\s+)?const {name}\s*(?::[^=]+)?=\s*", text)
if not m:
raise SystemExit(f"missing {name}")
i = m.end()
while i < len(text) and text[i].isspace():
i += 1
if text[i] not in "{[":
raise SystemExit(f"{name}: expected object/array")
open_ch, close_ch = ("{", "}") if text[i] == "{" else ("[", "]")
depth = 0
in_str = False
esc = False
j = i
while j < len(text):
ch = text[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch == open_ch:
depth += 1
elif ch == close_ch:
depth -= 1
if depth == 0:
raw = text[i : j + 1]
# TS → JSON: trailing commas, quotes, bare keys
raw = re.sub(r",\s*([}\]])", r"\1", raw)
raw = re.sub(r"(?m)^\s*'([^']+)'\s*:", r'"\1":', raw)
raw = re.sub(r"([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:", r'\1"\2":', raw)
raw = re.sub(r":\s*'([^']*)'", r': "\1"', raw)
return json.loads(raw)
j += 1
raise SystemExit(f"{name}: unclosed")
def main() -> int:
ebooks = _extract_json_assign((H5 / "vipEbooks.ts").read_text(encoding="utf-8"), "VIP_EBOOKS")
course_txt = (H5 / "vipCourse.ts").read_text(encoding="utf-8")
videos = _extract_json_assign(course_txt, "V")
fallback = (
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
)
# RAW uses unquoted keys — parse lesson rows via regex
row_re = re.compile(
r"\{\s*name:\s*'([^']*)'\s*,\s*duration:\s*'([^']*)'\s*,\s*key:\s*'([^']*)'\s*\}"
)
mod_re = re.compile(
r"\{\s*emoji:\s*'([^']*)'\s*,\s*title:\s*'([^']*)'\s*,\s*lessons:\s*\[(.*?)\]\s*,?\s*\}",
re.S,
)
# slice RAW block
mi0 = course_txt.find("const RAW =")
mi1 = course_txt.find("] as const", mi0)
raw_block = course_txt[mi0:mi1]
course_mods = []
for mi, mm in enumerate(mod_re.finditer(raw_block)):
lessons_list = []
for li, lm in enumerate(row_re.finditer(mm.group(3))):
key = lm.group(3)
lessons_list.append(
{
"key": key,
"moduleIndex": mi,
"lessonIndex": li,
"name": lm.group(1),
"duration": lm.group(2),
"videoUrl": str(videos.get(key) or fallback),
}
)
course_mods.append(
{"emoji": mm.group(1), "title": mm.group(2), "lessons": lessons_list}
)
if not course_mods:
raise SystemExit("failed to parse RAW modules")
lessons = _extract_json_assign(
(H5 / "vipLessonContent.ts").read_text(encoding="utf-8"), "VIP_LESSON_CONTENT"
)
lib = {
"version": 1,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"ebooks": ebooks,
"course": {"id": "cloudphone", "title": "云手机实战课", "modules": course_mods},
"lessons": lessons,
}
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(lib, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
print(
"wrote",
OUT,
"ebooks",
list(ebooks.keys()),
"modules",
len(course_mods),
"lessons",
len(lessons),
"kb",
OUT.stat().st_size // 1024,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,28 +0,0 @@
#!/usr/bin/env python3
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
LOCAL = Path(__file__).resolve().parents[1] / "backend/app/services/tt_platform_config.py"
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()
sftp.put(str(LOCAL), "/tmp/tt_platform_config.py")
sftp.close()
cmd = """
sudo cp /tmp/tt_platform_config.py /opt/nomadmini/backend/app/services/tt_platform_config.py
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w 'api_health %{http_code}\\n' https://api.nomadro.cn/health
curl -sk -o /dev/null -w 'dy_meta %{http_code}\\n' https://admin.nomadro.cn/api/admin/douyin/meta
journalctl -u nomadmini-api -n 12 --no-pager
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(stdout.read().decode("utf-8", "replace"))
c.close()

View File

@ -1,75 +0,0 @@
#!/usr/bin/env python3
"""Hotfix tt_platform_config.py and verify /api/admin/douyin/config."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
LOCAL = Path(__file__).resolve().parents[1] / "backend" / "app" / "services" / "tt_platform_config.py"
REMOTE = "/opt/nomadmini/backend/app/services/tt_platform_config.py"
def main() -> int:
text = LOCAL.read_text(encoding="utf-8")
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/tt_platform_config.py", "w") as f:
f.write(text)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/tt_platform_config.py /opt/nomadmini/backend/app/services/tt_platform_config.py
sudo chown ubuntu:ubuntu /opt/nomadmini/backend/app/services/tt_platform_config.py
# also copy seed book if missing
if [ ! -f /opt/nomadmini/backend/data/tt-default-book.json ] && [ -f /var/www/nomadro.cn/lib/tt-default-book.json ]; then
sudo mkdir -p /opt/nomadmini/backend/data
sudo cp /var/www/nomadro.cn/lib/tt-default-book.json /opt/nomadmini/backend/data/
fi
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
cd /opt/nomadmini/backend && .venv/bin/python - <<'PY'
from app.services.tt_platform_config import read_tt_platform, resolve_config_file
print('file', resolve_config_file())
cfg = read_tt_platform()
print('modules', {k: v.get('enabled') for k,v in (cfg.get('modules') or {}).items()})
print('chapters', len((cfg.get('bookContent') or {}).get('chapters') or []))
PY
# login then hit config
TOKEN=$(curl -sk -X POST https://admin.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") or json.load(open("/dev/stdin")).get("access_token",""))' 2>/dev/null || true)
# try common login shapes
if [ -z "$TOKEN" ]; then
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}')
echo "login_body=$BODY"
TOKEN=$(echo "$BODY" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
fi
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); print("config_ok", d.get("ok"), "mods", list((d.get("config") or {}).get("modules") or {}).keys())'
else
curl -sk -o /dev/null -w "config_noauth %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/config
fi
"""
_, 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())

View File

@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""Probe live douyin admin / API layout on production."""
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo "=== systemd ==="
systemctl show nomadmini-api -p WorkingDirectory -p FragmentPath --no-pager 2>/dev/null || true
echo "=== files ==="
ls -la /opt/nomadmini/backend/app/routers/douyin_admin.py /opt/nomadmini/backend/app/services/tt_platform_config.py 2>&1 || true
ls -la /opt/nomadmini/backend/app/main.py 2>&1 || true
echo "=== imports ==="
head -20 /opt/nomadmini/backend/app/routers/douyin_admin.py 2>/dev/null || true
echo "=== homeVariant in py ==="
grep -n homeVariant /opt/nomadmini/backend/app/services/tt_platform_config.py 2>/dev/null || echo no_homeVariant
echo "=== remote-config tt ==="
python3 - <<'PY'
import json
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
d = json.loads(p.read_text(encoding="utf-8"))
tt = (d.get("platforms") or {}).get("tt") or {}
print("homeVariant", tt.get("homeVariant"))
mods = tt.get("modules") or {}
print("mods", {k: (v or {}).get("enabled") for k, v in mods.items()})
print("chapters", len(((tt.get("bookContent") or {}).get("chapters") or [])))
PY
"""
def main() -> int:
import sys
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
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)
_, stdout, _ = c.exec_command(CMD, timeout=60, get_pty=True)
print(stdout.read().decode("utf-8", "replace"))
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,38 +0,0 @@
#!/usr/bin/env python3
import json
import urllib.request
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main():
# get password from server env
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)
_, o, _ = c.exec_command(
r"""
cd /opt/nomadmini/backend
USER=$(grep -E '^ADMIN_USERNAME=' .env 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")
PASS=$(grep -E '^ADMIN_PASSWORD=' .env 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")
[ -z "$USER" ] && USER=admin
echo "user=$USER"
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d "{\"username\":\"$USER\",\"password\":\"$PASS\"}")
echo "login=$BODY"
TOKEN=$(echo "$BODY" | .venv/bin/python -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
echo "tok=${#TOKEN}"
CFG=$(curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config)
echo "$CFG" | .venv/bin/python -c 'import sys,json; d=json.load(sys.stdin); print(json.dumps({k:d.get(k) if k!="config" else {"modules": (d.get("config") or {}).get("modules"), "ch": len(((d.get("config") or {}).get("bookContent") or {}).get("chapters") or [])} for k in d}, ensure_ascii=False, indent=2)[:2000])'
META=$(curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/meta)
echo "meta=$META"
""",
timeout=60,
get_pty=True,
)
print(o.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""Smoke-check Douyin admin + API on production."""
from __future__ import annotations
import json
import urllib.request
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def http(url: str) -> tuple[int, str]:
req = urllib.request.Request(url, method="GET")
try:
with urllib.request.urlopen(req, timeout=20) as r:
return r.status, r.read().decode("utf-8", "replace")[:800]
except urllib.error.HTTPError as e:
return e.code, e.read().decode("utf-8", "replace")[:800]
def main() -> int:
for url in (
"https://api.nomadro.cn/health",
"https://admin.nomadro.cn/",
"https://admin.nomadro.cn/douyin",
"https://admin.nomadro.cn/api/admin/douyin/meta",
):
code, body = http(url)
print(f"{code} {url}")
if "health" in url or "meta" in url:
print(" ", body[:200].replace("\n", " "))
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)
_, o, _ = c.exec_command(
"grep -o 'douyin' /www/wwwroot/admin.nomadro.cn/assets/*.js | wc -l; "
"grep -o 'PlatformSelect\\|入口开关\\|小册 Markdown' /www/wwwroot/admin.nomadro.cn/assets/*.js | head -5; "
"python3 -c \"import ast; ast.parse(open('/opt/nomadmini/backend/app/services/tt_platform_config.py').read()); print('tt_platform_config AST ok')\"; "
"systemctl is-active nomadmini-api",
timeout=60,
)
print(o.read().decode("utf-8", "replace"))
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,53 +0,0 @@
#!/usr/bin/env python3
"""Verify realtime homeVariant PUT + config_change track."""
from __future__ import annotations
import json
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
BASE = "https://admin.nomadro.cn"
def req(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(r, timeout=25) as resp:
return json.loads(resp.read().decode())
def main() -> int:
login = req("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
if not token:
print("login fail", login)
return 1
before = req("GET", "/api/admin/douyin/config", token=token)
hv = (before.get("config") or {}).get("homeVariant") or "bmi"
print("before", hv)
target = "bmi" if hv == "hub" else "hub"
put = req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": target})
after = (put.get("config") or {}).get("homeVariant")
print("after", after, "ok", put.get("ok"))
# restore
req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": hv})
print("restored", hv)
events = req("GET", "/api/admin/track-events?limit=5&name=config_change", token=token)
rows = events.get("events") or events.get("items") or events
if isinstance(rows, dict):
rows = rows.get("events") or []
print("recent config_change count sample", len(rows) if isinstance(rows, list) else type(rows))
if isinstance(rows, list) and rows:
e0 = rows[0]
print("latest", e0.get("name"), e0.get("label"), e0.get("client"))
return 0 if after == target else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,7 +0,0 @@
Reload service nginx... done
---
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=d

View File

@ -1,65 +0,0 @@
# Nginx for admin.nomadro.cn -> Nomadmini Admin SPA + API proxy
server
{
listen 80;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
location ~ ^/\.well-known/ {
allow all;
}
location / {
return 301 https://$host$request_uri;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}
server
{
listen 443 ssl http2;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
index index.html;
client_max_body_size 20m;
ssl_certificate /etc/letsencrypt/live/admin.nomadro.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/admin.nomadro.cn/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location ~ ^/\.well-known/ {
allow all;
}
location /api/ {
proxy_pass http://127.0.0.1:8010/api/;
proxy_http_version 1.1;
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;
}
location /health {
proxy_pass http://127.0.0.1:8010/health;
proxy_set_header Host $host;
}
location /assets/ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}

View File

@ -1,54 +0,0 @@
# Nginx for api.nomadro.cn -> Nomadmini FastAPI :8010
server
{
listen 80;
server_name api.nomadro.cn;
root /www/wwwroot/api.nomadro.cn;
location ~ ^/\.well-known/ {
allow all;
}
location / {
return 301 https://$host$request_uri;
}
access_log /www/wwwlogs/api.nomadro.cn.log;
error_log /www/wwwlogs/api.nomadro.cn.error.log;
}
server
{
listen 443 ssl http2;
server_name api.nomadro.cn;
client_max_body_size 32m;
ssl_certificate /etc/letsencrypt/live/api.nomadro.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.nomadro.cn/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location ~ ^/\.well-known/ {
root /www/wwwroot/api.nomadro.cn;
allow all;
}
location / {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
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_cache off;
proxy_no_cache 1;
proxy_cache_bypass 1;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
access_log /www/wwwlogs/api.nomadro.cn.log;
error_log /www/wwwlogs/api.nomadro.cn.error.log;
}

View File

@ -1,26 +0,0 @@
import paramiko
from pathlib import Path
conf = Path("deploy/admin.nomadro.cn.conf").read_text(encoding="utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
sftp = c.open_sftp()
with sftp.file("/tmp/admin.nomadro.cn.conf", "w") as f:
f.write(conf)
sftp.close()
cmd = """
sudo cp /tmp/admin.nomadro.cn.conf /www/server/panel/vhost/nginx/admin.nomadro.cn.conf
sudo nginx -t && sudo /etc/init.d/nginx reload
curl -sI https://admin.nomadro.cn/ | head -8
echo '---'
curl -s https://admin.nomadro.cn/ | head -c 120
echo
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/admin-ssl-fix.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,241 +0,0 @@
# 写在前面
欢迎阅读《数字游民入门指南》。
这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。
你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。
建议按顺序阅读。每章不长,方便通勤或午休时翻完。
# 什么是数字游民
「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。
它不是逃避现实,也不是只顾旅行不顾责任。更常见的状态是:
- 工作目标清晰,交付结果可衡量
- 沟通及时,团队协作顺畅
- 作息稳定,身心健康有保障
- 遵守公司制度与当地法律法规
对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。
## 它适合谁
更适合这些情况:
- 内容创作、设计、开发、运营、客服、翻译、数据分析等可线上完成的工作
- 公司已支持居家办公或混合办公
- 个人执行力较强,能自我管理进度
不太适合:强依赖现场设备、面对面服务、或必须到岗的岗位——除非岗位本身已经改为线上流程。
## 先建立正确预期
灵活不等于松散。远程工作往往更考验:
1. **结果导向**:用可验收的成果说话
2. **可见度**:主动同步进度,减少信息不对称
3. **边界感**:工作与生活有节奏,避免「一直在线却效率很低」
# 远程办公的基本功
远程办公的核心不是「换一个风景」,而是「换一种可协作的工作方式」。
## 1. 固定工作时段
建议每天有固定的核心工作时间(例如 9:30–12:00、14:00–18:00),并告诉同事:
- 哪些时段适合会议
- 哪些时段专注深度工作
- 紧急事项如何联系
时间透明,协作成本会明显下降。
## 2. 日计划与周复盘
每天开工前列三件「今天必须完成」的事;每周五花十五分钟复盘:
- 本周完成了什么
- 卡在哪里
- 下周优先做什么
简单记录即可,不必写成复杂文档。
## 3. 工具只保留必要的
常见组合已经足够:
- 文档协作:在线文档 / 表格
- 沟通:即时消息 + 邮件
- 会议:视频会议软件
- 任务:看板或待办清单
工具越多越容易分心。优先把「任务状态」和「最终交付物」放在团队约定的地方。
## 4. 会议要短、要有结论
开会前写清楚目的;开会后写三条结论:谁负责、做什么、何时完成。没有结论的会,尽量少开。
# 居家与旅居的工作环境
环境会直接影响专注力。不必追求豪华,但要「够用、安静、可持续」。
## 居家办公清单
- 稳定的桌椅与屏幕高度,减少颈椎负担
- 光线充足,白天尽量靠近自然光
- 耳机(隔音或降噪均可)
- 备用充电器与移动电源
- 水杯与简单加餐,减少频繁打断
如果家里容易被打扰,可以约定「工作时关门」或使用图书馆、咖啡馆的安静时段。
## 短途旅居怎么选地方
如果公司允许短期异地办公,优先考虑:
1. 网络稳定、电源方便
2. 住宿安静,适合睡眠
3. 周边有餐饮与运动条件
4. 往返交通可预期,不耽误会议
先从周末附近城市试住一两晚,再考虑更长的停留。陌生城市的第一周,把作息跑稳比「打卡景点」更重要。
# 时间管理:让灵活真正有效
灵活工作最大的风险是:时间碎、注意力散、任务拖。
## 番茄工作法(简化版)
- 25 分钟专注做一件事
- 休息 5 分钟
- 四个循环后休息 15–20 分钟
深度工作时关闭无关通知。回复消息可以集中到固定时段处理。
## 分清「紧急」和「重要」
每天真正重要的通常只有少数几项。把「看起来很忙」和「真正推进目标」分开:
| 类型 | 例子 | 建议 |
| --- | --- | --- |
| 重要且紧急 | 当天截止的交付 | 立刻做 |
| 重要不紧急 | 学习新技能、健康锻炼 | 排进日程 |
| 紧急不重要 | 部分临时打扰 | 能委托就委托 |
| 都不紧急 | 无目的刷信息 | 自觉限制 |
## 保护深度工作时段
建议每天至少留 90 分钟不被会议打断的时间,用来写方案、写代码、做设计或复盘数据。这段时间尽量提前在日历里标出来。
# 沟通与团队协作
远程场景里,沟通质量几乎等于工作质量。
## 同步信息的三个原则
1. **默认公开**:进度写在团队可见的地方,少用只有你知道的私聊结论
2. **结论先行**:先说结果,再补背景
3. **可执行**:说清楚下一步、负责人和时间
## 异步沟通模板
需要同事处理时,可以这样写:
> 背景:……
> 需要你:……
> 截止:……
> 参考资料:……
对方不用来回追问,效率会高很多。
## 信任来自稳定交付
远程信任不是靠「一直在线」,而是靠:
- 承诺的事按时完成
- 延期提前说明原因与新时间
- 问题主动暴露,而不是临近截止才说
把「靠谱」做成习惯,比任何管理鸡汤都管用。
# 健康、作息与心态
身体垮了,任何生活方式都不可持续。
## 作息建议
- 尽量固定睡眠与起床时间
- 每工作一小时起身活动两分钟
- 中午留一段真正休息,而不是边吃边回消息
- 晚上给眼睛和大脑降温,少熬夜赶工
## 运动不必复杂
散步、拉伸、居家力量训练都可以。关键是「每周能坚持」,而不是一次练到力竭。
## 孤独感怎么处理
长期独处容易闷。可以:
- 定期与同事语音同步
- 参加健康正向的兴趣社群或线下读书会
- 与家人朋友保持固定联系时间
把社交安排进日历,和安排会议一样认真。
# 学习成长与职业规划
数字游民不是终点,而是一种工作形态。真正护城河仍是能力与口碑。
## 持续提升三件事
1. **专业技能**:让你的交付更稳、更快、质量更高
2. **表达能力**:把复杂问题讲清楚
3. **项目管理**:把事情拆小、排期、闭环
每周抽出固定学习时间,哪怕只有三十分钟,也比「有空再说」强。
## 作品集思维
把完成的项目整理成可展示的说明:
- 解决了什么问题
- 你做了哪些关键决策
- 结果如何衡量
这对转岗、晋升或接更匹配的远程岗位都很有帮助。
## 合规与边界
请始终遵守:
- 劳动合同与公司远程办公制度
- 信息安全与保密要求
- 所在地法律法规与税务规定
不传播不当内容,不从事违法违规业务。稳健发展,才能走得长远。
# 七天起步计划
如果你想从零开始尝试更灵活的工作节奏,可以用这一周做轻量实验(在公司制度允许的前提下):
**第 1 天**:整理工位,列出核心工作时段
**第 2 天**:建立待办清单,只保留三个每日目标
**第 3 天**:把常用文档放到团队约定位置
**第 4 天**:练习「结论先行」的消息写法
**第 5 天**:完成一次短复盘,记下卡点
**第 6 天**:安排一次户外散步或轻度运动
**第 7 天**:回顾本周,写下下周只改一件事
目标不是完美,而是建立可重复的节奏。
# 结语
数字游民生活方式的本质,是用更好的方式完成工作、照顾生活,而不是追逐表象上的「自由」。
先把远程协作做好,把身体照顾好,把专业能力垒扎实。地点可以慢慢变化,但秩序、责任与成长不能丢。
祝你工作顺利,生活安定,步履从容。

View File

@ -1,22 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
systemctl is-active nomadmini-api
curl -s http://127.0.0.1:8010/health
echo
curl -s https://api.nomadro.cn/health
echo
curl -sI https://admin.nomadro.cn/ | head -8
echo ---
# ensure admin SPA uses production API
grep -R "api.nomadro.cn\|VITE_API" /www/wwwroot/admin.nomadro.cn/assets/*.js 2>/dev/null | head -c 200 || true
echo
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/continue-verify.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,19 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
ls -la /etc/letsencrypt/live/admin.nomadro.cn/ 2>&1
echo '---'
sudo cat /www/server/panel/vhost/nginx/admin.nomadro.cn.conf
echo '---'
curl -sI https://admin.nomadro.cn/ | head -10
curl -s http://admin.nomadro.cn/ | head -c 80
echo
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/admin-debug.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,23 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
journalctl -u nomadmini-api -n 50 --no-pager
echo '---'
ls -la /opt/nomadmini/backend/app
echo '---'
cd /opt/nomadmini/backend && ./.venv/bin/python -c 'import app.main' 2>&1
echo '---'
ss -ltnp | grep 8000 || true
echo '---'
ls -la /etc/nginx/sites-enabled/
echo '---'
cat /etc/nginx/sites-enabled/nomadmini | head -20
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check2.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,22 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
echo 'PORT8000'
sudo ss -ltnp | grep ':8000' || true
echo 'PROCESSES'
ps aux | grep -E 'uvicorn|gunicorn|8000' | grep -v grep || true
echo 'NGINX'
ls -la /etc/nginx/sites-enabled/ || true
ls -la /etc/nginx/conf.d/ || true
grep -R "server_name" /etc/nginx/sites-enabled /etc/nginx/conf.d 2>/dev/null | head -30 || true
echo 'SYSTEMD8000'
systemctl list-units --type=service --all | grep -iE 'nomad|api|uvicorn|fastapi|pocket' || true
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check3.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,20 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
echo 'PAYJSAPI'
systemctl cat payjsapi.service 2>/dev/null | head -20
sudo ss -ltnp | grep -E '8010|8011|8020|8030|8040|8050|8060|8070|8080|8090|8100' || true
echo 'NGINX_ALL'
sudo grep -R "server_name" /etc/nginx/ 2>/dev/null | grep -E 'nomadro|admin' || true
echo 'PAYJSAPI_PORT'
sudo ss -ltnp | grep payjs || true
sudo ss -ltnp | grep python | head -20
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check4.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,17 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
sudo grep -R "api.nomadro.cn\|admin.nomadro.cn" /etc/nginx/ 2>/dev/null
echo '---'
sudo ss -ltnp | grep 8007
echo '---'
cat /var/www/api.nomadro.cn/run.py 2>/dev/null | head -20
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check5.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,15 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
sudo find /etc/nginx -type f -name '*.conf' 2>/dev/null
echo '---'
sudo nginx -T 2>/dev/null | grep -E 'server_name|proxy_pass|root ' | head -80
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check6.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,18 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
sudo grep -R "api.nomadro.cn" /www/server/panel/vhost/nginx/ /etc/nginx/ 2>/dev/null | head -20
echo '---'
sudo grep -R "admin.nomadro.cn" /www/server/panel/vhost/nginx/ /etc/nginx/ 2>/dev/null | head -20
echo '---'
sudo ls -la /www/server/panel/vhost/nginx/ 2>/dev/null | grep nomad || true
sudo ls -la /www/wwwroot/ 2>/dev/null | grep -E 'admin|api' || true
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check7.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,15 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
sudo cat /www/server/panel/vhost/nginx/api.nomadro.cn.conf
echo '=== ebook ==='
sudo cat /www/server/panel/vhost/nginx/ebook.nomadro.cn.conf
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check8.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,15 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
ls -la /etc/letsencrypt/live/ 2>/dev/null | grep admin || true
dig +short admin.nomadro.cn A 2>/dev/null || nslookup admin.nomadro.cn 2>/dev/null | tail -3
dig +short api.nomadro.cn A 2>/dev/null || true
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-check9.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,175 +0,0 @@
#!/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=wxa55815dd741a540d
WX_SECRET=bf71025c209e7567d49268bc427ba22b
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=admin
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()

View File

@ -1,146 +0,0 @@
#!/usr/bin/env python3
"""Deploy Douyin custom admin panel to admin.nomadro.cn + restart API."""
from __future__ import annotations
import io
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[2] # nomadro
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE_SH = r"""
set -e
cd /tmp
rm -rf dy-unpack && mkdir dy-unpack
tar -xzf dy-admin-release.tar.gz -C dy-unpack
sudo rsync -a --delete dy-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then
for d in /opt/nomadmini /www/wwwroot/nomadmini /opt/wemini /var/www/nomadmini /home/ubuntu/nomadmini; do
if [ -f "$d/backend/app/main.py" ] || [ -f "$d/app/main.py" ]; then API_ROOT=$d; break; fi
done
fi
echo API_ROOT=$API_ROOT
if [ -n "$API_ROOT" ]; then
if [ -d "$API_ROOT/backend/app" ]; then
B=$API_ROOT/backend/app
else
B=$API_ROOT/app
fi
sudo mkdir -p "$B/routers" "$B/services" "$API_ROOT/data" "$API_ROOT/backend/data" 2>/dev/null || true
sudo cp dy-unpack/backend/app/routers/douyin_admin.py "$B/routers/"
sudo cp dy-unpack/backend/app/services/tt_platform_config.py "$B/services/"
sudo cp dy-unpack/backend/app/main.py "$B/main.py"
sudo cp dy-unpack/backend/app/config.py "$B/config.py"
if [ -f dy-unpack/data/tt-default-book.json ]; then
sudo cp dy-unpack/data/tt-default-book.json "$API_ROOT/data/" 2>/dev/null || true
sudo cp dy-unpack/data/tt-default-book.json "$API_ROOT/backend/data/" 2>/dev/null || true
fi
fi
if [ -d /var/www/nomadro.cn/lib ] && [ -f dy-unpack/portal-lib/tt-default-book.json ]; then
sudo cp dy-unpack/portal-lib/tt-default-book.json /var/www/nomadro.cn/lib/tt-default-book.json
fi
if [ -f /var/www/nomadro.cn/data/remote-config.json ]; then
sudo python3 <<'PY'
import json
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 = plats.get("tt") or {}
need = not tt.get("modules")
if need:
seed = {}
sp = Path("/var/www/nomadro.cn/lib/tt-default-book.json")
if sp.exists():
seed = json.loads(sp.read_text(encoding="utf-8"))
plats["tt"] = {
"modules": {
"nav": {"enabled": False, "title": "出海导航", "tabLabel": "导航", "note": "抖音默认隐藏"},
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册", "note": "默认开"},
"community": {"enabled": False, "title": "旅居社群", "tabLabel": "社群", "note": "抖音默认隐藏"},
},
"bookContent": seed or {"title": "数字游民", "chapters": []},
}
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
print("seeded platforms.tt")
else:
print("platforms.tt already present")
print("top modules.nav", (cfg.get("modules") or {}).get("nav", {}).get("enabled"))
PY
fi
sudo systemctl restart nomadmini-api || true
sleep 3
systemctl is-active nomadmini-api || true
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
code=$(curl -sk -o /dev/null -w "%{http_code}" https://admin.nomadro.cn/api/admin/douyin/meta || echo ERR)
echo "douyin_meta_http=$code"
rm -rf dy-unpack dy-admin-release.tar.gz
"""
def main() -> int:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
dist = ROOT / "dist"
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for rel in (
"backend/app/routers/douyin_admin.py",
"backend/app/services/tt_platform_config.py",
"backend/app/main.py",
"backend/app/config.py",
"data/tt-default-book.json",
):
p = ROOT / rel
if p.exists():
tar.add(p, arcname=rel)
seed = REPO / "src" / "lib" / "tt-default-book.json"
if seed.exists():
tar.add(seed, arcname="portal-lib/tt-default-book.json")
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-admin-release.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, 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())

View File

@ -1,194 +0,0 @@
#!/usr/bin/env python3
"""Deploy join-group admin UI + API to 82.157.112.245 (admin.nomadro.cn / nomadmini-api)."""
from __future__ import annotations
import io
import re
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1] # apps/admin
REPO = ROOT.parents[1] # nomadro
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 jg-unpack && mkdir jg-unpack
tar -xzf jg-release.tar.gz -C jg-unpack
# --- admin SPA ---
if [ -d jg-unpack/admin-dist ]; then
sudo rsync -a --delete jg-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
# --- API 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 jg-unpack/backend/routers/join_group_admin.py "$B/routers/"
sudo cp jg-unpack/backend/services/join_group_config.py "$B/services/"
# patch main.py to include join_group_admin (idempotent)
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
if "join_group_admin" not in t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
)
if t2 == t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track\n",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track\n",
)
t = t2
if "join_group_admin" not in t:
raise SystemExit("failed to patch import in main.py")
changed = True
if "include_router(join_group_admin.router)" not in t:
needle = "app.include_router(douyin_admin.router)"
if needle not in t:
raise SystemExit("douyin_admin include missing")
t = t.replace(
needle,
needle + "\napp.include_router(join_group_admin.router)",
1,
)
changed = True
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
# additive flags on portal remote-config (never wipe platforms/modules)
CFG=/var/www/nomadro.cn/data/remote-config.json
if [ -f "$CFG" ]; then
sudo python3 <<'PY'
import json
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
cfg = json.loads(p.read_text(encoding="utf-8"))
flags = cfg.setdefault("flags", {})
copy = cfg.setdefault("copy", {})
changed = False
defaults = {
"joinGroupWechat": True,
"joinGroupDouyin": False,
"socialFollowAuto": False,
}
for k, v in defaults.items():
if k not in flags:
flags[k] = v
changed = True
copy_defs = {
"wechatOaName": "异度世界",
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
"joinGroupDouyinQr": "",
}
for k, v in copy_defs.items():
if k not in copy:
copy[k] = v
changed = True
if changed:
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("remote-config flags seeded (additive)")
else:
print("remote-config flags already present")
print("flags=", {k: flags.get(k) for k in list(defaults)})
PY
fi
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/
# login + join-group get
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/join-group | python3 -c "import sys,json; d=json.load(sys.stdin); print('join-group', d.get('ok'), d.get('flags'))"
fi
curl -sk https://nomadro.cn/api/config | python3 -c "import sys,json; f=json.load(sys.stdin).get('config',{}).get('flags',{}); print('portal flags', {k:f.get(k) for k in ('joinGroupWechat','joinGroupDouyin','socialFollowAuto')})"
rm -rf jg-unpack jg-release.tar.gz
echo DONE
"""
def main() -> int:
dist = ROOT / "dist"
if not (dist / "index.html").exists():
print("missing apps/admin/dist — run pnpm build first")
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())
router_src = (EBOOK / "routers" / "join_group_admin.py").read_text(encoding="utf-8")
svc_src = (EBOOK / "services" / "join_group_config.py").read_text(encoding="utf-8")
for name, text in (
("backend/routers/join_group_admin.py", to_app_pkg(router_src)),
("backend/services/join_group_config.py", to_app_pkg(svc_src)),
):
data = text.encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
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/jg-release.tar.gz", "wb") as rf:
rf.write(payload)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, 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()
print(f"[exit {code}]", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,205 +0,0 @@
#!/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())

View File

@ -1,221 +0,0 @@
#!/usr/bin/env python3
"""Deploy nav CRUD admin + API (navContent in remote-config)."""
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"
SEED = REPO / "src" / "lib" / "nav-default-links.json"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE = r'''#!/bin/bash
set -euo pipefail
cd /tmp
rm -rf nav-unpack && mkdir nav-unpack
tar -xzf nav-release.tar.gz -C nav-unpack
if [ -d nav-unpack/admin-dist ]; then
sudo rsync -a --delete nav-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" "$API_ROOT/data"
sudo cp nav-unpack/backend/routers/nav_admin.py "$B/routers/"
sudo cp nav-unpack/backend/services/nav_config.py "$B/services/"
if [ -f nav-unpack/nav-default-links.json ]; then
sudo cp nav-unpack/nav-default-links.json "$API_ROOT/data/"
sudo cp nav-unpack/nav-default-links.json /var/www/nomadro.cn/data/nav-default-links.json 2>/dev/null || true
fi
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(",")]
if "nav_admin" not in parts:
names = names.rstrip() + ", nav_admin"
changed = True
print("import + nav_admin")
newt = f"from app.routers import {names}"
if newt != line:
t = t.replace(line, newt, 1)
changed = True
if "include_router(nav_admin.router)" not in t:
for a in (
"app.include_router(memo_admin.router)",
"app.include_router(shop_admin.router)",
"app.include_router(vip_admin.router)",
"app.include_router(public_config.router)",
):
if a in t:
t = t.replace(a, a + "\napp.include_router(nav_admin.router)", 1)
changed = True
print("nav_admin after", a)
break
if "include_router(nav_admin.router)" not in t:
raise SystemExit("failed nav_admin include")
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
# seed navContent into remote-config if missing
sudo python3 <<'PY'
import json
from pathlib import Path
from datetime import datetime, timezone
cands = [
Path("/var/www/nomadro.cn/data/remote-config.json"),
Path("/opt/nomadmini/backend/data/remote-config.json"),
]
seed_paths = [
Path("/opt/nomadmini/backend/data/nav-default-links.json"),
Path("/var/www/nomadro.cn/data/nav-default-links.json"),
]
seed = None
for sp in seed_paths:
if sp.is_file():
seed = json.loads(sp.read_text(encoding="utf-8"))
break
if not seed:
print("no seed, skip navContent inject")
else:
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
for cfg in cands:
if not cfg.is_file():
continue
raw = json.loads(cfg.read_text(encoding="utf-8"))
nav = raw.get("navContent")
if isinstance(nav, dict) and isinstance(nav.get("categories"), list) and nav["categories"]:
print(cfg, "navContent already set", len(nav["categories"]))
continue
seed["updatedAt"] = now
raw["navContent"] = seed
raw["updatedAt"] = now
raw["version"] = int(raw.get("version") or 0) + 1
tmp = cfg.with_suffix(".json.tmp")
tmp.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
tmp.replace(cfg)
print("seeded navContent into", cfg)
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
echo "--- smoke ---"
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/nav | python3 -c "import sys,json; d=json.load(sys.stdin); n=d.get('nav') or {}; print('nav_ok', d.get('ok'), 'cats', len(n.get('categories') or []), d.get('stats'))"
fi
curl -sk https://api.nomadro.cn/api/config | python3 -c "import sys,json; d=json.load(sys.stdin); c=d.get('config') or {}; nc=c.get('navContent') or {}; print('public_nav', len(nc.get('categories') or []))"
rm -rf nav-unpack nav-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 "")[-500:], flush=True)
if r.returncode != 0:
print(r.stderr or "", flush=True)
return r.returncode or 1
dist = ROOT / "dist"
files = (
("backend/routers/nav_admin.py", EBOOK / "routers" / "nav_admin.py"),
("backend/services/nav_config.py", EBOOK / "services" / "nav_config.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))
if SEED.is_file():
data = SEED.read_bytes()
info = tarfile.TarInfo(name="nav-default-links.json")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
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/nav-release.tar.gz", "wb") as rf:
rf.write(payload)
with sftp.file("/tmp/nav-deploy.sh", "w") as sf:
sf.write(REMOTE.replace("\r\n", "\n"))
sftp.chmod("/tmp/nav-deploy.sh", 0o755)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command("bash /tmp/nav-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())

View File

@ -1,80 +0,0 @@
"""部署 ntfy 推送集成到腾讯云 API。"""
from __future__ import annotations
import io
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 = "Xiao4669805"
NTFY_TOKEN = "tk_xt9nxxtbwo24w9bm7qpzcqu7urgkw"
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
for rel in [
"app/routers/pay.py",
"app/services/ntfy.py",
"app/config.py",
]:
p = ROOT / "backend" / rel
data = p.read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=rel)
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/ntfy-hook.tar.gz")
cmd = rf"""
set -e
cd /tmp
rm -rf ntfy-hook && mkdir ntfy-hook
tar -xzf ntfy-hook.tar.gz -C ntfy-hook
cp ntfy-hook/app/routers/pay.py /opt/nomadmini/backend/app/routers/pay.py
cp ntfy-hook/app/services/ntfy.py /opt/nomadmini/backend/app/services/ntfy.py
cp ntfy-hook/app/config.py /opt/nomadmini/backend/app/config.py
ENV=/opt/nomadmini/backend/.env
upsert() {{
key="$1"; val="$2"
if grep -q "^${{key}}=" "$ENV"; then
sed -i "s|^${{key}}=.*|${{key}}=${{val}}|" "$ENV"
else
echo "${{key}}=${{val}}" >> "$ENV"
fi
}}
upsert NTFY_ENABLED true
upsert NTFY_BASE_URL http://127.0.0.1:2586
upsert NTFY_TOPIC nomadmini
upsert NTFY_TOKEN {NTFY_TOKEN}
sudo systemctl restart nomadmini-api
sleep 2
curl -s http://127.0.0.1:8010/health
echo
cd /opt/nomadmini/backend
/opt/nomadmini/backend/.venv/bin/python - <<'PY'
import asyncio
from app.services.ntfy import notify
ok = asyncio.run(notify('联调:支付/消息将推送到本 topic', title='Nomadmini 已接通', tags='rocket', priority=4))
print('ntfy_ok', ok)
PY
rm -rf /tmp/ntfy-hook /tmp/ntfy-hook.tar.gz
"""
_, o, e = c.exec_command(cmd)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
Path("deploy/ntfy-hook-deploy.txt").write_text(out + "\nERR\n" + err, encoding="utf-8")
c.close()
tar_path.unlink(missing_ok=True)
print(out.encode("ascii", "replace").decode())
print(err.encode("ascii", "replace").decode())

View File

@ -1,135 +0,0 @@
#!/usr/bin/env python3
"""Deploy public /api/config on dyapi/api (valid TLS) for Douyin 真机."""
from __future__ import annotations
import io
import tarfile
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
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 pc-unpack && mkdir pc-unpack
tar -xzf pc-release.tar.gz -C pc-unpack
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"
sudo cp pc-unpack/backend/routers/public_config.py "$B/routers/"
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
if "public_config" not in t:
for old in (
"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\n",
"from app.routers import admin, auth, books, douyin_admin, pay, track",
):
if old.strip() in t.replace("\r",""):
pass
if "join_group_admin" in t and "public_config" not in t:
t2 = t.replace(
"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, public_config, track",
)
if t2 == t:
t2 = t.replace(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, pay, public_config, track",
)
t = t2
changed = True
if "public_config" not in t:
raise SystemExit("failed to patch import")
if "include_router(public_config.router)" not in t:
for needle in (
"app.include_router(join_group_admin.router)",
"app.include_router(douyin_admin.router)",
"app.include_router(admin.router)",
):
if needle in t:
t = t.replace(needle, needle + "\napp.include_router(public_config.router)", 1)
changed = True
break
else:
raise SystemExit("no include needle")
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 3
systemctl is-active nomadmini-api
echo "--- smoke ---"
for u in \
https://dyapi.nomadro.cn/api/config \
https://api.nomadro.cn/api/config \
https://dyapi.nomadro.cn/api/config/meta \
https://api.nomadro.cn/api/config/meta
do
code=$(curl -s -o /tmp/pcbody.json -w '%{http_code}' -m 15 "$u" || echo ERR)
echo "$code $u"
python3 -c "import json; d=json.load(open('/tmp/pcbody.json')); c=d.get('config',d); f=(c.get('flags') or {}) if isinstance(c,dict) else {}; print(' ver', c.get('version') if isinstance(c,dict) else d.get('version'), 'wx', f.get('joinGroupWechat'), 'dy', f.get('joinGroupDouyin'))" 2>/dev/null || head -c 120 /tmp/pcbody.json; echo
done
rm -rf pc-unpack pc-release.tar.gz
"""
def main() -> None:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
src = (EBOOK / "routers" / "public_config.py").read_text(encoding="utf-8")
data = to_app_pkg(src).encode("utf-8")
info = tarfile.TarInfo(name="backend/routers/public_config.py")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30)
sftp = c.open_sftp()
with sftp.file("/tmp/pc-release.tar.gz", "wb") as f:
f.write(payload)
with sftp.file("/tmp/pc-deploy.sh", "w") as f:
f.write(REMOTE_SH)
sftp.close()
print("uploaded, running remote…")
_, stdout, stderr = c.exec_command("bash /tmp/pc-deploy.sh", timeout=120)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
print(out)
if err.strip():
print("STDERR:", err)
c.close()
print("done", time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()

View File

@ -1,227 +0,0 @@
#!/usr/bin/env python3
"""Deploy WeChat shop (电商) admin UI + API to 82.157.112.245.
- Admin SPA → /www/wwwroot/admin.nomadro.cn
- shop / shop_admin / shop_store + pay.py / store.py (shop fulfill)
- Patch main.py include_router (idempotent)
- Restart nomadmini-api
"""
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.")
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",
)
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
files = (
("backend/routers/shop.py", EBOOK / "routers" / "shop.py"),
("backend/routers/shop_admin.py", EBOOK / "routers" / "shop_admin.py"),
("backend/services/shop_store.py", EBOOK / "services" / "shop_store.py"),
("backend/routers/pay.py", EBOOK / "routers" / "pay.py"),
("backend/services/store.py", EBOOK / "services" / "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/shop-release.tar.gz", "wb") as rf:
rf.write(payload)
with sftp.file("/tmp/shop-deploy.sh", "w") as sf:
sf.write(remote.replace("\r\n", "\n"))
sftp.chmod("/tmp/shop-deploy.sh", 0o755)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command("bash /tmp/shop-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
def _remote_script() -> str:
return r'''#!/bin/bash
set -euo pipefail
cd /tmp
rm -rf shop-unpack && mkdir shop-unpack
tar -xzf shop-release.tar.gz -C shop-unpack
if [ -d shop-unpack/admin-dist ]; then
sudo rsync -a --delete shop-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 shop-unpack/backend/routers/shop.py "$B/routers/"
sudo cp shop-unpack/backend/routers/shop_admin.py "$B/routers/"
sudo cp shop-unpack/backend/services/shop_store.py "$B/services/"
sudo cp shop-unpack/backend/routers/pay.py "$B/routers/"
sudo cp shop-unpack/backend/services/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)
for mod in ("shop", "shop_admin", "vip_admin", "join_group_admin", "public_config"):
# crude: check token
parts = [x.strip() for x in names.split(",")]
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
# shop under api prefix loop
if "include_router(shop.router" not in t:
if 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(shop.router, prefix=_api_prefix)",
t,
count=1,
)
changed = True
print("shop in _api_prefix loop")
elif re.search(r"app\.include_router\(track\.router,\s*prefix=_prefix\)", t):
t = re.sub(
r"(app\.include_router\(track\.router,\s*prefix=_prefix\))",
r"\1\n app.include_router(shop.router, prefix=_prefix)",
t,
count=1,
)
changed = True
print("shop in _prefix loop")
else:
for a in ("app.include_router(track.router)", "app.include_router(pay.router)"):
if a in t and "include_router(shop.router)" not in t:
t = t.replace(a, a + "\napp.include_router(shop.router)", 1)
changed = True
print("shop include fallback")
break
if "include_router(shop_admin.router)" not in t:
for a in (
"app.include_router(vip_admin.router)",
"app.include_router(join_group_admin.router)",
"app.include_router(douyin_admin.router)",
"app.include_router(admin.router)",
):
if a in t:
t = t.replace(a, a + "\napp.include_router(shop_admin.router)", 1)
changed = True
print("shop_admin include after", a)
break
if "include_router(shop_admin.router)" not in t:
raise SystemExit("failed shop_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 "shop_page %{http_code}\n" https://admin.nomadro.cn/wechat/shop
curl -sk http://127.0.0.1:8010/health; echo
curl -sk http://127.0.0.1:8010/api/shop/catalog | python3 -c "import sys,json; d=json.load(sys.stdin); print('catalog', d.get('ok'), len(d.get('products') or []))" || echo catalog_fail
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/shop/products | python3 -c "import sys,json; d=json.load(sys.stdin); ps=d.get('items') or []; print('admin_products', len(ps)); print([(p.get('id'), p.get('wxProductId'), p.get('priceFen')) for p in ps[:4]])"
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 'shop' in k]; print('shop_paths', len(ks), ks[:12])"
rm -rf shop-unpack shop-release.tar.gz
echo DONE
'''
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,67 +0,0 @@
import paramiko
from scp import SCPClient
from pathlib import Path
import io
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = "Xiao4669805"
FILES = [
"app/main.py",
"app/routers/track.py",
"app/routers/pay.py",
"app/routers/admin.py",
"app/routers/auth.py",
"app/schemas/track.py",
"app/services/track.py",
"app/services/store.py",
]
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
for rel in FILES:
p = ROOT / "backend" / rel
assert p.exists(), rel
data = p.read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=rel)
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
print("connected")
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/track-update.tar.gz")
print("uploaded", tar_path.stat().st_size)
cmd = """
set -e
cd /tmp
rm -rf track-update && mkdir track-update
tar -xzf track-update.tar.gz -C track-update
ls track-update/app/routers/
cp track-update/app/main.py /opt/nomadmini/backend/app/main.py
cp track-update/app/routers/track.py /opt/nomadmini/backend/app/routers/track.py
cp track-update/app/routers/pay.py /opt/nomadmini/backend/app/routers/pay.py
cp track-update/app/routers/admin.py /opt/nomadmini/backend/app/routers/admin.py
cp track-update/app/routers/auth.py /opt/nomadmini/backend/app/routers/auth.py
mkdir -p /opt/nomadmini/backend/app/schemas
cp track-update/app/schemas/track.py /opt/nomadmini/backend/app/schemas/track.py
cp track-update/app/services/track.py /opt/nomadmini/backend/app/services/track.py
cp track-update/app/services/store.py /opt/nomadmini/backend/app/services/store.py
sudo systemctl restart nomadmini-api
sleep 2
curl -s http://127.0.0.1:8010/health; echo
curl -s -X POST http://127.0.0.1:8010/api/track -H 'Content-Type: application/json' -d '{"events":[{"name":"page_view","page":"pages/home/index","label":"deploy-test"}],"client":"deploy"}'; echo
"""
_, o, e = c.exec_command(cmd)
print(o.read().decode("utf-8", "replace"))
print("STDERR:", e.read().decode("utf-8", "replace")[:2000])
c.close()
tar_path.unlink(missing_ok=True)

View File

@ -1,94 +0,0 @@
#!/usr/bin/env python3
"""Deploy track analytics + ntfy channel labels to nomadmini-api."""
from __future__ import annotations
import io
import tarfile
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
FILES = [
"routers/admin.py",
"services/track.py",
"services/store.py",
]
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf ta-unpack && mkdir ta-unpack
tar -xzf ta-release.tar.gz -C ta-unpack
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 ta-unpack/backend/routers/admin.py "$B/routers/"
sudo cp ta-unpack/backend/services/track.py "$B/services/"
sudo cp ta-unpack/backend/services/store.py "$B/services/"
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo "--- smoke ---"
curl -s -X POST http://127.0.0.1:8010/api/track \
-H 'Content-Type: application/json' \
-d '{"events":[{"name":"page_view","page":"pages/index/index","label":"deploy-test","props":{"channel":"tt"}}],"client":"tt"}'
echo
curl -s -X POST http://127.0.0.1:8010/api/track \
-H 'Content-Type: application/json' \
-d '{"events":[{"name":"join_group_show","label":"公众号","props":{"popup":"wechat","channel":"weapp"}}],"client":"weapp"}'
echo
rm -rf ta-unpack ta-release.tar.gz
"""
def main() -> None:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel in FILES:
src = (EBOOK / rel).read_text(encoding="utf-8")
data = to_app_pkg(src).encode("utf-8")
info = tarfile.TarInfo(name=f"backend/{rel}")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30)
sftp = c.open_sftp()
with sftp.file("/tmp/ta-release.tar.gz", "wb") as f:
f.write(payload)
with sftp.file("/tmp/ta-deploy.sh", "w") as f:
f.write(REMOTE_SH)
sftp.close()
print("uploaded, running remote…")
_, stdout, stderr = c.exec_command("bash /tmp/ta-deploy.sh", timeout=120)
print(stdout.read().decode("utf-8", errors="replace"))
err = stderr.read().decode("utf-8", errors="replace")
if err.strip():
print("STDERR:", err)
c.close()
print("done", time.strftime("%H:%M:%S"))
if __name__ == "__main__":
main()

View File

@ -1,259 +0,0 @@
#!/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())

View File

@ -1,226 +0,0 @@
#!/usr/bin/env python3
"""Deploy VIP formal content library (ebooks/courses) + Admin VIP Library UI.
Additive: does not wipe remote-config / orders / platforms.tt.
Seeds vip-library.json only when missing (from package seed).
"""
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"
SEED = EBOOK / "data" / "vip_library_seed.json"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> int:
# refresh seed from H5 SoT
print("exporting vip_library_seed.json…", flush=True)
er = subprocess.run(
[
"node",
"--experimental-strip-types",
"--experimental-transform-types",
str(ROOT / "deploy" / "_export_vip_library_seed.mts"),
],
cwd=REPO,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
print((er.stdout or "")[-400:], flush=True)
if er.returncode != 0:
print(er.stderr[-800:], flush=True)
return er.returncode or 1
if not SEED.is_file():
print("missing seed", SEED)
return 1
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",
)
log = ((r.stdout or "") + (r.stderr or ""))[-800:]
print(log.encode("ascii", "replace").decode("ascii"), flush=True)
if r.returncode != 0:
return r.returncode or 1
dist = ROOT / "dist"
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())
files = (
("backend/routers/vip_admin.py", EBOOK / "routers" / "vip_admin.py"),
("backend/routers/vip_library_admin.py", EBOOK / "routers" / "vip_library_admin.py"),
("backend/routers/vip_library_public.py", EBOOK / "routers" / "vip_library_public.py"),
("backend/services/vip_config.py", EBOOK / "services" / "vip_config.py"),
("backend/services/vip_content.py", EBOOK / "services" / "vip_content.py"),
("backend/services/vip_library.py", EBOOK / "services" / "vip_library.py"),
("backend/data/vip_library_seed.json", SEED),
)
for name, src in files:
data = src.read_bytes()
if name.endswith(".py"):
data = to_app_pkg(data.decode("utf-8")).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
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-library-release.tar.gz", "wb") as rf:
rf.write(payload)
with sftp.file("/tmp/vip-library-deploy.sh", "w") as sf:
sf.write(_REMOTE_CLEAN)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command("bash /tmp/vip-library-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
_REMOTE_CLEAN = r"""#!/bin/bash
set -euo pipefail
cd /tmp
rm -rf vip-lib-unpack && mkdir vip-lib-unpack
tar -xzf vip-library-release.tar.gz -C vip-lib-unpack
if [ -d vip-lib-unpack/admin-dist ]; then
sudo rsync -a --delete vip-lib-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
B=$API_ROOT/app
[ -d "$B" ] || B=$API_ROOT/backend/app
echo API_ROOT=$API_ROOT B=$B
sudo mkdir -p "$B/routers" "$B/services" "$B/data"
sudo cp vip-lib-unpack/backend/routers/vip_admin.py "$B/routers/"
sudo cp vip-lib-unpack/backend/routers/vip_library_admin.py "$B/routers/"
sudo cp vip-lib-unpack/backend/routers/vip_library_public.py "$B/routers/"
sudo cp vip-lib-unpack/backend/services/vip_config.py "$B/services/"
sudo cp vip-lib-unpack/backend/services/vip_content.py "$B/services/"
sudo cp vip-lib-unpack/backend/services/vip_library.py "$B/services/"
sudo cp vip-lib-unpack/backend/data/vip_library_seed.json "$B/data/"
for DIR in /var/www/nomadro.cn/data /www/wwwroot/nomadro.cn/data; do
if [ -d "$DIR" ]; then
if [ ! -f "$DIR/vip-library.json" ]; then
sudo cp vip-lib-unpack/backend/data/vip_library_seed.json "$DIR/vip-library.json"
sudo chown ubuntu:ubuntu "$DIR/vip-library.json" 2>/dev/null || sudo chown www:www "$DIR/vip-library.json" 2>/dev/null || true
echo "seeded $DIR/vip-library.json"
else
echo "keep existing $DIR/vip-library.json"
fi
fi
done
MAIN="$B/main.py"
sudo python3 - <<PY
from pathlib import Path
import ast, re
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
m = re.search(r"from app\.routers import \((.*?)\)\n", t, re.S)
if m:
names = []
for part in m.group(1).replace("\n", ",").split(","):
n = part.strip()
if n and n not in names:
names.append(n)
for req in ("vip_admin", "vip_library_admin", "vip_library_public"):
if req not in names:
names.append(req)
changed = True
block = "from app.routers import (\n" + ",\n".join(f" {n}" for n in names) + "\n)\n"
t = t[: m.start()] + block + t[m.end() :]
elif "vip_library_admin" not in t:
# single-line import → parenthesize and append
m2 = re.search(r"from app\.routers import ([^\n]+)\n", t)
if not m2:
raise SystemExit("cannot find routers import")
names = [x.strip() for x in m2.group(1).split(",") if x.strip()]
for req in ("vip_admin", "vip_library_admin", "vip_library_public"):
if req not in names:
names.append(req)
block = "from app.routers import (\n" + ",\n".join(f" {n}" for n in names) + "\n)\n"
t = t[: m2.start()] + block + t[m2.end() :]
changed = True
if "include_router(vip_library_admin.router)" not in t:
if "include_router(vip_admin.router)" in t:
t = t.replace(
"app.include_router(vip_admin.router)",
"app.include_router(vip_admin.router)\napp.include_router(vip_library_admin.router)\napp.include_router(vip_library_public.router)",
1,
)
changed = True
else:
raise SystemExit("vip_admin router missing")
ast.parse(t)
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched for vip_library")
else:
print("main.py already has vip_library")
PY
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 "vip_library_page %{http_code}\n" https://admin.nomadro.cn/wechat/vip/library
curl -sk -o /dev/null -w "public_course %{http_code}\n" https://api.nomadro.cn/api/vip/course
curl -sk https://api.nomadro.cn/api/vip/library/meta | python3 -c "import sys,json; d=json.load(sys.stdin); print('meta', d.get('ok'), d.get('ebookIds'), d.get('courseLessons'), d.get('hasFile'))" || true
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)
if [ -n "$TOK" ]; then
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip/library/meta | python3 -c "import sys,json; d=json.load(sys.stdin); print('admin_meta', d.get('ok'), d.get('ebookIds'), d.get('courseLessons'))"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip | python3 -c "import sys,json; d=json.load(sys.stdin); print('vip_price', d.get('vipPriceFen'), d.get('is_free'))"
fi
curl -sk https://api.nomadro.cn/api/config | python3 -c "import sys,json; d=json.load(sys.stdin); c=d.get('config') or d; print('tt_ok', 'tt' in (c.get('platforms') or {}))"
rm -rf vip-lib-unpack vip-library-release.tar.gz
echo DONE
"""
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,83 +0,0 @@
import hashlib
import io
import tarfile
import tempfile
import time
from pathlib import Path
import paramiko
from scp import SCPClient
ROOT = Path(__file__).resolve().parents[1]
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = "Xiao4669805"
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
for rel in [
"app/routers/pay.py",
"app/services/wxmsg.py",
"app/config.py",
"requirements.txt",
]:
p = ROOT / "backend" / rel
data = p.read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=rel)
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/wxmsg-update.tar.gz")
# update remote .env keys + code + deps + restart
cmd = r"""
set -e
cd /tmp
rm -rf wxmsg-update && mkdir wxmsg-update
tar -xzf wxmsg-update.tar.gz -C wxmsg-update
cp wxmsg-update/app/routers/pay.py /opt/nomadmini/backend/app/routers/pay.py
cp wxmsg-update/app/services/wxmsg.py /opt/nomadmini/backend/app/services/wxmsg.py
cp wxmsg-update/app/config.py /opt/nomadmini/backend/app/config.py
cp wxmsg-update/requirements.txt /opt/nomadmini/backend/requirements.txt
# upsert env
ENV=/opt/nomadmini/backend/.env
grep -q '^WX_PUSH_TOKEN=' $ENV && sed -i 's/^WX_PUSH_TOKEN=.*/WX_PUSH_TOKEN=hackrobot/' $ENV || echo 'WX_PUSH_TOKEN=hackrobot' >> $ENV
grep -q '^WX_PUSH_ENCODING_AES_KEY=' $ENV && sed -i 's/^WX_PUSH_ENCODING_AES_KEY=.*/WX_PUSH_ENCODING_AES_KEY=ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI/' $ENV || echo 'WX_PUSH_ENCODING_AES_KEY=ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI' >> $ENV
/opt/nomadmini/backend/.venv/bin/pip install -q pycryptodome==3.21.0
sudo systemctl restart nomadmini-api
sleep 2
curl -s http://127.0.0.1:8010/health
echo
# local signature self-test
python3 - <<'PY'
import hashlib, urllib.parse, urllib.request
token='hackrobot'
ts='1710000000'
nonce='nonce123'
echo='hello_echo'
s=''.join(sorted([token,ts,nonce]))
sig=hashlib.sha1(s.encode()).hexdigest()
url=f'https://api.nomadro.cn/api/pay/notify?signature={sig}&timestamp={ts}&nonce={nonce}&echostr={echo}'
print(urllib.request.urlopen(url, timeout=15).read().decode())
# bad sig should 403
try:
bad=f'https://api.nomadro.cn/api/pay/notify?signature=bad&timestamp={ts}&nonce={nonce}&echostr={echo}'
print('bad', urllib.request.urlopen(bad, timeout=15).read().decode())
except Exception as e:
print('bad_ok', type(e).__name__)
PY
rm -rf wxmsg-update wxmsg-update.tar.gz
"""
_, o, e = c.exec_command(cmd)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
Path("deploy/wxmsg-deploy.txt").write_text(out + "\nERR\n" + err, encoding="utf-8")
c.close()
tar_path.unlink(missing_ok=True)
print(out.encode("ascii", "replace").decode())

View File

@ -1,36 +0,0 @@
import paramiko, json
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = r"""
python3 - <<'PY'
import json, urllib.request
print('health', urllib.request.urlopen('https://api.nomadro.cn/health').read().decode())
req = urllib.request.Request(
'https://api.nomadro.cn/api/admin/login',
data=json.dumps({'username':'admin','password':'Xiao4669805'}).encode(),
headers={'Content-Type':'application/json'}
)
tok = json.loads(urllib.request.urlopen(req).read().decode())['token']
req2 = urllib.request.Request(
'https://api.nomadro.cn/api/admin/stats',
headers={'Authorization': f'Bearer {tok}'}
)
print('stats', urllib.request.urlopen(req2).read().decode())
req3 = urllib.request.Request(
'https://api.nomadro.cn/api/admin/checklist',
headers={'Authorization': f'Bearer {tok}'}
)
print('checklist_items', len(json.loads(urllib.request.urlopen(req3).read().decode())['items']))
print('admin_html_ok', 'Nomadro Admin' in urllib.request.urlopen('https://admin.nomadro.cn/').read().decode())
PY
"""
_, o, e = c.exec_command(cmd)
Path("deploy/final-verify.txt").write_text(
o.read().decode("utf-8", "replace") + "\nERR\n" + e.read().decode("utf-8", "replace"),
encoding="utf-8",
)
c.close()
print("ok")

View File

@ -1,51 +0,0 @@
import io
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 = "Xiao4669805"
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
for rel in ["app/services/wxpay.py", "app/config.py"]:
p = ROOT / "backend" / rel
data = p.read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=rel)
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/login-fix.tar.gz")
cmd = r"""
set -e
cd /tmp && rm -rf login-fix && mkdir login-fix && tar -xzf login-fix.tar.gz -C login-fix
cp login-fix/app/services/wxpay.py /opt/nomadmini/backend/app/services/wxpay.py
cp login-fix/app/config.py /opt/nomadmini/backend/app/config.py
ENV=/opt/nomadmini/backend/.env
grep -q '^WX_ALLOW_DEVTOOLS_LOGIN=' $ENV && sed -i 's/^WX_ALLOW_DEVTOOLS_LOGIN=.*/WX_ALLOW_DEVTOOLS_LOGIN=true/' $ENV || echo 'WX_ALLOW_DEVTOOLS_LOGIN=true' >> $ENV
sudo systemctl restart nomadmini-api
sleep 2
# test mock login
curl -s -X POST http://127.0.0.1:8010/api/auth/login -H 'Content-Type: application/json' -d '{"code":"the code is a mock one"}'
echo
curl -s http://127.0.0.1:8010/health
echo
rm -rf login-fix login-fix.tar.gz
"""
_, o, e = c.exec_command(cmd)
print(o.read().decode("utf-8", "replace").encode("ascii", "replace").decode())
print(e.read().decode("utf-8", "replace").encode("ascii", "replace").decode())
c.close()
tar_path.unlink(missing_ok=True)

View File

@ -1,20 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
sudo cat /www/server/panel/vhost/nginx/api.nomadro.cn.conf
echo '=== reload ==='
sudo nginx -t && sudo /etc/init.d/nginx reload
sleep 1
curl -s --resolve api.nomadro.cn:443:127.0.0.1 https://api.nomadro.cn/health -k
echo
curl -s --resolve admin.nomadro.cn:80:127.0.0.1 http://admin.nomadro.cn/ | head -c 150
echo
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-verify4.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,99 +0,0 @@
import io
import json
import tarfile
import tempfile
import urllib.request
from pathlib import Path
import paramiko
from scp import SCPClient
ROOT = Path(__file__).resolve().parents[1]
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = "Xiao4669805"
EBOOK = ROOT / "data" / "ebook.md"
# 1) build already done separately - upload backend + admin dist + ebook
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
files = [
("backend/app/services/markdown_book.py", ROOT / "backend/app/services/markdown_book.py"),
("backend/app/routers/admin.py", ROOT / "backend/app/routers/admin.py"),
("backend/app/routers/books.py", ROOT / "backend/app/routers/books.py"),
("data/ebook.md", EBOOK),
]
for name, p in files:
data = p.read_bytes().replace(b"\r\n", b"\n") if p.suffix != ".md" else p.read_bytes()
if p.suffix != ".md":
data = data.replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, fileobj=io.BytesIO(data))
dist = ROOT / "dist"
if dist.exists():
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname=f"admin/dist/{p.relative_to(dist).as_posix()}")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/ebook-import.tar.gz")
cmd = r"""
set -e
cd /tmp
rm -rf ebook-import && mkdir ebook-import
tar -xzf ebook-import.tar.gz -C ebook-import
cp ebook-import/backend/app/services/markdown_book.py /opt/nomadmini/backend/app/services/markdown_book.py
cp ebook-import/backend/app/routers/admin.py /opt/nomadmini/backend/app/routers/admin.py
cp ebook-import/backend/app/routers/books.py /opt/nomadmini/backend/app/routers/books.py
mkdir -p /opt/nomadmini/data
cp ebook-import/data/ebook.md /opt/nomadmini/data/ebook.md
if [ -d ebook-import/admin/dist ]; then
sudo rsync -a --delete ebook-import/admin/dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
fi
sudo systemctl restart nomadmini-api
sleep 2
curl -s http://127.0.0.1:8010/health
echo
"""
_, o, e = c.exec_command(cmd)
print(o.read().decode("utf-8", "replace").encode("ascii", "replace").decode())
print(e.read().decode("utf-8", "replace").encode("ascii", "replace").decode())
c.close()
tar_path.unlink(missing_ok=True)
# 2) import markdown via API from local file (avoids remote encoding issues)
md = EBOOK.read_text(encoding="utf-8")
req = urllib.request.Request(
"https://api.nomadro.cn/api/admin/login",
data=json.dumps({"username": "admin", "password": "Xiao4669805"}).encode(),
headers={"Content-Type": "application/json"},
)
token = json.loads(urllib.request.urlopen(req, timeout=30).read().decode())["token"]
payload = {
"markdown": md,
"replace_meta": True,
"title": "数字游民出海笔记",
"subtitle": "低成本工作室 · 云手机 · 自动化杠杆",
"description": "数字游民地理套利与自动化杠杆实战笔记:无人直播、Youtube、独立开发与地理套利。",
}
req2 = urllib.request.Request(
"https://api.nomadro.cn/api/admin/books/default/import-markdown",
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
method="POST",
)
resp = json.loads(urllib.request.urlopen(req2, timeout=120).read().decode())
print("imported chapters=", resp.get("chapter_count"), "words=", resp.get("word_count"))

View File

@ -1,42 +0,0 @@
# Nomadro DNS / 反向代理示例
# api.nomadro.cn -> FastAPI :8000
# admin.nomadro.cn -> Admin 静态资源(Vite build)并反代 /api
server {
listen 80;
server_name api.nomadro.cn;
client_max_body_size 10m;
location / {
proxy_pass http://127.0.0.1:8000;
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;
}
}
server {
listen 80;
server_name admin.nomadro.cn;
root /var/www/nomadmini/admin/dist;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:8000/api/;
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;
}
location /health {
proxy_pass http://127.0.0.1:8000/health;
}
location / {
try_files $uri $uri/ /index.html;
}
}

View File

@ -1,15 +0,0 @@
[Unit]
Description=Nomadmini FastAPI (api.nomadro.cn)
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/opt/nomadmini/backend
EnvironmentFile=/opt/nomadmini/backend/.env
ExecStart=/opt/nomadmini/backend/.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8010
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target

View File

@ -1,61 +0,0 @@
import paramiko
from pathlib import Path
from scp import SCPClient
ROOT = Path(__file__).resolve().parents[1]
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = "Xiao4669805"
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
# upload admin dist as tar
import tarfile, tempfile, io
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
dist = ROOT / "dist"
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname=p.relative_to(dist).as_posix())
conf = (ROOT / "deploy" / "admin.nomadro.cn.conf").read_bytes().replace(b"\r\n", b"\n")
info = tarfile.TarInfo(name="admin.nomadro.cn.conf")
info.size = len(conf)
tar.addfile(info, fileobj=io.BytesIO(conf))
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/admin-release.tar.gz")
cmd = """
set -e
sudo mkdir -p /www/wwwroot/admin.nomadro.cn
cd /tmp
rm -rf admin-unpack && mkdir admin-unpack
tar -xzf admin-release.tar.gz -C admin-unpack
sudo rsync -a --delete --exclude admin.nomadro.cn.conf admin-unpack/ /www/wwwroot/admin.nomadro.cn/
sudo cp admin-unpack/admin.nomadro.cn.conf /www/server/panel/vhost/nginx/admin.nomadro.cn.conf
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
sudo nginx -t
sudo /etc/init.d/nginx reload
echo HEALTH
curl -s https://admin.nomadro.cn/health
echo
echo LOGIN
curl -s -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}'
echo
echo API
curl -s https://api.nomadro.cn/health
echo
rm -rf admin-unpack admin-release.tar.gz
"""
_, o, e = c.exec_command(cmd)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
Path("deploy/admin-redeploy.txt").write_text(out + "\nERR\n" + err, encoding="utf-8")
c.close()
tar_path.unlink(missing_ok=True)
print(out.encode("ascii", "replace").decode())
print("done")

View File

@ -1,99 +0,0 @@
#!/bin/bash
set -euo pipefail
APP_ROOT="/opt/nomadmini"
BACKEND="$APP_ROOT/backend"
ADMIN_WWW="/www/wwwroot/admin.nomadro.cn"
NGINX_VHOST="/www/server/panel/vhost/nginx"
echo "==> Prepare directories"
sudo mkdir -p "$ADMIN_WWW" "$APP_ROOT/data"
sudo rsync -a --delete "$APP_ROOT/admin/dist/" "$ADMIN_WWW/"
sudo chown -R www:www "$ADMIN_WWW"
sudo chown -R ubuntu:ubuntu "$APP_ROOT"
echo "==> Backend venv + deps"
cd "$BACKEND"
python3 -m venv .venv
./.venv/bin/pip install --upgrade pip
./.venv/bin/pip install -r requirements.txt
echo "==> systemd (port 8010)"
sudo cp "$APP_ROOT/deploy/nomadmini-api.service" /etc/systemd/system/nomadmini-api.service
sudo systemctl daemon-reload
sudo systemctl enable nomadmini-api
sudo systemctl restart nomadmini-api
echo "==> nginx vhosts (BaoTa)"
sudo cp "$APP_ROOT/deploy/api.nomadro.cn.conf" "$NGINX_VHOST/api.nomadro.cn.conf"
if [ ! -f "$NGINX_VHOST/admin.nomadro.cn.conf" ]; then
sudo cp "$APP_ROOT/deploy/admin.nomadro.cn.conf" "$NGINX_VHOST/admin.nomadro.cn.conf"
fi
sudo nginx -t
sudo systemctl reload nginx
echo "==> SSL for admin.nomadro.cn (if missing)"
if [ ! -d /etc/letsencrypt/live/admin.nomadro.cn ]; then
sudo certbot certonly --webroot -w "$ADMIN_WWW" -d admin.nomadro.cn \
--non-interactive --agree-tos -m admin@nomadro.cn || true
if [ -d /etc/letsencrypt/live/admin.nomadro.cn ]; then
sudo tee "$NGINX_VHOST/admin.nomadro.cn.conf" >/dev/null <<'EOF'
server
{
listen 80;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
location ~ ^/\.well-known/ {
allow all;
}
location / {
return 301 https://$host$request_uri;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}
server
{
listen 443 ssl http2;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
index index.html;
client_max_body_size 20m;
ssl_certificate /etc/letsencrypt/live/admin.nomadro.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/admin.nomadro.cn/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location ~ ^/\.well-known/ {
allow all;
}
location /assets/ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}
EOF
sudo nginx -t && sudo systemctl reload nginx
fi
fi
echo "==> Status"
sudo systemctl status nomadmini-api --no-pager -l | head -15
curl -s http://127.0.0.1:8010/health || true
echo
echo "Deploy finished."

View File

@ -1,81 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
if [ ! -d /etc/letsencrypt/live/admin.nomadro.cn ]; then
sudo certbot certonly --webroot -w /www/wwwroot/admin.nomadro.cn -d admin.nomadro.cn --non-interactive --agree-tos -m admin@nomadro.cn
fi
"""
_, o, e = c.exec_command(cmd)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
Path("deploy/certbot.txt").write_text(out + "\n" + err, encoding="utf-8")
# write ssl nginx if cert exists
cmd2 = """
if [ -d /etc/letsencrypt/live/admin.nomadro.cn ]; then
sudo tee /www/server/panel/vhost/nginx/admin.nomadro.cn.conf >/dev/null <<'EOF'
server
{
listen 80;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
location ~ ^/\\.well-known/ {
allow all;
}
location / {
return 301 https://$host$request_uri;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}
server
{
listen 443 ssl http2;
server_name admin.nomadro.cn;
root /www/wwwroot/admin.nomadro.cn;
index index.html;
client_max_body_size 20m;
ssl_certificate /etc/letsencrypt/live/admin.nomadro.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/admin.nomadro.cn/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location ~ ^/\\.well-known/ {
allow all;
}
location /assets/ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
access_log /www/wwwlogs/admin.nomadro.cn.log;
error_log /www/wwwlogs/admin.nomadro.cn.error.log;
}
EOF
sudo nginx -t && sudo /etc/init.d/nginx reload
fi
curl -s https://admin.nomadro.cn/ | head -c 120
echo
curl -s https://api.nomadro.cn/health
echo
"""
_, o2, _ = c.exec_command(cmd2)
Path("deploy/certbot2.txt").write_text(o.read().decode("utf-8","replace") + o2.read().decode("utf-8","replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,78 +0,0 @@
import io
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 = "Xiao4669805"
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
tmp.close()
tar_path = Path(tmp.name)
with tarfile.open(tar_path, "w:gz") as tar:
backend = ROOT / "backend"
for p in backend.rglob("*"):
rel = p.relative_to(backend)
if not p.is_file():
continue
if any(x in rel.parts for x in (".venv", "__pycache__", ".git")):
continue
if p.suffix in {".pyc", ".pyo"}:
continue
tar.add(p, arcname=f"backend/{rel.as_posix()}")
dist = ROOT / "dist"
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname=f"admin/dist/{p.relative_to(dist).as_posix()}")
for name in ["admin.nomadro.cn.conf", "api.nomadro.cn.conf", "nomadmini-api.service"]:
data = (ROOT / "deploy" / name).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))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
with SCPClient(c.get_transport()) as scp:
scp.put(str(tar_path), "/tmp/nomadmini-update.tar.gz")
cmd = r"""
set -e
cd /tmp
rm -rf nomadmini-update && mkdir nomadmini-update
tar -xzf nomadmini-update.tar.gz -C nomadmini-update
# keep .env and .venv
rsync -a --delete --exclude '.env' --exclude '.venv' nomadmini-update/backend/ /opt/nomadmini/backend/
sudo rsync -a --delete nomadmini-update/admin/dist/ /www/wwwroot/admin.nomadro.cn/
sudo cp nomadmini-update/deploy/admin.nomadro.cn.conf /www/server/panel/vhost/nginx/admin.nomadro.cn.conf
sudo cp nomadmini-update/deploy/api.nomadro.cn.conf /www/server/panel/vhost/nginx/api.nomadro.cn.conf
sudo cp nomadmini-update/deploy/nomadmini-api.service /etc/systemd/system/nomadmini-api.service
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
sudo systemctl daemon-reload
sudo systemctl restart nomadmini-api
sudo nginx -t
sudo /etc/init.d/nginx reload
sleep 1
curl -s http://127.0.0.1:8010/health
echo
curl -s -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | head -c 80
echo
rm -rf nomadmini-update nomadmini-update.tar.gz
"""
_, o, e = c.exec_command(cmd)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
Path("deploy/continue-redeploy.txt").write_text(out + "\nERR\n" + err, encoding="utf-8")
c.close()
tar_path.unlink(missing_ok=True)
print(out.encode("ascii", "replace").decode())
print("done")

View File

@ -1,11 +0,0 @@
{"ok":true,"service":"nomadmini-api"}
{"ok":true,"saved":1,"notified":1}
[{"id":455,"name":"page_view","page":"pages/home/index","label":"deploy-verify","openid":"","client":"deploy","ts":1790236058.4086673,"created_at":1790236058.4089525,"props":{}},{"id":454,"name":"page_view","page":"pages/home/index","label":"deploy-verify","openid":"","client":"deploy","ts":1790236047.0650654,"created_at":1790236047.065438,"props":{}},{"id":453,"name":"page_view","page":"pages/home/index","label":"deploy-test","openid":"","client":"deploy","ts":1790236045.3911617,"created_at":1790236045.391523,"props":{}}]
213: "name": "pay_deliver",
34: "wx_push",
49: "wx_push": 4,
77: "wx_push": "incoming_envelope",
active
ERR

View File

@ -1,25 +0,0 @@
import json
import urllib.request
html = urllib.request.urlopen("https://admin.nomadro.cn/").read().decode("utf-8", "replace")
print("html has DaTXLZ96", "DaTXLZ96" in html)
req = urllib.request.Request(
"https://api.nomadro.cn/api/admin/login",
data=json.dumps({"username": "admin", "password": "Xiao4669805"}).encode(),
headers={"Content-Type": "application/json"},
)
tok = json.loads(urllib.request.urlopen(req).read())["token"]
req2 = urllib.request.Request(
"https://api.nomadro.cn/api/admin/product-offers",
headers={"Authorization": f"Bearer {tok}"},
)
items = json.loads(urllib.request.urlopen(req2).read())["items"]
print("offers", [(i["key"], i["product_id"], i["price_fen"]) for i in items])
js = urllib.request.urlopen("https://admin.nomadro.cn/assets/index-DaTXLZ96.js").read().decode(
"utf-8", "replace"
)
print("live monetize-panel", "monetize-panel" in js)
print("live product-offers", "product-offers" in js)
print("live old unlock label present", "试读解锁百分比" in js)

View File

@ -1,22 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
systemctl is-active nomadmini-api
curl -s http://127.0.0.1:8010/health
echo
curl -s http://127.0.0.1:8010/api/books/default | head -c 120
echo
curl -sI https://api.nomadro.cn/health | head -8
echo '---'
curl -sI https://admin.nomadro.cn/ | head -8
echo '---'
ls -la /www/wwwroot/admin.nomadro.cn/ | head
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-verify.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,22 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
curl -s https://api.nomadro.cn/health
echo
curl -s https://api.nomadro.cn/api/books/default | head -c 150
echo
curl -s http://admin.nomadro.cn/ | head -c 120
echo
curl -sI http://admin.nomadro.cn/ | head -8
echo '---'
ls -la /etc/letsencrypt/live/ | grep admin || true
sudo cat /www/server/panel/vhost/nginx/admin.nomadro.cn.conf 2>/dev/null | head -30
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-verify2.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,22 +0,0 @@
import paramiko
from pathlib import Path
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("82.157.112.245", username="ubuntu", password="Xiao4669805", timeout=20)
cmd = """
grep proxy_pass /www/server/panel/vhost/nginx/api.nomadro.cn.conf
echo '---'
sudo nginx -T 2>/dev/null | grep -A2 'server_name api.nomadro.cn' | head -20
echo '---'
sudo nginx -T 2>/dev/null | grep -A2 'server_name admin.nomadro.cn' | head -20
echo '---'
curl -s --resolve api.nomadro.cn:443:127.0.0.1 https://api.nomadro.cn/health -k
echo
curl -s --resolve admin.nomadro.cn:80:127.0.0.1 http://admin.nomadro.cn/ | head -c 100
echo
"""
_, o, _ = c.exec_command(cmd)
Path("deploy/remote-verify3.txt").write_text(o.read().decode("utf-8", "replace"), encoding="utf-8")
c.close()
print("ok")

View File

@ -1,36 +0,0 @@
import json
import paramiko
HOST = "82.157.112.245"
USER = "ubuntu"
PASSWORD = "Xiao4669805"
cmds = r"""
set -e
curl -s http://127.0.0.1:8010/health; echo
curl -s -X POST http://127.0.0.1:8010/api/track \
-H 'Content-Type: application/json' \
-d '{"events":[{"name":"page_view","page":"pages/home/index","label":"deploy-verify"}],"client":"deploy"}'; echo
TOKEN=$(curl -s -X POST http://127.0.0.1:8010/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}' \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["token"])')
curl -s "http://127.0.0.1:8010/api/admin/track-events?limit=3" \
-H "Authorization: Bearer $TOKEN"; echo
grep -n pay_deliver /opt/nomadmini/backend/app/routers/pay.py | head -3
grep -n wx_push /opt/nomadmini/backend/app/services/track.py | head -3
systemctl is-active nomadmini-api; echo
"""
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
_, o, e = c.exec_command(cmds)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
c.close()
from pathlib import Path
Path(__file__).resolve().parent.joinpath("verify-track-out.txt").write_text(
out + "\nERR\n" + err, encoding="utf-8"
)
print("ok bytes", len(out))

View File

@ -1,31 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1"
/>
<meta name="theme-color" content="#0e1512" media="(prefers-color-scheme: dark)" />
<meta name="theme-color" content="#0e1512" />
<meta name="color-scheme" content="dark" />
<meta name="description" content="Nomadro 微信 / 抖音小程序管理后台" />
<meta name="application-name" content="Nomadro Admin" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Nomadro" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no" />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>Nomadro Admin</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +0,0 @@
{
"name": "@nomadro/admin",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0 --port 5173",
"build": "tsc -b && vite build",
"preview": "vite preview --host 0.0.0.0 --port 5173"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.6.3",
"vite": "^5.4.11"
}
}

1128
apps/admin/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 317 B

View File

@ -1,20 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Nomadro Admin">
<defs>
<linearGradient id="g" x1="8" y1="4" x2="56" y2="60" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#7be0a4"/>
<stop offset="55%" stop-color="#3f9d68"/>
<stop offset="100%" stop-color="#246b45"/>
</linearGradient>
<linearGradient id="shine" x1="12" y1="6" x2="40" y2="36" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#fff" stop-opacity="0.35"/>
<stop offset="100%" stop-color="#fff" stop-opacity="0"/>
</linearGradient>
</defs>
<rect width="64" height="64" rx="14" fill="#0e1512"/>
<rect x="4" y="4" width="56" height="56" rx="12" fill="url(#g)"/>
<rect x="4" y="4" width="56" height="56" rx="12" fill="url(#shine)"/>
<path
d="M18 44V20h7.2l7.6 15.2L40.4 20H47.6v24h-6.2V29.2L35.2 44h-6.4L22.6 29.2V44H18z"
fill="#062012"
/>
</svg>

Before

Width:  |  Height:  |  Size: 938 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

View File

@ -1,38 +0,0 @@
{
"name": "Nomadro Admin",
"short_name": "Nomadro",
"description": "Nomadro 微信 / 抖音小程序管理后台",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "any",
"background_color": "#0e1512",
"theme_color": "#0e1512",
"lang": "zh-CN",
"icons": [
{
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/apple-touch-icon.png",
"sizes": "180x180",
"type": "image/png",
"purpose": "any"
}
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

View File

@ -1,118 +0,0 @@
import { Navigate, Route, Routes, useParams } from 'react-router-dom'
import { getToken } from './api'
import Login from './pages/Login'
import PlatformSelect from './pages/PlatformSelect'
import Dashboard from './pages/Dashboard'
import Switches from './pages/Switches'
import BookEdit from './pages/BookEdit'
import './pages/BookEdit.css'
import Orders from './pages/Orders'
import Users from './pages/Users'
import VipUsers from './pages/VipUsers'
import Events from './pages/Events'
import Checklist from './pages/Checklist'
import Vip from './pages/Vip'
import VipLibrary from './pages/VipLibrary'
import Shop from './pages/Shop'
import Memo from './pages/Memo'
import Nav from './pages/Nav'
import Layout from './components/Layout'
import DouyinLayout from './pages/douyin/DouyinLayout'
import DouyinOverview from './pages/douyin/DouyinOverview'
import DouyinModules from './pages/douyin/DouyinModules'
import DouyinBook from './pages/douyin/DouyinBook'
import DouyinDocs from './pages/douyin/DouyinDocs'
function Private({ children }: { children: React.ReactNode }) {
if (!getToken()) return <Navigate to="/login" replace />
return <>{children}</>
}
function WechatRedirect({ to }: { to: string }) {
return <Navigate to={to} replace />
}
function LegacyBookRedirect() {
const { id } = useParams()
return <Navigate to={`/wechat/books/${id || 'default'}`} replace />
}
/**
* https://admin.nomadro.cn
* - /wechat/* 微信电子书后台
* - /douyin/* 抖音定制面板(加群弹窗集成在 /douyin/modules)
* 门户 nomadro.cn/admin 是另一套系统
*/
export default function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/"
element={
<Private>
<PlatformSelect />
</Private>
}
/>
<Route path="/join-group" element={<Navigate to="/douyin/modules#join-group" replace />} />
<Route
path="/wechat"
element={
<Private>
<Layout />
</Private>
}
>
<Route index element={<Dashboard />} />
<Route path="switches" element={<Switches />} />
<Route path="books/:id" element={<BookEdit />} />
<Route path="vip" element={<Vip />} />
<Route path="vip/users" element={<VipUsers />} />
<Route path="vip/ebooks" element={<Navigate to="/wechat/vip/ebooks/nomad" replace />} />
<Route path="vip/ebooks/:bookId" element={<VipLibrary />} />
<Route path="vip/course" element={<VipLibrary />} />
<Route path="vip/library" element={<Navigate to="/wechat/vip/ebooks/nomad" replace />} />
<Route path="nav" element={<Nav />} />
<Route path="shop" element={<Shop />} />
<Route path="memo" element={<Memo />} />
<Route path="orders" element={<Orders />} />
<Route path="users" element={<Users />} />
<Route path="events" element={<Events />} />
<Route path="checklist" element={<Checklist />} />
<Route path="join-group" element={<Navigate to="/douyin/modules#join-group" replace />} />
</Route>
<Route
path="/douyin"
element={
<Private>
<DouyinLayout />
</Private>
}
>
<Route index element={<DouyinOverview />} />
<Route path="modules" element={<DouyinModules />} />
<Route path="book" element={<DouyinBook />} />
<Route path="join-group" element={<Navigate to="/douyin/modules#join-group" replace />} />
<Route path="docs" element={<DouyinDocs />} />
</Route>
<Route path="/books/:id" element={<LegacyBookRedirect />} />
<Route path="/orders" element={<WechatRedirect to="/wechat/orders" />} />
<Route path="/users" element={<WechatRedirect to="/wechat/users" />} />
<Route path="/events" element={<WechatRedirect to="/wechat/events" />} />
<Route path="/checklist" element={<WechatRedirect to="/wechat/checklist" />} />
<Route path="/vip" element={<WechatRedirect to="/wechat/vip" />} />
<Route path="/vip/users" element={<WechatRedirect to="/wechat/vip/users" />} />
<Route path="/nav" element={<WechatRedirect to="/wechat/nav" />} />
<Route path="/shop" element={<WechatRedirect to="/wechat/shop" />} />
<Route path="/memo" element={<WechatRedirect to="/wechat/memo" />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}

View File

@ -1,2 +0,0 @@
/** @deprecated 请从 `./api/client` 导入;保留以兼容现有页面 */
export * from './api/client'

View File

@ -1,3 +0,0 @@
# API 层:请求封装(admin)
后续可按领域拆成 `books.ts` / `orders.ts`;类型见 `@nomadmini/shared-types` 或本地 `types/`。

View File

@ -1,37 +0,0 @@
const TOKEN_KEY = 'nomadro_admin_token'
/** 生产环境走同域 /api 或通过 VITE_API_BASE 指定 */
export const API_BASE = import.meta.env.VITE_API_BASE || ''
export function getToken() {
return localStorage.getItem(TOKEN_KEY) || ''
}
export function setToken(t: string) {
localStorage.setItem(TOKEN_KEY, t)
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY)
}
export async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(init.headers as Record<string, string> | undefined),
}
const token = getToken()
if (token) headers.Authorization = `Bearer ${token}`
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
if (res.status === 401) {
clearToken()
if (!path.includes('/login')) window.location.href = '/login'
}
const data = await res.json().catch(() => ({}))
if (!res.ok) {
const err = data as { detail?: string; message?: string }
throw new Error(err.detail || err.message || '请求失败')
}
return data as T
}

View File

@ -1,313 +0,0 @@
import { useEffect, useMemo, useState } from 'react'
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { clearToken } from '../api'
import '../pages/wechat.css'
type NavLeaf = { kind?: 'link'; to: string; end?: boolean; ico: string; label: string }
type NavBranch = {
kind: 'branch'
id: string
ico: string
label: string
/** 任一前缀命中则父级高亮并保持展开 */
match: string[]
children: NavItem[]
/** 展开时默认跳转 */
defaultTo?: string
}
type NavItem = NavLeaf | NavBranch
type NavGroup = { label: string; items: NavItem[] }
const NAV_GROUPS: NavGroup[] = [
{
label: '总览',
items: [
{ to: '/wechat', end: true, ico: '◈', label: '运营概览' },
{ to: '/wechat/switches', ico: '⏻', label: '开关' },
],
},
{
label: '内容',
items: [
{ to: '/wechat/nav', ico: '🧭', label: '导航' },
{
kind: 'branch',
id: 'vip',
ico: '👑',
label: 'VIP',
match: ['/wechat/vip', '/wechat/shop', '/wechat/memo', '/wechat/books'],
defaultTo: '/wechat/vip',
children: [
{ to: '/wechat/vip', end: true, ico: '⚙', label: '运营配置' },
{ to: '/wechat/vip/users', ico: '👑', label: 'VIP用户' },
{
kind: 'branch',
id: 'ebooks',
ico: '📖',
label: '电子书',
match: ['/wechat/vip/ebooks', '/wechat/books'],
defaultTo: '/wechat/vip/ebooks/nomad',
children: [
{ to: '/wechat/vip/ebooks/nomad', ico: '🌍', label: '数字游民' },
{ to: '/wechat/vip/ebooks/cloudphone', ico: '📱', label: '云手机' },
{ to: '/wechat/books/default', ico: '▶️', label: 'youtube运营笔记' },
],
},
{ to: '/wechat/vip/course', ico: '🎬', label: '视频课程' },
{ to: '/wechat/shop', ico: '🛒', label: '电商' },
{ to: '/wechat/memo', ico: '🏕️', label: '知识社群' },
],
},
],
},
{
label: '运营',
items: [
{ to: '/wechat/users', ico: '👥', label: '读者' },
{ to: '/wechat/vip/users', ico: '👑', label: 'VIP用户' },
{ to: '/wechat/orders', ico: '🧾', label: '订单' },
],
},
{
label: '数据与发布',
items: [
{ to: '/wechat/events', ico: '📊', label: '埋点事件' },
{ to: '/wechat/checklist', ico: '✓', label: '部署检查清单' },
],
},
]
function flattenLeaves(items: NavItem[]): NavLeaf[] {
const out: NavLeaf[] = []
for (const item of items) {
if (item.kind === 'branch') out.push(...flattenLeaves(item.children))
else out.push(item)
}
return out
}
const FLAT_NAV = NAV_GROUPS.flatMap((g) => flattenLeaves(g.items))
function titleFromPath(pathname: string) {
const sorted = [...FLAT_NAV].sort((a, b) => b.to.length - a.to.length)
const hit = sorted.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
return hit?.label || '微信后台'
}
function isBranchActive(branch: NavBranch, pathname: string) {
return branch.match.some((m) => pathname === m || pathname.startsWith(`${m}/`))
}
/** 微信小程序后台壳层 — 仅 /wechat/*;VIP / 电子书二级菜单;移动端抽屉 */
export default function Layout() {
const nav = useNavigate()
const { pathname } = useLocation()
const [drawerOpen, setDrawerOpen] = useState(false)
const vipActive = useMemo(
() =>
pathname === '/wechat/vip' ||
pathname.startsWith('/wechat/vip/') ||
pathname.startsWith('/wechat/shop') ||
pathname.startsWith('/wechat/memo') ||
pathname.startsWith('/wechat/books'),
[pathname],
)
const ebooksActive = useMemo(
() => pathname.startsWith('/wechat/vip/ebooks') || pathname.startsWith('/wechat/books'),
[pathname],
)
const [vipOpen, setVipOpen] = useState(() => vipActive)
const [ebooksOpen, setEbooksOpen] = useState(() => ebooksActive)
useEffect(() => {
setDrawerOpen(false)
}, [pathname])
useEffect(() => {
if (vipActive) setVipOpen(true)
}, [vipActive])
useEffect(() => {
if (ebooksActive) {
setVipOpen(true)
setEbooksOpen(true)
}
}, [ebooksActive])
useEffect(() => {
document.body.style.overflow = drawerOpen ? 'hidden' : ''
return () => {
document.body.style.overflow = ''
}
}, [drawerOpen])
function logout() {
clearToken()
nav('/login')
}
function toggleBranch(branch: NavBranch) {
if (branch.id === 'vip') {
setVipOpen((v) => {
const next = !v
if (next && !vipActive) nav(branch.defaultTo || '/wechat/vip')
return next
})
return
}
if (branch.id === 'ebooks') {
setEbooksOpen((v) => {
const next = !v
if (next && !ebooksActive) nav(branch.defaultTo || '/wechat/vip/ebooks/nomad')
return next
})
}
}
function isOpen(branch: NavBranch) {
if (branch.id === 'vip') return vipOpen
if (branch.id === 'ebooks') return ebooksOpen
return false
}
function renderEntry(item: NavItem, depth = 0) {
if (item.kind === 'branch') {
const open = isOpen(item)
const active = isBranchActive(item, pathname)
const nestClass = depth > 0 ? ' wx-nav-branch--nested' : ''
return (
<div
key={item.id}
className={`wx-nav-branch${nestClass}${open ? ' is-open' : ''}${active ? ' is-active' : ''}`}
>
<button
type="button"
className={`wx-nav-parent${depth > 0 ? ' wx-nav-parent--nested' : ''}`}
aria-expanded={open}
onClick={() => toggleBranch(item)}
>
<span className="wx-nav-ico" aria-hidden>
{item.ico}
</span>
<span className="wx-nav-parent-label">{item.label}</span>
<span className="wx-nav-caret" aria-hidden>
{open ? '▾' : '▸'}
</span>
</button>
{open ? (
<div className="wx-nav-sub" role="group" aria-label={`${item.label}子菜单`}>
{item.children.map((child) =>
child.kind === 'branch' ? (
renderEntry(child, depth + 1)
) : (
<NavLink
key={child.to}
to={child.to}
end={!!child.end}
className={depth > 0 ? 'wx-nav-sublink wx-nav-sublink--deep' : 'wx-nav-sublink'}
onClick={() => setDrawerOpen(false)}
>
<span className="wx-nav-ico" aria-hidden>
{child.ico}
</span>
{child.label}
</NavLink>
),
)}
</div>
) : null}
</div>
)
}
return (
<NavLink
key={item.to}
to={item.to}
end={!!item.end}
onClick={() => setDrawerOpen(false)}
>
<span className="wx-nav-ico" aria-hidden>
{item.ico}
</span>
{item.label}
</NavLink>
)
}
return (
<div className={`wx-shell${drawerOpen ? ' wx-shell--nav-open' : ''}`}>
<header className="wx-topbar">
<button
type="button"
className="wx-topbar-menu"
aria-label={drawerOpen ? '关闭菜单' : '打开菜单'}
aria-expanded={drawerOpen}
onClick={() => setDrawerOpen((v) => !v)}
>
<span />
<span />
<span />
</button>
<div className="wx-topbar-brand">
<img src="/favicon-32x32.png" width={28} height={28} alt="" />
<div>
<div className="wx-topbar-title">微信后台</div>
<div className="wx-topbar-sub">{titleFromPath(pathname)}</div>
</div>
</div>
<button type="button" className="wx-topbar-action" onClick={() => nav('/')}>
平台
</button>
</header>
{drawerOpen && (
<button
type="button"
className="wx-nav-scrim"
aria-label="关闭菜单"
onClick={() => setDrawerOpen(false)}
/>
)}
<aside className="wx-side" aria-hidden={!drawerOpen}>
<div className="wx-logo">
<img src="/apple-touch-icon.png" width={42} height={42} alt="" />
<div>
<div className="wx-title">微信后台</div>
<div className="wx-sub">小程序 · 虚拟支付运营</div>
</div>
</div>
<div className="wx-pill">
<span className="wx-pill-dot" />
与抖音数据隔离
</div>
<nav className="wx-nav" aria-label="微信后台导航">
{NAV_GROUPS.map((group) => (
<div className="wx-nav-group" key={group.label}>
<div className="wx-nav-label">{group.label}</div>
{group.items.map((item) => renderEntry(item))}
</div>
))}
</nav>
<div className="wx-side-foot">
<button type="button" className="wx-ghost" onClick={() => nav('/')}>
← 切换平台
</button>
<button type="button" className="wx-ghost" onClick={logout}>
退出登录
</button>
</div>
</aside>
<main className="wx-main">
<Outlet />
</main>
</div>
)
}

View File

@ -1,134 +0,0 @@
import { ReactNode, useEffect } from 'react'
export function WxHead({
eyebrow,
title,
desc,
children,
}: {
eyebrow?: string
title: string
desc?: string
children?: ReactNode
}) {
return (
<header className="wx-head">
<div>
{eyebrow ? <div className="wx-eyebrow">{eyebrow}</div> : null}
<h1>{title}</h1>
{desc ? <p>{desc}</p> : null}
</div>
{children ? <div className="wx-head-actions">{children}</div> : null}
</header>
)
}
export function WxToast({
kind,
children,
onClose,
}: {
kind: 'ok' | 'err' | 'info'
children: ReactNode
onClose?: () => void
}) {
useEffect(() => {
if (!onClose || kind === 'err') return
const t = window.setTimeout(onClose, 4200)
return () => window.clearTimeout(t)
}, [children, kind, onClose])
return (
<div className={`wx-toast wx-toast--${kind}`} role="status">
<span>{children}</span>
{onClose ? (
<button type="button" onClick={onClose}>
关闭
</button>
) : null}
</div>
)
}
export function WxTabs<T extends string>({
value,
onChange,
items,
}: {
value: T
onChange: (v: T) => void
items: { key: T; label: string; count?: number }[]
}) {
return (
<div className="wx-tabs" role="tablist">
{items.map((it) => (
<button
key={it.key}
type="button"
role="tab"
aria-selected={value === it.key}
className={`wx-tab${value === it.key ? ' is-on' : ''}`}
onClick={() => onChange(it.key)}
>
{it.label}
{typeof it.count === 'number' ? <em>{it.count}</em> : null}
</button>
))}
</div>
)
}
export function WxBadge({
tone,
children,
}: {
tone?: 'ok' | 'warn' | 'bad' | 'muted' | 'info'
children: ReactNode
}) {
return <span className={`wx-badge wx-badge--${tone || 'muted'}`}>{children}</span>
}
export function WxEmpty({ title, hint }: { title: string; hint?: string }) {
return (
<div className="wx-empty">
<strong>{title}</strong>
{hint ? <span>{hint}</span> : null}
</div>
)
}
export async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
try {
const ta = document.createElement('textarea')
ta.value = text
ta.style.position = 'fixed'
ta.style.left = '-9999px'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
return true
} catch {
return false
}
}
}
export function fmtYuan(fen: number) {
return `¥${(Number(fen || 0) / 100).toFixed(2)}`
}
export function fmtTime(sec?: number | null) {
if (!sec) return '—'
return new Date(sec * 1000).toLocaleString()
}
export function shortId(id?: string | null, keep = 8) {
if (!id) return '—'
if (id.length <= keep + 2) return id
return `…${id.slice(-keep)}`
}

View File

@ -1,13 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './styles.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
)

Some files were not shown because too many files have changed in this diff Show More