Migrate navmini/ebook/nomadweb into apps/ as same-origin portal subpaths.
Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
24
.gitignore
vendored
@ -2,6 +2,7 @@
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/apps/**/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
@ -16,6 +17,9 @@
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
/apps/**/.next/
|
||||
/apps/**/out/
|
||||
/apps/**/dist/
|
||||
|
||||
# production
|
||||
/build
|
||||
@ -23,6 +27,8 @@
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
@ -32,6 +38,9 @@ yarn-error.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
!.env.example
|
||||
!**/.env.example
|
||||
!**/.env.production.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@ -39,3 +48,18 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# local / runtime data
|
||||
/apps/nomadweb/pocketbase/pb_data/
|
||||
/apps/nomadweb/tmp-screenshots/
|
||||
/apps/**/.turbo/
|
||||
/apps/**/.venv/
|
||||
/deploy/**/__pycache__/
|
||||
|
||||
# secrets / private mini-program configs
|
||||
**/*credentials*.txt
|
||||
**/nowpayments.env
|
||||
**/nomadro-api.env
|
||||
!**/*.env.example
|
||||
!**/.env*.example
|
||||
**/project.private.config.json
|
||||
|
||||
47
apps/README.md
Normal file
@ -0,0 +1,47 @@
|
||||
# Vertical apps inside nomadro portal
|
||||
|
||||
本目录迁入三个垂直项目,由门户首页三个入口打开**同站子路径**(外链跳转已屏蔽,代码保留)。
|
||||
|
||||
| 入口 | 路径 | 源目录 | Web | 微信 | 抖音 | 小红书 |
|
||||
|------|------|--------|-----|------|------|--------|
|
||||
| 出海导航 | `/nav` | `apps/navmini` | Vite H5/PC | `weapp/` | `tt/` | `xhs/`(纯前端小工具) |
|
||||
| 数字游民小册 | `/book` | `apps/ebook` | Next.js + FastAPI | `wemini/` | `dymini/` | `redmini/`(纯前端) |
|
||||
| 旅居社群 | `/community` | `apps/nomadweb` | Next.js + FastAPI + PB | `wemini/` | `dymini/` | `redmini/`(纯前端) |
|
||||
|
||||
## 本地联调
|
||||
|
||||
在仓库根目录:
|
||||
|
||||
```bash
|
||||
# 终端 1 — 门户 :3000(会把 /nav /book /community reverse-proxy 到下游)
|
||||
pnpm dev
|
||||
|
||||
# 终端 2 — 导航
|
||||
cd apps/navmini && npm i && npm run dev
|
||||
|
||||
# 终端 3 — 电子书(端口 3001)
|
||||
cd apps/ebook && npm i --legacy-peer-deps && npx next dev -p 3001
|
||||
|
||||
# 终端 4 — 社群前端(端口 3002;另起 backend :8000)
|
||||
cd apps/nomadweb/frontend && npm i --legacy-peer-deps && npx next dev -p 3002
|
||||
```
|
||||
|
||||
也可先构建导航静态资源到门户 `public/nav`(不依赖 Vite 进程):
|
||||
|
||||
```bash
|
||||
pnpm build:nav
|
||||
```
|
||||
|
||||
## 环境变量(门户)
|
||||
|
||||
| 变量 | 默认 | 含义 |
|
||||
|------|------|------|
|
||||
| `NAV_UPSTREAM` | `http://127.0.0.1:5173` | navmini |
|
||||
| `BOOK_UPSTREAM` | `http://127.0.0.1:3001` | ebook |
|
||||
| `COMMUNITY_UPSTREAM` | `http://127.0.0.1:3002` | nomadweb frontend |
|
||||
|
||||
生产建议用 Caddy 做路径反代(见 `deploy/caddy/nomadro-portal.Caddyfile`),比 Next rewrite 更稳。
|
||||
|
||||
## 恢复外链跳转
|
||||
|
||||
编辑 `components/sections/hero.tsx`,将 `EXTERNAL_JUMP_ENABLED` 改为 `true`(勿删 `EXTERNAL_PORTALS`)。
|
||||
26
apps/ebook/.env.example
Normal file
@ -0,0 +1,26 @@
|
||||
# 站点 URL(分享 / OG 预览必填)
|
||||
NEXT_PUBLIC_SITE_URL=https://ebook.nomadro.cn
|
||||
|
||||
# 分享 UTM campaign(与 content/site.json 的 share.campaign 保持一致)
|
||||
NEXT_PUBLIC_SHARE_CAMPAIGN=nomad-code
|
||||
|
||||
# Google Analytics 4(数据分析)
|
||||
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
|
||||
|
||||
# Google AdSense(盈利)
|
||||
NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-XXXXXXXXXXXXXXXX
|
||||
NEXT_PUBLIC_ADSENSE_SLOT_COVER=
|
||||
NEXT_PUBLIC_ADSENSE_SLOT_READER_MID=
|
||||
NEXT_PUBLIC_ADSENSE_SLOT_READER_END=
|
||||
|
||||
# 用户反馈 Webhook(可选,如 Slack / Discord / 自建 API)
|
||||
FEEDBACK_WEBHOOK_URL=
|
||||
|
||||
# NOWPayments — fill from vault, do not commit real keys
|
||||
NOWPAYMENTS_API_KEY=
|
||||
NOWPAYMENTS_IPN_SECRET=
|
||||
|
||||
# Creem — fill from vault, do not commit real keys
|
||||
CREEM_API_KEY=
|
||||
CREEM_PRODUCT_ID=
|
||||
CREEM_WEBHOOK_SECRET=
|
||||
9
apps/ebook/.gitignore
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
.DS_Store
|
||||
*.log
|
||||
.env*.local
|
||||
tsconfig.tsbuildinfo
|
||||
__pycache__/
|
||||
*.pyc
|
||||
470
apps/ebook/README.md
Normal file
@ -0,0 +1,470 @@
|
||||
# 游牧代码 · 电子书多端
|
||||
|
||||
本仓库包含 **网页电子书** 与 **微信 / 抖音 / 小红书** 三端小程序(或小工具)子项目,共用「Markdown 电子书 → 阅读体验 → 变现」主线。
|
||||
|
||||
| 端 | 目录 | 形态 | 详情 |
|
||||
|----|------|------|------|
|
||||
| **网页** | 仓库根目录 | Next.js + FastAPI + PocketBase | 下文「网页电子书」 |
|
||||
| **微信小程序** | [`wemini/`](wemini/) | Taro + FastAPI + 虚拟支付 | [wemini/README.md](wemini/README.md) |
|
||||
| **抖音小程序** | [`dymini/`](dymini/) | Taro + FastAPI(支付可 mock) | [dymini/README.md](dymini/README.md) |
|
||||
| **小红书小工具** | [`redmini/`](redmini/) | 纯离线 ZIP(无后端) | [redmini/README.md](redmini/README.md) |
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **仓库** | https://gitea.dsx2020.com/eric/ebook |
|
||||
| **分支** | `dev1`(当前生产) |
|
||||
|
||||
---
|
||||
|
||||
## 多端速览(运维配置)
|
||||
|
||||
> 密钥放各子目录 `backend/.env` / 服务器环境变量,**不要写进 README**。
|
||||
|
||||
### 网页 · ebook.nomadro.cn
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| 线上 | https://ebook.nomadro.cn |
|
||||
| 门户子路径 | `/book`(本 monorepo) |
|
||||
| API | FastAPI(Caddy `/api/*`) |
|
||||
| PocketBase | Caddy `/pb/*` |
|
||||
| 管理账号 | 见 `backend/.env` |
|
||||
|
||||
### 微信 · `wemini/`
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| API | https://api.nomadro.cn |
|
||||
| Admin | https://admin.nomadro.cn |
|
||||
| AppID / Secret / 支付 | 见 `wemini/backend/.env` |
|
||||
|
||||
本地:`cd wemini && npm run dev:api` / `dev:admin` / `dev:miniapp`。
|
||||
|
||||
### 抖音 · `dymini/`
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| API | https://dyapi.nomadro.cn |
|
||||
| Admin | https://dyadmin.nomadro.cn |
|
||||
| AppID / Secret | 见 `dymini/backend/.env` |
|
||||
| 合法域名 | `dyapi.nomadro.cn` |
|
||||
|
||||
本地:`cd dymini/backend` 起 API;`cd dymini/miniapp && npm run dev:tt`。
|
||||
|
||||
### 小红书 · `redmini/`
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| 形态 | 创作服务平台「小工具」ZIP,**禁网、无后端** |
|
||||
| 上传包 | `redmini/dist/yidu-xingqiu-xhs-tool.zip` |
|
||||
| 构建 | `python scripts/assemble.py` → `python scripts/pack.py` |
|
||||
|
||||
阅读 UI 对齐 [`wemini/`](wemini/),能力边界见 [redmini/README.md](redmini/README.md)。
|
||||
|
||||
---
|
||||
|
||||
# 网页电子书
|
||||
|
||||
**单本 Markdown 电子书落地页 + 沉浸式阅读器 + 管理后台**,面向 X(Twitter)引流、广告投流与内容变现。
|
||||
|
||||
在 X 发帖或投放广告时附上本站 URL,会自动展示**大图封面预览**;用户点击后先看到转化封面,再一键进入连续滚动阅读。全书免费在线读。英语读者可用加密货币打赏(NOWPayments)或购买下载版(Creem);中文赞赏可另接微信 / 支付宝。
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| **线上** | https://book.nomadro.com |
|
||||
| **管理后台** | https://book.nomadro.com/admin |
|
||||
|
||||
---
|
||||
|
||||
## 架构概览
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ Caddy (443/80) │
|
||||
│ book.nomadro.com │
|
||||
├──────────────┬──────────────┬────────────────────┤
|
||||
│ /api/* │ /pb/* │ 其余所有 │
|
||||
│ ↓ │ ↓ │ ↓ │
|
||||
│ FastAPI │ PocketBase │ Next.js │
|
||||
│ :8010 │ :8090 │ :3022 (PM2) │
|
||||
└──────────────┴──────────────┴────────────────────┘
|
||||
```
|
||||
|
||||
| 层 | 技术 | 用途 |
|
||||
|---|---|---|
|
||||
| **前端** | Next.js 15 (standalone) | SSR、封面、阅读器、管理台 UI |
|
||||
| **后端** | FastAPI (uvicorn) | 支付、webhook、用户数据、管理 API |
|
||||
| **数据库** | PocketBase | 订单、用户、书签、划线、进度、反馈、支付密钥 |
|
||||
| **反代** | Caddy | HTTPS、按路径分流 |
|
||||
| **进程** | PM2 + systemd | Next.js 用 PM2;FastAPI / PocketBase 用 systemd |
|
||||
|
||||
业务逻辑在 FastAPI + PocketBase,**不**走 Next.js Route Handler。`content/features.json` 是前后端共用的模块总开关。
|
||||
|
||||
---
|
||||
|
||||
## 设计目的
|
||||
|
||||
| 环节 | 目标 | 实现 |
|
||||
|------|------|------|
|
||||
| **引流** | X / 广告链接有吸引力 | 动态 OG 大图(1200×630)、`summary_large_image` |
|
||||
| **转化** | 封面让人想点「开始阅读」 | 渐变封面、书摘轮播、免费徽章、sticky CTA |
|
||||
| **阅读** | 赏心悦目、愿意读完 | 连续滚动、沉浸模式、划线、搜索、主题切换 |
|
||||
| **数据** | 知道漏斗在哪丢人 | GA4:封面、开始阅读、章节、读完、分享、支付点击 |
|
||||
| **盈利** | 广告 + 联盟 + 打赏 + 购买 | AdSense、affiliate、NOWPayments、Creem |
|
||||
| **裂变** | 读者帮你传播 | UTM 分享、滚动分享提示、金句卡片 |
|
||||
| **运营** | 可视化开关与密钥 | `/admin` Ant Design 后台 |
|
||||
| **双语** | 中英读者同一站点 | `locale` cookie + 界面词典 + 英文章节元数据 |
|
||||
|
||||
**一本书 = 一个部署。** 发第二本:复制项目,替换 `content/` 即可。
|
||||
|
||||
---
|
||||
|
||||
## 中英双语
|
||||
|
||||
默认中文。右上角 **中文 / EN** 切换后写入 `locale` cookie 并刷新。
|
||||
|
||||
| 范围 | 中文 | 英文 |
|
||||
|------|------|------|
|
||||
| 界面文案 | `src/lib/i18n/messages/zh.ts` | `src/lib/i18n/messages/en.ts` |
|
||||
| 书名 / 章节元数据 | `content/book.json` | `content/en/book.json` |
|
||||
| 章节正文 | `content/chapters/*.md` | 暂共用中文 Markdown(可另放 `content/en/chapters/`) |
|
||||
| 管理后台 | 同一套词典 + Ant Design `zh_CN` / `en_US` | 同上 |
|
||||
| HTML `lang` / OG locale | `zh-CN` / `zh_CN` | `en` / `en_US` |
|
||||
|
||||
浏览器 `Accept-Language` 以 `en` 开头且无 cookie 时,首次访问会落到英文。
|
||||
|
||||
---
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 阅读体验
|
||||
|
||||
- **连续滚动**(`/read`):全书一页滑完
|
||||
- **左侧目录**:PC 固定;移动端抽屉;当前章展开二级标题
|
||||
- 封面「开始阅读 / 继续阅读」(恢复滚动位置、剩余时长)
|
||||
- 进度、书签、划线、全书搜索(`/`)、划词高亮、沉浸模式(`z`)
|
||||
- 宋体 / 黑体、字号 / 行距 / 版心
|
||||
- 金句卡片、标题深链、章末下一章预告
|
||||
- **默认阅读设置(无缓存时):** 暗色、黑体、小字号、紧行距、宽版心
|
||||
|
||||
### 增长与变现
|
||||
|
||||
- 动态 OG / Twitter 图(`/opengraph-image`)
|
||||
- GA4 全链路事件
|
||||
- AdSense 位:封面底、阅读中段、全书结尾(关广告开关则不加载)
|
||||
- Affiliate:按域名改写 Markdown 外链
|
||||
- **NOWPayments**:`$5 / $10 / $20`,托管收银台,IPN 入账
|
||||
- **Creem**:一次性 PDF / EPUB,webhook 记订单并可发邮件
|
||||
- UTM 分享、约 42% 进度弹出分享引导、反馈浮窗
|
||||
|
||||
### 管理后台(`/admin`)
|
||||
|
||||
Ant Design 风格控制台,Basic Auth(`backend/.env` 的 `ADMIN_USERNAME` / `ADMIN_PASSWORD`)。
|
||||
|
||||
| 页 | 作用 |
|
||||
|----|------|
|
||||
| 仪表盘 | 订单数、已支付、收入、支付服务健康 |
|
||||
| 支付中心 | 读写 PocketBase 中 NOWPayments / Creem 密钥 |
|
||||
| 订单 | 最近订单列表 |
|
||||
| 功能开关 | 读写 `content/features.json` |
|
||||
| 站点设置 | 品牌名、邮箱、X、分享 campaign、购买按钮文案 |
|
||||
|
||||
保存配置后会调度重启 `ebook-api`,使 FastAPI 按新开关重新挂载路由。
|
||||
|
||||
### 数据持久化(PocketBase)
|
||||
|
||||
| 集合 | 说明 |
|
||||
|------|------|
|
||||
| `orders` | NOWPayments / Creem 订单 |
|
||||
| `users` | 邮箱、是否已购买 |
|
||||
| `bookmarks` / `highlights` / `reading_progress` | 按 `device_id` |
|
||||
| `feedback` | 用户反馈 |
|
||||
| `payment_providers` | 支付商 `secrets` / `config`(JSON) |
|
||||
|
||||
`features.json` 里 `userdata.syncToServer` 为 `false` 时,书签 / 划线 / 进度仍可只走 localStorage。
|
||||
|
||||
---
|
||||
|
||||
## 模块开关(`content/features.json`)
|
||||
|
||||
关闭任一模块不影响其余功能。FastAPI 按开关注册路由;Next.js 按开关加载组件。
|
||||
|
||||
| 路径 | 作用 |
|
||||
|------|------|
|
||||
| `analytics.enabled` | GA4 |
|
||||
| `ads.enabled` | AdSense |
|
||||
| `payment.crypto.enabled` | NOWPayments 打赏 |
|
||||
| `payment.checkout.enabled` | Creem 购买 |
|
||||
| `feedback.enabled` | 反馈浮窗 |
|
||||
| `affiliate.enabled` | 联盟改写 |
|
||||
| `share.enabled` | 分享 / UTM / 裂变提示 |
|
||||
| `reader.*` | 书签、划线、搜索、进度、沉浸、快捷键 |
|
||||
| `userdata.enabled` | 用户数据 API |
|
||||
| `backend.email.enabled` | 购买后 SMTP 发信 |
|
||||
|
||||
品牌身份在 `content/site.json`(名称、X、联系邮箱),不再和开关混在一起。
|
||||
|
||||
---
|
||||
|
||||
## 键盘快捷键
|
||||
|
||||
| 按键 | 作用 |
|
||||
|------|------|
|
||||
| `/` | 搜索全书 |
|
||||
| `n` / `]` / `→` | 下一章 |
|
||||
| `p` / `[` / `←` | 上一章 |
|
||||
| `t` | 打开目录(移动端) |
|
||||
| `b` | 添加 / 取消书签 |
|
||||
| `z` | 进入 / 退出沉浸模式 |
|
||||
| `?` | 快捷键说明 |
|
||||
| `Esc` | 关闭浮层 / 退出沉浸 |
|
||||
|
||||
---
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 前端
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env.local
|
||||
npm run dev
|
||||
npm run build && npm start
|
||||
```
|
||||
|
||||
### 后端
|
||||
|
||||
```bash
|
||||
# PocketBase
|
||||
./pocketbase serve --http=127.0.0.1:8090
|
||||
|
||||
cd backend
|
||||
python3 -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
python -m app.pb_schema # 建表 + 补字段 + 种子支付密钥
|
||||
uvicorn app.main:app --host 127.0.0.1 --port 8010 --reload
|
||||
```
|
||||
|
||||
本地 API 文档:http://127.0.0.1:8010/api/docs
|
||||
线上文档:https://book.nomadro.com/api/docs
|
||||
|
||||
---
|
||||
|
||||
## 环境变量
|
||||
|
||||
### 前端 `.env`
|
||||
|
||||
| 变量 | 用途 |
|
||||
|------|------|
|
||||
| `NEXT_PUBLIC_SITE_URL` | 站点 URL(OG、分享、支付回跳,**必填**) |
|
||||
| `NEXT_PUBLIC_SHARE_CAMPAIGN` | 分享 UTM campaign |
|
||||
| `NEXT_PUBLIC_GA_MEASUREMENT_ID` | GA4 |
|
||||
| `NEXT_PUBLIC_ADSENSE_CLIENT_ID` | AdSense |
|
||||
| `NEXT_PUBLIC_ADSENSE_SLOT_*` | 广告位 Slot |
|
||||
| `FEEDBACK_WEBHOOK_URL` | 反馈 Webhook(可选) |
|
||||
|
||||
### 后端 `backend/.env`
|
||||
|
||||
| 变量 | 用途 |
|
||||
|------|------|
|
||||
| `PB_URL` | PocketBase,默认 `http://127.0.0.1:8090` |
|
||||
| `PB_ADMIN_EMAIL` / `PB_ADMIN_PASSWORD` | PocketBase 超管(部署时 `superuser upsert`) |
|
||||
| `NOWPAYMENTS_API_KEY` / `NOWPAYMENTS_IPN_SECRET` | 打赏(可被 PocketBase 覆盖) |
|
||||
| `CREEM_API_KEY` / `CREEM_PRODUCT_ID` / `CREEM_WEBHOOK_SECRET` | 购买 |
|
||||
| `SMTP_*` / `SMTP_FROM` | 购买后发下载邮件 |
|
||||
| `DOWNLOAD_BASE_URL` | PDF/EPUB 链接前缀 |
|
||||
| `ADMIN_USERNAME` / `ADMIN_PASSWORD` | `/admin` 与 `/api/admin` Basic Auth |
|
||||
|
||||
支付运行时优先读 PocketBase `payment_providers`,没有再回退 `.env`。`CREEM_API_KEY` 以 `creem_test_` 开头时走沙箱 API。
|
||||
|
||||
---
|
||||
|
||||
## 支付系统
|
||||
|
||||
### NOWPayments(加密货币打赏)
|
||||
|
||||
面向英语读者。不设付费墙。
|
||||
|
||||
| 档位 | 金额 |
|
||||
|------|------|
|
||||
| Coffee | $5 |
|
||||
| Lunch | $10 |
|
||||
| Sponsor | $20 |
|
||||
|
||||
- `POST /api/pay/invoice` → 托管发票 → 收银台
|
||||
- `POST /api/pay/ipn`(HMAC-SHA512)→ 写入 `orders`
|
||||
- `$5` 开票按 **$5.50** 提交,避免 USDT 低于网络最低额
|
||||
- `is_fee_paid_by_user`:链上手续费由付款人承担
|
||||
|
||||
### Creem(下载版)
|
||||
|
||||
- `POST /api/creem/checkout` → 结账页
|
||||
- `POST /api/creem/webhook`(HMAC-SHA256)→ 订单、`has_purchased`、可选邮件
|
||||
|
||||
### Webhook URL
|
||||
|
||||
| 平台 | URL | 签名头 |
|
||||
|------|-----|--------|
|
||||
| NOWPayments | `https://book.nomadro.com/api/pay/ipn` | `x-nowpayments-sig` |
|
||||
| Creem | `https://book.nomadro.com/api/creem/webhook` | `creem-signature` |
|
||||
|
||||
---
|
||||
|
||||
## 生产部署
|
||||
|
||||
站点:https://book.nomadro.com
|
||||
VPS:`107.173.30.245`
|
||||
|
||||
| 服务 | 管理 | 端口 |
|
||||
|------|------|------|
|
||||
| Next.js | PM2 fork `ebook` | `:3022` |
|
||||
| FastAPI | systemd `ebook-api` | `:8010` |
|
||||
| PocketBase | systemd `pocketbase` | `:8090` |
|
||||
| Caddy | systemd | `:80` / `:443` |
|
||||
|
||||
### 一键部署
|
||||
|
||||
```bash
|
||||
python deploy/remote_deploy.py
|
||||
```
|
||||
|
||||
流程:SSH → `git pull` `dev1` → `npm ci` + `next build` → PM2 → PocketBase / FastAPI / schema 种子 → Caddy reload。
|
||||
|
||||
服务器上手动:
|
||||
|
||||
```bash
|
||||
export GIT_PASS=你的Gitea密码
|
||||
bash /var/www/ebook/deploy/install.sh
|
||||
```
|
||||
|
||||
| 文件 | 作用 |
|
||||
|------|------|
|
||||
| `deploy/install.sh` | 前端 build + PM2,再调 backend 安装 |
|
||||
| `deploy/install_backend.sh` | PocketBase、venv、systemd、`python -m app.pb_schema` |
|
||||
| `deploy/ecosystem.config.cjs` | PM2,端口 3022 |
|
||||
| `deploy/caddy-book.caddy` | `/api/*` → 8010,`/pb/*` → 8090,其余 → 3022 |
|
||||
| `deploy/remote_deploy.py` | 本机触发全量部署 |
|
||||
| `deploy/nowpayments.env` | 支付密钥(随仓库) |
|
||||
|
||||
PocketBase 集合使用 **0.25 `fields`**(不是旧版 `schema`)。`pb_schema.py` 会对已有集合补字段,并删除早期空记录后写入支付密钥。
|
||||
|
||||
---
|
||||
|
||||
## API 与页面
|
||||
|
||||
所有业务 `/api/*` 由 FastAPI 处理(Caddy 分流)。
|
||||
|
||||
| 路径 | 方法 | 说明 |
|
||||
|------|------|------|
|
||||
| `/api/health` | GET | 健康检查 + 模块状态 |
|
||||
| `/api/pay/invoice` | POST | NOWPayments 发票 |
|
||||
| `/api/pay/ipn` | POST | NOWPayments IPN |
|
||||
| `/api/creem/checkout` | POST | Creem 结账 |
|
||||
| `/api/creem/webhook` | POST | Creem webhook |
|
||||
| `/api/feedback` | POST | 反馈 |
|
||||
| `/api/userdata/highlights` | GET/POST | 划线 |
|
||||
| `/api/userdata/highlights/{id}` | DELETE | 删划线 |
|
||||
| `/api/userdata/bookmarks` | GET/POST | 书签 |
|
||||
| `/api/userdata/bookmarks/{slug}` | DELETE | 删书签 |
|
||||
| `/api/userdata/progress` | GET/POST | 进度 |
|
||||
| `/api/admin/login` | POST | 管理登录 |
|
||||
| `/api/admin/config` | GET/PUT | `features.json` + `site.json` |
|
||||
| `/api/admin/payment-providers` | GET | 支付商配置 |
|
||||
| `/api/admin/payment-providers/{provider}` | PUT | 保存密钥(`creem` / `nowpayments`) |
|
||||
| `/api/admin/orders` | GET | 订单列表 |
|
||||
| `/api/docs` | GET | Swagger |
|
||||
|
||||
| 页面 | 说明 |
|
||||
|------|------|
|
||||
| `/` | 封面 |
|
||||
| `/read` | 连续阅读 |
|
||||
| `/read/[slug]` | 深链 → `/read#slug` |
|
||||
| `/admin` | 管理后台 |
|
||||
| `/opengraph-image` | OG 图 |
|
||||
| `/support/thanks` | 打赏成功 |
|
||||
| `/purchase/thanks` | 购买成功 |
|
||||
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
ebook/
|
||||
├── README.md # 本文件(多端总览)
|
||||
├── content/ … # 网页书:元数据 + chapters
|
||||
├── backend/ … # 网页书 FastAPI
|
||||
├── deploy/ … # 网页书部署
|
||||
├── src/ … # Next.js 封面 / 阅读器 /admin
|
||||
├── wemini/ # 微信小程序(Taro + FastAPI + admin)
|
||||
│ ├── miniapp/ backend/ admin/ data/ deploy/ docs/
|
||||
│ └── README.md
|
||||
├── dymini/ # 抖音小程序(结构对齐 wemini)
|
||||
│ ├── miniapp/ backend/ admin/ data/ deploy/ docs/
|
||||
│ └── README.md
|
||||
└── redmini/ # 小红书离线小工具(ZIP)
|
||||
├── content/ tool/ release/ dist/ scripts/
|
||||
└── README.md
|
||||
```
|
||||
|
||||
网页端细节:
|
||||
|
||||
```
|
||||
ebook/(网页)
|
||||
├── content/
|
||||
│ ├── book.json # 中文书籍元数据
|
||||
│ ├── en/book.json # 英文章节标题 / 书摘
|
||||
│ ├── site.json # 品牌身份
|
||||
│ ├── features.json # 模块总开关
|
||||
│ └── chapters/*.md
|
||||
├── backend/
|
||||
│ ├── app/ # main, routers, services, pb_schema…
|
||||
│ ├── requirements.txt
|
||||
│ └── .env
|
||||
├── deploy/
|
||||
├── src/
|
||||
│ ├── app/ # 页面 + middleware(locale cookie)
|
||||
│ ├── components/
|
||||
│ └── lib/ # i18n、features、book.server
|
||||
└── .env.example
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 数据分析事件(GA4)
|
||||
|
||||
| 事件 | 时机 |
|
||||
|------|------|
|
||||
| `cover_view` | 打开封面 |
|
||||
| `start_read` / `continue_read` | 开始 / 继续阅读 |
|
||||
| `chapter_view` | 滚到新章节 |
|
||||
| `book_complete` | 读完 |
|
||||
| `share_x` / `share_copy` | 分享 |
|
||||
| `affiliate_click` | 正文外链 |
|
||||
| `pay_click` / `buy_click` | 打赏 / 购买 |
|
||||
| `feedback_open` / `feedback_submit` | 反馈 |
|
||||
|
||||
---
|
||||
|
||||
## 发布第二本书
|
||||
|
||||
1. 复制仓库
|
||||
2. 改 `content/book.json` 与 `content/en/book.json`
|
||||
3. 替换 `content/chapters/*.md`
|
||||
4. 改 `content/site.json`、`content/features.json`
|
||||
5. 填 `.env` 与 `backend/.env`
|
||||
6. 部署
|
||||
|
||||
---
|
||||
|
||||
## Git
|
||||
|
||||
| 分支 | 说明 |
|
||||
|------|------|
|
||||
| `main` | 初始稳定版 |
|
||||
| `dev1` | 当前生产(全功能) |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
0
apps/ebook/backend/app/__init__.py
Normal file
79
apps/ebook/backend/app/config.py
Normal file
@ -0,0 +1,79 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# PocketBase
|
||||
pb_url: str = "http://127.0.0.1:8090"
|
||||
pb_admin_email: str = ""
|
||||
pb_admin_password: str = ""
|
||||
|
||||
# NOWPayments
|
||||
nowpayments_api_key: str = ""
|
||||
nowpayments_ipn_secret: str = ""
|
||||
|
||||
# Creem
|
||||
creem_api_key: str = ""
|
||||
creem_product_id: str = ""
|
||||
creem_webhook_secret: str = ""
|
||||
|
||||
# Site
|
||||
site_url: str = "https://book.nomadro.com"
|
||||
|
||||
# Feedback
|
||||
feedback_webhook_url: str = ""
|
||||
|
||||
# SMTP
|
||||
smtp_host: str = ""
|
||||
smtp_port: int = 465
|
||||
smtp_user: str = ""
|
||||
smtp_pass: str = ""
|
||||
smtp_from: str = "noreply@nomadro.com"
|
||||
|
||||
# Downloads
|
||||
download_base_url: str = "https://book.nomadro.com/downloads"
|
||||
|
||||
# Admin
|
||||
admin_username: str = "hackrobot"
|
||||
admin_password: str = "Xiao4669805@"
|
||||
|
||||
model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
|
||||
|
||||
@property
|
||||
def creem_api_base(self) -> str:
|
||||
if self.creem_api_key.startswith("creem_test_"):
|
||||
return "https://test-api.creem.io"
|
||||
return "https://api.creem.io"
|
||||
|
||||
@property
|
||||
def nowpayments_configured(self) -> bool:
|
||||
# Allow runtime override from PocketBase payment_providers
|
||||
try:
|
||||
from .services.payment_providers import get_payment_provider
|
||||
|
||||
p = get_payment_provider("nowpayments")
|
||||
secrets = p.get("secrets") or {}
|
||||
api_key = secrets.get("api_key") or self.nowpayments_api_key
|
||||
ipn_secret = secrets.get("ipn_secret") or self.nowpayments_ipn_secret
|
||||
return bool(api_key and ipn_secret)
|
||||
except Exception:
|
||||
return bool(self.nowpayments_api_key and self.nowpayments_ipn_secret)
|
||||
|
||||
@property
|
||||
def creem_configured(self) -> bool:
|
||||
try:
|
||||
from .services.payment_providers import get_payment_provider
|
||||
|
||||
p = get_payment_provider("creem")
|
||||
secrets = p.get("secrets") or {}
|
||||
api_key = secrets.get("api_key") or self.creem_api_key
|
||||
product_id = secrets.get("product_id") or self.creem_product_id
|
||||
return bool(api_key and product_id)
|
||||
except Exception:
|
||||
return bool(self.creem_api_key and self.creem_product_id)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
17
apps/ebook/backend/app/db.py
Normal file
@ -0,0 +1,17 @@
|
||||
"""PocketBase client singleton."""
|
||||
|
||||
from pocketbase import PocketBase
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
_client: PocketBase | None = None
|
||||
|
||||
|
||||
def get_pb() -> PocketBase:
|
||||
global _client
|
||||
s = get_settings()
|
||||
if _client is None:
|
||||
_client = PocketBase(s.pb_url)
|
||||
if s.pb_admin_email and s.pb_admin_password:
|
||||
_client.admins.auth_with_password(s.pb_admin_email, s.pb_admin_password)
|
||||
return _client
|
||||
26
apps/ebook/backend/app/features.py
Normal file
@ -0,0 +1,26 @@
|
||||
"""Feature flags for the backend — reads content/features.json."""
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
FEATURES_PATH = Path(__file__).resolve().parent.parent.parent / "content" / "features.json"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_features() -> dict:
|
||||
if not FEATURES_PATH.exists():
|
||||
return {}
|
||||
with open(FEATURES_PATH, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def is_enabled(path: str) -> bool:
|
||||
"""Check a dot-separated feature path, e.g. 'payment.crypto.enabled'."""
|
||||
obj = get_features()
|
||||
for key in path.split("."):
|
||||
if isinstance(obj, dict):
|
||||
obj = obj.get(key)
|
||||
else:
|
||||
return False
|
||||
return bool(obj)
|
||||
74
apps/ebook/backend/app/main.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""FastAPI application — ebook backend (modular, feature-flag driven)."""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from .config import get_settings
|
||||
from .features import is_enabled
|
||||
from .pb_schema import create_collections
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
||||
|
||||
app = FastAPI(title="Ebook Backend", docs_url="/api/docs", openapi_url="/api/openapi.json")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"https://book.nomadro.com",
|
||||
"https://nomadro.com",
|
||||
"http://localhost:3000",
|
||||
],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# ── Conditionally register routers based on feature flags ───
|
||||
|
||||
if is_enabled("payment.crypto.enabled"):
|
||||
from .routers import pay
|
||||
app.include_router(pay.router)
|
||||
|
||||
if is_enabled("payment.checkout.enabled"):
|
||||
from .routers import creem
|
||||
app.include_router(creem.router)
|
||||
|
||||
if is_enabled("feedback.enabled"):
|
||||
from .routers import feedback
|
||||
app.include_router(feedback.router)
|
||||
|
||||
if is_enabled("userdata.enabled"):
|
||||
from .routers import userdata
|
||||
app.include_router(userdata.router)
|
||||
|
||||
from .routers import admin
|
||||
app.include_router(admin.router)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _ensure_pb_schema():
|
||||
# Create collections if not exist. Safe to call repeatedly.
|
||||
try:
|
||||
create_collections()
|
||||
except Exception:
|
||||
# Don't block service startup due to schema initialization
|
||||
pass
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
s = get_settings()
|
||||
return {
|
||||
"status": "ok",
|
||||
"modules": {
|
||||
"crypto_pay": is_enabled("payment.crypto.enabled"),
|
||||
"checkout_pay": is_enabled("payment.checkout.enabled"),
|
||||
"feedback": is_enabled("feedback.enabled"),
|
||||
"userdata": is_enabled("userdata.enabled"),
|
||||
"pocketbase": is_enabled("backend.pocketbase.enabled"),
|
||||
"email": is_enabled("backend.email.enabled"),
|
||||
"admin": True,
|
||||
},
|
||||
}
|
||||
230
apps/ebook/backend/app/pb_schema.py
Normal file
@ -0,0 +1,230 @@
|
||||
"""PocketBase collection schema — bootstrap + patch missing fields.
|
||||
|
||||
Usage:
|
||||
python -m app.pb_schema
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .db import get_pb
|
||||
from .services.payment_providers import get_payment_provider, upsert_payment_provider
|
||||
|
||||
EBOOK_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _field(name: str, type: str, required: bool = False) -> dict[str, Any]:
|
||||
return {"name": name, "type": type, "required": required}
|
||||
|
||||
|
||||
COLLECTIONS: list[dict[str, Any]] = [
|
||||
{
|
||||
"name": "orders",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("provider", "text", True),
|
||||
_field("provider_id", "text"),
|
||||
_field("email", "email"),
|
||||
_field("customer_name", "text"),
|
||||
_field("amount_usd", "number"),
|
||||
_field("currency", "text"),
|
||||
_field("status", "text", True),
|
||||
_field("invoice_url", "url"),
|
||||
_field("meta", "json"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "users",
|
||||
"type": "auth",
|
||||
"fields": [
|
||||
_field("has_purchased", "bool"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "feedback",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("email", "email"),
|
||||
_field("message", "text", True),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "highlights",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("device_id", "text", True),
|
||||
_field("highlight_id", "text", True),
|
||||
_field("slug", "text", True),
|
||||
_field("text", "text", True),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "bookmarks",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("device_id", "text", True),
|
||||
_field("slug", "text", True),
|
||||
_field("scroll_y", "number"),
|
||||
_field("title", "text"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "reading_progress",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("device_id", "text", True),
|
||||
_field("slug", "text", True),
|
||||
_field("scroll_y", "number"),
|
||||
_field("read_chapters", "json"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "payment_providers",
|
||||
"type": "base",
|
||||
"fields": [
|
||||
_field("provider", "text", True),
|
||||
_field("secrets", "json"),
|
||||
_field("config", "json"),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _field_to_body(field: Any) -> dict[str, Any]:
|
||||
if isinstance(field, dict):
|
||||
body = {k: v for k, v in field.items() if v is not None}
|
||||
else:
|
||||
body = {
|
||||
"id": getattr(field, "id", ""),
|
||||
"name": getattr(field, "name", ""),
|
||||
"type": getattr(field, "type", "text"),
|
||||
"required": bool(getattr(field, "required", False)),
|
||||
"presentable": bool(getattr(field, "presentable", False)),
|
||||
"system": bool(getattr(field, "system", False)),
|
||||
"hidden": bool(getattr(field, "hidden", False)),
|
||||
"unique": bool(getattr(field, "unique", False)),
|
||||
}
|
||||
for attr, key in (
|
||||
("max", "max"),
|
||||
("min", "min"),
|
||||
("pattern", "pattern"),
|
||||
("primary_key", "primaryKey"),
|
||||
("auto_generate_pattern", "autogeneratePattern"),
|
||||
):
|
||||
value = getattr(field, attr, None)
|
||||
if value is not None:
|
||||
body[key] = value
|
||||
|
||||
if body.get("primary_key") is not None:
|
||||
body["primaryKey"] = body.pop("primary_key")
|
||||
if body.get("auto_generate_pattern") is not None:
|
||||
body["autogeneratePattern"] = body.pop("auto_generate_pattern")
|
||||
return body
|
||||
|
||||
|
||||
def _merge_fields(existing_fields: list[Any], desired_fields: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
merged = [_field_to_body(f) for f in existing_fields]
|
||||
merged = [f for f in merged if f.get("name")]
|
||||
existing_names = {f.get("name") for f in merged}
|
||||
for spec in desired_fields:
|
||||
if spec["name"] not in existing_names:
|
||||
merged.append(spec)
|
||||
return merged
|
||||
|
||||
|
||||
def _read_env_files() -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for path in (
|
||||
EBOOK_ROOT / "backend" / ".env",
|
||||
EBOOK_ROOT / "deploy" / "nowpayments.env",
|
||||
EBOOK_ROOT / ".env",
|
||||
):
|
||||
if not path.exists():
|
||||
continue
|
||||
for raw in path.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
out[k.strip()] = v.strip()
|
||||
return out
|
||||
|
||||
|
||||
def _seed_payment_providers() -> None:
|
||||
env = _read_env_files()
|
||||
pb = get_pb()
|
||||
|
||||
# Remove broken records created before schema fields existed.
|
||||
try:
|
||||
for rec in pb.collection("payment_providers").get_list(1, 100).items or []:
|
||||
if not getattr(rec, "provider", None):
|
||||
pb.collection("payment_providers").delete(rec.id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now_cfg = get_payment_provider("nowpayments")
|
||||
now_secrets = now_cfg.get("secrets") or {}
|
||||
if not now_secrets.get("api_key"):
|
||||
upsert_payment_provider(
|
||||
"nowpayments",
|
||||
{
|
||||
"api_key": env.get("NOWPAYMENTS_API_KEY", ""),
|
||||
"ipn_secret": env.get("NOWPAYMENTS_IPN_SECRET", ""),
|
||||
"payout_usdt_trx": env.get("NOWPAYMENTS_PAYOUT_USDT_TRX", ""),
|
||||
},
|
||||
now_cfg.get("config") or {},
|
||||
)
|
||||
|
||||
creem_cfg = get_payment_provider("creem")
|
||||
creem_secrets = creem_cfg.get("secrets") or {}
|
||||
if not creem_secrets.get("api_key"):
|
||||
upsert_payment_provider(
|
||||
"creem",
|
||||
{
|
||||
"api_key": env.get("CREEM_API_KEY", ""),
|
||||
"product_id": env.get("CREEM_PRODUCT_ID", ""),
|
||||
"webhook_secret": env.get("CREEM_WEBHOOK_SECRET", ""),
|
||||
},
|
||||
creem_cfg.get("config") or {},
|
||||
)
|
||||
|
||||
|
||||
def create_collections() -> None:
|
||||
pb = get_pb()
|
||||
existing = {c.name: c for c in pb.collections.get_full_list()}
|
||||
|
||||
for spec in COLLECTIONS:
|
||||
name = spec["name"]
|
||||
desired_fields = spec["fields"]
|
||||
|
||||
if name not in existing:
|
||||
pb.collections.create(
|
||||
{
|
||||
"name": name,
|
||||
"type": spec["type"],
|
||||
"fields": desired_fields,
|
||||
}
|
||||
)
|
||||
print(f" created: {name}")
|
||||
continue
|
||||
|
||||
col = existing[name]
|
||||
merged = _merge_fields(col.fields or [], desired_fields)
|
||||
current_names = {getattr(f, "name", None) for f in (col.fields or [])}
|
||||
desired_names = {f["name"] for f in desired_fields}
|
||||
missing = desired_names - current_names
|
||||
if missing:
|
||||
pb.collections.update(col.id, {"fields": merged})
|
||||
print(f" patched: {name} (+{', '.join(sorted(missing))})")
|
||||
else:
|
||||
print(f" skip: {name} (ok)")
|
||||
|
||||
_seed_payment_providers()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_collections()
|
||||
print("Done.")
|
||||
0
apps/ebook/backend/app/routers/__init__.py
Normal file
188
apps/ebook/backend/app/routers/admin.py
Normal file
@ -0,0 +1,188 @@
|
||||
"""Admin API for visual feature/site configuration."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_pb
|
||||
from ..services.payment_providers import get_payment_provider, upsert_payment_provider
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
EBOOK_ROOT = Path(__file__).resolve().parents[3] # .../ebook
|
||||
FEATURES_FILE = EBOOK_ROOT / "content" / "features.json"
|
||||
SITE_FILE = EBOOK_ROOT / "content" / "site.json"
|
||||
BACKEND_ENV_FILE = EBOOK_ROOT / "backend" / ".env"
|
||||
|
||||
|
||||
def _check_auth(authorization: str | None) -> bool:
|
||||
if not authorization or not authorization.startswith("Basic "):
|
||||
return False
|
||||
try:
|
||||
raw = base64.b64decode(authorization.split(" ", 1)[1]).decode("utf-8")
|
||||
username, password = raw.split(":", 1)
|
||||
except Exception:
|
||||
return False
|
||||
s = get_settings()
|
||||
return username == s.admin_username and password == s.admin_password
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict:
|
||||
if not path.exists():
|
||||
return {}
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _write_json(path: Path, data: dict) -> None:
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
def _read_env_file(path: Path) -> dict[str, str]:
|
||||
if not path.exists():
|
||||
return {}
|
||||
out: dict[str, str] = {}
|
||||
for raw in path.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
out[k.strip()] = v.strip()
|
||||
return out
|
||||
|
||||
|
||||
def _write_env_file(path: Path, updates: dict[str, str]) -> None:
|
||||
current = _read_env_file(path)
|
||||
for k, v in updates.items():
|
||||
# allow setting to empty string; do not allow deleting for safety
|
||||
current[k] = v
|
||||
lines = [f"{k}={v}" for k, v in sorted(current.items())]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
class AdminConfigPayload(BaseModel):
|
||||
features: dict
|
||||
site: dict
|
||||
|
||||
|
||||
class PaymentProviderPayload(BaseModel):
|
||||
secrets: dict = {}
|
||||
config: dict = {}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def admin_login(authorization: str | None = Header(None)):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "invalid credentials"}, 401)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
async def get_config(authorization: str | None = Header(None)):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
||||
return {
|
||||
"ok": True,
|
||||
"features": _read_json(FEATURES_FILE),
|
||||
"site": _read_json(SITE_FILE),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/config")
|
||||
async def save_config(payload: AdminConfigPayload, authorization: str | None = Header(None)):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
||||
_write_json(FEATURES_FILE, payload.features)
|
||||
_write_json(SITE_FILE, payload.site)
|
||||
subprocess.Popen(
|
||||
["bash", "-lc", "sleep 1 && systemctl restart ebook-api >/dev/null 2>&1 || true"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
return {"ok": True, "message": "saved; backend reload scheduled"}
|
||||
|
||||
|
||||
@router.get("/payment-providers")
|
||||
async def list_payment_providers(authorization: str | None = Header(None)):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
||||
|
||||
# Supported providers
|
||||
providers = ["creem", "nowpayments"]
|
||||
return {
|
||||
"ok": True,
|
||||
"providers": {p: get_payment_provider(p) for p in providers},
|
||||
}
|
||||
|
||||
|
||||
@router.put("/payment-providers/{provider}")
|
||||
async def save_payment_provider(
|
||||
provider: str,
|
||||
payload: PaymentProviderPayload,
|
||||
authorization: str | None = Header(None),
|
||||
):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
||||
|
||||
if provider not in ["creem", "nowpayments"]:
|
||||
return JSONResponse({"ok": False, "error": "unsupported provider"}, 400)
|
||||
|
||||
upsert_payment_provider(provider, payload.secrets or {}, payload.config or {})
|
||||
|
||||
# reload backend so services pick up new keys
|
||||
subprocess.Popen(
|
||||
["bash", "-lc", "sleep 1 && systemctl restart ebook-api >/dev/null 2>&1 || true"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/orders")
|
||||
async def list_orders(
|
||||
authorization: str | None = Header(None),
|
||||
provider: str | None = None,
|
||||
status: str | None = None,
|
||||
limit: int = 20,
|
||||
):
|
||||
if not _check_auth(authorization):
|
||||
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
||||
|
||||
pb = get_pb()
|
||||
# Avoid PocketBase sort/filter quirks; fetch first page and filter in Python.
|
||||
recs = pb.collection("orders").get_list(1, 50)
|
||||
all_items = [
|
||||
{
|
||||
"id": r.id,
|
||||
"provider": r.provider,
|
||||
"provider_id": r.provider_id,
|
||||
"email": r.email,
|
||||
"amount_usd": r.amount_usd,
|
||||
"currency": r.currency,
|
||||
"status": r.status,
|
||||
"invoice_url": r.invoice_url,
|
||||
"created": r.get_created(),
|
||||
}
|
||||
for r in (recs.items or [])
|
||||
]
|
||||
|
||||
def match(item: dict):
|
||||
if provider and item.get("provider") != provider:
|
||||
return False
|
||||
if status and item.get("status") != status:
|
||||
return False
|
||||
return True
|
||||
|
||||
items = [it for it in all_items if match(it)]
|
||||
# If created exists, sort desc; otherwise keep original order.
|
||||
try:
|
||||
items.sort(key=lambda x: x.get("created") or 0, reverse=True)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "items": items[: max(1, min(limit, 50))]}
|
||||
123
apps/ebook/backend/app/routers/creem.py
Normal file
@ -0,0 +1,123 @@
|
||||
"""Creem routes: create checkout + webhook."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_pb
|
||||
from ..services.creem import create_checkout, verify_webhook_signature
|
||||
from ..services.email import send_purchase_email
|
||||
|
||||
router = APIRouter(prefix="/api/creem", tags=["creem"])
|
||||
logger = logging.getLogger("creem")
|
||||
|
||||
|
||||
@router.post("/checkout")
|
||||
async def post_checkout():
|
||||
s = get_settings()
|
||||
if not s.creem_configured:
|
||||
return JSONResponse({"ok": False, "error": "creem not configured"}, 503)
|
||||
|
||||
try:
|
||||
checkout = await create_checkout()
|
||||
except Exception as e:
|
||||
logger.error("Creem checkout: %s", e)
|
||||
return JSONResponse({"ok": False, "error": "checkout failed"}, 502)
|
||||
|
||||
return {"ok": True, "checkoutUrl": checkout["checkout_url"]}
|
||||
|
||||
|
||||
@router.post("/webhook")
|
||||
async def post_webhook(request: Request):
|
||||
raw = await request.body()
|
||||
raw_str = raw.decode()
|
||||
signature = request.headers.get("creem-signature")
|
||||
|
||||
if not verify_webhook_signature(raw_str, signature):
|
||||
logger.warning("Creem webhook: invalid signature")
|
||||
return JSONResponse({"ok": False}, 401)
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_str)
|
||||
except Exception:
|
||||
return JSONResponse({"ok": False}, 400)
|
||||
|
||||
event_type = payload.get("eventType", "")
|
||||
obj = payload.get("object", {})
|
||||
|
||||
logger.info(
|
||||
"Creem webhook: event=%s obj_id=%s status=%s email=%s",
|
||||
event_type,
|
||||
obj.get("id"),
|
||||
obj.get("status"),
|
||||
(obj.get("customer") or {}).get("email"),
|
||||
)
|
||||
|
||||
if event_type == "checkout.completed":
|
||||
await _handle_checkout_completed(obj)
|
||||
elif event_type == "refund.created":
|
||||
await _handle_refund(obj)
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
async def _handle_checkout_completed(obj: dict):
|
||||
order = obj.get("order", {})
|
||||
customer = obj.get("customer", {})
|
||||
email = customer.get("email", "")
|
||||
name = customer.get("name", "")
|
||||
|
||||
# Record purchase in PocketBase
|
||||
try:
|
||||
pb = get_pb()
|
||||
pb.collection("orders").create({
|
||||
"provider": "creem",
|
||||
"provider_id": obj.get("id", ""),
|
||||
"email": email,
|
||||
"customer_name": name,
|
||||
"amount_usd": (order.get("amount", 0)) / 100,
|
||||
"currency": order.get("currency", "USD"),
|
||||
"status": "paid",
|
||||
"meta": json.dumps(obj),
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("Failed to record Creem order: %s", e)
|
||||
|
||||
# Unlock content for user
|
||||
if email:
|
||||
try:
|
||||
pb = get_pb()
|
||||
existing = pb.collection("users").get_list(1, 1, {"filter": f'email="{email}"'})
|
||||
if existing.items:
|
||||
pb.collection("users").update(existing.items[0].id, {"has_purchased": True})
|
||||
else:
|
||||
pb.collection("users").create({
|
||||
"email": email,
|
||||
"name": name,
|
||||
"has_purchased": True,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning("Failed to update user purchase status: %s", e)
|
||||
|
||||
# Send download email
|
||||
if email:
|
||||
try:
|
||||
send_purchase_email(email, name or None)
|
||||
logger.info("Purchase email sent to %s", email)
|
||||
except Exception as e:
|
||||
logger.error("Failed to send purchase email: %s", e)
|
||||
|
||||
|
||||
async def _handle_refund(obj: dict):
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("orders").get_list(
|
||||
1, 1, {"filter": f'provider_id="{obj.get("id", "")}"'}
|
||||
)
|
||||
if records.items:
|
||||
pb.collection("orders").update(records.items[0].id, {"status": "refunded"})
|
||||
except Exception as e:
|
||||
logger.warning("Failed to update refund: %s", e)
|
||||
48
apps/ebook/backend/app/routers/feedback.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Feedback route."""
|
||||
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_pb
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["feedback"])
|
||||
logger = logging.getLogger("feedback")
|
||||
|
||||
|
||||
@router.post("/feedback")
|
||||
async def post_feedback(request: Request):
|
||||
body = await request.json()
|
||||
message = (body.get("message") or "").strip()
|
||||
if not message or len(message) < 4:
|
||||
return JSONResponse({"ok": False, "error": "message required"}, 400)
|
||||
|
||||
email = (body.get("email") or "").strip()
|
||||
|
||||
# Save to PocketBase
|
||||
try:
|
||||
pb = get_pb()
|
||||
pb.collection("feedback").create({
|
||||
"email": email,
|
||||
"message": message,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning("Failed to save feedback: %s", e)
|
||||
|
||||
# Forward to webhook if configured
|
||||
s = get_settings()
|
||||
if s.feedback_webhook_url:
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
await client.post(s.feedback_webhook_url, json={
|
||||
"email": email,
|
||||
"message": message,
|
||||
"at": __import__("datetime").datetime.utcnow().isoformat(),
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning("Feedback webhook failed: %s", e)
|
||||
|
||||
return {"ok": True}
|
||||
81
apps/ebook/backend/app/routers/pay.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""NOWPayments routes: create invoice + IPN webhook."""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ..db import get_pb
|
||||
from ..services.nowpayments import create_invoice, is_allowed_amount, verify_ipn_signature
|
||||
from ..config import get_settings
|
||||
|
||||
router = APIRouter(prefix="/api/pay", tags=["pay"])
|
||||
logger = logging.getLogger("pay")
|
||||
|
||||
|
||||
@router.post("/invoice")
|
||||
async def post_invoice(request: Request):
|
||||
s = get_settings()
|
||||
if not s.nowpayments_configured:
|
||||
return JSONResponse({"ok": False, "error": "payments not configured"}, 503)
|
||||
|
||||
body = await request.json()
|
||||
amount = int(body.get("amount", 0))
|
||||
if not is_allowed_amount(amount):
|
||||
return JSONResponse({"ok": False, "error": "invalid amount"}, 400)
|
||||
|
||||
try:
|
||||
invoice = await create_invoice(amount)
|
||||
except Exception as e:
|
||||
logger.error("NOWPayments invoice: %s", e)
|
||||
return JSONResponse({"ok": False, "error": "invoice failed"}, 502)
|
||||
|
||||
# Record in PocketBase
|
||||
try:
|
||||
pb = get_pb()
|
||||
pb.collection("orders").create({
|
||||
"provider": "nowpayments",
|
||||
"provider_id": invoice["id"],
|
||||
"amount_usd": amount,
|
||||
"status": "pending",
|
||||
"invoice_url": invoice["invoice_url"],
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning("Failed to record order: %s", e)
|
||||
|
||||
return {"ok": True, "invoiceUrl": invoice["invoice_url"]}
|
||||
|
||||
|
||||
@router.post("/ipn")
|
||||
async def post_ipn(request: Request):
|
||||
raw = await request.body()
|
||||
raw_str = raw.decode()
|
||||
signature = request.headers.get("x-nowpayments-sig")
|
||||
|
||||
if not verify_ipn_signature(raw_str, signature):
|
||||
return JSONResponse({"ok": False}, 401)
|
||||
|
||||
import json
|
||||
payload = json.loads(raw_str)
|
||||
logger.info(
|
||||
"NOWPayments IPN: status=%s order=%s amount=%s currency=%s paid=%s",
|
||||
payload.get("payment_status"),
|
||||
payload.get("order_id"),
|
||||
payload.get("price_amount"),
|
||||
payload.get("pay_currency"),
|
||||
payload.get("actually_paid"),
|
||||
)
|
||||
|
||||
# Update order status in PocketBase
|
||||
status = payload.get("payment_status", "")
|
||||
order_id = payload.get("order_id", "")
|
||||
if order_id and status:
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("orders").get_list(1, 1, {"filter": f'provider_id="{order_id}"'})
|
||||
if records.items:
|
||||
pb.collection("orders").update(records.items[0].id, {"status": status})
|
||||
except Exception as e:
|
||||
logger.warning("Failed to update order: %s", e)
|
||||
|
||||
return {"ok": True}
|
||||
210
apps/ebook/backend/app/routers/userdata.py
Normal file
@ -0,0 +1,210 @@
|
||||
"""User data sync: highlights, bookmarks, reading progress.
|
||||
|
||||
Replaces localStorage-only approach with PocketBase persistence.
|
||||
Client sends a device_id (or user token in the future) to identify the user.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..db import get_pb
|
||||
|
||||
router = APIRouter(prefix="/api/userdata", tags=["userdata"])
|
||||
logger = logging.getLogger("userdata")
|
||||
|
||||
|
||||
def _get_device_id(x_device_id: str | None = Header(None)) -> str:
|
||||
return (x_device_id or "").strip()
|
||||
|
||||
|
||||
# ── Highlights ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class HighlightIn(BaseModel):
|
||||
id: str
|
||||
slug: str
|
||||
text: str
|
||||
|
||||
|
||||
@router.get("/highlights")
|
||||
async def get_highlights(x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("highlights").get_list(
|
||||
1, 200, {"filter": f'device_id="{did}"', "sort": "-created"}
|
||||
)
|
||||
items = [{"id": r.id, "highlight_id": r.highlight_id, "slug": r.slug, "text": r.text} for r in records.items]
|
||||
return {"ok": True, "items": items}
|
||||
except Exception as e:
|
||||
logger.error("get highlights: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
@router.post("/highlights")
|
||||
async def save_highlight(data: HighlightIn, x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
pb.collection("highlights").create({
|
||||
"device_id": did,
|
||||
"highlight_id": data.id,
|
||||
"slug": data.slug,
|
||||
"text": data.text,
|
||||
})
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("save highlight: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
@router.delete("/highlights/{highlight_id}")
|
||||
async def delete_highlight(highlight_id: str, x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("highlights").get_list(
|
||||
1, 1, {"filter": f'device_id="{did}" && highlight_id="{highlight_id}"'}
|
||||
)
|
||||
if records.items:
|
||||
pb.collection("highlights").delete(records.items[0].id)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("delete highlight: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
# ── Bookmarks ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class BookmarkIn(BaseModel):
|
||||
slug: str
|
||||
scroll_y: float = 0
|
||||
title: str = ""
|
||||
|
||||
|
||||
@router.get("/bookmarks")
|
||||
async def get_bookmarks(x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("bookmarks").get_list(
|
||||
1, 50, {"filter": f'device_id="{did}"', "sort": "-created"}
|
||||
)
|
||||
items = [{"slug": r.slug, "scroll_y": r.scroll_y, "title": r.title} for r in records.items]
|
||||
return {"ok": True, "items": items}
|
||||
except Exception as e:
|
||||
logger.error("get bookmarks: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
@router.post("/bookmarks")
|
||||
async def save_bookmark(data: BookmarkIn, x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
# Upsert: remove old bookmark for same slug
|
||||
existing = pb.collection("bookmarks").get_list(
|
||||
1, 1, {"filter": f'device_id="{did}" && slug="{data.slug}"'}
|
||||
)
|
||||
if existing.items:
|
||||
pb.collection("bookmarks").delete(existing.items[0].id)
|
||||
pb.collection("bookmarks").create({
|
||||
"device_id": did,
|
||||
"slug": data.slug,
|
||||
"scroll_y": data.scroll_y,
|
||||
"title": data.title,
|
||||
})
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("save bookmark: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
@router.delete("/bookmarks/{slug}")
|
||||
async def delete_bookmark(slug: str, x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("bookmarks").get_list(
|
||||
1, 1, {"filter": f'device_id="{did}" && slug="{slug}"'}
|
||||
)
|
||||
if records.items:
|
||||
pb.collection("bookmarks").delete(records.items[0].id)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("delete bookmark: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
# ── Reading Progress ────────────────────────────────────────
|
||||
|
||||
|
||||
class ProgressIn(BaseModel):
|
||||
slug: str
|
||||
scroll_y: float = 0
|
||||
read_chapters: list[str] = []
|
||||
|
||||
|
||||
@router.get("/progress")
|
||||
async def get_progress(x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
records = pb.collection("reading_progress").get_list(
|
||||
1, 1, {"filter": f'device_id="{did}"', "sort": "-updated"}
|
||||
)
|
||||
if not records.items:
|
||||
return {"ok": True, "progress": None}
|
||||
r = records.items[0]
|
||||
return {"ok": True, "progress": {
|
||||
"slug": r.slug,
|
||||
"scroll_y": r.scroll_y,
|
||||
"read_chapters": r.read_chapters,
|
||||
}}
|
||||
except Exception as e:
|
||||
logger.error("get progress: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
|
||||
|
||||
@router.post("/progress")
|
||||
async def save_progress(data: ProgressIn, x_device_id: str | None = Header(None)):
|
||||
did = _get_device_id(x_device_id)
|
||||
if not did:
|
||||
return JSONResponse({"ok": False, "error": "device_id required"}, 400)
|
||||
try:
|
||||
pb = get_pb()
|
||||
existing = pb.collection("reading_progress").get_list(
|
||||
1, 1, {"filter": f'device_id="{did}"'}
|
||||
)
|
||||
record_data = {
|
||||
"device_id": did,
|
||||
"slug": data.slug,
|
||||
"scroll_y": data.scroll_y,
|
||||
"read_chapters": data.read_chapters,
|
||||
}
|
||||
if existing.items:
|
||||
pb.collection("reading_progress").update(existing.items[0].id, record_data)
|
||||
else:
|
||||
pb.collection("reading_progress").create(record_data)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("save progress: %s", e)
|
||||
return JSONResponse({"ok": False}, 500)
|
||||
0
apps/ebook/backend/app/services/__init__.py
Normal file
48
apps/ebook/backend/app/services/creem.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Creem: checkout creation + webhook signature verification."""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import get_settings
|
||||
from .payment_providers import get_payment_provider
|
||||
|
||||
|
||||
async def create_checkout() -> dict:
|
||||
s = get_settings()
|
||||
provider = get_payment_provider("creem")
|
||||
api_key = (provider.get("secrets") or {}).get("api_key") or s.creem_api_key
|
||||
product_id = (provider.get("secrets") or {}).get("product_id") or s.creem_product_id
|
||||
api_base = "https://test-api.creem.io" if str(api_key).startswith("creem_test_") else "https://api.creem.io"
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{api_base}/v1/checkouts",
|
||||
headers={"x-api-key": api_key, "Content-Type": "application/json"},
|
||||
json={
|
||||
"product_id": product_id,
|
||||
"success_url": f"{s.site_url}/purchase/thanks",
|
||||
"request_id": f"ebook-{int(__import__('time').time() * 1000)}",
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
if not data.get("checkout_url"):
|
||||
raise ValueError(data.get("message", "checkout creation failed"))
|
||||
return {"id": data.get("id", ""), "checkout_url": data["checkout_url"]}
|
||||
|
||||
|
||||
def verify_webhook_signature(raw_body: str, signature: str | None) -> bool:
|
||||
s = get_settings()
|
||||
provider = get_payment_provider("creem")
|
||||
webhook_secret = (provider.get("secrets") or {}).get("webhook_secret") or s.creem_webhook_secret
|
||||
|
||||
if not webhook_secret or not signature:
|
||||
return False
|
||||
expected = hmac.new(
|
||||
webhook_secret.encode(),
|
||||
raw_body.encode(),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
return hmac.compare_digest(expected, signature)
|
||||
54
apps/ebook/backend/app/services/email.py
Normal file
@ -0,0 +1,54 @@
|
||||
"""Send transactional emails via SMTP."""
|
||||
|
||||
import smtplib
|
||||
import ssl
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
from ..config import get_settings
|
||||
|
||||
|
||||
def send_purchase_email(to_email: str, customer_name: str | None = None) -> bool:
|
||||
s = get_settings()
|
||||
if not s.smtp_host or not s.smtp_user:
|
||||
return False
|
||||
|
||||
name = customer_name or "Reader"
|
||||
msg = MIMEMultipart("alternative")
|
||||
msg["Subject"] = "Your Nomad Code ebook — download links"
|
||||
msg["From"] = s.smtp_from
|
||||
msg["To"] = to_email
|
||||
|
||||
text = f"""Hi {name},
|
||||
|
||||
Thank you for purchasing the Nomad Code ebook!
|
||||
|
||||
Download your files here:
|
||||
PDF: {s.download_base_url}/nomad-code.pdf
|
||||
EPUB: {s.download_base_url}/nomad-code.epub
|
||||
|
||||
If you have any issues, reply to this email.
|
||||
|
||||
— Nomad Code
|
||||
"""
|
||||
html = f"""\
|
||||
<html><body style="font-family:sans-serif;line-height:1.6;color:#333">
|
||||
<h2>Hi {name},</h2>
|
||||
<p>Thank you for purchasing the <strong>Nomad Code</strong> ebook!</p>
|
||||
<p>Download your files:</p>
|
||||
<ul>
|
||||
<li><a href="{s.download_base_url}/nomad-code.pdf">PDF</a></li>
|
||||
<li><a href="{s.download_base_url}/nomad-code.epub">EPUB</a></li>
|
||||
</ul>
|
||||
<p>If you have any issues, reply to this email.</p>
|
||||
<p>— Nomad Code</p>
|
||||
</body></html>
|
||||
"""
|
||||
msg.attach(MIMEText(text, "plain"))
|
||||
msg.attach(MIMEText(html, "html"))
|
||||
|
||||
ctx = ssl.create_default_context()
|
||||
with smtplib.SMTP_SSL(s.smtp_host, s.smtp_port, context=ctx) as server:
|
||||
server.login(s.smtp_user, s.smtp_pass)
|
||||
server.sendmail(s.smtp_from, to_email, msg.as_string())
|
||||
return True
|
||||
79
apps/ebook/backend/app/services/nowpayments.py
Normal file
@ -0,0 +1,79 @@
|
||||
"""NOWPayments: invoice creation + IPN signature verification."""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import get_settings
|
||||
from .payment_providers import get_payment_provider
|
||||
|
||||
API_BASE = "https://api.nowpayments.io/v1"
|
||||
|
||||
SUPPORT_TIERS = [
|
||||
{"amount": 5, "label": "Coffee"},
|
||||
{"amount": 10, "label": "Lunch"},
|
||||
{"amount": 20, "label": "Sponsor"},
|
||||
]
|
||||
|
||||
ALLOWED_AMOUNTS = {t["amount"] for t in SUPPORT_TIERS}
|
||||
|
||||
|
||||
def is_allowed_amount(amount: int | float) -> bool:
|
||||
return amount in ALLOWED_AMOUNTS
|
||||
|
||||
|
||||
def _sort_obj(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {k: _sort_obj(v) for k, v in sorted(value.items())}
|
||||
return value
|
||||
|
||||
|
||||
async def create_invoice(amount_usd: int) -> dict:
|
||||
s = get_settings()
|
||||
price = 5.5 if amount_usd == 5 else float(amount_usd)
|
||||
|
||||
provider = get_payment_provider("nowpayments")
|
||||
api_key = (provider.get("secrets") or {}).get("api_key") or s.nowpayments_api_key
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{API_BASE}/invoice",
|
||||
headers={"x-api-key": api_key, "Content-Type": "application/json"},
|
||||
json={
|
||||
"price_amount": price,
|
||||
"price_currency": "usd",
|
||||
"order_id": f"support-{amount_usd}-{int(__import__('time').time() * 1000)}",
|
||||
"order_description": f"Support Nomad Code — ${amount_usd}",
|
||||
"ipn_callback_url": f"{s.site_url}/api/pay/ipn",
|
||||
"success_url": f"{s.site_url}/support/thanks",
|
||||
"cancel_url": s.site_url,
|
||||
"is_fee_paid_by_user": True,
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
if not data.get("invoice_url"):
|
||||
raise ValueError(data.get("message", "invoice creation failed"))
|
||||
return {"id": str(data.get("id", "")), "invoice_url": data["invoice_url"]}
|
||||
|
||||
|
||||
def verify_ipn_signature(raw_body: str, signature: str | None) -> bool:
|
||||
if not signature:
|
||||
return False
|
||||
s = get_settings()
|
||||
payload = json.loads(raw_body)
|
||||
sorted_payload = json.dumps(_sort_obj(payload), separators=(",", ":"))
|
||||
|
||||
provider = get_payment_provider("nowpayments")
|
||||
ipn_secret = (provider.get("secrets") or {}).get("ipn_secret") or s.nowpayments_ipn_secret
|
||||
|
||||
expected = hmac.new(
|
||||
ipn_secret.encode(),
|
||||
sorted_payload.encode(),
|
||||
hashlib.sha512,
|
||||
).hexdigest()
|
||||
return hmac.compare_digest(expected, signature)
|
||||
41
apps/ebook/backend/app/services/payment_providers.py
Normal file
@ -0,0 +1,41 @@
|
||||
"""Read/write payment provider configs in PocketBase."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ..db import get_pb
|
||||
|
||||
|
||||
def _list_all_providers():
|
||||
pb = get_pb()
|
||||
try:
|
||||
# PocketBase filter/sort params may vary across versions.
|
||||
# For admin UI stability, fetch first page without filter and match in Python.
|
||||
res = pb.collection("payment_providers").get_list(1, 50)
|
||||
return res.items or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _get_provider_record(provider: str):
|
||||
for it in _list_all_providers():
|
||||
if getattr(it, "provider", None) == provider:
|
||||
return it
|
||||
return None
|
||||
|
||||
|
||||
def get_payment_provider(provider: str) -> dict[str, Any]:
|
||||
rec = _get_provider_record(provider)
|
||||
if not rec:
|
||||
return {"provider": provider, "secrets": {}, "config": {}}
|
||||
return {"provider": rec.provider, "secrets": rec.secrets or {}, "config": rec.config or {}}
|
||||
|
||||
|
||||
def upsert_payment_provider(provider: str, secrets: dict[str, Any], config: dict[str, Any]) -> None:
|
||||
pb = get_pb()
|
||||
rec = _get_provider_record(provider)
|
||||
data = {"provider": provider, "secrets": secrets, "config": config}
|
||||
if rec:
|
||||
pb.collection("payment_providers").update(rec.id, data)
|
||||
else:
|
||||
pb.collection("payment_providers").create(data)
|
||||
|
||||
7
apps/ebook/backend/requirements.txt
Normal file
@ -0,0 +1,7 @@
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.30
|
||||
pocketbase>=0.12
|
||||
python-dotenv>=1.0
|
||||
httpx>=0.27
|
||||
pydantic>=2.0
|
||||
pydantic-settings>=2.0
|
||||
73
apps/ebook/content/book.json
Normal file
@ -0,0 +1,73 @@
|
||||
{
|
||||
"title": "游牧代码",
|
||||
"subtitle": "数字游民与 Homelab 生存指南",
|
||||
"author": "林远",
|
||||
"description": "一个程序员离开工位、带上电脑环游世界,同时把「家」装进机柜的故事。",
|
||||
"tagline": "在任意城市,过你想要的生活。",
|
||||
"coverGradient": "from-violet-950 via-fuchsia-900 to-orange-900",
|
||||
"readingMinutes": 45,
|
||||
"viralTags": ["数字游民", "Homelab", "远程办公", "Tailscale", "自由职业"],
|
||||
"stats": [
|
||||
{ "emoji": "🌍", "value": "7", "label": "章精华" },
|
||||
{ "emoji": "⏱️", "value": "45", "label": "分钟读完" },
|
||||
{ "emoji": "📍", "value": "3+", "label": "城市灵感" },
|
||||
{ "emoji": "🔥", "value": "12", "label": "书摘片段" }
|
||||
],
|
||||
"hooks": [
|
||||
{ "emoji": "💻", "text": "远程办公的第一周,效率奇高。第二周,你开始分不清「工作结束」和「生活开始」。" },
|
||||
{ "emoji": "🌴", "text": "清迈的周二早晨:flat white + VS Code,旁边有人在写旅行博客。" },
|
||||
{ "emoji": "🗄️", "text": "Homelab 给你的锚,不是地理上的,是数字上的——文件在,服务在,随时等你回来。" },
|
||||
{ "emoji": "🔑", "text": "Tailscale:无论 IP 怎么变,你的设备永远在「同一个局域网」。" }
|
||||
],
|
||||
"chapters": [
|
||||
{
|
||||
"slug": "00-preface",
|
||||
"title": "序:我为什么开始游牧",
|
||||
"emoji": "✈️",
|
||||
"hook": "我想要的不是更好的工位,而是可以选择坐在哪里。",
|
||||
"shareQuote": "数字游民是一种工作方式:产出不绑定在某个地理坐标上。"
|
||||
},
|
||||
{
|
||||
"slug": "01-first-remote",
|
||||
"title": "第一次远程办公的那个周五",
|
||||
"emoji": "🏠",
|
||||
"hook": "穿着睡衣开 Zoom,可能是当代最魔幻的上班方式。",
|
||||
"shareQuote": "异步沟通:不是「随时在线」,而是「明确预期」。"
|
||||
},
|
||||
{
|
||||
"slug": "02-chiangmai",
|
||||
"title": "清迈的周二早晨",
|
||||
"emoji": "☕",
|
||||
"hook": "游牧不是一个人流浪,是在流动中找到同类。",
|
||||
"shareQuote": "在这里,旅游和工作本来就不矛盾。"
|
||||
},
|
||||
{
|
||||
"slug": "03-gear",
|
||||
"title": "行囊里真正重要的东西",
|
||||
"emoji": "🎒",
|
||||
"hook": "带多了是负担,带少了会后悔——这是游牧者的永恒命题。",
|
||||
"shareQuote": "网络,比护照更重要。"
|
||||
},
|
||||
{
|
||||
"slug": "04-homelab",
|
||||
"title": "Homelab:把家装进一个机柜",
|
||||
"emoji": "🖥️",
|
||||
"hook": "几百块的旧电脑,可以成为整个数字生活的中枢。",
|
||||
"shareQuote": "完美是优秀的敌人。先跑起来,再迭代。"
|
||||
},
|
||||
{
|
||||
"slug": "05-network",
|
||||
"title": "无论在哪,都能连回家",
|
||||
"emoji": "🔗",
|
||||
"hook": "人在巴厘岛,手在家里。",
|
||||
"shareQuote": "Homelab 服务默认不暴露公网——这是安全感的前提。"
|
||||
},
|
||||
{
|
||||
"slug": "06-epilogue",
|
||||
"title": "终章:自由是一种日常",
|
||||
"emoji": "🌅",
|
||||
"hook": "自由不是不用工作,而是可以选择在哪里、以什么节奏工作。",
|
||||
"shareQuote": "小步验证,比宏大计划更可靠。"
|
||||
}
|
||||
]
|
||||
}
|
||||
31
apps/ebook/content/chapters/00-preface.md
Normal file
@ -0,0 +1,31 @@
|
||||
# 序:我为什么开始游牧
|
||||
|
||||
二〇二三年秋天,我在公司工位上坐满了三年。
|
||||
|
||||
显示器左边是 Jira,右边是 Slack,中间是我已经改过十七遍的需求文档。某个加班的深夜,我刷到一张清迈咖啡馆的照片——阳光从百叶窗缝里漏进来,一台 MacBook 和一杯冰美式,背景里有人在用泰语点单。
|
||||
|
||||
那一刻我突然意识到:**我想要的不是更好的工位,而是可以选择坐在哪里。**
|
||||
|
||||
---
|
||||
|
||||
## 这不是逃离
|
||||
|
||||
很多人把数字游民理解成「辞职、环游世界、发 Instagram」。不是的。
|
||||
|
||||
数字游民是一种**工作方式**:你的产出不绑定在某个地理坐标上。你可以在上海写代码,也可以在里斯本写代码——只要网络稳定、时区能协调、交付不掉链子。
|
||||
|
||||
Homelab 则是另一种自由:无论你在哪个时区醒来,你的文件、你的服务、你的数据,都在一个你完全掌控的地方等着你。
|
||||
|
||||
这本书写的,就是这两件事如何交织在一起。
|
||||
|
||||
---
|
||||
|
||||
## 你会读到什么
|
||||
|
||||
这不是技术文档,也不是旅行攻略。这是一个普通程序员,从第一次远程办公,到在东南亚租下月付公寓,再到把家里那台旧服务器变成「随时能连回去的数字基地」的真实过程。
|
||||
|
||||
有踩过的坑,也有意外的好运。
|
||||
|
||||
如果你也在想:**能不能不辞职,但换一种活法?**
|
||||
|
||||
那就从下一章开始吧。
|
||||
39
apps/ebook/content/chapters/01-first-remote.md
Normal file
@ -0,0 +1,39 @@
|
||||
# 第一次远程办公的那个周五
|
||||
|
||||
周五下午三点,Team Leader 在群里发了一条消息:
|
||||
|
||||
> 「下周开始,技术组全员 remote,有问题的私聊 HR。」
|
||||
|
||||
我盯着这条消息看了很久。不是担心,是一种奇怪的安静——像考试结束铃响之前,你已经写完了最后一道题。
|
||||
|
||||
---
|
||||
|
||||
## 第一天
|
||||
|
||||
周一早上九点,我穿着睡衣坐在餐桌前,打开 Zoom。
|
||||
|
||||
同事们的脸出现在格子里,有人还在刷牙,有人背景是乱糟糟的卧室。会议结束后,我泡了杯咖啡,走到阳台。
|
||||
|
||||
楼下有人在遛狗,阳光很好。
|
||||
|
||||
**原来工作日也可以是这样。**
|
||||
|
||||
---
|
||||
|
||||
## 效率的幻觉
|
||||
|
||||
远程的第一周,我效率奇高。没有通勤,没有工位旁的闲聊,没有「开完这个会再写代码」的拖延。
|
||||
|
||||
第二周,我开始分不清「工作结束」和「生活开始」的边界。晚上十一点,Slack 还亮着绿点。周末,邮箱里躺着三条「不急,周一前看就行」的消息。
|
||||
|
||||
我学到一个词:**异步沟通**。不是「随时在线」,而是「明确预期」——什么时候回复、什么算紧急、什么可以等到下一个工作日。
|
||||
|
||||
---
|
||||
|
||||
## 那个周五的后续
|
||||
|
||||
三个月后,HR 发邮件说办公室租约到期,技术组永久 remote。
|
||||
|
||||
我没有回「太好了」,也没有回「怎么办」。我只是打开地图,搜索了「清迈 月租 公寓 WiFi」。
|
||||
|
||||
有些改变,不是突然发生的。是你某天回头看,发现路已经走了一半。
|
||||
44
apps/ebook/content/chapters/02-chiangmai.md
Normal file
@ -0,0 +1,44 @@
|
||||
# 清迈的周二早晨
|
||||
|
||||
七点半,我被摩托车声叫醒。
|
||||
|
||||
不是闹钟——是楼下送菜的小贩,喇叭里循环播放泰语,我一个字也听不懂,但已经习惯了。这是我在清迈的第三周。
|
||||
|
||||
---
|
||||
|
||||
## 咖啡馆即办公室
|
||||
|
||||
我住的公寓步行十分钟有一家叫 **Graph Table** 的咖啡馆。二层靠窗的位置,能看到一条安静的小巷。WiFi 密码写在收银台的小黑板上,下载速度稳定在 80 Mbps 左右。
|
||||
|
||||
我点一杯 flat white,打开 VS Code。
|
||||
|
||||
旁边的荷兰设计师在画 Figma,日本背包客在写旅行博客。没有人问「你是来旅游的还是来工作的」——在这里,这两件事本来就不矛盾。
|
||||
|
||||
---
|
||||
|
||||
## 时区的艺术
|
||||
|
||||
我在东七区,团队大部分人在东八区。这意味着:
|
||||
|
||||
- 我的「早上十点 standup」,是清迈的九点
|
||||
- 他们的「下班前 review」,是我的下午五点——刚好收工去夜市
|
||||
|
||||
我学会把深度工作放在本地上午,把会议和沟通压缩到下午。不是妥协,是**设计**。
|
||||
|
||||
---
|
||||
|
||||
## 孤独与社群
|
||||
|
||||
数字游民最容易被忽视的问题,不是签证,不是网络,是**孤独**。
|
||||
|
||||
我在 Nomad List 的 Discord 里认识了几个常驻清迈的开发者。我们每周三晚上在 Nimman 区聚餐,聊技术、聊签证、聊哪个 co-working 空间的空调更冷。
|
||||
|
||||
**游牧不是一个人流浪,是在流动中找到同类。**
|
||||
|
||||
---
|
||||
|
||||
## 周二的结尾
|
||||
|
||||
晚上八点,我骑摩托车回公寓。路过塔佩门,游客正在拍夜景。我停了一分钟,然后继续往前。
|
||||
|
||||
明天还有 standup。但此刻,清迈的风是温的。
|
||||
45
apps/ebook/content/chapters/03-gear.md
Normal file
@ -0,0 +1,45 @@
|
||||
# 行囊里真正重要的东西
|
||||
|
||||
出发前,我在 Reddit 的 r/digitalnomad 翻了三天装备帖。最后发现:**带多了是负担,带少了会后悔。**
|
||||
|
||||
这是我在路上一年后,精简再精简的清单。
|
||||
|
||||
---
|
||||
|
||||
## 电脑:唯一不能妥协的
|
||||
|
||||
一台 14 寸 MacBook Pro,M 系列芯片,16GB 内存。不是最新款,但足够跑 Docker、开十几个 Chrome 标签、同时 Zoom 和写代码。
|
||||
|
||||
外接显示器?我试过,最后卖了。游牧的核心是**移动**,不是把工位复制到每一个城市。
|
||||
|
||||
---
|
||||
|
||||
## 网络:比护照更重要
|
||||
|
||||
我随身带三样东西:
|
||||
|
||||
1. **本地 SIM 卡** — 落地当天买,流量包月
|
||||
2. **便携路由器** — GL.iNet 那类,支持 4G 备用
|
||||
3. **Tailscale** — 后面会细讲,这是连回 Homelab 的钥匙
|
||||
|
||||
在清迈、巴厘岛、里斯本,我学会的第一件事永远是:先测 WiFi,再 unpack。
|
||||
|
||||
---
|
||||
|
||||
## 其他:能省则省
|
||||
|
||||
- 降噪耳机:飞机、咖啡馆、合租房必备
|
||||
- 万能转换插头:一个就够
|
||||
- 折叠键盘:可选,我最后只用笔记本自带
|
||||
|
||||
衣服?一个 40L 背包,七天的量,到哪里都能洗。
|
||||
|
||||
---
|
||||
|
||||
## 真正重要的
|
||||
|
||||
装备可以列清单,但有三样东西清单上写不下:
|
||||
|
||||
**稳定的收入、可预期的工作节奏、以及一个随时可以回去的地方。**
|
||||
|
||||
第三个,Homelab 会帮你解决。
|
||||
48
apps/ebook/content/chapters/04-homelab.md
Normal file
@ -0,0 +1,48 @@
|
||||
# Homelab:把家装进一个机柜
|
||||
|
||||
二〇二二年,我还住在租来的单间里,床底下藏着一台 Dell OptiPlex 小主机。
|
||||
|
||||
当时只是想跑个 Plex,把电影串流到手机。没想到,这台几百块的机器,后来成了我整个数字生活的中枢。
|
||||
|
||||
---
|
||||
|
||||
## 什么是 Homelab
|
||||
|
||||
Homelab,字面意思是「家庭实验室」。简单说,就是**你自己搭的、自己管的服务器环境**。
|
||||
|
||||
不是云服务那种「按月订阅、数据在别人机房」。是你的 NAS、你的 Git 仓库、你的笔记同步、你的自动化脚本——物理上可能就在你国内那个出租屋里,逻辑上却跟着你走遍世界。
|
||||
|
||||
---
|
||||
|
||||
## 我的第一套配置
|
||||
|
||||
| 组件 | 选择 | 用途 |
|
||||
|------|------|------|
|
||||
| 主机 | Dell OptiPlex 7040 | 7×24 低功耗运行 |
|
||||
| 系统 | Proxmox | 虚拟机管理 |
|
||||
| 存储 | 4TB 机械 + 256GB SSD | 文件 + 系统 |
|
||||
| 服务 | Jellyfin, Nextcloud, Gitea | 媒体、同步、代码 |
|
||||
|
||||
总花费不到三千块。比一台新 iPhone 便宜,但价值在于:**它是你的。**
|
||||
|
||||
---
|
||||
|
||||
## 为什么游牧者需要 Homelab
|
||||
|
||||
人在清迈,文件在上海的硬盘里——听起来很蠢,对吧?
|
||||
|
||||
但云盘有容量限制,有审查风险,有「服务条款变更」的隐患。Homelab 给你的,是**数据主权**和**不受地点限制的访问权**。
|
||||
|
||||
配合 Tailscale 或 WireGuard,你在任何 WiFi 下,都能像坐在家里一样访问自己的服务。
|
||||
|
||||
---
|
||||
|
||||
## 从一台旧电脑开始
|
||||
|
||||
你不需要一上来就买机柜、交换机、UPS。
|
||||
|
||||
找一台闲置笔记本,装 Linux,跑一个 Nextcloud 或 FileBrowser。能远程访问,就算 Homelab 入门了。
|
||||
|
||||
**完美是优秀的敌人。先跑起来,再迭代。**
|
||||
|
||||
下一章,我们聊怎么「连回家」。
|
||||
59
apps/ebook/content/chapters/05-network.md
Normal file
@ -0,0 +1,59 @@
|
||||
# 无论在哪,都能连回家
|
||||
|
||||
清迈咖啡馆的 WiFi 突然断了。
|
||||
|
||||
我切换到手机热点,打开终端,输入:
|
||||
|
||||
```bash
|
||||
ssh nas
|
||||
```
|
||||
|
||||
三秒后,我出现在家里那台 Proxmox 主机的 shell 里。文件在,服务在,就像从未离开过。
|
||||
|
||||
靠的是 **Tailscale**。
|
||||
|
||||
---
|
||||
|
||||
## 虚拟局域网
|
||||
|
||||
Tailscale 基于 WireGuard,把你在不同网络的设备,组成一个加密的虚拟局域网(Tailnet)。
|
||||
|
||||
家里跑 Tailscale 的 NAS,笔记本跑 Tailscale 客户端——无论 IP 怎么变,它们永远在「同一个局域网」里。
|
||||
|
||||
配置过程:
|
||||
|
||||
1. 在 Homelab 主机安装 Tailscale
|
||||
2. 笔记本、手机同样安装并登录同一账号
|
||||
3. 用 MagicDNS 给设备起名字,比如 `nas.tail-xxxxx.ts.net`
|
||||
|
||||
不需要公网 IP,不需要端口转发,不需要折腾路由器。
|
||||
|
||||
---
|
||||
|
||||
## 我常用的远程场景
|
||||
|
||||
**同步文件** — Nextcloud 客户端走 Tailscale 内网,速度比公网快,也不暴露服务到互联网。
|
||||
|
||||
**看代码** — Gitea 跑在内网,浏览器打开 `http://gitea:3000`,只有 Tailnet 里的设备能访问。
|
||||
|
||||
**紧急修复** — 生产环境告警,SSH 进去,改配置,重启服务。人在巴厘岛,手在家里。
|
||||
|
||||
---
|
||||
|
||||
## 安全习惯
|
||||
|
||||
- Homelab 服务**默认不暴露公网**
|
||||
- 敏感操作走 SSH 密钥,禁用密码登录
|
||||
- 定期备份到另一块硬盘,异地再备一份
|
||||
|
||||
网络自由的前提,是**安全意识**不能掉线。
|
||||
|
||||
---
|
||||
|
||||
## 连回家,意味着什么
|
||||
|
||||
游牧者容易有一种漂流感:今天这条街,明天那座城,没有锚。
|
||||
|
||||
Homelab 给我的锚,不是地理上的,是**数字上的**——我知道有一个地方,存着我的东西,跑着我的服务,随时等我回来。
|
||||
|
||||
这种确定感,和清迈的咖啡一样,是/nomad 生活的基础设施。
|
||||
49
apps/ebook/content/chapters/06-epilogue.md
Normal file
@ -0,0 +1,49 @@
|
||||
# 终章:自由是一种日常
|
||||
|
||||
写这本书时,我人在里斯本。
|
||||
|
||||
公寓窗外是电车轨道,偶尔有铃声。桌上有半杯 bica,电脑屏幕里是未提交的 commit。
|
||||
|
||||
---
|
||||
|
||||
## 自由不是假期
|
||||
|
||||
很多人把数字游民想象成「永远在度假」。实际上,周二依然是周二,需求依然会改,bug 依然会在上线前出现。
|
||||
|
||||
**自由不是不用工作,而是可以选择在哪里、以什么节奏工作。**
|
||||
|
||||
---
|
||||
|
||||
## Homelab 与游牧的共生
|
||||
|
||||
这两件事看起来方向相反:
|
||||
|
||||
- 游牧是**流动**
|
||||
- Homelab 是**固定**
|
||||
|
||||
但组合在一起,逻辑就通了:你在物理世界移动,数字世界的「家」保持不动。像蜗牛的壳,不是负担,是随身携带的秩序。
|
||||
|
||||
---
|
||||
|
||||
## 给正在考虑的你
|
||||
|
||||
如果你还在工位上读这本书,不必立刻辞职,不必立刻买票。
|
||||
|
||||
你可以:
|
||||
|
||||
1. 先和团队谈一次 remote 的可能性
|
||||
2. 用一台旧电脑搭一个最小 Homelab
|
||||
3. 选一个周末,带着电脑去邻城住两晚,测试「在别处工作」的感觉
|
||||
|
||||
**小步验证,比宏大计划更可靠。**
|
||||
|
||||
---
|
||||
|
||||
## 最后
|
||||
|
||||
游牧代码,写的不是「如何逃离」,而是「如何建造」——建造一种你真正想要的生活,并用技术和纪律去支撑它。
|
||||
|
||||
书到这里结束。你的下一章,在自己手里。
|
||||
|
||||
—— 林远
|
||||
写于里斯本,一个普通的周二
|
||||
73
apps/ebook/content/en/book.json
Normal file
@ -0,0 +1,73 @@
|
||||
{
|
||||
"title": "Nomad Code",
|
||||
"subtitle": "A Digital Nomad & Homelab Survival Guide",
|
||||
"author": "Lin Yuan",
|
||||
"description": "A programmer leaves the office, travels with a laptop, and packs \"home\" into a rack.",
|
||||
"tagline": "Live the life you want — from any city.",
|
||||
"coverGradient": "from-violet-950 via-fuchsia-900 to-orange-900",
|
||||
"readingMinutes": 45,
|
||||
"viralTags": ["DigitalNomad", "Homelab", "RemoteWork", "Tailscale", "Freelance"],
|
||||
"stats": [
|
||||
{ "emoji": "🌍", "value": "7", "label": "Chapters" },
|
||||
{ "emoji": "⏱️", "value": "45", "label": "Min read" },
|
||||
{ "emoji": "📍", "value": "3+", "label": "City ideas" },
|
||||
{ "emoji": "🔥", "value": "12", "label": "Quotes" }
|
||||
],
|
||||
"hooks": [
|
||||
{ "emoji": "💻", "text": "Week one of remote work: productivity soars. Week two: you can't tell when work ends and life begins." },
|
||||
{ "emoji": "🌴", "text": "Tuesday morning in Chiang Mai: flat white + VS Code, someone writing a travel blog nearby." },
|
||||
{ "emoji": "🗄️", "text": "Homelab is your anchor — not geographic, but digital. Files stay, services stay, waiting for you." },
|
||||
{ "emoji": "🔑", "text": "Tailscale: no matter how IPs change, your devices stay on the same LAN." }
|
||||
],
|
||||
"chapters": [
|
||||
{
|
||||
"slug": "00-preface",
|
||||
"title": "Preface: Why I Started Nomading",
|
||||
"emoji": "✈️",
|
||||
"hook": "I didn't want a better desk — I wanted to choose where I sit.",
|
||||
"shareQuote": "Digital nomadism is a way of working: output isn't tied to a place."
|
||||
},
|
||||
{
|
||||
"slug": "01-first-remote",
|
||||
"title": "That First Remote Friday",
|
||||
"emoji": "🏠",
|
||||
"hook": "Zoom in pajamas might be the most surreal way to work today.",
|
||||
"shareQuote": "Async communication: not \"always online\", but \"clear expectations\"."
|
||||
},
|
||||
{
|
||||
"slug": "02-chiangmai",
|
||||
"title": "Tuesday Morning in Chiang Mai",
|
||||
"emoji": "☕",
|
||||
"hook": "Nomading isn't wandering alone — it's finding your people on the move.",
|
||||
"shareQuote": "Here, travel and work were never at odds."
|
||||
},
|
||||
{
|
||||
"slug": "03-gear",
|
||||
"title": "What Actually Matters in Your Bag",
|
||||
"emoji": "🎒",
|
||||
"hook": "Pack too much and you're burdened; too little and you'll regret it.",
|
||||
"shareQuote": "Connectivity matters more than passports."
|
||||
},
|
||||
{
|
||||
"slug": "04-homelab",
|
||||
"title": "Homelab: Home in a Rack",
|
||||
"emoji": "🖥️",
|
||||
"hook": "An old PC can become the hub of your digital life.",
|
||||
"shareQuote": "Perfect is the enemy of good. Ship first, iterate later."
|
||||
},
|
||||
{
|
||||
"slug": "05-network",
|
||||
"title": "Connect Home from Anywhere",
|
||||
"emoji": "🔗",
|
||||
"hook": "Body in Bali, hands at home.",
|
||||
"shareQuote": "Homelab services shouldn't face the public internet — that's the baseline for safety."
|
||||
},
|
||||
{
|
||||
"slug": "06-epilogue",
|
||||
"title": "Epilogue: Freedom as a Daily Practice",
|
||||
"emoji": "🌅",
|
||||
"hook": "Freedom isn't not working — it's choosing where and at what pace you work.",
|
||||
"shareQuote": "Small experiments beat grand plans."
|
||||
}
|
||||
]
|
||||
}
|
||||
94
apps/ebook/content/features.json
Normal file
@ -0,0 +1,94 @@
|
||||
{
|
||||
"$schema": "./features.schema.json",
|
||||
"$comment": "功能模块总开关 — 关闭任何模块不影响其余功能",
|
||||
|
||||
"analytics": {
|
||||
"enabled": true,
|
||||
"provider": "ga4",
|
||||
"measurementId": ""
|
||||
},
|
||||
|
||||
"ads": {
|
||||
"enabled": false,
|
||||
"provider": "adsense",
|
||||
"clientId": "",
|
||||
"slots": {
|
||||
"cover": "",
|
||||
"readerMid": "",
|
||||
"readerEnd": ""
|
||||
}
|
||||
},
|
||||
|
||||
"payment": {
|
||||
"crypto": {
|
||||
"enabled": true,
|
||||
"provider": "nowpayments",
|
||||
"tiers": [
|
||||
{ "amount": 5, "label": "Coffee" },
|
||||
{ "amount": 10, "label": "Lunch" },
|
||||
{ "amount": 20, "label": "Sponsor" }
|
||||
]
|
||||
},
|
||||
"checkout": {
|
||||
"enabled": true,
|
||||
"provider": "creem",
|
||||
"buttonText": "Buy Now — $29",
|
||||
"productName": "Download Edition (PDF & EPUB)"
|
||||
}
|
||||
},
|
||||
|
||||
"feedback": {
|
||||
"enabled": true,
|
||||
"title": "这本书对你有帮助吗?",
|
||||
"subtitle": "欢迎提建议、纠错或合作联系,我会认真看每一条。"
|
||||
},
|
||||
|
||||
"affiliate": {
|
||||
"enabled": true,
|
||||
"rules": [
|
||||
{
|
||||
"hosts": ["amazon.com", "amzn.to", "amazon.cn"],
|
||||
"param": "tag=your-amazon-tag-20"
|
||||
},
|
||||
{
|
||||
"hosts": ["taobao.com", "tmall.com"],
|
||||
"rewrite": "https://s.click.taobao.com/t?eurl={encoded}&union_lens=lensId"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"share": {
|
||||
"enabled": true,
|
||||
"campaign": "nomad-code",
|
||||
"defaultHashtags": ["数字游民", "Homelab", "远程办公"],
|
||||
"viralPrompt": {
|
||||
"enabled": true,
|
||||
"triggerPercent": 42
|
||||
}
|
||||
},
|
||||
|
||||
"reader": {
|
||||
"bookmarks": { "enabled": true },
|
||||
"highlights": { "enabled": true },
|
||||
"search": { "enabled": true },
|
||||
"progress": { "enabled": true },
|
||||
"zen": { "enabled": true },
|
||||
"shortcuts": { "enabled": true },
|
||||
"themeToggle": { "enabled": true },
|
||||
"fontControl": { "enabled": true }
|
||||
},
|
||||
|
||||
"userdata": {
|
||||
"enabled": true,
|
||||
"syncToServer": false,
|
||||
"$comment": "syncToServer=true 时书签/划线/进度同步到 PocketBase,否则仅 localStorage"
|
||||
},
|
||||
|
||||
"backend": {
|
||||
"pocketbase": { "enabled": true },
|
||||
"email": {
|
||||
"enabled": false,
|
||||
"$comment": "需要配置 SMTP 环境变量才能发送购买邮件"
|
||||
}
|
||||
}
|
||||
}
|
||||
8
apps/ebook/content/site.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"$comment": "品牌身份信息 — 模块开关和配置见 features.json",
|
||||
"brand": {
|
||||
"name": "游牧代码",
|
||||
"xHandle": "@linyuan",
|
||||
"contactEmail": "hello@example.com"
|
||||
}
|
||||
}
|
||||
49
apps/ebook/deploy/caddy-book.caddy
Normal file
@ -0,0 +1,49 @@
|
||||
# ebook — Markdown reader + FastAPI backend
|
||||
# https://book.nomadro.com
|
||||
|
||||
book.nomadro.com {
|
||||
encode gzip
|
||||
|
||||
# FastAPI backend — all /api/* except Next.js static routes
|
||||
handle /api/pay/* {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/creem/* {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/feedback {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/userdata/* {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/health {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/admin/* {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/docs {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
handle /api/openapi.json {
|
||||
reverse_proxy 127.0.0.1:8010
|
||||
}
|
||||
|
||||
# PocketBase admin UI (optional, restrict in production)
|
||||
handle /pb/* {
|
||||
uri strip_prefix /pb
|
||||
reverse_proxy 127.0.0.1:8090
|
||||
}
|
||||
|
||||
# Everything else → Next.js
|
||||
handle {
|
||||
reverse_proxy 127.0.0.1:3022
|
||||
}
|
||||
}
|
||||
|
||||
# 直连 IP 访问
|
||||
http://107.173.30.245 {
|
||||
encode gzip
|
||||
reverse_proxy 127.0.0.1:3022
|
||||
}
|
||||
9
apps/ebook/deploy/caddy_probe.py
Normal file
@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
_, stdout, _ = client.exec_command("cat /etc/caddy/Caddyfile")
|
||||
print(stdout.read().decode("utf-8", errors="replace"))
|
||||
client.close()
|
||||
41
apps/ebook/deploy/check_server.py
Normal file
@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
USER = "root"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
|
||||
def run(client, cmd):
|
||||
print(">", cmd)
|
||||
_, stdout, stderr = client.exec_command(cmd, timeout=60)
|
||||
out = stdout.read().decode("utf-8", errors="replace").strip()
|
||||
err = stderr.read().decode("utf-8", errors="replace").strip()
|
||||
if out:
|
||||
print(out)
|
||||
if err:
|
||||
print("ERR:", err)
|
||||
return stdout.channel.recv_exit_status()
|
||||
|
||||
|
||||
def main():
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
|
||||
print("=== STATUS ===")
|
||||
run(client, "pm2 status 2>/dev/null || echo PM2_NOT_INSTALLED")
|
||||
run(client, "curl -sf -o /dev/null -w 'app:%{http_code}' http://127.0.0.1:3000/ || echo app:DOWN")
|
||||
run(client, "curl -sf -o /dev/null -w 'nginx:%{http_code}' http://127.0.0.1/ || echo nginx:DOWN")
|
||||
run(client, "test -d /var/www/ebook && cd /var/www/ebook && git log -1 --oneline || echo NO_REPO")
|
||||
run(client, "pgrep -af next || pgrep -af standalone || echo NO_NODE_APP")
|
||||
|
||||
client.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
23
apps/ebook/deploy/domain_probe.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
cmds = [
|
||||
"dig +short book.nomadro.com A",
|
||||
"dig +short book.noamdro.com A",
|
||||
"ls -la /etc/caddy/sites/",
|
||||
"grep -r book /etc/caddy/ 2>/dev/null",
|
||||
"curl -sk -o /dev/null -w 'book.nomadro.com:%{http_code}\n' https://book.nomadro.com/",
|
||||
"curl -sI -H 'Host: book.nomadro.com' http://127.0.0.1/ | head -8",
|
||||
"ss -tlnp | grep -E ':3000|:4003|:4403'",
|
||||
"pm2 status",
|
||||
]
|
||||
for c in cmds:
|
||||
print("===", c)
|
||||
_, stdout, stderr = client.exec_command(c)
|
||||
out = stdout.read().decode("utf-8", errors="replace")
|
||||
err = stderr.read().decode("utf-8", errors="replace")
|
||||
print(out or err)
|
||||
client.close()
|
||||
51
apps/ebook/deploy/ecosystem.config.cjs
Normal file
@ -0,0 +1,51 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function parseEnvFile(file) {
|
||||
const out = {};
|
||||
if (!fs.existsSync(file)) return out;
|
||||
for (const raw of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const eq = line.indexOf('=');
|
||||
if (eq < 1) continue;
|
||||
const key = line.slice(0, eq).trim();
|
||||
let val = line.slice(eq + 1).trim();
|
||||
if (
|
||||
(val.startsWith('"') && val.endsWith('"')) ||
|
||||
(val.startsWith("'") && val.endsWith("'"))
|
||||
) {
|
||||
val = val.slice(1, -1);
|
||||
}
|
||||
out[key] = val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const secretEnv = {
|
||||
...parseEnvFile(path.join(__dirname, 'nowpayments.env')),
|
||||
...parseEnvFile(path.join(__dirname, '..', '.env')),
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'ebook',
|
||||
script: 'server.js',
|
||||
cwd: '/var/www/ebook/.next/standalone',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
autorestart: true,
|
||||
watch: false,
|
||||
max_memory_restart: '512M',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
PORT: 3022,
|
||||
HOSTNAME: '0.0.0.0',
|
||||
NEXT_PUBLIC_SITE_URL: 'https://book.nomadro.com',
|
||||
NEXT_PUBLIC_SHARE_CAMPAIGN: 'nomad-code',
|
||||
...secretEnv,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
70
apps/ebook/deploy/install.sh
Normal file
@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env bash
|
||||
# Git 拉取部署:服务器上 git pull → build → pm2 重启
|
||||
set -euo pipefail
|
||||
|
||||
APP_DIR="/var/www/ebook"
|
||||
GIT_HOST="${GIT_HOST:-gitea.dsx2020.com}"
|
||||
GIT_USER="${GIT_USER:-eric}"
|
||||
GIT_PASS="${GIT_PASS:?Set GIT_PASS for git pull}"
|
||||
GIT_REPO="${GIT_REPO:-eric/ebook.git}"
|
||||
BRANCH="${BRANCH:-dev1}"
|
||||
|
||||
REPO_URL="https://${GIT_USER}:${GIT_PASS}@${GIT_HOST}/${GIT_REPO}"
|
||||
|
||||
export NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://book.nomadro.com}"
|
||||
export NEXT_PUBLIC_SHARE_CAMPAIGN="${NEXT_PUBLIC_SHARE_CAMPAIGN:-nomad-code}"
|
||||
|
||||
echo "==> Node $(node -v 2>/dev/null || echo 'not installed')"
|
||||
|
||||
if ! command -v node >/dev/null 2>&1; then
|
||||
echo "==> Installing Node.js 20..."
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt-get install -y nodejs
|
||||
fi
|
||||
|
||||
if [ ! -d "$APP_DIR/.git" ]; then
|
||||
echo "==> git clone $BRANCH"
|
||||
mkdir -p "$APP_DIR"
|
||||
git clone -b "$BRANCH" "$REPO_URL" "$APP_DIR"
|
||||
else
|
||||
echo "==> git pull $BRANCH"
|
||||
cd "$APP_DIR"
|
||||
git remote set-url origin "$REPO_URL"
|
||||
git fetch origin "$BRANCH"
|
||||
git reset --hard "origin/$BRANCH"
|
||||
fi
|
||||
|
||||
cd "$APP_DIR"
|
||||
|
||||
echo "==> npm ci (含 dev 依赖,供 next build)..."
|
||||
NODE_ENV=development npm ci --prefer-offline --no-audit --no-fund
|
||||
|
||||
echo "==> npm run build..."
|
||||
rm -rf "$APP_DIR/.next"
|
||||
NEXT_PUBLIC_SITE_URL="$NEXT_PUBLIC_SITE_URL" NEXT_PUBLIC_SHARE_CAMPAIGN="$NEXT_PUBLIC_SHARE_CAMPAIGN" npm run build
|
||||
|
||||
echo "==> standalone assets..."
|
||||
STANDALONE="$APP_DIR/.next/standalone"
|
||||
cp -r public "$STANDALONE/public" 2>/dev/null || true
|
||||
mkdir -p "$STANDALONE/.next"
|
||||
cp -r .next/static "$STANDALONE/.next/static"
|
||||
cp -r content "$STANDALONE/content"
|
||||
cp -f "$APP_DIR/.env" "$STANDALONE/.env" 2>/dev/null || true
|
||||
cp -f "$APP_DIR/deploy/nowpayments.env" "$STANDALONE/.env.nowpayments" 2>/dev/null || true
|
||||
|
||||
if ! command -v pm2 >/dev/null 2>&1; then
|
||||
npm install -g pm2
|
||||
fi
|
||||
|
||||
fuser -k 3022/tcp 2>/dev/null || true
|
||||
pm2 delete ebook 2>/dev/null || true
|
||||
pm2 start deploy/ecosystem.config.cjs
|
||||
pm2 save
|
||||
|
||||
echo "==> Deploy frontend OK"
|
||||
curl -sf -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:3022/ || echo "WARN: app not responding yet"
|
||||
|
||||
echo "==> Installing backend (FastAPI + PocketBase)..."
|
||||
bash "$APP_DIR/deploy/install_backend.sh"
|
||||
|
||||
echo "==> Deploy ALL OK"
|
||||
124
apps/ebook/deploy/install_backend.sh
Normal file
@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install PocketBase + FastAPI backend on VPS
|
||||
set -euo pipefail
|
||||
|
||||
APP_DIR="/var/www/ebook"
|
||||
BACKEND_DIR="$APP_DIR/backend"
|
||||
PB_DIR="/opt/pocketbase"
|
||||
PB_VERSION="0.25.9"
|
||||
|
||||
# ── PocketBase ──────────────────────────────────────────────
|
||||
|
||||
echo "==> PocketBase setup"
|
||||
if [ ! -f "$PB_DIR/pocketbase" ]; then
|
||||
mkdir -p "$PB_DIR"
|
||||
cd /tmp
|
||||
wget -q "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_amd64.zip" -O pb.zip
|
||||
unzip -o pb.zip -d "$PB_DIR"
|
||||
rm pb.zip
|
||||
echo " installed PocketBase $PB_VERSION"
|
||||
else
|
||||
echo " PocketBase already installed"
|
||||
fi
|
||||
|
||||
# systemd service for PocketBase
|
||||
cat > /etc/systemd/system/pocketbase.service <<'SVC'
|
||||
[Unit]
|
||||
Description=PocketBase
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/opt/pocketbase/pocketbase serve --http=127.0.0.1:8090
|
||||
WorkingDirectory=/opt/pocketbase
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
SVC
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable pocketbase
|
||||
systemctl restart pocketbase
|
||||
sleep 2
|
||||
echo " PocketBase status: $(systemctl is-active pocketbase)"
|
||||
|
||||
# ── Ensure superuser exists (for creating collections / admin APIs) ──
|
||||
echo "==> PocketBase superuser upsert"
|
||||
BACKEND_ENV_FILE="$BACKEND_DIR/.env"
|
||||
PB_ADMIN_EMAIL=""
|
||||
PB_ADMIN_PASSWORD=""
|
||||
if [ -f "$BACKEND_ENV_FILE" ]; then
|
||||
while IFS='=' read -r k v; do
|
||||
k="$(echo "$k" | tr -d '\r')"
|
||||
v="$(echo "$v" | tr -d '\r')"
|
||||
if [ "$k" = "PB_ADMIN_EMAIL" ]; then PB_ADMIN_EMAIL="$v"; fi
|
||||
if [ "$k" = "PB_ADMIN_PASSWORD" ]; then PB_ADMIN_PASSWORD="$v"; fi
|
||||
done < "$BACKEND_ENV_FILE"
|
||||
fi
|
||||
if [ -n "$PB_ADMIN_EMAIL" ] && [ -n "$PB_ADMIN_PASSWORD" ]; then
|
||||
/opt/pocketbase/pocketbase superuser upsert "$PB_ADMIN_EMAIL" "$PB_ADMIN_PASSWORD" >/dev/null 2>&1 || true
|
||||
echo " superuser ensured: $PB_ADMIN_EMAIL"
|
||||
else
|
||||
echo " WARN: PB_ADMIN_EMAIL/PB_ADMIN_PASSWORD missing in backend/.env"
|
||||
fi
|
||||
|
||||
# ── Python + FastAPI ────────────────────────────────────────
|
||||
|
||||
echo "==> Python + FastAPI setup"
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq python3 python3-pip python3-venv >/dev/null 2>&1
|
||||
fi
|
||||
|
||||
cd "$BACKEND_DIR"
|
||||
|
||||
if [ ! -d "venv" ]; then
|
||||
python3 -m venv venv
|
||||
fi
|
||||
|
||||
source venv/bin/activate
|
||||
pip install -q --upgrade pip
|
||||
pip install -q -r requirements.txt
|
||||
|
||||
# systemd service for FastAPI
|
||||
cat > /etc/systemd/system/ebook-api.service <<SVC
|
||||
[Unit]
|
||||
Description=Ebook FastAPI Backend
|
||||
After=network.target pocketbase.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=$BACKEND_DIR
|
||||
ExecStart=$BACKEND_DIR/venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8010
|
||||
EnvironmentFile=$BACKEND_DIR/.env
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
SVC
|
||||
|
||||
fuser -k 8010/tcp 2>/dev/null || true
|
||||
fuser -k 8090/tcp 2>/dev/null || true
|
||||
systemctl daemon-reload
|
||||
systemctl enable ebook-api
|
||||
systemctl restart pocketbase
|
||||
systemctl restart ebook-api
|
||||
sleep 2
|
||||
echo " FastAPI status: $(systemctl is-active ebook-api)"
|
||||
|
||||
# ── PocketBase schema + seed payment providers ───────────────
|
||||
echo "==> PocketBase schema"
|
||||
cd "$BACKEND_DIR"
|
||||
source venv/bin/activate
|
||||
python -m app.pb_schema || echo " WARN: pb_schema failed"
|
||||
|
||||
# ── Health check ────────────────────────────────────────────
|
||||
|
||||
echo "==> Health checks"
|
||||
curl -sf http://127.0.0.1:8090/api/health || echo " WARN: PocketBase not responding"
|
||||
curl -sf http://127.0.0.1:8010/api/health || echo " WARN: FastAPI not responding"
|
||||
echo ""
|
||||
echo "==> Backend deploy OK"
|
||||
17
apps/ebook/deploy/nginx-book.conf
Normal file
@ -0,0 +1,17 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name book.nomadro.com 107.173.30.245;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3022;
|
||||
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_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
23
apps/ebook/deploy/nginx_probe.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
USER = "root"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
cmds = [
|
||||
"nginx -V 2>&1 | head -1",
|
||||
"ls -la /etc/nginx/ 2>/dev/null || echo NO_NGINX",
|
||||
"ls -la /etc/nginx/conf.d/ 2>/dev/null || true",
|
||||
"ls -la /etc/nginx/sites-available/ 2>/dev/null || true",
|
||||
"cat /etc/nginx/nginx.conf 2>/dev/null | head -40",
|
||||
]
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(HOST, username=USER, password=PASS, timeout=20)
|
||||
for c in cmds:
|
||||
print(">", c)
|
||||
_, stdout, _ = client.exec_command(c)
|
||||
print(stdout.read().decode())
|
||||
client.close()
|
||||
21
apps/ebook/deploy/pay_probe.py
Normal file
@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
cmds = [
|
||||
"cd /var/www/ebook && git log -1 --oneline",
|
||||
"test -f /var/www/ebook/.next/standalone/server.js && echo HAS_STANDALONE",
|
||||
"ls /var/www/ebook/.next/standalone/src/app/api/pay 2>/dev/null || ls /var/www/ebook/.next/standalone/.next/server/app/api/pay 2>/dev/null || echo NO_PAY_ROUTE",
|
||||
"grep -n NOWPAYMENTS /proc/$(pgrep -n -f 'next-server' | head -1)/environ 2>/dev/null | tr '\\0' '\\n' | grep NOWPAY || pm2 prettylist | grep -i nowpay | head",
|
||||
"curl -s -o /dev/null -w 'local_post:%{http_code}\n' -H 'Content-Type: application/json' -d '{\"amount\":5}' http://127.0.0.1:3000/api/pay/invoice",
|
||||
"curl -s -m 35 -H 'Content-Type: application/json' -d '{\"amount\":5}' http://127.0.0.1:3000/api/pay/invoice | head -c 400",
|
||||
"echo",
|
||||
"cat /etc/caddy/sites/book.nomadro.com.caddy",
|
||||
]
|
||||
for c in cmds:
|
||||
print("===", c)
|
||||
_, stdout, stderr = client.exec_command(c, timeout=45)
|
||||
print(stdout.read().decode("utf-8", errors="replace") or stderr.read().decode("utf-8", errors="replace"))
|
||||
client.close()
|
||||
23
apps/ebook/deploy/pay_probe2.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
cmds = [
|
||||
"ls -la /var/www/ebook/.next/standalone/.next/server/app/api/pay/invoice/",
|
||||
"python3 - <<'PY'\nimport json\np='/var/www/ebook/.next/standalone/.next/app-path-routes-manifest.json'\ntry:\n print(open(p).read()[:2000])\nexcept Exception as e:\n print('no manifest', e)\nPY",
|
||||
"curl -s -o /dev/null -w 'thanks:%{http_code} get_invoice:%{http_code}\\n' http://127.0.0.1:3000/support/thanks http://127.0.0.1:3000/api/pay/invoice",
|
||||
"curl -s -o /dev/null -w 'thanks:%{http_code}\\n' http://127.0.0.1:3000/support/thanks",
|
||||
"curl -s -o /dev/null -w 'get_inv:%{http_code}\\n' http://127.0.0.1:3000/api/pay/invoice",
|
||||
"ss -tlnp | grep 3000",
|
||||
"pm2 describe ebook | head -40",
|
||||
]
|
||||
for c in cmds:
|
||||
print("===", c[:80])
|
||||
_, stdout, stderr = client.exec_command(c, timeout=30)
|
||||
print(stdout.read().decode("utf-8", errors="replace"))
|
||||
err = stderr.read().decode("utf-8", errors="replace")
|
||||
if err.strip():
|
||||
print("ERR", err[:500])
|
||||
client.close()
|
||||
15
apps/ebook/deploy/pay_probe3.py
Normal file
@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
cmds = [
|
||||
"tail -n 80 /root/.pm2/logs/ebook-error-0.log",
|
||||
"ss -tlnp | awk '{print $4}' | sed 's/.*://' | sort -n | uniq",
|
||||
]
|
||||
for c in cmds:
|
||||
print("===", c)
|
||||
_, stdout, _ = client.exec_command(c, timeout=20)
|
||||
print(stdout.read().decode("utf-8", errors="replace")[-4000:])
|
||||
client.close()
|
||||
16
apps/ebook/deploy/port_probe.py
Normal file
@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
for c in [
|
||||
"ss -tlnp | grep ':80 '",
|
||||
"ss -tlnp | grep ':3000 '",
|
||||
"curl -sI http://127.0.0.1/ | head -10",
|
||||
"curl -sI http://127.0.0.1:3000/ | head -10",
|
||||
"curl -sI -H 'Host: book.noamdro.com' http://127.0.0.1/ | head -10",
|
||||
]:
|
||||
print(">", c)
|
||||
_, stdout, _ = client.exec_command(c)
|
||||
print(stdout.read().decode())
|
||||
client.close()
|
||||
6
apps/ebook/deploy/pull.sh
Normal file
@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# 服务器上日常更新:git pull + build + 重启(已由 install.sh 实现,此为快捷入口)
|
||||
set -euo pipefail
|
||||
export GIT_USER="${GIT_USER:-eric}"
|
||||
export GIT_PASS="${GIT_PASS:?export GIT_PASS=your_gitea_password}"
|
||||
exec "$(dirname "$0")/install.sh"
|
||||
9
apps/ebook/deploy/read_book_caddy.py
Normal file
@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
_, stdout, _ = client.exec_command("cat /etc/caddy/sites/book.nomadro.com.caddy")
|
||||
print(stdout.read().decode("utf-8", errors="replace"))
|
||||
client.close()
|
||||
8
apps/ebook/deploy/read_nginx_conf.py
Normal file
@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect("107.173.30.245", username="root", password="Xiao4669805", timeout=20)
|
||||
_, stdout, _ = client.exec_command("cat /etc/nginx/conf.d/sing_box_VMess_HTTPUpgrade.conf")
|
||||
print(stdout.read().decode())
|
||||
client.close()
|
||||
75
apps/ebook/deploy/remote_deploy.py
Normal file
@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从本机触发 VPS 部署:SSH + Git pull (eric) + build + pm2"""
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
SSH_USER = "root"
|
||||
SSH_PASS = "Xiao4669805"
|
||||
GIT_USER = "eric"
|
||||
GIT_PASS = "Xiao4669805"
|
||||
|
||||
REMOTE = f"""set -e
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
export GIT_USER={GIT_USER}
|
||||
export GIT_PASS={GIT_PASS}
|
||||
export NEXT_PUBLIC_SITE_URL=https://book.nomadro.com
|
||||
export NEXT_PUBLIC_SHARE_CAMPAIGN=nomad-code
|
||||
|
||||
echo '=== [1/4] system deps ==='
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq git curl ca-certificates python3 python3-pip python3-venv unzip wget >/dev/null 2>&1 || true
|
||||
|
||||
echo '=== [2/4] git pull + build (server-side, ~3 min) ==='
|
||||
export GIT_PASS={GIT_PASS}
|
||||
if [ -f /var/www/ebook/deploy/install.sh ] && [ -d /var/www/ebook/.git ]; then
|
||||
bash /var/www/ebook/deploy/install.sh
|
||||
else
|
||||
rm -rf /var/www/ebook
|
||||
mkdir -p /var/www
|
||||
git clone -b dev1 https://{GIT_USER}:{GIT_PASS}@gitea.dsx2020.com/eric/ebook.git /var/www/ebook
|
||||
bash /var/www/ebook/deploy/install.sh
|
||||
fi
|
||||
|
||||
echo '=== [3/4] caddy reverse proxy ==='
|
||||
mkdir -p /etc/caddy/sites
|
||||
cp /var/www/ebook/deploy/caddy-book.caddy /etc/caddy/sites/book.nomadro.com.caddy
|
||||
rm -f /etc/caddy/sites/book.caddy
|
||||
caddy validate --config /etc/caddy/Caddyfile
|
||||
systemctl reload caddy
|
||||
|
||||
sleep 2
|
||||
echo '=== [4/4] health checks ==='
|
||||
curl -sf -o /dev/null -w 'nextjs:%{{http_code}}\\n' http://127.0.0.1:3022/ || true
|
||||
curl -sf -o /dev/null -w 'fastapi:%{{http_code}}\\n' http://127.0.0.1:8010/api/health || true
|
||||
curl -sf -o /dev/null -w 'pocketbase:%{{http_code}}\\n' http://127.0.0.1:8090/api/health || true
|
||||
curl -sf -o /dev/null -w 'caddy:%{{http_code}}\\n' -H 'Host: book.nomadro.com' http://127.0.0.1/ || true
|
||||
pm2 status || true
|
||||
systemctl status ebook-api --no-pager -l || true
|
||||
systemctl status pocketbase --no-pager -l || true
|
||||
echo '=== DEPLOY DONE ==='
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
print(f"SSH -> {HOST} | Git -> eric@gitea (dev1)")
|
||||
client.connect(HOST, username=SSH_USER, password=SSH_PASS, timeout=30, banner_timeout=60)
|
||||
print("Connected. Deploying via git pull...")
|
||||
_, stdout, stderr = client.exec_command(REMOTE, get_pty=True)
|
||||
for line in iter(stdout.readline, ""):
|
||||
print(line, end="", flush=True)
|
||||
err = stderr.read().decode("utf-8", errors="replace")
|
||||
if err.strip():
|
||||
print("STDERR:", err)
|
||||
code = stdout.channel.recv_exit_status()
|
||||
client.close()
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
30
apps/ebook/deploy/restart_ebook.py
Normal file
@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
HOST = "107.173.30.245"
|
||||
REMOTE = r"""set -e
|
||||
export GIT_PASS=Xiao4669805
|
||||
cd /var/www/ebook
|
||||
git remote set-url origin https://eric:Xiao4669805@gitea.dsx2020.com/eric/ebook.git
|
||||
git fetch origin dev1 && git reset --hard origin/dev1
|
||||
cp deploy/caddy-book.caddy /etc/caddy/sites/book.nomadro.com.caddy
|
||||
caddy validate --config /etc/caddy/Caddyfile
|
||||
systemctl reload caddy
|
||||
pm2 delete ebook 2>/dev/null || true
|
||||
fuser -k 3022/tcp 2>/dev/null || true
|
||||
pm2 start /var/www/ebook/deploy/ecosystem.config.cjs
|
||||
pm2 save
|
||||
sleep 2
|
||||
pm2 describe ebook | head -20
|
||||
curl -s -o /dev/null -w 'app:%{http_code}\n' http://127.0.0.1:3022/
|
||||
curl -s -m 40 -H 'Content-Type: application/json' -d '{"amount":5}' http://127.0.0.1:3022/api/pay/invoice | head -c 300
|
||||
echo
|
||||
"""
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(HOST, username="root", password="Xiao4669805", timeout=30)
|
||||
_, stdout, _ = client.exec_command(REMOTE, get_pty=True)
|
||||
for line in iter(stdout.readline, ""):
|
||||
print(line, end="", flush=True)
|
||||
print("exit", stdout.channel.recv_exit_status())
|
||||
client.close()
|
||||
29
apps/ebook/deploy/setup_caddy.py
Normal file
@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
REMOTE = """set -e
|
||||
export GIT_PASS=Xiao4669805
|
||||
cd /var/www/ebook
|
||||
git remote set-url origin https://eric:Xiao4669805@gitea.dsx2020.com/eric/ebook.git
|
||||
git fetch origin dev1 && git reset --hard origin/dev1
|
||||
mkdir -p /etc/caddy/sites
|
||||
cp deploy/caddy-book.caddy /etc/caddy/sites/book.caddy
|
||||
caddy validate --config /etc/caddy/Caddyfile
|
||||
systemctl reload caddy
|
||||
sleep 2
|
||||
curl -sf -o /dev/null -w 'app:%{http_code}\n' http://127.0.0.1:3000/
|
||||
curl -sI -H 'Host: book.noamdro.com' http://127.0.0.1/ | head -5
|
||||
curl -sk -o /dev/null -w 'https:%{http_code}\n' https://book.noamdro.com/ || echo https:pending_dns
|
||||
"""
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(HOST, username="root", password=PASS, timeout=30)
|
||||
_, stdout, _ = client.exec_command(REMOTE, get_pty=True)
|
||||
for line in iter(stdout.readline, ""):
|
||||
print(line, end="")
|
||||
client.close()
|
||||
42
apps/ebook/deploy/switch_domain.py
Normal file
@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""切换 book.nomadro.com → ebook + 重建"""
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
REMOTE = """set -e
|
||||
export GIT_USER=eric
|
||||
export GIT_PASS=Xiao4669805
|
||||
export NEXT_PUBLIC_SITE_URL=https://book.nomadro.com
|
||||
export NEXT_PUBLIC_SHARE_CAMPAIGN=nomad-code
|
||||
|
||||
cd /var/www/ebook
|
||||
git remote set-url origin https://eric:Xiao4669805@gitea.dsx2020.com/eric/ebook.git
|
||||
git fetch origin dev1 && git reset --hard origin/dev1
|
||||
|
||||
bash deploy/install.sh
|
||||
|
||||
mkdir -p /etc/caddy/sites
|
||||
cp deploy/caddy-book.caddy /etc/caddy/sites/book.nomadro.com.caddy
|
||||
rm -f /etc/caddy/sites/book.caddy
|
||||
caddy validate --config /etc/caddy/Caddyfile
|
||||
systemctl reload caddy
|
||||
|
||||
sleep 2
|
||||
curl -sk -o /dev/null -w 'https:%{http_code}\n' https://book.nomadro.com/
|
||||
curl -s https://book.nomadro.com/ | head -c 200
|
||||
echo
|
||||
"""
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
print("Deploying book.nomadro.com...")
|
||||
client.connect(HOST, username="root", password=PASS, timeout=30, banner_timeout=60)
|
||||
_, stdout, _ = client.exec_command(REMOTE, get_pty=True)
|
||||
for line in iter(stdout.readline, ""):
|
||||
print(line, end="", flush=True)
|
||||
code = stdout.channel.recv_exit_status()
|
||||
client.close()
|
||||
sys.exit(code)
|
||||
30
apps/ebook/dymini/.gitignore
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
# 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
|
||||
50
apps/ebook/dymini/README.md
Normal file
@ -0,0 +1,50 @@
|
||||
# Dymini(抖音小程序电子书)
|
||||
|
||||
抖音小程序电子书,结构对齐微信版 [`../wemini`](../wemini/)。现为 monorepo [`ebook`](../README.md) 子目录。支付暂为模拟发货(`TT_PAY_MOCK=true`)。
|
||||
|
||||
| 模块 | 技术 | 目录 |
|
||||
|------|------|------|
|
||||
| 小程序 | Taro 4 + React(`tt`) | `miniapp/` |
|
||||
| API | FastAPI + SQLite | `backend/` |
|
||||
| 管理后台 | Vite + React | `admin/` |
|
||||
| 内容稿 | Markdown | `data/ebook.md` |
|
||||
| 运维 | nginx / systemd / 脚本 | `deploy/` |
|
||||
|
||||
## 域名与密钥
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| API | https://dyapi.nomadro.cn(线上 **:8011**) |
|
||||
| Admin | https://dyadmin.nomadro.cn |
|
||||
| AppID | `tt995defe007255b2701` |
|
||||
| AppSecret | `8628800c6f2290175180b94e255380c2e9d34dc0` |
|
||||
| 后台 | `admin` / `Xiao4669805` |
|
||||
| JWT | `dymini-jwt-2026` |
|
||||
| 默认道具 | `ebook_unlock_default` @ ¥188(试读 **100%**,便于联调) |
|
||||
| 支付 | `TT_PAY_MOCK=true` |
|
||||
| ntfy | 默认关;topic `dymini` |
|
||||
|
||||
> **注意:** `dy.nomadro.cn` 服务器上已有其他业务(WG 网关),本项目**不会覆盖**该站点。落地页可用 `dyadmin`。
|
||||
|
||||
抖音后台 request 合法域名请加:`dyapi.nomadro.cn`。更多凭证见 `douyin.txt`、`backend/.env`。
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
# API :8000
|
||||
cd backend && .\.venv\Scripts\uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||||
|
||||
# 小程序 watch → dist/
|
||||
cd miniapp && npm run dev:tt
|
||||
```
|
||||
|
||||
或仓库根脚本:`npm run dev:api` / `dev:admin` / `dev:miniapp`。
|
||||
|
||||
抖音开发者工具打开本目录下 `miniapp/`,关闭合法域名校验。
|
||||
|
||||
## 部署
|
||||
|
||||
```bash
|
||||
cd admin && npm run build
|
||||
python deploy/deploy.py
|
||||
```
|
||||
15
apps/ebook/dymini/admin/index.html
Normal file
@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Nomadro Admin</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@600;700;800&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
1834
apps/ebook/dymini/admin/package-lock.json
generated
Normal file
23
apps/ebook/dymini/admin/package.json
Normal file
@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "dymini-admin",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0 --port 5173",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview --host 0.0.0.0 --port 5173"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.11"
|
||||
}
|
||||
}
|
||||
BIN
apps/ebook/dymini/admin/public/props/ebook.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
apps/ebook/dymini/admin/public/props/nomad.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
apps/ebook/dymini/admin/public/props/svip.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
apps/ebook/dymini/admin/public/props/test.png
Normal file
|
After Width: | Height: | Size: 2.7 KiB |
BIN
apps/ebook/dymini/admin/public/props/tiktok.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
apps/ebook/dymini/admin/public/props/youtube.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
39
apps/ebook/dymini/admin/src/App.tsx
Normal file
@ -0,0 +1,39 @@
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { getToken } from './api'
|
||||
import Login from './pages/Login'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import BookEdit from './pages/BookEdit'
|
||||
import './pages/BookEdit.css'
|
||||
import Orders from './pages/Orders'
|
||||
import Users from './pages/Users'
|
||||
import Events from './pages/Events'
|
||||
import Checklist from './pages/Checklist'
|
||||
import Layout from './components/Layout'
|
||||
|
||||
function Private({ children }: { children: React.ReactNode }) {
|
||||
if (!getToken()) return <Navigate to="/login" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<Private>
|
||||
<Layout />
|
||||
</Private>
|
||||
}
|
||||
>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="books/:id" element={<BookEdit />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="events" element={<Events />} />
|
||||
<Route path="checklist" element={<Checklist />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
2
apps/ebook/dymini/admin/src/api.ts
Normal file
@ -0,0 +1,2 @@
|
||||
/** @deprecated 请从 `./api/client` 导入;保留以兼容现有页面 */
|
||||
export * from './api/client'
|
||||
3
apps/ebook/dymini/admin/src/api/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# API 层:请求封装(admin)
|
||||
|
||||
后续可按领域拆成 `books.ts` / `orders.ts`;类型见 `@dymini/shared-types` 或本地 `types/`。
|
||||
37
apps/ebook/dymini/admin/src/api/client.ts
Normal file
@ -0,0 +1,37 @@
|
||||
const TOKEN_KEY = 'dymini_admin_token'
|
||||
|
||||
/** 生产:同域空串(nginx 反代 /api);本地 Vite proxy */
|
||||
export const API_BASE = import.meta.env.VITE_API_BASE || ''
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
export function setToken(t: string) {
|
||||
localStorage.setItem(TOKEN_KEY, t)
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(init.headers as Record<string, string> | undefined),
|
||||
}
|
||||
const token = getToken()
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
|
||||
if (res.status === 401) {
|
||||
clearToken()
|
||||
if (!path.includes('/login')) window.location.href = '/login'
|
||||
}
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
const err = data as { detail?: string; message?: string }
|
||||
throw new Error(err.detail || err.message || '请求失败')
|
||||
}
|
||||
return data as T
|
||||
}
|
||||
39
apps/ebook/dymini/admin/src/components/Layout.tsx
Normal file
@ -0,0 +1,39 @@
|
||||
import { NavLink, Outlet, useNavigate } from 'react-router-dom'
|
||||
import { clearToken } from '../api'
|
||||
|
||||
export default function Layout() {
|
||||
const nav = useNavigate()
|
||||
return (
|
||||
<div className="shell">
|
||||
<aside className="side">
|
||||
<div className="logo">
|
||||
<span className="logo-mark">N</span>
|
||||
<div>
|
||||
<div className="logo-title">Dymini</div>
|
||||
<div className="logo-sub">抖音电子书后台</div>
|
||||
</div>
|
||||
</div>
|
||||
<nav className="nav">
|
||||
<NavLink to="/" end>概览</NavLink>
|
||||
<NavLink to="/books/default">书籍与试读%</NavLink>
|
||||
<NavLink to="/users">读者</NavLink>
|
||||
<NavLink to="/orders">订单</NavLink>
|
||||
<NavLink to="/events">埋点</NavLink>
|
||||
<NavLink to="/checklist">部署检查清单</NavLink>
|
||||
</nav>
|
||||
<button
|
||||
className="ghost-btn"
|
||||
onClick={() => {
|
||||
clearToken()
|
||||
nav('/login')
|
||||
}}
|
||||
>
|
||||
退出登录
|
||||
</button>
|
||||
</aside>
|
||||
<main className="main">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
13
apps/ebook/dymini/admin/src/main.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './styles.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
478
apps/ebook/dymini/admin/src/pages/BookEdit.css
Normal file
@ -0,0 +1,478 @@
|
||||
.book-edit-page .head-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.file-btn,
|
||||
.ghost {
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--text);
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.meta-form {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.editor-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr 1fr;
|
||||
gap: 14px;
|
||||
min-height: 70vh;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.editor-grid.full {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.chapter-rail {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: rgba(0, 0, 0, 0.18);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.rail-title {
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
.rail-list {
|
||||
overflow: auto;
|
||||
max-height: 68vh;
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.rail-item {
|
||||
text-align: left;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
border-radius: 10px;
|
||||
padding: 10px 10px;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
grid-template-columns: 28px 1fr;
|
||||
gap: 8px;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.rail-item em {
|
||||
font-style: normal;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rail-item.active,
|
||||
.rail-item:hover {
|
||||
background: rgba(94, 196, 120, 0.12);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.editor-pane,
|
||||
.preview-pane {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: rgba(0, 0, 0, 0.18);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 70vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pane-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.md-editor {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
border: none;
|
||||
resize: none;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 16px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.md-preview {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 16px 18px 28px;
|
||||
color: #d7ebdd;
|
||||
line-height: 1.75;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.md-preview h1,
|
||||
.md-preview h2,
|
||||
.md-preview h3 {
|
||||
font-family: var(--font-display);
|
||||
color: #f2fff7;
|
||||
margin: 16px 0 8px;
|
||||
}
|
||||
|
||||
.md-preview img {
|
||||
display: block;
|
||||
width: 80%;
|
||||
max-width: 80%;
|
||||
height: auto;
|
||||
margin: 12px auto;
|
||||
border-radius: 10px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.md-preview blockquote {
|
||||
margin: 10px 0;
|
||||
padding: 8px 12px;
|
||||
border-left: 3px solid #6fcf8f;
|
||||
background: rgba(90, 170, 120, 0.12);
|
||||
color: #b7d8c2;
|
||||
}
|
||||
|
||||
.md-preview code {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.md-preview a {
|
||||
color: #8fd4a8;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.editor-grid,
|
||||
.editor-grid.full {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.rail-list {
|
||||
max-height: 240px;
|
||||
}
|
||||
.editor-pane,
|
||||
.preview-pane {
|
||||
min-height: 420px;
|
||||
}
|
||||
}
|
||||
|
||||
.offer-board {
|
||||
margin-bottom: 18px;
|
||||
padding: 16px;
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.monetize-panel {
|
||||
margin-bottom: 22px;
|
||||
padding: 18px;
|
||||
border-radius: 18px;
|
||||
border: 1px solid rgba(167, 139, 250, 0.22);
|
||||
background:
|
||||
radial-gradient(520px 180px at 0% 0%, rgba(244, 114, 182, 0.12), transparent 60%),
|
||||
rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.monetize-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 18px;
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.monetize-title {
|
||||
margin: 0 0 6px;
|
||||
font-family: var(--font-display);
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.live-preview {
|
||||
min-width: 220px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 16px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
background: rgba(12, 11, 18, 0.55);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.live-preview-label {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.live-btn {
|
||||
height: 44px;
|
||||
border-radius: 999px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
color: #3b0764;
|
||||
background: linear-gradient(135deg, #ffffff, #fce7f3);
|
||||
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.live-btn.free {
|
||||
color: #062012;
|
||||
background: linear-gradient(135deg, #bbf7d0, #6ee7b7);
|
||||
}
|
||||
|
||||
.live-preview-sub {
|
||||
font-size: 12px;
|
||||
color: #c4b5d8;
|
||||
}
|
||||
|
||||
.offer-board-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.offer-status {
|
||||
padding: 8px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.offer-status.free {
|
||||
background: rgba(110, 231, 183, 0.16);
|
||||
color: #6ee7b7;
|
||||
}
|
||||
|
||||
.offer-status.paid {
|
||||
background: rgba(244, 114, 182, 0.14);
|
||||
color: #f9a8d4;
|
||||
}
|
||||
|
||||
.offer-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.offer-grid-6 {
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.offer-card {
|
||||
position: relative;
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: var(--text);
|
||||
border-radius: 14px;
|
||||
padding: 12px 10px 14px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font: inherit;
|
||||
transition: border-color 0.15s ease, transform 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.offer-card:hover {
|
||||
border-color: rgba(244, 114, 182, 0.45);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.offer-card.active {
|
||||
border-color: #f472b6;
|
||||
box-shadow: 0 0 0 1px rgba(244, 114, 182, 0.35);
|
||||
background: rgba(244, 114, 182, 0.08);
|
||||
}
|
||||
|
||||
.offer-card.is-free.active {
|
||||
border-color: #6ee7b7;
|
||||
box-shadow: 0 0 0 1px rgba(110, 231, 183, 0.35);
|
||||
background: rgba(110, 231, 183, 0.08);
|
||||
}
|
||||
|
||||
.offer-img {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 14px;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.offer-free-badge {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(145deg, #1f2937, #111827);
|
||||
color: #a7f3d0;
|
||||
font-weight: 800;
|
||||
letter-spacing: 1px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.offer-card strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.offer-card .offer-id {
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
word-break: break-all;
|
||||
text-align: center;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.offer-card em {
|
||||
font-style: normal;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #fce7f3;
|
||||
}
|
||||
|
||||
.offer-remark {
|
||||
font-style: normal;
|
||||
font-size: 10px;
|
||||
color: #8b7fa3;
|
||||
text-align: center;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.offer-on {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: 999px;
|
||||
background: rgba(244, 114, 182, 0.9);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.offer-card.is-free .offer-on {
|
||||
background: rgba(16, 185, 129, 0.9);
|
||||
}
|
||||
|
||||
.unlock-hero {
|
||||
display: grid;
|
||||
grid-template-columns: 1.4fr 1fr;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.monetize-unlock {
|
||||
margin-top: 16px;
|
||||
margin-bottom: 0;
|
||||
padding-top: 14px;
|
||||
border-top: 1px dashed rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.unlock-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.unlock-row input[type='range'] {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.price-box input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mono-box {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 14px;
|
||||
background: rgba(0, 0, 0, 0.28);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.mono-box label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.mono-box code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 13px;
|
||||
color: #f3eefc;
|
||||
}
|
||||
|
||||
.yuan {
|
||||
margin: 6px 0 12px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 6px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.free-hint {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.free-banner {
|
||||
margin-top: 14px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
background: rgba(110, 231, 183, 0.1);
|
||||
border: 1px solid rgba(110, 231, 183, 0.28);
|
||||
color: #a7f3d0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.offer-grid,
|
||||
.offer-grid-6 {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.offer-grid,
|
||||
.offer-grid-6 {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.unlock-hero {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
444
apps/ebook/dymini/admin/src/pages/BookEdit.tsx
Normal file
@ -0,0 +1,444 @@
|
||||
import { FormEvent, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
import './BookEdit.css'
|
||||
|
||||
type Chapter = { id: string; title: string; order: number; content: string }
|
||||
type Book = {
|
||||
id: string
|
||||
title: string
|
||||
subtitle: string
|
||||
author: string
|
||||
cover_emoji: string
|
||||
description: string
|
||||
tags: string[]
|
||||
price_fen: number
|
||||
product_id: string
|
||||
unlock_percent: number
|
||||
rating: number
|
||||
chapters: Chapter[]
|
||||
chapter_count?: number
|
||||
word_count?: number
|
||||
offer_key?: string
|
||||
is_free?: boolean
|
||||
}
|
||||
|
||||
type ProductOffer = {
|
||||
key: string
|
||||
label: string
|
||||
name: string
|
||||
product_id: string
|
||||
price_fen: number
|
||||
price_yuan: string
|
||||
free: boolean
|
||||
image: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
function simplePreviewHtml(md: string): string {
|
||||
return (md || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
||||
.replace(/!\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g, '<img src="$2" alt="$1" />')
|
||||
.replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>')
|
||||
.replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>')
|
||||
.replace(/^- (.+)$/gm, '<li>$1</li>')
|
||||
.replace(/\n{2,}/g, '<br/><br/>')
|
||||
.replace(/\n/g, '<br/>')
|
||||
}
|
||||
|
||||
export default function BookEdit() {
|
||||
const { id = 'default' } = useParams()
|
||||
const [book, setBook] = useState<Book | null>(null)
|
||||
const [offers, setOffers] = useState<ProductOffer[]>([])
|
||||
const [activeIdx, setActiveIdx] = useState(0)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [mode, setMode] = useState<'chapter' | 'full'>('chapter')
|
||||
const [fullMd, setFullMd] = useState('')
|
||||
|
||||
async function loadBook() {
|
||||
const data = await api<Book>(`/api/admin/books/${id}`)
|
||||
if ((data.author || '').toLowerCase().includes('nomadro studio')) {
|
||||
data.author = ''
|
||||
}
|
||||
setBook(data)
|
||||
setActiveIdx(0)
|
||||
}
|
||||
|
||||
async function loadOffers() {
|
||||
try {
|
||||
const res = await api<{ items: ProductOffer[] }>('/api/admin/product-offers')
|
||||
setOffers(res.items || [])
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadBook().catch((e) => setMsg(e.message))
|
||||
loadOffers()
|
||||
}, [id])
|
||||
|
||||
const chapter = book?.chapters?.[activeIdx]
|
||||
const isFree = !!book && (book.is_free || book.unlock_percent >= 100)
|
||||
const activeOfferKey =
|
||||
book?.offer_key ||
|
||||
offers.find((o) => (!o.free && o.product_id === book?.product_id) || (o.free && isFree))?.key ||
|
||||
''
|
||||
|
||||
const previewHtml = useMemo(() => {
|
||||
if (mode === 'full') return simplePreviewHtml(fullMd)
|
||||
return simplePreviewHtml(chapter?.content || '')
|
||||
}, [mode, fullMd, chapter?.content])
|
||||
|
||||
async function applyOffer(offerKey: string) {
|
||||
if (!book) return
|
||||
setSaving(true)
|
||||
setMsg('')
|
||||
try {
|
||||
const updated = await api<Book>(`/api/admin/books/${id}/offer`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ offer_key: offerKey, keep_preview_percent: true }),
|
||||
})
|
||||
setBook(updated)
|
||||
const label = offers.find((o) => o.key === offerKey)?.name || offerKey
|
||||
setMsg(
|
||||
updated.unlock_percent >= 100
|
||||
? `已切换:免费全书(unlock=100%)· 小程序刷新后生效`
|
||||
: `已切换:${label} · 道具ID ${updated.product_id} · ¥${(updated.price_fen / 100).toFixed(2)} · 小程序刷新后生效`
|
||||
)
|
||||
} catch (ex: any) {
|
||||
setMsg(ex.message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveMetaAndChapters() {
|
||||
if (!book) return
|
||||
setSaving(true)
|
||||
setMsg('')
|
||||
try {
|
||||
const updated = await api<Book>(`/api/admin/books/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
title: book.title,
|
||||
subtitle: book.subtitle,
|
||||
author: book.author === 'Nomadro Studio' ? '' : book.author,
|
||||
cover_emoji: book.cover_emoji,
|
||||
description: book.description,
|
||||
tags: book.tags,
|
||||
price_fen: Number(book.price_fen),
|
||||
product_id: book.product_id,
|
||||
unlock_percent: Number(book.unlock_percent),
|
||||
rating: Number(book.rating),
|
||||
chapters: book.chapters,
|
||||
}),
|
||||
})
|
||||
setBook(updated)
|
||||
setMsg(`已保存 · ${updated.chapter_count} 章 · ${updated.word_count} 字 · 小程序刷新后生效`)
|
||||
} catch (ex: any) {
|
||||
setMsg(ex.message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function onSave(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
await saveMetaAndChapters()
|
||||
}
|
||||
|
||||
function updateChapterContent(content: string) {
|
||||
if (!book || !chapter) return
|
||||
const chapters = [...book.chapters]
|
||||
chapters[activeIdx] = { ...chapter, content }
|
||||
// sync title from first heading if present
|
||||
const m = /^#\s+(.+)$/m.exec(content)
|
||||
if (m) chapters[activeIdx].title = m[1].trim()
|
||||
setBook({ ...book, chapters })
|
||||
}
|
||||
|
||||
async function loadFullMarkdown() {
|
||||
const data = await api<{ markdown: string }>(`/api/admin/books/${id}/markdown`)
|
||||
setFullMd(data.markdown)
|
||||
setMode('full')
|
||||
}
|
||||
|
||||
async function importMarkdown(markdown: string, fromFile = false) {
|
||||
setImporting(true)
|
||||
setMsg('')
|
||||
try {
|
||||
const res = await api<{ chapter_count: number; word_count: number; book: Book }>(
|
||||
`/api/admin/books/${id}/import-markdown`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
markdown,
|
||||
replace_meta: fromFile,
|
||||
title: '数字游民出海笔记',
|
||||
subtitle: '低成本工作室 · 云手机 · 自动化杠杆',
|
||||
description: '数字游民地理套利与自动化杠杆实战笔记',
|
||||
}),
|
||||
},
|
||||
)
|
||||
setBook(res.book)
|
||||
setActiveIdx(0)
|
||||
setMode('chapter')
|
||||
setMsg(`已入库 · ${res.chapter_count} 章 · ${res.word_count} 字`)
|
||||
} catch (ex: any) {
|
||||
setMsg(ex.message)
|
||||
} finally {
|
||||
setImporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function onPickFile(file: File | null) {
|
||||
if (!file) return
|
||||
const text = await file.text()
|
||||
await importMarkdown(text, true)
|
||||
}
|
||||
|
||||
async function saveFullMarkdown() {
|
||||
await importMarkdown(fullMd, false)
|
||||
}
|
||||
|
||||
if (!book) return <div className="page">加载中… {msg}</div>
|
||||
|
||||
return (
|
||||
<div className="page book-edit-page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>内容编辑台</h1>
|
||||
<p>
|
||||
数据库实时读写 · {book.chapter_count || book.chapters.length} 章 ·{' '}
|
||||
{book.word_count || 0} 字 · 保存后小程序下次打开即更新
|
||||
</p>
|
||||
</div>
|
||||
<div className="head-actions">
|
||||
<label className="file-btn">
|
||||
导入 ebook.md
|
||||
<input
|
||||
type="file"
|
||||
accept=".md,text/markdown,text/plain"
|
||||
hidden
|
||||
onChange={(e) => onPickFile(e.target.files?.[0] || null)}
|
||||
/>
|
||||
</label>
|
||||
<button type="button" className="ghost" onClick={() => loadFullMarkdown()}>
|
||||
全文模式
|
||||
</button>
|
||||
<button type="button" className="ghost" onClick={() => setMode('chapter')}>
|
||||
分章模式
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg && <div className="banner">{msg}</div>}
|
||||
|
||||
<form className="panel form meta-form" onSubmit={onSave}>
|
||||
<section className="monetize-panel">
|
||||
<div className="monetize-head">
|
||||
<div>
|
||||
<h2 className="monetize-title">阅读与付费控制</h2>
|
||||
<p className="hint">
|
||||
一键切换免费 / 已发布道具。切换后小程序「解锁全文」按钮文案与价格立即跟随(需重新打开阅读页)。
|
||||
</p>
|
||||
</div>
|
||||
<div className="live-preview">
|
||||
<span className="live-preview-label">小程序按钮预览</span>
|
||||
<div className={`live-btn ${isFree ? 'free' : ''}`}>
|
||||
{isFree
|
||||
? '开始阅读'
|
||||
: `解锁全文 · ¥${(book.price_fen / 100).toFixed(0)}`}
|
||||
</div>
|
||||
<span className="live-preview-sub">
|
||||
{isFree
|
||||
? '免费模式 · 无支付墙'
|
||||
: `道具 ${book.product_id || '-'} · 试读 ${Math.min(99, book.unlock_percent)}%`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="offer-grid offer-grid-6">
|
||||
{offers.map((o) => {
|
||||
const active = o.key === activeOfferKey
|
||||
const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : ''
|
||||
return (
|
||||
<button
|
||||
key={o.key}
|
||||
type="button"
|
||||
className={`offer-card ${active ? 'active' : ''} ${o.free ? 'is-free' : ''}`}
|
||||
disabled={saving}
|
||||
onClick={() => applyOffer(o.key)}
|
||||
>
|
||||
{o.free ? (
|
||||
<div className="offer-free-badge">FREE</div>
|
||||
) : img ? (
|
||||
<img className="offer-img" src={img} alt={o.label} />
|
||||
) : (
|
||||
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
|
||||
)}
|
||||
<strong>{o.label}</strong>
|
||||
<span className="offer-id">
|
||||
{o.free ? 'unlock=100%' : o.product_id}
|
||||
</span>
|
||||
<em>{o.price_yuan}</em>
|
||||
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
|
||||
{active ? <b className="offer-on">使用中</b> : null}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{!isFree ? (
|
||||
<div className="unlock-hero monetize-unlock">
|
||||
<div>
|
||||
<label>试读比例(付费时生效,不在首页展示)</label>
|
||||
<div className="unlock-row">
|
||||
<input
|
||||
type="range"
|
||||
min={1}
|
||||
max={99}
|
||||
value={Math.min(99, book.unlock_percent)}
|
||||
onChange={(e) =>
|
||||
setBook({ ...book, unlock_percent: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
<strong>{Math.min(99, book.unlock_percent)}%</strong>
|
||||
</div>
|
||||
<p className="hint">保存后生效。点「免费」卡片 = 100% 全开。</p>
|
||||
</div>
|
||||
<div className="price-box mono-box">
|
||||
<div>
|
||||
<label>道具 ID</label>
|
||||
<code>{book.product_id || '—'}</code>
|
||||
</div>
|
||||
<div>
|
||||
<label>价格</label>
|
||||
<code>¥{(book.price_fen / 100).toFixed(0)}({book.price_fen} 分)</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="free-banner">当前为免费全书:读者无支付墙,目录全部可读。</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="grid-2">
|
||||
<label>
|
||||
标题
|
||||
<input value={book.title} onChange={(e) => setBook({ ...book, title: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
副标题
|
||||
<input value={book.subtitle} onChange={(e) => setBook({ ...book, subtitle: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
作者(可留空)
|
||||
<input value={book.author} onChange={(e) => setBook({ ...book, author: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
封面 Emoji
|
||||
<input value={book.cover_emoji} onChange={(e) => setBook({ ...book, cover_emoji: e.target.value })} />
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
简介
|
||||
<textarea
|
||||
rows={3}
|
||||
value={book.description}
|
||||
onChange={(e) => setBook({ ...book, description: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={saving || importing} type="submit">
|
||||
{saving ? '保存中…' : '保存元信息与当前章节'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{mode === 'chapter' ? (
|
||||
<div className="editor-grid panel">
|
||||
<aside className="chapter-rail">
|
||||
<div className="rail-title">目录</div>
|
||||
<div className="rail-list">
|
||||
{book.chapters.map((c, idx) => (
|
||||
<button
|
||||
type="button"
|
||||
key={c.id}
|
||||
className={idx === activeIdx ? 'rail-item active' : 'rail-item'}
|
||||
onClick={() => setActiveIdx(idx)}
|
||||
>
|
||||
<span>{String(idx + 1).padStart(2, '0')}</span>
|
||||
<em>{c.title}</em>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section className="editor-pane">
|
||||
<div className="pane-head">
|
||||
<strong>编辑 · {chapter?.title || ''}</strong>
|
||||
<button type="button" onClick={saveMetaAndChapters} disabled={saving}>
|
||||
{saving ? '保存中…' : '保存到数据库'}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
className="md-editor"
|
||||
value={chapter?.content || ''}
|
||||
onChange={(e) => updateChapterContent(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="preview-pane">
|
||||
<div className="pane-head">
|
||||
<strong>实时预览</strong>
|
||||
</div>
|
||||
<div className="md-preview" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
</section>
|
||||
</div>
|
||||
) : (
|
||||
<div className="editor-grid full panel">
|
||||
<section className="editor-pane">
|
||||
<div className="pane-head">
|
||||
<strong>全文 Markdown</strong>
|
||||
<button type="button" onClick={saveFullMarkdown} disabled={importing}>
|
||||
{importing ? '写入中…' : '拆章并写入数据库'}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
className="md-editor"
|
||||
value={fullMd}
|
||||
onChange={(e) => setFullMd(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</section>
|
||||
<section className="preview-pane">
|
||||
<div className="pane-head">
|
||||
<strong>实时预览</strong>
|
||||
</div>
|
||||
<div className="md-preview" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="panel" style={{ marginTop: 16 }}>
|
||||
<h2>读者运营</h2>
|
||||
<p className="muted">
|
||||
手动解锁、收回、拉黑、备注等操作已迁到独立页面,按微信 openid 管理。
|
||||
</p>
|
||||
<Link className="primary-link" to="/users">
|
||||
打开读者页 →
|
||||
</Link>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
65
apps/ebook/dymini/admin/src/pages/Checklist.tsx
Normal file
@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
|
||||
type Item = { id: string; title: string; status: string }
|
||||
type Guide = { product_id: string; price_fen: number; steps: string[] }
|
||||
|
||||
export default function Checklist() {
|
||||
const [items, setItems] = useState<Item[]>([])
|
||||
const [guide, setGuide] = useState<Guide | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
api<{ items: Item[]; product_guide?: Guide }>('/api/admin/checklist').then((d) => {
|
||||
setItems(d.items)
|
||||
setGuide(d.product_guide || null)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const badge = (s: string) => {
|
||||
if (s === 'ok') return <span className="badge ok">已就绪</span>
|
||||
if (s === 'missing') return <span className="badge bad">缺失</span>
|
||||
return <span className="badge manual">需人工确认</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>部署前检查清单</h1>
|
||||
<p>对照微信「虚拟支付:个人」文末清单逐项验收</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{guide && (
|
||||
<div className="panel" style={{ marginBottom: 16 }}>
|
||||
<h2>先解决 PRODUCT_ID_NOT_PUBLISH</h2>
|
||||
<ol className="guide-ol">
|
||||
{guide.steps.map((s) => (
|
||||
<li key={s}>{s}</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="panel">
|
||||
<ul className="checklist">
|
||||
{items.map((it) => (
|
||||
<li key={it.id}>
|
||||
<div>{it.title}</div>
|
||||
{badge(it.status)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="fee-note">
|
||||
<h3>费率 / 结算 / 退款(需告知运营方)</h3>
|
||||
<ul>
|
||||
<li>Android 等:费率 1%;结算 T+3</li>
|
||||
<li>iOS:费率 12%;结算约 45–60 天;退款由用户向 App Store 申请</li>
|
||||
<li>个人主体月支付限额 10 万元</li>
|
||||
<li>发货以推送为主,query_order 每 5 分钟兜底</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
68
apps/ebook/dymini/admin/src/pages/Dashboard.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
|
||||
type Stats = {
|
||||
users: number
|
||||
unlocks: number
|
||||
paid_orders: number
|
||||
paid_amount_fen: number
|
||||
pending_orders: number
|
||||
track_events?: number
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState<Stats | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
api<Stats>('/api/admin/stats').then(setStats).catch(console.error)
|
||||
}, [])
|
||||
|
||||
const cards = [
|
||||
{ label: '读者', value: stats?.users ?? '—', emoji: '👥' },
|
||||
{ label: '已解锁', value: stats?.unlocks ?? '—', emoji: '🔓' },
|
||||
{ label: '已支付订单', value: stats?.paid_orders ?? '—', emoji: '💳' },
|
||||
{
|
||||
label: '成交额(元)',
|
||||
value: stats ? (stats.paid_amount_fen / 100).toFixed(2) : '—',
|
||||
emoji: '📈',
|
||||
},
|
||||
{ label: '待支付', value: stats?.pending_orders ?? '—', emoji: '⏳' },
|
||||
{ label: '埋点事件', value: stats?.track_events ?? '—', emoji: '📊' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>概览</h1>
|
||||
<p>电子书业务与虚拟支付运行状态</p>
|
||||
</div>
|
||||
<Link className="primary-link" to="/books/default">
|
||||
编辑试读百分比 →
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<div className="stat-grid">
|
||||
{cards.map((c) => (
|
||||
<div className="stat-card" key={c.label}>
|
||||
<div className="stat-emoji">{c.emoji}</div>
|
||||
<div className="stat-value">{c.value}</div>
|
||||
<div className="stat-label">{c.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<section className="panel">
|
||||
<h2>快捷操作</h2>
|
||||
<div className="quick">
|
||||
<Link to="/books/default">📚 书籍 / 解锁阈值</Link>
|
||||
<Link to="/users">👥 读者运营</Link>
|
||||
<Link to="/orders">🧾 订单列表</Link>
|
||||
<Link to="/events">📊 埋点事件</Link>
|
||||
<Link to="/checklist">✅ 部署前检查清单</Link>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
120
apps/ebook/dymini/admin/src/pages/Events.tsx
Normal file
@ -0,0 +1,120 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
|
||||
type TrackEvent = {
|
||||
id: number
|
||||
name: string
|
||||
page: string | null
|
||||
label: string | null
|
||||
props: Record<string, unknown>
|
||||
openid: string
|
||||
client: string
|
||||
ts: number
|
||||
created_at: number
|
||||
}
|
||||
|
||||
const FILTERS = [
|
||||
'',
|
||||
'page_view',
|
||||
'btn_click',
|
||||
'read_start',
|
||||
'unlock_click',
|
||||
'pay_start',
|
||||
'pay_success',
|
||||
'pay_fail',
|
||||
'pay_cancel',
|
||||
'pay_order_created',
|
||||
'pay_deliver',
|
||||
'login_ok',
|
||||
'login_fail',
|
||||
'access_updated',
|
||||
'wx_push',
|
||||
'error',
|
||||
'app_launch',
|
||||
]
|
||||
|
||||
export default function Events() {
|
||||
const [events, setEvents] = useState<TrackEvent[]>([])
|
||||
const [filter, setFilter] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true)
|
||||
const q = filter ? `?limit=200&name=${encodeURIComponent(filter)}` : '?limit=200'
|
||||
api<TrackEvent[]>(`/api/admin/track-events${q}`)
|
||||
.then(setEvents)
|
||||
.catch(console.error)
|
||||
.finally(() => setLoading(false))
|
||||
}, [filter])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>埋点事件</h1>
|
||||
<p>小程序行为与支付链路;关键事件同步推送到 ntfy</p>
|
||||
</div>
|
||||
<button className="primary-link" type="button" onClick={load} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="panel" style={{ marginBottom: 16 }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<span>筛选事件</span>
|
||||
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
|
||||
{FILTERS.map((f) => (
|
||||
<option key={f || 'all'} value={f}>
|
||||
{f || '全部'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="panel table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>事件</th>
|
||||
<th>页面</th>
|
||||
<th>标签</th>
|
||||
<th>OpenID</th>
|
||||
<th>客户端</th>
|
||||
<th>属性</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{events.map((ev) => (
|
||||
<tr key={ev.id}>
|
||||
<td>{new Date((ev.ts || ev.created_at) * 1000).toLocaleString()}</td>
|
||||
<td>
|
||||
<code>{ev.name}</code>
|
||||
</td>
|
||||
<td>{ev.page || '—'}</td>
|
||||
<td>{ev.label || '—'}</td>
|
||||
<td className="mono">{ev.openid ? `…${ev.openid.slice(-8)}` : '—'}</td>
|
||||
<td>{ev.client || '—'}</td>
|
||||
<td className="mono" style={{ maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{Object.keys(ev.props || {}).length
|
||||
? JSON.stringify(ev.props)
|
||||
: '—'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!events.length && (
|
||||
<tr>
|
||||
<td colSpan={7}>{loading ? '加载中…' : '暂无埋点数据'}</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
54
apps/ebook/dymini/admin/src/pages/Login.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { FormEvent, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { api, setToken } from '../api'
|
||||
|
||||
export default function Login() {
|
||||
const nav = useNavigate()
|
||||
const [username, setUsername] = useState('admin')
|
||||
const [password, setPassword] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<{ token: string }>('/api/admin/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
setToken(data.token)
|
||||
nav('/')
|
||||
} catch (ex: any) {
|
||||
setErr(ex.message || '登录失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="login-bg" />
|
||||
<form className="login-card" onSubmit={onSubmit}>
|
||||
<h1>Nomadro Admin</h1>
|
||||
<p>管理试读百分比、书籍内容与虚拟支付订单 · admin.nomadro.cn</p>
|
||||
<label>
|
||||
用户名
|
||||
<input value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />
|
||||
</label>
|
||||
<label>
|
||||
密码
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</label>
|
||||
{err && <div className="error">{err}</div>}
|
||||
<button disabled={loading}>{loading ? '登录中…' : '进入控制台'}</button>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
65
apps/ebook/dymini/admin/src/pages/Orders.tsx
Normal file
@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
|
||||
type Order = {
|
||||
out_trade_no: string
|
||||
wx_order_id: string | null
|
||||
openid: string
|
||||
book_id: string
|
||||
amount_fen: number
|
||||
status: string
|
||||
delivered: number
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export default function Orders() {
|
||||
const [orders, setOrders] = useState<Order[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
api<Order[]>('/api/admin/orders').then(setOrders).catch(console.error)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>订单</h1>
|
||||
<p>虚拟支付道具直购订单与发货状态</p>
|
||||
</div>
|
||||
</header>
|
||||
<div className="panel table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>业务单号</th>
|
||||
<th>平台单号</th>
|
||||
<th>OpenID</th>
|
||||
<th>金额</th>
|
||||
<th>状态</th>
|
||||
<th>发货</th>
|
||||
<th>时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{orders.map((o) => (
|
||||
<tr key={o.out_trade_no}>
|
||||
<td>{o.out_trade_no}</td>
|
||||
<td>{o.wx_order_id || '—'}</td>
|
||||
<td className="mono">{o.openid}</td>
|
||||
<td>¥{(o.amount_fen / 100).toFixed(2)}</td>
|
||||
<td>{o.status}</td>
|
||||
<td>{o.delivered ? '✅' : '—'}</td>
|
||||
<td>{new Date(o.created_at * 1000).toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!orders.length && (
|
||||
<tr>
|
||||
<td colSpan={7}>暂无订单</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
224
apps/ebook/dymini/admin/src/pages/Users.tsx
Normal file
@ -0,0 +1,224 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
|
||||
type UnlockRow = { book_id: string; unlocked_at: number; source: string }
|
||||
|
||||
type UserRow = {
|
||||
openid: string
|
||||
unionid?: string | null
|
||||
nickname?: string | null
|
||||
status?: string
|
||||
notes?: string | null
|
||||
pb_record_id?: string | null
|
||||
updated_at: number
|
||||
created_at?: number
|
||||
unlocked_default: boolean
|
||||
unlocks: UnlockRow[]
|
||||
}
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<UserRow[]>([])
|
||||
const [q, setQ] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [manualOpenid, setManualOpenid] = useState('')
|
||||
const [busy, setBusy] = useState('')
|
||||
|
||||
async function refresh(search = q) {
|
||||
const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
|
||||
setUsers(await api<UserRow[]>(`/api/admin/users${qs}`))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
refresh().catch((e) => setMsg(String(e.message || e)))
|
||||
}, [])
|
||||
|
||||
const blockedCount = useMemo(
|
||||
() => users.filter((u) => (u.status || 'active') === 'blocked').length,
|
||||
[users],
|
||||
)
|
||||
|
||||
async function run(key: string, fn: () => Promise<void>) {
|
||||
setBusy(key)
|
||||
setMsg('')
|
||||
try {
|
||||
await fn()
|
||||
await refresh()
|
||||
} catch (e: any) {
|
||||
setMsg(e.message || String(e))
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>读者</h1>
|
||||
<p>
|
||||
以微信 openid 绑定(SQLite 主存;PocketBase 可选同步集合 wx_readers)。共 {users.length}{' '}
|
||||
人,拉黑 {blockedCount}。
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="banner">{msg}</div> : null}
|
||||
|
||||
<section className="panel" style={{ marginBottom: 16 }}>
|
||||
<div className="row" style={{ gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<input
|
||||
value={q}
|
||||
placeholder="搜索 openid / 备注 / 昵称"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
style={{ minWidth: 240, flex: 1 }}
|
||||
/>
|
||||
<button type="button" onClick={() => refresh().catch(console.error)}>
|
||||
搜索
|
||||
</button>
|
||||
<input
|
||||
value={manualOpenid}
|
||||
placeholder="补录 openid 并解锁"
|
||||
onChange={(e) => setManualOpenid(e.target.value)}
|
||||
style={{ minWidth: 220, flex: 1 }}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!manualOpenid.trim() || busy === 'manual'}
|
||||
onClick={() =>
|
||||
run('manual', async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: manualOpenid.trim(), book_id: 'default' }),
|
||||
})
|
||||
setMsg(`已解锁 ${manualOpenid.trim()}`)
|
||||
setManualOpenid('')
|
||||
})
|
||||
}
|
||||
>
|
||||
手动解锁
|
||||
</button>
|
||||
</div>
|
||||
<p className="muted" style={{ marginTop: 10 }}>
|
||||
绑定方案:小程序 wx.login → code2session → openid 作为读者主键;不把微信用户做成 PocketBase
|
||||
Auth 密码账号。详见 <Link to="/checklist">部署清单</Link>。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div className="panel table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>OpenID</th>
|
||||
<th>状态</th>
|
||||
<th>解锁</th>
|
||||
<th>备注</th>
|
||||
<th>最近活跃</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => {
|
||||
const blocked = (u.status || 'active') === 'blocked'
|
||||
return (
|
||||
<tr key={u.openid} style={blocked ? { opacity: 0.72 } : undefined}>
|
||||
<td className="mono">
|
||||
{u.openid}
|
||||
{u.pb_record_id ? (
|
||||
<div className="muted" style={{ fontSize: 12 }}>
|
||||
PB:{u.pb_record_id}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td>{blocked ? '拉黑' : '正常'}</td>
|
||||
<td>
|
||||
{u.unlocked_default ? '✅ 全书' : '—'}
|
||||
{u.unlocks?.length ? (
|
||||
<div className="muted" style={{ fontSize: 12 }}>
|
||||
{u.unlocks
|
||||
.map((x) => `${x.book_id}${x.source ? `(${x.source})` : ''}`)
|
||||
.join(' · ')}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td style={{ minWidth: 160 }}>
|
||||
<input
|
||||
defaultValue={u.notes || ''}
|
||||
key={`${u.openid}-notes-${u.updated_at}`}
|
||||
placeholder="备注"
|
||||
onBlur={(e) => {
|
||||
const notes = e.target.value
|
||||
if (notes === (u.notes || '')) return
|
||||
run(`notes-${u.openid}`, async () => {
|
||||
await api(`/api/admin/users/${encodeURIComponent(u.openid)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ notes }),
|
||||
})
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td>{u.updated_at ? new Date(u.updated_at * 1000).toLocaleString() : '—'}</td>
|
||||
<td style={{ whiteSpace: 'nowrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={u.unlocked_default || busy === `unlock-${u.openid}`}
|
||||
onClick={() =>
|
||||
run(`unlock-${u.openid}`, async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
|
||||
})
|
||||
setMsg(`已解锁 ${u.openid}`)
|
||||
})
|
||||
}
|
||||
>
|
||||
解锁
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!u.unlocked_default || busy === `revoke-${u.openid}`}
|
||||
onClick={() =>
|
||||
run(`revoke-${u.openid}`, async () => {
|
||||
await api('/api/admin/revoke-unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
|
||||
})
|
||||
setMsg(`已收回解锁 ${u.openid}`)
|
||||
})
|
||||
}
|
||||
>
|
||||
收回
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy === `block-${u.openid}`}
|
||||
onClick={() =>
|
||||
run(`block-${u.openid}`, async () => {
|
||||
await api(
|
||||
`/api/admin/users/${encodeURIComponent(u.openid)}/${
|
||||
blocked ? 'unblock' : 'block'
|
||||
}`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
setMsg(blocked ? `已恢复 ${u.openid}` : `已拉黑 ${u.openid}`)
|
||||
})
|
||||
}
|
||||
>
|
||||
{blocked ? '解除拉黑' : '拉黑'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
{!users.length && (
|
||||
<tr>
|
||||
<td colSpan={6}>暂无读者(用户打开小程序登录后会出现)</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
245
apps/ebook/dymini/admin/src/styles.css
Normal file
@ -0,0 +1,245 @@
|
||||
:root {
|
||||
--bg: #0e1512;
|
||||
--panel: #152019;
|
||||
--line: rgba(150, 210, 170, 0.16);
|
||||
--text: #e7f3ea;
|
||||
--muted: #8fad99;
|
||||
--accent: #5ec478;
|
||||
--accent-2: #d7b35a;
|
||||
--danger: #e07060;
|
||||
--font-display: 'Syne', sans-serif;
|
||||
--font-body: 'IBM Plex Sans', sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #root { min-height: 100%; margin: 0; }
|
||||
body {
|
||||
font-family: var(--font-body);
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(900px 500px at 0% 0%, rgba(70, 150, 100, 0.22), transparent 55%),
|
||||
radial-gradient(700px 400px at 100% 0%, rgba(180, 150, 60, 0.12), transparent 50%),
|
||||
var(--bg);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: 260px 1fr;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.side {
|
||||
border-right: 1px solid var(--line);
|
||||
padding: 28px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
background: rgba(10, 18, 14, 0.7);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.logo { display: flex; gap: 12px; align-items: center; }
|
||||
.logo-mark {
|
||||
width: 42px; height: 42px; border-radius: 12px;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3f9d68, #7be0a4);
|
||||
color: #062012; font-family: var(--font-display); font-weight: 800;
|
||||
}
|
||||
.logo-title { font-family: var(--font-display); font-size: 20px; }
|
||||
.logo-sub { color: var(--muted); font-size: 12px; }
|
||||
|
||||
.nav { display: flex; flex-direction: column; gap: 8px; flex: 1; }
|
||||
.nav a {
|
||||
padding: 12px 14px; border-radius: 12px; color: var(--muted);
|
||||
}
|
||||
.nav a.active, .nav a:hover {
|
||||
background: rgba(94, 196, 120, 0.12);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.ghost-btn {
|
||||
border: 1px solid var(--line);
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
border-radius: 12px;
|
||||
padding: 10px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.main { padding: 32px 36px 60px; }
|
||||
.page-head {
|
||||
display: flex; justify-content: space-between; align-items: end; gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.page-head h1 {
|
||||
margin: 0 0 6px;
|
||||
font-family: var(--font-display);
|
||||
font-size: 32px;
|
||||
}
|
||||
.page-head p { margin: 0; color: var(--muted); }
|
||||
|
||||
.primary-link {
|
||||
background: linear-gradient(135deg, #3f9d68, #67d094);
|
||||
color: #062012 !important;
|
||||
padding: 12px 16px;
|
||||
border-radius: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.stat-card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
}
|
||||
.stat-emoji { font-size: 22px; }
|
||||
.stat-value { font-size: 28px; font-family: var(--font-display); margin-top: 8px; }
|
||||
.stat-label { color: var(--muted); margin-top: 4px; font-size: 13px; }
|
||||
|
||||
.panel {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 20px;
|
||||
padding: 22px;
|
||||
}
|
||||
.panel h2, .panel h3 { font-family: var(--font-display); margin-top: 0; }
|
||||
.quick { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.quick a {
|
||||
padding: 12px 16px;
|
||||
border-radius: 12px;
|
||||
background: rgba(255,255,255,0.04);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.login-page {
|
||||
min-height: 100vh; display: grid; place-items: center; position: relative;
|
||||
}
|
||||
.login-bg {
|
||||
position: absolute; inset: 0;
|
||||
background:
|
||||
radial-gradient(600px 300px at 30% 20%, rgba(94,196,120,.25), transparent),
|
||||
radial-gradient(500px 280px at 70% 70%, rgba(215,179,90,.15), transparent);
|
||||
}
|
||||
.login-card {
|
||||
position: relative;
|
||||
width: min(420px, 92vw);
|
||||
background: rgba(18, 30, 24, 0.92);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 24px;
|
||||
padding: 28px;
|
||||
display: flex; flex-direction: column; gap: 14px;
|
||||
}
|
||||
.login-card h1 { font-family: var(--font-display); margin: 0; }
|
||||
.login-card p { margin: 0; color: var(--muted); font-size: 14px; }
|
||||
label { display: flex; flex-direction: column; gap: 8px; font-size: 13px; color: var(--muted); }
|
||||
input, textarea, button {
|
||||
font: inherit;
|
||||
}
|
||||
input, textarea {
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(0,0,0,0.25);
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
}
|
||||
button {
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
padding: 12px 16px;
|
||||
background: linear-gradient(135deg, #3f9d68, #67d094);
|
||||
color: #062012;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.error { color: #ffb4a8; font-size: 13px; }
|
||||
.banner {
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
background: rgba(94,196,120,0.12);
|
||||
border: 1px solid rgba(94,196,120,0.3);
|
||||
}
|
||||
|
||||
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||
.grid-2 {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 14px;
|
||||
}
|
||||
.unlock-hero {
|
||||
display: grid;
|
||||
grid-template-columns: 1.4fr 1fr;
|
||||
gap: 18px;
|
||||
padding: 16px;
|
||||
border-radius: 16px;
|
||||
background: rgba(0,0,0,0.2);
|
||||
}
|
||||
.unlock-row { display: flex; align-items: center; gap: 12px; }
|
||||
.unlock-row input[type=range] { flex: 1; }
|
||||
.bar-preview {
|
||||
position: relative;
|
||||
height: 12px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255,255,255,0.08);
|
||||
margin-top: 14px;
|
||||
}
|
||||
.bar-preview-fill {
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(90deg, #3f9d68, #7be0a4);
|
||||
}
|
||||
.bar-preview span {
|
||||
position: absolute; top: -18px; transform: translateX(-50%);
|
||||
}
|
||||
.hint { color: var(--muted); font-size: 13px; }
|
||||
.price-box { display: flex; flex-direction: column; gap: 8px; }
|
||||
.yuan { color: var(--accent-2); font-weight: 600; }
|
||||
.chapter-editor {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.table-wrap { overflow: auto; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
th, td { text-align: left; padding: 10px 8px; border-bottom: 1px solid var(--line); }
|
||||
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
||||
|
||||
.checklist { list-style: none; padding: 0; margin: 0; }
|
||||
.checklist li {
|
||||
display: flex; justify-content: space-between; gap: 16px; align-items: center;
|
||||
padding: 14px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.badge {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.badge.ok { background: rgba(94,196,120,.18); color: #9ee0b4; }
|
||||
.badge.bad { background: rgba(220,80,60,.18); color: #ffb4a8; }
|
||||
.badge.manual { background: rgba(215,179,90,.18); color: #f0d78a; }
|
||||
.fee-note { margin-top: 20px; color: var(--muted); }
|
||||
.fee-note ul { padding-left: 18px; }
|
||||
.guide-ol { color: var(--muted); line-height: 1.7; padding-left: 22px; }
|
||||
.guide-ol code {
|
||||
color: var(--accent-2);
|
||||
background: rgba(0,0,0,0.25);
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.shell { grid-template-columns: 1fr; }
|
||||
.side { border-right: none; border-bottom: 1px solid var(--line); }
|
||||
.stat-grid, .unlock-hero, .grid-2 { grid-template-columns: 1fr; }
|
||||
}
|
||||
24
apps/ebook/dymini/admin/src/types/book.ts
Normal file
@ -0,0 +1,24 @@
|
||||
/** 管理端书籍类型(与 packages/shared-types 对齐) */
|
||||
export type ChapterMeta = {
|
||||
id: string
|
||||
title: string
|
||||
order: number
|
||||
content?: string
|
||||
}
|
||||
|
||||
export type BookDetail = {
|
||||
id: string
|
||||
title: string
|
||||
subtitle: string
|
||||
author: string
|
||||
cover_emoji: string
|
||||
description: string
|
||||
tags: string[]
|
||||
price_fen: number
|
||||
product_id: string
|
||||
unlock_percent: number
|
||||
chapter_count: number
|
||||
word_count: number
|
||||
rating: number
|
||||
chapters: ChapterMeta[]
|
||||
}
|
||||
9
apps/ebook/dymini/admin/src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
17
apps/ebook/dymini/admin/tsconfig.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
18
apps/ebook/dymini/admin/vite.config.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// 生产独立域名 dyadmin.nomadro.cn,base 用 /
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
base: '/',
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8000',
|
||||
'/health': 'http://127.0.0.1:8000',
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
},
|
||||
})
|
||||
BIN
apps/ebook/dymini/assets/ebook_unlock_default.jpg
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
apps/ebook/dymini/assets/ebook_unlock_default.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
25
apps/ebook/dymini/backend/.env.example
Normal file
@ -0,0 +1,25 @@
|
||||
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-local-dev-2026
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=Xiao4669805
|
||||
PB_URL=http://127.0.0.1:8090
|
||||
PB_ADMIN_EMAIL=admin@nomadro.cn
|
||||
PB_ADMIN_PASSWORD=Xiao4669805
|
||||
USE_POCKETBASE=false
|
||||
PUBLIC_API_BASE=https://api.nomadro.cn
|
||||
ADMIN_ORIGIN=https://admin.nomadro.cn
|
||||
CORS_ORIGINS=https://admin.nomadro.cn,http://localhost:5173,http://127.0.0.1:5173,http://localhost:8000
|
||||
DEFAULT_PRODUCT_ID=ebook_unlock_default
|
||||
DEFAULT_PRICE_FEN=18800
|
||||
DEFAULT_UNLOCK_PERCENT=30
|
||||
SQLITE_PATH=../data/nomadmini.db
|
||||
WX_PUSH_TOKEN=hackrobot
|
||||
WX_PUSH_ENCODING_AES_KEY=ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI
|
||||
WX_ALLOW_DEVTOOLS_LOGIN=true
|
||||
DEBUG=true
|
||||
API_PORT=8000
|
||||
1
apps/ebook/dymini/backend/app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Nomadmini backend package
|
||||
47
apps/ebook/dymini/backend/app/config.py
Normal file
@ -0,0 +1,47 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
app_name: str = "dymini-api"
|
||||
debug: bool = True
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
public_api_base: str = "https://dyapi.nomadro.cn"
|
||||
admin_origin: str = "https://dyadmin.nomadro.cn"
|
||||
cors_origins: str = (
|
||||
"https://dyadmin.nomadro.cn,https://dy.nomadro.cn,"
|
||||
"http://localhost:5173,http://127.0.0.1:5173,http://localhost:8000"
|
||||
)
|
||||
|
||||
# 抖音小程序
|
||||
tt_appid: str = "tt995defe007255b2701"
|
||||
tt_secret: str = "8628800c6f2290175180b94e255380c2e9d34dc0"
|
||||
tt_allow_devtools_login: bool = True
|
||||
# 个人主体暂不确定能否真实支付:默认开启模拟支付
|
||||
tt_pay_mock: bool = True
|
||||
|
||||
jwt_secret: str = "dymini-jwt-2026"
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = "Xiao4669805"
|
||||
|
||||
pb_url: str = "http://127.0.0.1:8090"
|
||||
pb_admin_email: str = "admin@nomadro.cn"
|
||||
pb_admin_password: str = "Xiao4669805"
|
||||
use_pocketbase: bool = False
|
||||
|
||||
sqlite_path: str = "../data/dymini.db"
|
||||
|
||||
default_product_id: str = "ebook_unlock_default"
|
||||
default_price_fen: int = 18800
|
||||
# 个人主体暂不能支付:默认全书可读
|
||||
default_unlock_percent: int = 100
|
||||
|
||||
ntfy_enabled: bool = True
|
||||
ntfy_base_url: str = "http://127.0.0.1:2586"
|
||||
ntfy_topic: str = "dymini"
|
||||
ntfy_token: str = ""
|
||||
|
||||
|
||||
settings = Settings()
|
||||
6
apps/ebook/dymini/backend/app/core/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
"""核心横切能力:依赖注入、鉴权。"""
|
||||
|
||||
from .deps import get_current_openid
|
||||
from .security import create_admin_token, require_admin
|
||||
|
||||
__all__ = ["get_current_openid", "create_admin_token", "require_admin"]
|
||||
19
apps/ebook/dymini/backend/app/core/deps.py
Normal file
@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from app.services.store import store
|
||||
|
||||
|
||||
async def get_current_openid(authorization: Annotated[str | None, Header()] = None) -> str:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(401, "未登录")
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
user = store.get_user_by_token(token)
|
||||
if not user:
|
||||
raise HTTPException(401, "登录已失效")
|
||||
if (user.get("status") or "active") == "blocked":
|
||||
raise HTTPException(403, "账号不可用")
|
||||
return user["openid"]
|
||||
31
apps/ebook/dymini/backend/app/core/security.py
Normal file
@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated
|
||||
|
||||
import jwt
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def create_admin_token(username: str) -> str:
|
||||
payload = {
|
||||
"sub": username,
|
||||
"role": "admin",
|
||||
"exp": datetime.now(timezone.utc) + timedelta(days=7),
|
||||
}
|
||||
return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
async def require_admin(authorization: Annotated[str | None, Header()] = None) -> str:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(401, "未登录管理后台")
|
||||
token = authorization.removeprefix("Bearer ").strip()
|
||||
try:
|
||||
data = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
|
||||
except Exception as e:
|
||||
raise HTTPException(401, "登录已失效") from e
|
||||
if data.get("role") != "admin":
|
||||
raise HTTPException(403, "无权限")
|
||||
return data.get("sub") or "admin"
|
||||
1
apps/ebook/dymini/backend/app/domains/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""按领域拆分的业务逻辑(与 HTTP router / infra 解耦)。"""
|
||||
24
apps/ebook/dymini/backend/app/domains/books/__init__.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""书籍领域逻辑。"""
|
||||
|
||||
from .products import (
|
||||
PRODUCT_OFFERS,
|
||||
apply_offer_key,
|
||||
is_book_free,
|
||||
match_offer,
|
||||
offer_public_list,
|
||||
unlock_button_text,
|
||||
)
|
||||
from .read_policy import access_snapshot, is_free_unlock, public_book, truncate_by_percent
|
||||
|
||||
__all__ = [
|
||||
"PRODUCT_OFFERS",
|
||||
"access_snapshot",
|
||||
"apply_offer_key",
|
||||
"is_book_free",
|
||||
"is_free_unlock",
|
||||
"match_offer",
|
||||
"offer_public_list",
|
||||
"public_book",
|
||||
"truncate_by_percent",
|
||||
"unlock_button_text",
|
||||
]
|
||||
182
apps/ebook/dymini/backend/app/domains/books/products.py
Normal file
@ -0,0 +1,182 @@
|
||||
"""虚拟支付道具目录:免费 + 微信已发布道具。
|
||||
|
||||
已发布(MP):
|
||||
tiktok / youtube / nomad / svip / ebook_unlock_default
|
||||
价格单位:分;道具 ID 与名称字段一致(ebook 道具 ID 为 ebook_unlock_default)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
PRODUCT_OFFERS: list[dict[str, Any]] = [
|
||||
{
|
||||
"key": "free",
|
||||
"label": "免费",
|
||||
"name": "免费全书",
|
||||
"product_id": "",
|
||||
"price_fen": 0,
|
||||
"unlock_percent": 100,
|
||||
"free": True,
|
||||
"image": "",
|
||||
"remark": "unlock_percent=100,全书可读,不拉起支付",
|
||||
},
|
||||
{
|
||||
"key": "tiktok",
|
||||
"label": "tiktok",
|
||||
"name": "tiktok",
|
||||
"product_id": "tiktok",
|
||||
"price_fen": 29800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/tiktok.png",
|
||||
"remark": "已发布 · ¥298",
|
||||
},
|
||||
{
|
||||
"key": "youtube",
|
||||
"label": "youtube",
|
||||
"name": "youtube",
|
||||
"product_id": "youtube",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/youtube.png",
|
||||
"remark": "已发布 · ¥188",
|
||||
},
|
||||
{
|
||||
"key": "nomad",
|
||||
"label": "nomad",
|
||||
"name": "nomad",
|
||||
"product_id": "nomad",
|
||||
"price_fen": 4900,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad.png",
|
||||
"remark": "已发布 · ¥49",
|
||||
},
|
||||
{
|
||||
"key": "svip",
|
||||
"label": "svip",
|
||||
"name": "svip",
|
||||
"product_id": "svip",
|
||||
"price_fen": 99800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/svip.png",
|
||||
"remark": "已发布 · ¥998",
|
||||
},
|
||||
{
|
||||
"key": "ebook",
|
||||
"label": "ebook",
|
||||
"name": "ebook",
|
||||
"product_id": "ebook_unlock_default",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/ebook.png",
|
||||
"remark": "已发布 · ¥188 · 旧默认道具",
|
||||
},
|
||||
{
|
||||
"key": "test",
|
||||
"label": "test",
|
||||
"name": "test",
|
||||
"product_id": "test",
|
||||
"price_fen": 100, # ¥1.00 测试
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/test.png",
|
||||
"remark": "测试道具 · ¥1 · 需在微信 MP 发布",
|
||||
},
|
||||
]
|
||||
|
||||
_LEGACY_PRODUCT_IDS = {
|
||||
"298": "tiktok",
|
||||
"188": "youtube",
|
||||
"49": "nomad",
|
||||
"998": "svip",
|
||||
}
|
||||
|
||||
|
||||
def is_book_free(book: dict[str, Any] | None) -> bool:
|
||||
if not book:
|
||||
return False
|
||||
return int(book.get("unlock_percent") or 0) >= 100
|
||||
|
||||
|
||||
def match_offer(book: dict[str, Any] | None) -> dict[str, Any]:
|
||||
if is_book_free(book):
|
||||
return PRODUCT_OFFERS[0]
|
||||
pid = str((book or {}).get("product_id") or "")
|
||||
mapped = _LEGACY_PRODUCT_IDS.get(pid, pid)
|
||||
for offer in PRODUCT_OFFERS:
|
||||
if offer["free"]:
|
||||
continue
|
||||
if offer["product_id"] == pid or offer["key"] == mapped or offer["product_id"] == mapped:
|
||||
return offer
|
||||
price = int((book or {}).get("price_fen") or 0)
|
||||
return {
|
||||
"key": "custom",
|
||||
"label": pid or "自定义",
|
||||
"name": pid or "自定义",
|
||||
"product_id": pid,
|
||||
"price_fen": price,
|
||||
"unlock_percent": 100,
|
||||
"free": False,
|
||||
"image": "",
|
||||
"remark": "未在目录中的自定义道具",
|
||||
}
|
||||
|
||||
|
||||
def apply_offer_key(key: str, current_unlock_percent: int | None = None) -> dict[str, Any]:
|
||||
key = _LEGACY_PRODUCT_IDS.get(key, key)
|
||||
offer = next(
|
||||
(
|
||||
o
|
||||
for o in PRODUCT_OFFERS
|
||||
if o["key"] == key or o["product_id"] == key or o["name"] == key
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not offer:
|
||||
raise ValueError(f"未知方案: {key}")
|
||||
if offer["free"]:
|
||||
return {"unlock_percent": 100, "price_fen": 0, "product_id": ""}
|
||||
preview = current_unlock_percent if current_unlock_percent is not None else offer["unlock_percent"]
|
||||
if preview >= 100:
|
||||
preview = offer["unlock_percent"]
|
||||
preview = max(1, min(99, int(preview)))
|
||||
return {
|
||||
"unlock_percent": preview,
|
||||
"price_fen": int(offer["price_fen"]),
|
||||
"product_id": str(offer["product_id"]),
|
||||
}
|
||||
|
||||
|
||||
def offer_public_list() -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"key": o["key"],
|
||||
"label": o["label"],
|
||||
"name": o.get("name") or o["label"],
|
||||
"product_id": o["product_id"],
|
||||
"price_fen": o["price_fen"],
|
||||
"price_yuan": f"¥{(o['price_fen'] / 100):.0f}" if not o["free"] else "免费",
|
||||
"free": o["free"],
|
||||
"image": o.get("image") or "",
|
||||
"remark": o.get("remark") or "",
|
||||
}
|
||||
for o in PRODUCT_OFFERS
|
||||
]
|
||||
|
||||
|
||||
def unlock_button_text(book: dict[str, Any] | None) -> str:
|
||||
"""小程序解锁按钮文案(后台方案驱动)。"""
|
||||
if is_book_free(book):
|
||||
return "开始阅读"
|
||||
price = int((book or {}).get("price_fen") or 0)
|
||||
if price <= 0:
|
||||
return "立即解锁全文"
|
||||
yuan = price / 100
|
||||
if yuan == int(yuan):
|
||||
return f"解锁全文 · ¥{int(yuan)}"
|
||||
return f"解锁全文 · ¥{yuan:.2f}"
|
||||
109
apps/ebook/dymini/backend/app/domains/books/read_policy.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""试读截断策略:按全书正文字符数百分比裁剪。 unlock_percent>=100 视为免费全书。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .products import is_book_free, match_offer, unlock_button_text
|
||||
|
||||
_INCOMPLETE_IMG = re.compile(r"<img\b[^>]*$", re.IGNORECASE | re.DOTALL)
|
||||
_INCOMPLETE_MD_IMG = re.compile(r"!\[[^\]]*\]\([^)]*$")
|
||||
_INCOMPLETE_HTML = re.compile(r"<[A-Za-z][^>]*$")
|
||||
|
||||
|
||||
def is_free_unlock(percent: int | None) -> bool:
|
||||
return int(percent or 0) >= 100
|
||||
|
||||
|
||||
def safe_cut_text(content: str, limit: int) -> str:
|
||||
"""按字数裁剪,避免切在 HTML/Markdown 图片标签中间。"""
|
||||
if limit <= 0:
|
||||
return ""
|
||||
cut = content if len(content) <= limit else content[:limit]
|
||||
cut = cut.rstrip()
|
||||
|
||||
if len(content) > limit:
|
||||
for sep in ("\n\n", "\n", "。", "!", "?", ".", "!", "?"):
|
||||
idx = cut.rfind(sep)
|
||||
if idx >= max(40, limit // 3):
|
||||
cut = cut[: idx + len(sep)].rstrip()
|
||||
break
|
||||
|
||||
# 无论是否整段装下,末尾半截标签都清掉(防预算刚好卡在 <img 中间)
|
||||
cut = _INCOMPLETE_IMG.sub("", cut)
|
||||
cut = _INCOMPLETE_MD_IMG.sub("", cut)
|
||||
cut = _INCOMPLETE_HTML.sub("", cut)
|
||||
return cut.rstrip()
|
||||
|
||||
|
||||
def truncate_by_percent(chapters: list[dict], percent: int) -> list[dict]:
|
||||
if is_free_unlock(percent):
|
||||
return [{**ch, "content": ch.get("content") or ""} for ch in chapters]
|
||||
ratio = max(1, min(99, int(percent))) / 100.0
|
||||
total = sum(len(ch.get("content") or "") for ch in chapters) or 1
|
||||
budget = max(120, int(total * ratio))
|
||||
used = 0
|
||||
out: list[dict] = []
|
||||
for ch in chapters:
|
||||
content = ch.get("content") or ""
|
||||
if used >= budget:
|
||||
out.append({**ch, "content": ""})
|
||||
continue
|
||||
remain = budget - used
|
||||
if len(content) <= remain:
|
||||
out.append({**ch, "content": content})
|
||||
used += len(content)
|
||||
else:
|
||||
cut = safe_cut_text(content, remain)
|
||||
out.append({**ch, "content": cut})
|
||||
used = budget
|
||||
return out
|
||||
|
||||
|
||||
def public_book(book: dict) -> dict:
|
||||
chapters = [
|
||||
{"id": c["id"], "title": c["title"], "order": c["order"]}
|
||||
for c in book.get("chapters") or []
|
||||
]
|
||||
free = is_book_free(book)
|
||||
offer = match_offer(book)
|
||||
price_fen = 0 if free else int(book.get("price_fen") or 0)
|
||||
return {
|
||||
"id": book["id"],
|
||||
"title": book["title"],
|
||||
"subtitle": book["subtitle"],
|
||||
"author": book["author"],
|
||||
"cover_emoji": book["cover_emoji"],
|
||||
"description": book["description"],
|
||||
"tags": book["tags"],
|
||||
"price_fen": price_fen,
|
||||
"product_id": "" if free else book["product_id"],
|
||||
"unlock_percent": book["unlock_percent"],
|
||||
"is_free": free,
|
||||
"offer_key": offer.get("key"),
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"price_label": "" if free or price_fen <= 0 else f"¥{price_fen / 100:.0f}",
|
||||
"unlock_btn_text": unlock_button_text(book),
|
||||
"updated_at": book.get("updated_at"),
|
||||
"chapter_count": book["chapter_count"],
|
||||
"word_count": book["word_count"],
|
||||
"rating": book["rating"],
|
||||
"chapters": chapters,
|
||||
}
|
||||
|
||||
|
||||
def access_snapshot(book: dict, *, openid: str, unlocked: bool) -> dict:
|
||||
"""轻量权限快照,供小程序轮询,无需清缓存。"""
|
||||
free = is_book_free(book)
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
"book_id": book["id"],
|
||||
"unlocked": bool(unlocked or free),
|
||||
"is_free": free,
|
||||
"unlock_percent": int(book.get("unlock_percent") or 0),
|
||||
"product_id": "" if free else str(book.get("product_id") or ""),
|
||||
"price_fen": 0 if free else int(book.get("price_fen") or 0),
|
||||
"offer_key": offer.get("key"),
|
||||
"updated_at": book.get("updated_at") or 0,
|
||||
"openid": openid,
|
||||
}
|
||||
5
apps/ebook/dymini/backend/app/jobs/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""后台定时任务。"""
|
||||
|
||||
from .reconcile import reconcile_pending_orders
|
||||
|
||||
__all__ = ["reconcile_pending_orders"]
|
||||
23
apps/ebook/dymini/backend/app/jobs/reconcile.py
Normal file
@ -0,0 +1,23 @@
|
||||
"""支付查单兜底任务。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.store import store
|
||||
from app.services.wxpay import query_order
|
||||
|
||||
|
||||
async def reconcile_pending_orders() -> None:
|
||||
"""推送丢失时,周期 query_order 查单补发货。"""
|
||||
pending = store.list_pending_orders()
|
||||
for order in pending:
|
||||
try:
|
||||
data = await query_order(order["openid"], order["out_trade_no"])
|
||||
text = str(data).lower()
|
||||
if "not pay" in text or "unpaid" in text or data.get("errcode") not in (0, None, "0"):
|
||||
if data.get("errcode") not in (0, None, "0"):
|
||||
continue
|
||||
if any(k in text for k in ["success", "paid", "已支付", '"status": 1', "order_state\":1"]):
|
||||
wx_id = str(data.get("wx_order_id") or data.get("order_id") or order["out_trade_no"])
|
||||
store.mark_delivered(order["out_trade_no"], wx_order_id=wx_id, raw_notify=str(data))
|
||||
except Exception:
|
||||
continue
|
||||
65
apps/ebook/dymini/backend/app/main.py
Normal file
@ -0,0 +1,65 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.config import settings
|
||||
from app.routers import admin, auth, books, pay, track
|
||||
|
||||
scheduler = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title=settings.app_name, lifespan=lifespan)
|
||||
|
||||
origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins or ["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(books.router)
|
||||
app.include_router(pay.router)
|
||||
app.include_router(track.router)
|
||||
app.include_router(admin.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"ok": True, "service": "dymini-api", "pay_mock": settings.tt_pay_mock}
|
||||
|
||||
|
||||
# 本地 debug 时可挂 admin;生产由 dyadmin.nomadro.cn 静态托管
|
||||
ADMIN_DIST = Path(__file__).resolve().parents[2] / "admin" / "dist"
|
||||
if settings.debug and ADMIN_DIST.exists():
|
||||
assets = ADMIN_DIST / "assets"
|
||||
if assets.exists():
|
||||
app.mount("/admin-assets", StaticFiles(directory=assets), name="admin-assets")
|
||||
|
||||
@app.get("/admin")
|
||||
@app.get("/admin/")
|
||||
async def admin_index():
|
||||
return FileResponse(ADMIN_DIST / "index.html")
|
||||
|
||||
|
||||
def run():
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("app.main:app", host=settings.api_host, port=settings.api_port, reload=settings.debug)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
2
apps/ebook/dymini/backend/app/models/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
# 占位:领域 Pydantic 已迁至 app/schemas/
|
||||
# 后续可将 ORM / 持久化实体放此处。
|
||||