Compare commits
No commits in common. "2026-11-10" and "main" have entirely different histories.
2026-11-10
...
main
@ -1,48 +0,0 @@
|
||||
---
|
||||
description: 中文/国际受众模块化 — 支付登录关注文案VIP埋点等全进模块
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 受众模块化(强制)
|
||||
|
||||
## SoT
|
||||
|
||||
`src/modules/audience/`
|
||||
|
||||
| 路径 | 职责 |
|
||||
|------|------|
|
||||
| `detect.ts` | 微信 UA + is-china-user 识别 |
|
||||
| `cn/` | 中文用户:支付/登录/关注/文案/VIP/埋点/社群 |
|
||||
| `intl/` | 国际用户(.com 默认):同上全套 |
|
||||
| `resolve.ts` | `resolveAudienceBundle()` 合并远程 `audience.*` |
|
||||
| `index.ts` | **唯一公共面** |
|
||||
|
||||
## 产品姿态
|
||||
|
||||
- **intl**:`.com` 默认(英语为主 + 多语言 UI)
|
||||
- **cn**:必须特殊对待(微信内置 / is-china-user 命中)
|
||||
|
||||
## 开发铁律
|
||||
|
||||
```ts
|
||||
import { resolveAudienceBundle, useAudienceModule } from "~/modules/audience"
|
||||
const { module, lane, profile } = resolveAudienceBundle()
|
||||
// module.pay / .login / .follow / .copy / .vip / .track / .social
|
||||
```
|
||||
|
||||
**禁止**在页面散落 `if (isChina)` / `if (locale === "zh")` 决定支付网关、登录方式、关注渠道、VIP CTA。
|
||||
|
||||
新增能力(支付、登录、关注、文案、VIP、埋点、社群、小册 PDF/加密货币、运营位…)→ **同时改 `cn/` 与 `intl/`**,再经 `AudienceModule` 类型约束。
|
||||
|
||||
小册变现:`module.ebook.showPdfBuy` / `showCryptoSupport` — **仅 intl**;中文用户禁止展示 Download Edition / Buy Now $29 / Coffee·Lunch·Sponsor。
|
||||
|
||||
## 后台
|
||||
|
||||
登录后全屏选模块 → `/cn/*` | `/intl/*`(`admin.nomadro.com`)。
|
||||
|
||||
## 识别
|
||||
|
||||
1. 微信 / 企业微信内置 → cn
|
||||
2. `is-china-user` → cn
|
||||
3. 否则 → intl
|
||||
勿用 UI locale 反推受众轨。
|
||||
@ -1,42 +0,0 @@
|
||||
---
|
||||
description: .com 美国机为开发发版核心;.cn 独立同步;Taro→三端小程序链路
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 核心机与发版顺序(强制)
|
||||
|
||||
## 一句话
|
||||
|
||||
**本仓开发与默认发版核心是 `nomadro.com`(美国 VPS),不是 `.cn`。**
|
||||
|
||||
## 双站关系
|
||||
|
||||
| 站 | 机 | 角色 |
|
||||
|---|---|---|
|
||||
| **`.com`** | 美国 VPS(如 `108.174.50.68`) | **主开发 / 默认部署目标** |
|
||||
| **`.cn`** | 中国机 `82.157.112.245` | 独立生产;**仅在 .com 中文轨测稳后**再同步 |
|
||||
|
||||
- `.com` 内分 **中文用户 / 国际用户**(`src/modules/audience/{cn,intl}`,`resolveAudienceBundle()`)。
|
||||
- `.com` 中文用户体验测好 → 再同步到 `.cn` 与中国服务器。
|
||||
- **`.com` 中文轨与 `.cn` 服务器彼此独立**(库、配置、进程、发版互不顶替)。禁止「只发 82 就当 .com 已上线」。
|
||||
- 用户说「部署上线」且未点名域名 → **默认发 `.com` / 美国机**;发 `.cn` 必须明确说 `.cn` / 中国机 / 82。
|
||||
- **前端另加门禁**:未经本轮明确允许,不能上线前端(见 `no-frontend-deploy-without-ok`);「默认 .com」不等于已获前端许可。
|
||||
|
||||
## 产品复制链(中国三端)
|
||||
|
||||
```
|
||||
.com(Next · 受众 cn/intl)
|
||||
└─ 中文轨测稳 → 同步 .cn(Next · 中国机,独立)
|
||||
└─ Taro H5(apps/miniprogram/h5)对齐 .cn 体验
|
||||
└─ Taro 多端编译 → 微信 / 抖音 / 小红书
|
||||
```
|
||||
|
||||
- **微信小程序**是中国核心;抖音、小红书跟 Taro H5 SoT。
|
||||
- 小程序 **禁止 web-view** 承载业务(见 `no-webview-content.mdc`)。
|
||||
- `.com` 树 `apps/com/*` **无小程序**;小程序只走 `apps/miniprogram/*`。
|
||||
|
||||
## 反模式
|
||||
|
||||
- 默认 `deploy_*_82.py` / 只冒烟 `nomadro.cn` 却对用户说「已上线」
|
||||
- 把 `.cn` 当主站、把 `.com` 当镜像
|
||||
- 用 UI locale 代替受众轨;或假定 `.com` 中文与 `.cn` 共享同一后端
|
||||
@ -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 中声明的分支对齐
|
||||
@ -1,12 +0,0 @@
|
||||
---
|
||||
description: 本地前端默认直连线上 .com 后端(禁止默认 127.0.0.1:802x)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 本地前端直连线上后端(写死)
|
||||
|
||||
**本地前端直连线上后端。**
|
||||
|
||||
- `pnpm dev` / localhost:`WORK_API_URL` / `NOTIFY_API_URL` / `COFFEE_API_URL` / `API_URL` 默认 **`https://nomadro.com`**
|
||||
- 禁止默认 `127.0.0.1:8021/8023/8024`;本机后端仅在用户本轮明确要求联调时使用
|
||||
- 细节见 `.cursor/skills/local-frontend-online-backend/SKILL.md`
|
||||
@ -1,17 +0,0 @@
|
||||
---
|
||||
description: 模块化设计 — 易扩展业务、解耦
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 模块化与解耦
|
||||
|
||||
- **门户业务**:垂直前端进 `src/modules/<name>`,路由在 `src/app/<route>`;禁止把业务堆进 `src/components/` 壳层。
|
||||
- **受众横切**:中文 / 国际进 `src/modules/audience/{cn,intl}`(支付·登录·关注·文案·VIP·埋点·社群等);见 `audience-cn-intl.mdc`。禁止页面散落 `if (isChina)`。
|
||||
- **端形态**:小程序 / 管理 SPA / API 进 `apps/{miniprogram,admin,api}`;**.com(美国 VPS)进 `apps/com/*`,与 `.cn` 源码隔离**;共享进 `packages/*`。
|
||||
- **远程工作**:门户壳 `src/modules/work`;Planka / Etherpad 上游与 overlay 在 `apps/work`(二次开发写 overlay,勿把整个 upstream 硬塞进主仓)。
|
||||
- **稳定公共面**:`@nomadro/pay`、`@nomadro/pb`、`@nomadro/sdk` 经显式导出;模块之间禁止深路径互相 import。
|
||||
- **依赖方向**:`packages` ← `apps` / `src/modules` ← 门户路由;下层不依赖上层;**`apps/com` 禁止依赖 `apps/admin` / 小程序源码**。
|
||||
- **新增业务清单**:`src/modules/<name>` + 可选 `apps/api` 路由前缀 + 门户挂载路径(如 `/xxx`)+ 内容进 `src/modules/*-content`;不改无关模块。**.com Web 能力进 `apps/com`,勿塞进微信/抖音后台。**
|
||||
- **接口优先**:模块对外用 HTTP/OpenAPI 或清晰 TS 类型;配置与密钥走 env。
|
||||
- **可替换**:支付/存储/分析经 provider 接入(见 `@nomadro/pay.resolvePayProvider`)。
|
||||
- **统一编排**:`.cn` 跨垂直入口在 `/admin` 与 `apps/admin`;`.com` 在 `apps/com/admin`(`admin.nomadro.com`);后台壳不承载垂直页面实现。
|
||||
@ -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`。
|
||||
@ -1,13 +0,0 @@
|
||||
---
|
||||
description: 未经允许禁止上线前端(门户/admin/小程序产物)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 未经允许,不能上线前端(写死)
|
||||
|
||||
**未经允许,不能上线前端。**
|
||||
|
||||
- 上传 `.next`、admin `dist`、小程序包,或宣称前端已上线 → 必须本轮用户明确说可以部署/上线前端。
|
||||
- 「继续改 / 修好 / 深度定制 / 只查线上」**不是**许可。
|
||||
- 无许可时只本地改与自测;后端-only 部署可做,但脚本里带前端包则跳过前端或整段停。
|
||||
- 细节见 `.cursor/skills/no-frontend-deploy-without-ok/SKILL.md`。
|
||||
@ -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 以后再说」。
|
||||
@ -1,52 +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) |
|
||||
| 管理后台 .cn | `apps/admin` | admin.nomadro.cn(微信 / 抖音) |
|
||||
| 管理后台 .com | `apps/com/admin` | admin.nomadro.com(美国 VPS · 仅 Web · 无小程序) |
|
||||
| 共享包 | `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.com`(美国 VPS)**;`.cn` 为中国独立站(测稳后同步)
|
||||
- `.cn` 机:`82.157.112.245`,`ubuntu` / `Xiao4669805`;二级 DNS 在 Cloudflare
|
||||
- 发版默认目标与双站关系见 `com-first-deploy.mdc`
|
||||
|
||||
## 开发流程(强制)
|
||||
|
||||
1. Windows 本地改 → `pnpm dev` / 对应后端启动 → 自测 OK
|
||||
2. **默认部署 `.com`(美国机)** → 冒烟 OK;`.cn` 仅明确要求或中文轨同步时再发
|
||||
3. 最后更新 README
|
||||
|
||||
模块化见 `modular-design.mdc`:门户业务在 `src/modules/`,端形态进 `apps/`,共享进 `packages/`。
|
||||
@ -1,24 +0,0 @@
|
||||
---
|
||||
description: 支付网关与多语言约定
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 支付与 i18n
|
||||
|
||||
## 支付分流
|
||||
|
||||
| 场景 | 网关 |
|
||||
|------|------|
|
||||
| 海外 | Creem / NOWPayments |
|
||||
| 国内 PC/H5 浏览器 | zpay |
|
||||
| 国内微信内 H5 | xpay / xorpay(与现网 VIP 一致) |
|
||||
| 微信小程序虚拟支付 | OfferID + AppKey(见 wechat 规则) |
|
||||
|
||||
统一经 FastAPI(`apps/api`)写 PocketBase;前端勿直连商户密钥。
|
||||
|
||||
## 多语言与受众
|
||||
|
||||
- **`.com`**:国际(英语为主)默认;中文用户特殊对待(见 `audience-cn-intl.mdc`)
|
||||
- UI 语言:中文 / 英语;扩展日语、越南语、泰语等小语种
|
||||
- 支付分流跟 **`detectAudience().isChina`**(含微信内置),**不要**跟 UI locale
|
||||
- 门户:`lib/i18n` + `lib/audience` + `is-china-user`;垂直应用对齐,勿再造冲突 locale 键
|
||||
@ -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 才能打开首页
|
||||
@ -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`)
|
||||
@ -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
|
||||
```
|
||||
@ -1,57 +0,0 @@
|
||||
---
|
||||
name: com-local-build-deploy
|
||||
description: >-
|
||||
Deploy nomadro.com (US VPS) by building Next + admin locally, then uploading
|
||||
artifacts. Use ONLY after explicit user permission to 部署/上线 frontend
|
||||
(see no-frontend-deploy-without-ok). Also when remote VPS CPU is too weak
|
||||
for next build. Never rebuild Next on the US server.
|
||||
---
|
||||
|
||||
# .com 本地构建再部署(强制)
|
||||
|
||||
## 许可门禁(先于一切)
|
||||
|
||||
**未经允许,不能上线前端。** 必须本轮用户明确授权前端发版后才能执行本 skill。
|
||||
详见 `.cursor/skills/no-frontend-deploy-without-ok/SKILL.md`。无许可 → 停,勿上传 `.next` / admin dist。
|
||||
|
||||
## 铁律
|
||||
|
||||
**性能不够就本地构建。** 美国机只接收已构建产物,**禁止**在 `108.174.50.68` 上跑 `pnpm exec next build` / `next build`。
|
||||
|
||||
默认发版目标:`nomadro.com`(美国 VPS)。未点名 `.cn` / 82 时不要发中国机。
|
||||
|
||||
## 步骤(按序)
|
||||
|
||||
1. **本地构建(Windows 仓根)**
|
||||
```powershell
|
||||
pnpm build
|
||||
pnpm build:admin-com
|
||||
```
|
||||
确认存在:
|
||||
- `.next/BUILD_ID`
|
||||
- `apps/com/admin/dist/index.html`
|
||||
|
||||
2. **发版脚本**(打包 `.next` + admin dist + API/social 增量源码):
|
||||
```powershell
|
||||
python scripts/deploy_platform_upgrade_com.py
|
||||
```
|
||||
- 目标:门户 `/var/www/nomadro.cn`(机器是美国,路径历史名)、`admin.nomadro.com`、`nomadmini-api`、`nomadro-social`
|
||||
- 带备份与失败回滚
|
||||
|
||||
3. **冒烟**
|
||||
- `https://nomadro.com/`
|
||||
- `https://nomadro.com/social/places`
|
||||
- `https://admin.nomadro.com/`
|
||||
- API health(脚本内已 curl)
|
||||
|
||||
## 反模式
|
||||
|
||||
- SSH 上美国机 `pnpm build` / `next build`(慢、易 OOM、易挂死)
|
||||
- 只改源码不重建本地 `.next` 就上传
|
||||
- 默认 `deploy_*_82.py` 却对用户说「.com 已上线」
|
||||
|
||||
## 相关
|
||||
|
||||
- 双站顺序:`.cursor/rules/com-first-deploy.mdc`
|
||||
- 上传连接:`apps/admin/deploy/_upload_next_us.py`(`connect()`)
|
||||
- 仅门户包:可参考 `_upload_next_us.py`,完整栈仍用 `deploy_platform_upgrade_com.py`
|
||||
@ -1,45 +0,0 @@
|
||||
---
|
||||
name: local-frontend-online-backend
|
||||
description: >-
|
||||
Hard gate: local frontend must talk to online .com backends, not localhost
|
||||
FastAPI by default. Use when configuring WORK_API_URL / COFFEE_API_URL /
|
||||
NOTIFY_API_URL / API_URL, pnpm dev, or fixing「无法连接 work API」on localhost.
|
||||
---
|
||||
|
||||
# 本地前端直连线上后端(写死)
|
||||
|
||||
## 铁律(逐字)
|
||||
|
||||
**本地前端直连线上后端。**
|
||||
|
||||
`pnpm dev` / `localhost:3000` 的业务 API **默认**打 **`https://nomadro.com`**(美国机线上),**禁止**默认假设本机已起 `dev:work-api` / `8021` / `8023` / `8024`。
|
||||
|
||||
## 默认上游
|
||||
|
||||
| 本地 Next 路径 | 环境变量 | 默认值(无 env 时) |
|
||||
|----------------|----------|---------------------|
|
||||
| `/api/work/v1/*` | `WORK_API_URL` | `https://nomadro.com` |
|
||||
| `/api/notify/v1/*` | `NOTIFY_API_URL` | `https://nomadro.com` |
|
||||
| `/api/coffee/v1/*` | `COFFEE_API_URL` | `https://nomadro.com` |
|
||||
| 其它门户业务 | `API_URL` | `https://nomadro.com` |
|
||||
| 远程配置(浏览器) | `NEXT_PUBLIC_REMOTE_CONFIG_URL` | `https://nomadro.com/api/config` |
|
||||
|
||||
代理拼法:`{ORIGIN}/api/work/v1/...` —— **只写站点根**(`https://nomadro.com`),不要写成带 `/api/work/v1` 的完整前缀以免双拼。
|
||||
|
||||
## 反模式(禁止)
|
||||
|
||||
- `.env.local` 默认 `WORK_API_URL=http://127.0.0.1:8021`,导致 pads「请先启动 pnpm dev:work-api」
|
||||
- 代码默认 `127.0.0.1:802x` 却对用户说「本地开前端就能用」
|
||||
- 为躲线上后端,把本地 offline JSON 当成主路径(offline **仅**线上不可达时兜底)
|
||||
- 要求用户「再开一个 work-api 终端」才算本地可用
|
||||
|
||||
## 唯一例外
|
||||
|
||||
用户**本轮明确**说要联调本机后端(例如「起本地 work-api」「WORK_API_URL 指 8021」)时,才允许 `.env.local` 指向 `127.0.0.1:802x`。
|
||||
|
||||
## Agent 行为
|
||||
|
||||
1. 改 work/notify/coffee 代理或 `.env*` 时先读本 skill。
|
||||
2. 发现默认仍是 localhost → **立刻改成** `https://nomadro.com`。
|
||||
3. 本地 pads/boards 连不上 → 先查是否误指 127.0.0.1,再查线上 `https://nomadro.com/api/work/v1/health`。
|
||||
4. **不要**为修本地连通性去上线前端(见 `no-frontend-deploy-without-ok`)。
|
||||
@ -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`
|
||||
@ -1,56 +0,0 @@
|
||||
---
|
||||
name: no-frontend-deploy-without-ok
|
||||
description: >-
|
||||
Hard gate: never deploy / 上线 frontend without explicit user permission.
|
||||
Use whenever 部署、上线、deploy、发版、upload .next、admin dist、小程序包, or any
|
||||
script that ships portal/admin/miniprogram UI to a server.
|
||||
---
|
||||
|
||||
# 未经允许,不能上线前端(写死)
|
||||
|
||||
## 铁律(逐字)
|
||||
|
||||
**未经允许,不能上线前端。**
|
||||
|
||||
未得到用户**本轮明确许可**时:禁止任何前端发版动作。没有例外(「修完顺手发」「冒烟需要线上」「全权操作」历史句、上一轮曾说过部署、默认 .com 发版流程)都不能覆盖本条。
|
||||
|
||||
## 什么算「上线前端」
|
||||
|
||||
下列任一均算,必须先停、先问:
|
||||
|
||||
| 动作 | 示例 |
|
||||
|------|------|
|
||||
| 门户 Next 产物 | `pnpm build` 后上传 `.next`、`_upload_next_us.py`、`deploy_platform_upgrade_com.py`、`_deploy_*_us.py` 里带 portal `.next` |
|
||||
| 管理后台 SPA | `pnpm build:admin-com` / `build:admin` 后上传 `dist` |
|
||||
| 小程序 / Taro | 上传 weapp/tt/xhs/H5 构建包、提审包 |
|
||||
| 线上替换 UI | `systemctl restart nomadro` **且**刚换了 `.next` / 静态前端;rsync/scp 门户 `src/` 指望线上再 build(仍禁止) |
|
||||
| 对用户宣称已上线 | 说「已上线 / 已部署前端 / 打开某某 URL 看新 UI」而本轮未获许可 |
|
||||
|
||||
## 允许(不叫上线前端)
|
||||
|
||||
- 本地改代码、`pnpm dev`、本地 `pnpm build` **仅自测**(产物不上传)
|
||||
- 只动后端:FastAPI / work_svc / PocketBase schema / systemd 环境变量 / 不换 UI 产物的服务重启
|
||||
- 只 curl / 读日志排查线上,不换前端包
|
||||
|
||||
若脚本**同时**含前端包 + API:未获前端许可时,**只跑 API/后端部分**,或整段不跑并说明卡在前端门禁。
|
||||
|
||||
## 许可怎么算「明确」
|
||||
|
||||
本轮用户原话须直接授权前端发版,例如:
|
||||
|
||||
- 「可以上线前端」「部署前端」「发门户」「上传 .next」「按 com-local-build-deploy 发」
|
||||
- 「全权操作 / 部署上线」且语境是发版(仍以本轮为准;不要用更早会话的「全权」推断)
|
||||
|
||||
**不算许可:**「继续改」「修好」「参考开源深度定制」「部署 API / 管理后台后端」「看看线上」「冒烟一下」。
|
||||
|
||||
## Agent 行为
|
||||
|
||||
1. 触达任何前端上线步骤前,先读本 skill。
|
||||
2. 无明确许可 → **立刻停止**,用一两句问用户是否允许上线前端;禁止先传再问。
|
||||
3. 有许可 → 再读 `com-local-build-deploy`,本地构建再上传;禁止在美国机上 `next build`。
|
||||
4. 未获许可却已改好前端:只保留本地改动 + 说明如何自测;**不要**自行发版。
|
||||
|
||||
## 与其它规则
|
||||
|
||||
- `com-first-deploy.mdc`:默认发版目标仍是 `.com`,但**须先有本 skill 的前端许可**。
|
||||
- `com-local-build-deploy`:有许可后的执行手册,不能单独当作许可。
|
||||
@ -1,63 +0,0 @@
|
||||
---
|
||||
name: nomadro-platform
|
||||
description: >-
|
||||
Use Nomadro public API / SDK / MCP tools for nomadro.com (US primary).
|
||||
Health, remote-config, social map/meetups/gigs/join, VIP check, nav links.
|
||||
Prefer MCP tools or GET https://nomadro.com/api/public/v1/* .
|
||||
---
|
||||
|
||||
# Nomadro Platform
|
||||
|
||||
## Deploy truth
|
||||
|
||||
- **Core**: `https://nomadro.com` (US). Default for agents and SDK `baseUrl`.
|
||||
- **China mirror**: `https://nomadro.cn` — independent; sync only after `.com` cn-audience is stable.
|
||||
- Audience lanes: `cn` | `intl` via `src/modules/audience`.
|
||||
|
||||
## Surfaces (same tool list)
|
||||
|
||||
| Surface | Entry |
|
||||
|---|---|
|
||||
| Docs UI | `https://nomadro.com/developers` (Scalar) |
|
||||
| OpenAPI | `GET /api/public/v1/openapi.json` |
|
||||
| Tools | `GET /api/public/v1/tools` |
|
||||
| SDK | `@nomadro/sdk` → `createNomadroClient({ baseUrl })` |
|
||||
| MCP | `pnpm mcp` / `node packages/mcp/src/cli.mjs` |
|
||||
| WeChat skill | `apps/miniprogram/weapp/ai-pkg/socialSkill` |
|
||||
|
||||
Tool SoT: `packages/sdk/tools.json`
|
||||
|
||||
## When to call which tool
|
||||
|
||||
- Platform probe → `health` / `getMeta` / `getConfig`
|
||||
- Map / cities → `listMapCities` / `searchCities` → handoff `/social/map`
|
||||
- Video rooms → `listMeetups` / `openMeetup` (no web-view in miniprograms)
|
||||
- Gigs → `listGigs` / `applyGig` (name+contact required)
|
||||
- Paid community join (not VIP) → `joinSocial` → `/social/join`
|
||||
- VIP membership → `checkVip` with email
|
||||
- Nav catalog → `listNavLinks`
|
||||
|
||||
## MCP config (Cursor)
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"nomadro": {
|
||||
"command": "node",
|
||||
"args": ["packages/mcp/src/cli.mjs"],
|
||||
"env": {
|
||||
"NOMADRO_PUBLIC_ORIGIN": "https://nomadro.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Optional: `NOMADRO_PUBLIC_API_KEY`, `NOMADRO_SOCIAL_GUEST_ID`.
|
||||
|
||||
## Constraints
|
||||
|
||||
1. Do not treat `.cn` as the default ship target.
|
||||
2. Social join ≠ VIP (`__social_join__` vs `__vip__`).
|
||||
3. Miniprogram content must stay native (no business web-view).
|
||||
4. Prefer returning `pagePath` handoffs so users complete pay/forms in UI.
|
||||
80
.env.example
80
.env.example
@ -1,66 +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`.
|
||||
|
||||
# 本地前端直连线上后端(默认 .com;仅本机联调 API 时才改 127.0.0.1:802x)
|
||||
# WORK_API_URL=https://nomadro.com
|
||||
# NOTIFY_API_URL=https://nomadro.com
|
||||
# COFFEE_API_URL=https://nomadro.com
|
||||
# API_URL=https://nomadro.com
|
||||
# This file will be committed to version control, so make sure not to have any
|
||||
# secrets in it. If you are cloning this repo, create a copy of this file named
|
||||
# ".env" and populate it with your secrets.
|
||||
|
||||
# Admin panel
|
||||
NOMADRO_ADMIN_PASSWORD=change-me
|
||||
NOMADRO_ADMIN_SESSION_SECRET=change-me-session
|
||||
# Optional PocketBase admin token for /admin/users
|
||||
# PB_ADMIN_TOKEN=
|
||||
# When adding additional environment variables, the schema in "/src/env.js"
|
||||
# should be updated accordingly.
|
||||
|
||||
# WeChat miniprogram virtual pay (apps/api)
|
||||
WX_APPID=wxa55815dd741a540d
|
||||
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
|
||||
WX_OFFER_ID=1450642200
|
||||
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
# 1=sandbox 0=live
|
||||
WX_PAY_ENV=1
|
||||
# Next Auth
|
||||
# You can generate a new secret on the command line with:
|
||||
# npx auth secret
|
||||
# https://next-auth.js.org/configuration/options#secret
|
||||
AUTH_SECRET=""
|
||||
|
||||
# Observability (production)
|
||||
# NOMADRO_PUBLIC_ORIGIN=https://nomadro.com
|
||||
# API_URL=https://api.nomadro.com
|
||||
# 本地前端直连线上配置(浏览器 CORS;与 admin.nomadro.com 同源)
|
||||
# NEXT_PUBLIC_REMOTE_CONFIG_URL=https://nomadro.com/api/config
|
||||
# NEXT_PUBLIC_UMAMI_WEBSITE_ID=
|
||||
# NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://umami.nomadro.cn/script.js
|
||||
# PostHog(https://github.com/PostHog/posthog · 可自建或 Cloud)
|
||||
# NEXT_PUBLIC_POSTHOG_KEY=
|
||||
# NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
|
||||
# FingerprintJS 开源 visitorId(https://github.com/fingerprintjs/fingerprintjs)默认开;关:remote-config flags.fingerprintEnabled=false
|
||||
# Google (portal GoogleTags · remote-config flags override)
|
||||
# NEXT_PUBLIC_SITE_URL=https://nomadro.com
|
||||
# NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXX
|
||||
# NEXT_PUBLIC_GOOGLE_ADS_ID=AW-XXXXXXXX
|
||||
# NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABEL=
|
||||
# NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION=
|
||||
# NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-XXXXXXXX
|
||||
# NEXT_PUBLIC_ADSENSE_PUBLISHER_ID=pub-XXXXXXXX
|
||||
# Google OAuth(admin「用 Google 账号授权」→ 跳转登录)
|
||||
# GOOGLE_OAUTH_CLIENT_ID=
|
||||
# GOOGLE_OAUTH_CLIENT_SECRET=
|
||||
# GOOGLE_OAUTH_REDIRECT_URI=https://api.nomadro.com/api/admin/google/oauth/callback
|
||||
# GOOGLE_OAUTH_ADMIN_RETURN=https://admin.nomadro.com
|
||||
# GOOGLE_OAUTH_TOKEN_PATH=/var/www/nomadro-data/google_oauth_tokens.json
|
||||
# NTFY_BASE_URL=https://ntfy.nomadro.cn
|
||||
# NTFY_TOPIC=nomadro
|
||||
# Optional: .com 专用 topic(不设则用 NTFY_TOPIC)
|
||||
# NTFY_TOPIC_COM=nomadro-com
|
||||
# NTFY_TOKEN=
|
||||
# Next Auth Discord Provider
|
||||
AUTH_DISCORD_ID=""
|
||||
AUTH_DISCORD_SECRET=""
|
||||
|
||||
# Overseas pay (payjsapi)
|
||||
# CREEM_API_KEY=
|
||||
# NOWPAYMENTS_API_KEY=
|
||||
|
||||
# Social geo (MapLibre + Photon + PocketBase trips)
|
||||
# NEXT_PUBLIC_MAP_STYLE_URL=https://tiles.openfreemap.org/styles/dark
|
||||
# PHOTON_BASE_URL=https://photon.komoot.io
|
||||
# SOCIAL_GEO_USE_PB=true
|
||||
# SOCIAL_TRIPS_COLLECTION=social_trips
|
||||
# PB_URL=http://127.0.0.1:8090
|
||||
# PB_ADMIN_EMAIL=
|
||||
# PB_ADMIN_PASSWORD=
|
||||
# Prisma
|
||||
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
|
||||
DATABASE_URL="file:./db.sqlite"
|
||||
|
||||
@ -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
|
||||
78
.gitignore
vendored
78
.gitignore
vendored
@ -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
|
||||
node_modules/
|
||||
/node_modules
|
||||
/apps/**/node_modules
|
||||
/packages/**/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js / builds
|
||||
# database
|
||||
/prisma/db.sqlite
|
||||
/prisma/db.sqlite-journal
|
||||
db.sqlite
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
/apps/**/.next/
|
||||
/apps/**/out/
|
||||
/apps/**/dist/
|
||||
/apps/miniprogram/**/dist/
|
||||
/apps/admin/dist/
|
||||
next-env.d.ts
|
||||
|
||||
# production
|
||||
/build
|
||||
@ -31,25 +24,6 @@ node_modules/
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
*.log
|
||||
.turbo/
|
||||
.claude/
|
||||
|
||||
# xhs offline assemble output (regenerate via pnpm build:xhs)
|
||||
/apps/miniprogram/xhs/release/
|
||||
|
||||
# remote-config 本地备份(写入时自动生成)
|
||||
/data/backups/
|
||||
/data/notify/
|
||||
/data/work/
|
||||
/data/coffee/
|
||||
|
||||
# secondary-dev upstream clones (reference only)
|
||||
/apps/work/upstream/
|
||||
/apps/notify/upstream/
|
||||
/apps/coffee/upstream/
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
@ -57,38 +31,16 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env
|
||||
.env*
|
||||
!.env.example
|
||||
!**/.env.example
|
||||
!**/.env.production.example
|
||||
# local env files
|
||||
# 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
|
||||
.env*.local
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# python / api local
|
||||
/apps/**/.venv/
|
||||
/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
|
||||
# idea files
|
||||
.idea
|
||||
7
.npmrc
7
.npmrc
@ -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
|
||||
35
AGENTS.md
35
AGENTS.md
@ -1,35 +0,0 @@
|
||||
# Nomadro agent notes
|
||||
|
||||
Follow `.cursor/rules/*.mdc`。
|
||||
|
||||
**发版核心:`nomadro.com`(美国机)**。`.com` 分中文/国际受众;中文轨测稳后再**独立同步** `.cn`(中国机)。未点名域名时默认部署 `.com`,见 `com-first-deploy.mdc`。链路:`.com` → `.cn`(Next) → Taro H5 → 微信/抖音/小红书(微信为中国核心)。
|
||||
|
||||
**未经允许,不能上线前端**(写死):见 `.cursor/skills/no-frontend-deploy-without-ok` + `.cursor/rules/no-frontend-deploy-without-ok.mdc`。无本轮明确许可勿上传 `.next` / admin dist / 小程序包。
|
||||
|
||||
**本地前端直连线上后端**(写死):`pnpm dev` 默认 `WORK_API_URL`/`NOTIFY_API_URL`/`COFFEE_API_URL`/`API_URL` → `https://nomadro.com`;禁止默认 `127.0.0.1:802x`。见 `.cursor/skills/local-frontend-online-backend`。
|
||||
|
||||
**对外标准面**:`/api/public/v1` + `@nomadro/sdk` + `@nomadro/mcp` + `.cursor/skills/nomadro-platform`(工具 SoT `packages/sdk/tools.json`)。文档 [`docs/public-api.md`](docs/public-api.md)。
|
||||
|
||||
| Layer | Path |
|
||||
|---|---|
|
||||
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
|
||||
| Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 |
|
||||
| Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 |
|
||||
| Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 |
|
||||
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
|
||||
| Unified API | `apps/api` |
|
||||
| Admin SPA (.cn) | `apps/admin` → `admin.nomadro.cn`(微信 / 抖音) |
|
||||
| **.com 隔离树** | `apps/com/*`(美国 VPS · **无小程序**);`apps/com/admin` → `admin.nomadro.com` |
|
||||
| Shared | `packages/{pay,pb,sdk}` |
|
||||
|
||||
## Dev
|
||||
|
||||
根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:admin-com` / `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`。
|
||||
|
||||
**受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。后台登录后选 `/cn`|`/intl`。见 `audience-cn-intl.mdc`。
|
||||
|
||||
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。
|
||||
401
README.md
401
README.md
@ -1,379 +1,92 @@
|
||||
# Nomadro
|
||||
# nomadro
|
||||
|
||||
2026-11-09:`test14` 门户、后端及 `.com` 管理后台已获许可并部署美国机。门户构建 `T9G517UdX-JND3zgNO3SD`;修复生产通知/预约代理自循环,公网接口恢复 200。门户/后台静态资源哈希、服务健康与后台鉴权验证通过,`.cn` 未同步。备份与验收见 [test14 上线记录](docs/test14-release.md)。
|
||||
|
||||
2026-11-09:`test13` 收尾后切换 `test14`,仅优化门户/后端/后台功能与构建,不调整前端视觉、不部署生产。修复首页重写循环、迁移 Next.js 16 `proxy`、统一本地 `.com` API/配置默认值、修复 Strict Mode 埋点监听及后台请求异常处理、为共享 PocketBase 凭证增加并发保护与一次 401 恢复,并修复 `.cn` 后台构建类型冲突。范围与验证见 [test14 开发记录](docs/test14-development.md)。
|
||||
|
||||
2026-11-08:远程工作门禁 + Work UX + 语言水合修复并部署 `.com` — `/social/work` 未加入社区不可用(登录/注册/补资料,与约会同门禁);Pads/Boards 增强(收藏复制删除、专注预览快捷键、看板筛选模板);`LocaleProvider`/`LanguageSwitcher` 首帧固定 zh 消除 hydration mismatch;反馈页英文短语补全。本地构建上传门户 `.next` + `admin.nomadro.com` + API/social;`.cn` 未同步。
|
||||
## Getting started
|
||||
|
||||
2026-11-07:Work Pads 深度定制(Etherpad 域模型 → Next 原生)— `/social/work/pads`:作者色条、行号、在场名单、侧栏聊天、时间轴浏览/还原、冲突提示、导入导出、Ctrl/⌘+S、删除;API `presence`/`chat`/`DELETE` + Welcome pad;work 服务补 PocketBase 鉴权。无 iframe。
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
2026-11-07:Google 增长 OAuth UX 修复 — 未配 Client 时不再展示灰掉的「用 Google 账号授权」;改为红条提示 +「① 保存客户端」为主按钮,保存成功后再出现「② 用 Google 账号授权」。
|
||||
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)!
|
||||
|
||||
2026-11-07:用户分析补全环境特征并部署 `.com` — 埋点写入 IP(服务端)+ UA/浏览器/系统/设备/屏幕/时区/语言等;后台「访客明细 → 看明细」展示环境特征卡与时间线;API `track-analytics` / `track-visitor`。
|
||||
## Add your files
|
||||
|
||||
2026-11-07:产品分析 — 门户接入 [PostHog](https://github.com/PostHog/posthog)(`posthog-js`)与开源 [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) visitorId;经 `PortalAnalytics` + `src/lib/analytics/*` 镜像现有 `/api/track`;远程配置 `flags.posthog*` / `fingerprintEnabled` + env `NEXT_PUBLIC_POSTHOG_KEY`。未配 key 时 PostHog 静默跳过。
|
||||
|
||||
2026-11-07:Google 增长自动化 — 后台「增长 → Google 增长」支持粘贴片段 / 同步 env / 一键写入;API `/api/admin/google/{status,parse,auto-link}`;`ca-pub` 自动补 `ads.txt` publisher;保留手填。门户 `GoogleTags` + `/sitemap.xml` `/robots.txt` `/ads.txt`。文字厅双语与咖啡聊离线兜底见 [`src/modules/social/README.md`](src/modules/social/README.md)。
|
||||
|
||||
2026-11-05:UI/UX 与预约、通知功能升级已上线 .com,详见 [本轮发布与验收记录](docs/uiux-upgrade-2026-11-05.md),包括当前构建、备份位置及功能边界。
|
||||
|
||||
数字游民操作系统(主开发与默认发版:[nomadro.com](https://nomadro.com);中国独立站:[nomadro.cn](https://nomadro.cn))。
|
||||
|
||||
2026-11 平台升级已部署至 `.com` 门户、API 与 [Web 管理后台](https://admin.nomadro.com)。升级内容、验收范围、构建编号与回滚位置见 [升级记录](docs/platform-upgrade-2026-11.md)。`.cn` 未同步本次发版。
|
||||
|
||||
**归档禁发:** 分支 `test12`(Codex 实验改动)已冻结,**永远不要上线**;见 [docs/archive/test12-NEVER-DEPLOY.md](docs/archive/test12-NEVER-DEPLOY.md) 与 tag `archive/test12-never-deploy`。
|
||||
|
||||
## 架构
|
||||
- [ ] [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 门户 .cn(app 路由壳 + modules 业务)
|
||||
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(仅 .cn 备案线)
|
||||
apps/api/ 统一 FastAPI(ebook + community + pay + social + work + notify)
|
||||
apps/admin/ admin.nomadro.cn 管理 SPA(微信 / 抖音)
|
||||
apps/com/ .com 源码隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
|
||||
apps/work/ 远程工作参考 upstream / overlay(Planka · Etherpad;产品 UI 不跑 iframe)
|
||||
apps/notify/ 通知参考 upstream(Novu;产品 UI 不跑 iframe)
|
||||
apps/coffee/ 咖啡聊预约参考 upstream(Cal.com;产品 UI 不跑 iframe)
|
||||
packages/ @nomadro/pay · pb · sdk
|
||||
data/ 远程配置等运行时数据(含 social.db · work/notify/coffee.sqlite3)
|
||||
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
cd existing_repo
|
||||
git remote add origin http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
| 产品 | 门户路由 | 源码 |
|
||||
|------|----------|------|
|
||||
| 导航 | `/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 |
|
||||
| **远程工作** | `/social/work` | `src/modules/work` · FastAPI `work_svc` `/api/work/v1`(看板 + 文档) |
|
||||
| **通知** | `/notifications` · `/social/notify` | `src/modules/notify` · FastAPI `notify_svc` `/api/notify/v1`(收件箱 + 工作流) |
|
||||
| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
|
||||
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
|
||||
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
|
||||
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
|
||||
| API | api.nomadro.cn | `apps/api` |
|
||||
## Integrate with your tools
|
||||
|
||||
`.cn` 后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗集成在 **`/douyin/modules`**。`.com` 未备案,**无**小程序后台。
|
||||
- [ ] [Set up project integrations](http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro/-/settings/integrations)
|
||||
|
||||
## 技术栈(Next 门户 + FastAPI)
|
||||
## Collaborate with your team
|
||||
|
||||
### 前端(`src/` · Next.js)
|
||||
- [ ] [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)
|
||||
|
||||
| 层 | 技术 |
|
||||
|---|---|
|
||||
| 框架 | Next.js 16(App Router)· React 19 · TypeScript · pnpm workspace |
|
||||
| 样式 | Tailwind CSS 4 · Sass · 模块 CSS |
|
||||
| 主题 | `next-themes`(日/夜防闪烁) |
|
||||
| 动效 / 图标 | Framer Motion · animate.css · Lucide |
|
||||
| 地图 | MapLibre GL · h3-js |
|
||||
| 实时 | Centrifuge(对接 Centrifugo)· socket.io-client |
|
||||
| Markdown / 编辑 | react-markdown · marked · markdown-it · Gravity UI Markdown · Diplodoc · highlight.js |
|
||||
| DnD / 组件库 | `@hello-pangea/dnd` · Ant Design · Gravity UI · Semantic UI React |
|
||||
| 3D | three.js |
|
||||
| i18n / 受众 | i18next · `is-china-user` · `src/modules/audience/{cn,intl}` |
|
||||
| 产品分析 | PostHog(`posthog-js`)· FingerprintJS(开源 visitorId)· Umami · GA4/Ads gtag · `/api/track` |
|
||||
| 其它 | PocketBase JS SDK · QR · PhotoSwipe · `@nomadro/{pay,pb,sdk}` |
|
||||
## Test and Deploy
|
||||
|
||||
业务垂直在 `src/modules/{nav,ebook,community,social,work,notify,vip,audience}`;`src/app` 只挂路由。同源 API 经 Next Route Handler 反代到 FastAPI(如 `/api/work/v1`、`/api/notify/v1`)。
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
### 后端(`apps/api` · FastAPI)
|
||||
- [ ] [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)
|
||||
|
||||
| 层 | 技术 |
|
||||
|---|---|
|
||||
| 运行时 | FastAPI · Uvicorn |
|
||||
| 服务 | `ebook_svc` · `community_svc` · `pay_svc` · `social_svc` · `work_svc` · `notify_svc` · `coffee_svc` |
|
||||
| 独立进程 | `social_main :8020` · `work_main :8021` · `notify_main :8023` · `coffee_main :8024`(主 API 另有统一入口) |
|
||||
| 数据 | PocketBase(账号/订单等)· SQLite(social / work / notify / coffee) |
|
||||
| 对象存储 | SeaweedFS S3(`s3.nomadro.com`;社群 / 加入头像共用 `S3_*`) |
|
||||
| 支付 | 海外 Creem / NOWPayments;国内 zpay · xpay/xorpay;密钥只走 API |
|
||||
***
|
||||
|
||||
### 周边同仓
|
||||
# Editing this README
|
||||
|
||||
| 端 | 技术 |
|
||||
|---|---|
|
||||
| 小程序 | Taro 4 + React(H5 SoT → 微信 / 抖音 / 小红书);**禁止 web-view 承载业务** |
|
||||
| 管理后台 | Vite SPA(`apps/admin` · `apps/com/admin`) |
|
||||
| 运维常见 | Nginx / Caddy · Docker · Umami · Uptime-Kuma · ntfy · SeaweedFS / MinIO |
|
||||
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.
|
||||
|
||||
## 开源对照(域模型二次开发)
|
||||
## 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.
|
||||
|
||||
原则:**读开源域模型后自研进 Nomadro**,同域原生页;**禁止** iframe / 二级域硬嵌官方 UI。上游仅对照:`pnpm work:fetch` · `pnpm notify:fetch`。
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
| 开源项目 | 用途 | Nomadro 落点 |
|
||||
|---|---|---|
|
||||
| [Planka](https://github.com/plankanban/planka) | 看板域模型 | `/social/work/boards` · `work_svc` |
|
||||
| [Etherpad](https://github.com/ether/etherpad) | 协作文档 / 修订 | `/social/work/pads` · `work_svc` |
|
||||
| [Novu](https://github.com/novuhq/novu) | 通知工作流 / Inbox | `/social/notify` · `/notifications` · `notify_svc` |
|
||||
| [Cal.com](https://github.com/calcom/cal.com) | 预约 / 日程 / 时段 | `/social/coffeechat` · `coffee_svc` |
|
||||
| MiroTalk | 视频厅(白标同域) | 社群活动直播 / join |
|
||||
| Centrifugo | 实时推送 | Social 聊天 WebSocket |
|
||||
| PocketBase | BaaS / 鉴权与业务库 | `@nomadro/pb` · 支付写库 |
|
||||
| Taro | 多端小程序 | `apps/miniprogram/*` |
|
||||
| MapLibre | 地图 | `/social/map` 等 |
|
||||
| three.js | 3D | 门户 / H5(游戏模块冷冻) |
|
||||
| [PostHog](https://github.com/PostHog/posthog) | 产品分析 / 事件 | 门户 `src/lib/analytics` · `PortalAnalytics`(env / remote-config) |
|
||||
| [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) | 浏览器 fingerprint → visitorId(MIT 开源) | `src/lib/analytics/fingerprint.ts`(挂到 track / PostHog identify) |
|
||||
| Umami | 隐私友好访问统计 | 运维 · `UmamiAnalytics` |
|
||||
| Uptime-Kuma | 可用性监控 | 运维 |
|
||||
| ntfy | 运维通知 | 运维 |
|
||||
| SeaweedFS / MinIO | 对象存储(头像 / 社群媒体 → `s3.nomadro.com`) | `social_svc` · `community_svc` |
|
||||
| Caddy | 反代(可选) | 运维 |
|
||||
## 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.
|
||||
|
||||
细节:[`apps/work/README.md`](apps/work/README.md) · [`apps/notify/README.md`](apps/notify/README.md)。
|
||||
## 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.
|
||||
|
||||
### 微信后台(admin.nomadro.cn/wechat)
|
||||
## 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.
|
||||
|
||||
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。
|
||||
## Installation
|
||||
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.
|
||||
|
||||
| 分组 | 菜单 | 路径 |
|
||||
|------|------|------|
|
||||
| 总览 | 运营概览 | `/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` |
|
||||
## Usage
|
||||
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.
|
||||
|
||||
兼容:`/wechat/vip/library` → 重定向到 `/wechat/vip/ebooks`。
|
||||
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`)。
|
||||
## Support
|
||||
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.
|
||||
|
||||
### 微信小程序 VIP(原生,禁止 web-view)
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
对照 `src/modules/vip` / nomadvip H5,微信端业务内容必须原生页(见 `.cursor/rules/no-webview-content.mdc`):
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
| 能力 | 小程序页 | 说明 |
|
||||
|------|----------|------|
|
||||
| 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` |
|
||||
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.
|
||||
|
||||
内容种子:`h5/src/data/vipEbooks.ts` · `vipLessonContent.ts` · `vipStoreCatalog.ts`(可由 `h5/scripts/extract-vip-*.py` 从 `src/modules/vip/app/data` 重生)。
|
||||
正式正文库:`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`。
|
||||
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.
|
||||
|
||||
部署脚本(本地构建 admin + 同步 API):
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
```bash
|
||||
python apps/admin/deploy/deploy_vip_library.py # VIP 正式内容库 + Admin
|
||||
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 到线上
|
||||
```
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
|
||||
## 本地
|
||||
|
||||
根目录一次安装(pnpm workspace):
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
|
||||
pnpm dev # 门户 :3000
|
||||
pnpm dev:h5 # Taro H5 :10086
|
||||
pnpm dev:weapp # 微信小程序
|
||||
pnpm dev:tt # 抖音小程序
|
||||
pnpm dev:admin # 管理后台 :5173
|
||||
pnpm dev:api # FastAPI(需先建 apps/api/.venv)
|
||||
pnpm dev:work-api # 仅本机联调 work_svc :8021;日常 pnpm dev 直连线上 nomadro.com
|
||||
pnpm dev:notify-api # 通知 notify_svc :8023(收件箱 / 工作流)
|
||||
pnpm dev:coffee-api # 咖啡聊 coffee_svc :8024(预约 / 时段)
|
||||
|
||||
pnpm build:portal
|
||||
pnpm build:admin
|
||||
pnpm build:xhs # 小红书离线包 → apps/miniprogram/xhs/release
|
||||
pnpm typecheck
|
||||
pnpm clean # 清 .next / dist
|
||||
```
|
||||
|
||||
API 首次:
|
||||
|
||||
```bash
|
||||
cd apps/api
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\pip install -r requirements.txt
|
||||
cd ../..
|
||||
pnpm dev:api
|
||||
```
|
||||
|
||||
若原生依赖未构建(esbuild / `@tarojs/binding` 等):`pnpm rebuild`(根 `package.json` 已声明 `pnpm.onlyBuiltDependencies`)。
|
||||
|
||||
## 约定
|
||||
|
||||
- **业务在 `src/modules/`**,`src/app/` 只挂路由与薄 re-export
|
||||
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
||||
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
||||
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||
- 审核冻结分支:`pre4`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`**
|
||||
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
|
||||
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
|
||||
- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`)
|
||||
|
||||
### 游民社区(`/social`)
|
||||
|
||||
与旅居社群 `/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)。
|
||||
|
||||
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。**人脸门禁**(默认开):头像需**单人正脸**;优先 InsightFace 检测 + RGB 活体。**现场自拍核验**(推荐):`POST /api/social/v1/avatar/challenge` 收正脸+转头两帧,校验同人 embedding + 转头幅度后再存头像。关检测:`SOCIAL_AVATAR_FACE_CHECK=false`;关活体:`SOCIAL_AVATAR_LIVENESS=false`。
|
||||
|
||||
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
|
||||
|
||||
**文字厅(`/social/chat`)**:Centrifugo WS 优先(`/rt` 反代 · token `/api/social/v1/realtime/token`),失败降级轮询。侧栏为 Lobby + **国家频道**(多语言国名,不做大洲分组)。消息能力:未读分隔、在线 presence、发送中态、@提及、转发、已读回执、频道 rail 实时。气泡内 **MessageBilingual**:原文 + 当前 UI 语言译文同框(细线分隔,非第二气泡);不展示活动条 / 置顶条。本地:`pnpm` 起 Next `:3000` + `social_main :8020` + Centrifugo(见 `deploy/social/centrifugo`)。
|
||||
|
||||
### 远程工作(`/social/work`)
|
||||
|
||||
游民社区「一起做事」下的 **看板 + 实时文档**:读 Planka / Etherpad **域模型后自研** Next + FastAPI,同域挂载,**禁止** iframe / 二级域跳转 / micro-app 壳。
|
||||
|
||||
| 能力 | 路由 | 前端 | 后端 |
|
||||
|------|------|------|------|
|
||||
| 落地 | `/social/work` | `WorkClient` 品牌首屏;**加入社区门禁**(`WorkAccessGate`) | — |
|
||||
| 看板 | `/social/work/boards` · `/boards/:id` | DnD · 筛选 · 模板 · 标签/清单/成员/活动流 | `work_svc` |
|
||||
| 文档 | `/social/work/pads` · `/pads/:id` | 自动保存 · 修订 · 专注/预览/快捷键 · 收藏复制 | 同上 |
|
||||
|
||||
```bash
|
||||
pnpm dev:work-api # 可选本机 :8021;默认 WORK_API_URL=https://nomadro.com(本地前端直连线上)
|
||||
pnpm dev # http://localhost:3000/social/work
|
||||
```
|
||||
|
||||
数据:`data/work/work.sqlite3`(或 `WORK_DATA_DIR`)。参考 upstream:`pnpm work:fetch`(仅对照,产品不跑 Docker Planka UI)。细节见 [`apps/work/README.md`](apps/work/README.md)。
|
||||
|
||||
### 通知(`/notifications` · `/social/notify`)
|
||||
|
||||
读 **Novu** 域模型后自研。用户向收件箱与编排控制台分离;同域原生页,**禁止** iframe。
|
||||
|
||||
| 能力 | 路由 | 说明 |
|
||||
|------|------|------|
|
||||
| 全部通知 | `/social/notifications`(根路径 `/notifications` 重定向) | 分类:社交 / 搭子 / 项目 / 系统;点击跳转;全部/单条已读;删除 |
|
||||
| 偏好设置 | `/social/notifications/settings` | 免打扰 · 邮件订阅 · 浏览器推送授权 |
|
||||
| 顶部铃铛 | SiteShell | 未读角标,轮询 `/api/notify/v1/inbox/unread` |
|
||||
| 编排控制台 | `/social/notify` | 工作流 / 订阅者 / 主题 / 活动(Novu 二次开发) |
|
||||
|
||||
```bash
|
||||
pnpm dev:notify-api # :8023 · NOTIFY_API_URL → /api/notify/v1
|
||||
pnpm notify:fetch # 可选对照源码
|
||||
pnpm dev # http://localhost:3000/notifications
|
||||
```
|
||||
|
||||
数据:`data/notify/notify.sqlite3`。细节见 [`apps/notify/README.md`](apps/notify/README.md)。
|
||||
|
||||
### 咖啡聊预约(`/social/coffeechat`)
|
||||
|
||||
读 **Cal.com** 域模型后自研:Host · EventType · Schedule/Availability · Slots · Booking。同域原生页;咖啡馆点位仍见 `/social/places?tab=cafes`。
|
||||
|
||||
```bash
|
||||
pnpm dev:coffee-api # :8024 · COFFEE_API_URL → /api/coffee/v1
|
||||
pnpm coffee:fetch # 可选对照源码
|
||||
pnpm dev # http://localhost:3000/social/coffeechat
|
||||
```
|
||||
|
||||
数据:`data/coffee/coffee.sqlite3`。细节见 [`apps/coffee/README.md`](apps/coffee/README.md)。
|
||||
|
||||
**`.com`(美国机,默认发版)**:`python deploy/work/deploy_us.py` → 门户 `nomadro` `:4003` + `nomadro-work` `:8021`;nginx `^~ /api/work/` **直连** work_svc(勿经 Next,避免 `Connection: upgrade` 导致 503)。冒烟:`https://nomadro.com/social/work` · `/api/work/v1/boards`。
|
||||
|
||||
| 层 | 线上(82 · `.cn`) | 说明 |
|
||||
|---|---|---|
|
||||
| 门户 | `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) |
|
||||
| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
|
||||
| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
|
||||
|
||||
提审上传:
|
||||
|
||||
```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`。
|
||||
## 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.
|
||||
|
||||
@ -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
30
apps/admin/.gitignore
vendored
@ -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
|
||||
@ -1,76 +0,0 @@
|
||||
# Nomadro 管理后台(admin.nomadro.cn)
|
||||
|
||||
Vite + React SPA。业务 API 经同源反代到 **`nomadmini-api`** / `apps/api`。
|
||||
|
||||
> **`.com` Web 后台已源码隔离**:见 [`apps/com`](../com) → `admin.nomadro.com`(美国 VPS,无微信/抖音)。勿把小程序能力做到 `.com` 树,也勿把 `.com` 合回本包。
|
||||
|
||||
## 本地
|
||||
|
||||
```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`
|
||||
@ -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 配置。
|
||||
@ -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})
|
||||
@ -1,104 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Build apps/com/admin and deploy static dist to admin.nomadro.com (US VPS)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
US = ("108.174.50.68", "root", "Xiao4669805")
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
ADMIN_COM = ROOT / "apps" / "com" / "admin"
|
||||
REMOTE_ROOT = "/www/wwwroot/admin.nomadro.com"
|
||||
|
||||
|
||||
def build() -> Path:
|
||||
subprocess.run(
|
||||
["pnpm", "--filter", "@nomadro/admin-com", "build"],
|
||||
cwd=str(ROOT),
|
||||
check=True,
|
||||
shell=True,
|
||||
)
|
||||
dist = ADMIN_COM / "dist"
|
||||
if not dist.is_dir():
|
||||
raise SystemExit("dist missing")
|
||||
return dist
|
||||
|
||||
|
||||
def pack(dist: Path) -> bytes:
|
||||
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=p.relative_to(dist).as_posix())
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("=== build ===", flush=True)
|
||||
dist = build()
|
||||
blob = pack(dist)
|
||||
print("pack", len(blob), "bytes", flush=True)
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
host, user, password = US
|
||||
c.connect(host, 22, user, password, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/admin-com.tgz", "wb") as f:
|
||||
f.write(blob)
|
||||
sftp.close()
|
||||
|
||||
remote = rf"""
|
||||
set -euo pipefail
|
||||
mkdir -p {REMOTE_ROOT}
|
||||
ts=$(date +%Y%m%d%H%M%S)
|
||||
if [ -d {REMOTE_ROOT} ] && [ "$(ls -A {REMOTE_ROOT} 2>/dev/null)" ]; then
|
||||
mkdir -p /www/wwwroot/_bak_admin_com
|
||||
tar -C {REMOTE_ROOT} -czf /www/wwwroot/_bak_admin_com/admin-$ts.tgz . || true
|
||||
fi
|
||||
rm -rf {REMOTE_ROOT}.new
|
||||
mkdir -p {REMOTE_ROOT}.new
|
||||
tar -xzf /tmp/admin-com.tgz -C {REMOTE_ROOT}.new
|
||||
# atomic swap
|
||||
rm -rf {REMOTE_ROOT}.old
|
||||
mv {REMOTE_ROOT} {REMOTE_ROOT}.old 2>/dev/null || true
|
||||
mv {REMOTE_ROOT}.new {REMOTE_ROOT}
|
||||
rm -rf {REMOTE_ROOT}.old
|
||||
# spa fallback already in nginx; smoke
|
||||
curl -sk -o /dev/null -w "admin_home %{{http_code}}\n" https://admin.nomadro.com/
|
||||
curl -sk https://admin.nomadro.com/ | tr '\n' ' ' | grep -o 'Nomadro' | head -1 || true
|
||||
# keep API up
|
||||
systemctl is-active nomadmini-api
|
||||
curl -sS -o /tmp/login.json -w "login %{{http_code}}\n" --max-time 10 -X POST https://api.nomadro.com/api/admin/login \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}'
|
||||
head -c 120 /tmp/login.json; echo
|
||||
echo DEPLOY_ADMIN_COM_OK
|
||||
"""
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(180)
|
||||
chan.get_pty()
|
||||
chan.exec_command(remote)
|
||||
buf = []
|
||||
end = time.time() + 180
|
||||
while time.time() < end:
|
||||
if chan.recv_ready():
|
||||
buf.append(chan.recv(65536).decode("utf-8", "replace"))
|
||||
if chan.exit_status_ready():
|
||||
while chan.recv_ready():
|
||||
buf.append(chan.recv(65536).decode("utf-8", "replace"))
|
||||
break
|
||||
time.sleep(0.05)
|
||||
print("".join(buf)[-5000:], flush=True)
|
||||
code = chan.recv_exit_status()
|
||||
c.close()
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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()
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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()
|
||||
@ -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())
|
||||
@ -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()
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -1,186 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Push PocketBase social_ugc admin stack to US nomadmini-api + social_svc.
|
||||
|
||||
admin.nomadro.com Social page needs:
|
||||
GET /api/admin/social/ugc/{stats,archives,detail/...}
|
||||
and soft-delete via social_svc.pb_data → PocketBase.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
US = ("108.174.50.68", "root", "Xiao4669805")
|
||||
REMOTE_APP = "/opt/nomadmini/backend/app"
|
||||
REMOTE_API = "/var/www/nomadro.cn/apps/api"
|
||||
REMOTE_BACKEND = "/opt/nomadmini/backend"
|
||||
|
||||
LOCAL_UGC = ROOT / "apps/api/services/ebook_svc/services/social_ugc.py"
|
||||
LOCAL_ADMIN = ROOT / "apps/api/services/ebook_svc/routers/social_ugc_admin.py"
|
||||
LOCAL_SVC = ROOT / "apps/api/services/social_svc"
|
||||
LOCAL_PB = ROOT / "apps/api/services/nomadro_pb"
|
||||
|
||||
|
||||
def to_app(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def connect() -> paramiko.SSHClient:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
h, u, p = US
|
||||
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=90)
|
||||
t = c.get_transport()
|
||||
if t:
|
||||
t.set_keepalive(15)
|
||||
return c
|
||||
|
||||
|
||||
def sh(c: paramiko.SSHClient, cmd: str, timeout: int = 240) -> tuple[int, str]:
|
||||
print(f"$ {cmd[:240].replace(chr(10), ' ')}", flush=True)
|
||||
_, o, e = c.exec_command(cmd, timeout=timeout)
|
||||
out = o.read().decode("utf-8", "replace")
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
code = o.channel.recv_exit_status()
|
||||
text = out + (("\n" + err) if err.strip() else "")
|
||||
if text.strip():
|
||||
print(text[-8000:], flush=True)
|
||||
print("exit", code, flush=True)
|
||||
return code, text
|
||||
|
||||
|
||||
def pack() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for src, name in (
|
||||
(LOCAL_UGC, "api/services/social_ugc.py"),
|
||||
(LOCAL_ADMIN, "api/routers/social_ugc_admin.py"),
|
||||
):
|
||||
if not src.is_file():
|
||||
raise SystemExit(f"missing {src}")
|
||||
text = to_app(src.read_text(encoding="utf-8"))
|
||||
if "ebook_svc." in text:
|
||||
raise SystemExit(f"rewrite failed: {src}")
|
||||
data = text.encode("utf-8")
|
||||
info = tarfile.TarInfo(name=name)
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
tar.add(LOCAL_SVC, arcname="services/social_svc")
|
||||
tar.add(LOCAL_PB, arcname="services/nomadro_pb")
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not LOCAL_SVC.is_dir() or not LOCAL_PB.is_dir():
|
||||
raise SystemExit("missing social_svc or nomadro_pb")
|
||||
blob = pack()
|
||||
print(f"pack {len(blob)} bytes", flush=True)
|
||||
|
||||
c = connect()
|
||||
try:
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/social_ugc_admin_us.tgz", "wb") as rf:
|
||||
rf.write(blob)
|
||||
sftp.close()
|
||||
|
||||
code, _ = sh(
|
||||
c,
|
||||
f"""
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/social_ugc_extract
|
||||
rm -rf /tmp/social_ugc_extract/*
|
||||
tar -xzf /tmp/social_ugc_admin_us.tgz -C /tmp/social_ugc_extract
|
||||
TS=$(date +%Y%m%d%H%M%S)
|
||||
|
||||
# 1) social_svc + nomadro_pb → social API tree
|
||||
mkdir -p {REMOTE_API}/services
|
||||
[ -d {REMOTE_API}/services/social_svc ] && cp -a {REMOTE_API}/services/social_svc /tmp/social_svc.bak.$TS || true
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_API}/services/social_svc/
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_API}/services/nomadro_pb/
|
||||
|
||||
# 2) same packages on nomadmini PYTHONPATH (import social_svc / nomadro_pb)
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/social_svc/
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/nomadro_pb/
|
||||
# also under services/ for social_ugc parents[2] path probe
|
||||
mkdir -p {REMOTE_BACKEND}/services
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/services/social_svc/
|
||||
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/services/nomadro_pb/
|
||||
|
||||
# 3) hot-patch ugc modules (ebook_svc→app already rewritten)
|
||||
cp -a {REMOTE_APP}/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py.bak-$TS 2>/dev/null || true
|
||||
cp -a {REMOTE_APP}/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py.bak-$TS 2>/dev/null || true
|
||||
cp /tmp/social_ugc_extract/api/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py
|
||||
cp /tmp/social_ugc_extract/api/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py
|
||||
|
||||
# 4) ensure PB URL in nomadmini env (do not clobber secrets)
|
||||
ENVF={REMOTE_BACKEND}/.env
|
||||
touch "$ENVF"
|
||||
grep -q '^PB_URL=' "$ENVF" || echo 'PB_URL=http://127.0.0.1:8090' >> "$ENVF"
|
||||
grep -q '^POCKETBASE_URL=' "$ENVF" || echo 'POCKETBASE_URL=http://127.0.0.1:8090' >> "$ENVF"
|
||||
|
||||
# 5) import smoke
|
||||
cd {REMOTE_BACKEND}
|
||||
.venv/bin/python - <<'PY'
|
||||
import sys
|
||||
sys.path.insert(0, ".")
|
||||
sys.path.insert(0, "services")
|
||||
from app.routers import social_ugc_admin
|
||||
from app.services import social_ugc
|
||||
paths = sorted({{getattr(r, "path", "") for r in social_ugc_admin.router.routes}})
|
||||
need = [
|
||||
"/api/admin/social/ugc/stats",
|
||||
"/api/admin/social/ugc/archives",
|
||||
"/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}",
|
||||
"/api/admin/social/ugc/overview",
|
||||
]
|
||||
for p in need:
|
||||
assert p in paths, (p, paths)
|
||||
print("ugc_routes_ok", len(paths))
|
||||
print("backend", social_ugc.available())
|
||||
PY
|
||||
|
||||
# 6) restart APIs
|
||||
systemctl kill -s9 nomadro-social.service 2>/dev/null || true
|
||||
fuser -k 8020/tcp 2>/dev/null || true
|
||||
sleep 1
|
||||
systemctl reset-failed nomadro-social 2>/dev/null || true
|
||||
systemctl start nomadro-social 2>/dev/null || true
|
||||
systemctl restart nomadmini-api
|
||||
sleep 3
|
||||
systemctl is-active nomadmini-api
|
||||
systemctl is-active nomadro-social || true
|
||||
curl -sS -o /dev/null -w 'social_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8020/api/social/v1/health || true
|
||||
curl -sS -o /dev/null -w 'api_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8010/docs || true
|
||||
|
||||
TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \\
|
||||
-H 'content-type: application/json' \\
|
||||
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))')
|
||||
echo "token_len ${{#TOKEN}}"
|
||||
for path in overview stats archives; do
|
||||
code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \\
|
||||
-H "Authorization: Bearer $TOKEN" \\
|
||||
"https://api.nomadro.com/api/admin/social/ugc/$path")
|
||||
echo "ugc_$path $code"
|
||||
head -c 220 /tmp/ugc_$path.json; echo
|
||||
done
|
||||
curl -sk -o /dev/null -w 'admin_com %{{http_code}}\\n' https://admin.nomadro.com/
|
||||
echo PUSH_SOCIAL_UGC_ADMIN_US_OK
|
||||
""",
|
||||
)
|
||||
return code
|
||||
finally:
|
||||
c.close()
|
||||
print("done", time.strftime("%H:%M:%S"), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -1,97 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Hot-patch US nomadmini social_ugc to SQLite soft-delete + stats (no PocketBase)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
US = ("108.174.50.68", "root", "Xiao4669805")
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SRC = HERE / "_us_social_ugc_sqlite.py"
|
||||
ADMIN_SRC = (
|
||||
Path(__file__).resolve().parents[3]
|
||||
/ "apps/api/services/ebook_svc/routers/social_ugc_admin.py"
|
||||
)
|
||||
REMOTE_APP = "/opt/nomadmini/backend/app"
|
||||
|
||||
|
||||
def to_app(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not SRC.is_file():
|
||||
raise SystemExit(f"missing {SRC}")
|
||||
body = SRC.read_text(encoding="utf-8").encode("utf-8")
|
||||
admin_body = to_app(ADMIN_SRC.read_text(encoding="utf-8")).encode("utf-8")
|
||||
if b"ebook_svc." in admin_body:
|
||||
raise SystemExit("admin rewrite failed")
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
h, u, p = US
|
||||
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/social_ugc_sqlite_us.py", "wb") as f:
|
||||
f.write(body)
|
||||
with sftp.file("/tmp/social_ugc_admin_us.py", "wb") as f:
|
||||
f.write(admin_body)
|
||||
sftp.close()
|
||||
print("uploaded", len(body), len(admin_body), flush=True)
|
||||
|
||||
cmd = rf"""
|
||||
set -euo pipefail
|
||||
TS=$(date +%Y%m%d%H%M%S)
|
||||
B={REMOTE_APP}
|
||||
cp -a "$B/services/social_ugc.py" "$B/services/social_ugc.py.bak-pre-sqlite-$TS" || true
|
||||
cp -a "$B/routers/social_ugc_admin.py" "$B/routers/social_ugc_admin.py.bak-pre-sqlite-$TS" || true
|
||||
cp /tmp/social_ugc_sqlite_us.py "$B/services/social_ugc.py"
|
||||
cp /tmp/social_ugc_admin_us.py "$B/routers/social_ugc_admin.py"
|
||||
# ensure SOCIAL_DB_PATH on nomadmini
|
||||
ENVF=/opt/nomadmini/backend/.env
|
||||
grep -q '^SOCIAL_DB_PATH=' "$ENVF" || echo 'SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db' >> "$ENVF"
|
||||
# prefer empty PB so nothing accidental
|
||||
sed -i 's/^USE_POCKETBASE=.*/USE_POCKETBASE=false/' "$ENVF" || true
|
||||
cd /opt/nomadmini/backend
|
||||
.venv/bin/python - <<'PY'
|
||||
from app.services import social_ugc as ugc
|
||||
from app.routers import social_ugc_admin
|
||||
print('available', ugc.available())
|
||||
print('overview', ugc.overview())
|
||||
print('stats', {{k: ugc.stats().get(k) for k in ('ok','counts','backend')}})
|
||||
paths = sorted({{getattr(r,'path','') for r in social_ugc_admin.router.routes}})
|
||||
for need in ['/api/admin/social/ugc/stats','/api/admin/social/ugc/archives','/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}']:
|
||||
assert need in paths, need
|
||||
print('routes_ok', len(paths))
|
||||
PY
|
||||
systemctl restart nomadmini-api
|
||||
sleep 3
|
||||
systemctl is-active nomadmini-api
|
||||
systemctl is-active nomadro-social
|
||||
curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo
|
||||
TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))')
|
||||
echo "token_len ${{#TOKEN}}"
|
||||
for path in overview stats archives roster; do
|
||||
code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
"https://api.nomadro.com/api/admin/social/ugc/$path")
|
||||
echo "ugc_$path $code"
|
||||
head -c 260 /tmp/ugc_$path.json; echo
|
||||
done
|
||||
curl -sk -o /dev/null -w 'admin_com %{{http_code}}\n' https://admin.nomadro.com/
|
||||
echo PUSH_UGC_SQLITE_US_OK
|
||||
"""
|
||||
_, o, e = c.exec_command(cmd, timeout=180)
|
||||
print(o.read().decode("utf-8", "replace"), flush=True)
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
if err.strip():
|
||||
print("STDERR", err[-3000:], flush=True)
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -1,66 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Restore US social_svc to pre-PB SQLite backup; fetch bak ugc for local enhance."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
US = ("108.174.50.68", "root", "Xiao4669805")
|
||||
OUT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
h, u, p = US
|
||||
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
sftp.get(
|
||||
"/opt/nomadmini/backend/app/services/social_ugc.py.bak-20261104081910",
|
||||
str(OUT / "_tmp_social_ugc_sqlite.py"),
|
||||
)
|
||||
sftp.get(
|
||||
"/opt/nomadmini/backend/app/routers/social_ugc_admin.py.bak-20261104081910",
|
||||
str(OUT / "_tmp_social_ugc_admin_old.py"),
|
||||
)
|
||||
sftp.close()
|
||||
print("downloaded bak ugc", flush=True)
|
||||
|
||||
cmd = r"""
|
||||
set -euo pipefail
|
||||
BAK=$(ls -dt /tmp/social_svc.bak.* | head -1)
|
||||
echo restoring_from "$BAK"
|
||||
rsync -a --delete "$BAK/" /var/www/nomadro.cn/apps/api/services/social_svc/
|
||||
rm -rf /opt/nomadmini/backend/social_svc /opt/nomadmini/backend/services/social_svc
|
||||
systemctl kill -s9 nomadro-social 2>/dev/null || true
|
||||
fuser -k 8020/tcp 2>/dev/null || true
|
||||
sleep 1
|
||||
systemctl reset-failed nomadro-social 2>/dev/null || true
|
||||
systemctl start nomadro-social
|
||||
sleep 2
|
||||
systemctl is-active nomadro-social
|
||||
curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo
|
||||
python3 - <<'PY'
|
||||
import sqlite3
|
||||
db=sqlite3.connect('/var/www/nomadro-data/social/social.db')
|
||||
print('tables', [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1")])
|
||||
for t in ['roster','messages','cafe_reviews','gig_apps','feedback']:
|
||||
try:
|
||||
print(t, db.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0])
|
||||
except Exception as e:
|
||||
print(t, e)
|
||||
PY
|
||||
echo RESTORE_SOCIAL_SQLITE_OK
|
||||
"""
|
||||
_, o, e = c.exec_command(cmd, timeout=120)
|
||||
print(o.read().decode("utf-8", "replace"), flush=True)
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
if err.strip():
|
||||
print("STDERR", err[-2000:], flush=True)
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -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())
|
||||
@ -1,77 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import paramiko
|
||||
|
||||
US = ("108.174.50.68", "root", "Xiao4669805")
|
||||
|
||||
|
||||
def http(url: str, **kw):
|
||||
req = urllib.request.Request(url, **kw)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
body = resp.read().decode("utf-8", "replace")
|
||||
return resp.status, body
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode("utf-8", "replace")
|
||||
except Exception as e:
|
||||
return 0, str(e)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
time.sleep(2)
|
||||
code, body = http("https://admin.nomadro.com/")
|
||||
print("admin_com", code, "Nomadro" in body)
|
||||
code, body = http(
|
||||
"https://api.nomadro.com/api/admin/login",
|
||||
data=json.dumps(
|
||||
{"username": "hackrobot", "password": "Xiao4669805@"}
|
||||
).encode(),
|
||||
headers={"content-type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
print("login", code, body[:160])
|
||||
token = ""
|
||||
try:
|
||||
token = json.loads(body).get("token") or ""
|
||||
except Exception:
|
||||
pass
|
||||
if not token:
|
||||
# remote curl fallback
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
h, u, p = US
|
||||
c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
_, o, e = c.exec_command(
|
||||
r"""
|
||||
systemctl is-active nomadmini-api
|
||||
journalctl -u nomadmini-api -n 40 --no-pager
|
||||
curl -sS -o /tmp/login.json -w 'login %{http_code}\n' --max-time 15 -X POST https://api.nomadro.com/api/admin/login \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"username":"hackrobot","password":"Xiao4669805@"}'
|
||||
head -c 300 /tmp/login.json; echo
|
||||
""",
|
||||
timeout=60,
|
||||
)
|
||||
print(o.read().decode("utf-8", "replace"))
|
||||
print(e.read().decode("utf-8", "replace")[-1500:])
|
||||
c.close()
|
||||
return 1
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
for path in ("overview", "stats", "archives", "messages?limit=5", "roster?limit=5"):
|
||||
c2, b2 = http(
|
||||
f"https://api.nomadro.com/api/admin/social/ugc/{path}",
|
||||
headers=headers,
|
||||
)
|
||||
print(f"ugc/{path}", c2, b2[:220].replace("\n", " "))
|
||||
print("SMOKE_OK")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -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()
|
||||
@ -1,36 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
login = json.loads(
|
||||
urllib.request.urlopen(
|
||||
urllib.request.Request(
|
||||
"https://api.nomadro.com/api/admin/login",
|
||||
data=json.dumps(
|
||||
{"username": "hackrobot", "password": "Xiao4669805@"}
|
||||
).encode(),
|
||||
headers={"content-type": "application/json"},
|
||||
),
|
||||
timeout=20,
|
||||
).read()
|
||||
)
|
||||
tok = login["token"]
|
||||
for p in (
|
||||
"liveness",
|
||||
"reports",
|
||||
"coffee-bookings",
|
||||
"meetup-reviews",
|
||||
"trips",
|
||||
"blocks",
|
||||
"files",
|
||||
):
|
||||
req = urllib.request.Request(
|
||||
f"https://api.nomadro.com/api/admin/social/ugc/{p}?limit=5",
|
||||
headers={"Authorization": f"Bearer {tok}"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
d = json.loads(r.read())
|
||||
print(p, r.status, "total=", d.get("total"), "items=", len(d.get("items") or []))
|
||||
except Exception as e:
|
||||
print(p, getattr(e, "code", None), e)
|
||||
@ -1,869 +0,0 @@
|
||||
"""游民社区 UGC 管理 — 直连 social.db(US 生产;软删除 + social_archives)。
|
||||
|
||||
默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from app.core.sqlite_util import connect as _connect
|
||||
|
||||
_DEFAULT = Path("/var/www/nomadro-data/social/social.db")
|
||||
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve()
|
||||
|
||||
ENTITY_TABLES = {
|
||||
"roster": ("roster", "guest_id"),
|
||||
"messages": ("messages", "id"),
|
||||
"reviews": ("cafe_reviews", "id"),
|
||||
"gigApps": ("gig_apps", "id"),
|
||||
"feedback": ("feedback", "id"),
|
||||
}
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
|
||||
|
||||
|
||||
def _uid(prefix: str = "arc") -> str:
|
||||
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]:
|
||||
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if readonly and SOCIAL_DB_PATH.is_file():
|
||||
uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro"
|
||||
conn = sqlite3.connect(uri, uri=True, timeout=30.0)
|
||||
conn.row_factory = sqlite3.Row
|
||||
else:
|
||||
conn = _connect(SOCIAL_DB_PATH)
|
||||
try:
|
||||
if not readonly:
|
||||
_ensure_schema(conn)
|
||||
yield conn
|
||||
if not readonly:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
if not readonly:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _ensure_schema(conn: sqlite3.Connection) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS social_archives (
|
||||
id TEXT PRIMARY KEY,
|
||||
entity TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
guest_id TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
note TEXT DEFAULT '',
|
||||
payload TEXT DEFAULT '{}',
|
||||
created_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_social_archives_entity ON social_archives(entity, entity_id, created_at)"
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS join_leads (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
guest_id TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '',
|
||||
name TEXT DEFAULT '',
|
||||
paid TEXT DEFAULT '',
|
||||
face_ok TEXT DEFAULT '',
|
||||
liveness_status TEXT DEFAULT '',
|
||||
ua TEXT DEFAULT '',
|
||||
payload TEXT DEFAULT '{}',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_join_leads_email ON join_leads(email)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_join_leads_updated ON join_leads(updated_at)"
|
||||
)
|
||||
# soft-delete markers on live tables (idempotent)
|
||||
for table, _pk in {
|
||||
"roster": "guest_id",
|
||||
"messages": "id",
|
||||
"cafe_reviews": "id",
|
||||
"gig_apps": "id",
|
||||
"feedback": "id",
|
||||
}.items():
|
||||
cols = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
if "deleted_at" not in cols:
|
||||
try:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN deleted_at TEXT")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
if table == "roster" and "status" not in cols:
|
||||
try:
|
||||
conn.execute("ALTER TABLE roster ADD COLUMN status TEXT DEFAULT ''")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
|
||||
def _row_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
|
||||
if row is None:
|
||||
return None
|
||||
return {k: row[k] for k in row.keys()}
|
||||
|
||||
|
||||
def _archive(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
entity: str,
|
||||
entity_id: str,
|
||||
action: str,
|
||||
payload: dict[str, Any] | None,
|
||||
guest_id: str = "",
|
||||
note: str = "",
|
||||
) -> str:
|
||||
aid = _uid("arc")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
aid,
|
||||
entity,
|
||||
entity_id,
|
||||
guest_id or "",
|
||||
action,
|
||||
note or "",
|
||||
json.dumps(payload or {}, ensure_ascii=False),
|
||||
_now(),
|
||||
),
|
||||
)
|
||||
return aid
|
||||
|
||||
|
||||
def _soft_delete(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
entity: str,
|
||||
entity_id: str,
|
||||
table: str,
|
||||
pk: str,
|
||||
guest_id: str = "",
|
||||
) -> bool:
|
||||
row = conn.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
payload = _row_dict(row) or {}
|
||||
if payload.get("deleted_at"):
|
||||
return True
|
||||
_archive(
|
||||
conn,
|
||||
entity=entity,
|
||||
entity_id=entity_id,
|
||||
action="soft_delete",
|
||||
payload=payload,
|
||||
guest_id=guest_id or str(payload.get("guest_id") or ""),
|
||||
)
|
||||
if table == "roster":
|
||||
conn.execute(
|
||||
"UPDATE roster SET deleted_at=?, status='deleted', updated_at=? WHERE guest_id=?",
|
||||
(_now(), _now(), entity_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET deleted_at=? WHERE {pk}=?",
|
||||
(_now(), entity_id),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _alive_clause(alias: str = "") -> str:
|
||||
col = f"{alias}.deleted_at" if alias else "deleted_at"
|
||||
return f"({col} IS NULL OR {col}='')"
|
||||
|
||||
|
||||
def available() -> dict[str, Any]:
|
||||
exists = SOCIAL_DB_PATH.is_file()
|
||||
size = SOCIAL_DB_PATH.stat().st_size if exists else 0
|
||||
writable = False
|
||||
if exists:
|
||||
try:
|
||||
writable = os.access(SOCIAL_DB_PATH, os.W_OK)
|
||||
except Exception:
|
||||
writable = False
|
||||
return {
|
||||
"ok": True,
|
||||
"path": str(SOCIAL_DB_PATH),
|
||||
"exists": exists,
|
||||
"bytes": size,
|
||||
"writable": writable,
|
||||
"backend": "sqlite",
|
||||
}
|
||||
|
||||
|
||||
def overview() -> dict[str, Any]:
|
||||
info = available()
|
||||
counts = {
|
||||
"messages": 0,
|
||||
"roster": 0,
|
||||
"reviews": 0,
|
||||
"gigApps": 0,
|
||||
"feedback": 0,
|
||||
}
|
||||
if not info["exists"]:
|
||||
return {**info, "counts": counts}
|
||||
try:
|
||||
with _db() as c:
|
||||
counts["messages"] = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM messages WHERE {_alive_clause()}"
|
||||
).fetchone()["n"]
|
||||
counts["roster"] = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'"
|
||||
).fetchone()["n"]
|
||||
counts["reviews"] = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM cafe_reviews WHERE {_alive_clause()}"
|
||||
).fetchone()["n"]
|
||||
counts["gigApps"] = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM gig_apps WHERE {_alive_clause()}"
|
||||
).fetchone()["n"]
|
||||
counts["feedback"] = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM feedback WHERE {_alive_clause()}"
|
||||
).fetchone()["n"]
|
||||
except Exception as e:
|
||||
return {**info, "counts": counts, "error": str(e)}
|
||||
return {**info, "counts": counts}
|
||||
|
||||
|
||||
def list_messages(
|
||||
*,
|
||||
channel_id: str = "",
|
||||
q: str = "",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> dict[str, Any]:
|
||||
limit = max(1, min(int(limit or 100), 500))
|
||||
offset = max(0, int(offset or 0))
|
||||
clauses: list[str] = [_alive_clause()]
|
||||
params: list[Any] = []
|
||||
if channel_id.strip():
|
||||
clauses.append("channel_id=?")
|
||||
params.append(channel_id.strip())
|
||||
if q.strip():
|
||||
clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)")
|
||||
like = f"%{q.strip()}%"
|
||||
params.extend([like, like, like])
|
||||
where = f" WHERE {' AND '.join(clauses)}"
|
||||
with _db() as c:
|
||||
total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT id, channel_id, author, text, guest_id, created_at, deleted_at
|
||||
FROM messages{where}
|
||||
ORDER BY created_at DESC, rowid DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(*params, limit, offset),
|
||||
).fetchall()
|
||||
items = [
|
||||
{
|
||||
"id": r["id"],
|
||||
"channelId": r["channel_id"],
|
||||
"author": r["author"],
|
||||
"text": r["text"],
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
|
||||
|
||||
def delete_message(message_id: str) -> bool:
|
||||
with _db() as c:
|
||||
return _soft_delete(
|
||||
c, entity="messages", entity_id=message_id, table="messages", pk="id"
|
||||
)
|
||||
|
||||
|
||||
def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
limit = max(1, min(int(limit or 100), 500))
|
||||
offset = max(0, int(offset or 0))
|
||||
clauses: list[str] = [_alive_clause(), "IFNULL(status,'')!='deleted'"]
|
||||
params: list[Any] = []
|
||||
if q.strip():
|
||||
clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)")
|
||||
like = f"%{q.strip()}%"
|
||||
params.extend([like, like, like, like, like])
|
||||
where = f" WHERE {' AND '.join(clauses)}"
|
||||
with _db() as c:
|
||||
total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at, status, deleted_at
|
||||
FROM roster{where}
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(*params, limit, offset),
|
||||
).fetchall()
|
||||
items = [
|
||||
{
|
||||
"guestId": r["guest_id"],
|
||||
"name": r["name"],
|
||||
"title": r["title"] or "",
|
||||
"city": r["city"] or "",
|
||||
"phone": r["phone"] or "",
|
||||
"linktree": r["linktree"] or "",
|
||||
"skills": r["skills"] or "",
|
||||
"bio": r["bio"] or "",
|
||||
"updatedAt": r["updated_at"],
|
||||
"status": r["status"] or "",
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
|
||||
|
||||
def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
|
||||
with _db() as c:
|
||||
row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
restore = bool(patch.get("restore"))
|
||||
fields = {
|
||||
"name": str(patch.get("name", row["name"] or ""))[:64] or "游民",
|
||||
"title": str(patch.get("title", row["title"] or ""))[:80],
|
||||
"city": str(patch.get("city", row["city"] or ""))[:64],
|
||||
"phone": str(patch.get("phone", row["phone"] or ""))[:32],
|
||||
"linktree": str(patch.get("linktree", row["linktree"] or ""))[:240],
|
||||
"skills": str(patch.get("skills", row["skills"] or ""))[:200],
|
||||
"bio": str(patch.get("bio", row["bio"] or ""))[:2000],
|
||||
}
|
||||
status = str(patch.get("status", row["status"] if "status" in row.keys() else "") or "")
|
||||
deleted_at = row["deleted_at"] if "deleted_at" in row.keys() else None
|
||||
if restore:
|
||||
status = ""
|
||||
deleted_at = None
|
||||
_archive(
|
||||
c,
|
||||
entity="roster",
|
||||
entity_id=guest_id,
|
||||
action="restore",
|
||||
payload=_row_dict(row),
|
||||
guest_id=guest_id,
|
||||
)
|
||||
updated = _now()
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?,
|
||||
status=?, deleted_at=?, updated_at=?
|
||||
WHERE guest_id=?
|
||||
""",
|
||||
(
|
||||
fields["name"],
|
||||
fields["title"],
|
||||
fields["city"],
|
||||
fields["phone"],
|
||||
fields["linktree"],
|
||||
fields["skills"],
|
||||
fields["bio"],
|
||||
status,
|
||||
deleted_at,
|
||||
updated,
|
||||
guest_id,
|
||||
),
|
||||
)
|
||||
_archive(
|
||||
c,
|
||||
entity="roster",
|
||||
entity_id=guest_id,
|
||||
action="update",
|
||||
payload={**fields, "status": status},
|
||||
guest_id=guest_id,
|
||||
)
|
||||
return {
|
||||
**fields,
|
||||
"guestId": guest_id,
|
||||
"updatedAt": updated,
|
||||
"status": status,
|
||||
}
|
||||
|
||||
|
||||
def delete_roster(guest_id: str) -> bool:
|
||||
with _db() as c:
|
||||
return _soft_delete(
|
||||
c,
|
||||
entity="roster",
|
||||
entity_id=guest_id,
|
||||
table="roster",
|
||||
pk="guest_id",
|
||||
guest_id=guest_id,
|
||||
)
|
||||
|
||||
|
||||
def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
limit = max(1, min(int(limit or 100), 500))
|
||||
offset = max(0, int(offset or 0))
|
||||
clauses: list[str] = [_alive_clause()]
|
||||
params: list[Any] = []
|
||||
if cafe_id.strip():
|
||||
clauses.append("cafe_id=?")
|
||||
params.append(cafe_id.strip())
|
||||
where = f" WHERE {' AND '.join(clauses)}"
|
||||
with _db() as c:
|
||||
total = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params)
|
||||
).fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at
|
||||
FROM cafe_reviews{where}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(*params, limit, offset),
|
||||
).fetchall()
|
||||
items = [
|
||||
{
|
||||
"id": r["id"],
|
||||
"cafeId": r["cafe_id"],
|
||||
"author": r["author"],
|
||||
"score": r["score"],
|
||||
"text": r["text"],
|
||||
"photoNote": r["photo_note"] or "",
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
|
||||
|
||||
def delete_review(review_id: str) -> bool:
|
||||
with _db() as c:
|
||||
return _soft_delete(
|
||||
c, entity="reviews", entity_id=review_id, table="cafe_reviews", pk="id"
|
||||
)
|
||||
|
||||
|
||||
def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
limit = max(1, min(int(limit or 100), 500))
|
||||
offset = max(0, int(offset or 0))
|
||||
clauses: list[str] = [_alive_clause()]
|
||||
params: list[Any] = []
|
||||
if gig_id.strip():
|
||||
clauses.append("gig_id=?")
|
||||
params.append(gig_id.strip())
|
||||
where = f" WHERE {' AND '.join(clauses)}"
|
||||
with _db() as c:
|
||||
total = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params)
|
||||
).fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT id, gig_id, name, contact, note, guest_id, created_at
|
||||
FROM gig_apps{where}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(*params, limit, offset),
|
||||
).fetchall()
|
||||
items = [
|
||||
{
|
||||
"id": r["id"],
|
||||
"gigId": r["gig_id"],
|
||||
"name": r["name"],
|
||||
"contact": r["contact"],
|
||||
"note": r["note"] or "",
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
|
||||
|
||||
def delete_gig_app(app_id: str) -> bool:
|
||||
with _db() as c:
|
||||
return _soft_delete(
|
||||
c, entity="gigApps", entity_id=app_id, table="gig_apps", pk="id"
|
||||
)
|
||||
|
||||
|
||||
def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
limit = max(1, min(int(limit or 100), 500))
|
||||
offset = max(0, int(offset or 0))
|
||||
where = f" WHERE {_alive_clause()}"
|
||||
with _db() as c:
|
||||
total = c.execute(f"SELECT COUNT(*) AS n FROM feedback{where}").fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT id, kind, text, contact, guest_id, created_at
|
||||
FROM feedback{where}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(limit, offset),
|
||||
).fetchall()
|
||||
items = [
|
||||
{
|
||||
"id": r["id"],
|
||||
"kind": r["kind"],
|
||||
"text": r["text"],
|
||||
"contact": r["contact"] or "",
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
|
||||
|
||||
def delete_feedback(fid: str) -> bool:
|
||||
with _db() as c:
|
||||
return _soft_delete(
|
||||
c, entity="feedback", entity_id=fid, table="feedback", pk="id"
|
||||
)
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
with _db() as c:
|
||||
def cnt(sql: str) -> int:
|
||||
return int(c.execute(sql).fetchone()[0])
|
||||
|
||||
counts = {
|
||||
"messages": cnt(f"SELECT COUNT(*) FROM messages WHERE {_alive_clause()}"),
|
||||
"roster": cnt(
|
||||
f"SELECT COUNT(*) FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'"
|
||||
),
|
||||
"reviews": cnt(f"SELECT COUNT(*) FROM cafe_reviews WHERE {_alive_clause()}"),
|
||||
"gigApps": cnt(f"SELECT COUNT(*) FROM gig_apps WHERE {_alive_clause()}"),
|
||||
"feedback": cnt(f"SELECT COUNT(*) FROM feedback WHERE {_alive_clause()}"),
|
||||
"archives": cnt("SELECT COUNT(*) FROM social_archives"),
|
||||
}
|
||||
soft = {
|
||||
"roster": cnt(
|
||||
"SELECT COUNT(*) FROM roster WHERE (deleted_at IS NOT NULL AND deleted_at!='') OR status='deleted'"
|
||||
),
|
||||
"messages": cnt(
|
||||
"SELECT COUNT(*) FROM messages WHERE deleted_at IS NOT NULL AND deleted_at!=''"
|
||||
),
|
||||
"reviews": cnt(
|
||||
"SELECT COUNT(*) FROM cafe_reviews WHERE deleted_at IS NOT NULL AND deleted_at!=''"
|
||||
),
|
||||
"gigApps": cnt(
|
||||
"SELECT COUNT(*) FROM gig_apps WHERE deleted_at IS NOT NULL AND deleted_at!=''"
|
||||
),
|
||||
"feedback": cnt(
|
||||
"SELECT COUNT(*) FROM feedback WHERE deleted_at IS NOT NULL AND deleted_at!=''"
|
||||
),
|
||||
}
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT IFNULL(NULLIF(TRIM(city),''),'未填') AS city, COUNT(*) AS n
|
||||
FROM roster
|
||||
WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'
|
||||
GROUP BY 1
|
||||
ORDER BY n DESC
|
||||
LIMIT 12
|
||||
"""
|
||||
).fetchall()
|
||||
by_city = [{"name": r["city"], "value": int(r["n"])} for r in rows]
|
||||
day_rows = c.execute(
|
||||
f"""
|
||||
SELECT substr(updated_at,1,10) AS d, COUNT(*) AS n
|
||||
FROM roster
|
||||
WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'
|
||||
AND updated_at IS NOT NULL AND updated_at!=''
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
"""
|
||||
).fetchall()
|
||||
day_series = [{"date": r["d"], "value": int(r["n"])} for r in day_rows][-30:]
|
||||
return {
|
||||
"ok": True,
|
||||
"counts": counts,
|
||||
"softDeleted": soft,
|
||||
"activeRoster": counts["roster"],
|
||||
"byCity": by_city,
|
||||
"rosterByDay": day_series,
|
||||
"backend": "sqlite",
|
||||
}
|
||||
|
||||
|
||||
def get_detail(entity: str, entity_id: str) -> dict[str, Any] | None:
|
||||
meta = ENTITY_TABLES.get(entity)
|
||||
if not meta:
|
||||
return None
|
||||
table, pk = meta
|
||||
with _db() as c:
|
||||
row = c.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
item = _row_dict(row) or {}
|
||||
hist = c.execute(
|
||||
"""
|
||||
SELECT id, action, note, payload, created_at
|
||||
FROM social_archives
|
||||
WHERE entity=? AND entity_id=?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(entity, entity_id),
|
||||
).fetchall()
|
||||
soft = bool(item.get("deleted_at")) or item.get("status") == "deleted"
|
||||
history = []
|
||||
for h in hist:
|
||||
try:
|
||||
payload = json.loads(h["payload"] or "{}")
|
||||
except Exception:
|
||||
payload = {}
|
||||
history.append(
|
||||
{
|
||||
"id": h["id"],
|
||||
"action": h["action"],
|
||||
"at": h["created_at"],
|
||||
"note": h["note"] or "",
|
||||
"payload": payload,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"entity": entity,
|
||||
"id": entity_id,
|
||||
"item": item,
|
||||
"softDeleted": soft,
|
||||
"history": history,
|
||||
}
|
||||
|
||||
|
||||
def upsert_join_lead(
|
||||
*,
|
||||
email: str,
|
||||
guest_id: str = "",
|
||||
stage: str = "email_submit",
|
||||
name: str = "",
|
||||
payload: dict[str, Any] | None = None,
|
||||
ua: str = "",
|
||||
paid: str = "",
|
||||
face_ok: str = "",
|
||||
liveness_status: str = "",
|
||||
) -> dict[str, Any]:
|
||||
email_n = (email or "").strip().lower()[:160]
|
||||
if not email_n or "@" not in email_n:
|
||||
raise ValueError("invalid email")
|
||||
now = _now()
|
||||
stage_n = (stage or "email_submit")[:48]
|
||||
body = payload if isinstance(payload, dict) else {}
|
||||
with _db() as c:
|
||||
existing = c.execute(
|
||||
"SELECT * FROM join_leads WHERE email=?", (email_n,)
|
||||
).fetchone()
|
||||
if existing:
|
||||
new_payload = {}
|
||||
try:
|
||||
new_payload = json.loads(existing["payload"] or "{}")
|
||||
except Exception:
|
||||
new_payload = {}
|
||||
if isinstance(new_payload, dict):
|
||||
stages = list(new_payload.get("stages") or [])
|
||||
if stage_n not in stages:
|
||||
stages.append(stage_n)
|
||||
new_payload = {**new_payload, **body, "stages": stages}
|
||||
else:
|
||||
new_payload = {**body, "stages": [stage_n]}
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE join_leads SET
|
||||
guest_id=COALESCE(NULLIF(?,''), guest_id),
|
||||
stage=?,
|
||||
name=COALESCE(NULLIF(?,''), name),
|
||||
paid=COALESCE(NULLIF(?,''), paid),
|
||||
face_ok=COALESCE(NULLIF(?,''), face_ok),
|
||||
liveness_status=COALESCE(NULLIF(?,''), liveness_status),
|
||||
ua=COALESCE(NULLIF(?,''), ua),
|
||||
payload=?,
|
||||
updated_at=?
|
||||
WHERE email=?
|
||||
""",
|
||||
(
|
||||
(guest_id or "")[:120],
|
||||
stage_n,
|
||||
(name or "")[:64],
|
||||
(paid or "")[:8],
|
||||
(face_ok or "")[:8],
|
||||
(liveness_status or "")[:24],
|
||||
(ua or "")[:240],
|
||||
json.dumps(new_payload, ensure_ascii=False),
|
||||
now,
|
||||
email_n,
|
||||
),
|
||||
)
|
||||
rid = existing["id"]
|
||||
else:
|
||||
rid = _uid("jl")
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO join_leads(
|
||||
id, email, guest_id, stage, name, paid, face_ok, liveness_status,
|
||||
ua, payload, created_at, updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
rid,
|
||||
email_n,
|
||||
(guest_id or "")[:120],
|
||||
stage_n,
|
||||
(name or "")[:64],
|
||||
(paid or "")[:8],
|
||||
(face_ok or "")[:8],
|
||||
(liveness_status or "")[:24],
|
||||
(ua or "")[:240],
|
||||
json.dumps({**body, "stages": [stage_n]}, ensure_ascii=False),
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
# also archive snapshot
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at)
|
||||
VALUES (?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
_uid("arc"),
|
||||
"join_leads",
|
||||
email_n,
|
||||
(guest_id or "")[:120],
|
||||
stage_n,
|
||||
f"join:{stage_n}",
|
||||
json.dumps(
|
||||
{
|
||||
"email": email_n,
|
||||
"guestId": guest_id,
|
||||
"stage": stage_n,
|
||||
"name": name,
|
||||
"paid": paid,
|
||||
"faceOk": face_ok,
|
||||
"livenessStatus": liveness_status,
|
||||
"ua": ua,
|
||||
"payload": body,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
now,
|
||||
),
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"id": rid,
|
||||
"email": email_n,
|
||||
"guestId": guest_id,
|
||||
"stage": stage_n,
|
||||
"at": now,
|
||||
}
|
||||
|
||||
|
||||
def list_join_leads(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
lim = max(1, min(int(limit or 100), 500))
|
||||
off = max(0, int(offset or 0))
|
||||
needle = (q or "").strip().lower()
|
||||
with _db(readonly=True) as c:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM join_leads ORDER BY updated_at DESC"
|
||||
).fetchall()
|
||||
items = []
|
||||
for r in rows:
|
||||
try:
|
||||
payload = json.loads(r["payload"] or "{}")
|
||||
except Exception:
|
||||
payload = {}
|
||||
item = {
|
||||
"id": r["id"],
|
||||
"email": r["email"] or "",
|
||||
"guestId": r["guest_id"] or "",
|
||||
"stage": r["stage"] or "",
|
||||
"name": r["name"] or "",
|
||||
"paid": r["paid"] or "",
|
||||
"faceOk": r["face_ok"] or "",
|
||||
"livenessStatus": r["liveness_status"] or "",
|
||||
"ua": r["ua"] or "",
|
||||
"payload": payload,
|
||||
"createdAt": r["created_at"] or "",
|
||||
"updatedAt": r["updated_at"] or "",
|
||||
}
|
||||
if needle:
|
||||
blob = " ".join(
|
||||
[
|
||||
item["email"],
|
||||
item["guestId"],
|
||||
item["name"],
|
||||
item["stage"],
|
||||
]
|
||||
).lower()
|
||||
if needle not in blob:
|
||||
continue
|
||||
items.append(item)
|
||||
total = len(items)
|
||||
return {"ok": True, "total": total, "items": items[off : off + lim]}
|
||||
|
||||
|
||||
def list_archives(
|
||||
*, entity: str = "", limit: int = 100, offset: int = 0
|
||||
) -> dict[str, Any]:
|
||||
lim = max(1, min(int(limit or 100), 500))
|
||||
off = max(0, int(offset or 0))
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if entity.strip():
|
||||
clauses.append("entity=?")
|
||||
params.append(entity.strip())
|
||||
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
with _db() as c:
|
||||
total = c.execute(
|
||||
f"SELECT COUNT(*) AS n FROM social_archives{where}", tuple(params)
|
||||
).fetchone()["n"]
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT id, entity, entity_id, guest_id, action, note, payload, created_at
|
||||
FROM social_archives{where}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(*params, lim, off),
|
||||
).fetchall()
|
||||
items = []
|
||||
for r in rows:
|
||||
try:
|
||||
payload = json.loads(r["payload"] or "{}")
|
||||
except Exception:
|
||||
payload = {}
|
||||
items.append(
|
||||
{
|
||||
"id": r["id"],
|
||||
"entity": r["entity"],
|
||||
"entityId": r["entity_id"],
|
||||
"guestId": r["guest_id"] or "",
|
||||
"action": r["action"],
|
||||
"note": r["note"] or "",
|
||||
"at": r["created_at"],
|
||||
"payload": payload,
|
||||
}
|
||||
)
|
||||
return {"ok": True, "total": total, "items": items}
|
||||
@ -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()
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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()
|
||||
@ -1,547 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""vip.hackrobot.cn track sidecar — SQLite + ntfy, isolated from VIP business."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
PORT = int(os.environ.get("VIP_TRACK_PORT", "4011"))
|
||||
BASE_DIR = Path(os.environ.get("VIP_TRACK_DIR", "/opt/vip-track"))
|
||||
DB_PATH = Path(os.environ.get("VIP_TRACK_DB", str(BASE_DIR / "events.db")))
|
||||
ENV_FILE = BASE_DIR / "ntfy.env"
|
||||
|
||||
def _load_env_file() -> None:
|
||||
if not ENV_FILE.exists():
|
||||
return
|
||||
try:
|
||||
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
k, v = k.strip(), v.strip().strip('"').strip("'")
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = v
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_load_env_file()
|
||||
|
||||
NTFY_BASE = os.environ.get("NTFY_BASE_URL", "https://ntfy.nomadro.cn").rstrip("/")
|
||||
NTFY_TOPIC = (os.environ.get("NTFY_TOPIC") or "vip-hackrobot").strip().strip("/")
|
||||
NTFY_TOKEN = (os.environ.get("NTFY_TOKEN") or "").strip()
|
||||
|
||||
# health_down/up 只由 cron healthcheck.sh 推一次,避免 sidecar 再推「用户 ·」重复刷屏
|
||||
NTFY_EVENTS = {
|
||||
"session_start",
|
||||
"page_view",
|
||||
"btn_click",
|
||||
"pay_start",
|
||||
"pay_success",
|
||||
"pay_cancel",
|
||||
"pay_fail",
|
||||
"pay_pending",
|
||||
"login_ok",
|
||||
"login_fail",
|
||||
"login_submit",
|
||||
"error",
|
||||
"web_vital_slow",
|
||||
}
|
||||
# 访问类:会话内去重,避免同人刷屏
|
||||
VISIT_EVENTS = {"session_start", "page_view"}
|
||||
TITLE = {
|
||||
"session_start": "用户访问",
|
||||
"page_view": "浏览页面",
|
||||
"btn_click": "点击",
|
||||
"pay_start": "拉起支付",
|
||||
"pay_success": "支付成功",
|
||||
"pay_cancel": "取消支付",
|
||||
"pay_fail": "支付失败",
|
||||
"pay_pending": "支付确认中",
|
||||
"login_ok": "登录成功",
|
||||
"login_fail": "登录失败",
|
||||
"login_submit": "提交登录",
|
||||
"error": "前端异常",
|
||||
"health_down": "站点异常",
|
||||
"health_up": "站点恢复",
|
||||
"web_vital_slow": "性能偏慢",
|
||||
}
|
||||
TAGS = {
|
||||
"session_start": "eyes,globe_with_meridians",
|
||||
"page_view": "eyes,globe_with_meridians",
|
||||
"btn_click": "point_right,globe_with_meridians",
|
||||
"pay_start": "credit_card,globe_with_meridians",
|
||||
"pay_success": "moneybag,tada,globe_with_meridians",
|
||||
"pay_cancel": "wave,globe_with_meridians",
|
||||
"pay_fail": "warning,x,globe_with_meridians",
|
||||
"pay_pending": "hourglass,globe_with_meridians",
|
||||
"login_ok": "key,globe_with_meridians",
|
||||
"login_fail": "key,warning,globe_with_meridians",
|
||||
"login_submit": "key,globe_with_meridians",
|
||||
"error": "rotating_light,globe_with_meridians",
|
||||
"health_down": "rotating_light,skull",
|
||||
"health_up": "white_check_mark,tada",
|
||||
"web_vital_slow": "snail,chart_with_downwards_trend",
|
||||
}
|
||||
PRIORITY = {
|
||||
"pay_success": "5",
|
||||
"pay_fail": "5",
|
||||
"health_down": "5",
|
||||
"pay_start": "4",
|
||||
"login_fail": "4",
|
||||
"error": "4",
|
||||
"session_start": "3",
|
||||
"page_view": "2",
|
||||
"btn_click": "2",
|
||||
"health_up": "3",
|
||||
"web_vital_slow": "3",
|
||||
}
|
||||
|
||||
_times: list[float] = []
|
||||
_visit_times: list[float] = []
|
||||
_seen_visit: dict[str, float] = {}
|
||||
MAX_PER_MIN = 40
|
||||
MAX_VISIT_PER_MIN = 20
|
||||
VISIT_DEDUP_SEC = 600 # 同 session+事件+页 10 分钟内只推一次
|
||||
_db_lock = threading.Lock()
|
||||
_stats = {"received": 0, "stored": 0, "notified": 0, "ntfy_fail": 0, "started": time.time(), "last_ntfy_err": ""}
|
||||
|
||||
|
||||
def budget_ok(visit: bool = False) -> bool:
|
||||
now = time.time()
|
||||
while _times and _times[0] < now - 60:
|
||||
_times.pop(0)
|
||||
if len(_times) >= MAX_PER_MIN:
|
||||
return False
|
||||
if visit:
|
||||
while _visit_times and _visit_times[0] < now - 60:
|
||||
_visit_times.pop(0)
|
||||
if len(_visit_times) >= MAX_VISIT_PER_MIN:
|
||||
return False
|
||||
_visit_times.append(now)
|
||||
_times.append(now)
|
||||
return True
|
||||
|
||||
|
||||
def visit_dedup_ok(key: str) -> bool:
|
||||
now = time.time()
|
||||
# prune
|
||||
dead = [k for k, t in _seen_visit.items() if now - t > VISIT_DEDUP_SEC]
|
||||
for k in dead:
|
||||
_seen_visit.pop(k, None)
|
||||
if key in _seen_visit:
|
||||
return False
|
||||
_seen_visit[key] = now
|
||||
return True
|
||||
|
||||
|
||||
def short_uid(u: str) -> str:
|
||||
u = (u or "").strip()
|
||||
if not u:
|
||||
return "-"
|
||||
return ("…" + u[-8:]) if len(u) > 10 else u
|
||||
|
||||
|
||||
def role_of(props: dict, identity: dict | None = None) -> tuple[str, str]:
|
||||
"""Return (role_key, role_cn). Prefer props from browser localStorage paidType."""
|
||||
identity = identity or {}
|
||||
role = str(props.get("role") or identity.get("role") or "").strip().lower()
|
||||
paid = str(props.get("paid_type") or identity.get("paid_type") or "").strip().lower()
|
||||
role_cn = str(props.get("role_cn") or identity.get("role_cn") or "").strip()
|
||||
if role == "vip" or paid == "vip":
|
||||
return "vip", role_cn or "会员VIP"
|
||||
return "guest", role_cn or "普通访客"
|
||||
|
||||
|
||||
def fmt_secs(ms) -> str:
|
||||
try:
|
||||
v = int(ms or 0)
|
||||
except Exception:
|
||||
v = 0
|
||||
if v <= 0:
|
||||
return "-"
|
||||
s = v // 1000
|
||||
if s < 60:
|
||||
return "%ds" % s
|
||||
return "%dm%ds" % (s // 60, s % 60)
|
||||
|
||||
|
||||
def _md_esc(v: object, limit: int = 160) -> str:
|
||||
s = str(v if v is not None else "-").replace("|", "\\|").replace("\n", " ").strip()
|
||||
return s[:limit] or "-"
|
||||
|
||||
|
||||
def build_rich_message(
|
||||
*,
|
||||
ntfy_name: str,
|
||||
openid: str,
|
||||
session: str,
|
||||
page: str,
|
||||
label: str,
|
||||
props: dict,
|
||||
ip: str,
|
||||
identity: dict | None,
|
||||
) -> tuple[str, str, str, str, str]:
|
||||
"""title, markdown message, tags, priority, click_url — 详情尽量完整。"""
|
||||
role, role_cn = role_of(props, identity)
|
||||
crown = "👑会员" if role == "vip" else "👤访客"
|
||||
action = TITLE.get(ntfy_name, ntfy_name)
|
||||
who = "VIP" if role == "vip" else "访客"
|
||||
title = "[WebVIP] / [%s] %s" % (who, action)
|
||||
|
||||
email = str(props.get("email") or (identity or {}).get("email") or "").strip()
|
||||
name = str(props.get("name") or (identity or {}).get("name") or "").strip()
|
||||
user_id = str(props.get("user_id") or (identity or {}).get("user_id") or openid or "").strip()
|
||||
device = str(props.get("device") or "-")
|
||||
browser = str(props.get("browser") or "-")
|
||||
screen = str(props.get("screen") or "-")
|
||||
lang = str(props.get("lang") or "-")
|
||||
tz = str(props.get("tz") or "-")
|
||||
href = str(props.get("href") or "").strip()
|
||||
ref = str(props.get("ref") or "").strip()
|
||||
doc_title = str(props.get("title") or "").strip()
|
||||
click_text = str(props.get("text") or label or "").strip()
|
||||
el = str(props.get("el") or "").strip()
|
||||
ua = str(props.get("ua") or "").strip()
|
||||
alive = fmt_secs(props.get("alive_ms"))
|
||||
paid = props.get("paid_type") or (identity or {}).get("paid_type") or "guest"
|
||||
|
||||
lines = [
|
||||
"### %s · %s" % (crown, _md_esc(action, 80)),
|
||||
"",
|
||||
"- **站点** `vip.hackrobot.cn`",
|
||||
"- **身份** `%s` · paidType=`%s`" % (_md_esc(role_cn, 40), _md_esc(paid, 40)),
|
||||
"- **用户ID** `%s`" % _md_esc(user_id or "-"),
|
||||
"- **昵称** `%s`" % _md_esc(name or "-"),
|
||||
"- **邮箱** `%s`" % _md_esc(email or "-"),
|
||||
"- **页面** `%s`" % _md_esc(page or "/"),
|
||||
"- **标题** %s" % _md_esc(doc_title or "-"),
|
||||
"- **动作** %s" % _md_esc(label or "-"),
|
||||
"- **时间** `%s`" % time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"",
|
||||
"| 字段 | 值 |",
|
||||
"| --- | --- |",
|
||||
"| 设备 | `%s / %s / %s` |" % (_md_esc(device, 40), _md_esc(browser, 40), _md_esc(screen, 40)),
|
||||
"| 语言/时区 | `%s` / `%s` |" % (_md_esc(lang, 40), _md_esc(tz, 40)),
|
||||
"| IP | `%s` |" % _md_esc(ip or "-", 64),
|
||||
"| 会话 | `%s` |" % _md_esc(session or "-", 48),
|
||||
"| 停留 | `%s` |" % _md_esc(alive, 24),
|
||||
]
|
||||
if click_text and ntfy_name in ("btn_click", "pay_start", "login_submit"):
|
||||
lines.append("| 点击文案 | %s |" % _md_esc(click_text, 120))
|
||||
if el:
|
||||
lines.append("| 元素 | `<%s>` |" % _md_esc(el, 40))
|
||||
if href:
|
||||
lines.append("| URL | %s |" % _md_esc(href, 160))
|
||||
lines.append("")
|
||||
lines.append("[打开来源页](%s)" % href[:400])
|
||||
if ref:
|
||||
lines.append("| 来源 | %s |" % _md_esc(ref, 140))
|
||||
if props.get("ms"):
|
||||
lines.append("| 性能 | `%sms` |" % _md_esc(props.get("ms"), 24))
|
||||
if ua:
|
||||
lines.append("| UA | `%s` |" % _md_esc(ua, 140))
|
||||
|
||||
tags = TAGS.get(ntfy_name, "bar_chart,globe_with_meridians")
|
||||
if role == "vip":
|
||||
tags = "crown," + tags
|
||||
else:
|
||||
tags = "bust_in_silhouette," + tags
|
||||
pri = PRIORITY.get(ntfy_name, "3")
|
||||
if role == "vip" and ntfy_name in ("pay_start", "pay_success", "session_start"):
|
||||
try:
|
||||
pri = str(max(int(pri), 4))
|
||||
except Exception:
|
||||
pass
|
||||
click = href if href.startswith("http") else "https://vip.hackrobot.cn/"
|
||||
return title, "\n".join(lines), tags, pri, click
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
BASE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with _db_lock:
|
||||
con = sqlite3.connect(str(DB_PATH))
|
||||
try:
|
||||
con.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts REAL NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
page TEXT,
|
||||
label TEXT,
|
||||
openid TEXT,
|
||||
session TEXT,
|
||||
client TEXT,
|
||||
props TEXT,
|
||||
ip TEXT,
|
||||
notified INTEGER DEFAULT 0
|
||||
)
|
||||
"""
|
||||
)
|
||||
con.execute("CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts)")
|
||||
con.execute("CREATE INDEX IF NOT EXISTS idx_events_name ON events(name)")
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def store_event(
|
||||
*,
|
||||
name: str,
|
||||
page: str,
|
||||
label: str,
|
||||
openid: str,
|
||||
session: str,
|
||||
client: str,
|
||||
props: dict,
|
||||
ip: str,
|
||||
notified: int,
|
||||
) -> None:
|
||||
with _db_lock:
|
||||
con = sqlite3.connect(str(DB_PATH), timeout=2)
|
||||
try:
|
||||
con.execute(
|
||||
"INSERT INTO events(ts,name,page,label,openid,session,client,props,ip,notified) VALUES(?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
time.time(),
|
||||
name,
|
||||
page,
|
||||
label,
|
||||
openid,
|
||||
session,
|
||||
client,
|
||||
json.dumps(props, ensure_ascii=False)[:2000],
|
||||
ip,
|
||||
notified,
|
||||
),
|
||||
)
|
||||
con.commit()
|
||||
_stats["stored"] += 1
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def stats_summary() -> dict:
|
||||
out = dict(_stats)
|
||||
out["uptime_s"] = int(time.time() - _stats["started"])
|
||||
out["ntfy_base"] = NTFY_BASE
|
||||
out["ntfy_topic"] = NTFY_TOPIC
|
||||
out["ntfy_token_set"] = bool(NTFY_TOKEN)
|
||||
with _db_lock:
|
||||
con = sqlite3.connect(str(DB_PATH), timeout=2)
|
||||
try:
|
||||
row = con.execute("SELECT COUNT(*) FROM events").fetchone()
|
||||
out["events_total"] = int(row[0] if row else 0)
|
||||
recent = con.execute(
|
||||
"SELECT name, COUNT(*) FROM events WHERE ts > ? GROUP BY name ORDER BY COUNT(*) DESC LIMIT 12",
|
||||
(time.time() - 86400,),
|
||||
).fetchall()
|
||||
out["last_24h"] = {k: v for k, v in recent}
|
||||
except Exception as e:
|
||||
out["db_error"] = str(e)[:120]
|
||||
finally:
|
||||
con.close()
|
||||
return out
|
||||
|
||||
|
||||
def publish(
|
||||
title: str,
|
||||
message: str,
|
||||
tags: str,
|
||||
priority: str,
|
||||
click: str = "",
|
||||
) -> bool:
|
||||
if not NTFY_BASE or not NTFY_TOPIC:
|
||||
return False
|
||||
url = "%s/" % NTFY_BASE.rstrip("/")
|
||||
try:
|
||||
pri = max(1, min(5, int(priority or 3)))
|
||||
except Exception:
|
||||
pri = 3
|
||||
click_url = (click or "").strip()[:512]
|
||||
payload = {
|
||||
"topic": NTFY_TOPIC.strip().strip("/"),
|
||||
"title": (title or "WebVIP")[:200],
|
||||
"message": (message or "")[:3900],
|
||||
"priority": pri,
|
||||
"markdown": True,
|
||||
"tags": [t.strip() for t in (tags or "").split(",") if t.strip()][:12],
|
||||
"icon": "https://nomadro.com/icon-192.png",
|
||||
}
|
||||
if click_url:
|
||||
payload["click"] = click_url
|
||||
payload["actions"] = [
|
||||
{"action": "view", "label": "打开页面", "url": click_url, "clear": True},
|
||||
{
|
||||
"action": "view",
|
||||
"label": "VIP 首页",
|
||||
"url": "https://vip.hackrobot.cn/",
|
||||
"clear": True,
|
||||
},
|
||||
]
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if NTFY_TOKEN:
|
||||
headers["Authorization"] = "Bearer " + NTFY_TOKEN
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=6) as resp:
|
||||
resp.read(64)
|
||||
return True
|
||||
except Exception as e:
|
||||
_stats["ntfy_fail"] += 1
|
||||
_stats["last_ntfy_err"] = ("%s: %s" % (type(e).__name__, e))[:200]
|
||||
return False
|
||||
|
||||
|
||||
def maybe_ntfy_name(name: str, props: dict) -> str | None:
|
||||
if name in NTFY_EVENTS:
|
||||
return name
|
||||
# promote slow vitals
|
||||
if name == "web_vital" and (props.get("slow") in (1, "1", True) or int(props.get("ms") or 0) > 4000):
|
||||
return "web_vital_slow"
|
||||
return None
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, fmt, *args):
|
||||
return
|
||||
|
||||
def _cors(self):
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
def _json(self, code: int, obj: dict):
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self._cors()
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_OPTIONS(self):
|
||||
self.send_response(204)
|
||||
self._cors()
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
path = (self.path or "/").split("?", 1)[0]
|
||||
if path in ("/stats", "/api/track/stats"):
|
||||
# localhost-ish only
|
||||
ip = self.client_address[0] if self.client_address else ""
|
||||
if ip not in ("127.0.0.1", "::1"):
|
||||
self._json(403, {"ok": False, "error": "local only"})
|
||||
return
|
||||
self._json(200, {"ok": True, "stats": stats_summary()})
|
||||
return
|
||||
if path in ("/health", "/api/track/health"):
|
||||
self._json(200, {"ok": True, "service": "vip-track", "uptime_s": int(time.time() - _stats["started"])})
|
||||
return
|
||||
self._json(200, {"ok": True, "service": "vip-track"})
|
||||
|
||||
def do_POST(self):
|
||||
try:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(max(0, min(n, 65536))) if n else b"{}"
|
||||
body = json.loads(raw.decode("utf-8", "replace") or "{}")
|
||||
except Exception:
|
||||
body = {}
|
||||
events = body.get("events") if isinstance(body, dict) else None
|
||||
if not isinstance(events, list):
|
||||
events = []
|
||||
openid = str((body or {}).get("openid") or "")[:64] if isinstance(body, dict) else ""
|
||||
session = str((body or {}).get("session") or "")[:64] if isinstance(body, dict) else ""
|
||||
client = str((body or {}).get("client") or "vip_web")[:32] if isinstance(body, dict) else "vip_web"
|
||||
identity = (body or {}).get("identity") if isinstance(body, dict) else None
|
||||
if not isinstance(identity, dict):
|
||||
identity = {}
|
||||
ip = self.headers.get("X-Real-IP") or self.headers.get("X-Forwarded-For") or (
|
||||
self.client_address[0] if self.client_address else ""
|
||||
)
|
||||
ip = str(ip).split(",")[0].strip()[:64]
|
||||
ua_hdr = (self.headers.get("User-Agent") or "")[:140]
|
||||
notified = 0
|
||||
stored = 0
|
||||
for raw_ev in events[:20]:
|
||||
if not isinstance(raw_ev, dict):
|
||||
continue
|
||||
name = str(raw_ev.get("name") or "").strip()[:64]
|
||||
if not name:
|
||||
continue
|
||||
_stats["received"] += 1
|
||||
page = str(raw_ev.get("page") or "")[:64]
|
||||
label = str(raw_ev.get("label") or "")[:160]
|
||||
props = raw_ev.get("props") if isinstance(raw_ev.get("props"), dict) else {}
|
||||
# merge identity defaults into props for storage/ntfy
|
||||
for k in ("role", "role_cn", "paid_type", "email", "name", "user_id"):
|
||||
if not props.get(k) and identity.get(k):
|
||||
props[k] = identity.get(k)
|
||||
if not props.get("ua") and ua_hdr:
|
||||
props["ua"] = ua_hdr
|
||||
ntfy_name = maybe_ntfy_name(name, props)
|
||||
did_notify = 0
|
||||
if client in ("healthcheck", "probe", "deploy"):
|
||||
ntfy_name = None
|
||||
is_visit = ntfy_name in VISIT_EVENTS if ntfy_name else False
|
||||
if ntfy_name and is_visit:
|
||||
dedup_key = "%s|%s|%s|%s" % (ntfy_name, session or openid or ip, page, label[:40])
|
||||
if not visit_dedup_ok(dedup_key):
|
||||
ntfy_name = None
|
||||
# 同类点击短去重(30s),保留详情但不刷屏
|
||||
if ntfy_name == "btn_click":
|
||||
ck = "btn|%s|%s|%s" % (session or openid or ip, page, label[:60])
|
||||
now = time.time()
|
||||
last = _seen_visit.get(ck)
|
||||
if last and now - last < 30:
|
||||
ntfy_name = None
|
||||
else:
|
||||
_seen_visit[ck] = now
|
||||
if ntfy_name and budget_ok(visit=is_visit):
|
||||
title, message, tags, pri, click = build_rich_message(
|
||||
ntfy_name=ntfy_name,
|
||||
openid=openid,
|
||||
session=session,
|
||||
page=page,
|
||||
label=label,
|
||||
props=props,
|
||||
ip=ip,
|
||||
identity=identity,
|
||||
)
|
||||
ok = publish(title, message, tags, pri, click=click)
|
||||
if ok:
|
||||
notified += 1
|
||||
did_notify = 1
|
||||
_stats["notified"] += 1
|
||||
# persist role into props for analytics
|
||||
store_props = dict(props)
|
||||
store_props["_role"] = role_of(props, identity)[0]
|
||||
store_event(
|
||||
name=name,
|
||||
page=page,
|
||||
label=label,
|
||||
openid=openid,
|
||||
session=session,
|
||||
client=client,
|
||||
props=store_props,
|
||||
ip=ip,
|
||||
notified=did_notify,
|
||||
)
|
||||
stored += 1
|
||||
self._json(200, {"ok": True, "notified": notified, "stored": stored})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db()
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
@ -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
|
||||
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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")
|
||||
@ -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 天**:回顾本周,写下下周只改一件事
|
||||
|
||||
目标不是完美,而是建立可重复的节奏。
|
||||
|
||||
# 结语
|
||||
|
||||
数字游民生活方式的本质,是用更好的方式完成工作、照顾生活,而不是追逐表象上的「自由」。
|
||||
|
||||
先把远程协作做好,把身体照顾好,把专业能力垒扎实。地点可以慢慢变化,但秩序、责任与成长不能丢。
|
||||
|
||||
祝你工作顺利,生活安定,步履从容。
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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")
|
||||
@ -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=hackrobot
|
||||
ADMIN_PASSWORD=Xiao4669805@
|
||||
PB_URL=http://127.0.0.1:8090
|
||||
PB_ADMIN_EMAIL=admin@nomadro.cn
|
||||
PB_ADMIN_PASSWORD=Xiao4669805
|
||||
USE_POCKETBASE=false
|
||||
DEBUG=false
|
||||
PUBLIC_API_BASE=https://api.nomadro.cn
|
||||
ADMIN_ORIGIN=https://admin.nomadro.cn
|
||||
CORS_ORIGINS=https://admin.nomadro.cn,https://api.nomadro.cn
|
||||
DEFAULT_PRODUCT_ID=ebook_unlock_default
|
||||
DEFAULT_PRICE_FEN=18800
|
||||
DEFAULT_UNLOCK_PERCENT=30
|
||||
SQLITE_PATH=/opt/nomadmini/data/nomadmini.db
|
||||
WX_PUSH_TOKEN=hackrobot
|
||||
WX_PUSH_ENCODING_AES_KEY=ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI
|
||||
WX_ALLOW_DEVTOOLS_LOGIN=true
|
||||
"""
|
||||
sftp = client.open_sftp()
|
||||
with sftp.file(f"{REMOTE}/backend/.env", "w") as f:
|
||||
f.write(env_content)
|
||||
try:
|
||||
sftp.chmod(f"{REMOTE}/deploy/remote-setup.sh", stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
|
||||
except OSError:
|
||||
pass
|
||||
sftp.close()
|
||||
|
||||
run(
|
||||
client,
|
||||
"command -v nginx >/dev/null 2>&1 || "
|
||||
"(sudo apt-get update -y && sudo DEBIAN_FRONTEND=noninteractive "
|
||||
"apt-get install -y nginx python3-venv python3-pip curl)",
|
||||
check=False,
|
||||
)
|
||||
run(client, f"bash {REMOTE}/deploy/remote-setup.sh")
|
||||
|
||||
_, out, _ = run(
|
||||
client,
|
||||
"curl -s http://127.0.0.1:8010/health || curl -s http://127.0.0.1:8000/health",
|
||||
check=False,
|
||||
)
|
||||
print("Health:", out.strip())
|
||||
finally:
|
||||
client.close()
|
||||
tar_path.unlink(missing_ok=True)
|
||||
|
||||
print("\nDeployed:")
|
||||
print(" API: https://api.nomadro.cn")
|
||||
print(" Admin: https://admin.nomadro.cn")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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())
|
||||
@ -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()
|
||||
@ -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())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user