Compare commits
12 Commits
3940a4ed3b
...
60606e53a7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60606e53a7 | ||
|
|
cee288b764 | ||
|
|
1c2486a9c5 | ||
|
|
76c22c23f4 | ||
|
|
ac1239c828 | ||
|
|
362dab20f6 | ||
|
|
5dd573ce22 | ||
|
|
b574a54d4c | ||
|
|
b845d0bcea | ||
|
|
525fbf7766 | ||
|
|
1dac5fd5fd | ||
|
|
de75f41816 |
@ -7,10 +7,12 @@
|
||||
|
||||
| 域名 | 产品 | 后端 | 源码 / 产物 | 鉴权 |
|
||||
|------|------|------|-------------|------|
|
||||
| **admin.hackrobot.cn** | **VIP 运营台**(`vip.hackrobot.cn`) | `/api/ops` → nomadvip `:4007`;`/api/admin/live/*` → nomadmini `:8010` | 独立 VIP SPA(勿用 Nomadro 微信壳覆盖) | `vip_ops_token`(HMAC) |
|
||||
| **admin.hackrobot.cn** | **VIP 运营台**(`vip.hackrobot.cn`) | `/api/ops` → nomadvip `:4007`;`/api/admin/live/*` → nomadmini `:8010` | **`apps/hackrobot/admin-site/`**(勿用 Nomadro 微信壳覆盖) | `vip_ops_token`(HMAC) |
|
||||
| **admin.nomadro.cn** | Nomadro 中国站后台(微信 / 抖音) | Nomadro API / PocketBase | `apps/admin` → admin.nomadro.cn | ebook/admin JWT |
|
||||
| admin.nomadro.com | Nomadro 国际站后台(仅 Web) | `.com` API | `apps/com/admin` | `.com` admin 会话 |
|
||||
|
||||
VIP 前台源码:`apps/hackrobot/vip/`(线上 `/www/wwwroot/nomadvip`)。同步/发版/强制备份见 `apps/hackrobot/README.md` 与 `hackrobot-vip-git.mdc`。
|
||||
|
||||
## 禁止
|
||||
|
||||
- 把 `apps/admin`(微信/抖音壳)部署成 `admin.hackrobot.cn`
|
||||
|
||||
24
.cursor/rules/hackrobot-vip-git.mdc
Normal file
@ -0,0 +1,24 @@
|
||||
# 异度星球 VIP(hackrobot)本地 SoT
|
||||
|
||||
## 源码位置(本仓)
|
||||
|
||||
| 线上 | 本地 |
|
||||
|---|---|
|
||||
| vip.hackrobot.cn(`/www/wwwroot/nomadvip` · `:4007`,含 `app/api`) | `apps/hackrobot/vip/` |
|
||||
| admin.hackrobot.cn(静态 SPA) | `apps/hackrobot/admin-site/` |
|
||||
| LIVE API `:8010` | `apps/hackrobot/nomadmini/` |
|
||||
| 支付 payjsapi | `apps/hackrobot/payjsapi/` |
|
||||
| 埋点 `:4011` | `apps/hackrobot/vip-track/` |
|
||||
| PocketBase `:8090` | `apps/hackrobot/pocketbase/` |
|
||||
|
||||
同步:`pull_from_129.py` + `pull_backends_from_129.py`
|
||||
发版:`deploy_admin_site.py` / `deploy_vip.py` / `deploy_nomadmini.py` / `deploy_payjsapi.py`(**一律先** `hackrobot-backup`)
|
||||
|
||||
## 铁律
|
||||
|
||||
- **禁止**把 `apps/admin`(Nomadro 微信/抖音壳)部署到 `admin.hackrobot.cn`
|
||||
- 改 VIP / 运营台只动 `apps/hackrobot/**`,勿与 `apps/admin` / `apps/com/admin` 混用
|
||||
- 发版前服务器必须有快照:`/opt/hackrobot-backup/snapshots/`
|
||||
- 前端上线仍受 `no-frontend-deploy-without-ok` 约束;未明确允许勿跑 `deploy_vip.py --build` / 上传 admin 静态站以外的擅自覆盖
|
||||
|
||||
详见 `apps/hackrobot/README.md` 与 `admin-hosts-never-confuse.mdc`。
|
||||
@ -18,8 +18,8 @@ alwaysApply: false
|
||||
## 微信配置(本项目允许写入 README;运行时仍可用环境变量覆盖)
|
||||
|
||||
```
|
||||
WX_APPID=wxa55815dd741a540d
|
||||
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
|
||||
WX_APPID=wx11f6afc44ea1532f
|
||||
WX_APPSECRET=04214ecc910dca4526781c90bae94da1
|
||||
WX_OFFER_ID=1450642200
|
||||
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
|
||||
18
.env.example
@ -13,13 +13,17 @@ NOMADRO_ADMIN_SESSION_SECRET=change-me-session
|
||||
# PB_ADMIN_TOKEN=
|
||||
|
||||
# WeChat miniprogram virtual pay (apps/api)
|
||||
WX_APPID=wxa55815dd741a540d
|
||||
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
|
||||
WX_OFFER_ID=1450642200
|
||||
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
# 1=sandbox 0=live
|
||||
WX_PAY_ENV=1
|
||||
WX_APPID=wx11f6afc44ea1532f
|
||||
WX_SECRET=04214ecc910dca4526781c90bae94da1
|
||||
WX_OFFER_ID=1450705308
|
||||
WX_APP_KEY=JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY
|
||||
WX_SANDBOX_APP_KEY=BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi
|
||||
# 0=现网 1=沙箱
|
||||
WX_PAY_ENV=0
|
||||
|
||||
# 公众号 userid 档案:读 vip.hackrobot.cn wechat-profile;可选 VIP 运营 token 拉全量列表
|
||||
# VIP_WEB_API_BASE=https://vip.hackrobot.cn
|
||||
# VIP_OPS_TOKEN=
|
||||
|
||||
# Observability (production)
|
||||
# NOMADRO_PUBLIC_ORIGIN=https://nomadro.com
|
||||
|
||||
11
.gitignore
vendored
@ -92,3 +92,14 @@ next-env.d.ts
|
||||
/apps/admin/deploy/certbot*.txt
|
||||
/apps/admin/deploy/*-redeploy*.txt
|
||||
/apps/admin/deploy/*-deploy.txt
|
||||
/apps/hackrobot/deploy/.cache/
|
||||
/apps/hackrobot/**/.venv/
|
||||
/apps/hackrobot/**/__pycache__/
|
||||
/apps/hackrobot/**/*.bak
|
||||
/apps/hackrobot/**/*.bak-*
|
||||
/apps/hackrobot/**/*.db
|
||||
/apps/hackrobot/**/*.sqlite*
|
||||
!/apps/hackrobot/pocketbase/data.db
|
||||
|
||||
/apps/hackrobot/vip/config/server-actions.key
|
||||
|
||||
|
||||
@ -21,6 +21,7 @@ Follow `.cursor/rules/*.mdc`。
|
||||
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
|
||||
| Unified API | `apps/api` |
|
||||
| Admin SPA (.cn) | `apps/admin` → `admin.nomadro.cn`(微信 / 抖音) |
|
||||
| **VIP hackrobot(隔离)** | `apps/hackrobot/{vip,admin-site,nomadmini}` → `vip.hackrobot.cn` / `admin.hackrobot.cn`(129);发版强制备份 |
|
||||
| **.com 隔离树** | `apps/com/*`(美国 VPS · **无小程序**);`apps/com/admin` → `admin.nomadro.com` |
|
||||
| Shared | `packages/{pay,pb,sdk}` |
|
||||
|
||||
@ -28,7 +29,7 @@ Follow `.cursor/rules/*.mdc`。
|
||||
|
||||
根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:admin-com` / `dev:api` / `typecheck` / `clean`。
|
||||
|
||||
Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`).
|
||||
Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `wemini`). VIP 源码在隔离树 `apps/hackrobot/`(勿再开顶层 `apps/nomadvip`)。
|
||||
|
||||
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
|
||||
|
||||
|
||||
21
README.md
@ -10,6 +10,8 @@
|
||||
>
|
||||
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 \.cursor/rules/admin-hosts-never-confuse.mdc\。
|
||||
|
||||
2026-11-22:微信小册**提审态默认免费**,且与正式付费数据隔离 — `platforms.weapp.bookAudit.reviewMode` 开启时读独立 `audit*` 书(永远 `is_free` / 不可下单 / 不读正式 `unlocks`·`__vip__`);关闭后重新拉正式已购与 VIP,互不粘态。weapp App 挂远程配置 WS + 1s 轮询,后台开关约 1s 热更新。API 已推 `api.nomadro.cn`(`_push_audit_free_isolate.py`);体验包须本轮许可后再 `build:weapp` 上传。
|
||||
|
||||
2026-11-15:VIP 运营台实时能力 — dmin.hackrobot.cn LIVE 在线/弹窗通知(ops token ↔ /api/admin/live)、用户拉黑/曾拉黑 tag 与身份提示;**写死** dmin.hackrobot.cn 与 dmin.nomadro.cn 永远禁止混淆。资产 pps/admin/deploy/_vip_live_assets/ · API live_ops/ops_live。
|
||||
|
||||
|
||||
@ -232,10 +234,10 @@ pnpm dev:api
|
||||
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
||||
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
||||
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||
- 审核冻结分支:`pre4`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`**
|
||||
- 审核冻结分支:`pre4`(历史审核包);历史微信提审包:`test9` + tag `2026-11-02`
|
||||
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
|
||||
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
|
||||
- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`)
|
||||
- **当前开发分支:`test14`**(微信小册提审隔离与热更新在此迭代;历史定版 tag 仍见 `test9`)
|
||||
|
||||
### 游民社区(`/social`)
|
||||
|
||||
@ -367,26 +369,29 @@ pnpm dev # http://localhost:3000/social/coffeechat
|
||||
| 分支 / Tag | `test9` · **`2026-11-02`** |
|
||||
| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) |
|
||||
| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` |
|
||||
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 audit 正文(失联才包内兜底);关则正式 nomad |
|
||||
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
|
||||
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 **audit 正文(默认免费全文)**;关则正式 nomad |
|
||||
| 提审/正式隔离 | 提审不读正式已购·VIP·付费方案;正式不粘提审免费态;`audit*` 书禁下单 / 禁手动解锁 / 禁配付费档 |
|
||||
| 配置热更新 | weapp `app.weapp`:WS + 1s poll;封面/阅读页 1s 拉配置;后台开关约 1s 生效 |
|
||||
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` · VIP 库「微信提审」卡 |
|
||||
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
|
||||
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
|
||||
| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
|
||||
| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
|
||||
|
||||
提审上传:
|
||||
提审上传(**须本轮明确许可**,见 `no-frontend-deploy-without-ok`):
|
||||
|
||||
```bash
|
||||
pnpm build:weapp
|
||||
# 微信开发者工具打开 apps/miniprogram/weapp(miniprogramRoot=dist/)→ 上传
|
||||
# 后台按需打开「数字游民」提审;socket 合法域名含 api.nomadro.cn
|
||||
# 微信开发者工具 / cli 上传 apps/miniprogram/weapp(miniprogramRoot=dist/)
|
||||
# 后台 VIP→电子书→数字游民打开「提审中」;socket 合法域名含 api.nomadro.cn
|
||||
# 后端隔离补丁:python apps/admin/deploy/_push_audit_free_isolate.py
|
||||
```
|
||||
|
||||
## pre3 摘要(已合入)
|
||||
|
||||
微信提审与包体:
|
||||
|
||||
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书,关则回正式 VIP 书;前端不展示「提审」文案
|
||||
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书(**默认免费**,与正式已购/VIP 隔离),关则回正式 VIP 书;前端不展示「提审」文案
|
||||
- **入口默认隐藏**:远程配置未就绪不渲染门户卡片 / 模块闸门,避免先闪后藏
|
||||
- **安全区**:自定义顶栏内联尺寸用大写 `PX` 跳过 Taro rpx;阅读页顶栏不再叠状态栏 padding
|
||||
- **代码质量**:`lazyCodeLoading` · 分包 + `optimizeMainPackage`(主包 ≪1.5MB)· 导航图标走 `https://nomadro.cn/icons`(包内图片合计 ≤200K)
|
||||
|
||||
@ -5,5 +5,6 @@
|
||||
| **`api/`** | 统一 FastAPI(电子书 + 社群 + 支付) |
|
||||
| **`miniprogram/`** | Taro:`h5` SoT · `weapp` / `tt` / `xhs` |
|
||||
| **`admin/`** | admin.nomadro.cn 管理 SPA(Vite) |
|
||||
| **`hackrobot/`** | 异度星球 VIP:`vip.hackrobot.cn` + `admin.hackrobot.cn`(与 Nomadro 后台隔离) |
|
||||
|
||||
门户 Next 在仓库根:`src/`(`src/app` + `src/modules`)。
|
||||
|
||||
50
apps/admin/deploy/_deploy_books_live_82.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy books_live + admin router (offer hot bump) to api.nomadro.cn."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
FILES = [
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/services/books_live.py",
|
||||
"/opt/nomadmini/backend/app/services/books_live.py",
|
||||
),
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/routers/admin.py",
|
||||
"/opt/nomadmini/backend/app/routers/admin.py",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for src, dest in FILES:
|
||||
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||
tmp = f"/tmp/{Path(dest).name}"
|
||||
with sftp.file(tmp, "wb") as rf:
|
||||
rf.write(data)
|
||||
print("up", src.name, len(data))
|
||||
sftp.close()
|
||||
_, o, e = c.exec_command(
|
||||
"sudo cp /tmp/books_live.py /opt/nomadmini/backend/app/services/books_live.py && "
|
||||
"sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py && "
|
||||
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
|
||||
"systemctl is-active nomadmini-api.service && curl -s http://127.0.0.1:8010/health",
|
||||
timeout=60,
|
||||
)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-800:])
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
82
apps/admin/deploy/_deploy_per_book_pay_82.py
Normal file
@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy admin.py (book shells) + admin SPA for per-book monetize."""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
ROOT = REPO / "apps" / "admin"
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("vite build…", flush=True)
|
||||
r = subprocess.run(
|
||||
["pnpm", "exec", "vite", "build"],
|
||||
cwd=ROOT,
|
||||
shell=True,
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
if r.returncode != 0:
|
||||
print(r.stdout)
|
||||
print(r.stderr)
|
||||
return r.returncode
|
||||
|
||||
dist = ROOT / "dist"
|
||||
buf = BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for p in dist.rglob("*"):
|
||||
if p.is_file():
|
||||
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
|
||||
buf.seek(0)
|
||||
|
||||
api = (REPO / "apps/api/services/ebook_svc/routers/admin.py").read_text(encoding="utf-8")
|
||||
api = api.replace("ebook_svc.", "app.").encode("utf-8")
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/admin-spa.tar.gz", "wb") as rf:
|
||||
rf.write(buf.getvalue())
|
||||
with sftp.file("/tmp/admin.py", "wb") as rf:
|
||||
rf.write(api)
|
||||
sftp.close()
|
||||
|
||||
cmd = r"""
|
||||
set -e
|
||||
# keep props
|
||||
sudo mkdir -p /tmp/props-bak && sudo cp -a /www/wwwroot/admin.nomadro.cn/props/. /tmp/props-bak/ 2>/dev/null || true
|
||||
cd /tmp
|
||||
rm -rf admin-unpack && mkdir admin-unpack
|
||||
tar -xzf admin-spa.tar.gz -C admin-unpack
|
||||
sudo rsync -a --delete admin-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
|
||||
sudo mkdir -p /www/wwwroot/admin.nomadro.cn/props
|
||||
sudo cp -a /tmp/props-bak/. /www/wwwroot/admin.nomadro.cn/props/ 2>/dev/null || true
|
||||
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
|
||||
sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py
|
||||
sudo systemctl restart nomadmini-api.service
|
||||
sleep 2
|
||||
systemctl is-active nomadmini-api.service
|
||||
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/vip/ebooks/nomad
|
||||
curl -sk -o /dev/null -w "props %{http_code}\n" https://admin.nomadro.cn/props/nomad_lite.png
|
||||
"""
|
||||
_, stdout, stderr = c.exec_command(cmd, timeout=120)
|
||||
print(stdout.read().decode())
|
||||
err = stderr.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-800:])
|
||||
c.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
109
apps/admin/deploy/_deploy_wx_props_catalog_82.py
Normal file
@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Push ops prop catalog (products.py / vip_config) to api.nomadro.cn + migrate old SKUs."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
|
||||
FILES = [
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/domains/books/products.py",
|
||||
"/opt/nomadmini/backend/app/domains/books/products.py",
|
||||
),
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/services/vip_config.py",
|
||||
"/opt/nomadmini/backend/app/services/vip_config.py",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def rewrite(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for src, dest in FILES:
|
||||
data = rewrite(src.read_text(encoding="utf-8")).encode("utf-8")
|
||||
tmp = f"/tmp/{Path(dest).name}"
|
||||
with sftp.file(tmp, "wb") as rf:
|
||||
rf.write(data)
|
||||
print("up", src.name, "->", dest, len(data))
|
||||
sftp.close()
|
||||
|
||||
remote = r"""
|
||||
set -e
|
||||
sudo cp /tmp/products.py /opt/nomadmini/backend/app/domains/books/products.py
|
||||
sudo cp /tmp/vip_config.py /opt/nomadmini/backend/app/services/vip_config.py
|
||||
sudo chown -R ubuntu:ubuntu /opt/nomadmini/backend/app/domains/books/products.py /opt/nomadmini/backend/app/services/vip_config.py
|
||||
|
||||
# 旧微信草稿 id → 新运营 SKU(书籍 + 商城商品)
|
||||
python3 <<'PY'
|
||||
import sqlite3
|
||||
db = "/opt/nomadmini/data/nomadmini.db"
|
||||
con = sqlite3.connect(db)
|
||||
maps = {
|
||||
"29": "nomad_lite",
|
||||
"298": "nomad_plus",
|
||||
"588": "nomad_pro",
|
||||
"test": "pay_test",
|
||||
}
|
||||
# books.product_id
|
||||
for old, new in maps.items():
|
||||
cur = con.execute("update books set product_id=? where product_id=?", (new, old))
|
||||
print("books", old, "->", new, "rows", cur.rowcount)
|
||||
# shop products wxProductId if column exists
|
||||
cols = {r[1] for r in con.execute("pragma table_info(shop_products)").fetchall()} if con.execute(
|
||||
"select name from sqlite_master where type='table' and name='shop_products'"
|
||||
).fetchone() else set()
|
||||
if "wxProductId" in cols or "wx_product_id" in cols:
|
||||
col = "wxProductId" if "wxProductId" in cols else "wx_product_id"
|
||||
for old, new in maps.items():
|
||||
cur = con.execute(f"update shop_products set {col}=? where {col}=?", (new, old))
|
||||
print("shop", old, "->", new, "rows", cur.rowcount)
|
||||
# goods table variants
|
||||
for table in ("products", "goods"):
|
||||
row = con.execute(
|
||||
"select name from sqlite_master where type='table' and name=?", (table,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
continue
|
||||
cols = {r[1] for r in con.execute(f"pragma table_info({table})").fetchall()}
|
||||
for col in ("wxProductId", "wx_product_id", "product_id"):
|
||||
if col not in cols:
|
||||
continue
|
||||
for old, new in maps.items():
|
||||
cur = con.execute(f"update {table} set {col}=? where {col}=?", (new, old))
|
||||
if cur.rowcount:
|
||||
print(table, col, old, "->", new, "rows", cur.rowcount)
|
||||
con.commit()
|
||||
# show current book SKUs
|
||||
print("--- books product_id ---")
|
||||
for r in con.execute("select id, title, product_id, price_fen from books order by id").fetchall():
|
||||
print(r)
|
||||
con.close()
|
||||
PY
|
||||
|
||||
sudo systemctl restart nomadmini-api.service
|
||||
sleep 2
|
||||
systemctl is-active nomadmini-api.service
|
||||
curl -s http://127.0.0.1:8010/health || true
|
||||
echo
|
||||
"""
|
||||
_, o, e = c.exec_command(remote, timeout=120)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("stderr", err[-2000:])
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
40
apps/admin/deploy/_probe_restart_products_82.py
Normal file
@ -0,0 +1,40 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
CMD = r"""
|
||||
set -e
|
||||
echo '=== file head ==='
|
||||
head -8 /opt/nomadmini/backend/app/domains/books/products.py
|
||||
echo '=== grep nomad_lite ==='
|
||||
grep -n nomad_lite /opt/nomadmini/backend/app/domains/books/products.py || true
|
||||
echo '=== processes ==='
|
||||
ps aux | grep -E 'uvicorn|nomadmini|gunicorn|8010' | grep -v grep || true
|
||||
echo '=== pm2 ==='
|
||||
pm2 list 2>/dev/null || true
|
||||
echo '=== systemd units ==='
|
||||
ls /etc/systemd/system/*nom* /etc/systemd/system/*ebook* /etc/systemd/system/*api* 2>/dev/null || true
|
||||
echo '=== how 8010 listens ==='
|
||||
sudo ss -lntp | grep -E '8010|8000' || true
|
||||
echo '=== find restart scripts ==='
|
||||
ls /opt/nomadmini/*.sh /opt/nomadmini/backend/*.sh 2>/dev/null || true
|
||||
cat /opt/nomadmini/ecosystem.config.* 2>/dev/null || true
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
_, o, e = c.exec_command(CMD, timeout=60)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-1500:])
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
37
apps/admin/deploy/_push_admin_offer_name_82.py
Normal file
@ -0,0 +1,37 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
SRC = REPO / "apps/api/services/ebook_svc/routers/admin.py"
|
||||
DEST = "/opt/nomadmini/backend/app/routers/admin.py"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/admin.py", "wb") as rf:
|
||||
rf.write(data)
|
||||
sftp.close()
|
||||
_, o, e = c.exec_command(
|
||||
"sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py && "
|
||||
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
|
||||
"systemctl is-active nomadmini-api.service && curl -s http://127.0.0.1:8010/health",
|
||||
timeout=60,
|
||||
)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-800:])
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
108
apps/admin/deploy/_push_audit_free_isolate.py
Normal file
@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Push audit-book free + pay isolation patches → 82 nomadmini-api (backend only)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
|
||||
FILES = [
|
||||
("apps/api/services/ebook_svc/domains/books/products.py", "domains/books/products.py"),
|
||||
("apps/api/services/ebook_svc/domains/books/__init__.py", "domains/books/__init__.py"),
|
||||
("apps/api/services/ebook_svc/routers/books.py", "routers/books.py"),
|
||||
("apps/api/services/ebook_svc/routers/pay.py", "routers/pay.py"),
|
||||
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
|
||||
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
||||
]
|
||||
|
||||
|
||||
def rewrite(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def pack() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for rel, dest in FILES:
|
||||
src = REPO / rel
|
||||
text = rewrite(src.read_text(encoding="utf-8"))
|
||||
if "ebook_svc." in text:
|
||||
raise SystemExit(f"rewrite failed: {rel}")
|
||||
data = text.encode("utf-8")
|
||||
info = tarfile.TarInfo(name="api/" + dest)
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
print("pack", dest, flush=True)
|
||||
buf.seek(0)
|
||||
blob = buf.read()
|
||||
print("blob", len(blob), flush=True)
|
||||
return blob
|
||||
|
||||
|
||||
REMOTE_CMD = r"""
|
||||
set -e
|
||||
cd /tmp
|
||||
rm -rf audit-free-api && mkdir audit-free-api
|
||||
tar -xzf audit-free-api.tar.gz -C audit-free-api
|
||||
B=/opt/nomadmini/backend/app
|
||||
for f in domains/books/products.py domains/books/__init__.py routers/books.py routers/pay.py routers/admin.py services/store.py; do
|
||||
sudo cp -a "$B/$f" "$B/$f.bak-audit-free" 2>/dev/null || true
|
||||
sudo mkdir -p "$(dirname "$B/$f")"
|
||||
sudo cp "audit-free-api/api/$f" "$B/$f"
|
||||
echo copied $f
|
||||
done
|
||||
cd /opt/nomadmini/backend
|
||||
.venv/bin/python - <<'PY'
|
||||
from app.domains.books import is_audit_book_id, is_book_free
|
||||
assert is_audit_book_id('audit')
|
||||
assert is_audit_book_id('audit-v2')
|
||||
assert not is_audit_book_id('nomad')
|
||||
assert is_book_free({'id': 'audit', 'unlock_percent': 30})
|
||||
print('audit_free_ok')
|
||||
PY
|
||||
sudo systemctl restart nomadmini-api
|
||||
sleep 3
|
||||
systemctl is-active nomadmini-api
|
||||
curl -sk -o /dev/null -w 'health %{http_code}\n' https://api.nomadro.cn/health
|
||||
curl -sk 'https://api.nomadro.cn/api/ebook/books/audit' | python3 -c 'import sys,json; d=json.load(sys.stdin); print("audit", d.get("id"), "free", d.get("is_free"), "pct", d.get("unlock_percent"), "fen", d.get("price_fen"))'
|
||||
rm -rf /tmp/audit-free-api /tmp/audit-free-api.tar.gz
|
||||
"""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
blob = pack()
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(
|
||||
HOST,
|
||||
username=USER,
|
||||
password=PASS,
|
||||
timeout=60,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/audit-free-api.tar.gz", "wb") as rf:
|
||||
rf.write(blob)
|
||||
sftp.close()
|
||||
_, stdout, stderr = c.exec_command(REMOTE_CMD, timeout=180)
|
||||
out = stdout.read().decode("utf-8", "replace")
|
||||
err = stderr.read().decode("utf-8", "replace")
|
||||
print(out)
|
||||
if err.strip():
|
||||
print("STDERR", err)
|
||||
c.close()
|
||||
if "audit_free_ok" not in out:
|
||||
return 2
|
||||
if "active" not in out:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
45
apps/admin/deploy/_restart_nomadmini_api_82.py
Normal file
@ -0,0 +1,45 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
_, o, e = c.exec_command(
|
||||
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
|
||||
"systemctl is-active nomadmini-api.service && "
|
||||
"curl -s http://127.0.0.1:8010/health",
|
||||
timeout=60,
|
||||
)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-1000:])
|
||||
c.close()
|
||||
|
||||
req = urllib.request.Request(
|
||||
"https://api.nomadro.cn/api/admin/login",
|
||||
data=json.dumps({"username": "admin", "password": "Xiao4669805"}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
tok = json.loads(urllib.request.urlopen(req, timeout=20).read()).get("token", "")
|
||||
req2 = urllib.request.Request(
|
||||
"https://api.nomadro.cn/api/admin/product-offers",
|
||||
headers={"Authorization": "Bearer " + tok},
|
||||
)
|
||||
items = json.loads(urllib.request.urlopen(req2, timeout=20).read()).get("items") or []
|
||||
for o in items:
|
||||
print(o.get("key"), o.get("product_id"), o.get("name"), o.get("price_yuan"), o.get("remark"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
50
apps/admin/deploy/_smoke_live_offer_82.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Smoke: admin VIP + book offer switch bumps remote config for live sync."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
BASE = "https://api.nomadro.cn"
|
||||
|
||||
|
||||
def post(url: str, data: dict | None = None, token: str = "") -> dict:
|
||||
body = None if data is None else json.dumps(data).encode()
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST" if body else "GET")
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
tok = post(f"{BASE}/api/admin/login", {"username": "admin", "password": "Xiao4669805"})["token"]
|
||||
before = post(f"{BASE}/api/config/pull", {"t": 1})
|
||||
cfg0 = before.get("config") or {}
|
||||
print("before", cfg0.get("version"), (cfg0.get("copy") or {}).get("vipProductId"), (cfg0.get("copy") or {}).get("booksOfferRev"))
|
||||
|
||||
vip = post(f"{BASE}/api/admin/vip/offer", {"offer_key": "nomad"}, tok)
|
||||
print("vip", vip.get("vipProductId"), vip.get("vipPriceFen"), vip.get("vipCta"))
|
||||
|
||||
book = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "yen29"}, tok)
|
||||
print("book", book.get("product_id"), book.get("price_fen"), book.get("offer_name"))
|
||||
|
||||
after = post(f"{BASE}/api/config/pull", {"t": 2})
|
||||
cfg1 = after.get("config") or {}
|
||||
copy = cfg1.get("copy") or {}
|
||||
print(
|
||||
"after",
|
||||
cfg1.get("version"),
|
||||
copy.get("vipProductId"),
|
||||
copy.get("vipPriceFen"),
|
||||
copy.get("booksOfferRev"),
|
||||
copy.get("booksOfferBookId"),
|
||||
)
|
||||
# restore book to nomad (main push)
|
||||
restored = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "nomad"}, tok)
|
||||
print("restore_book", restored.get("product_id"), restored.get("offer_name"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
50
apps/admin/deploy/_upload_new_props_82.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Upload ops prop PNGs to admin.nomadro.cn/props/ (CORS for WeChat batch)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
LOCAL = Path(__file__).resolve().parents[1] / "public" / "props"
|
||||
FILES = (
|
||||
"nomad_lite.png",
|
||||
"nomad_plus.png",
|
||||
"nomad_pro.png",
|
||||
"pay_test.png",
|
||||
"29.png",
|
||||
"298.png",
|
||||
"588.png",
|
||||
"test.png",
|
||||
"nomad.png",
|
||||
"tiktok.png",
|
||||
"youtube.png",
|
||||
"ebook.png",
|
||||
"svip.png",
|
||||
)
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
c.exec_command("mkdir -p /tmp/wx_props_new", timeout=10)
|
||||
for name in FILES:
|
||||
path = LOCAL / name
|
||||
if not path.is_file():
|
||||
print("skip missing", name)
|
||||
continue
|
||||
sftp.put(str(path), f"/tmp/wx_props_new/{name}")
|
||||
print("up", name, path.stat().st_size)
|
||||
sftp.close()
|
||||
_, o, e = c.exec_command(
|
||||
"sudo cp -a /tmp/wx_props_new/. /www/wwwroot/admin.nomadro.cn/props/ && "
|
||||
"sudo chown -R www:www /www/wwwroot/admin.nomadro.cn/props && "
|
||||
"ls -lah /www/wwwroot/admin.nomadro.cn/props/ && "
|
||||
"curl -sI https://admin.nomadro.cn/props/nomad_lite.png -H 'Origin: https://mp.weixin.qq.com' | tr -d '\\r' | head -15"
|
||||
)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("stderr", err)
|
||||
c.close()
|
||||
@ -113,11 +113,11 @@ def main() -> None:
|
||||
f"tar -xzf release.tar.gz && rm release.tar.gz",
|
||||
)
|
||||
|
||||
env_content = """WX_APPID=wxa55815dd741a540d
|
||||
WX_SECRET=bf71025c209e7567d49268bc427ba22b
|
||||
WX_OFFER_ID=1450642200
|
||||
WX_APP_KEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
WX_SANDBOX_APP_KEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
env_content = """WX_APPID=wx11f6afc44ea1532f
|
||||
WX_SECRET=04214ecc910dca4526781c90bae94da1
|
||||
WX_OFFER_ID=1450705308
|
||||
WX_APP_KEY=JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY
|
||||
WX_SANDBOX_APP_KEY=BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi
|
||||
WX_PAY_ENV=0
|
||||
JWT_SECRET=nomadro-jwt-prod-2026
|
||||
ADMIN_USERNAME=hackrobot
|
||||
|
||||
BIN
apps/admin/public/props/29.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
apps/admin/public/props/298.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/admin/public/props/588.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
apps/admin/public/props/nomad_lite.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
apps/admin/public/props/nomad_plus.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/admin/public/props/nomad_pro.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
apps/admin/public/props/pay_test.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 21 KiB |
235
apps/admin/src/components/BookMonetizePanel.tsx
Normal file
@ -0,0 +1,235 @@
|
||||
/**
|
||||
* 单本小册独立试读/付费方案(互不影响)。
|
||||
* 数据落在 books/{bookId}:product_id / price_fen / unlock_percent。
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import '../pages/BookEdit.css'
|
||||
|
||||
export type ProductOffer = {
|
||||
key: string
|
||||
label: string
|
||||
name: string
|
||||
product_id: string
|
||||
price_fen: number
|
||||
price_yuan: string
|
||||
free: boolean
|
||||
image: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export type BookMonetize = {
|
||||
id: string
|
||||
title?: string
|
||||
product_id: string
|
||||
price_fen: number
|
||||
unlock_percent: number
|
||||
offer_key?: string
|
||||
offer_name?: string
|
||||
is_free?: boolean
|
||||
}
|
||||
|
||||
type Props = {
|
||||
bookId: string
|
||||
/** 展示名,如「数字游民」 */
|
||||
bookLabel?: string
|
||||
/** 方案变更后回调(可用来同步 VIP 库 free 标记) */
|
||||
onChanged?: (book: BookMonetize) => void
|
||||
}
|
||||
|
||||
export default function BookMonetizePanel({ bookId, bookLabel, onChanged }: Props) {
|
||||
const [book, setBook] = useState<BookMonetize | null>(null)
|
||||
const [offers, setOffers] = useState<ProductOffer[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const [b, o] = await Promise.all([
|
||||
api<BookMonetize>(`/api/admin/books/${encodeURIComponent(bookId)}`),
|
||||
api<{ items: ProductOffer[] }>('/api/admin/product-offers'),
|
||||
])
|
||||
setBook(b)
|
||||
setOffers(o.items || [])
|
||||
}, [bookId])
|
||||
|
||||
useEffect(() => {
|
||||
setMsg('')
|
||||
setErr('')
|
||||
load().catch((e) => setErr(e.message || '加载付费方案失败'))
|
||||
}, [load])
|
||||
|
||||
const isFree = !!book && (book.is_free || book.unlock_percent >= 100 || !book.product_id)
|
||||
const activeOfferKey = useMemo(() => {
|
||||
if (!book) return ''
|
||||
if (book.offer_key) return book.offer_key
|
||||
if (isFree) return 'free'
|
||||
return (
|
||||
offers.find((o) => !o.free && o.product_id === book.product_id)?.key ||
|
||||
''
|
||||
)
|
||||
}, [book, offers, isFree])
|
||||
|
||||
async function applyOffer(offerKey: string) {
|
||||
if (!bookId || busy) return
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api<BookMonetize>(
|
||||
`/api/admin/books/${encodeURIComponent(bookId)}/offer`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ offer_key: offerKey, keep_preview_percent: true }),
|
||||
},
|
||||
)
|
||||
setBook(updated)
|
||||
onChanged?.(updated)
|
||||
const label = offers.find((o) => o.key === offerKey)?.name || offerKey
|
||||
setMsg(
|
||||
updated.unlock_percent >= 100 || !updated.product_id
|
||||
? `「${bookLabel || bookId}」已切免费 · 与其它小册互不影响`
|
||||
: `「${bookLabel || bookId}」已切 ${label} · 试读 ${Math.min(99, updated.unlock_percent)}% · 仅本册`,
|
||||
)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '切换方案失败')
|
||||
await load().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function savePreview() {
|
||||
if (!book || busy) return
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api<BookMonetize>(
|
||||
`/api/admin/books/${encodeURIComponent(bookId)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
unlock_percent: Math.min(99, Math.max(1, Number(book.unlock_percent) || 30)),
|
||||
}),
|
||||
},
|
||||
)
|
||||
setBook(updated)
|
||||
onChanged?.(updated)
|
||||
setMsg(`「${bookLabel || bookId}」试读 ${Math.min(99, updated.unlock_percent)}% 已保存 · 仅本册`)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '保存失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!book && !err) {
|
||||
return <section className="monetize-panel">加载本册付费方案…</section>
|
||||
}
|
||||
if (!book) {
|
||||
return (
|
||||
<section className="monetize-panel">
|
||||
<p className="hint" style={{ color: '#f87171' }}>
|
||||
{err}
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="monetize-panel">
|
||||
<div className="monetize-head">
|
||||
<div>
|
||||
<h2 className="monetize-title">本册 · 试读与付费</h2>
|
||||
<p className="hint">
|
||||
只改《{bookLabel || book.title || bookId}》的道具与试读比例,不影响其它小册 / VIP
|
||||
会员价。后台切换后小程序约 1–2 秒热更新。
|
||||
</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.offer_name || book.product_id || '-'} · 试读 ${Math.min(99, book.unlock_percent)}%`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{err ? <p className="hint" style={{ color: '#f87171' }}>{err}</p> : null}
|
||||
{msg ? <p className="hint" style={{ color: '#6ee7b7' }}>{msg}</p> : null}
|
||||
|
||||
<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={busy}
|
||||
onClick={() => void 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.name || o.label}</strong>
|
||||
<span className="offer-id">{o.free ? '免费加入' : 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)}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setBook({ ...book, unlock_percent: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
<strong>{Math.min(99, book.unlock_percent)}%</strong>
|
||||
</div>
|
||||
<p className="hint">点「保存试读」写入本册;点免费卡片 = 全书开放。</p>
|
||||
<button type="button" className="file-btn" disabled={busy} onClick={() => void savePreview()}>
|
||||
保存试读比例
|
||||
</button>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@ -21,6 +21,7 @@ type Book = {
|
||||
chapter_count?: number
|
||||
word_count?: number
|
||||
offer_key?: string
|
||||
offer_name?: string
|
||||
is_free?: boolean
|
||||
}
|
||||
|
||||
@ -297,9 +298,9 @@ export default function BookEdit() {
|
||||
<section className="monetize-panel">
|
||||
<div className="monetize-head">
|
||||
<div>
|
||||
<h2 className="monetize-title">阅读与付费</h2>
|
||||
<h2 className="monetize-title">本册 · 试读与付费</h2>
|
||||
<p className="hint">
|
||||
切换免费或付费方案后,小程序「解锁全文」按钮会跟着变(需重新打开阅读页)。
|
||||
只改本册道具与试读比例,与其它小册互不影响。小程序约 1–2 秒热更新。
|
||||
</p>
|
||||
</div>
|
||||
<div className="live-preview">
|
||||
@ -312,7 +313,7 @@ export default function BookEdit() {
|
||||
<span className="live-preview-sub">
|
||||
{isFree
|
||||
? '免费模式 · 无支付墙'
|
||||
: `道具 ${book.product_id || '-'} · 试读 ${Math.min(99, book.unlock_percent)}%`}
|
||||
: `${book.offer_name || book.product_id || '-'} · 试读 ${Math.min(99, book.unlock_percent)}%`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -336,9 +337,9 @@ export default function BookEdit() {
|
||||
) : (
|
||||
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
|
||||
)}
|
||||
<strong>{o.label}</strong>
|
||||
<strong>{o.name || o.label}</strong>
|
||||
<span className="offer-id">
|
||||
{o.free ? 'unlock=100%' : o.product_id}
|
||||
{o.free ? '免费加入' : o.product_id}
|
||||
</span>
|
||||
<em>{o.price_yuan}</em>
|
||||
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
|
||||
|
||||
@ -366,7 +366,7 @@ export default function Shop() {
|
||||
) : (
|
||||
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
|
||||
)}
|
||||
<strong>{o.label}</strong>
|
||||
<strong>{o.name || o.label}</strong>
|
||||
<span className="offer-id">{o.product_id}</span>
|
||||
<em>{o.price_yuan}</em>
|
||||
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
|
||||
|
||||
@ -392,7 +392,7 @@ export default function Vip() {
|
||||
setMsg(
|
||||
saved.is_free
|
||||
? '已切换免费 · 小程序「立即加入」→ 免费加入'
|
||||
: `已切换 ${saved.vipProductId} · CTA「${saved.vipCta}」约 3s 热更新`,
|
||||
: `已切换 ${saved.vipProductId || saved.vipOfferKey} · CTA「${saved.vipCta}」约 1s 热更新`,
|
||||
)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '切换方案失败')
|
||||
@ -416,7 +416,7 @@ export default function Vip() {
|
||||
<div className="vip-eyebrow">WeChat · VIP · Remote</div>
|
||||
<h1>VIP 运营</h1>
|
||||
<p>
|
||||
只影响微信小程序 · 不改抖音 · 不改订单。付费与落地页写远程配置,小程序约 3 秒热更新。
|
||||
只影响微信小程序 · 不改抖音 · 不改订单。付费与落地页写远程配置,小程序约 1 秒热更新(WS + 轮询)。
|
||||
</p>
|
||||
<div className="vip-chips">
|
||||
<span className={`vip-chip ${draft.vipEnabled ? 'on' : ''}`}>
|
||||
@ -474,7 +474,7 @@ export default function Vip() {
|
||||
<div>
|
||||
<h2>立即加入 · 付费控制</h2>
|
||||
<p>
|
||||
一键切换免费 / 已发布道具。切换后小程序按钮文案与价格立即跟随(已打开会员页约 3s
|
||||
一键切换免费 / 已发布道具。切换后小程序 CTA 与价格立即跟随(已打开会员页约 1s
|
||||
热更新)。
|
||||
</p>
|
||||
</div>
|
||||
@ -484,7 +484,7 @@ export default function Vip() {
|
||||
<em>
|
||||
{isFree
|
||||
? '免费模式 · 不拉起虚拟支付'
|
||||
: `道具 ${draft.vipProductId || '-'} · ¥${(draft.vipPriceFen / 100).toFixed(0)}`}
|
||||
: `${offers.find((o) => o.product_id === draft.vipProductId)?.name || draft.vipProductId || '-'} · ¥${(draft.vipPriceFen / 100).toFixed(0)}`}
|
||||
</em>
|
||||
</div>
|
||||
</div>
|
||||
@ -508,7 +508,7 @@ export default function Vip() {
|
||||
) : (
|
||||
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
|
||||
)}
|
||||
<strong>{o.label}</strong>
|
||||
<strong>{o.name || o.label}</strong>
|
||||
<span className="offer-id">{o.free ? '免费加入' : o.product_id}</span>
|
||||
<em>{o.price_yuan}</em>
|
||||
{o.remark && !o.remark.includes('unlock_percent') ? (
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import BookMonetizePanel, { type BookMonetize } from '../components/BookMonetizePanel'
|
||||
import './Vip.css'
|
||||
|
||||
type Ebook = {
|
||||
@ -431,7 +432,7 @@ export default function VipLibrary() {
|
||||
<div>
|
||||
<h2>微信提审</h2>
|
||||
<p>
|
||||
打开后,小程序「小册」只展示独立的审核版正文(不是下面这本正式会员书)。关了就恢复正式版。不影响云手机、youtube运营笔记。
|
||||
打开后,小程序「小册」只展示独立的审核版正文(默认免费全文,与正式会员书的已购/VIP/付费数据隔离)。关了就恢复正式版。不影响云手机、youtube运营笔记。
|
||||
</p>
|
||||
</div>
|
||||
<div className="vip-row" style={{ border: 'none', padding: 0, margin: 0 }}>
|
||||
@ -460,7 +461,7 @@ export default function VipLibrary() {
|
||||
去写审核版正文 →
|
||||
</Link>
|
||||
<span className="vip-hint" style={{ alignSelf: 'center' }}>
|
||||
审核版是单独一本,不会自动抄正式会员书
|
||||
审核版单独一本 · 永远免费 · 不共用正式付费解锁
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
@ -501,23 +502,23 @@ export default function VipLibrary() {
|
||||
onChange={(e) => setDraftTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="vip-row" style={{ border: 'none', padding: '0 0 8px' }}>
|
||||
<div>
|
||||
<strong>免费开放</strong>
|
||||
<p className="vip-hint">打开后无需会员也能读完全书</p>
|
||||
</div>
|
||||
<label className="vip-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draftFree}
|
||||
disabled={busy}
|
||||
onChange={(e) => setDraftFree(e.target.checked)}
|
||||
/>
|
||||
<span className="vip-switch-track">
|
||||
<span className="vip-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 每本独立试读/道具,与 youtube运营笔记(books/default) 同机制、互不影响 */}
|
||||
<div id="book-monetize" style={{ scrollMarginTop: 88 }}>
|
||||
<BookMonetizePanel
|
||||
bookId={bookId}
|
||||
bookLabel={bookLabel}
|
||||
onChanged={(m: BookMonetize) => {
|
||||
const free = !!(m.is_free || m.unlock_percent >= 100 || !m.product_id)
|
||||
setDraftFree(free)
|
||||
// 同步 VIP 库 free 标记,供落地页卡片展示;付费字段以 books 表为准
|
||||
void api(`/api/admin/vip/library/ebooks/${bookId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ free }),
|
||||
}).catch(() => undefined)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="vip-layout">
|
||||
|
||||
@ -23,12 +23,12 @@ class Settings(BaseSettings):
|
||||
"http://localhost:5173,http://127.0.0.1:5173,http://localhost:3000,http://127.0.0.1:3000"
|
||||
)
|
||||
|
||||
# WeChat
|
||||
wx_appid: str = "wxa55815dd741a540d"
|
||||
wx_secret: str = "bf71025c209e7567d49268bc427ba22b"
|
||||
wx_offer_id: str = "1450642200"
|
||||
wx_app_key: str = "CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg"
|
||||
wx_sandbox_app_key: str = "0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn"
|
||||
# WeChat 虚拟支付(AppID wx11f6afc44ea1532f · OfferID 1450705308)
|
||||
wx_appid: str = "wx11f6afc44ea1532f"
|
||||
wx_secret: str = "04214ecc910dca4526781c90bae94da1"
|
||||
wx_offer_id: str = "1450705308"
|
||||
wx_app_key: str = "JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY" # 现网
|
||||
wx_sandbox_app_key: str = "BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi" # 沙箱
|
||||
wx_pay_env: int = 0 # 0 现网 / 1 沙箱
|
||||
|
||||
# JWT / Admin
|
||||
@ -48,6 +48,11 @@ class Settings(BaseSettings):
|
||||
# 开启:环境变量 VIP_WEB_BRIDGE_ENABLED=true
|
||||
vip_web_bridge_enabled: bool = False
|
||||
vip_web_api_base: str = "https://vip.hackrobot.cn"
|
||||
# 可选:代理 vip.hackrobot.cn/api/wechat-users(运营台 token);空则自动登录 ops
|
||||
vip_ops_token: str = ""
|
||||
vip_ops_login_url: str = "https://admin.hackrobot.cn/api/ops/login"
|
||||
vip_ops_username: str = "hackrobot"
|
||||
vip_ops_password: str = "Xiao4669805@"
|
||||
|
||||
# 抖音 platforms.tt 写入路径(默认自动探测门户 remote-config.json)
|
||||
tt_remote_config_path: str = ""
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
from .products import (
|
||||
PRODUCT_OFFERS,
|
||||
apply_offer_key,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
match_offer,
|
||||
offer_public_list,
|
||||
@ -14,6 +15,7 @@ __all__ = [
|
||||
"PRODUCT_OFFERS",
|
||||
"access_snapshot",
|
||||
"apply_offer_key",
|
||||
"is_audit_book_id",
|
||||
"is_book_free",
|
||||
"is_free_unlock",
|
||||
"match_offer",
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
"""虚拟支付道具目录:免费 + 微信已发布道具。
|
||||
"""虚拟支付道具目录(运营 SoT)。
|
||||
|
||||
已发布(MP):
|
||||
tiktok / youtube / nomad / svip / ebook_unlock_default
|
||||
价格单位:分;道具 ID 与名称字段一致(ebook 道具 ID 为 ebook_unlock_default)。
|
||||
档位面向付费用户:名称是货架文案,product_id 是微信侧支付 SKU。
|
||||
价格单位:分。微信 MP「道具名称」≤10 字、「备注」≤50 字不对外。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -19,87 +18,133 @@ PRODUCT_OFFERS: list[dict[str, Any]] = [
|
||||
"unlock_percent": 100,
|
||||
"free": True,
|
||||
"image": "",
|
||||
"remark": "免费加入,不拉起支付",
|
||||
"remark": "全书可读,不拉起支付",
|
||||
},
|
||||
{
|
||||
"key": "tiktok",
|
||||
"label": "tiktok",
|
||||
"name": "tiktok",
|
||||
"product_id": "tiktok",
|
||||
"price_fen": 8800,
|
||||
"key": "yen29",
|
||||
"label": "轻享",
|
||||
"name": "轻享全书",
|
||||
"product_id": "nomad_lite",
|
||||
"price_fen": 2900,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/tiktok.png",
|
||||
"remark": "已发布 · ¥88",
|
||||
},
|
||||
{
|
||||
"key": "youtube",
|
||||
"label": "youtube",
|
||||
"name": "youtube",
|
||||
"product_id": "youtube",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/youtube.png",
|
||||
"remark": "已发布 · ¥188",
|
||||
"image": "props/nomad_lite.png",
|
||||
"remark": "入门价·首次解锁单本推荐",
|
||||
},
|
||||
{
|
||||
"key": "nomad",
|
||||
"label": "nomad",
|
||||
"name": "nomad",
|
||||
"label": "漫游",
|
||||
"name": "漫游全书",
|
||||
"product_id": "nomad",
|
||||
"price_fen": 4900,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad.png",
|
||||
"remark": "已发布 · ¥49",
|
||||
"remark": "标准漫游档·性价比主推",
|
||||
},
|
||||
{
|
||||
"key": "svip",
|
||||
"label": "svip",
|
||||
"name": "svip",
|
||||
"product_id": "svip",
|
||||
"price_fen": 99800,
|
||||
"key": "tiktok",
|
||||
"label": "短视频",
|
||||
"name": "短视频全书",
|
||||
"product_id": "tiktok",
|
||||
"price_fen": 8800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/svip.png",
|
||||
"remark": "已发布 · ¥998",
|
||||
"image": "props/tiktok.png",
|
||||
"remark": "短视频向专题全书",
|
||||
},
|
||||
{
|
||||
"key": "youtube",
|
||||
"label": "长视频",
|
||||
"name": "长视频全书",
|
||||
"product_id": "youtube",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/youtube.png",
|
||||
"remark": "长视频向·默认推荐档",
|
||||
},
|
||||
{
|
||||
"key": "ebook",
|
||||
"label": "ebook",
|
||||
"name": "ebook",
|
||||
"label": "经典",
|
||||
"name": "经典全书",
|
||||
"product_id": "ebook_unlock_default",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/ebook.png",
|
||||
"remark": "已发布 · ¥188 · 旧默认道具",
|
||||
"remark": "历史默认档·兼容旧订单",
|
||||
},
|
||||
{
|
||||
"key": "yen298",
|
||||
"label": "进阶",
|
||||
"name": "进阶全书",
|
||||
"product_id": "nomad_plus",
|
||||
"price_fen": 29800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad_plus.png",
|
||||
"remark": "进阶价·高价值小册",
|
||||
},
|
||||
{
|
||||
"key": "yen588",
|
||||
"label": "精英",
|
||||
"name": "精英全书",
|
||||
"product_id": "nomad_pro",
|
||||
"price_fen": 58800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad_pro.png",
|
||||
"remark": "精英价·深度专题册",
|
||||
},
|
||||
{
|
||||
"key": "svip",
|
||||
"label": "超级会员",
|
||||
"name": "超级会员",
|
||||
"product_id": "svip",
|
||||
"price_fen": 99800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/svip.png",
|
||||
"remark": "旗舰会员·最高权益档",
|
||||
},
|
||||
{
|
||||
"key": "test",
|
||||
"label": "test",
|
||||
"name": "test",
|
||||
"product_id": "test",
|
||||
"price_fen": 100, # ¥1.00 测试
|
||||
"label": "联调",
|
||||
"name": "联调占位",
|
||||
"product_id": "pay_test",
|
||||
"price_fen": 100,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/test.png",
|
||||
"remark": "测试道具 · ¥1 · 需在微信 MP 发布",
|
||||
"image": "props/pay_test.png",
|
||||
"remark": "仅内部联调·禁止对用户上架",
|
||||
},
|
||||
]
|
||||
|
||||
# 旧书 / 旧微信草稿 id → 现网 key
|
||||
_LEGACY_PRODUCT_IDS = {
|
||||
"298": "tiktok",
|
||||
"29": "yen29",
|
||||
"298": "yen298",
|
||||
"588": "yen588",
|
||||
"test": "test",
|
||||
"188": "youtube",
|
||||
"49": "nomad",
|
||||
"998": "svip",
|
||||
}
|
||||
|
||||
|
||||
def is_audit_book_id(book_id: str | None) -> bool:
|
||||
"""提审书 id:永远免费,且与正式付费 unlock / VIP 隔离。"""
|
||||
bid = (book_id or "").strip()
|
||||
return bid == "audit" or bid.startswith("audit")
|
||||
|
||||
|
||||
def is_book_free(book: dict[str, Any] | None) -> bool:
|
||||
if not book:
|
||||
return False
|
||||
# 提审书强制免费:禁止运营误配付费后与正式书共用解锁态
|
||||
if is_audit_book_id(str(book.get("id") or "")):
|
||||
return True
|
||||
return int(book.get("unlock_percent") or 0) >= 100
|
||||
|
||||
|
||||
@ -107,12 +152,18 @@ 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:
|
||||
if offer["product_id"] == pid or offer["key"] == pid:
|
||||
return offer
|
||||
mapped = _LEGACY_PRODUCT_IDS.get(pid, pid)
|
||||
if mapped != pid:
|
||||
for offer in PRODUCT_OFFERS:
|
||||
if offer["free"]:
|
||||
continue
|
||||
if offer["key"] == mapped or offer["product_id"] == mapped:
|
||||
return offer
|
||||
price = int((book or {}).get("price_fen") or 0)
|
||||
return {
|
||||
"key": "custom",
|
||||
@ -133,7 +184,7 @@ def apply_offer_key(key: str, current_unlock_percent: int | None = None) -> dict
|
||||
(
|
||||
o
|
||||
for o in PRODUCT_OFFERS
|
||||
if o["key"] == key or o["product_id"] == key or o["name"] == key
|
||||
if o["key"] == key or o["product_id"] == key or o["name"] == key or o["label"] == key
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
@ -7,7 +7,13 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.security import create_admin_token, require_admin
|
||||
from ebook_svc.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
|
||||
from ebook_svc.domains.books import (
|
||||
apply_offer_key,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
match_offer,
|
||||
offer_public_list,
|
||||
)
|
||||
from ebook_svc.schemas.admin import (
|
||||
AdminLoginBody,
|
||||
BookCreateBody,
|
||||
@ -121,16 +127,27 @@ async def admin_delete_book(book_id: str, _: str = Depends(require_admin)):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
_BOOK_SHELL_TITLES = {
|
||||
"audit": ("数字游民·提审版", "微信提审专用 · 与正式会员书无关"),
|
||||
"nomad": ("数字游民", "VIP 电子书 · 本册独立试读/付费"),
|
||||
"cloudphone": ("云手机", "VIP 电子书 · 本册独立试读/付费"),
|
||||
"default": ("Youtube运营笔记", "专属小册 · 本册独立试读/付费"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/books/{book_id}")
|
||||
async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||
book = store.get_book(book_id)
|
||||
# 审核备用书等:首次打开自动建壳,避免 404
|
||||
# 审核备用书 / VIP 电子书付费壳:首次打开自动建壳(每本独立,互不影响)
|
||||
if not book:
|
||||
try:
|
||||
title, subtitle = _BOOK_SHELL_TITLES.get(
|
||||
book_id, (book_id, "本册独立试读/付费壳")
|
||||
)
|
||||
book = store.ensure_book(
|
||||
book_id,
|
||||
title="数字游民·提审版" if book_id == "audit" else book_id,
|
||||
subtitle="微信提审专用 · 与正式会员书无关",
|
||||
title=title,
|
||||
subtitle=subtitle,
|
||||
free=True,
|
||||
)
|
||||
except Exception:
|
||||
@ -138,13 +155,26 @@ async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
offer = match_offer(book)
|
||||
return {**book, "offer_key": offer["key"], "is_free": is_book_free(book)}
|
||||
return {
|
||||
**book,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(book),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/books/{book_id}")
|
||||
async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(require_admin)):
|
||||
patch = body.model_dump(exclude_none=True)
|
||||
offer_key = patch.pop("offer_key", None)
|
||||
# 提审书永远免费,禁止改成付费方案以免与正式书数据串台
|
||||
if is_audit_book_id(book_id):
|
||||
if offer_key and offer_key != "free":
|
||||
raise HTTPException(400, "提审书默认免费,不可配置付费方案")
|
||||
patch["unlock_percent"] = 100
|
||||
patch["price_fen"] = 0
|
||||
patch["product_id"] = ""
|
||||
offer_key = "free"
|
||||
try:
|
||||
if offer_key:
|
||||
book = store.get_book(book_id)
|
||||
@ -159,8 +189,20 @@ async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(requ
|
||||
await pb.upsert_book(book)
|
||||
except Exception:
|
||||
pass
|
||||
if offer_key or any(k in patch for k in ("product_id", "price_fen", "unlock_percent")):
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id, free=is_book_free(book))
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
return {**book, "offer_key": offer["key"], "is_free": is_book_free(book)}
|
||||
return {
|
||||
**book,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(book),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/books/{book_id}/offer")
|
||||
@ -170,9 +212,13 @@ async def admin_apply_offer(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
if is_audit_book_id(book_id) and body.offer_key != "free":
|
||||
raise HTTPException(400, "提审书默认免费,不可配置付费方案")
|
||||
try:
|
||||
keep = book.get("unlock_percent") if body.keep_preview_percent else None
|
||||
patch = apply_offer_key(body.offer_key, keep)
|
||||
if is_audit_book_id(book_id):
|
||||
patch = apply_offer_key("free", None)
|
||||
updated = store.update_book(book_id, patch)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
@ -180,8 +226,19 @@ async def admin_apply_offer(
|
||||
await pb.upsert_book(updated)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id, free=is_book_free(updated))
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(updated)
|
||||
return {**updated, "offer_key": offer["key"], "is_free": is_book_free(updated)}
|
||||
return {
|
||||
**updated,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(updated),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/books/{book_id}/markdown")
|
||||
@ -261,6 +318,8 @@ async def admin_order_status(
|
||||
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
||||
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
if is_audit_book_id(book_id):
|
||||
raise HTTPException(400, "提审书默认免费,无需手动解锁")
|
||||
if book_id != VIP_BOOK_ID:
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
|
||||
@ -3,7 +3,14 @@ from __future__ import annotations
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
|
||||
from ebook_svc.core.deps import get_current_openid, get_optional_openid
|
||||
from ebook_svc.domains.books import access_snapshot, is_free_unlock, public_book, truncate_by_percent
|
||||
from ebook_svc.domains.books import (
|
||||
access_snapshot,
|
||||
is_audit_book_id,
|
||||
is_book_free,
|
||||
is_free_unlock,
|
||||
public_book,
|
||||
truncate_by_percent,
|
||||
)
|
||||
from ebook_svc.services.store import store
|
||||
|
||||
router = APIRouter(prefix="/books", tags=["books"])
|
||||
@ -19,6 +26,9 @@ def _no_store(resp: Response) -> None:
|
||||
|
||||
|
||||
def _book_unlocked(openid: str, book_id: str, *, free: bool) -> bool:
|
||||
# 提审书:只按免费放行,绝不读正式 unlocks / __vip__
|
||||
if is_audit_book_id(book_id):
|
||||
return True
|
||||
if free:
|
||||
return True
|
||||
if store.is_unlocked(openid, book_id):
|
||||
@ -28,6 +38,12 @@ def _book_unlocked(openid: str, book_id: str, *, free: bool) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _book_is_free(book: dict, book_id: str) -> bool:
|
||||
if is_audit_book_id(book_id):
|
||||
return True
|
||||
return is_book_free(book) or is_free_unlock(book.get("unlock_percent"))
|
||||
|
||||
|
||||
@router.get("/{book_id}")
|
||||
async def get_book(book_id: str, response: Response):
|
||||
_no_store(response)
|
||||
@ -48,7 +64,7 @@ async def book_access(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
free = _book_is_free(book, book_id)
|
||||
unlocked = _book_unlocked(openid, book_id, free=free)
|
||||
return access_snapshot(book, openid=openid, unlocked=unlocked)
|
||||
|
||||
@ -63,7 +79,7 @@ async def read_book(
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
free = _book_is_free(book, book_id)
|
||||
# 付费书必须登录;免费/提审书可匿名全文
|
||||
if not free and not openid:
|
||||
raise HTTPException(401, "未登录")
|
||||
|
||||
@ -11,14 +11,14 @@ from pydantic import BaseModel, Field
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.core.rate_limit import rate_limit
|
||||
from ebook_svc.domains.books import is_book_free
|
||||
from ebook_svc.domains.books import is_audit_book_id, is_book_free
|
||||
from ebook_svc.domains.books.products import PRODUCT_OFFERS
|
||||
from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.social_join_config import SOCIAL_JOIN_BOOK_ID, read_social_join_config
|
||||
from ebook_svc.services.vip_config import read_vip_config
|
||||
from ebook_svc.services.wxpay import build_sign_data, calc_pay_sig, calc_signature, query_order
|
||||
from ebook_svc.services.wxpay import active_wx_app_key, build_sign_data, calc_pay_sig, calc_signature, query_order
|
||||
|
||||
router = APIRouter(prefix="/pay", tags=["pay"])
|
||||
|
||||
@ -117,7 +117,7 @@ def _build_vip_order_payload(openid: str) -> dict[str, Any]:
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, active_wx_app_key())
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
return {
|
||||
"signData": sign_data,
|
||||
@ -216,7 +216,7 @@ def _build_social_join_order_payload(openid: str) -> dict[str, Any]:
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, active_wx_app_key())
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
return {
|
||||
"signData": sign_data,
|
||||
@ -369,7 +369,7 @@ async def create_shop_pay_order(
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, active_wx_app_key())
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
return {
|
||||
"signData": sign_data,
|
||||
@ -388,6 +388,8 @@ async def create_pay_order(
|
||||
body: OrderBody, request: Request, openid: str = Depends(get_current_openid)
|
||||
):
|
||||
rate_limit(request, bucket="pay.order", limit=20, window_sec=60.0)
|
||||
if is_audit_book_id(body.book_id):
|
||||
raise HTTPException(400, "提审书默认免费,不可购买")
|
||||
book = store.get_book(body.book_id)
|
||||
if not book:
|
||||
# 兼容旧 VIP 客户端:把 product_id 误当成 book_id 传来 → 走会员单
|
||||
@ -421,14 +423,18 @@ async def create_pay_order(
|
||||
amount_fen=book["price_fen"],
|
||||
attach=attach,
|
||||
)
|
||||
pay_env = int(settings.wx_pay_env) if body.env is None else (1 if int(body.env) == 1 else 0)
|
||||
sign_data = build_sign_data(
|
||||
offer_id=settings.wx_offer_id,
|
||||
product_id=book["product_id"],
|
||||
goods_price=book["price_fen"],
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
env=pay_env,
|
||||
)
|
||||
pay_sig = calc_pay_sig(
|
||||
"requestVirtualPayment", sign_data, active_wx_app_key(env=pay_env)
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
try:
|
||||
from ebook_svc.services.track import ingest_events
|
||||
@ -443,6 +449,7 @@ async def create_pay_order(
|
||||
"book_id": body.book_id,
|
||||
"out_trade_no": out_trade_no,
|
||||
"price_fen": book["price_fen"],
|
||||
"env": pay_env,
|
||||
},
|
||||
"ts": None,
|
||||
}
|
||||
@ -460,6 +467,7 @@ async def create_pay_order(
|
||||
"outTradeNo": out_trade_no,
|
||||
"productId": book["product_id"],
|
||||
"goodsPrice": book["price_fen"],
|
||||
"env": pay_env,
|
||||
"kind": "book",
|
||||
}
|
||||
|
||||
|
||||
50
apps/api/services/ebook_svc/services/books_live.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""小册付费方案变更 → 轻触 remote-config,走现有 WS/SSE/1s 轮询热推。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
|
||||
|
||||
def bump_books_offer_live(book_id: str) -> dict[str, Any]:
|
||||
"""后台切换小册道具后调用:copy.booksOfferRev++ 并 notify。"""
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
raw: dict[str, Any] = {}
|
||||
if path.is_file():
|
||||
try:
|
||||
parsed = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(parsed, dict):
|
||||
raw = parsed
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
out = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||
copy = dict(out.get("copy") or {})
|
||||
try:
|
||||
rev = int(copy.get("booksOfferRev") or 0) + 1
|
||||
except Exception:
|
||||
rev = 1
|
||||
copy["booksOfferRev"] = rev
|
||||
copy["booksOfferBookId"] = str(book_id or "").strip()
|
||||
out["copy"] = copy
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
from ebook_svc.services.config_live import notify_config_written
|
||||
|
||||
notify_config_written(out)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"booksOfferRev": rev,
|
||||
"booksOfferBookId": copy["booksOfferBookId"],
|
||||
"version": out["version"],
|
||||
}
|
||||
@ -103,10 +103,54 @@ class Store:
|
||||
("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"),
|
||||
("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"),
|
||||
("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"),
|
||||
# 公众号私信 userid(OA openid),与小程序 openid 分离
|
||||
("oa_userid", "ALTER TABLE users ADD COLUMN oa_userid TEXT"),
|
||||
("oa_bound_at", "ALTER TABLE users ADD COLUMN oa_bound_at REAL"),
|
||||
# 绑定发生在哪个微信小程序 AppID(openid 按 AppID 隔离;A/B 互不抢绑)
|
||||
("oa_mp_appid", "ALTER TABLE users ADD COLUMN oa_mp_appid TEXT"),
|
||||
]
|
||||
for name, sql in alters:
|
||||
if name not in cols:
|
||||
c.execute(sql)
|
||||
c.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS oa_profiles (
|
||||
userid TEXT PRIMARY KEY,
|
||||
nick TEXT,
|
||||
avatar TEXT,
|
||||
signature TEXT,
|
||||
gender_txt TEXT,
|
||||
region TEXT,
|
||||
follow_since TEXT,
|
||||
remark TEXT,
|
||||
matched_last_msg TEXT,
|
||||
channel_id TEXT,
|
||||
mp_openid TEXT,
|
||||
mp_appid TEXT,
|
||||
raw_json TEXT,
|
||||
created_at REAL,
|
||||
updated_at REAL
|
||||
)
|
||||
"""
|
||||
)
|
||||
oa_prof_cols = {r[1] for r in c.execute("PRAGMA table_info(oa_profiles)").fetchall()}
|
||||
if "mp_appid" not in oa_prof_cols:
|
||||
c.execute("ALTER TABLE oa_profiles ADD COLUMN mp_appid TEXT")
|
||||
c.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_oa_profiles_updated ON oa_profiles(updated_at DESC)"
|
||||
)
|
||||
c.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_users_oa_userid ON users(oa_userid)"
|
||||
)
|
||||
# 同一微信小程序 AppID 内:一个 OA userid 只能绑一个 mp openid
|
||||
c.execute(
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_oa_userid_appid_unique
|
||||
ON users(oa_userid, oa_mp_appid)
|
||||
WHERE oa_userid IS NOT NULL AND oa_userid != ''
|
||||
AND oa_mp_appid IS NOT NULL AND oa_mp_appid != ''
|
||||
"""
|
||||
)
|
||||
unlock_cols = {r[1] for r in c.execute("PRAGMA table_info(unlocks)").fetchall()}
|
||||
if "source" not in unlock_cols:
|
||||
c.execute("ALTER TABLE unlocks ADD COLUMN source TEXT")
|
||||
@ -293,6 +337,12 @@ class Store:
|
||||
raise ValueError("book_id required")
|
||||
existing = self.get_book(bid)
|
||||
if existing:
|
||||
# 提审书若被误配成付费,强制拉回免费,避免与正式书共用付费态
|
||||
if free and int(existing.get("unlock_percent") or 0) < 100:
|
||||
return self.update_book(
|
||||
bid,
|
||||
{"unlock_percent": 100, "price_fen": 0, "product_id": ""},
|
||||
)
|
||||
return existing
|
||||
now = time.time()
|
||||
chapters = [
|
||||
@ -485,6 +535,416 @@ class Store:
|
||||
)
|
||||
return self.get_user(openid)
|
||||
|
||||
def find_oa_binder(
|
||||
self,
|
||||
oa_userid: str,
|
||||
*,
|
||||
mp_appid: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""同一微信小程序 AppID 下,谁已绑定该公众号 userid。"""
|
||||
oa_userid = (oa_userid or "").strip()
|
||||
if not oa_userid:
|
||||
return None
|
||||
appid = (mp_appid or "").strip()
|
||||
with self.conn() as c:
|
||||
if appid:
|
||||
row = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, oa_mp_appid, oa_bound_at, nickname, avatar_url
|
||||
FROM users
|
||||
WHERE oa_userid=? AND oa_mp_appid=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(oa_userid, appid),
|
||||
).fetchone()
|
||||
else:
|
||||
row = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, oa_mp_appid, oa_bound_at, nickname, avatar_url
|
||||
FROM users
|
||||
WHERE oa_userid=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(oa_userid,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def bind_oa_userid(
|
||||
self,
|
||||
openid: str,
|
||||
oa_userid: str,
|
||||
*,
|
||||
nick: str | None = None,
|
||||
avatar: str | None = None,
|
||||
mp_appid: str | None = None,
|
||||
force: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
"""把公众号 userid 强制绑到「当前微信小程序」的 openid。
|
||||
|
||||
排他范围:同一 mp_appid(小程序 A / B 的 openid 互不干扰)。
|
||||
该 AppID 下若 OA 已被其他 openid 占用 → 抛 ValueError('oa_bound_other')。
|
||||
"""
|
||||
openid = (openid or "").strip()
|
||||
oa_userid = (oa_userid or "").strip()
|
||||
appid = (mp_appid or "").strip()
|
||||
if not openid or not oa_userid:
|
||||
return None
|
||||
if not appid:
|
||||
raise ValueError("oa_mp_appid_required")
|
||||
|
||||
existing = self.find_oa_binder(oa_userid, mp_appid=appid)
|
||||
if existing and (existing.get("openid") or "").strip() != openid:
|
||||
raise ValueError("oa_bound_other")
|
||||
|
||||
me = self.get_user(openid) or {}
|
||||
my_oa = (me.get("oa_userid") or "").strip()
|
||||
my_app = (me.get("oa_mp_appid") or "").strip()
|
||||
|
||||
now = time.time()
|
||||
nick_s = (nick or "").strip()
|
||||
avatar_s = (avatar or "").strip()
|
||||
with self.conn() as c:
|
||||
# 档案侧二次校验(同 AppID)
|
||||
prow = c.execute(
|
||||
"SELECT mp_openid, mp_appid FROM oa_profiles WHERE userid=?",
|
||||
(oa_userid,),
|
||||
).fetchone()
|
||||
if prow:
|
||||
bound_mp = (prow["mp_openid"] or "").strip()
|
||||
bound_app = (prow["mp_appid"] or "").strip()
|
||||
if bound_mp and bound_mp != openid and (not bound_app or bound_app == appid):
|
||||
raise ValueError("oa_bound_other")
|
||||
|
||||
# 本人换绑到新 OA:释放旧 OA(仅本 AppID)
|
||||
if my_oa and my_oa != oa_userid and my_app == appid:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles
|
||||
SET mp_openid=NULL, mp_appid=NULL, updated_at=?
|
||||
WHERE userid=? AND IFNULL(mp_openid,'')=? AND IFNULL(mp_appid,'')=?
|
||||
""",
|
||||
(now, my_oa, openid, appid),
|
||||
)
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET oa_userid=?, oa_bound_at=CASE
|
||||
WHEN IFNULL(oa_userid,'')=? AND IFNULL(oa_mp_appid,'')=? THEN oa_bound_at
|
||||
ELSE ?
|
||||
END,
|
||||
oa_mp_appid=?,
|
||||
updated_at=?,
|
||||
nickname=COALESCE(NULLIF(?, ''), nickname),
|
||||
avatar_url=COALESCE(NULLIF(?, ''), avatar_url)
|
||||
WHERE openid=?
|
||||
""",
|
||||
(
|
||||
oa_userid,
|
||||
oa_userid,
|
||||
appid,
|
||||
now,
|
||||
appid,
|
||||
now,
|
||||
nick_s,
|
||||
avatar_s,
|
||||
openid,
|
||||
),
|
||||
)
|
||||
if prow:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles
|
||||
SET nick=COALESCE(NULLIF(?, ''), nick),
|
||||
avatar=COALESCE(NULLIF(?, ''), avatar),
|
||||
mp_openid=?,
|
||||
mp_appid=?,
|
||||
updated_at=?
|
||||
WHERE userid=?
|
||||
""",
|
||||
(nick_s, avatar_s, openid, appid, now, oa_userid),
|
||||
)
|
||||
else:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO oa_profiles(
|
||||
userid, nick, avatar, mp_openid, mp_appid, created_at, updated_at
|
||||
) VALUES(?,?,?,?,?,?,?)
|
||||
""",
|
||||
(oa_userid, nick_s, avatar_s, openid, appid, now, now),
|
||||
)
|
||||
_ = force
|
||||
return self.get_user(openid)
|
||||
|
||||
def get_oa_profile(self, userid: str) -> dict[str, Any] | None:
|
||||
userid = (userid or "").strip()
|
||||
if not userid:
|
||||
return None
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE userid=?", (userid,)
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def get_oa_profile_by_mp_openid(self, mp_openid: str) -> dict[str, Any] | None:
|
||||
mp = (mp_openid or "").strip()
|
||||
if not mp:
|
||||
return None
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE mp_openid=? ORDER BY updated_at DESC LIMIT 1",
|
||||
(mp,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def list_unlocks_for_openid(self, openid: str, *, limit: int = 12) -> list[dict[str, Any]]:
|
||||
oid = (openid or "").strip()
|
||||
if not oid:
|
||||
return []
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT book_id, unlocked_at, source
|
||||
FROM unlocks WHERE openid=?
|
||||
ORDER BY unlocked_at DESC LIMIT ?
|
||||
""",
|
||||
(oid, max(1, min(int(limit), 40))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def upsert_oa_profile(self, payload: dict[str, Any], *, partial: bool = False) -> dict[str, Any]:
|
||||
userid = str(payload.get("userid") or payload.get("openid") or "").strip()
|
||||
if not userid:
|
||||
raise ValueError("userid required")
|
||||
now = time.time()
|
||||
|
||||
def pick(*keys: str, default: str = "") -> str:
|
||||
for k in keys:
|
||||
if k in payload and payload.get(k) is not None:
|
||||
return str(payload.get(k) or "").strip()
|
||||
return default
|
||||
|
||||
nick = pick("nick", "nickname")
|
||||
avatar = pick("avatar")
|
||||
signature = pick("signature")
|
||||
gender_txt = pick("gender_txt")
|
||||
region = pick("region")
|
||||
follow_since = pick("follow_since")
|
||||
remark = pick("remark")
|
||||
matched_last_msg = pick("matched_last_msg")
|
||||
channel_id = pick("channel_id")
|
||||
mp_openid = pick("mp_openid") or None
|
||||
mp_appid = pick("mp_appid") or None
|
||||
# VIP 同步默认不带 mp_openid:禁止顺带改写绑定
|
||||
touch_mp = ("mp_openid" in payload) or ("mp_appid" in payload)
|
||||
raw = payload.get("raw_json")
|
||||
if raw is None and isinstance(payload.get("raw_contact"), (dict, list)):
|
||||
raw = json.dumps(payload.get("raw_contact"), ensure_ascii=False)
|
||||
elif isinstance(raw, (dict, list)):
|
||||
raw = json.dumps(raw, ensure_ascii=False)
|
||||
raw_s = str(raw) if raw is not None else None
|
||||
|
||||
with self.conn() as c:
|
||||
exist = c.execute(
|
||||
"SELECT * FROM oa_profiles WHERE userid=?", (userid,)
|
||||
).fetchone()
|
||||
if exist:
|
||||
ex = dict(exist)
|
||||
|
||||
def merge(key: str, new_val: str) -> str:
|
||||
if partial and key not in payload and key != "nick" and key != "avatar":
|
||||
# nick/avatar 用别名键
|
||||
aliases = {"nick": ("nick", "nickname"), "avatar": ("avatar",)}
|
||||
if key in aliases and not any(a in payload for a in aliases[key]):
|
||||
return ex.get(key) or ""
|
||||
if partial and not new_val and key not in payload and key not in (
|
||||
"nick",
|
||||
"nickname",
|
||||
"avatar",
|
||||
):
|
||||
return ex.get(key) or ""
|
||||
return new_val if new_val or not partial else (ex.get(key) or "")
|
||||
|
||||
nick_v = nick or (ex.get("nick") or "")
|
||||
avatar_v = avatar or (ex.get("avatar") or "")
|
||||
next_mp = mp_openid if touch_mp else (ex.get("mp_openid") or None)
|
||||
next_app = mp_appid if ("mp_appid" in payload) else (ex.get("mp_appid") or None)
|
||||
if touch_mp and next_mp:
|
||||
# 同 AppID 下不得抢别人已绑的 OA
|
||||
rival = c.execute(
|
||||
"""
|
||||
SELECT openid FROM users
|
||||
WHERE oa_userid=? AND IFNULL(oa_mp_appid,'')=IFNULL(?, '')
|
||||
AND openid!=?
|
||||
LIMIT 1
|
||||
""",
|
||||
(userid, next_app or "", next_mp),
|
||||
).fetchone()
|
||||
if rival:
|
||||
raise ValueError("oa_bound_other")
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE oa_profiles SET
|
||||
nick=?, avatar=?, signature=?, gender_txt=?, region=?,
|
||||
follow_since=?, remark=?, matched_last_msg=?, channel_id=?,
|
||||
mp_openid=?,
|
||||
mp_appid=?,
|
||||
raw_json=COALESCE(?, raw_json),
|
||||
updated_at=?
|
||||
WHERE userid=?
|
||||
""",
|
||||
(
|
||||
nick_v,
|
||||
avatar_v,
|
||||
merge("signature", signature),
|
||||
merge("gender_txt", gender_txt),
|
||||
merge("region", region),
|
||||
merge("follow_since", follow_since),
|
||||
merge("remark", remark),
|
||||
merge("matched_last_msg", matched_last_msg),
|
||||
merge("channel_id", channel_id),
|
||||
next_mp,
|
||||
next_app,
|
||||
raw_s,
|
||||
now,
|
||||
userid,
|
||||
),
|
||||
)
|
||||
mp = next_mp if touch_mp else None
|
||||
app_for_user = next_app
|
||||
else:
|
||||
nick_v, avatar_v = nick, avatar
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO oa_profiles(
|
||||
userid, nick, avatar, signature, gender_txt, region,
|
||||
follow_since, remark, matched_last_msg, channel_id,
|
||||
mp_openid, mp_appid, raw_json, created_at, updated_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
userid,
|
||||
nick,
|
||||
avatar,
|
||||
signature,
|
||||
gender_txt,
|
||||
region,
|
||||
follow_since,
|
||||
remark,
|
||||
matched_last_msg,
|
||||
channel_id,
|
||||
mp_openid if touch_mp else None,
|
||||
mp_appid if touch_mp else None,
|
||||
raw_s,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
mp = mp_openid if touch_mp else None
|
||||
app_for_user = mp_appid if touch_mp else None
|
||||
if mp and touch_mp:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users SET oa_userid=?, oa_bound_at=COALESCE(oa_bound_at, ?),
|
||||
oa_mp_appid=COALESCE(?, oa_mp_appid),
|
||||
nickname=COALESCE(NULLIF(?, ''), nickname),
|
||||
avatar_url=COALESCE(NULLIF(?, ''), avatar_url),
|
||||
updated_at=?
|
||||
WHERE openid=?
|
||||
""",
|
||||
(userid, now, app_for_user, nick_v, avatar_v, now, mp),
|
||||
)
|
||||
return self.get_oa_profile(userid) or {"userid": userid}
|
||||
|
||||
def delete_oa_profile(self, userid: str) -> bool:
|
||||
userid = (userid or "").strip()
|
||||
if not userid:
|
||||
return False
|
||||
with self.conn() as c:
|
||||
cur = c.execute("DELETE FROM oa_profiles WHERE userid=?", (userid,))
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE users SET oa_userid=NULL, oa_bound_at=NULL, oa_mp_appid=NULL, updated_at=?
|
||||
WHERE oa_userid=?
|
||||
""",
|
||||
(time.time(), userid),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
|
||||
def list_oa_profiles(
|
||||
self,
|
||||
*,
|
||||
page: int = 1,
|
||||
limit: int = 50,
|
||||
q: str = "",
|
||||
) -> dict[str, Any]:
|
||||
page = max(1, int(page or 1))
|
||||
limit = max(1, min(int(limit or 50), 200))
|
||||
offset = (page - 1) * limit
|
||||
q = (q or "").strip()
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM oa_profiles ORDER BY updated_at DESC"
|
||||
).fetchall()
|
||||
bound = c.execute(
|
||||
"""
|
||||
SELECT openid, oa_userid, nickname, avatar_url, oa_bound_at, updated_at, status
|
||||
FROM users WHERE oa_userid IS NOT NULL AND oa_userid != ''
|
||||
"""
|
||||
).fetchall()
|
||||
by_id: dict[str, dict[str, Any]] = {}
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
by_id[item["userid"]] = item
|
||||
for b in bound:
|
||||
uid = (b["oa_userid"] or "").strip()
|
||||
if not uid:
|
||||
continue
|
||||
if uid in by_id:
|
||||
if not by_id[uid].get("mp_openid"):
|
||||
by_id[uid]["mp_openid"] = b["openid"]
|
||||
by_id[uid]["mp_status"] = b["status"] or "active"
|
||||
else:
|
||||
by_id[uid] = {
|
||||
"userid": uid,
|
||||
"nick": b["nickname"] or "",
|
||||
"avatar": b["avatar_url"] or "",
|
||||
"signature": "",
|
||||
"gender_txt": "",
|
||||
"region": "",
|
||||
"follow_since": "",
|
||||
"remark": "",
|
||||
"matched_last_msg": "",
|
||||
"channel_id": "",
|
||||
"mp_openid": b["openid"],
|
||||
"raw_json": None,
|
||||
"created_at": b["oa_bound_at"] or b["updated_at"],
|
||||
"updated_at": b["updated_at"],
|
||||
"from_users_only": True,
|
||||
"mp_status": b["status"] or "active",
|
||||
}
|
||||
users = list(by_id.values())
|
||||
if q:
|
||||
ql = q.lower()
|
||||
users = [
|
||||
u
|
||||
for u in users
|
||||
if ql in str(u.get("userid") or "").lower()
|
||||
or ql in str(u.get("nick") or "").lower()
|
||||
or ql in str(u.get("remark") or "").lower()
|
||||
or ql in str(u.get("mp_openid") or "").lower()
|
||||
]
|
||||
users.sort(key=lambda x: -(float(x.get("updated_at") or 0)))
|
||||
total_all = len(users)
|
||||
page_items = users[offset : offset + limit]
|
||||
return {
|
||||
"ok": True,
|
||||
"total": total_all,
|
||||
"page": page,
|
||||
"perPage": limit,
|
||||
"totalPages": max(1, (total_all + limit - 1) // limit) if total_all else 1,
|
||||
"users": page_items,
|
||||
}
|
||||
|
||||
def list_users(self, limit: int = 200, q: str = "") -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
if q.strip():
|
||||
@ -492,10 +952,11 @@ class Store:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT * FROM users
|
||||
WHERE openid LIKE ? OR IFNULL(nickname,'') LIKE ? OR IFNULL(notes,'') LIKE ?
|
||||
WHERE openid LIKE ? OR IFNULL(nickname,'') LIKE ?
|
||||
OR IFNULL(notes,'') LIKE ? OR IFNULL(oa_userid,'') LIKE ?
|
||||
ORDER BY updated_at DESC LIMIT ?
|
||||
""",
|
||||
(like, like, like, limit),
|
||||
(like, like, like, like, limit),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = c.execute(
|
||||
|
||||
@ -10,6 +10,14 @@ import httpx
|
||||
from ebook_svc.config import settings
|
||||
|
||||
|
||||
def active_wx_app_key(*, env: int | None = None) -> str:
|
||||
"""按 WX_PAY_ENV 选用现网 / 沙箱 AppKey。"""
|
||||
use_env = settings.wx_pay_env if env is None else env
|
||||
if int(use_env) == 1:
|
||||
return (settings.wx_sandbox_app_key or settings.wx_app_key or "").strip()
|
||||
return (settings.wx_app_key or "").strip()
|
||||
|
||||
|
||||
def calc_pay_sig(uri: str, post_body: str, appkey: str) -> str:
|
||||
"""uri 不带问号参数。C 端固定 requestVirtualPayment;B 端为 /xpay/* 路径。"""
|
||||
msg = f"{uri}&{post_body}"
|
||||
@ -112,7 +120,7 @@ async def query_order(openid: str, out_trade_no: str) -> dict[str, Any]:
|
||||
"""POST /xpay/query_order,带 pay_sig。"""
|
||||
body_obj = {"openid": openid, "env": settings.wx_pay_env, "order_id": out_trade_no}
|
||||
post_body = json.dumps(body_obj, ensure_ascii=False, separators=(",", ":"))
|
||||
pay_sig = calc_pay_sig("/xpay/query_order", post_body, settings.wx_app_key)
|
||||
pay_sig = calc_pay_sig("/xpay/query_order", post_body, active_wx_app_key())
|
||||
token = await get_access_token()
|
||||
url = f"https://api.weixin.qq.com/xpay/query_order?access_token={token}&pay_sig={pay_sig}"
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
|
||||
28
apps/hackrobot/BACKEND_API_ROUTES.txt
Normal file
@ -0,0 +1,28 @@
|
||||
/www/wwwroot/nomadvip/app/api/auth/email/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/auth/link-email/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/auth/logout/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/auth/me/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/auth/store-email-link/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/auth/sync-session/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/analytics/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/config/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/control/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/leads/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/login/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/members/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/ntfy/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/orders/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/overview/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/ops/users/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/pay/confirm/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/pay/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/pay/status/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/probe-sink/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/promo/recognize-discount/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/check-by-email/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/check-by-user/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/check/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/_helpers.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/identity-diagnose/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/linked-email/route.ts
|
||||
/www/wwwroot/nomadvip/app/api/vip/wechat-profile/route.ts
|
||||
45
apps/hackrobot/README.md
Normal file
@ -0,0 +1,45 @@
|
||||
# apps/hackrobot — 异度星球 VIP(与 Nomadro 隔离)
|
||||
|
||||
**域名写死,禁止与 Nomadro 后台混淆。**
|
||||
|
||||
## 目录 ↔ 线上
|
||||
|
||||
| 线上 | 端口 | 本地 |
|
||||
|---|---|---|
|
||||
| [vip.hackrobot.cn](https://vip.hackrobot.cn/) Next(含 `app/api` 后端) | `:4007` | `vip/` ← `/www/wwwroot/nomadvip` |
|
||||
| [admin.hackrobot.cn](https://admin.hackrobot.cn/) 运营台 SPA | nginx 静态 | `admin-site/` |
|
||||
| LIVE / 拉黑 API(nomadmini) | `:8010` | `nomadmini/` ← `/opt/nomadmini` |
|
||||
| 支付后端 payjsapi | (pay 回调) | `payjsapi/` ← `/www/wwwroot/payjsapi` |
|
||||
| 埋点 vip-track | `:4011` | `vip-track/` ← `/opt/vip-track` |
|
||||
| PocketBase | `:8090` | `pocketbase/`(`data.db` + schema,不含 storage 大文件) |
|
||||
|
||||
`apps/admin` = **admin.nomadro.cn**,**禁止**部署到 `admin.hackrobot.cn`。
|
||||
|
||||
VIP API 路由清单:`BACKEND_API_ROUTES.txt`(ops / pay / auth / vip)。
|
||||
|
||||
## 同步(线上 → 本地)
|
||||
|
||||
```bash
|
||||
# 全栈(前台 + 运营台 + 后端)
|
||||
python apps/hackrobot/deploy/pull_from_129.py
|
||||
python apps/hackrobot/deploy/pull_backends_from_129.py
|
||||
```
|
||||
|
||||
不含 `node_modules` / `.next` / 真实 `.env`。
|
||||
|
||||
## 发版(本地 → 线上,强制先备份)
|
||||
|
||||
```bash
|
||||
python apps/hackrobot/deploy/deploy_admin_site.py
|
||||
python apps/hackrobot/deploy/deploy_vip.py # 源码;加 --build 才编译重启
|
||||
python apps/hackrobot/deploy/deploy_nomadmini.py
|
||||
python apps/hackrobot/deploy/deploy_payjsapi.py
|
||||
```
|
||||
|
||||
快照:`/opt/hackrobot-backup/snapshots/`(含 admin / vip / nomadmini / payjsapi / pb)。
|
||||
|
||||
## 安装服务器备份钩子(一次性)
|
||||
|
||||
```bash
|
||||
python apps/hackrobot/deploy/install_server_backup.py
|
||||
```
|
||||
28
apps/hackrobot/SYNC_MANIFEST.json
Normal file
@ -0,0 +1,28 @@
|
||||
{
|
||||
"host": "129.204.21.129",
|
||||
"pulled_at": "2026-11-22T10:41:47+0800",
|
||||
"files": {
|
||||
"vip-track.tgz": 543680,
|
||||
"admin-site.tgz": 145661,
|
||||
"vip-src.tgz": 497514,
|
||||
"nomadmini.tgz": 713510,
|
||||
"nginx-ref.tgz": 3469
|
||||
},
|
||||
"notes": {
|
||||
"vip": "/www/wwwroot/nomadvip → next :4007 = vip.hackrobot.cn",
|
||||
"admin": "/www/wwwroot/admin.hackrobot.cn static SPA",
|
||||
"nomadmini": "/opt/nomadmini → :8010 live ops",
|
||||
"vip_track": "/opt/vip-track → :4011"
|
||||
},
|
||||
"backends": {
|
||||
"pulled_at": "2026-11-22T10:53:18+0800",
|
||||
"files": {
|
||||
"vip-track.tgz": 19846,
|
||||
"pocketbase-schema.tgz": 500228,
|
||||
"vip-api.tgz": 44933,
|
||||
"payjsapi.tgz": 200046,
|
||||
"nomadmini.tgz": 562567
|
||||
}
|
||||
},
|
||||
"backends_pulled_at": "2026-11-22T10:53:18+0800"
|
||||
}
|
||||
149
apps/hackrobot/admin-site/admin-leads-online.js
Normal file
@ -0,0 +1,149 @@
|
||||
/*! admin-leads-online.js — animate 在线 column on /leads without touching SPA bundle */
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.__adminLeadsOnlineBooted) return;
|
||||
window.__adminLeadsOnlineBooted = true;
|
||||
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
|
||||
|
||||
var TTL_MS = 120000;
|
||||
var STYLE_ID = "admin-leads-online-style";
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
var s = document.createElement("style");
|
||||
s.id = STYLE_ID;
|
||||
s.textContent =
|
||||
"@keyframes comOnlinePulse{0%{box-shadow:0 0 0 0 rgba(52,211,153,.55)}70%{box-shadow:0 0 0 8px rgba(52,211,153,0)}100%{box-shadow:0 0 0 0 rgba(52,211,153,0)}}" +
|
||||
"@keyframes comOnlineGlow{0%,100%{filter:none}50%{filter:drop-shadow(0 0 6px rgba(52,211,153,.4))}}" +
|
||||
".alo-cell{display:inline-flex;flex-direction:column;align-items:flex-start;gap:4px;min-width:64px}" +
|
||||
".alo-badge{display:inline-flex;align-items:center;gap:6px;padding:3px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.1em}" +
|
||||
".alo-badge.on{color:#6ee7b7;border:1px solid rgba(52,211,153,.4);background:rgba(52,211,153,.08);animation:comOnlineGlow 2s ease-in-out infinite}" +
|
||||
".alo-badge.on i{width:7px;height:7px;border-radius:50%;background:#34d399;animation:comOnlinePulse 1.6s ease-out infinite}" +
|
||||
".alo-badge.off{color:#a8a29e;border:1px solid rgba(168,162,158,.25);background:rgba(255,255,255,.03)}" +
|
||||
".alo-time{font-size:12px;color:#a8a29e}" +
|
||||
".alo-badge.on + .alo-time,.alo-cell.is-live .alo-time{color:#6ee7b7;font-weight:600}" +
|
||||
"th.alo-th-live{color:#6ee7b7}" +
|
||||
"tr.alo-row-live td:first-child{animation:comOnlineGlow 2.4s ease-in-out infinite}";
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
function parseTs(text, title) {
|
||||
// title often full locale string; text is relative like 刚刚 / 3分钟前
|
||||
if (title && title !== "—") {
|
||||
var d = Date.parse(title.replace(/年|月/g, "/").replace(/日/g, " "));
|
||||
if (!Number.isNaN(d)) return d;
|
||||
d = Date.parse(title);
|
||||
if (!Number.isNaN(d)) return d;
|
||||
}
|
||||
var t = (text || "").trim();
|
||||
if (!t || t === "—") return 0;
|
||||
if (t === "刚刚") return Date.now();
|
||||
var m = t.match(/^(\d+)\s*秒/);
|
||||
if (m) return Date.now() - Number(m[1]) * 1000;
|
||||
m = t.match(/^(\d+)\s*分钟/);
|
||||
if (m) return Date.now() - Number(m[1]) * 60000;
|
||||
m = t.match(/^(\d+)\s*小时/);
|
||||
if (m) return Date.now() - Number(m[1]) * 3600000;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function paintCell(td, live) {
|
||||
if (!td) return;
|
||||
if (td.getAttribute("data-alo") === "1") {
|
||||
var badge = td.querySelector(".alo-badge");
|
||||
var time = td.querySelector(".alo-time");
|
||||
if (badge) {
|
||||
badge.className = "alo-badge " + (live ? "on" : "off");
|
||||
badge.innerHTML = live ? "<i></i>在线" : "离线";
|
||||
}
|
||||
td.classList.toggle("is-live", !!live);
|
||||
var tr = td.closest("tr");
|
||||
if (tr) tr.classList.toggle("alo-row-live", !!live);
|
||||
return;
|
||||
}
|
||||
var rawText = (td.textContent || "").trim();
|
||||
var title = td.getAttribute("title") || "";
|
||||
td.setAttribute("data-alo", "1");
|
||||
td.innerHTML = "";
|
||||
var wrap = document.createElement("div");
|
||||
wrap.className = "alo-cell" + (live ? " is-live" : "");
|
||||
var badge = document.createElement("span");
|
||||
badge.className = "alo-badge " + (live ? "on" : "off");
|
||||
badge.innerHTML = live ? "<i></i>在线" : "离线";
|
||||
var time = document.createElement("span");
|
||||
time.className = "alo-time";
|
||||
time.textContent = rawText || "—";
|
||||
if (title) time.title = title;
|
||||
wrap.appendChild(badge);
|
||||
wrap.appendChild(time);
|
||||
td.appendChild(wrap);
|
||||
var tr = td.closest("tr");
|
||||
if (tr) tr.classList.toggle("alo-row-live", !!live);
|
||||
}
|
||||
|
||||
function findOnlineColIndex(table) {
|
||||
var ths = table.querySelectorAll("thead th");
|
||||
for (var i = 0; i < ths.length; i++) {
|
||||
var label = (ths[i].textContent || "").trim();
|
||||
if (label === "最近活跃" || label === "在线" || label.indexOf("活跃") >= 0) {
|
||||
ths[i].classList.add("alo-th-live");
|
||||
if (label === "最近活跃") ths[i].textContent = "在线";
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0; // leads list first col
|
||||
}
|
||||
|
||||
function enhance() {
|
||||
if (!location.pathname.replace(/\/$/, "").endsWith("/leads") && location.pathname !== "/leads") {
|
||||
// also allow /leads with query
|
||||
if (location.pathname.replace(/\/+$/, "") !== "/leads") return;
|
||||
}
|
||||
ensureStyle();
|
||||
var tables = document.querySelectorAll("table.com-table");
|
||||
tables.forEach(function (table) {
|
||||
var idx = findOnlineColIndex(table);
|
||||
var rows = table.querySelectorAll("tbody tr");
|
||||
rows.forEach(function (tr) {
|
||||
var tds = tr.querySelectorAll("td");
|
||||
if (!tds.length || idx >= tds.length) return;
|
||||
var td = tds[idx];
|
||||
var title = td.getAttribute("title") || "";
|
||||
var text = td.getAttribute("data-alo") === "1"
|
||||
? (td.querySelector(".alo-time") || {}).textContent || ""
|
||||
: (td.textContent || "").trim();
|
||||
// Prefer title absolute time; if missing, relative text
|
||||
var ts = parseTs(text, title);
|
||||
var live = ts > 0 && Date.now() - ts < TTL_MS;
|
||||
// relative "刚刚" / N分钟
|
||||
if (!ts) {
|
||||
var rel = text;
|
||||
if (td.getAttribute("data-alo") === "1") {
|
||||
rel = (td.querySelector(".alo-time") || {}).textContent || "";
|
||||
}
|
||||
if (rel === "刚刚" || /^\d+\s*秒/.test(rel) || /^[1-2]\s*分钟/.test(rel)) live = true;
|
||||
}
|
||||
paintCell(td, live);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function boot() {
|
||||
ensureStyle();
|
||||
enhance();
|
||||
setInterval(enhance, 5000);
|
||||
var obs = new MutationObserver(function () {
|
||||
enhance();
|
||||
});
|
||||
obs.observe(document.documentElement, { childList: true, subtree: true });
|
||||
window.addEventListener("popstate", function () {
|
||||
setTimeout(enhance, 50);
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
})();
|
||||
275
apps/hackrobot/admin-site/admin-live.js
Normal file
@ -0,0 +1,275 @@
|
||||
/*! admin-live.js — LIVE online + broadcast dock for admin.hackrobot.cn VIP 运营台 */
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.__adminLiveBooted) return;
|
||||
window.__adminLiveBooted = true;
|
||||
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
|
||||
|
||||
var TOKEN_KEY = "vip_ops_token";
|
||||
var API_ONLINE = "/api/admin/live/online";
|
||||
var API_BC = "/api/admin/live/broadcast";
|
||||
var API_STREAM = "/api/admin/live/stream";
|
||||
var POLL_MS = 5000;
|
||||
|
||||
function token() {
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY) || "";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function authHeaders() {
|
||||
var t = token();
|
||||
return t
|
||||
? { Authorization: "Bearer " + t, "Content-Type": "application/json" }
|
||||
: { "Content-Type": "application/json" };
|
||||
}
|
||||
|
||||
function el(tag, attrs, kids) {
|
||||
var n = document.createElement(tag);
|
||||
if (attrs) {
|
||||
Object.keys(attrs).forEach(function (k) {
|
||||
if (k === "style" && typeof attrs[k] === "object") {
|
||||
Object.assign(n.style, attrs[k]);
|
||||
} else if (k === "text") {
|
||||
n.textContent = attrs[k];
|
||||
} else if (k.slice(0, 2) === "on") {
|
||||
n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
|
||||
} else {
|
||||
n.setAttribute(k, attrs[k]);
|
||||
}
|
||||
});
|
||||
}
|
||||
(kids || []).forEach(function (c) {
|
||||
if (c == null) return;
|
||||
n.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
|
||||
});
|
||||
return n;
|
||||
}
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById("admin-live-style")) return;
|
||||
var s = document.createElement("style");
|
||||
s.id = "admin-live-style";
|
||||
s.textContent =
|
||||
"@keyframes alPulse{0%,100%{opacity:1}50%{opacity:.45}}" +
|
||||
"@keyframes alIn{from{opacity:0;transform:translateY(12px) scale(.98)}to{opacity:1;transform:none}}" +
|
||||
"#admin-live-fab{position:fixed;right:18px;bottom:18px;z-index:2147482500;display:flex;align-items:center;gap:8px;padding:12px 16px;min-height:44px;border-radius:999px;border:1px solid rgba(245,158,11,.45);background:linear-gradient(135deg,#1a1408,#0c0c0f 55%,#121016);color:#fbbf24;font:600 13px/1.2 'DM Sans',Syne,system-ui,sans-serif;cursor:pointer;box-shadow:0 12px 40px rgba(0,0,0,.45),0 0 0 1px rgba(245,158,11,.12);backdrop-filter:blur(10px)}" +
|
||||
"#admin-live-fab .dot{width:8px;height:8px;border-radius:50%;background:#22c55e;box-shadow:0 0 10px #22c55e;animation:alPulse 1.6s ease-in-out infinite}" +
|
||||
"#admin-live-fab[data-off=1] .dot{background:#78716c;box-shadow:none;animation:none}" +
|
||||
"#admin-live-panel{position:fixed;right:14px;bottom:72px;z-index:2147482501;width:min(380px,calc(100vw - 28px));max-height:min(72vh,560px);overflow:auto;border-radius:16px;border:1px solid rgba(245,158,11,.28);background:linear-gradient(165deg,#141418 0%,#0c0c0f 60%,#1a1408 100%);color:#e7e5e4;box-shadow:0 24px 60px rgba(0,0,0,.55);animation:alIn .28s ease;font-family:'DM Sans',system-ui,sans-serif;padding:14px}" +
|
||||
"#admin-live-panel h3{margin:0 0 8px;font:700 15px/1.2 Syne,'DM Sans',sans-serif;color:#fbbf24;letter-spacing:.02em}" +
|
||||
"#admin-live-panel .meta{font-size:12px;color:#a8a29e;margin-bottom:10px}" +
|
||||
"#admin-live-panel .list{display:flex;flex-direction:column;gap:6px;margin:0 0 12px;max-height:180px;overflow:auto}" +
|
||||
"#admin-live-panel .row{display:flex;flex-direction:column;gap:2px;padding:8px 10px;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);font-size:12px}" +
|
||||
"#admin-live-panel .row b{color:#fafaf9;font-weight:600}" +
|
||||
"#admin-live-panel .row span{color:#a8a29e}" +
|
||||
"#admin-live-panel label{display:block;font-size:11px;color:#a8a29e;margin:8px 0 4px}" +
|
||||
"#admin-live-panel input,#admin-live-panel textarea,#admin-live-panel select{width:100%;box-sizing:border-box;border-radius:10px;border:1px solid rgba(255,255,255,.1);background:#0a0a0c;color:#f5f5f4;padding:10px 12px;font:400 13px/1.35 inherit;min-height:44px}" +
|
||||
"#admin-live-panel textarea{min-height:72px;resize:vertical}" +
|
||||
"#admin-live-panel .actions{display:flex;gap:8px;margin-top:12px}" +
|
||||
"#admin-live-panel button{flex:1;min-height:44px;border-radius:12px;border:0;font:600 13px/1 inherit;cursor:pointer}" +
|
||||
"#admin-live-panel .send{background:linear-gradient(135deg,#f59e0b,#d97706);color:#111}" +
|
||||
"#admin-live-panel .ghost{background:rgba(255,255,255,.06);color:#e7e5e4}" +
|
||||
"#admin-live-panel .msg{margin-top:8px;font-size:12px;color:#86efac}" +
|
||||
"#admin-live-panel .err{color:#fda4af}" +
|
||||
"#admin-live-panel .empty{font-size:12px;color:#78716c;padding:8px 0}";
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
var state = { open: false, online: [], ok: false, err: "", busy: false };
|
||||
var fab, panel;
|
||||
|
||||
function renderList() {
|
||||
if (!panel) return;
|
||||
var list = panel.querySelector(".list");
|
||||
list.innerHTML = "";
|
||||
if (!state.online.length) {
|
||||
list.appendChild(
|
||||
el("div", { class: "empty", text: state.ok ? "当前无人在线" : "等待连接…" })
|
||||
);
|
||||
return;
|
||||
}
|
||||
state.online.slice(0, 40).forEach(function (u) {
|
||||
var title = u.nick || u.email || u.id || "访客";
|
||||
var sub = [u.page || "/", u.role || "", u.email && u.nick ? u.email : ""]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
list.appendChild(
|
||||
el("div", { class: "row" }, [el("b", { text: title }), el("span", { text: sub })])
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function syncFab() {
|
||||
if (!fab) return;
|
||||
fab.setAttribute("data-off", state.ok ? "0" : "1");
|
||||
fab.querySelector(".lab").textContent = "LIVE · " + state.online.length;
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
var t = token();
|
||||
if (!t) {
|
||||
state.ok = false;
|
||||
state.online = [];
|
||||
syncFab();
|
||||
if (state.open) renderList();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
var res = await fetch(API_ONLINE, { headers: authHeaders(), credentials: "omit" });
|
||||
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||
var data = await res.json();
|
||||
state.online = Array.isArray(data.webOnline) ? data.webOnline : [];
|
||||
state.ok = true;
|
||||
} catch (e) {
|
||||
state.ok = false;
|
||||
}
|
||||
syncFab();
|
||||
if (state.open) renderList();
|
||||
}
|
||||
|
||||
async function sendBroadcast() {
|
||||
if (state.busy || !panel) return;
|
||||
var title = panel.querySelector("[name=title]").value.trim();
|
||||
var body = panel.querySelector("[name=body]").value.trim();
|
||||
var cta = panel.querySelector("[name=cta]").value.trim() || "知道了";
|
||||
var href = panel.querySelector("[name=href]").value.trim();
|
||||
var tone = panel.querySelector("[name=tone]").value || "amber";
|
||||
var msgEl = panel.querySelector(".msg");
|
||||
if (!title) {
|
||||
msgEl.className = "msg err";
|
||||
msgEl.textContent = "请填写标题";
|
||||
return;
|
||||
}
|
||||
state.busy = true;
|
||||
msgEl.className = "msg";
|
||||
msgEl.textContent = "发送中…";
|
||||
try {
|
||||
var res = await fetch(API_BC, {
|
||||
method: "POST",
|
||||
headers: authHeaders(),
|
||||
credentials: "omit",
|
||||
body: JSON.stringify({
|
||||
title: title,
|
||||
body: body,
|
||||
cta: cta,
|
||||
href: href,
|
||||
tone: tone,
|
||||
ttlSec: 90,
|
||||
}),
|
||||
});
|
||||
var data = await res.json().catch(function () {
|
||||
return {};
|
||||
});
|
||||
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
|
||||
msgEl.className = "msg";
|
||||
msgEl.textContent = "已推送到 vip.hackrobot.cn 在线用户";
|
||||
panel.querySelector("[name=title]").value = "";
|
||||
panel.querySelector("[name=body]").value = "";
|
||||
} catch (e) {
|
||||
msgEl.className = "msg err";
|
||||
msgEl.textContent = (e && e.message) || "发送失败";
|
||||
} finally {
|
||||
state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openPanel() {
|
||||
if (panel) {
|
||||
state.open = !state.open;
|
||||
panel.style.display = state.open ? "block" : "none";
|
||||
if (state.open) {
|
||||
renderList();
|
||||
refresh();
|
||||
}
|
||||
return;
|
||||
}
|
||||
panel = el("div", { id: "admin-live-panel" }, [
|
||||
el("h3", { text: "实时在线 · 通知" }),
|
||||
el("div", { class: "meta", text: "vip.hackrobot.cn 访客心跳 · 一键弹窗推送" }),
|
||||
el("div", { class: "list" }),
|
||||
el("label", { text: "标题" }),
|
||||
el("input", { name: "title", placeholder: "例如:限时优惠", maxlength: "80" }),
|
||||
el("label", { text: "正文" }),
|
||||
el("textarea", { name: "body", placeholder: "弹窗内容(可选)", maxlength: "400" }),
|
||||
el("label", { text: "按钮文案" }),
|
||||
el("input", { name: "cta", value: "知道了", maxlength: "32" }),
|
||||
el("label", { text: "跳转链接" }),
|
||||
el("input", { name: "href", value: "https://vip.hackrobot.cn/", maxlength: "300" }),
|
||||
el("label", { text: "色调" }),
|
||||
el("select", { name: "tone" }, [
|
||||
el("option", { value: "amber", text: "琥珀" }),
|
||||
el("option", { value: "mint", text: "薄荷绿" }),
|
||||
el("option", { value: "rose", text: "玫红" }),
|
||||
]),
|
||||
el("div", { class: "actions" }, [
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
type: "button",
|
||||
text: "刷新",
|
||||
onClick: function () {
|
||||
refresh();
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "send",
|
||||
type: "button",
|
||||
text: "推送弹窗",
|
||||
onClick: sendBroadcast,
|
||||
}),
|
||||
]),
|
||||
el("div", { class: "msg" }),
|
||||
]);
|
||||
document.body.appendChild(panel);
|
||||
state.open = true;
|
||||
renderList();
|
||||
}
|
||||
|
||||
function boot() {
|
||||
ensureStyle();
|
||||
fab = el(
|
||||
"button",
|
||||
{
|
||||
id: "admin-live-fab",
|
||||
type: "button",
|
||||
title: "实时在线 / 通知",
|
||||
onClick: openPanel,
|
||||
},
|
||||
[el("span", { class: "dot" }), el("span", { class: "lab", text: "LIVE · 0" })]
|
||||
);
|
||||
document.body.appendChild(fab);
|
||||
refresh();
|
||||
setInterval(refresh, POLL_MS);
|
||||
|
||||
try {
|
||||
var t = token();
|
||||
if (t && window.EventSource) {
|
||||
var es = new EventSource(API_STREAM + "?token=" + encodeURIComponent(t));
|
||||
es.addEventListener("tick", function (ev) {
|
||||
try {
|
||||
var data = JSON.parse(ev.data || "{}");
|
||||
if (Array.isArray(data.webOnline)) {
|
||||
state.online = data.webOnline;
|
||||
state.ok = true;
|
||||
syncFab();
|
||||
if (state.open) renderList();
|
||||
}
|
||||
} catch (e) {}
|
||||
});
|
||||
es.onerror = function () {
|
||||
try {
|
||||
es.close();
|
||||
} catch (e) {}
|
||||
};
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
})();
|
||||
272
apps/hackrobot/admin-site/admin-user-tags.js
Normal file
@ -0,0 +1,272 @@
|
||||
/*! admin-user-tags.js — blacklist/archive tags + identity across VIP ops */
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.__adminUserTagsBooted) return;
|
||||
window.__adminUserTagsBooted = true;
|
||||
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
|
||||
|
||||
var TOKEN_KEY = "vip_ops_token";
|
||||
var STYLE_ID = "admin-user-tags-style";
|
||||
var CACHE_MS = 20000;
|
||||
var state = { blocks: [], archives: [], leads: [], byId: {}, fetchedAt: 0, busy: false };
|
||||
|
||||
function token() {
|
||||
try { return localStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
|
||||
}
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
var s = document.createElement("style");
|
||||
s.id = STYLE_ID;
|
||||
s.textContent =
|
||||
".aut-chip{display:inline-flex;align-items:center;gap:4px;margin-left:6px;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.04em;vertical-align:middle;white-space:nowrap;cursor:help;line-height:1.4}" +
|
||||
".aut-chip-block{color:#fecaca;border:1px solid rgba(248,113,113,.45);background:rgba(239,68,68,.14)}" +
|
||||
".aut-chip-was{color:#fcd34d;border:1px solid rgba(245,158,11,.4);background:rgba(245,158,11,.12)}" +
|
||||
".aut-hint{display:block;font-size:11px;color:#a8a29e;margin-top:2px;line-height:1.35}" +
|
||||
"#admin-live-panel .row .aut-chip{margin-left:0;margin-top:2px}" +
|
||||
"code.aut-marked{outline:1px dashed rgba(245,158,11,.25);outline-offset:2px;border-radius:4px}";
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
function norm(s) { return String(s || "").trim().toLowerCase(); }
|
||||
|
||||
function addKeys(map, key, info) {
|
||||
var k = norm(key);
|
||||
if (!k || k === "-" || k === "—") return;
|
||||
var cur = map[k];
|
||||
if (!cur) { map[k] = info; return; }
|
||||
if (info.status === "blocked" || (info.status === "was" && cur.status !== "blocked")) {
|
||||
map[k] = Object.assign({}, cur, info);
|
||||
}
|
||||
}
|
||||
|
||||
function rebuildIndex() {
|
||||
var map = {};
|
||||
(state.blocks || []).forEach(function (b) {
|
||||
var info = {
|
||||
status: "blocked",
|
||||
reason: b.reason || "",
|
||||
note: b.note || "",
|
||||
kind: b.kind || "user",
|
||||
at: b.createdAt || "",
|
||||
by: b.createdBy || ""
|
||||
};
|
||||
addKeys(map, b.userId, info);
|
||||
(b.aliases || []).forEach(function (a) { addKeys(map, a, info); });
|
||||
});
|
||||
(state.archives || []).forEach(function (a) {
|
||||
var info = {
|
||||
status: "was",
|
||||
reason: a.reason || "",
|
||||
note: a.note || "",
|
||||
kind: a.kind || "user",
|
||||
at: a.createdAt || "",
|
||||
by: a.createdBy || "",
|
||||
unblockedAt: a.unblockedAt || "",
|
||||
unblockedBy: a.unblockedBy || ""
|
||||
};
|
||||
addKeys(map, a.userId, info);
|
||||
(a.aliases || []).forEach(function (x) { addKeys(map, x, info); });
|
||||
});
|
||||
(state.leads || []).forEach(function (u) {
|
||||
var ids = [u.key, u.display, u.email, u.openid, u.userId, u.ip].concat(u.aliases || []);
|
||||
var hit = null;
|
||||
for (var i = 0; i < ids.length; i++) {
|
||||
hit = map[norm(ids[i])];
|
||||
if (hit) break;
|
||||
}
|
||||
if (!hit && u.blocked) hit = { status: "blocked", reason: "线索标记", at: "", by: "" };
|
||||
if (hit) ids.forEach(function (id) { addKeys(map, id, hit); });
|
||||
});
|
||||
state.byId = map;
|
||||
}
|
||||
|
||||
function lookup() {
|
||||
for (var i = 0; i < arguments.length; i++) {
|
||||
var hit = state.byId[norm(arguments[i])];
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findLead() {
|
||||
var ids = [];
|
||||
for (var i = 0; i < arguments.length; i++) {
|
||||
var n = norm(arguments[i]);
|
||||
if (n) ids.push(n);
|
||||
}
|
||||
var leads = state.leads || [];
|
||||
for (var li = 0; li < leads.length; li++) {
|
||||
var u = leads[li];
|
||||
var bag = [u.key, u.display, u.email, u.openid, u.userId, u.ip]
|
||||
.concat(u.aliases || [])
|
||||
.map(norm);
|
||||
for (var j = 0; j < ids.length; j++) {
|
||||
if (ids[j] && bag.indexOf(ids[j]) >= 0) return u;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tipFor(info) {
|
||||
if (!info) return "";
|
||||
var parts = [];
|
||||
if (info.status === "blocked") parts.push("当前拉黑");
|
||||
if (info.status === "was") parts.push("历史拉黑(已解除,须重新付款开通)");
|
||||
if (info.reason) parts.push("原因: " + info.reason);
|
||||
if (info.note) parts.push("备注: " + info.note);
|
||||
if (info.at) parts.push("拉黑: " + info.at);
|
||||
if (info.unblockedAt) parts.push("解除: " + info.unblockedAt);
|
||||
if (info.by) parts.push("操作: " + info.by);
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function chipEl(info) {
|
||||
var span = document.createElement("span");
|
||||
if (info.status === "blocked") {
|
||||
span.className = "aut-chip aut-chip-block";
|
||||
span.textContent = "已拉黑";
|
||||
} else {
|
||||
span.className = "aut-chip aut-chip-was";
|
||||
span.textContent = "曾拉黑";
|
||||
}
|
||||
span.title = tipFor(info);
|
||||
return span;
|
||||
}
|
||||
|
||||
function identityHint(lead) {
|
||||
if (!lead) return null;
|
||||
var bits = [];
|
||||
var nick = null;
|
||||
(lead.aliases || []).forEach(function (a) {
|
||||
if (!a) return;
|
||||
if (/^user\d+$/i.test(a)) return;
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(a)) return;
|
||||
if (/^smw/i.test(a)) return;
|
||||
if (a.length >= 2 && a.length <= 32) nick = nick || a;
|
||||
});
|
||||
if (nick) bits.push("昵称 " + nick);
|
||||
if (lead.email && lead.email !== lead.display) bits.push(lead.email);
|
||||
if (lead.ip) bits.push("IP " + lead.ip);
|
||||
if (!bits.length) return null;
|
||||
var d = document.createElement("span");
|
||||
d.className = "aut-hint";
|
||||
d.textContent = bits.slice(0, 3).join(" · ");
|
||||
d.title = bits.join("\n");
|
||||
return d;
|
||||
}
|
||||
|
||||
function paintNear(node, ids) {
|
||||
if (!node || node.nodeType !== 1) return;
|
||||
var info = lookup.apply(null, ids);
|
||||
var lead = findLead.apply(null, ids);
|
||||
var next = node.nextSibling;
|
||||
while (next && next.nodeType === 1 && next.classList && next.classList.contains("aut-chip")) {
|
||||
var rm = next;
|
||||
next = next.nextSibling;
|
||||
rm.remove();
|
||||
}
|
||||
if (info) {
|
||||
node.classList.add("aut-marked");
|
||||
node.insertAdjacentElement("afterend", chipEl(info));
|
||||
}
|
||||
var host = node.parentElement;
|
||||
if (lead && host && node.tagName === "CODE" && !host.querySelector(":scope > .aut-hint")) {
|
||||
var hint = identityHint(lead);
|
||||
if (hint) host.appendChild(hint);
|
||||
}
|
||||
}
|
||||
|
||||
function enhanceCodes() {
|
||||
document.querySelectorAll("code").forEach(function (code) {
|
||||
if (code.closest("#admin-live-panel")) return;
|
||||
paintNear(code, [(code.textContent || "").trim()]);
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceLivePanel() {
|
||||
var panel = document.getElementById("admin-live-panel");
|
||||
if (!panel) return;
|
||||
panel.querySelectorAll(".row").forEach(function (row) {
|
||||
var b = row.querySelector("b");
|
||||
var span = row.querySelector("span");
|
||||
var ids = [];
|
||||
if (b) ids.push(b.textContent || "");
|
||||
if (span) {
|
||||
String(span.textContent || "").split("·").forEach(function (p) {
|
||||
ids.push(p.trim());
|
||||
});
|
||||
}
|
||||
row.querySelectorAll(".aut-chip, .aut-hint").forEach(function (c) {
|
||||
if (c.parentElement === row) c.remove();
|
||||
});
|
||||
var info = lookup.apply(null, ids);
|
||||
if (info) row.appendChild(chipEl(info));
|
||||
var hint = identityHint(findLead.apply(null, ids));
|
||||
if (hint) row.appendChild(hint);
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshData(force) {
|
||||
var t = token();
|
||||
if (!t) return;
|
||||
if (!force && Date.now() - state.fetchedAt < CACHE_MS) return;
|
||||
if (state.busy) return;
|
||||
state.busy = true;
|
||||
try {
|
||||
var headers = { Authorization: "Bearer " + t };
|
||||
var ctrl = await fetch("/api/ops/control", {
|
||||
headers: headers,
|
||||
credentials: "omit"
|
||||
}).then(function (r) { return r.ok ? r.json() : {}; });
|
||||
state.blocks = ctrl.blocks || [];
|
||||
state.archives = ctrl.archives || [];
|
||||
try {
|
||||
var leads = await fetch("/api/ops/leads?limit=400", {
|
||||
headers: headers,
|
||||
credentials: "omit"
|
||||
}).then(function (r) { return r.ok ? r.json() : {}; });
|
||||
state.leads = leads.users || [];
|
||||
} catch (e) {}
|
||||
rebuildIndex();
|
||||
state.fetchedAt = Date.now();
|
||||
} catch (e) {
|
||||
} finally {
|
||||
state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
var paintTimer = null;
|
||||
function schedulePaint() {
|
||||
if (paintTimer) return;
|
||||
paintTimer = setTimeout(function () {
|
||||
paintTimer = null;
|
||||
try {
|
||||
ensureStyle();
|
||||
enhanceCodes();
|
||||
enhanceLivePanel();
|
||||
} catch (e) {}
|
||||
}, 120);
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
await refreshData(false);
|
||||
schedulePaint();
|
||||
}
|
||||
|
||||
function boot() {
|
||||
ensureStyle();
|
||||
tick();
|
||||
setInterval(tick, 8000);
|
||||
new MutationObserver(function () { schedulePaint(); }).observe(
|
||||
document.documentElement,
|
||||
{ childList: true, subtree: true }
|
||||
);
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
})();
|
||||
786
apps/hackrobot/admin-site/admin-users.js
Normal file
@ -0,0 +1,786 @@
|
||||
/*! admin-users.js — 用户列表 CRUD(表格页) */
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.__adminUsersBooted) return;
|
||||
window.__adminUsersBooted = true;
|
||||
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
|
||||
|
||||
var TOKEN_KEY = "vip_ops_token";
|
||||
var PATH = "/user-list";
|
||||
var API = "https://vip.hackrobot.cn/api/wechat-users";
|
||||
|
||||
function token() {
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY) || "";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function el(tag, attrs, kids) {
|
||||
var n = document.createElement(tag);
|
||||
if (attrs) {
|
||||
Object.keys(attrs).forEach(function (k) {
|
||||
if (k === "style" && typeof attrs[k] === "object") Object.assign(n.style, attrs[k]);
|
||||
else if (k === "text") n.textContent = attrs[k];
|
||||
else if (k === "html") n.innerHTML = attrs[k];
|
||||
else if (k.slice(0, 2) === "on") n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
|
||||
else if (k === "checked") n.checked = !!attrs[k];
|
||||
else if (k === "value") n.value = attrs[k];
|
||||
else n.setAttribute(k, attrs[k]);
|
||||
});
|
||||
}
|
||||
(kids || []).forEach(function (c) {
|
||||
if (c == null) return;
|
||||
n.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
|
||||
});
|
||||
return n;
|
||||
}
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById("admin-users-style")) return;
|
||||
var s = document.createElement("style");
|
||||
s.id = "admin-users-style";
|
||||
s.textContent = [
|
||||
"#admin-users-root{--bg:transparent;--fg:#F8FAFC;--muted:#94A3B8;--card:rgba(27,35,54,.92);--border:#475569;--accent:#22C55E;--danger:#EF4444;--sky:#38BDF8;display:none;color:var(--fg);font:400 14px/1.45 ui-sans-serif,system-ui,sans-serif;width:100%}",
|
||||
"#admin-users-root[data-on='1']{display:block}",
|
||||
"main.com-main.admin-users-active > .com-page-enter{display:none!important}",
|
||||
"#admin-users-root .wrap{max-width:100%;margin:0;padding:4px 0 32px}",
|
||||
"#admin-users-root h1{margin:0 0 6px;font:700 22px/1.2 ui-sans-serif,system-ui,sans-serif}",
|
||||
"#admin-users-root .sub{color:var(--muted);font-size:13px;margin:0 0 14px}",
|
||||
"#admin-users-root .bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:12px}",
|
||||
"#admin-users-root input,#admin-users-root select,#admin-users-root textarea{min-height:44px;border-radius:10px;border:1px solid var(--border);background:#121826;color:var(--fg);padding:10px 12px;font:inherit}",
|
||||
"#admin-users-root input[type=search]{flex:1;min-width:200px}",
|
||||
"#admin-users-root textarea{min-height:88px;resize:vertical;width:100%}",
|
||||
"#admin-users-root button,.btn{min-height:40px;border-radius:10px;border:0;padding:0 14px;font:600 13px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer;transition:opacity .15s}",
|
||||
"#admin-users-root button:hover,.btn:hover{opacity:.92}",
|
||||
"#admin-users-root button:focus-visible,.btn:focus-visible{outline:2px solid #fff;outline-offset:2px}",
|
||||
"#admin-users-root .primary{background:var(--accent);color:#0F172A}",
|
||||
"#admin-users-root .sky{background:var(--sky);color:#0F172A}",
|
||||
"#admin-users-root .ghost{background:rgba(255,255,255,.08);color:var(--fg)}",
|
||||
"#admin-users-root .danger{background:rgba(239,68,68,.2);color:#FECACA}",
|
||||
"#admin-users-root .meta{font-size:12px;color:var(--muted);margin:8px 0 12px}",
|
||||
"#admin-users-root .err{color:#FDA4AF;font-size:13px;margin:8px 0}",
|
||||
"#admin-users-root .ok{color:#86EFAC;font-size:13px;margin:8px 0}",
|
||||
"#admin-users-root .table-wrap{overflow:auto;border:1px solid var(--border);border-radius:14px;background:var(--card)}",
|
||||
"#admin-users-root table{width:100%;border-collapse:collapse;min-width:980px}",
|
||||
"#admin-users-root th,#admin-users-root td{padding:10px 12px;text-align:left;border-bottom:1px solid rgba(71,85,105,.55);vertical-align:top}",
|
||||
"#admin-users-root th{font-size:12px;color:var(--muted);font-weight:600;position:sticky;top:0;background:#171f33;z-index:1}",
|
||||
"#admin-users-root tr:hover td{background:rgba(255,255,255,.03)}",
|
||||
"#admin-users-root .av{width:40px;height:40px;border-radius:999px;object-fit:cover;background:#0b1220;display:block}",
|
||||
"#admin-users-root .av.ph{width:40px;height:40px;border-radius:999px;display:flex;align-items:center;justify-content:center;background:#0b1220;color:var(--muted);font-size:14px}",
|
||||
"#admin-users-root .nick{font-weight:600}",
|
||||
"#admin-users-root .mono{font:12px/1.4 ui-monospace,Consolas,monospace;color:var(--sky);word-break:break-all}",
|
||||
"#admin-users-root .sig{font-size:12px;color:#CBD5E1;max-width:220px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}",
|
||||
"#admin-users-root .chip{display:inline-block;font-size:11px;padding:2px 7px;border-radius:999px;background:rgba(56,189,248,.14);color:#7DD3FC;margin-right:4px}",
|
||||
"#admin-users-root .ops{display:flex;flex-wrap:wrap;gap:6px}",
|
||||
"#admin-users-root .ops button{min-height:32px;padding:0 10px;font-size:12px}",
|
||||
"#admin-users-root .pager{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}",
|
||||
"#admin-users-root .modal-mask{position:fixed;inset:0;background:rgba(2,6,23,.72);display:flex;align-items:center;justify-content:center;padding:16px;z-index:2147483000}",
|
||||
"#admin-users-root .modal{width:min(560px,100%);max-height:90vh;overflow:auto;background:#121826;border:1px solid var(--border);border-radius:16px;padding:18px}",
|
||||
"#admin-users-root .modal h2{margin:0 0 12px;font-size:18px}",
|
||||
"#admin-users-root .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}",
|
||||
"#admin-users-root .form-grid .full{grid-column:1 / -1}",
|
||||
"#admin-users-root label{display:block;font-size:12px;color:var(--muted);margin-bottom:4px}",
|
||||
"#admin-users-root .modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}",
|
||||
"@media (max-width:720px){#admin-users-root .form-grid{grid-template-columns:1fr}}",
|
||||
"a.admin-users-nav.com-nav-link{display:flex!important}",
|
||||
].join("");
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
var state = {
|
||||
users: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
perPage: 50,
|
||||
totalPages: 1,
|
||||
q: "",
|
||||
busy: false,
|
||||
err: "",
|
||||
msg: "",
|
||||
selected: {},
|
||||
modal: null, // {mode:'create'|'edit', user:{}}
|
||||
};
|
||||
|
||||
function authHeaders() {
|
||||
return { Authorization: "Bearer " + token(), Accept: "application/json", "Content-Type": "application/json" };
|
||||
}
|
||||
|
||||
async function api(method, path, body) {
|
||||
var res = await fetch(API + (path || ""), {
|
||||
method: method || "GET",
|
||||
headers: authHeaders(),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
var data = await res.json().catch(function () {
|
||||
return {};
|
||||
});
|
||||
if (!res.ok || data.ok === false) {
|
||||
throw new Error(data.error || "请求失败 " + res.status);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function isOn() {
|
||||
return location.pathname.replace(/\/+$/, "") === PATH;
|
||||
}
|
||||
|
||||
function setTopbarTitle(on) {
|
||||
var title = document.querySelector(".com-topbar-title");
|
||||
if (!title) return;
|
||||
if (on) {
|
||||
if (!title.getAttribute("data-users-prev")) {
|
||||
title.setAttribute("data-users-prev", title.innerHTML);
|
||||
}
|
||||
title.innerHTML = '<span aria-hidden="true">👥</span> 用户列表';
|
||||
} else if (title.getAttribute("data-users-prev")) {
|
||||
title.innerHTML = title.getAttribute("data-users-prev");
|
||||
title.removeAttribute("data-users-prev");
|
||||
}
|
||||
}
|
||||
|
||||
function mountRoot() {
|
||||
var main = document.querySelector("main.com-main");
|
||||
var root = document.getElementById("admin-users-root");
|
||||
if (!root) {
|
||||
root = el("div", { id: "admin-users-root" });
|
||||
}
|
||||
if (main) {
|
||||
if (root.parentElement !== main) main.appendChild(root);
|
||||
} else if (!root.parentElement) {
|
||||
document.body.appendChild(root);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
function syncShell(on) {
|
||||
var main = document.querySelector("main.com-main");
|
||||
if (main) main.classList.toggle("admin-users-active", !!on);
|
||||
document.querySelectorAll("a.admin-users-nav").forEach(function (a) {
|
||||
a.classList.toggle("active", !!on);
|
||||
});
|
||||
document.querySelectorAll(".com-side-nav a.com-nav-link").forEach(function (a) {
|
||||
if (a.classList.contains("admin-users-nav")) return;
|
||||
if (on) a.classList.remove("active");
|
||||
});
|
||||
setTopbarTitle(on);
|
||||
}
|
||||
|
||||
function scrollMainIntoView() {
|
||||
var main = document.querySelector("main.com-main");
|
||||
if (!main) return;
|
||||
// 窄屏侧栏 translate 隐藏后仍占 grid 行,把主区滚进视口
|
||||
var y = main.getBoundingClientRect().top + window.scrollY - 4;
|
||||
if (y > 8) window.scrollTo(0, y);
|
||||
}
|
||||
|
||||
function openPage() {
|
||||
if (!isOn()) {
|
||||
history.pushState({}, "", PATH);
|
||||
}
|
||||
// 关掉 SPA 移动端侧栏
|
||||
var scrim = document.querySelector(".com-nav-scrim");
|
||||
if (scrim) scrim.click();
|
||||
var closeBtn = document.querySelector('button[aria-label="关闭菜单"]');
|
||||
if (closeBtn) closeBtn.click();
|
||||
render(true);
|
||||
scrollMainIntoView();
|
||||
setTimeout(scrollMainIntoView, 50);
|
||||
if (!state.busy) load();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
state.busy = true;
|
||||
state.err = "";
|
||||
state.msg = "";
|
||||
paint();
|
||||
if (!token()) {
|
||||
state.busy = false;
|
||||
state.err = "未登录运营台(缺少 vip_ops_token)";
|
||||
paint();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
var qs =
|
||||
"?page=" +
|
||||
state.page +
|
||||
"&limit=" +
|
||||
state.perPage +
|
||||
(state.q ? "&q=" + encodeURIComponent(state.q) : "");
|
||||
var data = await api("GET", qs);
|
||||
state.users = data.users || [];
|
||||
state.total = data.total || 0;
|
||||
state.totalPages = data.totalPages || 1;
|
||||
state.page = data.page || state.page;
|
||||
} catch (e) {
|
||||
state.err = (e && e.message) || String(e);
|
||||
state.users = [];
|
||||
}
|
||||
state.busy = false;
|
||||
paint();
|
||||
}
|
||||
|
||||
function n(v) {
|
||||
return v == null || v === "" ? 0 : Number(v) || 0;
|
||||
}
|
||||
|
||||
function copyText(text) {
|
||||
try {
|
||||
navigator.clipboard.writeText(text || "");
|
||||
state.msg = "已复制";
|
||||
paint();
|
||||
} catch (e) {
|
||||
state.err = "复制失败";
|
||||
paint();
|
||||
}
|
||||
}
|
||||
|
||||
function openModal(mode, user) {
|
||||
state.modal = {
|
||||
mode: mode,
|
||||
user: Object.assign(
|
||||
{
|
||||
userid: "",
|
||||
nick: "",
|
||||
avatar: "",
|
||||
signature: "",
|
||||
gender_txt: "",
|
||||
region: "",
|
||||
follow_since: "",
|
||||
remark: "",
|
||||
matched_last_msg: "",
|
||||
channel_id: "",
|
||||
},
|
||||
user || {}
|
||||
),
|
||||
};
|
||||
paint();
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
state.modal = null;
|
||||
paint();
|
||||
}
|
||||
|
||||
async function saveModal() {
|
||||
var m = state.modal;
|
||||
if (!m) return;
|
||||
var u = m.user || {};
|
||||
try {
|
||||
state.busy = true;
|
||||
paint();
|
||||
if (m.mode === "create") {
|
||||
await api("POST", "", {
|
||||
userid: u.userid,
|
||||
nick: u.nick,
|
||||
avatar: u.avatar,
|
||||
signature: u.signature,
|
||||
gender_txt: u.gender_txt,
|
||||
region: u.region,
|
||||
follow_since: u.follow_since,
|
||||
remark: u.remark,
|
||||
matched_last_msg: u.matched_last_msg,
|
||||
channel_id: u.channel_id,
|
||||
});
|
||||
state.msg = "已创建/更新用户";
|
||||
} else {
|
||||
await api("PATCH", "/" + encodeURIComponent(u.id), {
|
||||
userid: u.userid,
|
||||
nick: u.nick,
|
||||
avatar: u.avatar,
|
||||
signature: u.signature,
|
||||
gender_txt: u.gender_txt,
|
||||
region: u.region,
|
||||
follow_since: u.follow_since,
|
||||
remark: u.remark,
|
||||
matched_last_msg: u.matched_last_msg,
|
||||
channel_id: u.channel_id,
|
||||
});
|
||||
state.msg = "已保存";
|
||||
}
|
||||
state.modal = null;
|
||||
await load();
|
||||
} catch (e) {
|
||||
state.busy = false;
|
||||
state.err = (e && e.message) || String(e);
|
||||
paint();
|
||||
}
|
||||
}
|
||||
|
||||
async function removeUser(u, alsoOa) {
|
||||
if (!u || !u.id) return;
|
||||
var tip = alsoOa
|
||||
? "确定删除该用户,并同时删除 oa_fans 档案?"
|
||||
: "确定删除该用户(wechat_private_users)?";
|
||||
if (!window.confirm(tip)) return;
|
||||
try {
|
||||
state.busy = true;
|
||||
paint();
|
||||
await api("DELETE", "/" + encodeURIComponent(u.id) + (alsoOa ? "?also_oa_fans=1" : ""));
|
||||
state.msg = alsoOa ? "已删除用户 + OA档案" : "已删除用户";
|
||||
delete state.selected[u.id];
|
||||
await load();
|
||||
} catch (e) {
|
||||
state.busy = false;
|
||||
state.err = (e && e.message) || String(e);
|
||||
paint();
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshUser(u) {
|
||||
if (!u || !u.id) return;
|
||||
try {
|
||||
state.busy = true;
|
||||
paint();
|
||||
await api("POST", "/" + encodeURIComponent(u.id) + "/refresh", {});
|
||||
state.msg = "已从 oa_fans 回填";
|
||||
await load();
|
||||
} catch (e) {
|
||||
state.busy = false;
|
||||
state.err = (e && e.message) || String(e);
|
||||
paint();
|
||||
}
|
||||
}
|
||||
|
||||
async function batchDelete(alsoOa) {
|
||||
var ids = Object.keys(state.selected).filter(function (k) {
|
||||
return state.selected[k];
|
||||
});
|
||||
if (!ids.length) {
|
||||
state.err = "请先勾选用户";
|
||||
paint();
|
||||
return;
|
||||
}
|
||||
if (!window.confirm("批量删除 " + ids.length + " 个用户" + (alsoOa ? "(含 oa_fans)" : "") + "?")) return;
|
||||
state.busy = true;
|
||||
paint();
|
||||
var ok = 0;
|
||||
var fail = 0;
|
||||
for (var i = 0; i < ids.length; i++) {
|
||||
try {
|
||||
await api("DELETE", "/" + encodeURIComponent(ids[i]) + (alsoOa ? "?also_oa_fans=1" : ""));
|
||||
ok += 1;
|
||||
delete state.selected[ids[i]];
|
||||
} catch (e) {
|
||||
fail += 1;
|
||||
}
|
||||
}
|
||||
state.msg = "批量删除完成:成功 " + ok + (fail ? ",失败 " + fail : "");
|
||||
await load();
|
||||
}
|
||||
|
||||
function field(label, key, opts) {
|
||||
opts = opts || {};
|
||||
var u = state.modal.user;
|
||||
var isArea = !!opts.area;
|
||||
var input = isArea
|
||||
? el("textarea", {
|
||||
value: u[key] || "",
|
||||
oninput: function (ev) {
|
||||
state.modal.user[key] = ev.target.value;
|
||||
},
|
||||
})
|
||||
: el("input", {
|
||||
type: opts.type || "text",
|
||||
value: u[key] || "",
|
||||
placeholder: opts.placeholder || "",
|
||||
oninput: function (ev) {
|
||||
state.modal.user[key] = ev.target.value;
|
||||
},
|
||||
});
|
||||
return el("div", { class: opts.full ? "full" : "" }, [el("label", { text: label }), input]);
|
||||
}
|
||||
|
||||
function renderModal() {
|
||||
if (!state.modal) return null;
|
||||
var m = state.modal;
|
||||
var title = m.mode === "create" ? "新增用户" : "编辑用户";
|
||||
var form = el("div", { class: "form-grid" }, [
|
||||
field("微信 userid / openid", "userid", { full: true, placeholder: "oBVe71..." }),
|
||||
field("昵称", "nick"),
|
||||
field("性别", "gender_txt", { placeholder: "男/女" }),
|
||||
field("头像 URL", "avatar", { full: true }),
|
||||
field("签名", "signature", { full: true, area: true }),
|
||||
field("地区", "region"),
|
||||
field("关注时间", "follow_since", { placeholder: "2026/11/20 开始关注" }),
|
||||
field("备注", "remark", { full: true }),
|
||||
field("最近消息", "matched_last_msg", { full: true }),
|
||||
field("channel_id", "channel_id"),
|
||||
]);
|
||||
if (m.mode === "edit") {
|
||||
// userid 可改但通常保持
|
||||
}
|
||||
return el("div", { class: "modal-mask", onclick: function (ev) {
|
||||
if (ev.target.classList && ev.target.classList.contains("modal-mask")) closeModal();
|
||||
} }, [
|
||||
el("div", { class: "modal" }, [
|
||||
el("h2", { text: title }),
|
||||
form,
|
||||
el("div", { class: "modal-actions" }, [
|
||||
el("button", { class: "ghost", text: "取消", onclick: closeModal }),
|
||||
el("button", {
|
||||
class: "primary",
|
||||
text: state.busy ? "保存中…" : "保存",
|
||||
onclick: function () {
|
||||
saveModal();
|
||||
},
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
function paint() {
|
||||
ensureStyle();
|
||||
var root = mountRoot();
|
||||
var on = isOn();
|
||||
root.setAttribute("data-on", on ? "1" : "0");
|
||||
syncShell(on);
|
||||
if (!on) {
|
||||
root.innerHTML = "";
|
||||
return;
|
||||
}
|
||||
|
||||
root.innerHTML = "";
|
||||
var wrap = el("div", { class: "wrap" });
|
||||
wrap.appendChild(
|
||||
el("p", {
|
||||
class: "sub",
|
||||
text: "微信私信用户档案(wechat_private_users + oa_fans)",
|
||||
})
|
||||
);
|
||||
|
||||
var bar = el("div", { class: "bar" });
|
||||
var input = el("input", {
|
||||
type: "search",
|
||||
placeholder: "搜昵称 / userid",
|
||||
value: state.q,
|
||||
oninput: function (ev) {
|
||||
state.q = ev.target.value || "";
|
||||
},
|
||||
onkeydown: function (ev) {
|
||||
if (ev.key === "Enter") {
|
||||
state.page = 1;
|
||||
load();
|
||||
}
|
||||
},
|
||||
});
|
||||
bar.appendChild(input);
|
||||
bar.appendChild(
|
||||
el("button", {
|
||||
class: "sky",
|
||||
text: state.busy ? "加载中…" : "查询",
|
||||
onclick: function () {
|
||||
state.page = 1;
|
||||
load();
|
||||
},
|
||||
})
|
||||
);
|
||||
bar.appendChild(
|
||||
el("button", {
|
||||
class: "primary",
|
||||
text: "新增",
|
||||
onclick: function () {
|
||||
openModal("create", {});
|
||||
},
|
||||
})
|
||||
);
|
||||
bar.appendChild(
|
||||
el("button", {
|
||||
class: "danger",
|
||||
text: "批量删除",
|
||||
onclick: function () {
|
||||
batchDelete(false);
|
||||
},
|
||||
})
|
||||
);
|
||||
bar.appendChild(
|
||||
el("button", {
|
||||
class: "danger",
|
||||
text: "批量删(含OA)",
|
||||
onclick: function () {
|
||||
batchDelete(true);
|
||||
},
|
||||
})
|
||||
);
|
||||
wrap.appendChild(bar);
|
||||
|
||||
wrap.appendChild(
|
||||
el("div", {
|
||||
class: "meta",
|
||||
text:
|
||||
"共 " +
|
||||
state.total +
|
||||
" 人 · 第 " +
|
||||
state.page +
|
||||
"/" +
|
||||
state.totalPages +
|
||||
" 页 · 每页 " +
|
||||
state.perPage,
|
||||
})
|
||||
);
|
||||
if (state.err) wrap.appendChild(el("div", { class: "err", text: state.err }));
|
||||
if (state.msg) wrap.appendChild(el("div", { class: "ok", text: state.msg }));
|
||||
|
||||
var tableWrap = el("div", { class: "table-wrap" });
|
||||
var table = el("table");
|
||||
table.appendChild(
|
||||
el("thead", {}, [
|
||||
el("tr", {}, [
|
||||
el("th", { text: "" }),
|
||||
el("th", { text: "头像" }),
|
||||
el("th", { text: "昵称 / 签名" }),
|
||||
el("th", { text: "userid" }),
|
||||
el("th", { text: "档案" }),
|
||||
el("th", { text: "互动" }),
|
||||
el("th", { text: "更新" }),
|
||||
el("th", { text: "操作" }),
|
||||
]),
|
||||
])
|
||||
);
|
||||
var tbody = el("tbody");
|
||||
if (!state.users.length && !state.busy) {
|
||||
tbody.appendChild(
|
||||
el("tr", {}, [el("td", { text: "暂无数据", style: { color: "#94A3B8" } })])
|
||||
);
|
||||
}
|
||||
state.users.forEach(function (u) {
|
||||
var checked = !!state.selected[u.id];
|
||||
var av =
|
||||
u.avatar && String(u.avatar).indexOf("http") === 0
|
||||
? el("img", { class: "av", src: u.avatar, alt: "" })
|
||||
: el("div", { class: "av ph", text: "?" });
|
||||
var nickCell = el("div", {}, [
|
||||
el("div", { class: "nick", text: u.nick || "(无昵称)" }),
|
||||
u.gender_txt ? el("span", { class: "chip", text: u.gender_txt }) : null,
|
||||
u.has_oa_fans ? el("span", { class: "chip", text: "OA" }) : null,
|
||||
u.signature ? el("div", { class: "sig", text: u.signature }) : null,
|
||||
]);
|
||||
var profile = [
|
||||
u.region || "",
|
||||
u.follow_since || "",
|
||||
u.remark ? "备注:" + u.remark : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
var stats =
|
||||
"赞" +
|
||||
n(u.like_cnt) +
|
||||
" / 在看" +
|
||||
n(u.look_cnt) +
|
||||
" / 留言" +
|
||||
n(u.comment_cnt) +
|
||||
" / 赞赏" +
|
||||
(u.reward_amt || "¥0");
|
||||
var ops = el("div", { class: "ops" }, [
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
text: "编辑",
|
||||
onclick: function () {
|
||||
openModal("edit", u);
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "sky",
|
||||
text: "回填OA",
|
||||
onclick: function () {
|
||||
refreshUser(u);
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
text: "复制",
|
||||
onclick: function () {
|
||||
copyText(
|
||||
[u.nick, u.userid, u.signature, u.h5].filter(Boolean).join("\n")
|
||||
);
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
text: "打开VIP",
|
||||
onclick: function () {
|
||||
if (u.h5) window.open(u.h5, "_blank");
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "danger",
|
||||
text: "删除",
|
||||
onclick: function () {
|
||||
removeUser(u, false);
|
||||
},
|
||||
}),
|
||||
el("button", {
|
||||
class: "danger",
|
||||
text: "删含OA",
|
||||
onclick: function () {
|
||||
removeUser(u, true);
|
||||
},
|
||||
}),
|
||||
]);
|
||||
tbody.appendChild(
|
||||
el("tr", {}, [
|
||||
el("td", {}, [
|
||||
el("input", {
|
||||
type: "checkbox",
|
||||
checked: checked,
|
||||
onchange: function (ev) {
|
||||
if (ev.target.checked) state.selected[u.id] = true;
|
||||
else delete state.selected[u.id];
|
||||
},
|
||||
}),
|
||||
]),
|
||||
el("td", {}, [av]),
|
||||
el("td", {}, [nickCell]),
|
||||
el("td", {}, [el("div", { class: "mono", text: u.userid || "-" })]),
|
||||
el("td", { text: profile || "-" }),
|
||||
el("td", { text: stats }),
|
||||
el("td", { text: (u.updated || u.created || "-").slice(0, 19) }),
|
||||
el("td", {}, [ops]),
|
||||
])
|
||||
);
|
||||
});
|
||||
table.appendChild(tbody);
|
||||
tableWrap.appendChild(table);
|
||||
wrap.appendChild(tableWrap);
|
||||
|
||||
var pager = el("div", { class: "pager" });
|
||||
pager.appendChild(
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
text: "上一页",
|
||||
onclick: function () {
|
||||
if (state.page > 1) {
|
||||
state.page -= 1;
|
||||
load();
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
pager.appendChild(
|
||||
el("button", {
|
||||
class: "ghost",
|
||||
text: "下一页",
|
||||
onclick: function () {
|
||||
if (state.page < state.totalPages) {
|
||||
state.page += 1;
|
||||
load();
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
var sel = el("select", {
|
||||
onchange: function (ev) {
|
||||
state.perPage = Number(ev.target.value) || 50;
|
||||
state.page = 1;
|
||||
load();
|
||||
},
|
||||
});
|
||||
[20, 50, 100, 200].forEach(function (n) {
|
||||
var opt = el("option", { value: String(n), text: String(n) + " / 页" });
|
||||
if (n === state.perPage) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
pager.appendChild(sel);
|
||||
wrap.appendChild(pager);
|
||||
|
||||
var modal = renderModal();
|
||||
if (modal) wrap.appendChild(modal);
|
||||
root.appendChild(wrap);
|
||||
}
|
||||
|
||||
function injectNav() {
|
||||
var existing = document.querySelector("a.admin-users-nav");
|
||||
if (existing) return true;
|
||||
var nav = document.querySelector(".com-side-nav");
|
||||
var leads =
|
||||
document.querySelector('.com-side-nav a[href="/leads"]') ||
|
||||
document.querySelector('.com-side-nav a[href*="/leads"]');
|
||||
if (!nav || !leads || !leads.parentElement) return false;
|
||||
|
||||
var a = document.createElement("a");
|
||||
a.href = PATH;
|
||||
a.className = "com-nav-link com-nav-link-rich admin-users-nav";
|
||||
a.innerHTML =
|
||||
'<span class="com-nav-ico" aria-hidden="true">👥</span>' +
|
||||
'<span class="com-nav-label">用户列表</span>' +
|
||||
'<span class="com-nav-emoji" aria-hidden="true">📋</span>';
|
||||
a.addEventListener(
|
||||
"click",
|
||||
function (ev) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
openPage();
|
||||
},
|
||||
true
|
||||
);
|
||||
// 插在「加入线索」后面,同一经营分组
|
||||
if (leads.nextSibling) leads.parentElement.insertBefore(a, leads.nextSibling);
|
||||
else leads.parentElement.appendChild(a);
|
||||
return true;
|
||||
}
|
||||
|
||||
function onSpaNavigate() {
|
||||
// 用户点了侧栏其它 React Router 链接:离开用户列表
|
||||
if (!isOn()) {
|
||||
paint();
|
||||
return;
|
||||
}
|
||||
render(true);
|
||||
scrollMainIntoView();
|
||||
if (!state.users.length) load();
|
||||
}
|
||||
|
||||
function boot() {
|
||||
ensureStyle();
|
||||
injectNav();
|
||||
mountRoot();
|
||||
if (isOn()) {
|
||||
render(true);
|
||||
scrollMainIntoView();
|
||||
load();
|
||||
} else {
|
||||
paint();
|
||||
}
|
||||
}
|
||||
|
||||
function render(forceLoad) {
|
||||
paint();
|
||||
if (forceLoad && isOn() && !state.busy && !state.users.length) load();
|
||||
}
|
||||
|
||||
window.addEventListener("popstate", function () {
|
||||
onSpaNavigate();
|
||||
});
|
||||
|
||||
// 侧栏其它菜单用 React Router,监听 DOM/路径变化自动收起本页
|
||||
var lastPath = location.pathname;
|
||||
setInterval(function () {
|
||||
injectNav();
|
||||
if (location.pathname !== lastPath) {
|
||||
lastPath = location.pathname;
|
||||
onSpaNavigate();
|
||||
}
|
||||
}, 300);
|
||||
|
||||
// 点击侧栏其它链接时,先清掉我们的 active 态(RR 会改 URL)
|
||||
document.addEventListener(
|
||||
"click",
|
||||
function (ev) {
|
||||
var a = ev.target && ev.target.closest ? ev.target.closest(".com-side-nav a.com-nav-link") : null;
|
||||
if (!a || a.classList.contains("admin-users-nav")) return;
|
||||
// 留给 RR 跳转;短延迟后按新路径同步
|
||||
setTimeout(onSpaNavigate, 0);
|
||||
setTimeout(onSpaNavigate, 50);
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
})();
|
||||
BIN
apps/hackrobot/admin-site/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
1
apps/hackrobot/admin-site/assets/index-DJrK42yQ.css
Normal file
4
apps/hackrobot/admin-site/assets/index-OYkETFeq.js
Normal file
40
apps/hackrobot/admin-site/assets/react-d4cfecKK.js
vendored
Normal file
28
apps/hackrobot/admin-site/assets/router-CQ6o5G0Y.js
Normal file
6
apps/hackrobot/admin-site/brand-violet.css
Normal file
@ -0,0 +1,6 @@
|
||||
/* violet brand override */
|
||||
:root{--accent:#8b5cf6;}
|
||||
.com-mark{
|
||||
background:linear-gradient(135deg,#8b5cf6,#7c3aed)!important;
|
||||
box-shadow:0 8px 24px rgba(139,92,246,.35)!important;
|
||||
}
|
||||
BIN
apps/hackrobot/admin-site/favicon-16x16.png
Normal file
|
After Width: | Height: | Size: 775 B |
BIN
apps/hackrobot/admin-site/favicon-32x32.png
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
apps/hackrobot/admin-site/favicon.ico
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
22
apps/hackrobot/admin-site/favicon.svg
Normal file
@ -0,0 +1,22 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="异度星球 VIP 运营台">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="8" y1="4" x2="56" y2="60" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#a78bfa"/>
|
||||
<stop offset="55%" stop-color="#8b5cf6"/>
|
||||
<stop offset="100%" stop-color="#6d28d9"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="shine" x1="10" y1="6" x2="40" y2="34" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#fff" stop-opacity="0.38"/>
|
||||
<stop offset="100%" stop-color="#fff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="16" fill="#0c0c0f"/>
|
||||
<rect x="4" y="4" width="56" height="56" rx="14" fill="url(#bg)"/>
|
||||
<rect x="4" y="4" width="56" height="56" rx="14" fill="url(#shine)"/>
|
||||
<!-- planet + orbit (异度星球) -->
|
||||
<ellipse cx="32" cy="32" rx="18" ry="7.5" fill="none" stroke="#1e1033" stroke-width="2.4" transform="rotate(-28 32 32)"/>
|
||||
<ellipse cx="32" cy="32" rx="18" ry="7.5" fill="none" stroke="#1e1033" stroke-width="2.4" opacity="0.55" transform="rotate(38 32 32)"/>
|
||||
<circle cx="32" cy="32" r="9" fill="#1e1033"/>
|
||||
<circle cx="32" cy="32" r="3.2" fill="#c4b5fd"/>
|
||||
<circle cx="45.5" cy="24.5" r="2.4" fill="#1e1033"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
BIN
apps/hackrobot/admin-site/icon-192.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
apps/hackrobot/admin-site/icon-512.png
Normal file
|
After Width: | Height: | Size: 5.1 KiB |
34
apps/hackrobot/admin-site/index.html
Normal file
@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1" />
|
||||
<meta name="robots" content="noindex,nofollow" />
|
||||
<meta name="theme-color" content="#0c0c0f" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="any" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<title>异度星球 · VIP 运营台</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=DM+Sans:wght@400;500;600;700&family=Syne:wght@600;700&display=swap" rel="stylesheet" />
|
||||
<script type="module" crossorigin src="/assets/index-OYkETFeq.js?v=202611221042"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/react-d4cfecKK.js">
|
||||
<link rel="modulepreload" crossorigin href="/assets/router-CQ6o5G0Y.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DJrK42yQ.css?v=202611221042">
|
||||
<link rel="stylesheet" href="/brand-violet.css?v=202611221042" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
|
||||
<script src="/admin-live.js" defer></script>
|
||||
<script src="/admin-users.js" defer></script>
|
||||
<script src="/admin-user-tags.js" defer></script>
|
||||
<script src="/admin-leads-online.js" defer></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
13
apps/hackrobot/deploy/README.md
Normal file
@ -0,0 +1,13 @@
|
||||
# hackrobot deploy
|
||||
|
||||
| 脚本 | 作用 |
|
||||
|---|---|
|
||||
| `pull_from_129.py` | 前台/运营台/初版后端 → 本地 |
|
||||
| `pull_backends_from_129.py` | **补全后端**:payjsapi / nomadmini / vip-track / PB / vip `app/api` |
|
||||
| `install_server_backup.py` | 安装 `/opt/hackrobot-backup` + `hackrobot-backup` |
|
||||
| `deploy_admin_site.py` | 发 `admin.hackrobot.cn`(先备份) |
|
||||
| `deploy_vip.py` | 同步 VIP 源码;`--build` 才编译重启 |
|
||||
| `deploy_nomadmini.py` | 发 LIVE API `:8010`(先备份) |
|
||||
| `deploy_payjsapi.py` | 发支付后端(先备份) |
|
||||
|
||||
机器:`129.204.21.129`。快照:`/opt/hackrobot-backup/snapshots/`。
|
||||
71
apps/hackrobot/deploy/_probe_backends.py
Normal file
@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""List every VIP-related backend on 129."""
|
||||
from __future__ import annotations
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
CMD = r"""
|
||||
set +e
|
||||
echo '=== listeners ==='
|
||||
sudo ss -lntp | grep -E '4007|4011|8010|8090|8080|3000|8091|8092|5001|8099' || true
|
||||
|
||||
echo
|
||||
echo '=== systemd vip/nomad/pay/pb ==='
|
||||
systemctl list-units --type=service --all 2>/dev/null | grep -iE 'vip|nomad|pay|pocket|pb|track|admini|xor|zpay' | head -40
|
||||
|
||||
echo
|
||||
echo '=== /opt top ==='
|
||||
ls -lah /opt/ | head -60
|
||||
|
||||
echo
|
||||
echo '=== nomadvip app/api tree ==='
|
||||
find /www/wwwroot/nomadvip/app/api -type d 2>/dev/null | head -80
|
||||
ls /www/wwwroot/nomadvip/app/api/ops 2>/dev/null
|
||||
|
||||
echo
|
||||
echo '=== pocketbase for vip ==='
|
||||
ls -lah /www/wwwroot/pocketbase.hackrobot.cn 2>/dev/null | head
|
||||
ps aux | grep -i pocketbase | grep -v grep | head
|
||||
sudo find /opt /home/ubuntu /www/wwwroot -maxdepth 3 -iname '*pocketbase*' -o -iname 'pb_data' 2>/dev/null | head -40
|
||||
|
||||
echo
|
||||
echo '=== pay related ==='
|
||||
ls /www/wwwroot/payjsapi 2>/dev/null | head
|
||||
ls /opt | grep -iE 'pay|xor|zpay'
|
||||
sudo find /opt /www/wwwroot -maxdepth 2 -iname '*pay*' 2>/dev/null | head -30
|
||||
|
||||
echo
|
||||
echo '=== vip-track + nomadmini sizes ==='
|
||||
du -sh /opt/vip-track /opt/nomadmini /www/wwwroot/nomadvip 2>/dev/null
|
||||
ls -la /opt/vip-track/ | head -30
|
||||
ls -la /opt/nomadmini/ | head -20
|
||||
ls -la /opt/nomadmini/backend/ | head -30
|
||||
|
||||
echo
|
||||
echo '=== what local pull missed: compare key backend files ==='
|
||||
# list python/go services under /opt
|
||||
for d in /opt/*/; do
|
||||
[ -d "$d" ] || continue
|
||||
name=$(basename "$d")
|
||||
case "$name" in
|
||||
containerd|google|puppet*|rancher*|bitnami) continue ;;
|
||||
esac
|
||||
echo "-- $name --"
|
||||
ls "$d" 2>/dev/null | head -8
|
||||
done
|
||||
"""
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=50, allow_agent=False, look_for_keys=False)
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(120)
|
||||
chan.get_pty()
|
||||
chan.exec_command(CMD)
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
c.close()
|
||||
65
apps/hackrobot/deploy/_probe_vip_stack.py
Normal file
@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Probe VIP stack on 129 for sync."""
|
||||
from __future__ import annotations
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
CMD = r"""
|
||||
set +e
|
||||
echo '=== vip.hackrobot nginx conf ==='
|
||||
ls /www/server/panel/vhost/nginx/ | grep -i vip
|
||||
sudo grep -R 'server_name.*vip.hackrobot\|proxy_pass.*4007\|root .*vip' /www/server/panel/vhost/nginx/ 2>/dev/null | head -40
|
||||
|
||||
echo
|
||||
echo '=== who listens 4007 ==='
|
||||
sudo ss -lntp | grep -E '4007|4011|8010|3000'
|
||||
ps aux | grep -E 'next|node|4007|nomadvip|uvicorn|nomadmini' | grep -v grep | head -30
|
||||
|
||||
echo
|
||||
echo '=== systemd units ==='
|
||||
systemctl cat nomadmini-api.service 2>/dev/null | head -40
|
||||
ls /etc/systemd/system/*vip* /etc/systemd/system/*nomad* /etc/systemd/system/*admini* 2>/dev/null
|
||||
|
||||
echo
|
||||
echo '=== nomadmini path ==='
|
||||
sudo find /opt /www /home/ubuntu -maxdepth 3 -type d -iname '*nomadmini*' 2>/dev/null | head
|
||||
sudo find /opt /www /home/ubuntu -maxdepth 3 -type d -iname '*vip-track*' 2>/dev/null | head
|
||||
|
||||
echo
|
||||
echo '=== nomadvip git + sizes (no node_modules/.next) ==='
|
||||
cd /www/wwwroot/nomadvip
|
||||
git remote -v
|
||||
git status -sb | head
|
||||
git log -3 --oneline
|
||||
du -sh app lib public scripts config data docs 2>/dev/null
|
||||
du -sh --exclude=node_modules --exclude=.next . 2>/dev/null
|
||||
|
||||
echo
|
||||
echo '=== vip.hackrobot.cn wwwroot ==='
|
||||
ls -lah /www/wwwroot/vip.hackrobot.cn/
|
||||
head -c 400 /www/wwwroot/vip.hackrobot.cn/index.html 2>/dev/null; echo
|
||||
|
||||
echo
|
||||
echo '=== admin live listing ==='
|
||||
ls -lah /www/wwwroot/admin.hackrobot.cn/
|
||||
ls -lah /www/wwwroot/admin.hackrobot.cn/assets/
|
||||
|
||||
echo
|
||||
echo '=== env keys only (no secrets) ==='
|
||||
grep -E '^[A-Z0-9_]+=' /www/wwwroot/nomadvip/.env.local 2>/dev/null | cut -d= -f1
|
||||
"""
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=50, allow_agent=False, look_for_keys=False)
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(90)
|
||||
chan.get_pty()
|
||||
chan.exec_command(CMD)
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
c.close()
|
||||
39
apps/hackrobot/deploy/_ssh.py
Normal file
@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
|
||||
|
||||
def connect() -> paramiko.SSHClient:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||
return c
|
||||
|
||||
|
||||
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 180) -> str:
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(timeout)
|
||||
chan.get_pty()
|
||||
chan.exec_command(cmd)
|
||||
buf = b""
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
return buf.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def require_backup(c: paramiko.SSHClient, label: str) -> None:
|
||||
out = run(c, f"sudo /usr/local/bin/hackrobot-backup {label}", timeout=300)
|
||||
ok = (
|
||||
"[backup] ok" in out
|
||||
or "admin.hackrobot.cn.tgz" in out
|
||||
or "/opt/hackrobot-backup/snapshots" in out
|
||||
)
|
||||
if not ok:
|
||||
raise SystemExit(f"backup failed for label={label}")
|
||||
91
apps/hackrobot/deploy/backup_before_deploy.sh
Normal file
@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run on 129 BEFORE any vip/admin/nomadmini deploy. Idempotent.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=/opt/hackrobot-backup
|
||||
SNAP_ROOT="$ROOT/snapshots"
|
||||
KEEP="${HACKROBOT_BACKUP_KEEP:-20}"
|
||||
TS="$(date +%Y%m%d_%H%M%S)"
|
||||
LABEL="${1:-manual}"
|
||||
DEST="$SNAP_ROOT/${TS}_${LABEL}"
|
||||
|
||||
mkdir -p "$DEST"
|
||||
echo "[backup] → $DEST"
|
||||
|
||||
# admin SPA
|
||||
if [[ -d /www/wwwroot/admin.hackrobot.cn ]]; then
|
||||
tar -C /www/wwwroot -czf "$DEST/admin.hackrobot.cn.tgz" admin.hackrobot.cn
|
||||
fi
|
||||
|
||||
# VIP Next source + note of .next BUILD_ID (not full .next — too heavy)
|
||||
if [[ -d /www/wwwroot/nomadvip ]]; then
|
||||
tar -C /www/wwwroot/nomadvip -czf "$DEST/nomadvip-src.tgz" \
|
||||
--exclude=node_modules --exclude=.next --exclude=.git \
|
||||
--exclude='.env' --exclude='.env.local' \
|
||||
app lib public scripts config data docs \
|
||||
package.json pnpm-lock.yaml pnpm-workspace.yaml \
|
||||
next.config.ts tsconfig.json middleware.ts README.md vip.sh .env.example 2>/dev/null || true
|
||||
if [[ -f /www/wwwroot/nomadvip/.next/BUILD_ID ]]; then
|
||||
cp /www/wwwroot/nomadvip/.next/BUILD_ID "$DEST/nomadvip.BUILD_ID" || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# nomadmini
|
||||
if [[ -d /opt/nomadmini ]]; then
|
||||
tar -C /opt -czf "$DEST/nomadmini.tgz" \
|
||||
--exclude='nomadmini/backend/.venv' \
|
||||
--exclude='nomadmini/**/__pycache__' \
|
||||
--exclude='nomadmini/**/.env' \
|
||||
nomadmini 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# vip-track
|
||||
if [[ -d /opt/vip-track ]]; then
|
||||
tar -C /opt -czf "$DEST/vip-track.tgz" \
|
||||
--exclude='vip-track/.venv' --exclude='vip-track/.env' --exclude='vip-track/*.db' vip-track 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# payjsapi (payment backend)
|
||||
if [[ -d /www/wwwroot/payjsapi ]]; then
|
||||
tar -C /www/wwwroot -czf "$DEST/payjsapi.tgz" \
|
||||
--exclude='payjsapi/venv' --exclude='payjsapi/.git' --exclude='payjsapi/*.log' \
|
||||
--exclude='payjsapi/.env' --exclude='payjsapi/.env.local' payjsapi 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# PocketBase schema + data.db (no storage blobs)
|
||||
if [[ -d /home/ubuntu/pb_data ]]; then
|
||||
mkdir -p "$DEST/pb"
|
||||
cp -a /home/ubuntu/pocketbase.sh "$DEST/pb/" 2>/dev/null || true
|
||||
cp -a /home/ubuntu/pb_data/types.d.ts "$DEST/pb/" 2>/dev/null || true
|
||||
cp -a /home/ubuntu/pb_data/data.db "$DEST/pb/" 2>/dev/null || true
|
||||
sqlite3 /home/ubuntu/pb_data/data.db '.schema' > "$DEST/pb/data.schema.sql" 2>/dev/null || true
|
||||
tar -C "$DEST/pb" -czf "$DEST/pocketbase.tgz" . 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# nginx refs
|
||||
mkdir -p "$DEST/nginx"
|
||||
cp -a /www/server/panel/vhost/nginx/vip.hackrobot.cn.conf "$DEST/nginx/" 2>/dev/null || true
|
||||
cp -a /www/server/panel/vhost/nginx/admin.hackrobot.cn.conf "$DEST/nginx/" 2>/dev/null || true
|
||||
cp -a /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn "$DEST/nginx/ext-admin" 2>/dev/null || true
|
||||
cp -a /www/server/panel/vhost/nginx/extension/vip.hackrobot.cn "$DEST/nginx/ext-vip" 2>/dev/null || true
|
||||
|
||||
cat > "$DEST/MANIFEST.txt" <<EOF
|
||||
ts=$TS
|
||||
label=$LABEL
|
||||
host=$(hostname)
|
||||
admin=/www/wwwroot/admin.hackrobot.cn
|
||||
vip=/www/wwwroot/nomadvip
|
||||
nomadmini=/opt/nomadmini
|
||||
EOF
|
||||
|
||||
ln -sfn "$DEST" "$SNAP_ROOT/latest"
|
||||
echo "[backup] ok $(du -sh "$DEST" | awk '{print $1}')"
|
||||
|
||||
# prune old
|
||||
mapfile -t ALL < <(ls -1dt "$SNAP_ROOT"/*/ 2>/dev/null | grep -v '/latest' || true)
|
||||
if ((${#ALL[@]} > KEEP)); then
|
||||
for old in "${ALL[@]:$KEEP}"; do
|
||||
rm -rf "$old"
|
||||
echo "[backup] pruned $old"
|
||||
done
|
||||
fi
|
||||
61
apps/hackrobot/deploy/deploy_admin_site.py
Normal file
@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Deploy apps/hackrobot/admin-site → /www/wwwroot/admin.hackrobot.cn
|
||||
ALWAYS backups first via hackrobot-backup.
|
||||
Never touch admin.nomadro.cn.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from _ssh import connect, require_backup, run
|
||||
|
||||
SITE = Path(__file__).resolve().parents[1] / "admin-site"
|
||||
LIVE = "/www/wwwroot/admin.hackrobot.cn"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not (SITE / "index.html").exists():
|
||||
raise SystemExit(f"missing {SITE}/index.html — run pull_from_129.py first")
|
||||
|
||||
c = connect()
|
||||
print("[1] backup…")
|
||||
require_backup(c, "pre_admin_site")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tgz = Path(td) / "admin-site.tgz"
|
||||
with tarfile.open(tgz, "w:gz") as tar:
|
||||
for p in SITE.rglob("*"):
|
||||
if p.is_file() and ".bak" not in p.name:
|
||||
tar.add(p, arcname=str(p.relative_to(SITE)).replace("\\", "/"))
|
||||
sftp = c.open_sftp()
|
||||
sftp.put(str(tgz), "/tmp/admin-site-deploy.tgz")
|
||||
sftp.close()
|
||||
|
||||
print("[2] install…")
|
||||
run(
|
||||
c,
|
||||
rf"""
|
||||
set -e
|
||||
TMP=/tmp/admin-site-unpack-$$
|
||||
rm -rf "$TMP" && mkdir -p "$TMP"
|
||||
tar -xzf /tmp/admin-site-deploy.tgz -C "$TMP"
|
||||
# replace live contents but keep parent
|
||||
sudo find {LIVE} -mindepth 1 -maxdepth 1 ! -name '.*' -exec rm -rf {{}} +
|
||||
sudo cp -a "$TMP"/. {LIVE}/
|
||||
sudo chown -R www:www {LIVE}
|
||||
ls -lah {LIVE}
|
||||
curl -sS -o /dev/null -w 'home:%{{http_code}}\n' https://admin.hackrobot.cn/
|
||||
curl -sS -o /dev/null -w 'js:%{{http_code}}\n' https://admin.hackrobot.cn/assets/index-OYkETFeq.js || true
|
||||
echo DEPLOY_ADMIN_OK
|
||||
""",
|
||||
timeout=120,
|
||||
)
|
||||
c.close()
|
||||
print("[done] admin.hackrobot.cn")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
64
apps/hackrobot/deploy/deploy_nomadmini.py
Normal file
@ -0,0 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy apps/hackrobot/nomadmini → /opt/nomadmini (backup first, restart systemd)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from _ssh import connect, require_backup, run
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "nomadmini"
|
||||
REMOTE = "/opt/nomadmini"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not (SRC / "backend").exists():
|
||||
raise SystemExit("missing nomadmini/backend")
|
||||
|
||||
c = connect()
|
||||
print("[1] backup…")
|
||||
require_backup(c, "pre_nomadmini")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tgz = Path(td) / "nomadmini.tgz"
|
||||
with tarfile.open(tgz, "w:gz") as tar:
|
||||
for p in SRC.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
rel = str(p.relative_to(SRC)).replace("\\", "/")
|
||||
if "/.venv/" in f"/{rel}/" or rel.endswith(".pyc") or "__pycache__" in rel:
|
||||
continue
|
||||
if p.name.startswith(".env") and "example" not in p.name:
|
||||
continue
|
||||
tar.add(p, arcname=rel)
|
||||
sftp = c.open_sftp()
|
||||
sftp.put(str(tgz), "/tmp/nomadmini-deploy.tgz")
|
||||
sftp.close()
|
||||
|
||||
print("[2] sync + restart…")
|
||||
run(
|
||||
c,
|
||||
rf"""
|
||||
set -e
|
||||
TMP=/tmp/nomadmini-unpack-$$
|
||||
rm -rf "$TMP" && mkdir -p "$TMP"
|
||||
tar -xzf /tmp/nomadmini-deploy.tgz -C "$TMP"
|
||||
# keep live .env and .venv
|
||||
sudo rsync -a \
|
||||
--exclude .venv --exclude '__pycache__' --exclude .env \
|
||||
"$TMP"/ {REMOTE}/
|
||||
sudo systemctl restart nomadmini-api.service
|
||||
sleep 1
|
||||
systemctl is-active nomadmini-api.service
|
||||
curl -sS -o /dev/null -w 'live_health:%{{http_code}}\n' http://127.0.0.1:8010/docs || true
|
||||
echo DEPLOY_NOMADMINI_OK
|
||||
""",
|
||||
timeout=180,
|
||||
)
|
||||
c.close()
|
||||
print("[done] nomadmini")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
61
apps/hackrobot/deploy/deploy_payjsapi.py
Normal file
@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy apps/hackrobot/payjsapi → /www/wwwroot/payjsapi (backup first)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from _ssh import connect, require_backup, run
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "payjsapi"
|
||||
REMOTE = "/www/wwwroot/payjsapi"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not (SRC / "run.py").exists() and not (SRC / "app").exists():
|
||||
raise SystemExit("missing payjsapi — run pull_backends_from_129.py first")
|
||||
|
||||
c = connect()
|
||||
print("[1] backup…")
|
||||
require_backup(c, "pre_payjsapi")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tgz = Path(td) / "payjsapi.tgz"
|
||||
with tarfile.open(tgz, "w:gz") as tar:
|
||||
for p in SRC.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
rel = str(p.relative_to(SRC)).replace("\\", "/")
|
||||
if p.name.startswith(".env") and "example" not in p.name and "keys" not in p.name:
|
||||
continue
|
||||
if ".bak" in p.name.lower():
|
||||
continue
|
||||
tar.add(p, arcname=rel)
|
||||
sftp = c.open_sftp()
|
||||
sftp.put(str(tgz), "/tmp/payjsapi-deploy.tgz")
|
||||
sftp.close()
|
||||
|
||||
print("[2] sync (keep .env / venv)…")
|
||||
run(
|
||||
c,
|
||||
rf"""
|
||||
set -e
|
||||
TMP=/tmp/payjsapi-unpack-$$
|
||||
rm -rf "$TMP" && mkdir -p "$TMP"
|
||||
tar -xzf /tmp/payjsapi-deploy.tgz -C "$TMP"
|
||||
sudo rsync -a \
|
||||
--exclude venv --exclude .git --exclude .env --exclude .env.local \
|
||||
--exclude '*.log' \
|
||||
"$TMP"/ {REMOTE}/
|
||||
echo DEPLOY_PAYJSAPI_OK
|
||||
ls -lah {REMOTE} | head
|
||||
""",
|
||||
timeout=120,
|
||||
)
|
||||
c.close()
|
||||
print("[done] payjsapi")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
108
apps/hackrobot/deploy/deploy_vip.py
Normal file
@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Deploy apps/hackrobot/vip → /www/wwwroot/nomadvip (source sync).
|
||||
ALWAYS backups first. Does NOT auto-build/restart unless --build.
|
||||
|
||||
Usage:
|
||||
python deploy_vip.py # sync source only
|
||||
python deploy_vip.py --build # sync + pnpm build + restart :4007 (needs frontend OK)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from _ssh import connect, require_backup, run
|
||||
|
||||
VIP = Path(__file__).resolve().parents[1] / "vip"
|
||||
REMOTE = "/www/wwwroot/nomadvip"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
do_build = "--build" in sys.argv
|
||||
if not (VIP / "package.json").exists():
|
||||
raise SystemExit("missing vip/package.json — run pull_from_129.py first")
|
||||
|
||||
c = connect()
|
||||
print("[1] backup…")
|
||||
require_backup(c, "pre_vip")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tgz = Path(td) / "vip-src.tgz"
|
||||
with tarfile.open(tgz, "w:gz") as tar:
|
||||
for p in VIP.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
rel = str(p.relative_to(VIP)).replace("\\", "/")
|
||||
if rel.startswith("node_modules/") or rel.startswith(".next/"):
|
||||
continue
|
||||
if p.name in {".env", ".env.local"} or p.name.endswith(".local"):
|
||||
continue
|
||||
if p.name.endswith(".keys.example"):
|
||||
continue
|
||||
tar.add(p, arcname=rel)
|
||||
sftp = c.open_sftp()
|
||||
sftp.put(str(tgz), "/tmp/vip-src-deploy.tgz")
|
||||
sftp.close()
|
||||
|
||||
print("[2] sync source…")
|
||||
run(
|
||||
c,
|
||||
rf"""
|
||||
set -e
|
||||
TMP=/tmp/vip-src-unpack-$$
|
||||
rm -rf "$TMP" && mkdir -p "$TMP"
|
||||
tar -xzf /tmp/vip-src-deploy.tgz -C "$TMP"
|
||||
# sync into nomadvip without wiping .env.local / node_modules / .next
|
||||
sudo rsync -a --delete \
|
||||
--exclude node_modules --exclude .next --exclude .git \
|
||||
--exclude .env --exclude .env.local \
|
||||
"$TMP"/ {REMOTE}/
|
||||
sudo chown -R root:root {REMOTE}/app {REMOTE}/lib {REMOTE}/public {REMOTE}/scripts 2>/dev/null || true
|
||||
echo SYNC_VIP_OK
|
||||
""",
|
||||
timeout=180,
|
||||
)
|
||||
|
||||
if do_build:
|
||||
print("[3] build + restart :4007…")
|
||||
run(
|
||||
c,
|
||||
rf"""
|
||||
set -e
|
||||
cd {REMOTE}
|
||||
# reuse existing node_modules if present
|
||||
if [ ! -d node_modules ]; then
|
||||
sudo pnpm install --frozen-lockfile || sudo pnpm install
|
||||
fi
|
||||
sudo pnpm build
|
||||
# restart next on 4007 — prefer existing vip.sh / systemd / nohup pattern
|
||||
if [ -x ./vip.sh ]; then
|
||||
sudo ./vip.sh restart || true
|
||||
fi
|
||||
# fallback: kill old next on 4007 and start
|
||||
PID=$(sudo ss -lntp | awk '/:4007/{{print}}' | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | head -1)
|
||||
if [ -n "$PID" ]; then
|
||||
echo "restarting pid $PID"
|
||||
sudo kill "$PID" || true
|
||||
sleep 2
|
||||
fi
|
||||
cd {REMOTE}
|
||||
sudo nohup pnpm exec next start -H 0.0.0.0 -p 4007 >/tmp/nomadvip-4007.log 2>&1 &
|
||||
sleep 3
|
||||
curl -sS -o /dev/null -w 'vip:%{{http_code}}\n' https://vip.hackrobot.cn/ || true
|
||||
echo BUILD_VIP_OK
|
||||
""",
|
||||
timeout=600,
|
||||
)
|
||||
else:
|
||||
print("[skip] build — pass --build to compile/restart (requires frontend deploy permission)")
|
||||
|
||||
c.close()
|
||||
print("[done] vip source synced")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
51
apps/hackrobot/deploy/install_server_backup.py
Normal file
@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Install /opt/hackrobot-backup + backup_before_deploy.sh on 129."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
LOCAL_SH = Path(__file__).resolve().parent / "backup_before_deploy.sh"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=50, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
c.exec_command("mkdir -p /tmp/hackrobot_backup_install /opt/hackrobot-backup/snapshots", timeout=20)
|
||||
sftp.put(str(LOCAL_SH), "/tmp/hackrobot_backup_install/backup_before_deploy.sh")
|
||||
sftp.close()
|
||||
|
||||
cmd = r"""
|
||||
set -e
|
||||
sudo mkdir -p /opt/hackrobot-backup/snapshots
|
||||
sudo cp /tmp/hackrobot_backup_install/backup_before_deploy.sh /opt/hackrobot-backup/backup_before_deploy.sh
|
||||
sudo chmod +x /opt/hackrobot-backup/backup_before_deploy.sh
|
||||
# wrapper used by all deploy scripts
|
||||
sudo tee /usr/local/bin/hackrobot-backup >/dev/null <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
exec /opt/hackrobot-backup/backup_before_deploy.sh "$@"
|
||||
EOF
|
||||
sudo chmod +x /usr/local/bin/hackrobot-backup
|
||||
# seed first snapshot
|
||||
sudo /usr/local/bin/hackrobot-backup install
|
||||
ls -lah /opt/hackrobot-backup/snapshots/ | head
|
||||
echo INSTALL_OK
|
||||
"""
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(180)
|
||||
chan.get_pty()
|
||||
chan.exec_command(cmd)
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
229
apps/hackrobot/deploy/pull_backends_from_129.py
Normal file
@ -0,0 +1,229 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Pull VIP backends that were incomplete:
|
||||
- payjsapi (payment API)
|
||||
- nomadmini (full, re-sync)
|
||||
- vip-track (re-sync)
|
||||
- pocketbase runtime scripts + schema (not secrets; optional data.db)
|
||||
- vip Next app/api already in vip/ — re-confirm ops routes
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
REMOTE = r"""
|
||||
set -e
|
||||
OUT=/tmp/hackrobot_backends_$$
|
||||
mkdir -p "$OUT/extra"
|
||||
|
||||
# payjsapi source
|
||||
sudo tar -C /www/wwwroot/payjsapi -czf "$OUT/payjsapi.tgz" \
|
||||
--exclude=venv --exclude=.git --exclude='*.log' --exclude='*.bak*' \
|
||||
--exclude='.env' --exclude='.env.local' \
|
||||
app run.py requirements.txt README.md payjs.sh androidh5api.sh \
|
||||
run-with-logs.sh run-with-logs.bat .env.example .gitignore \
|
||||
'手机微信支付调试说明.md' 2>/dev/null || \
|
||||
sudo tar -C /www/wwwroot/payjsapi -czf "$OUT/payjsapi.tgz" \
|
||||
--exclude=venv --exclude=.git --exclude='*.log' --exclude='*.bak*' \
|
||||
--exclude='.env' --exclude='.env.local' .
|
||||
|
||||
# env keys only for payjsapi
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
for name in ['.env','.env.local','.env.example']:
|
||||
p=Path('/www/wwwroot/payjsapi')/name
|
||||
if not p.exists(): continue
|
||||
lines=[]
|
||||
for line in p.read_text('utf-8','ignore').splitlines():
|
||||
if not line.strip() or line.strip().startswith('#') or '=' not in line:
|
||||
lines.append(line); continue
|
||||
lines.append(line.split('=',1)[0]+'=')
|
||||
Path('/tmp/hackrobot_backends_keys_pay').write_text('\n'.join(lines)+'\n','utf-8')
|
||||
break
|
||||
PY
|
||||
cp /tmp/hackrobot_backends_keys_pay "$OUT/extra/payjsapi.env.keys.example" 2>/dev/null || true
|
||||
|
||||
# full nomadmini (no venv/env/bak)
|
||||
sudo tar -C /opt/nomadmini -czf "$OUT/nomadmini.tgz" \
|
||||
--exclude='backend/.venv' --exclude='**/__pycache__' --exclude='**/*.pyc' \
|
||||
--exclude='**/.env' --exclude='**/.env.*' --exclude='**/*.bak*' \
|
||||
--exclude='**/*.db' --exclude='.git' .
|
||||
|
||||
# vip-track source only
|
||||
sudo tar -C /opt/vip-track -czf "$OUT/vip-track.tgz" \
|
||||
server.py vip-track.js healthcheck.sh \
|
||||
--exclude='.env' --exclude='ntfy.env' --exclude='*.db' --exclude='__pycache__' 2>/dev/null || \
|
||||
sudo tar -C /opt/vip-track -czf "$OUT/vip-track.tgz" \
|
||||
--exclude='.env' --exclude='ntfy.env' --exclude='*.db' --exclude='__pycache__' \
|
||||
--exclude='*.log' --exclude='health.state' --exclude='health.streak' .
|
||||
|
||||
# pocketbase: binary too big optional — ship script + types + schema dump
|
||||
mkdir -p "$OUT/pb"
|
||||
cp /home/ubuntu/pocketbase.sh "$OUT/pb/" 2>/dev/null || true
|
||||
cp /home/ubuntu/pb_data/types.d.ts "$OUT/pb/" 2>/dev/null || true
|
||||
# sqlite schema (no row data)
|
||||
sqlite3 /home/ubuntu/pb_data/data.db '.schema' > "$OUT/pb/data.schema.sql" 2>/dev/null || true
|
||||
# collection list via sqlite
|
||||
sqlite3 /home/ubuntu/pb_data/data.db "SELECT name FROM sqlite_master WHERE type='table';" > "$OUT/pb/tables.txt" 2>/dev/null || true
|
||||
# compact data.db copy for local restore (2MB) — user asked for backend
|
||||
cp /home/ubuntu/pb_data/data.db "$OUT/pb/data.db" 2>/dev/null || true
|
||||
sudo tar -C "$OUT/pb" -czf "$OUT/pocketbase-schema.tgz" .
|
||||
|
||||
# vip Next API surface checklist
|
||||
find /www/wwwroot/nomadvip/app/api -type f -name '*.ts' | sort > "$OUT/extra/vip-api-routes.txt"
|
||||
# also pack app/api alone for safety overwrite
|
||||
sudo tar -C /www/wwwroot/nomadvip -czf "$OUT/vip-api.tgz" app/api app/lib
|
||||
|
||||
python3 - <<PY
|
||||
import json,time
|
||||
from pathlib import Path
|
||||
out=Path('$OUT')
|
||||
meta={
|
||||
'pulled_at': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
|
||||
'files': {p.name: p.stat().st_size for p in out.glob('*.tgz')},
|
||||
}
|
||||
(out/'MANIFEST.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2))
|
||||
print(json.dumps(meta,indent=2))
|
||||
PY
|
||||
sudo rm -f /tmp/hackrobot_backends_bundle.tgz
|
||||
sudo tar -C "$OUT" -czf /tmp/hackrobot_backends_bundle.tgz .
|
||||
sudo chown ubuntu:ubuntu /tmp/hackrobot_backends_bundle.tgz
|
||||
ls -lah /tmp/hackrobot_backends_bundle.tgz
|
||||
echo BUNDLE_OK
|
||||
"""
|
||||
|
||||
|
||||
def wipe_dir(dest: Path) -> None:
|
||||
if not dest.exists():
|
||||
dest.mkdir(parents=True)
|
||||
return
|
||||
for child in dest.iterdir():
|
||||
if child.name in {".gitkeep", ".gitignore"}:
|
||||
continue
|
||||
if child.is_dir():
|
||||
shutil.rmtree(child)
|
||||
else:
|
||||
child.unlink()
|
||||
|
||||
|
||||
def extract(tgz: Path, dest: Path) -> None:
|
||||
wipe_dir(dest)
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(tgz, "r:gz") as tar:
|
||||
for m in tar.getmembers():
|
||||
name = m.name.replace("\r", "").replace("\n", "").strip()
|
||||
if not name or ".." in Path(name).parts:
|
||||
continue
|
||||
if ".bak" in name.lower() or name.endswith(".pyc") or "__pycache__" in name:
|
||||
continue
|
||||
m.name = name
|
||||
try:
|
||||
tar.extract(m, path=dest)
|
||||
except OSError as e:
|
||||
print("[skip bad]", name, e)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||
print("[remote] packing backends…")
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(300)
|
||||
chan.get_pty()
|
||||
chan.exec_command(REMOTE)
|
||||
out = b""
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
out += chunk
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
if b"BUNDLE_OK" not in out:
|
||||
raise SystemExit("pack failed")
|
||||
|
||||
cache = ROOT / "deploy" / ".cache"
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
bundle = cache / "hackrobot_backends_bundle.tgz"
|
||||
sftp = c.open_sftp()
|
||||
sftp.get("/tmp/hackrobot_backends_bundle.tgz", str(bundle))
|
||||
sftp.close()
|
||||
c.close()
|
||||
print("[local]", bundle.stat().st_size)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td_path = Path(td)
|
||||
with tarfile.open(bundle, "r:gz") as tar:
|
||||
tar.extractall(td_path)
|
||||
|
||||
mapping = {
|
||||
"payjsapi.tgz": ROOT / "payjsapi",
|
||||
"nomadmini.tgz": ROOT / "nomadmini",
|
||||
"vip-track.tgz": ROOT / "vip-track",
|
||||
"pocketbase-schema.tgz": ROOT / "pocketbase",
|
||||
}
|
||||
for name, dest in mapping.items():
|
||||
src = td_path / name
|
||||
if src.exists():
|
||||
extract(src, dest)
|
||||
print("[ok]", name, "→", dest)
|
||||
|
||||
# merge vip API into vip/
|
||||
vip_api = td_path / "vip-api.tgz"
|
||||
if vip_api.exists():
|
||||
vip_dest = ROOT / "vip"
|
||||
with tarfile.open(vip_api, "r:gz") as tar:
|
||||
tar.extractall(vip_dest)
|
||||
print("[ok] vip-api → vip/app/api + vip/app/lib")
|
||||
|
||||
extra = td_path / "extra"
|
||||
if extra.exists():
|
||||
for f in extra.iterdir():
|
||||
if f.name.endswith("payjsapi.env.keys.example"):
|
||||
(ROOT / "payjsapi" / "payjsapi.env.keys.example").write_bytes(f.read_bytes())
|
||||
elif f.name == "vip-api-routes.txt":
|
||||
(ROOT / "BACKEND_API_ROUTES.txt").write_bytes(f.read_bytes())
|
||||
print("[extra]", f.name)
|
||||
|
||||
man = td_path / "MANIFEST.json"
|
||||
if man.exists():
|
||||
prev = {}
|
||||
mp = ROOT / "SYNC_MANIFEST.json"
|
||||
if mp.exists():
|
||||
try:
|
||||
prev = json.loads(mp.read_text("utf-8"))
|
||||
except Exception:
|
||||
prev = {}
|
||||
cur = json.loads(man.read_text("utf-8"))
|
||||
prev["backends"] = cur
|
||||
prev["backends_pulled_at"] = cur.get("pulled_at")
|
||||
mp.write_text(json.dumps(prev, ensure_ascii=False, indent=2), "utf-8")
|
||||
|
||||
# scrub secrets if any slipped
|
||||
for p in ROOT.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
if p.name.startswith(".env") and "example" not in p.name and "keys" not in p.name:
|
||||
print("[scrub]", p)
|
||||
p.unlink()
|
||||
if p.suffix == ".db" and "pocketbase" not in str(p).replace("\\", "/"):
|
||||
# keep pocketbase/data.db only
|
||||
if "pocketbase" not in p.parts:
|
||||
print("[scrub db]", p)
|
||||
p.unlink()
|
||||
|
||||
print("[done]")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
199
apps/hackrobot/deploy/pull_from_129.py
Normal file
@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Pull live VIP stack from 129 → apps/hackrobot/ (no secrets, no node_modules/.next).
|
||||
|
||||
Targets:
|
||||
- vip.hackrobot.cn → apps/hackrobot/vip (/www/wwwroot/nomadvip)
|
||||
- admin.hackrobot.cn → apps/hackrobot/admin-site
|
||||
- nomadmini :8010 → apps/hackrobot/nomadmini
|
||||
- vip-track :4011 → apps/hackrobot/vip-track (optional)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
|
||||
ROOT = Path(__file__).resolve().parents[1] # apps/hackrobot
|
||||
|
||||
REMOTE_PACK = r"""
|
||||
set -e
|
||||
OUT=/tmp/hackrobot_sync_$$
|
||||
mkdir -p "$OUT"
|
||||
|
||||
# VIP Next source (exclude heavy/secrets)
|
||||
sudo tar -C /www/wwwroot/nomadvip -czf "$OUT/vip-src.tgz" \
|
||||
--exclude=node_modules --exclude=.next --exclude=.git \
|
||||
--exclude='.env' --exclude='.env.local' --exclude='.env.*.local' \
|
||||
app lib public scripts config data docs \
|
||||
package.json pnpm-lock.yaml pnpm-workspace.yaml \
|
||||
next.config.ts tsconfig.json postcss.config.mjs eslint.config.mjs \
|
||||
middleware.ts next-env.d.ts README.md vip.sh .env.example .gitignore 2>/dev/null || true
|
||||
|
||||
# env example keys only
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
src=Path('/www/wwwroot/nomadvip/.env.local')
|
||||
dst=Path('/tmp/hackrobot_sync_envkeys')
|
||||
if src.exists():
|
||||
lines=[]
|
||||
for line in src.read_text('utf-8','ignore').splitlines():
|
||||
if not line.strip() or line.strip().startswith('#'):
|
||||
lines.append(line); continue
|
||||
if '=' in line:
|
||||
k=line.split('=',1)[0]
|
||||
lines.append(f'{k}=')
|
||||
else:
|
||||
lines.append(line)
|
||||
Path('/tmp').joinpath('vip.env.example.keys').write_text('\n'.join(lines)+'\n','utf-8')
|
||||
PY
|
||||
if [ -f /tmp/vip.env.example.keys ]; then
|
||||
# fold into pack dir
|
||||
mkdir -p "$OUT/extra"
|
||||
cp /tmp/vip.env.example.keys "$OUT/extra/vip.env.keys.example"
|
||||
fi
|
||||
|
||||
# Admin SPA live site
|
||||
sudo tar -C /www/wwwroot/admin.hackrobot.cn -czf "$OUT/admin-site.tgz" \
|
||||
--exclude='*.bak*' .
|
||||
|
||||
# nomadmini backend (no venv)
|
||||
if [ -d /opt/nomadmini ]; then
|
||||
sudo tar -C /opt/nomadmini -czf "$OUT/nomadmini.tgz" \
|
||||
--exclude='backend/.venv' --exclude='**/__pycache__' --exclude='**/.env' \
|
||||
--exclude='**/.git' --exclude='node_modules' .
|
||||
fi
|
||||
|
||||
# vip-track
|
||||
if [ -d /opt/vip-track ]; then
|
||||
sudo tar -C /opt/vip-track -czf "$OUT/vip-track.tgz" \
|
||||
--exclude='.venv' --exclude='**/__pycache__' --exclude='.env' --exclude='.git' .
|
||||
fi
|
||||
|
||||
# nginx snippets (reference)
|
||||
mkdir -p "$OUT/nginx"
|
||||
sudo cp -a /www/server/panel/vhost/nginx/vip.hackrobot.cn.conf "$OUT/nginx/" 2>/dev/null || true
|
||||
sudo cp -a /www/server/panel/vhost/nginx/admin.hackrobot.cn.conf "$OUT/nginx/" 2>/dev/null || true
|
||||
sudo cp -a /www/server/panel/vhost/nginx/extension/vip.hackrobot.cn "$OUT/nginx/ext-vip" 2>/dev/null || true
|
||||
sudo cp -a /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn "$OUT/nginx/ext-admin" 2>/dev/null || true
|
||||
sudo tar -C "$OUT/nginx" -czf "$OUT/nginx-ref.tgz" .
|
||||
|
||||
# manifest
|
||||
python3 - <<PY
|
||||
import json, os, time
|
||||
from pathlib import Path
|
||||
out=Path('$OUT')
|
||||
files={p.name: p.stat().st_size for p in out.glob('*.tgz')}
|
||||
meta={
|
||||
'host':'129.204.21.129',
|
||||
'pulled_at': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
|
||||
'files': files,
|
||||
'notes': {
|
||||
'vip': '/www/wwwroot/nomadvip → next :4007 = vip.hackrobot.cn',
|
||||
'admin': '/www/wwwroot/admin.hackrobot.cn static SPA',
|
||||
'nomadmini': '/opt/nomadmini → :8010 live ops',
|
||||
'vip_track': '/opt/vip-track → :4011',
|
||||
}
|
||||
}
|
||||
(out/'MANIFEST.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2),'utf-8')
|
||||
print(json.dumps(meta,ensure_ascii=False,indent=2))
|
||||
PY
|
||||
|
||||
# single bundle for scp
|
||||
sudo tar -C "$OUT" -czf /tmp/hackrobot_sync_bundle.tgz .
|
||||
sudo chown ubuntu:ubuntu /tmp/hackrobot_sync_bundle.tgz
|
||||
ls -lah /tmp/hackrobot_sync_bundle.tgz
|
||||
echo "BUNDLE_OK:/tmp/hackrobot_sync_bundle.tgz"
|
||||
"""
|
||||
|
||||
|
||||
def extract_into(tgz: Path, dest: Path) -> None:
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(tgz, "r:gz") as tar:
|
||||
tar.extractall(dest)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||
print("[remote] packing…")
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(300)
|
||||
chan.get_pty()
|
||||
chan.exec_command(REMOTE_PACK)
|
||||
out = b""
|
||||
while True:
|
||||
chunk = chan.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
out += chunk
|
||||
print(chunk.decode("utf-8", "replace"), end="", flush=True)
|
||||
if b"BUNDLE_OK" not in out:
|
||||
raise SystemExit("remote pack failed")
|
||||
|
||||
local_bundle = ROOT / "deploy" / ".cache" / "hackrobot_sync_bundle.tgz"
|
||||
local_bundle.parent.mkdir(parents=True, exist_ok=True)
|
||||
print("[scp] downloading bundle…")
|
||||
sftp = c.open_sftp()
|
||||
sftp.get("/tmp/hackrobot_sync_bundle.tgz", str(local_bundle))
|
||||
sftp.close()
|
||||
c.close()
|
||||
print("[local]", local_bundle, local_bundle.stat().st_size)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td_path = Path(td)
|
||||
with tarfile.open(local_bundle, "r:gz") as tar:
|
||||
tar.extractall(td_path)
|
||||
|
||||
mapping = {
|
||||
"vip-src.tgz": ROOT / "vip",
|
||||
"admin-site.tgz": ROOT / "admin-site",
|
||||
"nomadmini.tgz": ROOT / "nomadmini",
|
||||
"vip-track.tgz": ROOT / "vip-track",
|
||||
"nginx-ref.tgz": ROOT / "nginx-ref",
|
||||
}
|
||||
for name, dest in mapping.items():
|
||||
src = td_path / name
|
||||
if not src.exists():
|
||||
print("[skip]", name)
|
||||
continue
|
||||
if dest.exists():
|
||||
# wipe tracked content carefully: keep .gitkeep only if empty after
|
||||
for child in dest.iterdir():
|
||||
if child.name == ".gitkeep":
|
||||
continue
|
||||
if child.is_dir():
|
||||
import shutil
|
||||
|
||||
shutil.rmtree(child)
|
||||
else:
|
||||
child.unlink()
|
||||
else:
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
extract_into(src, dest)
|
||||
print("[ok]", name, "→", dest)
|
||||
|
||||
# extras
|
||||
extra = td_path / "extra"
|
||||
if extra.exists():
|
||||
(ROOT / "vip").mkdir(exist_ok=True)
|
||||
for f in extra.iterdir():
|
||||
target = ROOT / "vip" / f.name
|
||||
target.write_bytes(f.read_bytes())
|
||||
print("[extra]", target)
|
||||
|
||||
manifest = td_path / "MANIFEST.json"
|
||||
if manifest.exists():
|
||||
(ROOT / "SYNC_MANIFEST.json").write_bytes(manifest.read_bytes())
|
||||
print("[manifest]", ROOT / "SYNC_MANIFEST.json")
|
||||
|
||||
print("[done] synced under", ROOT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
76
apps/hackrobot/nginx-ref/admin.hackrobot.cn.conf
Normal file
@ -0,0 +1,76 @@
|
||||
server
|
||||
{
|
||||
listen 80;
|
||||
server_name admin.hackrobot.cn;
|
||||
#CERT-APPLY-CHECK--START
|
||||
include /www/server/panel/vhost/nginx/well-known/admin.hackrobot.cn.conf;
|
||||
#CERT-APPLY-CHECK--END
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /www/wwwroot/admin.hackrobot.cn;
|
||||
default_type text/plain;
|
||||
}
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server
|
||||
{
|
||||
listen 443 ssl http2;
|
||||
server_name admin.hackrobot.cn;
|
||||
index index.html;
|
||||
root /www/wwwroot/admin.hackrobot.cn;
|
||||
|
||||
#SSL-START
|
||||
ssl_certificate /www/server/panel/vhost/cert/admin.hackrobot.cn/fullchain.pem;
|
||||
ssl_certificate_key /www/server/panel/vhost/cert/admin.hackrobot.cn/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
add_header Strict-Transport-Security "max-age=31536000";
|
||||
error_page 497 https://$host$request_uri;
|
||||
#SSL-END
|
||||
|
||||
# Live ops SSE/API (more specific than /api/)
|
||||
include /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn/*.conf;
|
||||
|
||||
# Ops API -> VIP next (4007) /api/ops /api/ops. Do NOT send to VIP Next 4007.
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://127.0.0.1:4007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
add_header Cache-Control "no-store" always;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 3600s;
|
||||
}
|
||||
|
||||
location = /robots.txt {
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\nDisallow: /\n";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
access_log /www/wwwlogs/admin.hackrobot.cn.log;
|
||||
error_log /www/wwwlogs/admin.hackrobot.cn.error.log;
|
||||
}
|
||||
13
apps/hackrobot/nginx-ref/ext-admin/admin-live-sse.conf
Normal file
@ -0,0 +1,13 @@
|
||||
location ^~ /api/admin/live/ {
|
||||
proxy_pass http://127.0.0.1:8010;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Connection '';
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 3600s;
|
||||
chunked_transfer_encoding off;
|
||||
}
|
||||
70
apps/hackrobot/nginx-ref/ext-vip/security-harden.conf
Normal file
@ -0,0 +1,70 @@
|
||||
# VIP anti-recon / anti-AI-scan hardening (extension)
|
||||
# More-specific ^~ locations beat the catch-all proxy ^~ /
|
||||
|
||||
# ---- Sensitive / recon paths: silent 404 ----
|
||||
location ~* \.(?:map|env|bak|old|orig|swp|sql|tar|gz|zip|7z|rar|log|yml|yaml|toml|ini|pem|key)$ {
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.probe.log;
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~* (?:/\.git|/node_modules|/\.next/|/\.pnpm|/vendor|/phpmyadmin|/wp-admin|/wp-login|/actuator|/server-status|/debug|/config\.json|/package\.json|/composer\.json|/Dockerfile|/docker-compose) {
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.probe.log;
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~* ^/(?:\.env(?:\..*)?|\.git(?:/.*)?|\.svn|\.hg|\.DS_Store|id_rsa|id_ed25519|web\.config|\.htaccess|\.user\.ini)$ {
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.probe.log;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Honey paths often probed by scanners / LLM agents
|
||||
location ~* ^/(?:api/(?:debug|admin|config|internal|test|v1/admin|swagger|openapi)|\.well-known/security\.txt|telescope|horizon|graphql|console)$ {
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.probe.log;
|
||||
default_type application/json;
|
||||
return 404 '{"ok":false,"error":"not found"}';
|
||||
}
|
||||
|
||||
# Block source maps under _next even if built
|
||||
location ~* ^/_next/.*\.map$ {
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.probe.log;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Pay API: no cache + tighter proxy (longest ^~ prefix wins over /)
|
||||
location ^~ /api/pay {
|
||||
proxy_pass http://127.0.0.1:4007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_hide_header X-Powered-By;
|
||||
proxy_hide_header x-powered-by;
|
||||
proxy_hide_header X-Nextjs-Cache;
|
||||
proxy_hide_header X-Nextjs-Prerender;
|
||||
proxy_hide_header X-Nextjs-Stale-Time;
|
||||
proxy_hide_header x-nextjs-cache;
|
||||
proxy_hide_header x-nextjs-prerender;
|
||||
proxy_hide_header x-nextjs-stale-time;
|
||||
add_header Cache-Control "no-store" always;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 60s;
|
||||
# basic flood control if zone exists; ignore if not
|
||||
# limit_req zone=vip_pay burst=8 nodelay;
|
||||
}
|
||||
|
||||
location ^~ /api/vip {
|
||||
proxy_pass http://127.0.0.1:4007;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host 127.0.0.1;
|
||||
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_hide_header X-Powered-By;
|
||||
proxy_hide_header X-Nextjs-Cache;
|
||||
proxy_hide_header X-Nextjs-Prerender;
|
||||
proxy_hide_header X-Nextjs-Stale-Time;
|
||||
add_header Cache-Control "no-store" always;
|
||||
}
|
||||
2
apps/hackrobot/nginx-ref/ext-vip/site_total.conf
Normal file
@ -0,0 +1,2 @@
|
||||
add_header Set-Cookie $uid_cookie_value always;
|
||||
access_log syslog:server=unix:/tmp/site_total.sock,nohostname,tag=2__access site_total;
|
||||
22
apps/hackrobot/nginx-ref/ext-vip/track-api.conf
Normal file
@ -0,0 +1,22 @@
|
||||
# VIP track sidecar — isolate from Next (no vip restart)
|
||||
location = /api/track {
|
||||
proxy_pass http://127.0.0.1:4011;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_read_timeout 5s;
|
||||
}
|
||||
|
||||
# 微信用户列表 CRUD(需 ops token)
|
||||
location ^~ /api/wechat-users {
|
||||
proxy_pass http://127.0.0.1:4011;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_read_timeout 20s;
|
||||
}
|
||||
6
apps/hackrobot/nginx-ref/ext-vip/track-js.conf
Normal file
@ -0,0 +1,6 @@
|
||||
location = /vip-track.js {
|
||||
alias /opt/vip-track/vip-track.js;
|
||||
default_type application/javascript;
|
||||
add_header Cache-Control "no-cache";
|
||||
add_header Access-Control-Allow-Origin *;
|
||||
}
|
||||
16
apps/hackrobot/nginx-ref/ext-vip/vip-live-api.conf
Normal file
@ -0,0 +1,16 @@
|
||||
location ^~ /api/vip/live/ {
|
||||
proxy_pass http://127.0.0.1:8010;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Connection '';
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 3600s;
|
||||
chunked_transfer_encoding off;
|
||||
}
|
||||
location = /vip-live.js {
|
||||
root /www/wwwroot/nomadvip/public;
|
||||
add_header Cache-Control "public, max-age=60";
|
||||
}
|
||||
69
apps/hackrobot/nginx-ref/vip.hackrobot.cn.conf
Normal file
@ -0,0 +1,69 @@
|
||||
server
|
||||
{
|
||||
listen 80;
|
||||
listen 443 ssl http2 ;
|
||||
server_name vip.hackrobot.cn;
|
||||
index index.php index.html index.htm default.php default.htm default.html;
|
||||
root /www/wwwroot/vipgroup/dist;
|
||||
include /www/server/panel/vhost/nginx/extension/vip.hackrobot.cn/*.conf;
|
||||
|
||||
#CERT-APPLY-CHECK--START
|
||||
# Configuration related to file verification for SSL certificate application - Do not delete
|
||||
include /www/server/panel/vhost/nginx/well-known/vip.hackrobot.cn.conf;
|
||||
#CERT-APPLY-CHECK--END
|
||||
#SSL-START SSL related configuration, do NOT delete or modify the next line of commented-out 404 rules
|
||||
#error_page 404/404.html;
|
||||
ssl_certificate /www/server/panel/vhost/cert/vip.hackrobot.cn/fullchain.pem;
|
||||
ssl_certificate_key /www/server/panel/vhost/cert/vip.hackrobot.cn/privkey.pem;
|
||||
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_tickets on;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
add_header Strict-Transport-Security "max-age=31536000";
|
||||
error_page 497 https://$host$request_uri;
|
||||
|
||||
#SSL-END
|
||||
|
||||
#ERROR-PAGE-START Error page configuration, allowed to be commented, deleted or modified
|
||||
error_page 404 /404.html;
|
||||
error_page 502 /502.html;
|
||||
#ERROR-PAGE-END
|
||||
|
||||
#PHP-INFO-START PHP reference configuration, allowed to be commented, deleted or modified
|
||||
#Clear cache
|
||||
|
||||
location ~ /purge(/.*) {
|
||||
proxy_cache_purge cache_one $host$1$is_args$args;
|
||||
#access_log /www/wwwlogs/vip.hackrobot.cn_purge_cache.log;
|
||||
}
|
||||
#Referenced reverse proxy rule, if commented, the configured reverse proxy will be invalid
|
||||
include /www/server/panel/vhost/nginx/proxy/vip.hackrobot.cn/*.conf;
|
||||
|
||||
include enable-php-00.conf;
|
||||
#PHP-INFO-END
|
||||
|
||||
#REWRITE-START URL rewrite rule reference, any modification will invalidate the rewrite rules set by the panel
|
||||
include /www/server/panel/vhost/rewrite/vip.hackrobot.cn.conf;
|
||||
#REWRITE-END
|
||||
|
||||
# Forbidden files or directories
|
||||
location ~ ^/(\.user.ini|\.htaccess|\.git|\.env|\.svn|\.project|LICENSE|README.md)
|
||||
{
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Directory verification related settings for one-click application for SSL certificate
|
||||
location ~ \.well-known{
|
||||
allow all;
|
||||
}
|
||||
|
||||
#Prohibit putting sensitive files in certificate verification directory
|
||||
if ( $uri ~ "^/\.well-known/.*\.(php|jsp|py|js|css|lua|ts|go|zip|tar\.gz|rar|7z|sql|bak)$" ) {
|
||||
return 403;
|
||||
}
|
||||
|
||||
access_log /www/wwwlogs/vip.hackrobot.cn.log;
|
||||
error_log /www/wwwlogs/vip.hackrobot.cn.error.log;
|
||||
}
|
||||
14
apps/hackrobot/nomadmini/backend/.env.example
Normal file
@ -0,0 +1,14 @@
|
||||
WX_APPID=wx11f6afc44ea1532f
|
||||
WX_SECRET=04214ecc910dca4526781c90bae94da1
|
||||
WX_OFFER_ID=1450705308
|
||||
WX_APP_KEY=JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY
|
||||
WX_SANDBOX_APP_KEY=BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi
|
||||
WX_PAY_ENV=0
|
||||
JWT_SECRET=change-me
|
||||
ADMIN_USERNAME=hackrobot
|
||||
ADMIN_PASSWORD=change-me
|
||||
PB_URL=http://127.0.0.1:8090
|
||||
USE_POCKETBASE=false
|
||||
DEBUG=false
|
||||
PUBLIC_API_BASE=https://api.nomadro.cn
|
||||
ADMIN_ORIGIN=https://admin.nomadro.cn
|
||||
1
apps/hackrobot/nomadmini/backend/app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Nomadmini backend package
|
||||
54
apps/hackrobot/nomadmini/backend/app/config.py
Normal file
@ -0,0 +1,54 @@
|
||||
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 = "nomadmini-api"
|
||||
debug: bool = True
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
public_api_base: str = "https://api.nomadro.cn"
|
||||
admin_origin: str = "https://admin.nomadro.cn"
|
||||
cors_origins: str = "https://admin.nomadro.cn,http://localhost:5173,http://127.0.0.1:5173"
|
||||
|
||||
# WeChat 虚拟支付(与 Nomadro 小程序对齐)
|
||||
wx_appid: str = "wx11f6afc44ea1532f"
|
||||
wx_secret: str = "04214ecc910dca4526781c90bae94da1"
|
||||
wx_offer_id: str = "1450705308"
|
||||
wx_app_key: str = "JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY" # 现网
|
||||
wx_sandbox_app_key: str = "BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi" # 沙箱
|
||||
wx_pay_env: int = 0 # 0 现网 / 1 沙箱
|
||||
|
||||
# JWT / Admin
|
||||
jwt_secret: str = "nomadro-jwt-local-dev-2026"
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = "Xiao4669805"
|
||||
|
||||
# PocketBase
|
||||
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/nomadmini.db"
|
||||
|
||||
# 抖音 platforms.tt 写入路径(默认自动探测门户 remote-config.json)
|
||||
tt_remote_config_path: str = ""
|
||||
|
||||
default_product_id: str = "youtube"
|
||||
default_price_fen: int = 18800
|
||||
default_unlock_percent: int = 30
|
||||
|
||||
wx_push_token: str = "hackrobot"
|
||||
wx_push_encoding_aes_key: str = "ulnyydH8LF4uWmdpzSgUiWS6hVXp1V3wp26MhEYeHkI"
|
||||
wx_allow_devtools_login: bool = True
|
||||
|
||||
# ntfy(自建 https://ntfy.nomadro.cn)
|
||||
ntfy_enabled: bool = True
|
||||
ntfy_base_url: str = "http://127.0.0.1:2586" # 机内直连,避免自签/回环 HTTPS
|
||||
ntfy_topic: str = "nomadmini"
|
||||
ntfy_token: str = ""
|
||||
|
||||
|
||||
settings = Settings()
|
||||
5
apps/hackrobot/nomadmini/backend/app/core/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""核心横切能力:鉴权 / SQLite / 限流。
|
||||
|
||||
注意:勿在此包级 import deps(会与 store 形成循环导入)。
|
||||
按需:`from ebook_svc.core.deps import get_current_openid`
|
||||
"""
|
||||
45
apps/hackrobot/nomadmini/backend/app/core/deps.py
Normal file
@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from app.services.store import store
|
||||
|
||||
# 鉴权成功时节流写 last_seen,减轻 SQLite 写入
|
||||
_LAST_TOUCH: dict[str, float] = {}
|
||||
_TOUCH_MIN_INTERVAL = 20.0
|
||||
|
||||
|
||||
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, "账号不可用")
|
||||
openid = str(user["openid"])
|
||||
now = time.time()
|
||||
prev = _LAST_TOUCH.get(openid, 0.0)
|
||||
if now - prev >= _TOUCH_MIN_INTERVAL:
|
||||
_LAST_TOUCH[openid] = now
|
||||
try:
|
||||
store.touch_last_seen(openid)
|
||||
except Exception:
|
||||
pass
|
||||
return openid
|
||||
|
||||
|
||||
async def get_optional_openid(
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
) -> str:
|
||||
"""登录则返回 openid;未登录返回空串(供免费/提审书匿名阅读)。"""
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
return ""
|
||||
try:
|
||||
return await get_current_openid(authorization)
|
||||
except HTTPException:
|
||||
return ""
|
||||
35
apps/hackrobot/nomadmini/backend/app/core/rate_limit.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""简易内存限流(单进程)。按 IP + 桶名滑动窗口。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from threading import Lock
|
||||
from typing import Deque
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_lock = Lock()
|
||||
_buckets: dict[str, Deque[float]] = defaultdict(deque)
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()[:64]
|
||||
if request.client and request.client.host:
|
||||
return request.client.host
|
||||
return "unknown"
|
||||
|
||||
|
||||
def rate_limit(request: Request, *, bucket: str, limit: int, window_sec: float) -> None:
|
||||
"""超出限制抛 429。"""
|
||||
key = f"{bucket}:{_client_ip(request)}"
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
q = _buckets[key]
|
||||
cutoff = now - window_sec
|
||||
while q and q[0] < cutoff:
|
||||
q.popleft()
|
||||
if len(q) >= limit:
|
||||
raise HTTPException(429, "请求过于频繁,请稍后再试")
|
||||
q.append(now)
|
||||
31
apps/hackrobot/nomadmini/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"
|
||||
19
apps/hackrobot/nomadmini/backend/app/core/sqlite_util.py
Normal file
@ -0,0 +1,19 @@
|
||||
"""SQLite 连接约定:WAL + busy_timeout,减轻并发写锁。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
|
||||
p = Path(path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
c = sqlite3.connect(str(p), timeout=timeout)
|
||||
c.row_factory = sqlite3.Row
|
||||
try:
|
||||
c.execute("PRAGMA journal_mode=WAL")
|
||||
c.execute(f"PRAGMA busy_timeout={int(timeout * 1000)}")
|
||||
c.execute("PRAGMA synchronous=NORMAL")
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
return c
|
||||
1
apps/hackrobot/nomadmini/backend/app/domains/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""按领域拆分的业务逻辑(与 HTTP router / infra 解耦)。"""
|
||||
@ -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",
|
||||
]
|
||||
223
apps/hackrobot/nomadmini/backend/app/domains/books/products.py
Normal file
@ -0,0 +1,223 @@
|
||||
"""虚拟支付道具目录(运营 SoT,与 apps/api ebook_svc 对齐)。
|
||||
|
||||
档位面向付费用户:名称是货架文案,product_id 是微信侧支付 SKU。
|
||||
价格单位:分。微信 MP「道具名称」≤10 字、「备注」≤50 字不对外。
|
||||
"""
|
||||
|
||||
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": "全书可读,不拉起支付",
|
||||
},
|
||||
{
|
||||
"key": "yen29",
|
||||
"label": "轻享",
|
||||
"name": "轻享全书",
|
||||
"product_id": "nomad_lite",
|
||||
"price_fen": 2900,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad_lite.png",
|
||||
"remark": "入门价·首次解锁单本推荐",
|
||||
},
|
||||
{
|
||||
"key": "nomad",
|
||||
"label": "漫游",
|
||||
"name": "漫游全书",
|
||||
"product_id": "nomad",
|
||||
"price_fen": 4900,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad.png",
|
||||
"remark": "标准漫游档·性价比主推",
|
||||
},
|
||||
{
|
||||
"key": "tiktok",
|
||||
"label": "短视频",
|
||||
"name": "短视频全书",
|
||||
"product_id": "tiktok",
|
||||
"price_fen": 8800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/tiktok.png",
|
||||
"remark": "短视频向专题全书",
|
||||
},
|
||||
{
|
||||
"key": "youtube",
|
||||
"label": "长视频",
|
||||
"name": "长视频全书",
|
||||
"product_id": "youtube",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/youtube.png",
|
||||
"remark": "长视频向·默认推荐档",
|
||||
},
|
||||
{
|
||||
"key": "ebook",
|
||||
"label": "经典",
|
||||
"name": "经典全书",
|
||||
"product_id": "ebook_unlock_default",
|
||||
"price_fen": 18800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/ebook.png",
|
||||
"remark": "历史默认档·兼容旧订单",
|
||||
},
|
||||
{
|
||||
"key": "yen298",
|
||||
"label": "进阶",
|
||||
"name": "进阶全书",
|
||||
"product_id": "nomad_plus",
|
||||
"price_fen": 29800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad_plus.png",
|
||||
"remark": "进阶价·高价值小册",
|
||||
},
|
||||
{
|
||||
"key": "yen588",
|
||||
"label": "精英",
|
||||
"name": "精英全书",
|
||||
"product_id": "nomad_pro",
|
||||
"price_fen": 58800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/nomad_pro.png",
|
||||
"remark": "精英价·深度专题册",
|
||||
},
|
||||
{
|
||||
"key": "svip",
|
||||
"label": "超级会员",
|
||||
"name": "超级会员",
|
||||
"product_id": "svip",
|
||||
"price_fen": 99800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/svip.png",
|
||||
"remark": "旗舰会员·最高权益档",
|
||||
},
|
||||
{
|
||||
"key": "test",
|
||||
"label": "联调",
|
||||
"name": "联调占位",
|
||||
"product_id": "pay_test",
|
||||
"price_fen": 100,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/pay_test.png",
|
||||
"remark": "仅内部联调·禁止对用户上架",
|
||||
},
|
||||
]
|
||||
|
||||
_LEGACY_PRODUCT_IDS = {
|
||||
"29": "yen29",
|
||||
"298": "yen298",
|
||||
"588": "yen588",
|
||||
"test": "test",
|
||||
"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 "")
|
||||
for offer in PRODUCT_OFFERS:
|
||||
if offer["free"]:
|
||||
continue
|
||||
if offer["product_id"] == pid or offer["key"] == pid:
|
||||
return offer
|
||||
mapped = _LEGACY_PRODUCT_IDS.get(pid, pid)
|
||||
if mapped != pid:
|
||||
for offer in PRODUCT_OFFERS:
|
||||
if offer["free"]:
|
||||
continue
|
||||
if 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": int((book or {}).get("unlock_percent") or 30),
|
||||
"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 or o["label"] == 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}"
|
||||
@ -0,0 +1,113 @@
|
||||
"""试读截断策略:按全书正文字符数百分比裁剪。 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.get("id") or f"ch-{i + 1}",
|
||||
"title": c.get("title") or f"章节 {i + 1}",
|
||||
"order": int(c["order"]) if c.get("order") is not None else i + 1,
|
||||
}
|
||||
for i, c in enumerate(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/hackrobot/nomadmini/backend/app/jobs/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""后台定时任务。"""
|
||||
|
||||
from .reconcile import reconcile_pending_orders
|
||||
|
||||
__all__ = ["reconcile_pending_orders"]
|
||||
23
apps/hackrobot/nomadmini/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
|
||||
135
apps/hackrobot/nomadmini/backend/app/main.py
Normal file
@ -0,0 +1,135 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
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.jobs import reconcile_pending_orders
|
||||
from app.routers import (
|
||||
admin,
|
||||
auth,
|
||||
books,
|
||||
douyin_admin,
|
||||
join_group_admin,
|
||||
memo,
|
||||
memo_admin,
|
||||
nav_admin,
|
||||
pay,
|
||||
public_config,
|
||||
shop,
|
||||
shop_admin,
|
||||
track,
|
||||
vip_admin,
|
||||
vip_bridge,
|
||||
vip_library_admin,
|
||||
vip_library_public,
|
||||
)
|
||||
|
||||
scheduler = AsyncIOScheduler()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
scheduler.add_job(reconcile_pending_orders, "interval", minutes=5, id="xpay_query")
|
||||
scheduler.start()
|
||||
yield
|
||||
scheduler.shutdown(wait=False)
|
||||
|
||||
|
||||
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=["*"],
|
||||
)
|
||||
|
||||
# 老小程序 / 微信回调:/api/*
|
||||
# 门户 miniprogram:/api/ebook/*(同进程别名,共享 store)
|
||||
for _api_prefix in ("/api", "/api/ebook"):
|
||||
app.include_router(auth.router, prefix=_api_prefix)
|
||||
app.include_router(vip_bridge.router, prefix=_api_prefix)
|
||||
app.include_router(books.router, prefix=_api_prefix)
|
||||
app.include_router(pay.router, prefix=_api_prefix)
|
||||
app.include_router(track.router, prefix=_api_prefix)
|
||||
app.include_router(shop.router, prefix=_api_prefix)
|
||||
app.include_router(memo.router, prefix=_api_prefix)
|
||||
|
||||
# Admin 仅挂 /api/admin(admin.nomadro.cn),避免双后台路径
|
||||
app.include_router(admin.router)
|
||||
# 抖音定制面板(与微信读者/订单隔离)
|
||||
app.include_router(douyin_admin.router)
|
||||
# 加群引导开关(微信公众号 / 抖音群)
|
||||
app.include_router(join_group_admin.router)
|
||||
# 微信 VIP / 加群行为 / 3D 入口
|
||||
app.include_router(vip_admin.router)
|
||||
# VIP 正式内容(电子书 / 视频课)
|
||||
app.include_router(vip_library_admin.router)
|
||||
app.include_router(vip_library_public.router)
|
||||
# 电商(商品 / 卡密 / 发货)
|
||||
app.include_router(shop_admin.router)
|
||||
# VIP 私密社群(类微博)
|
||||
app.include_router(memo_admin.router)
|
||||
# 导航远程 CRUD(navContent)
|
||||
app.include_router(nav_admin.router)
|
||||
# 微信「开关」总控(页面/入口/文案/小册审核)
|
||||
from app.routers import weapp_switches_admin, google_admin, social_blog_admin
|
||||
from app.routers import social_ops_admin
|
||||
from app.routers import social_ugc_admin # noqa: E402
|
||||
from app.routers import community_admin # noqa: E402 # noqa: E402 # noqa: E402
|
||||
|
||||
app.include_router(weapp_switches_admin.router)
|
||||
app.include_router(google_admin.router)
|
||||
app.include_router(social_blog_admin.router)
|
||||
app.include_router(social_ops_admin.router)
|
||||
app.include_router(social_ugc_admin.router)
|
||||
app.include_router(community_admin.router)
|
||||
|
||||
# 运营:ntfy 状态 / 试推(admin.nomadro.com)
|
||||
from app.routers import ops_admin # noqa: E402
|
||||
|
||||
app.include_router(ops_admin.router)
|
||||
from app.routers import audience_admin # noqa: E402
|
||||
app.include_router(audience_admin.router)
|
||||
from app.routers import live_ops
|
||||
app.include_router(live_ops.router)
|
||||
|
||||
|
||||
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
||||
app.include_router(public_config.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
@app.get("/api/ebook/health")
|
||||
async def health():
|
||||
return {"ok": True, "service": "nomadmini-api"}
|
||||
|
||||
|
||||
# 可选:同域托管 admin(生产建议由 nginx 单独托管 admin.nomadro.cn)
|
||||
ADMIN_DIST = Path(__file__).resolve().parents[2] / "admin" / "dist"
|
||||
if settings.debug and ADMIN_DIST.exists():
|
||||
app.mount("/admin-assets", StaticFiles(directory=ADMIN_DIST), 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/hackrobot/nomadmini/backend/app/models/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
# 占位:领域 Pydantic 已迁至 app/schemas/
|
||||
# 后续可将 ORM / 持久化实体放此处。
|
||||
1
apps/hackrobot/nomadmini/backend/app/routers/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# routers
|
||||
477
apps/hackrobot/nomadmini/backend/app/routers/admin.py
Normal file
@ -0,0 +1,477 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.config import settings
|
||||
from app.core.security import create_admin_token, require_admin
|
||||
from app.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
|
||||
from app.schemas.admin import (
|
||||
AdminLoginBody,
|
||||
BookCreateBody,
|
||||
BookPatch,
|
||||
ManualUnlockBody,
|
||||
MarkdownImportBody,
|
||||
OfferApplyBody,
|
||||
OrderStatusBody,
|
||||
RevokeUnlockBody,
|
||||
UserPatchBody,
|
||||
)
|
||||
from app.services.pocketbase import pb
|
||||
from app.services.store import store
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def admin_login(body: AdminLoginBody):
|
||||
if body.username != settings.admin_username or body.password != settings.admin_password:
|
||||
raise HTTPException(401, "用户名或密码错误")
|
||||
return {"token": create_admin_token(body.username), "username": body.username}
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
async def admin_stats(_: str = Depends(require_admin)):
|
||||
return store.stats()
|
||||
|
||||
|
||||
@router.get("/track-events")
|
||||
async def admin_track_events(
|
||||
limit: int = 100,
|
||||
name: str = "",
|
||||
client: str = "",
|
||||
_: str = Depends(require_admin),
|
||||
):
|
||||
lim = max(1, min(limit, 500))
|
||||
return store.list_track_events(limit=lim, name=name, client=client)
|
||||
|
||||
|
||||
@router.get("/track-analytics")
|
||||
async def admin_track_analytics(
|
||||
days: int = 14,
|
||||
client: str = "",
|
||||
_: str = Depends(require_admin),
|
||||
):
|
||||
"""用户分析:独立访客(Fingerprint visitorId / openid)、DAU、漏斗、端与页面排行。"""
|
||||
return store.track_analytics(days=days, client=client)
|
||||
|
||||
|
||||
@router.get("/track-visitor")
|
||||
async def admin_track_visitor(
|
||||
visitorId: str = "",
|
||||
openid: str = "",
|
||||
days: int = 14,
|
||||
limit: int = 200,
|
||||
client: str = "",
|
||||
_: str = Depends(require_admin),
|
||||
):
|
||||
"""单个访客访问明细时间线。"""
|
||||
data = store.list_visitor_timeline(
|
||||
visitor_id=visitorId,
|
||||
openid=openid,
|
||||
days=days,
|
||||
limit=limit,
|
||||
client=client,
|
||||
)
|
||||
if not data.get("ok"):
|
||||
raise HTTPException(400, str(data.get("error") or "参数错误"))
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/product-offers")
|
||||
async def admin_product_offers(_: str = Depends(require_admin)):
|
||||
"""免费 + 4 个道具方案目录。"""
|
||||
return {"items": offer_public_list()}
|
||||
|
||||
|
||||
@router.get("/books")
|
||||
async def admin_books(_: str = Depends(require_admin)):
|
||||
return store.list_books()
|
||||
|
||||
|
||||
@router.post("/books")
|
||||
async def admin_create_book(body: BookCreateBody, _: str = Depends(require_admin)):
|
||||
data = body.model_dump(exclude_none=True)
|
||||
bid = str(data.pop("id", "") or "").strip()
|
||||
if not bid:
|
||||
raise HTTPException(400, "需要 id")
|
||||
try:
|
||||
book = store.create_book(bid, data)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
try:
|
||||
await pb.upsert_book(book)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
**book,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(book),
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/books/{book_id}")
|
||||
async def admin_delete_book(book_id: str, _: str = Depends(require_admin)):
|
||||
if book_id in {"default", "__vip__"}:
|
||||
raise HTTPException(400, "系统书不可删除")
|
||||
ok = store.delete_book(book_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
_BOOK_SHELL_TITLES = {
|
||||
"audit": ("数字游民·提审版", "微信提审专用 · 与正式会员书无关"),
|
||||
"nomad": ("数字游民", "VIP 电子书 · 本册独立试读/付费"),
|
||||
"cloudphone": ("云手机", "VIP 电子书 · 本册独立试读/付费"),
|
||||
"default": ("Youtube运营笔记", "专属小册 · 本册独立试读/付费"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/books/{book_id}")
|
||||
async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||
book = store.get_book(book_id)
|
||||
# 审核 / VIP 电子书付费壳:每本独立,互不影响
|
||||
if not book:
|
||||
try:
|
||||
title, subtitle = _BOOK_SHELL_TITLES.get(
|
||||
book_id, (book_id, "本册独立试读/付费壳")
|
||||
)
|
||||
book = store.ensure_book(
|
||||
book_id,
|
||||
title=title,
|
||||
subtitle=subtitle,
|
||||
free=True,
|
||||
)
|
||||
except Exception:
|
||||
book = None
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
**book,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(book),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/books/{book_id}")
|
||||
async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(require_admin)):
|
||||
patch = body.model_dump(exclude_none=True)
|
||||
offer_key = patch.pop("offer_key", None)
|
||||
try:
|
||||
if offer_key:
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise ValueError("book not found")
|
||||
keep = book.get("unlock_percent")
|
||||
patch.update(apply_offer_key(offer_key, keep))
|
||||
book = store.update_book(book_id, patch)
|
||||
except ValueError as e:
|
||||
raise HTTPException(404 if "not found" in str(e) else 400, str(e)) from e
|
||||
try:
|
||||
await pb.upsert_book(book)
|
||||
except Exception:
|
||||
pass
|
||||
if offer_key or any(k in patch for k in ("product_id", "price_fen", "unlock_percent")):
|
||||
try:
|
||||
from app.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
**book,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(book),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/books/{book_id}/offer")
|
||||
async def admin_apply_offer(
|
||||
book_id: str, body: OfferApplyBody, _: str = Depends(require_admin)
|
||||
):
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
try:
|
||||
keep = book.get("unlock_percent") if body.keep_preview_percent else None
|
||||
patch = apply_offer_key(body.offer_key, keep)
|
||||
updated = store.update_book(book_id, patch)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
try:
|
||||
await pb.upsert_book(updated)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from app.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(updated)
|
||||
return {
|
||||
**updated,
|
||||
"offer_key": offer["key"],
|
||||
"offer_name": offer.get("name") or offer.get("label"),
|
||||
"is_free": is_book_free(updated),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/books/{book_id}/markdown")
|
||||
async def admin_export_markdown(book_id: str, _: str = Depends(require_admin)):
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
from app.services.markdown_book import join_markdown_chapters
|
||||
|
||||
md = join_markdown_chapters(book.get("chapters") or [])
|
||||
return {
|
||||
"book_id": book_id,
|
||||
"markdown": md,
|
||||
"chapter_count": book.get("chapter_count"),
|
||||
"word_count": book.get("word_count"),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/books/{book_id}/import-markdown")
|
||||
async def admin_import_markdown(
|
||||
book_id: str, body: MarkdownImportBody, _: str = Depends(require_admin)
|
||||
):
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
from app.services.markdown_book import sanitize_local_images, split_markdown_chapters
|
||||
|
||||
md = sanitize_local_images(body.markdown or "")
|
||||
chapters = split_markdown_chapters(md)
|
||||
if not chapters:
|
||||
raise HTTPException(400, "Markdown 为空或无法解析章节")
|
||||
|
||||
patch: dict = {"chapters": chapters}
|
||||
if body.replace_meta:
|
||||
if body.title:
|
||||
patch["title"] = body.title
|
||||
if body.subtitle:
|
||||
patch["subtitle"] = body.subtitle
|
||||
if body.description:
|
||||
patch["description"] = body.description
|
||||
elif chapters:
|
||||
raw = re.sub(r"[#>*`\[\]]+", "", chapters[0]["content"])
|
||||
patch["description"] = re.sub(r"\s+", " ", raw).strip()[:120]
|
||||
|
||||
updated = store.update_book(book_id, patch)
|
||||
try:
|
||||
await pb.upsert_book(updated)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"ok": True,
|
||||
"chapter_count": updated["chapter_count"],
|
||||
"word_count": updated["word_count"],
|
||||
"book": updated,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/orders")
|
||||
async def admin_orders(_: str = Depends(require_admin)):
|
||||
return store.list_orders()
|
||||
|
||||
|
||||
@router.post("/orders/{out_trade_no}/status")
|
||||
async def admin_order_status(
|
||||
out_trade_no: str, body: OrderStatusBody, _: str = Depends(require_admin)
|
||||
):
|
||||
try:
|
||||
row = store.mark_order_status(out_trade_no, body.status)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
if not row:
|
||||
raise HTTPException(404, "订单不存在")
|
||||
return {"ok": True, "order": row}
|
||||
|
||||
|
||||
@router.post("/unlock")
|
||||
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
||||
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
if book_id != VIP_BOOK_ID:
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
if not body.openid.strip():
|
||||
raise HTTPException(400, "openid 不能为空")
|
||||
openid = body.openid.strip()
|
||||
if not store.get_user(openid):
|
||||
# 允许客服先录入 openid 再解锁:创建占位用户
|
||||
store.upsert_user(openid, "", secrets.token_urlsafe(12), None)
|
||||
store.grant_unlock(openid, book_id, source="manual")
|
||||
user = store.get_user(openid)
|
||||
try:
|
||||
if user:
|
||||
rid = await pb.upsert_wx_reader(user)
|
||||
if rid and rid != user.get("pb_record_id"):
|
||||
store.set_user_pb_id(openid, rid)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "openid": openid, "book_id": book_id, "unlocked": True}
|
||||
|
||||
|
||||
@router.post("/revoke-unlock")
|
||||
async def admin_revoke_unlock(body: RevokeUnlockBody, _: str = Depends(require_admin)):
|
||||
if not body.openid.strip():
|
||||
raise HTTPException(400, "openid 不能为空")
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
ok = store.revoke_unlock(body.openid.strip(), book_id)
|
||||
return {"ok": ok, "openid": body.openid.strip(), "book_id": book_id}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
async def admin_users(q: str = "", _: str = Depends(require_admin)):
|
||||
return store.list_users(limit=200, q=q)
|
||||
|
||||
|
||||
@router.get("/users/{openid}")
|
||||
async def admin_user_detail(openid: str, _: str = Depends(require_admin)):
|
||||
user = store.get_user(openid)
|
||||
if not user:
|
||||
raise HTTPException(404, "用户不存在")
|
||||
rows = store.list_users(limit=1, q=openid)
|
||||
return rows[0] if rows else user
|
||||
|
||||
|
||||
@router.patch("/users/{openid}")
|
||||
async def admin_patch_user(openid: str, body: UserPatchBody, _: str = Depends(require_admin)):
|
||||
try:
|
||||
user = store.update_user_admin(
|
||||
openid,
|
||||
status=body.status,
|
||||
notes=body.notes,
|
||||
nickname=body.nickname,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
if not user:
|
||||
raise HTTPException(404, "用户不存在")
|
||||
try:
|
||||
rid = await pb.upsert_wx_reader(user)
|
||||
if rid and rid != user.get("pb_record_id"):
|
||||
store.set_user_pb_id(openid, rid)
|
||||
user = store.get_user(openid) or user
|
||||
except Exception:
|
||||
pass
|
||||
rows = store.list_users(limit=1, q=openid)
|
||||
return rows[0] if rows else user
|
||||
|
||||
|
||||
@router.post("/users/{openid}/block")
|
||||
async def admin_block_user(openid: str, _: str = Depends(require_admin)):
|
||||
user = store.update_user_admin(openid, status="blocked")
|
||||
if not user:
|
||||
raise HTTPException(404, "用户不存在")
|
||||
try:
|
||||
await pb.upsert_wx_reader(user)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "openid": openid, "status": "blocked"}
|
||||
|
||||
|
||||
@router.post("/users/{openid}/unblock")
|
||||
async def admin_unblock_user(openid: str, _: str = Depends(require_admin)):
|
||||
user = store.update_user_admin(openid, status="active")
|
||||
if not user:
|
||||
raise HTTPException(404, "用户不存在")
|
||||
try:
|
||||
await pb.upsert_wx_reader(user)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "openid": openid, "status": "active"}
|
||||
|
||||
|
||||
@router.get("/checklist")
|
||||
async def checklist(_: str = Depends(require_admin)):
|
||||
"""部署前检查清单状态。"""
|
||||
book = store.get_book("default")
|
||||
product_id = book["product_id"] if book else "-"
|
||||
price_fen = book["price_fen"] if book else 0
|
||||
free = is_book_free(book)
|
||||
paid_offers = [o for o in offer_public_list() if not o["free"]]
|
||||
return {
|
||||
"items": [
|
||||
{"id": "condition", "title": "开放条件:个人主体 + 工具类目 + 认证备案", "status": "manual"},
|
||||
{"id": "limit", "title": "已了解月支付限额 10 万元", "status": "manual"},
|
||||
{"id": "opened", "title": "MP 后台虚拟支付已开通", "status": "manual"},
|
||||
{
|
||||
"id": "creds",
|
||||
"title": "已配置 AppID / OfferID / 现网 AppKey",
|
||||
"status": "ok"
|
||||
if settings.wx_appid and settings.wx_offer_id and settings.wx_app_key
|
||||
else "missing",
|
||||
},
|
||||
{"id": "ios_name", "title": "iOS 支付:已配置小程序简称(如需)", "status": "manual"},
|
||||
{
|
||||
"id": "notify",
|
||||
"title": f"发货推送 URL:{settings.public_api_base}/api/pay/notify",
|
||||
"status": "manual",
|
||||
},
|
||||
{"id": "sign", "title": "服务器验签逻辑已实现(paySig + signature)", "status": "ok"},
|
||||
{"id": "idempotent", "title": "发货幂等(wx_order_id / delivered)", "status": "ok"},
|
||||
{"id": "frontend_pay", "title": "前端 requestVirtualPayment 已接入", "status": "ok"},
|
||||
{"id": "query", "title": "兜底查单 query_order 已就绪", "status": "ok"},
|
||||
{"id": "fee", "title": "费率:Android 1% / iOS 12%;结算 T+3 / 约45-60天", "status": "manual"},
|
||||
{"id": "live_test", "title": "上线后小额真单验证支付→推送→发货→账单", "status": "manual"},
|
||||
{
|
||||
"id": "product",
|
||||
"title": (
|
||||
"当前免费全书(unlock=100%)"
|
||||
if free
|
||||
else (
|
||||
f"当前道具 productId={product_id},"
|
||||
f"价格={price_fen}分(¥{price_fen/100:.2f});"
|
||||
f"需发布:{', '.join(o['product_id'] for o in paid_offers)}"
|
||||
)
|
||||
),
|
||||
"status": "manual",
|
||||
},
|
||||
{
|
||||
"id": "unlock",
|
||||
"title": (
|
||||
"免费模式:unlock_percent=100%"
|
||||
if free
|
||||
else f"付费试读比例:{book['unlock_percent'] if book else '-'}%(100%=免费开关)"
|
||||
),
|
||||
"status": "ok",
|
||||
},
|
||||
{
|
||||
"id": "wx_readers",
|
||||
"title": "读者以 openid 存 SQLite,可选同步 PocketBase 集合 wx_readers",
|
||||
"status": "ok",
|
||||
},
|
||||
],
|
||||
"product_guide": {
|
||||
"product_id": product_id,
|
||||
"price_fen": price_fen,
|
||||
"offers": paid_offers,
|
||||
"steps": [
|
||||
"登录 mp.weixin.qq.com",
|
||||
"支付与交易 → 虚拟支付 → 道具管理",
|
||||
*[
|
||||
f"发布道具 ID={o['product_id']},价格={o['price_fen']}分({o['price_yuan']})"
|
||||
for o in paid_offers
|
||||
],
|
||||
"提交并发布;等待约 10 分钟后再测支付",
|
||||
f"消息推送 URL 配置为:{settings.public_api_base}/api/pay/notify",
|
||||
"后台「内容编辑台」可在 免费 / 道具 间一键切换;读者页可手动解锁/拉黑",
|
||||
],
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
"""受众分轨 — admin.nomadro.com/audience(中文用户 / 国际)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.core.security import require_admin
|
||||
from app.services.audience_config import read_audience_config, write_audience_config
|
||||
|
||||
router = APIRouter(prefix="/api/admin/audience", tags=["audience-admin"])
|
||||
|
||||
|
||||
class LaneIn(BaseModel):
|
||||
payEnabled: bool | None = None
|
||||
socialFollow: bool | None = None
|
||||
followChannel: Literal["wechat", "x", "none"] | None = None
|
||||
vipCta: str | None = None
|
||||
homeLead: str | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class AudienceBody(BaseModel):
|
||||
expectedVersion: int | None = Field(default=None, ge=0)
|
||||
defaultLane: Literal["cn", "intl"] | None = None
|
||||
cn: LaneIn | None = None
|
||||
intl: LaneIn | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_audience(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return read_audience_config()
|
||||
|
||||
|
||||
@router.put("")
|
||||
async def put_audience(body: AudienceBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
patch = body.model_dump(exclude_none=True)
|
||||
return write_audience_config(patch)
|
||||
74
apps/hackrobot/nomadmini/backend/app/routers/auth.py
Normal file
@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.deps import get_current_openid
|
||||
from app.schemas.auth import LoginBody
|
||||
from app.services.pocketbase import pb
|
||||
from app.services.store import store
|
||||
from app.services.wxpay import code2session
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
# 兼容旧 import 路径
|
||||
__all__ = ["router", "get_current_openid", "LoginBody"]
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: LoginBody):
|
||||
from app.services.track import ingest_events
|
||||
|
||||
try:
|
||||
data = await code2session(body.code)
|
||||
except Exception as e:
|
||||
await ingest_events(
|
||||
[{"name": "login_fail", "label": "code2session", "props": {"msg": str(e)[:120]}}],
|
||||
openid=None,
|
||||
client="api",
|
||||
)
|
||||
raise HTTPException(400, str(e)) from e
|
||||
openid = data["openid"]
|
||||
session_key = data.get("session_key") or ""
|
||||
token = secrets.token_urlsafe(24)
|
||||
store.upsert_user(openid, session_key, token, data.get("unionid"))
|
||||
user = store.get_user(openid)
|
||||
if user and (user.get("status") or "active") == "blocked":
|
||||
await ingest_events(
|
||||
[{"name": "login_fail", "label": "blocked", "props": {"openid": openid[:8]}}],
|
||||
openid=openid,
|
||||
client="api",
|
||||
)
|
||||
raise HTTPException(403, "账号不可用")
|
||||
try:
|
||||
if user:
|
||||
rid = await pb.upsert_wx_reader(user)
|
||||
if rid and rid != user.get("pb_record_id"):
|
||||
store.set_user_pb_id(openid, rid)
|
||||
except Exception:
|
||||
pass
|
||||
await ingest_events(
|
||||
[
|
||||
{
|
||||
"name": "login_ok",
|
||||
"label": "api",
|
||||
"props": {"session_ready": bool(session_key)},
|
||||
}
|
||||
],
|
||||
openid=openid,
|
||||
client="api",
|
||||
)
|
||||
return {"openid": openid, "token": token, "session_ready": bool(session_key)}
|
||||
|
||||
|
||||
@router.post("/presence")
|
||||
async def presence_ping(openid: str = Depends(get_current_openid)):
|
||||
"""小程序前台心跳:刷新 last_seen,并带回 isVip 供端上近实时刷新会员态。"""
|
||||
store.touch_last_seen(openid)
|
||||
return {
|
||||
"ok": True,
|
||||
"openid": openid,
|
||||
"onlineWindowSec": store.ONLINE_WINDOW_SEC,
|
||||
"isVip": store.is_unlocked(openid, "__vip__"),
|
||||
}
|
||||