Compare commits

..

No commits in common. "2026-11-02" and "main" have entirely different histories.

4017 changed files with 22591 additions and 421906 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,17 +0,0 @@
---
description: 多端 UI 比例铁律 — Web/微信/抖音/小红书;禁止把 Web px 弹窗原样搬进小程序
alwaysApply: true
---
# 多端 UI 比例(强制)
**Web 只参考结构;尺寸必须按端适配。** 详情见 `.cursor/skills/multi-platform-ui-scale/SKILL.md`。
| 端 | 要点 |
|----|------|
| Web VIP | 可居中 `max-w-[400px]` |
| Taro H5/weapp/tt/xhs | `designWidth: 750`;**裸 `px` → rpx 会缩水**;弹窗/表单用 **`rem` 或 `rpx`** |
| 小程序弹窗 | **全宽底栏** + 触控 ≥44px;勿抄 Web 桌面小卡片 |
反模式:VIP LoginModal 在微信里变成拇指盖大的居中框。
正确参考:`apps/miniprogram/h5/src/components/VipLoginModal.scss`、`vip-landing.scss`。

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,14 +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
- **多端比例**:Web 只参考结构;微信/抖音/小红书/Taro 禁止照抄 Web 桌面 `px` 弹窗(`designWidth: 750` 会缩水)。见 `multi-platform-ui-scale` skill + rule
- 社媒引导:海外弹 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,60 +0,0 @@
---
name: multi-platform-ui-scale
description: >-
Nomadro 多端 UI 比例与 CSS 单位铁律:Web / H5 / 微信小程序 / 抖音小程序 / 小红书。
写或改任何弹窗、按钮、落地页、VIP LoginModal、Taro 样式时必须遵守;
禁止把 Web 桌面尺寸原样搬到小程序导致弹窗缩成一团。
---
# 多端 UI 比例铁律(写死,勿再问)
## 一句话
**Web 只参考结构与信息架构;最终尺寸必须按当前端的触控与单位体系适配。禁止「照抄 Web 的 px 弹窗」到微信/抖音/小红书。**
## 端与技术
| 端 | 路径 | 单位 / 设计稿 |
|----|------|----------------|
| Web 门户 VIP | `src/modules/vip` | CSS / Tailwind;桌面可居中 `max-w-[400px]` |
| Taro H5 SoT | `apps/miniprogram/h5` | 与落地页一致优先 **`rem`**(对齐 vip-landing) |
| 微信 weapp | `apps/miniprogram/weapp` · `designWidth: 750` | **裸写 `px` 会被转成 rpx → 尺寸腰斩** |
| 抖音 tt | `apps/miniprogram/tt` · `designWidth: 750` | 同 weapp |
| 小红书 xhs | `apps/miniprogram/xhs` | 同 Taro 750;纯工具页离线优先 |
H5 SoT 共用源码:`weapp/tt` 的 `sourceRoot` 指向 `../h5/src` —— **一处样式四端吃**,写样式时按「最严端(小程序)」适配。
## 强制规则
1. **小程序 / Taro 共用样式**
- 弹窗、表单、CTA:**用 `rem`(与 `vip-landing.scss` 同尺度)或显式 `rpx`**
- **禁止**在共用 SCSS 里写死 Web 桌面感的 `max-width: 400px` + 一堆裸 `px`(会被 750 稿压成拇指盖大的卡片)
- 触控热区:**≥ 44px 等价**(约 `2.75rem` / `88rpx`)
- 手机弹窗:**全宽底栏 sheet**(`align-items: flex-end` + 顶圆角);宽屏再可居中。不要默认桌面居中小卡片。
2. **Web VIP LoginModal**
- 仅参考:**标题「登录」+ Tab「账号/邮箱」+ 输入 +「验证并登录」+ 验证中全屏层**
- **不要**把 Web 的 `max-w-[400px]` 居中小卡原样搬进小程序
- 不要加品牌眉、副标题、字段标签等「超级优化」花活,除非产品明确要求
3. **参考 ≠ 复制尺寸**
- 结构、文案、交互流:可对齐 Web
- padding / font / 宽度 / 圆角:**按小程序重算**
4. **改弹窗前自检**
- [ ] 微信模拟器里弹窗是否接近屏宽、按钮是否好点
- [ ] 是否误用裸 `px` 导致缩水
- [ ] H5 / weapp / tt 是否同源样式、比例一致
## 反模式(禁止)
- 把 Web `LoginModal` 的 Tailwind 间距原样抄成 Taro `px`
- 小程序里居中一块「桌面对话框」又细又小
- 用户每次提醒「比例」才改 —— 本 skill 已写死,开工先遵守
## 关联
- 全端禁止 web-view:`.cursor/rules/no-webview-content.mdc`
- 远程配置 + 离线:`.cursor/rules/remote-config-offline.mdc`
- 现成正确示例:`apps/miniprogram/h5/src/components/VipLoginModal.scss`(rem + 底栏)
`apps/miniprogram/h5/src/styles/vip-landing.scss`

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: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`).
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。

254
README.md
View File

@ -1,222 +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 + social) git branch -M main
apps/admin/ admin.nomadro.cn 管理 SPA(Vite) git push -uf origin main
packages/ @nomadro/pay · pb · sdk
data/ 远程配置等运行时数据(含 social.db 独立库)
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`(Lounge / Ergo / MiroTalk;**勿改名**) |
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
| 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);**Youtube运营笔记**走 `pages/reader?id=default`(后台 books/default) |
| **知识社群** | `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`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`**
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`)
### 游民社区(`/social`) ## License
For open source projects, say how it is licensed.
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。 ## Project status
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.
| 层 | 线上(82) | 说明 |
|---|---|---|
| 门户 | `nomadro.service` `:4003` | `/social/*`;前端发版须**本地确认后再上线** |
| Social API | `nomadro-social.service` `:8020` | `apps/api/social_main.py`;nginx `/api/social/` |
| 实时 | `centrifugo.service` `:8008` | `wss://nomadro.cn/rt/connection/websocket`;密钥 `/etc/nomadro/centrifugo.env` |
| 视频 | `mirotalk-p2p` → `mirotalk.nomadro.cn` | 白标中文极速进房;禁 `.com`/107 |
**视觉主题**:代码保留 T1(旅居社群对齐,**默认**)与 T2(琥珀信号,`theme2.css`);导航切换器已隐藏,强制 T1。恢复切换:见 `SiteShell` + `lib/skin.ts`。
**生产铁律**:[`https://nomadro.cn`](https://nomadro.cn/) 全链路只跑 **`82.157.112.245`**。视频厅用同机 **`https://mirotalk.nomadro.cn`**(nginx → `127.0.0.1:9300`),禁止进房再走 `mirotalk.nomadro.com` / 107。
## pre4 摘要(审核包)
- 微信启动页 **`pages/home/index`**;`pages/index` 兼容 `reLaunch` → home
- 本轮标记:**`20261011-2`**(审核中;承接 `20261011b` 路径 + `20261011` 视觉)
- **VIP ↔ Web 账号打通(增量,默认关)**
- Flag:`flags.vipWebBridgeEnabled`(后台 VIP 运营可开;`VIP_WEB_BRIDGE_ENABLED` 可强开)
- 小程序:`VipLoginModal`(rem 底栏)· `pages/vip-account`;已绑定不展示废按钮/支付 hint
- API:`/api/ebook/auth/vip-web-login` · `vip-bind-email` · `vip-bridge-status`(只读校验 vip.hackrobot.cn)
- **网盘 / 课时资料**
- VIP 落地:`netdisk` 列表 + `NetdiskShareModal`(对齐 Web 分享弹窗结构,小程序全宽底栏)
- 课时页:默认**不**展示资料;仅 `lessonMaterials[课时key]` 单独配了 `url` 才显示
- **多端 UI 比例**:`.cursor/skills/multi-platform-ui-scale` + rule(Web 只参考结构,小程序用 rem/rpx)
- **课时播放**:视频 URL 编码空格/中文;本地片源先起播,不挡 `forceRefresh`
- **审核前修复(`20261011-2`)**
- VIP「Youtube运营笔记」→ `reader?id=default`;提审开关不劫持 `book_id=default`
- VIP/加群开关联动;加群点击强制拉最新 `/api/config`
- **P0/P1 加固**(`017008d`):VIP library 鉴权、Mine 登录、game stub、WAL/限流、CORS
## pre5 摘要
从 `pre4` 切出;**勿改动审核包行为**。本轮落地:
- **游民社区**:`/social` 全站能力(加入 / 文字厅 / 活动直播嵌 MiroTalk / coffeechat / 约会 / 花名册 / UGC / 接单 / 反馈 / VIP 入口)
- 隔离 API + SQLite;远程配置 `modules.social`;门户 hero 主入口切换为游民社区
- 社区 Settings `extra="ignore"`,避免统一 `.env` 拖垮 community 启动
## test5
从 `pre5` 切出。已落地(细节以 `deploy/social/README.md` 为准):
- **Social 实时**:Centrifugo + `/api/social/v1/realtime/token`;聊天页优先 WS,失败降级轮询
- **Social API 独立进程**:`nomadro-social` `:8020`,与 ebook/community/pay 隔离
- **MiroTalk**:钉死 82 `.cn`、白标中文、极速进房
- **视觉**:T1 默认;T2 代码保留、切换器隐藏
## test6 / test7(已发版)
游民社区 `/social` 手机端深优(门户 `h5.css` 最后加载):
- **Ways**:`群组聊天 → 认识一下 → 开视频 → 见面 → 找搭子`;竖列表,勿再做成轮播
- **底栏**:首页 → 聊天 → 认识 → 看看谁 → 我;聊天/滑卡操作区避开 dock + safe-area
- **首屏**:群组聊天在左、认识一下在右;窄屏收掉宇宙轨道,Ways 进首视口
- **滑卡 / 群聊**:手机更低滑动阈值、震动反馈;composer / 加入 sheet 全宽底栏
- **Meetup**:活动卡保留参与者头像 + 声纹条
- **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social`
## test8
从 `test7` 切出;原生 weapp 游民社区、SRS 直播、加群支付等已合入 `test9`。
## test9 · tag `2026-11-02`(微信提审包)
从 `test8` / `f204063` 线切出并定版,准备上传微信审核与上线。
| 项 | 说明 |
|---|---|
| 分支 / Tag | `test9` · **`2026-11-02`** |
| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) |
| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` |
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 audit 正文(失联才包内兜底);关则正式 nomad |
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
提审上传:
```bash
pnpm build:weapp
# 微信开发者工具打开 apps/miniprogram/weapp(miniprogramRoot=dist/)→ 上传
# 后台按需打开「数字游民」提审;socket 合法域名含 api.nomadro.cn
```
## pre3 摘要(已合入)
微信提审与包体:
- **数字游民小册提审**:后台 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`**。历史审核 tag:`20261011` / `20261011b` / `20261011-2`;**本轮提审 tag:`2026-11-02`(分支 `test9`)**。`pages/index/index` 仅兼容 `reLaunch` → home。详见 `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,19 +0,0 @@
# -*- coding: utf-8 -*-
import json
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
url = "https://api.nomadro.cn/api/ebook/config"
with urllib.request.urlopen(url, timeout=15) as r:
d = json.loads(r.read().decode("utf-8", "replace"))
cfg = d.get("config") or {}
flags = cfg.get("flags") or {}
copy = cfg.get("copy") or {}
plat = ((cfg.get("platforms") or {}).get("weapp") or {})
print("flags.reviewMode / bookAudit =", {k: flags.get(k) for k in flags if "audit" in k.lower() or "review" in k.lower()})
print("copy keys sample", [k for k in copy if "audit" in k.lower() or "book" in k.lower() or "review" in k.lower()])
print("weapp keys", list(plat.keys())[:20])
# dump relevant
import pprint
pprint.pp({k: flags[k] for k in sorted(flags) if k in flags})

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,110 +0,0 @@
# -*- coding: utf-8 -*-
"""Fix audit book API 500 (missing chapter order) + deploy read_policy/store."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
REPO / "apps/api/services/ebook_svc/domains/books/read_policy.py",
"/opt/nomadmini/backend/app/domains/books/read_policy.py",
),
(
REPO / "apps/api/services/ebook_svc/services/store.py",
"/opt/nomadmini/backend/app/services/store.py",
),
]
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
tmp = f"/tmp/{Path(dest).name}"
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("upload", src.name, flush=True)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/read_policy.py /opt/nomadmini/backend/app/domains/books/read_policy.py
sudo cp /tmp/store.py /opt/nomadmini/backend/app/services/store.py
python3 - <<'PY'
import json, sqlite3, time
db='/opt/nomadmini/data/nomadmini.db'
con=sqlite3.connect(db)
row=con.execute("select chapters_json from books where id='audit'").fetchone()
if row:
ch=json.loads(row[0] or '[]')
fixed=[]
for i,c in enumerate(ch if isinstance(ch,list) else []):
if not isinstance(c, dict):
continue
c=dict(c)
c['id']=str(c.get('id') or f'ch-{i+1}')
c['title']=str(c.get('title') or f'章节 {i+1}')
c['order']=int(c['order']) if c.get('order') is not None else i+1
c['content']=str(c.get('content') or '')
fixed.append(c)
if not fixed:
fixed=[{
'id':'01-audit','title':'欢迎阅读','order':1,
'content':'# 数字游民·提审版\n\n这是微信提审用的独立内容,与会员正式书无关。\n'
}]
con.execute(
"update books set title=?, subtitle=?, unlock_percent=100, price_fen=0, product_id='', chapters_json=?, updated_at=? where id='audit'",
('数字游民·提审版','微信提审专用 · 与正式会员书无关', json.dumps(fixed, ensure_ascii=False), time.time())
)
con.commit()
print('fixed chapters', len(fixed), 'orders', [x['order'] for x in fixed])
else:
print('no audit row')
PY
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
curl -sk -o /tmp/audit.json -w "books/audit %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit"
python3 - <<'PY'
import json
d=json.load(open('/tmp/audit.json',encoding='utf-8'))
print('title', d.get('title'), 'chapters', len(d.get('chapters') or []), 'free', d.get('is_free'))
print('ch0', (d.get('chapters') or [{}])[0])
PY
curl -sk -o /tmp/audit_read.json -w "books/audit/read %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit/read"
python3 - <<'PY'
import json
d=json.load(open('/tmp/audit_read.json',encoding='utf-8'))
chs=d.get('chapters') or []
print('read chapters', len(chs), 'title', (d.get('book') or {}).get('title'))
if chs:
print('body', (chs[0].get('content') or '')[:120].replace('\n',' '))
PY
rm -f /tmp/read_policy.py /tmp/store.py /tmp/audit.json /tmp/audit_read.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,56 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(REPO / "apps/api/services/ebook_svc/core/deps.py", "/opt/nomadmini/backend/app/core/deps.py"),
(REPO / "apps/api/services/ebook_svc/routers/books.py", "/opt/nomadmini/backend/app/routers/books.py"),
]
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
with sftp.file(f"/tmp/{Path(dest).name}", "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/deps.py /opt/nomadmini/backend/app/core/deps.py
sudo cp /tmp/books.py /opt/nomadmini/backend/app/routers/books.py
sudo systemctl restart nomadmini-api
sleep 2
curl -sk -o /tmp/r.json -w "read %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit/read
python3 - <<'PY'
import json
d=json.load(open('/tmp/r.json',encoding='utf-8'))
print('title', (d.get('book') or {}).get('title'))
print('chapters', len(d.get('chapters') or []))
body=((d.get('chapters') or [{}])[0].get('content') or '')[:100]
print('body', body.replace('\n',' '))
PY
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,39 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
ls -la /www/server/panel/vhost/nginx/*api* 2>/dev/null || true
echo ---CONF---
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
if [ -f "$CONF" ]; then
grep -n 'config/ws\|proxy_pass\|location /' "$CONF" | head -80
else
echo missing_conf
ls /www/server/panel/vhost/nginx/ | head
fi
echo ---DIRECT---
curl -sk -i -N --max-time 3 \
-H 'Connection: Upgrade' \
-H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
http://127.0.0.1:8010/api/config/ws | head -30
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
echo '=== find api host conf ==='
sudo grep -RIl 'api.nomadro.cn' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
echo '=== find 8010 ==='
sudo grep -RIl '8010' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
echo '=== our bak? ==='
ls -la /www/server/panel/vhost/nginx/api.nomadro.cn.conf* 2>/dev/null || true
ls -la /www/server/panel/vhost/nginx/*.bak-config-ws 2>/dev/null || true
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=90)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -1,72 +0,0 @@
# -*- coding: utf-8 -*-
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT=/www/server/panel/vhost/nginx/extension/www.nomadro.cn/live-flv.conf
sudo tee "$EXT" >/dev/null <<'EOF'
# Nomadro social native live — must beat Next catch-all
location ^~ /live/ {
proxy_pass http://127.0.0.1:1985/live/;
proxy_http_version 1.1;
proxy_set_header Connection "";
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_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-cache always;
add_header X-Nomadro-Live srs always;
}
EOF
sudo nginx -t
sudo systemctl reload nginx
echo '=== public /live/ headers ==='
curl -skI --max-time 5 'https://nomadro.cn/live/nope.flv' | head -20 || true
echo '=== local srs headers ==='
curl -sI --max-time 3 'http://127.0.0.1:1985/live/nope.flv' | head -15 || true
echo '=== join 2 peers ==='
curl -sk --max-time 8 -X POST 'https://nomadro.cn/api/social/v1/live/rooms/hall1/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: peer_alice' \
-d '{"nick":"Alice"}' > /tmp/a.json
curl -sk --max-time 8 -X POST 'https://nomadro.cn/api/social/v1/live/rooms/hall1/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: peer_bob' \
-d '{"nick":"Bob"}' > /tmp/b.json
python3 - <<'PY'
import json
a=json.load(open('/tmp/a.json'))
b=json.load(open('/tmp/b.json'))
print('alice_ok', a.get('ok'), 'peers', [p['nick'] for p in a.get('peers',[])])
print('bob_ok', b.get('ok'), 'peers', [p['nick'] for p in b.get('peers',[])])
print('push', (a.get('pushUrl') or '')[:90])
print('play', (a.get('playUrl') or '')[:90])
print('engine', a.get('engine'))
PY
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()

View File

@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
echo '=== who serves 443 ==='
sudo ss -lntp | grep ':443'
echo '=== caddy? ==='
systemctl is-active caddy 2>/dev/null || true
ls /etc/caddy 2>/dev/null | head
echo '=== nginx? ==='
systemctl is-active nginx 2>/dev/null || true
sudo nginx -T 2>/dev/null | grep -E 'server_name|8020|api/social|listen 443' | head -40
echo '=== find social proxy ==='
sudo grep -R '8020\|api/social' /etc /var/www -g '!*.log' 2>/dev/null | head -30
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -1,27 +0,0 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
sudo nginx -T 2>/dev/null | grep -n 'server_name nomadro.cn' | head
# dump the nomadro.cn server block roughly
sudo nginx -T 2>/dev/null | awk '/server_name nomadro.cn/{flag=1} flag{print} /server_name / && !/nomadro.cn/{if(flag&&seen++){exit}}' | head -120
echo '==== conf files ===='
sudo ls /www/server/panel/vhost/nginx 2>/dev/null | head
sudo ls /www/server/nginx/conf/vhost 2>/dev/null | head
ls /etc/nginx/sites-enabled 2>/dev/null
find /www /etc/nginx -name '*nomadro*' 2>/dev/null | head -40
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -1,28 +0,0 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name '*.conf' | sort
echo '---'
F=$(find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name 'nomadro.cn.conf' | head -1)
echo "F=$F"
if [ -n "$F" ]; then
grep -n 'location\|8020\|proxy_pass\|social\|live\|server_name' "$F" | head -80
fi
# also check extension
ls /www/server/panel/vhost/nginx/extension/nomadro.cn 2>/dev/null || true
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -1,27 +0,0 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
sudo ls /www/server/panel/vhost/nginx | grep -i nomad | head -40
echo '===='
sudo grep -Rnl 'server_name nomadro.cn' /www/server/panel/vhost/nginx 2>/dev/null | head
F=$(sudo grep -Rnl 'server_name nomadro.cn;' /www/server/panel/vhost/nginx 2>/dev/null | head -1)
echo F=$F
sudo grep -n 'location\|8020\|proxy_pass\|social\|#LIVE' "$F" | head -100
echo '==== ext ===='
sudo ls "/www/server/panel/vhost/nginx/extension/nomadro.cn" 2>/dev/null || true
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -1,26 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
sudo sed -n '1,220p' "$CONF"
echo '===== WS LOC ====='
sudo grep -n 'config/ws\|Upgrade\|location ' "$CONF" | head -80
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -1,89 +0,0 @@
# -*- coding: utf-8 -*-
"""Patch api.nomadro.cn 443 block for /api/config/ws Upgrade."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
PATCHER = r'''
from pathlib import Path
import shutil
p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
text = p.read_text(encoding="utf-8")
marker = "location /api/config/ws"
parts = text.split("listen 443")
if len(parts) < 2:
raise SystemExit("no 443 block")
if marker in parts[1]:
print("ssl_ws_already")
raise SystemExit(0)
lines = [
"",
" location /api/config/ws {",
" proxy_pass http://127.0.0.1:8010;",
" proxy_http_version 1.1;",
" proxy_set_header Upgrade $http_upgrade;",
' proxy_set_header Connection "upgrade";',
" proxy_set_header Host $host;",
" proxy_set_header X-Real-IP $remote_addr;",
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
" proxy_set_header X-Forwarded-Proto $scheme;",
" proxy_read_timeout 3600s;",
" proxy_send_timeout 3600s;",
" proxy_buffering off;",
" }",
" location /api/ebook/config/ws {",
" proxy_pass http://127.0.0.1:8010;",
" proxy_http_version 1.1;",
" proxy_set_header Upgrade $http_upgrade;",
' proxy_set_header Connection "upgrade";',
" proxy_set_header Host $host;",
" proxy_set_header X-Real-IP $remote_addr;",
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
" proxy_set_header X-Forwarded-Proto $scheme;",
" proxy_read_timeout 3600s;",
" proxy_send_timeout 3600s;",
" proxy_buffering off;",
" }",
"",
]
snippet = "\n".join(lines)
ssl = parts[1]
idx = ssl.find("location / {")
if idx < 0:
raise SystemExit("no location / in 443")
ssl2 = ssl[:idx] + snippet + "\n" + ssl[idx:]
out = parts[0] + "listen 443" + ssl2
shutil.copy2(p, str(p) + ".bak-ws-ssl")
p.write_text(out, encoding="utf-8")
print("ssl_ws_patched")
'''
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/patch_ws_ssl.py", "w") as rf:
rf.write(PATCHER)
sftp.close()
cmd = "sudo python3 /tmp/patch_ws_ssl.py && sudo nginx -t && sudo nginx -s reload && rm -f /tmp/patch_ws_ssl.py && echo DONE"
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

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,137 +0,0 @@
# -*- coding: utf-8 -*-
"""Deploy vip_content.py + patch remote-config: Youtube运营笔记 → books/default."""
from __future__ import annotations
import json
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/services/vip_content.py"
YT = {
"id": "youtube-notes",
"title": "Youtube运营笔记",
"desc": "试读可进,单买或 VIP 解锁全文",
"ebookId": "default",
"href": "/pages/reader/index?id=default",
"free": False,
"enabled": True,
"sort": 1,
}
def to_app_pkg(src: Path) -> bytes:
return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
def main() -> int:
data = to_app_pkg(SRC)
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_content_yt.py", "wb") as rf:
rf.write(data)
print("up vip_content", len(data), flush=True)
sftp.close()
patch_json = json.dumps(YT, ensure_ascii=False)
cmd = r"""
set -e
B=/opt/nomadmini/backend/app
sudo cp /tmp/vip_content_yt.py "$B/services/vip_content.py"
# patch remote-config ebooks
python3 <<'PY'
import json
from pathlib import Path
paths = [
Path("/var/www/nomadro.cn/data/remote-config.json"),
Path("/opt/nomadmini/backend/data/remote-config.json"),
]
yt = {
"id": "youtube-notes",
"title": "Youtube运营笔记",
"desc": "试读可进,单买或 VIP 解锁全文",
"ebookId": "default",
"href": "/pages/reader/index?id=default",
"free": False,
"enabled": True,
"sort": 1,
}
for p in paths:
if not p.is_file():
print("skip missing", p)
continue
raw = json.loads(p.read_text(encoding="utf-8"))
platforms = raw.setdefault("platforms", {})
weapp = platforms.setdefault("weapp", {})
vc = weapp.setdefault("vipContent", {})
ebooks = list(vc.get("ebooks") or [])
hit = -1
for i, e in enumerate(ebooks):
if not isinstance(e, dict):
continue
t = str(e.get("title") or "")
if (
e.get("id") == "youtube-notes"
or e.get("ebookId") == "default"
or "youtube" in t.lower()
or "运营笔记" in t
):
hit = i
break
if hit >= 0:
prev = ebooks[hit]
ebooks[hit] = {**yt, "title": prev.get("title") or yt["title"], "desc": prev.get("desc") or yt["desc"], "enabled": prev.get("enabled") is not False, "sort": prev.get("sort", 1)}
else:
idx = next((i for i, e in enumerate(ebooks) if isinstance(e, dict) and (e.get("id") == "1" or e.get("title") == "数字游民")), -1)
if idx >= 0:
ebooks.insert(idx + 1, dict(yt))
else:
ebooks.append(dict(yt))
# fix cloudphone sort if needed
for e in ebooks:
if isinstance(e, dict) and e.get("id") == "2" and e.get("sort") in (None, 1):
e["sort"] = 2
vc["ebooks"] = ebooks
stats = dict(vc.get("stats") or {})
stats["ebooks"] = "3"
vc["stats"] = stats
weapp["vipContent"] = vc
platforms["weapp"] = weapp
raw["platforms"] = platforms
raw["updatedAt"] = raw.get("updatedAt") or ""
bak = p.with_suffix(p.suffix + ".bak-yt")
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
p.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
print("patched", p, "ebooks=", [e.get("id") for e in ebooks if isinstance(e, dict)])
PY
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.services import vip_content as v; d=v.default_vip_content(); ids=[e["id"] for e in d["ebooks"]]; assert "youtube-notes" in ids; print("default_ok", ids)'
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk https://api.nomadro.cn/api/config | python3 -c 'import sys,json; d=json.load(sys.stdin); e=((d.get("config") or {}).get("platforms") or {}).get("weapp",{}).get("vipContent",{}).get("ebooks") or []); print("live_ebooks", [(x.get("id"), x.get("ebookId"), x.get("href")) for x in e])'
rm -f /tmp/vip_content_yt.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

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,90 +0,0 @@
# -*- coding: utf-8 -*-
"""Add /live/ FLV proxy next to social-api extension for www.nomadro.cn."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT_DIR=/www/server/panel/vhost/nginx/extension/www.nomadro.cn
sudo mkdir -p "$EXT_DIR"
echo '--- existing ---'
sudo ls -la "$EXT_DIR"
sudo cat "$EXT_DIR/social-api.conf" 2>/dev/null | head -40 || true
# write live-flv.conf
sudo tee "$EXT_DIR/live-flv.conf" >/dev/null <<'EOF'
# Nomadro social native live — SRS HTTP-FLV for WeChat LivePlayer
location /live/ {
proxy_pass http://127.0.0.1:1985/live/;
proxy_http_version 1.1;
proxy_set_header Connection "";
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_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-cache always;
}
EOF
# also ensure www.nomadro.cn.conf exists and includes extension (baota usually does)
F=/www/server/panel/vhost/nginx/www.nomadro.cn.conf
if sudo test -f "$F"; then
echo "www conf exists"
sudo grep -n 'extension\|include\|server_name' "$F" | head -30
else
echo "www conf missing?"
sudo ls /www/server/panel/vhost/nginx | grep -i www || true
fi
sudo nginx -t
sudo systemctl reload nginx
echo '--- verify ---'
curl -sk -o /dev/null -w 'flv_public %{http_code}\n' 'https://nomadro.cn/live/smoke_smoke_peer_1.flv' || true
curl -sk -o /dev/null -w 'www_flv %{http_code}\n' 'https://www.nomadro.cn/live/smoke_smoke_peer_1.flv' || true
curl -sk -o /dev/null -w 'srs_local %{http_code}\n' 'http://127.0.0.1:1985/api/v1/versions' || true
curl -sk 'http://127.0.0.1:1985/api/v1/versions' | head -c 200; echo
curl -sk -X POST 'https://nomadro.cn/api/social/v1/live/rooms/demo/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: demo_a' \
-d '{"nick":"A"}' | head -c 350; echo
sudo docker ps --filter name=nomadro-srs --format '{{.Names}} {{.Status}} {{.Ports}}'
systemctl is-active nomadro-social
"""
_, 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,93 +0,0 @@
# -*- coding: utf-8 -*-
"""Proxy Centrifugo /rt/ on api.nomadro.cn for weapp socket合法域名."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
# also push latest social api router
from pathlib import Path
repo = Path(__file__).resolve().parents[3]
sftp = c.open_sftp()
for rel, remote in (
("apps/api/services/social_svc/routers/api.py", "/tmp/social_routers_api.py"),
):
data = (repo / rel).read_bytes()
with sftp.file(remote, "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
EXT=/www/server/panel/vhost/nginx/extension/api.nomadro.cn
sudo mkdir -p "$EXT"
# copy www centrifugo snippet if exists, else write
if sudo test -f /www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf; then
sudo cp /www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf "$EXT/centrifugo-rt.conf"
else
sudo tee "$EXT/centrifugo-rt.conf" >/dev/null <<'EOF'
location ^~ /rt/ {
proxy_pass http://127.0.0.1:8008/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
EOF
fi
# ensure social-api still there
sudo test -f "$EXT/social-api.conf" || true
sudo nginx -t
sudo systemctl reload nginx
sudo cp /tmp/social_routers_api.py /var/www/nomadro.cn/apps/api/services/social_svc/routers/api.py
sudo systemctl restart nomadro-social
sleep 2
echo '=== token ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/realtime/token?channel_id=general&guest=chat1' | head -c 280; echo
echo '=== list ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' | head -c 200; echo
echo '=== post ==='
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' \
-H 'Content-Type: application/json' --data-binary '{"author":"系统","text":"Centrifugo 聊天通路已接通"}' | head -c 240; echo
echo '=== list2 ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' | head -c 400; echo
systemctl is-active centrifugo nomadro-social
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,95 +0,0 @@
# -*- coding: utf-8 -*-
"""Proxy /api/social/ on api.nomadro.cn → nomadro-social:8020 (weapp whitelist)."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT_DIR=/www/server/panel/vhost/nginx/extension/api.nomadro.cn
sudo mkdir -p "$EXT_DIR"
sudo tee "$EXT_DIR/social-api.conf" >/dev/null <<'EOF'
# weapp 合法域名多为 api.nomadro.cn — 社交 live/join 必须可直连
location ^~ /api/social/ {
proxy_pass http://127.0.0.1:8020;
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_set_header X-Social-Guest-Id $http_x_social_guest_id;
}
EOF
# ensure api conf includes extension/*.conf
F=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
sudo grep -n 'extension/api.nomadro.cn\|include' "$F" | head -20
if ! sudo grep -q 'extension/api.nomadro.cn/\*\.conf' "$F"; then
# inject include after server_name line in https server
sudo python3 - <<'PY'
from pathlib import Path
p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
text = p.read_text(encoding="utf-8")
inc = " include /www/server/panel/vhost/nginx/extension/api.nomadro.cn/*.conf;\n"
if "extension/api.nomadro.cn" in text:
print("include already")
else:
# after first ssl server_name api.nomadro.cn;
needle = "server_name api.nomadro.cn;"
# prefer the ssl block (second occurrence often); insert after both
parts = text.split(needle)
if len(parts) < 2:
raise SystemExit("no server_name")
out = parts[0]
for i, part in enumerate(parts[1:], 1):
out += needle
if "extension/api.nomadro.cn" not in part[:200]:
out += "\n" + inc
out += part
p.write_text(out, encoding="utf-8")
print("include injected")
PY
fi
sudo nginx -t
sudo systemctl reload nginx
echo '=== api social health ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/health' | head -c 300; echo
echo '=== api live join ==='
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join' \
-H 'Content-Type: application/json' \
-H 'X-Social-Guest-Id: weapp_real_1' \
--data-binary '{"nick":"真机"}' | head -c 400; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,257 +0,0 @@
# -*- coding: utf-8 -*-
"""Deploy admin SPA + CRUD APIs (stats series, social ugc, community, memo/books/orders).
- Never wipe catalogs unless catalog PUT is called by operator
- Snapshot /api/config version before/after
- Set SOCIAL_DB_PATH + fix social.db perms for www
"""
from __future__ import annotations
import io
import json
import subprocess
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
ADMIN = REPO / "apps/admin"
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def snapshot() -> dict:
req = urllib.request.Request(
"https://api.nomadro.cn/api/config",
headers={"User-Agent": "nomadro-admin-crud-deploy"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
data = json.loads(resp.read().decode("utf-8"))
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
return {
"version": cfg.get("version"),
"social": mods.get("social"),
"source": data.get("source"),
}
def build_admin() -> None:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
raise SystemExit(r.returncode)
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in API_FILES:
src = REPO / rel
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc" in text and dest != "main.py":
# main may mention ebook only in comments; services must be clean
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name="api/" + dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
dist = ADMIN / "dist"
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
buf.seek(0)
blob = buf.read()
print("pack", len(blob), flush=True)
return blob
def main() -> int:
before = snapshot()
print("BEFORE", before, flush=True)
build_admin()
blob = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin-crud.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf admin-crud && mkdir admin-crud
tar -xzf admin-crud.tar.gz -C admin-crud
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
echo B=$B
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
for f in \
services/store.py \
services/social_ugc.py \
services/memo_store.py \
services/shop_store.py \
schemas/admin.py \
routers/admin.py \
routers/social_ugc_admin.py \
routers/community_admin.py \
routers/memo_admin.py \
routers/shop_admin.py
do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "admin-crud/api/$f" "$B/$f"
done
# Patch main.py to include new routers (idempotent)
python3 - <<'PY'
from pathlib import Path
p = Path("/opt/nomadmini/backend/app/main.py")
text = p.read_text(encoding="utf-8")
changed = False
if "social_ugc_admin" not in text:
needle = "from app.routers import social_ops_admin"
if needle in text:
text = text.replace(
needle,
needle
+ "\nfrom app.routers import social_ugc_admin # noqa: E402\nfrom app.routers import community_admin # noqa: E402",
1,
)
changed = True
if "include_router(social_ugc_admin.router)" not in text:
needle2 = "include_router(social_ops_admin.router)"
if needle2 in text:
text = text.replace(
needle2,
needle2
+ "\napp.include_router(social_ugc_admin.router)\napp.include_router(community_admin.router)",
1,
)
changed = True
if changed:
p.write_text(text, encoding="utf-8")
print("patched_main")
else:
print("main_ok")
PY
# social db perms + env for nomadmini-api
sudo mkdir -p /var/www/nomadro-data/social /var/www/nomadro-data/community
if [ -f /var/www/nomadro-data/social/social.db ]; then
sudo chown www:www /var/www/nomadro-data/social/social.db || true
sudo chmod 664 /var/www/nomadro-data/social/social.db || true
sudo chown www:www /var/www/nomadro-data/social || true
fi
sudo mkdir -p /etc/systemd/system/nomadmini-api.service.d
sudo tee /etc/systemd/system/nomadmini-api.service.d/social-db.conf >/dev/null <<'EOF'
[Service]
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json
EOF
sudo systemctl daemon-reload
sudo rsync -a --delete /tmp/admin-crud/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_synced
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
AUTH="Authorization: Bearer $TOK"
echo -n 'stats '
curl -sk -o /tmp/st.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
python3 - <<'PY'
import json
d=json.load(open('/tmp/st.json',encoding='utf-8'))
assert 'series' in d, d
print('series_ok', len(d['series'].get('revenue',[])), 'top', len(d.get('topEvents') or []))
PY
echo -n 'social_ugc '
curl -sk -o /tmp/su.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/social/ugc/overview
python3 - <<'PY'
import json
d=json.load(open('/tmp/su.json',encoding='utf-8'))
print('ugc', d.get('exists'), d.get('writable'), d.get('counts'))
PY
echo -n 'community '
curl -sk -o /tmp/co.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/community/overview
for u in /wechat /wechat/social/data /wechat/community /wechat/books; do
curl -sk -o /dev/null -w "admin$u %{http_code}\n" "https://admin.nomadro.cn$u"
done
curl -sk https://api.nomadro.cn/api/config -o /tmp/cfg-after.json
python3 - <<'PY'
import json
d=json.load(open('/tmp/cfg-after.json',encoding='utf-8'))
social=d.get('config',{}).get('modules',{}).get('social')
print('live_social', social)
assert isinstance(social, dict) and social.get('enabled') is True
print('config_ok')
PY
rm -rf /tmp/admin-crud /tmp/admin-crud.tar.gz /tmp/st.json /tmp/su.json /tmp/co.json /tmp/cfg-after.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
after = snapshot()
print("AFTER", after, flush=True)
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
print("FAIL config drifted", flush=True)
return 3
print(f"[exit {code}] admin CRUD deployed; version {after.get('version')}", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,229 +0,0 @@
# -*- coding: utf-8 -*-
"""Deploy pending ebook API backend only (no admin SPA).
- Rewrite ebook_svc.* → app.*
- Hot-copy into /opt/nomadmini/backend/app
- Restart nomadmini-api only
- Snapshot /api/config version before/after (must not drift)
"""
from __future__ import annotations
import io
import json
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
("apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
("apps/api/services/ebook_svc/services/social_ops.py", "services/social_ops.py"),
(
"apps/api/services/ebook_svc/services/public_config_snapshot.py",
"services/public_config_snapshot.py",
),
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
("apps/api/services/ebook_svc/routers/social_ops_admin.py", "routers/social_ops_admin.py"),
("apps/api/services/ebook_svc/routers/public_config.py", "routers/public_config.py"),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def snapshot() -> dict:
req = urllib.request.Request(
"https://api.nomadro.cn/api/config",
headers={"User-Agent": "nomadro-api-backend-deploy"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
data = json.loads(resp.read().decode("utf-8"))
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
return {
"version": cfg.get("version"),
"social": mods.get("social"),
"book": mods.get("book"),
"source": data.get("source"),
}
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in API_FILES:
src = REPO / rel
if not src.is_file():
raise SystemExit(f"missing {rel}")
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name="api/" + dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
buf.seek(0)
blob = buf.read()
print("pack", len(blob), "files", len(API_FILES), flush=True)
return blob
def main() -> int:
before = snapshot()
print("BEFORE", before, flush=True)
blob = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/api-backend.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf api-backend && mkdir api-backend
tar -xzf api-backend.tar.gz -C api-backend
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
echo B=$B
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
for f in \
services/store.py \
services/memo_store.py \
services/shop_store.py \
services/weapp_switches.py \
services/social_ugc.py \
services/social_ops.py \
services/public_config_snapshot.py \
schemas/admin.py \
routers/admin.py \
routers/memo_admin.py \
routers/shop_admin.py \
routers/social_ugc_admin.py \
routers/community_admin.py \
routers/social_ops_admin.py \
routers/public_config.py
do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "api-backend/api/$f" "$B/$f"
echo copied $f
done
# Ensure main.py registers new admin routers (idempotent)
python3 - <<'PY'
from pathlib import Path
candidates = [
Path("/opt/nomadmini/backend/app/main.py"),
]
for p in candidates:
if not p.is_file():
continue
text = p.read_text(encoding="utf-8")
changed = False
imports = [
("social_ops_admin", "from app.routers import social_ops_admin # noqa: E402"),
("social_ugc_admin", "from app.routers import social_ugc_admin # noqa: E402"),
("community_admin", "from app.routers import community_admin # noqa: E402"),
]
for key, line in imports:
if key not in text:
# append near other router imports
anchor = "from app.routers import"
idx = text.rfind(anchor)
if idx >= 0:
end = text.find("\n", idx)
text = text[: end + 1] + line + "\n" + text[end + 1 :]
changed = True
else:
text = line + "\n" + text
changed = True
includes = [
("social_ops_admin.router", "app.include_router(social_ops_admin.router)"),
("social_ugc_admin.router", "app.include_router(social_ugc_admin.router)"),
("community_admin.router", "app.include_router(community_admin.router)"),
]
for key, line in includes:
if key not in text:
# after last include_router
needle = "app.include_router("
idx = text.rfind(needle)
if idx >= 0:
end = text.find("\n", idx)
text = text[: end + 1] + line + "\n" + text[end + 1 :]
changed = True
if changed:
p.write_text(text, encoding="utf-8")
print("patched_main", p)
else:
print("main_ok", p)
PY
cd "$API_ROOT"
if [ -x .venv/bin/python ]; then
.venv/bin/python - <<'PY'
from app.services.weapp_switches import read_weapp_switches
from app.services import public_config_snapshot
print("import_ok", read_weapp_switches().get("bookAudit"))
print("snapshot_cls", public_config_snapshot.PublicConfigSnapshot)
PY
fi
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
echo token_len=${#TOK}
AUTH="Authorization: Bearer $TOK"
curl -sk -o /dev/null -w "switches %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/weapp/switches
curl -sk -o /dev/null -w "stats %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
rm -rf /tmp/api-backend /tmp/api-backend.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
after = snapshot()
print("AFTER", after, flush=True)
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
print("FAIL config drifted", flush=True)
return 3
print(f"[exit {code}] api backend deployed; version {after.get('version')}", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,48 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/routers/public_config.py"
def main() -> int:
text = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.")
if "ebook_svc." in text:
raise SystemExit("rewrite failed")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/public_config.py", "w") as rf:
rf.write(text)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/public_config.py /opt/nomadmini/backend/app/routers/public_config.py
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk -X POST https://api.nomadro.cn/api/config/pull -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);c=d['config'];print('POST_PULL',c.get('version'),c.get('modules',{}).get('nav'))"
curl -sk -X POST https://api.nomadro.cn/api/config -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);print('POST_CFG',d['config'].get('version'))"
rm -f /tmp/public_config.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,164 +0,0 @@
# -*- coding: utf-8 -*-
"""Deploy config SSE/WebSocket realtime to api.nomadro.cn (nomadmini-api)."""
from __future__ import annotations
import io
import json
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
"apps/api/services/ebook_svc/services/config_live.py",
"services/config_live.py",
),
(
"apps/api/services/ebook_svc/routers/public_config.py",
"routers/public_config.py",
),
(
"apps/api/services/ebook_svc/services/weapp_switches.py",
"services/weapp_switches.py",
),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> int:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in FILES:
src = REPO / rel
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name=dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
blob = buf.getvalue()
print("pack", len(blob), flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/config-rt.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf config-rt && mkdir config-rt
tar -xzf config-rt.tar.gz -C config-rt
B=/opt/nomadmini/backend/app
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers"
for f in services/config_live.py routers/public_config.py services/weapp_switches.py; do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "config-rt/$f" "$B/$f"
echo copied $f
done
# nginx websocket:写到 /tmp 再 sudo 覆盖
sudo python3 - <<'PY'
from pathlib import Path
import shutil
src = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
if not src.is_file():
print("nginx_ws_skip_no_conf")
raise SystemExit(0)
text = src.read_text(encoding="utf-8")
if "location /api/config/ws" in text:
print("nginx_ws_ok")
raise SystemExit(0)
upstream = "http://127.0.0.1:8000"
for line in text.splitlines():
s = line.strip()
if s.startswith("proxy_pass ") and "127.0.0.1" in s:
upstream = s.split("proxy_pass", 1)[1].strip().rstrip(";")
break
snippet = (
"\n location /api/config/ws {\n"
f" proxy_pass {upstream};\n"
" proxy_http_version 1.1;\n"
" proxy_set_header Upgrade $http_upgrade;\n"
' proxy_set_header Connection "upgrade";\n'
" proxy_set_header Host $host;\n"
" proxy_set_header X-Real-IP $remote_addr;\n"
" proxy_read_timeout 3600s;\n"
" proxy_send_timeout 3600s;\n"
" }\n"
" location /api/ebook/config/ws {\n"
f" proxy_pass {upstream};\n"
" proxy_http_version 1.1;\n"
" proxy_set_header Upgrade $http_upgrade;\n"
' proxy_set_header Connection "upgrade";\n'
" proxy_set_header Host $host;\n"
" proxy_set_header X-Real-IP $remote_addr;\n"
" proxy_read_timeout 3600s;\n"
" proxy_send_timeout 3600s;\n"
" }\n"
)
idx = text.find("location /")
if idx < 0:
idx = text.rfind("}")
if idx <= 0:
print("nginx_ws_skip")
raise SystemExit(0)
out = text[:idx] + snippet + "\n" + text[idx:]
bak = src.with_suffix(src.suffix + ".bak-config-ws")
shutil.copy2(src, bak)
src.write_text(out, encoding="utf-8")
print("nginx_ws_patched", upstream)
PY
sudo nginx -t && sudo nginx -s reload || true
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.services import config_live
from app.routers import public_config
print("import_ok", config_live.read_config_meta())
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
# SSE hello (2s)
timeout 3 curl -sk -N -H 'Accept: text/event-stream' https://api.nomadro.cn/api/config/stream | head -c 400 || true
echo
rm -rf /tmp/config-rt /tmp/config-rt.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
# local meta check
meta = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config/meta", timeout=15).read())
print("META", meta, flush=True)
print(f"[exit {code}] config realtime deployed", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,98 +0,0 @@
# -*- coding: utf-8 -*-
"""Push social-join virtual pay routes to production (/opt/nomadmini)."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def to_app_pkg(src: Path) -> bytes:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
assert b"ebook_svc" not in data, f"rewrite failed: {src}"
return data
def main() -> int:
pairs = [
(
REPO / "apps/api/services/ebook_svc/core/rate_limit.py",
"/tmp/rate_limit_app.py",
"/opt/nomadmini/backend/app/core/rate_limit.py",
),
(
REPO / "apps/api/services/ebook_svc/services/social_join_config.py",
"/tmp/social_join_config_app.py",
"/opt/nomadmini/backend/app/services/social_join_config.py",
),
(
REPO / "apps/api/services/ebook_svc/routers/pay.py",
"/tmp/pay_app.py",
"/opt/nomadmini/backend/app/routers/pay.py",
),
]
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
for src, tmp, _final in pairs:
data = to_app_pkg(src)
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("up", tmp, len(data), flush=True)
sftp.close()
cmd = r"""
set -e
B=/opt/nomadmini/backend/app
sudo cp /tmp/rate_limit_app.py "$B/core/rate_limit.py"
sudo cp /tmp/social_join_config_app.py "$B/services/social_join_config.py"
sudo cp /tmp/pay_app.py "$B/routers/pay.py"
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.core.rate_limit import rate_limit
from app.services.social_join_config import SOCIAL_JOIN_BOOK_ID, read_social_join_config
from app.routers import pay
print(
"import_ok",
SOCIAL_JOIN_BOOK_ID,
hasattr(pay, "create_social_join_order"),
callable(rate_limit),
read_social_join_config().get("socialJoinEnabled"),
)
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health || true
# 未登录应 401,不应再 404
curl -sk -o /dev/null -w "sj-status %{http_code}\n" https://api.nomadro.cn/api/pay/social-join-status || true
curl -sk -o /dev/null -w "sj-ebook %{http_code}\n" https://api.nomadro.cn/api/ebook/pay/social-join-status || true
rm -f /tmp/rate_limit_app.py /tmp/social_join_config_app.py /tmp/pay_app.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,56 +0,0 @@
# -*- coding: utf-8 -*-
"""Push social live API router + smoke join via api.nomadro.cn."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
local = REPO / "apps/api/services/social_svc/routers/api.py"
with sftp.file("/tmp/social_routers_api.py", "wb") as rf:
rf.write(local.read_bytes())
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/social_routers_api.py /var/www/nomadro.cn/apps/api/services/social_svc/routers/api.py
sudo systemctl restart nomadro-social
sleep 2
systemctl is-active nomadro-social
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join?guest=weapp_real_2' \
-H 'Content-Type: application/json' \
--data-binary '{"nick":"真机"}' | head -c 420; echo
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/health'; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, 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,55 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
for rel in ("live.py", "routers/api.py"):
local = REPO / "apps/api/services/social_svc" / rel
remote = f"/tmp/social_{rel.replace('/', '_')}"
with sftp.file(remote, "wb") as rf:
rf.write(local.read_bytes())
print("up", remote, flush=True)
sftp.close()
cmd = r"""
set -e
B=/var/www/nomadro.cn/apps/api/services/social_svc
sudo cp /tmp/social_live.py "$B/live.py"
sudo cp /tmp/social_routers_api.py "$B/routers/api.py"
sudo systemctl restart nomadro-social
sleep 2
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join?guest=camtest1' \
-H 'Content-Type: application/json' --data-binary '{"nick":"cam"}' | head -c 360; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, 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)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
"""Deploy weapp switches API + admin SPA."""
from __future__ import annotations
import subprocess
import tarfile
import time
from io import BytesIO
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[1]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
(REPO / "apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
(REPO / "apps/api/services/ebook_svc/routers/weapp_switches_admin.py", "routers/weapp_switches_admin.py"),
(REPO / "apps/api/services/ebook_svc/services/store.py", "services/store.py"),
(REPO / "apps/api/services/ebook_svc/main.py", "main.py"),
]
def to_app(src: Path) -> bytes:
return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
def main() -> int:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
return r.returncode
dist = ROOT / "dist"
buf = BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for src, rel in API_FILES:
data = to_app(src)
info = tarfile.TarInfo(name="api/" + rel.replace("/", "__"))
info.size = len(data)
tar.addfile(info, BytesIO(data))
buf.seek(0)
print("pack", buf.getbuffer().nbytes, flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/weapp-switches.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf sw-unpack && mkdir sw-unpack
tar -xzf weapp-switches.tar.gz -C sw-unpack
sudo rsync -a --delete sw-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
B=/opt/nomadmini/backend/app
sudo mkdir -p "$B/services" "$B/routers"
sudo cp sw-unpack/api/services__weapp_switches.py "$B/services/weapp_switches.py"
sudo cp sw-unpack/api/routers__weapp_switches_admin.py "$B/routers/weapp_switches_admin.py"
sudo cp sw-unpack/api/services__store.py "$B/services/store.py"
sudo cp sw-unpack/api/main.py "$B/../main.py" 2>/dev/null || sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
# main may live as app package entry
if [ -f /opt/nomadmini/backend/app/main.py ]; then
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/app/main.py
elif [ -f /opt/nomadmini/backend/main.py ]; then
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
fi
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.services.weapp_switches import read_weapp_switches
from app.routers import weapp_switches_admin
from app.services.store import store
assert hasattr(store, "ensure_book")
print("ok", "switches", list(read_weapp_switches().get("modules", {}).keys())[:3])
PY
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/switches
curl -sk -o /dev/null -w "api %{http_code}\n" https://api.nomadro.cn/health
rm -rf sw-unpack weapp-switches.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,46 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/services/weapp_switches.py"
def main() -> int:
data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/weapp_switches.py", "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/weapp_switches.py /opt/nomadmini/backend/app/services/weapp_switches.py
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.services.weapp_switches import read_weapp_switches; print("ok", read_weapp_switches()["bookAudit"])'
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
rm -f /tmp/weapp_switches.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,116 +0,0 @@
# -*- coding: utf-8 -*-
"""Write WeChat-safe digital-nomad audit booklet into prod DB."""
from __future__ import annotations
import json
import re
import time
from pathlib import Path
import paramiko
HERE = Path(__file__).resolve().parent
MD = (HERE / "audit_book_seed.md").read_text(encoding="utf-8")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def split_markdown_chapters(md: str) -> list[dict]:
text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip()
if not text:
return []
parts = re.split(r"(?m)^(#{1} .+)$", text)
chapters: list[dict] = []
preamble = (parts[0] or "").strip()
order = 1
if preamble and len(parts) == 1:
return [{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}]
if preamble:
chapters.append({"id": "c0", "title": "前言", "order": order, "content": preamble + "\n"})
order += 1
i = 1
while i < len(parts):
heading = parts[i].strip()
body = parts[i + 1] if i + 1 < len(parts) else ""
title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章"
content = f"{heading}\n{body}".strip() + "\n"
chapters.append({"id": f"c{order}", "title": title, "order": order, "content": content})
order += 1
i += 2
return chapters
def main() -> int:
chapters = split_markdown_chapters(MD)
assert chapters, "no chapters"
payload = {
"title": "数字游民入门指南",
"subtitle": "远程办公 · 自律生活 · 稳健成长",
"description": "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。",
"chapters": chapters,
}
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/audit_book_seed.json", "wb") as rf:
rf.write(raw)
sftp.close()
cmd = r"""
set -e
python3 <<'PY'
import json, sqlite3, time
data=json.load(open('/tmp/audit_book_seed.json',encoding='utf-8'))
chapters=data['chapters']
con=sqlite3.connect('/opt/nomadmini/data/nomadmini.db')
now=time.time()
row=con.execute("select id from books where id='audit'").fetchone()
meta=(
data['title'], data['subtitle'], '', '📗', data['description'],
json.dumps(['数字游民','远程办公','生活方式'], ensure_ascii=False),
0, '', 100, 5.0, json.dumps(chapters, ensure_ascii=False), now,
)
if row:
con.execute(
'UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?,'
' price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=?',
meta + ('audit',),
)
else:
con.execute(
'INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,'
'price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) '
"VALUES ('audit',?,?,?,?,?,?,?,?,?,?,?,?)",
meta,
)
con.commit()
print('chapters', len(chapters))
print('titles', [c['title'] for c in chapters])
print('words', sum(len(c.get('content') or '') for c in chapters))
PY
curl -sk -o /tmp/audit_check.json -w "audit %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit
python3 <<'PY'
import json
d=json.load(open('/tmp/audit_check.json',encoding='utf-8'))
print('api', d.get('title'), d.get('chapter_count'), d.get('is_free'))
print('toc', [c.get('title') for c in (d.get('chapters') or [])])
PY
rm -f /tmp/audit_book_seed.json /tmp/audit_check.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,57 +0,0 @@
# -*- coding: utf-8 -*-
"""Publish a short test stream to SRS and confirm HTTPS FLV proxy responds."""
from __future__ import annotations
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
# ffmpeg available?
which ffmpeg || sudo apt-get install -y -qq ffmpeg >/tmp/ffinstall.log 2>&1 || true
which ffmpeg
# publish 8s color bars in background
nohup ffmpeg -re -f lavfi -i color=c=black:s=320x240:d=12 -f lavfi -i sine=f=440:d=12 \
-c:v libx264 -tune zerolatency -preset ultrafast -pix_fmt yuv420p -g 30 \
-c:a aac -f flv rtmp://127.0.0.1/live/smoke_test \
>/tmp/ff_push.log 2>&1 &
FFPID=$!
echo "ffmpeg pid $FFPID"
sleep 3
echo '=== local flv code ==='
curl -s --max-time 4 -o /tmp/chunk.flv -w 'local %{http_code} size %{size_download}\n' \
'http://127.0.0.1:1985/live/smoke_test.flv' || true
file /tmp/chunk.flv 2>/dev/null || ls -la /tmp/chunk.flv
echo '=== public flv code ==='
curl -sk --max-time 4 -o /tmp/chunk2.flv -D /tmp/chunk2.hdr -w 'public %{http_code} size %{size_download}\n' \
'https://nomadro.cn/live/smoke_test.flv' || true
head -20 /tmp/chunk2.hdr || true
ls -la /tmp/chunk2.flv || true
kill $FFPID 2>/dev/null || true
sleep 1
tail -5 /tmp/ff_push.log || true
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()

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,26 +0,0 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
# GET with max-time; print status + key headers
curl -sk --max-time 3 -D - -o /dev/null 'https://nomadro.cn/live/nope.flv' | head -25 || true
echo '----'
curl -s --max-time 3 -D - -o /dev/null 'http://127.0.0.1:1985/live/nope.flv' | head -20 || true
echo '---- ext file ----'
sudo cat /www/server/panel/vhost/nginx/extension/www.nomadro.cn/live-flv.conf
echo '---- rtmp port ----'
ss -lntp | grep 1935 || true
"""
_, o, _ = c.exec_command(cmd, timeout=40, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

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

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