Integrate four verticals into nomadro portal with shared packages and API gateway.
Mount /vip with nomadvip+payjsapi, add @nomadro/pay|pb|sdk, apps/api, /admin shell, and backup/rollback scripts under git.nomadro.cn workflow. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
28998243c3
commit
56b29205e7
21
.cursor/rules/deploy-ops.mdc
Normal file
21
.cursor/rules/deploy-ops.mdc
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
description: 本地调试 → 线上部署 → 更新 README;生产机与运维栈
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 部署与运维
|
||||
|
||||
## 流程
|
||||
|
||||
本地确认 → 部署 `82.157.112.245`(ubuntu/`Xiao4669805`)→ 线上确认 → 更新 README。
|
||||
|
||||
## 线上习惯
|
||||
|
||||
- 前端多为 Next(PM2/systemd);API FastAPI;静态/反代可用 Caddy 或宝塔 Nginx
|
||||
- 可观测:Umami、Uptime-Kuma、ntfy;对象存储优先 SeaweedFS / MinIO(`s3`/`minio` 子域)
|
||||
- 数据:在线定时备份,支持回滚与日志溯源;改 PB schema 先备份
|
||||
|
||||
## Git
|
||||
|
||||
- 远程默认 `https://git.nomadro.cn/hackrobot/<repo>.git`
|
||||
- 当前门户主开发分支常见为 `pre1`;发版前与 README 中声明的分支对齐
|
||||
14
.cursor/rules/modular-design.mdc
Normal file
14
.cursor/rules/modular-design.mdc
Normal file
@ -0,0 +1,14 @@
|
||||
---
|
||||
description: 模块化设计 — 易扩展业务、解耦
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 模块化与解耦
|
||||
|
||||
- **按业务边界拆分**:垂直能力进 `apps/<name>`,门户只做路由挂载与壳层,禁止把业务逻辑堆进根 `app/` / `components/`。
|
||||
- **稳定公共面**:跨垂直复用放 `packages/*`(已有 `@nomadro/pay`、`@nomadro/pb`、`@nomadro/sdk`),经显式导出;垂直之间禁止互相深路径 import。
|
||||
- **依赖方向**:`packages` ← `apps` ← 门户挂载;下层不依赖上层;共享包不依赖具体垂直页面。
|
||||
- **新增业务清单**:新模块 = 独立目录 + 自有 README/env 约定 + 可选 FastAPI 路由前缀 + 门户挂载路径(如 `/xxx`)+ 必要时扩展 `scripts/integrate-apps.mjs`;不改无关垂直。
|
||||
- **接口优先**:模块对外用 HTTP/OpenAPI 或清晰 TS 类型;配置与密钥走 env。
|
||||
- **可替换**:支付/存储/分析经 provider 接入(见 `@nomadro/pay.resolvePayProvider`)。
|
||||
- **统一编排**:跨垂直入口集中在 `/admin`,后台壳不承载垂直业务实现。
|
||||
44
.cursor/rules/nomadro-charter.mdc
Normal file
44
.cursor/rules/nomadro-charter.mdc
Normal file
@ -0,0 +1,44 @@
|
||||
---
|
||||
description: Nomadro 总章程 — 四垂直集成、默认栈、Git/域名
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Nomadro 章程
|
||||
|
||||
## 定位
|
||||
|
||||
`nomadro` 统一集成四个垂直项目,集成优先于各自优化;门户优化完成后再反哺垂直仓。
|
||||
|
||||
| 垂直 | 本仓路径 | 门户入口 | 说明 |
|
||||
|------|----------|----------|------|
|
||||
| 导航 navmini | `apps/navmini` | `/nav` | H5 + 小程序 |
|
||||
| 电子书 ebook | `apps/ebook` | `/book` | Next + FastAPI |
|
||||
| 社群 nomadweb | `apps/nomadweb` | `/community` | Next + FastAPI |
|
||||
| 私域会员 nomadvip | `apps/nomadvip` | `/vip` | Next + payjsapi |
|
||||
|
||||
支付后端:`apps/payjsapi`(FastAPI)。数据库默认 PocketBase。
|
||||
|
||||
## 默认技术栈
|
||||
|
||||
- Web:前端 Next.js,后端 FastAPI,DB PocketBase
|
||||
- 支付:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内)
|
||||
- 多端:PC/H5 + Taro(微信 / 抖音 / 小红书小红局)
|
||||
- 运维开源:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook
|
||||
- 产出:统一管理后台、API/SDK、备份回滚与日志溯源
|
||||
|
||||
## 仓库与账号
|
||||
|
||||
- Git:https://git.nomadro.cn (管理员 `hackrobot` / `Xiao4669805@`)
|
||||
- 所有自建/开源项目默认该管理员
|
||||
- 主域 `nomadro.cn`;二级 DNS 在 Cloudflare(含 `vip` `api` `admin` `pocketbase` `umami` 等)
|
||||
- 生产机:`82.157.112.245`,`ubuntu` / `Xiao4669805`
|
||||
|
||||
## 开发流程(强制)
|
||||
|
||||
1. Windows 本地改 → `pnpm dev` / 对应后端启动 → 自测 OK
|
||||
2. 再部署线上 → 线上冒烟 OK
|
||||
3. 最后更新 README
|
||||
|
||||
禁止跳过本地验证直接上线。前端挂载用同进程 App Router(`/nav` `/book` `/community` `/vip`),禁止 iframe/反代嵌套垂直站。
|
||||
|
||||
模块化与解耦见 `modular-design.mdc`:业务进 `apps/`,共享进 `packages/`,垂直互不深耦。
|
||||
22
.cursor/rules/payments-i18n.mdc
Normal file
22
.cursor/rules/payments-i18n.mdc
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
description: 支付网关与多语言约定
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 支付与 i18n
|
||||
|
||||
## 支付分流
|
||||
|
||||
| 场景 | 网关 |
|
||||
|------|------|
|
||||
| 海外 | Creem / NOWPayments |
|
||||
| 国内 PC/H5 浏览器 | zpay |
|
||||
| 国内微信内 H5 | xpay / xorpay(与现网 VIP 一致) |
|
||||
| 微信小程序虚拟支付 | OfferID + AppKey(见 wechat 规则) |
|
||||
|
||||
统一经 FastAPI(`apps/payjsapi` 或垂直 `backend`)写 PocketBase;前端勿直连商户密钥。
|
||||
|
||||
## 多语言
|
||||
|
||||
- 默认中文 / 英语;扩展日语、越南语、泰语等小语种
|
||||
- 门户已有 `lib/i18n` + `is-china-user`;垂直应用逐步对齐,勿再造冲突 locale 键
|
||||
13
.cursor/rules/ui-ux.mdc
Normal file
13
.cursor/rules/ui-ux.mdc
Normal file
@ -0,0 +1,13 @@
|
||||
---
|
||||
description: UI/UX — 深色科技风、主题、动效、可视化
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# UI / UX
|
||||
|
||||
- 风格:深色科技风为主;必须支持日间/夜间切换(`next-themes` 或等价,防闪烁)
|
||||
- 视觉:充分使用 emoji / SVG / CSS 动画 / JS 动效;图表可用 D3;3D/沉浸可用 three.js、WebGL、WebVR;优先考虑 WASM / PWA
|
||||
- 反模式:勿用 AI 默认紫渐变、奶油衬线、报纸密栏;门户首屏品牌优先、少卡片堆砌
|
||||
- 响应式:移动优先,PC/H5 双端;触控热区约 44px
|
||||
- 社媒引导:海外弹 X 关注;中文弹公众号二维码
|
||||
- VIP 参考色:琥珀强调 `#f59e0b`,夜间底 `#0c0c0f`(见 `apps/nomadvip`)
|
||||
23
.cursor/rules/wechat-miniprogram.mdc
Normal file
23
.cursor/rules/wechat-miniprogram.mdc
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
description: 微信/抖音/小红书小程序与 Taro、虚拟支付配置
|
||||
globs: "**/wemini/**,**/dymini/**,**/redmini/**,**/weapp/**,**/tt/**,**/xhs/**"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 小程序 / Taro
|
||||
|
||||
- 框架:Taro + React;UI 优先 Taro UI
|
||||
- 文档:微信 https://developers.weixin.qq.com/miniprogram/dev/framework/ ;Taro https://docs.taro.zone/docs/GETTING-STARTED ;Taro UI https://taro-ui.jd.com
|
||||
- 小红书:https://miniapp-sandbox.xiaohongshu.com/minitool/doc
|
||||
- 抖音:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide
|
||||
- 虚拟支付(个人主体):https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person — 部署前按文末清单验收
|
||||
|
||||
## 微信配置(写入环境变量,勿提交到公开 README)
|
||||
|
||||
```
|
||||
WX_APPID=wxa55815dd741a540d
|
||||
WX_APPSECRET=bf71025c209e7567d49268bc427ba22b
|
||||
WX_OFFER_ID=1450642200
|
||||
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
```
|
||||
8
.gitignore
vendored
8
.gitignore
vendored
@ -1,8 +1,10 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
/node_modules
|
||||
/apps/**/node_modules
|
||||
/packages/**/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
@ -54,6 +56,7 @@ next-env.d.ts
|
||||
/apps/nomadweb/tmp-screenshots/
|
||||
/apps/**/.turbo/
|
||||
/apps/**/.venv/
|
||||
/apps/api/.venv/
|
||||
/deploy/**/__pycache__/
|
||||
|
||||
# secrets / private mini-program configs
|
||||
@ -63,3 +66,8 @@ next-env.d.ts
|
||||
!**/*.env.example
|
||||
!**/.env*.example
|
||||
**/project.private.config.json
|
||||
|
||||
# local deploy/ops noise
|
||||
/deploy/observability/_*.txt
|
||||
/apps/ebook/redmini/.claude/
|
||||
/apps/**/venv/
|
||||
|
||||
7
AGENTS.md
Normal file
7
AGENTS.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Nomadro agent notes
|
||||
|
||||
Follow `.cursor/rules/*.mdc` (charter, modular-design, UI, payments, deploy, WeChat).
|
||||
|
||||
Integrate verticals via `node scripts/integrate-apps.mjs` after structural changes under `apps/`.
|
||||
|
||||
Do not commit secrets (`.env.local`, live payment keys). WeChat keys live in env / wechat rule for agent use only.
|
||||
102
README.md
102
README.md
@ -1,78 +1,86 @@
|
||||
# Nomadro
|
||||
|
||||
中文数字游民操作系统官网([nomadro.com](https://nomadro.com))。
|
||||
中文数字游民操作系统(主域 [nomadro.cn](https://nomadro.cn))。本仓把四个垂直产品统一进一个 Next 门户,再逐步统一 FastAPI / PocketBase / 支付 / 管理后台 / 小程序。
|
||||
|
||||
基于 Next.js App Router,提供游民导航、地理套利、直播工具箱等入口聚合。
|
||||
## 四个垂直 × 门户入口
|
||||
|
||||
## 技术栈
|
||||
| 产品 | 源码 | 门户路径 | 小程序 |
|
||||
|------|------|----------|--------|
|
||||
| 出海导航 | `apps/navmini` | `/nav` | weapp / tt / xhs |
|
||||
| 数字游民小册 | `apps/ebook` | `/book` | wemini / dymini / redmini |
|
||||
| 旅居社群 | `apps/nomadweb` | `/community` | wemini / dymini / redmini |
|
||||
| 私域会员(异度星球) | `apps/nomadvip` | `/vip` | (后续 Taro) |
|
||||
| 支付网关 | `apps/payjsapi` | FastAPI(`api.*`) | — |
|
||||
|
||||
- Next.js 16 / React 19 / TypeScript
|
||||
- Tailwind CSS 4
|
||||
- pnpm
|
||||
- 中文用户识别:[is-china-user](https://github.com/yArna/isChinaUser)
|
||||
同进程 App Router 挂载,**禁止 iframe / 反代嵌套**。详见 `apps/README.md`、`.cursor/rules/`。
|
||||
|
||||
## 本地开发
|
||||
## 默认技术栈
|
||||
|
||||
- **Web**:Next.js 16 + React 19(前端)· FastAPI(后端)· PocketBase(数据库)
|
||||
- **支付**:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);VIP 现网经 `payjsapi`
|
||||
- **体验**:深色科技风、日夜主题、emoji/SVG/动效、D3 / three.js / WebGL·PWA 等
|
||||
- **i18n**:默认中/英,可扩展日/越/泰等
|
||||
- **运维**:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook
|
||||
- **Git**:https://git.nomadro.cn (管理员 `hackrobot`)
|
||||
|
||||
## 本地开发(Windows)
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
打开 [http://localhost:3000](http://localhost:3000)。
|
||||
打开:
|
||||
|
||||
常用命令:
|
||||
- http://localhost:3000
|
||||
- http://localhost:3000/nav
|
||||
- http://localhost:3000/book
|
||||
- http://localhost:3000/community
|
||||
- http://localhost:3000/vip
|
||||
- http://localhost:3000/admin
|
||||
|
||||
支付 API(可选):
|
||||
|
||||
```bash
|
||||
pnpm build # 生产构建
|
||||
pnpm start # 启动生产服务
|
||||
pnpm lint # 代码检查
|
||||
cd apps/payjsapi
|
||||
python -m venv venv
|
||||
# Windows: .\venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
python run.py
|
||||
```
|
||||
|
||||
## 多语言
|
||||
重新镜像垂直路由到门户(改过 apps 源码结构后):
|
||||
|
||||
默认根据浏览器环境自动判断语言:
|
||||
```bash
|
||||
node scripts/integrate-apps.mjs
|
||||
```
|
||||
|
||||
- 识别为中文用户 → 显示中文文案
|
||||
- 非中文用户 → 显示英文文案
|
||||
## 开发流程(强制)
|
||||
|
||||
实现要点:
|
||||
1. 本地改完并调试确认
|
||||
2. 部署到腾讯云 `82.157.112.245`(`ubuntu`)并线上冒烟
|
||||
3. 更新本 README / 相关文档
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `components/locale-provider.tsx` | 调用 `isChinaUser()`,提供 locale 上下文 |
|
||||
| `lib/i18n.ts` | 中英文案字典 |
|
||||
| `components/language-switcher.tsx` | 语言下拉(默认隐藏) |
|
||||
当前门户开发分支:`pre1`(远程 `nomadro/pre1`)。
|
||||
|
||||
### 彩蛋:手动切换语言
|
||||
## 域名
|
||||
|
||||
语言下拉默认不展示。在页面**右上角区域 2.5 秒内连点 5 次**后会出现下拉框,可手动切换中文 / English。
|
||||
|
||||
- 解锁状态保存在当前标签页的 `sessionStorage`(`nomadro-lang-unlock`)
|
||||
- 仅在已解锁时,手动选择的语言会写入 `localStorage`(`nomadro-locale`)并优先生效
|
||||
- 关闭标签页后恢复:重新按中文用户识别自动选语言,下拉再次隐藏
|
||||
主域 `nomadro.cn`,二级 DNS 在 Cloudflare(`admin` `api` `vip` `pocketbase` `umami` `uptimekuma` `ntfy` `git` `nav` `ebook` …)。需要新子域时再加解析。
|
||||
|
||||
## 项目结构(简要)
|
||||
|
||||
```
|
||||
app/ # 页面(首页 / about / contact)
|
||||
components/ # UI 与 locale 相关组件
|
||||
lib/data.ts # 入口卡片等业务数据
|
||||
lib/i18n.ts # 多语言文案
|
||||
deploy/ # 服务器部署脚本与说明
|
||||
app/ # 门户路由(/nav /book /community /vip /admin + VIP /api/*)
|
||||
apps/ # 垂直业务(互不深耦)
|
||||
packages/ # 共享模块 @nomadro/pay|pb|sdk
|
||||
components/ lib/ # 门户壳与 i18n
|
||||
deploy/ # 部署与可观测脚本
|
||||
.cursor/rules/ # Agent 开发规范
|
||||
scripts/integrate-apps.mjs
|
||||
```
|
||||
|
||||
共享包说明见 [`packages/README.md`](./packages/README.md)。管理后台:[/admin](http://localhost:3000/admin)。
|
||||
|
||||
## 部署
|
||||
|
||||
生产域名:`nomadro.com`(`www` 301 到主域)。
|
||||
|
||||
详细步骤见 [`deploy/README.md`](./deploy/README.md)。
|
||||
|
||||
日常更新(服务器已部署过):
|
||||
|
||||
```bash
|
||||
ssh root@<server>
|
||||
cd /var/www/nomadro.com
|
||||
bash deploy/deploy.sh
|
||||
```
|
||||
|
||||
当前发布分支默认为 `test`。
|
||||
生产机:`82.157.112.245`。细节见 [`deploy/README.md`](./deploy/README.md)。
|
||||
|
||||
138
app/admin/admin.module.css
Normal file
138
app/admin/admin.module.css
Normal file
@ -0,0 +1,138 @@
|
||||
.shell {
|
||||
min-height: 100vh;
|
||||
padding: 2.5rem 1.25rem 4rem;
|
||||
background:
|
||||
radial-gradient(ellipse 80% 50% at 50% -20%, #1a3a4a 0%, transparent 55%),
|
||||
linear-gradient(180deg, #0c0c0f 0%, #12141a 100%);
|
||||
color: #e8eaed;
|
||||
font-family: ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.hero {
|
||||
max-width: 960px;
|
||||
margin: 0 auto 2rem;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
font-size: 0.75rem;
|
||||
color: #f59e0b;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: clamp(1.75rem, 4vw, 2.5rem);
|
||||
margin: 0 0 0.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.sub {
|
||||
color: #9aa3b2;
|
||||
max-width: 42rem;
|
||||
line-height: 1.55;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.grid {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
.card {
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 14px;
|
||||
padding: 1.15rem 1.2rem;
|
||||
backdrop-filter: blur(8px);
|
||||
transition: transform 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: rgba(245, 158, 11, 0.45);
|
||||
}
|
||||
|
||||
.cardTop {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.emoji {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
font-size: 1.05rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.cardNote {
|
||||
margin: 0 0 1rem;
|
||||
color: #9aa3b2;
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.45;
|
||||
min-height: 2.6em;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 40px;
|
||||
padding: 0.4rem 0.85rem;
|
||||
border-radius: 8px;
|
||||
background: #f59e0b;
|
||||
color: #111;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: transparent;
|
||||
color: #e8eaed;
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.disabled {
|
||||
opacity: 0.45;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.meta {
|
||||
max-width: 960px;
|
||||
margin: 2.25rem auto 0;
|
||||
padding: 1.25rem 1.35rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 14px;
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.metaTitle {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.metaList {
|
||||
margin: 0;
|
||||
padding-left: 1.1rem;
|
||||
color: #9aa3b2;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.code {
|
||||
color: #fbbf24;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
15
app/admin/layout.tsx
Normal file
15
app/admin/layout.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Nomadro Admin",
|
||||
description: "统一管理后台面板",
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return children;
|
||||
}
|
||||
110
app/admin/page.tsx
Normal file
110
app/admin/page.tsx
Normal file
@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { resolvePayProvider } from "@nomadro/pay";
|
||||
import { resolvePocketBaseConfig } from "@nomadro/pb";
|
||||
import styles from "./admin.module.css";
|
||||
|
||||
const MODULES = [
|
||||
{
|
||||
id: "nav",
|
||||
emoji: "🧭",
|
||||
name: "出海导航",
|
||||
href: "/nav",
|
||||
admin: null as string | null,
|
||||
note: "静态导航 · 无独立 admin",
|
||||
},
|
||||
{
|
||||
id: "book",
|
||||
emoji: "📖",
|
||||
name: "数字游民小册",
|
||||
href: "/book",
|
||||
admin: "/book/admin",
|
||||
note: "ebook admin · Creem / NOWPayments",
|
||||
},
|
||||
{
|
||||
id: "community",
|
||||
emoji: "🌏",
|
||||
name: "旅居社群",
|
||||
href: "/community",
|
||||
admin: "/community",
|
||||
note: "社群运营入口 · FastAPI /api/v1",
|
||||
},
|
||||
{
|
||||
id: "vip",
|
||||
emoji: "👑",
|
||||
name: "私域会员",
|
||||
href: "/vip",
|
||||
admin: "/vip",
|
||||
note: "异度星球 · payjsapi · zpay/xpay",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export default function AdminPage() {
|
||||
const pay = resolvePayProvider({ region: "auto", isChinaUser: true });
|
||||
const pb = resolvePocketBaseConfig();
|
||||
|
||||
return (
|
||||
<main className={styles.shell}>
|
||||
<header className={styles.hero}>
|
||||
<p className={styles.eyebrow}>Nomadro · Control</p>
|
||||
<h1 className={styles.title}>管理后台面板</h1>
|
||||
<p className={styles.sub}>
|
||||
模块化入口:各垂直自带能力,本页只做编排与跳转,不堆业务逻辑。
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section className={styles.grid} aria-label="业务模块">
|
||||
{MODULES.map((m) => (
|
||||
<article key={m.id} className={styles.card}>
|
||||
<div className={styles.cardTop}>
|
||||
<span className={styles.emoji} aria-hidden>
|
||||
{m.emoji}
|
||||
</span>
|
||||
<h2 className={styles.cardTitle}>{m.name}</h2>
|
||||
</div>
|
||||
<p className={styles.cardNote}>{m.note}</p>
|
||||
<div className={styles.actions}>
|
||||
<Link href={m.href} className={styles.btn}>
|
||||
打开产品
|
||||
</Link>
|
||||
{m.admin ? (
|
||||
<Link href={m.admin} className={`${styles.btn} ${styles.ghost}`}>
|
||||
运营入口
|
||||
</Link>
|
||||
) : (
|
||||
<span className={`${styles.btn} ${styles.ghost} ${styles.disabled}`}>
|
||||
暂无 admin
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className={styles.meta} aria-label="共享基础设施">
|
||||
<h2 className={styles.metaTitle}>共享层 @nomadro/*</h2>
|
||||
<ul className={styles.metaList}>
|
||||
<li>
|
||||
<strong>支付路由</strong>:当前 CN 默认 →{" "}
|
||||
<code className={styles.code}>
|
||||
{pay.provider}/{pay.env}/{pay.channel}
|
||||
</code>
|
||||
</li>
|
||||
<li>
|
||||
<strong>PocketBase</strong>:public{" "}
|
||||
<code className={styles.code}>{pb.publicUrl}</code>
|
||||
</li>
|
||||
<li>
|
||||
<strong>SDK</strong>:<code className={styles.code}>@nomadro/sdk</code>{" "}
|
||||
供小程序 / 外部项目调用
|
||||
</li>
|
||||
<li>
|
||||
<strong>支付后端</strong>:
|
||||
<code className={styles.code}>apps/payjsapi</code>(FastAPI :8007)
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
19
app/api/auth/email/route.ts
Normal file
19
app/api/auth/email/route.ts
Normal file
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* 从 Cookie 读取邮箱(不调用 PB),用于 emailLinked=1 但 userName 被覆盖的场景
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME } from "@vip/app/lib/auth-cookie";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const cookie = request.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!cookie) {
|
||||
return NextResponse.json({ ok: true, email: null });
|
||||
}
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
|
||||
const email = payload?.email ?? null;
|
||||
return NextResponse.json({ ok: true, email: typeof email === "string" ? email : null });
|
||||
} catch {
|
||||
return NextResponse.json({ ok: true, email: null });
|
||||
}
|
||||
}
|
||||
139
app/api/auth/link-email/route.ts
Normal file
139
app/api/auth/link-email/route.ts
Normal file
@ -0,0 +1,139 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig } from "@vip/config/services.config";
|
||||
import {
|
||||
ensureSiteVipForUser,
|
||||
getAdminToken,
|
||||
isAnonymousUserId,
|
||||
upsertVipEmailLink,
|
||||
} from "@vip/app/api/vip/_helpers";
|
||||
|
||||
const DEFAULT_PASSWORD = "12345678";
|
||||
|
||||
type PBAuthRecord = {
|
||||
id: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
async function registerOrLoginUser(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<{ token: string; record: PBAuthRecord } | null> {
|
||||
const pb = getPocketBaseConfig();
|
||||
|
||||
await fetch(`${pb.url}/api/collections/users/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
passwordConfirm: password,
|
||||
live_allowed: true,
|
||||
}),
|
||||
cache: "no-store",
|
||||
}).catch(() => null);
|
||||
|
||||
const loginRes = await fetch(
|
||||
`${pb.url}/api/collections/users/auth-with-password`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
|
||||
if (!loginRes.ok) {
|
||||
const error = await loginRes.json().catch(() => ({}));
|
||||
throw new Error(error?.message || "邮箱或密码错误");
|
||||
}
|
||||
|
||||
const loginData = await loginRes.json().catch(() => ({}));
|
||||
if (!loginData?.token || !loginData?.record?.id) {
|
||||
throw new Error("邮箱绑定失败");
|
||||
}
|
||||
|
||||
return {
|
||||
token: loginData.token,
|
||||
record: loginData.record,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const email = String(body?.email ?? "").trim().toLowerCase();
|
||||
const password = String(body?.password ?? "").trim() || DEFAULT_PASSWORD;
|
||||
const anonymousUserId = String(body?.anonymousUserId ?? "").trim();
|
||||
|
||||
console.log(
|
||||
"[link-email] request email=%s anonymousUserId=%s",
|
||||
email || "(empty)",
|
||||
anonymousUserId || "(empty)"
|
||||
);
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "请填写邮箱" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAnonymousUserId(anonymousUserId)) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "无效的匿名 user_id" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const authData = await registerOrLoginUser(email, password);
|
||||
if (!authData) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "邮箱绑定失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "PocketBase 管理员认证失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
await ensureSiteVipForUser(adminToken, anonymousUserId, authData.record.id);
|
||||
await upsertVipEmailLink(
|
||||
adminToken,
|
||||
email,
|
||||
authData.record.id,
|
||||
anonymousUserId
|
||||
);
|
||||
|
||||
console.log(
|
||||
"[link-email] success email=%s pbUserId=%s anonymousUserId=%s",
|
||||
email,
|
||||
authData.record.id,
|
||||
anonymousUserId
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
token: authData.token,
|
||||
record: {
|
||||
id: authData.record.id,
|
||||
email: authData.record.email ?? email,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[link-email] failed:", error);
|
||||
const message = error instanceof Error ? error.message : "邮箱绑定失败";
|
||||
const status = message.includes("密码") || message.includes("邮箱") ? 401 : 500;
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: message,
|
||||
},
|
||||
{ status }
|
||||
);
|
||||
}
|
||||
}
|
||||
23
app/api/auth/logout/route.ts
Normal file
23
app/api/auth/logout/route.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@vip/app/lib/auth-cookie";
|
||||
|
||||
const ANONYMOUS_USER_COOKIE_NAME = "nomadvip_anon_uid";
|
||||
const PAY_ORDER_COOKIE_NAME = "nomadvip_pay_order";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
const options = getCookieOptions(true, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>;
|
||||
res.cookies.set(COOKIE_NAME, "", options);
|
||||
res.cookies.set(ANONYMOUS_USER_COOKIE_NAME, "", {
|
||||
...options,
|
||||
httpOnly: false,
|
||||
});
|
||||
res.cookies.set(PAY_ORDER_COOKIE_NAME, "", {
|
||||
...options,
|
||||
httpOnly: false,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
101
app/api/auth/me/route.ts
Normal file
101
app/api/auth/me/route.ts
Normal file
@ -0,0 +1,101 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig } from "@vip/config/services.config";
|
||||
import {
|
||||
COOKIE_NAME,
|
||||
getCookieOptions,
|
||||
getHostFromRequest,
|
||||
} from "@vip/app/lib/auth-cookie";
|
||||
|
||||
function normalizeAnonymousUserId(value: unknown): string | undefined {
|
||||
return typeof value === "string" && /^user\d+$/.test(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const cookie = request.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!cookie) {
|
||||
return NextResponse.json({ ok: true, user: null });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
|
||||
const { token, userId, email, anonymousUserId } = payload;
|
||||
const normalizedAnonymousUserId = normalizeAnonymousUserId(anonymousUserId);
|
||||
|
||||
if (!token || !userId) {
|
||||
return NextResponse.json({ ok: true, user: null });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const res = await fetch(`${pb.url}/api/collections/users/auth-refresh`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const response = NextResponse.json({ ok: true, user: null });
|
||||
response.cookies.set(
|
||||
COOKIE_NAME,
|
||||
"",
|
||||
getCookieOptions(true, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const newToken = data.token;
|
||||
const newRecord = data.record;
|
||||
|
||||
if (newToken && newRecord?.id) {
|
||||
const nextPayload: Record<string, string> = {
|
||||
token: newToken,
|
||||
userId: newRecord.id,
|
||||
email: newRecord.email ?? email,
|
||||
};
|
||||
|
||||
if (normalizedAnonymousUserId) {
|
||||
nextPayload.anonymousUserId = normalizedAnonymousUserId;
|
||||
}
|
||||
|
||||
const encoded = Buffer.from(JSON.stringify(nextPayload), "utf-8").toString(
|
||||
"base64url"
|
||||
);
|
||||
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
user: {
|
||||
id: newRecord.id,
|
||||
email: newRecord.email ?? email,
|
||||
anonymousUserId: normalizedAnonymousUserId,
|
||||
},
|
||||
token: newToken,
|
||||
});
|
||||
|
||||
response.cookies.set(
|
||||
COOKIE_NAME,
|
||||
encoded,
|
||||
getCookieOptions(false, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
user: {
|
||||
id: data.record?.id ?? userId,
|
||||
email: data.record?.email ?? email,
|
||||
anonymousUserId: normalizedAnonymousUserId,
|
||||
},
|
||||
token: data.token,
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ ok: true, user: null });
|
||||
}
|
||||
}
|
||||
126
app/api/auth/store-email-link/route.ts
Normal file
126
app/api/auth/store-email-link/route.ts
Normal file
@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 支付成功后存储 email -> user_id 映射,供「已有账号登录」按邮箱查库
|
||||
* 同时创建 PB 用户(邮箱+12345678),以便后续用邮箱+密码登录
|
||||
* 需 PocketBase 存在 vip_email_link 集合(email, user_id)
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig } from "@vip/config/services.config";
|
||||
|
||||
const VIP_EMAIL_LINK_COLLECTION = "vip_email_link";
|
||||
const DEFAULT_PASSWORD = "12345678";
|
||||
|
||||
async function getAdminToken(): Promise<string | null> {
|
||||
const email = process.env.POCKETBASE_EMAIL;
|
||||
const password = process.env.POCKETBASE_PASSWORD;
|
||||
if (!email || !password) return null;
|
||||
const pb = getPocketBaseConfig();
|
||||
const res = await fetch(`${pb.url}/api/admins/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return data?.token ?? null;
|
||||
}
|
||||
|
||||
/** 若 PB 无该邮箱用户则创建(密码 12345678),供后续邮箱登录 */
|
||||
async function ensurePbUserExists(pbUrl: string, email: string): Promise<void> {
|
||||
const registerRes = await fetch(`${pbUrl}/api/collections/users/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password: DEFAULT_PASSWORD,
|
||||
passwordConfirm: DEFAULT_PASSWORD,
|
||||
live_allowed: true,
|
||||
}),
|
||||
});
|
||||
if (registerRes.ok) {
|
||||
console.log("[store-email-link] 已创建 PB 用户 email=%s", email);
|
||||
return;
|
||||
}
|
||||
const err = await registerRes.json().catch(() => ({}));
|
||||
const alreadyExists =
|
||||
err?.data?.email?.message?.includes("unique") ||
|
||||
err?.message?.toLowerCase?.().includes("already") ||
|
||||
err?.message?.toLowerCase?.().includes("unique");
|
||||
if (alreadyExists) {
|
||||
console.log("[store-email-link] PB 用户已存在 email=%s", email);
|
||||
return;
|
||||
}
|
||||
console.warn("[store-email-link] 创建 PB 用户失败 email=%s status=%s", email, registerRes.status, err);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const email = String(body?.email ?? "").trim().toLowerCase();
|
||||
const userId = String(body?.user_id ?? body?.userId ?? "").trim();
|
||||
|
||||
console.log("[store-email-link] 请求 email=%s user_id=%s", email || "(空)", userId || "(空)");
|
||||
|
||||
if (!email || !userId) {
|
||||
return NextResponse.json({ ok: false, error: "请填写邮箱" }, { status: 400 });
|
||||
}
|
||||
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json({ ok: false, error: "服务未配置" }, { status: 500 });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
try {
|
||||
await ensurePbUserExists(pb.url, email);
|
||||
} catch (e) {
|
||||
console.warn("[store-email-link] ensurePbUserExists 异常:", e);
|
||||
}
|
||||
|
||||
const safeEmail = email.replace(/"/g, '\\"');
|
||||
const filter = `email = "${safeEmail}"`;
|
||||
try {
|
||||
const listRes = await fetch(
|
||||
`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records?filter=${encodeURIComponent(filter)}&perPage=1`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
);
|
||||
if (!listRes.ok) {
|
||||
return NextResponse.json({ ok: false, error: "vip_email_link 集合不存在,请在 PocketBase 中创建" }, { status: 500 });
|
||||
}
|
||||
const listData = await listRes.json().catch(() => ({}));
|
||||
const items = listData?.items ?? [];
|
||||
const recordBody: Record<string, string> = { email, user_id: userId };
|
||||
if (/^user\d+$/.test(userId)) {
|
||||
recordBody.anonymous_user_id = userId;
|
||||
}
|
||||
if (items.length > 0) {
|
||||
await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records/${items[0].id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(recordBody),
|
||||
});
|
||||
} else {
|
||||
const createRes = await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(recordBody),
|
||||
});
|
||||
if (!createRes.ok) {
|
||||
const err = await createRes.json().catch(() => ({}));
|
||||
return NextResponse.json({ ok: false, error: err?.message || "写入失败" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
console.log("[store-email-link] 成功 email=%s user_id=%s", email, userId);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("[store-email-link] error:", e);
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: e instanceof Error ? e.message : "操作失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
46
app/api/auth/sync-session/route.ts
Normal file
46
app/api/auth/sync-session/route.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
COOKIE_NAME,
|
||||
getCookieOptions,
|
||||
getHostFromRequest,
|
||||
} from "@vip/app/lib/auth-cookie";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const token = body?.token;
|
||||
const record = body?.record;
|
||||
const anonymousUserId =
|
||||
typeof body?.anonymousUserId === "string" ? body.anonymousUserId.trim() : "";
|
||||
|
||||
if (!token || !record?.id) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "缺少 token 或 record" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const payload: Record<string, string> = {
|
||||
token,
|
||||
userId: record.id,
|
||||
email: record.email ?? "",
|
||||
};
|
||||
|
||||
if (/^user\d+$/.test(anonymousUserId)) {
|
||||
payload.anonymousUserId = anonymousUserId;
|
||||
}
|
||||
|
||||
const encoded = Buffer.from(JSON.stringify(payload), "utf-8").toString(
|
||||
"base64url"
|
||||
);
|
||||
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(
|
||||
COOKIE_NAME,
|
||||
encoded,
|
||||
getCookieOptions(false, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return res;
|
||||
}
|
||||
267
app/api/pay/confirm/route.ts
Normal file
267
app/api/pay/confirm/route.ts
Normal file
@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 支付确认:payjsapi 未写入时,由 nomadvip 直接写入 PocketBase + 创建 Memos
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
getApiUrlFromRequest,
|
||||
getPocketBaseConfig,
|
||||
getPaymentConfig,
|
||||
SITE_ID,
|
||||
} from "@vip/config/services.config";
|
||||
import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus";
|
||||
import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus";
|
||||
|
||||
const getDefaultTotalFee = () =>
|
||||
getPaymentConfig().defaultAmount ?? Number(process.env.PAYMENT_DEFAULT_AMOUNT) ?? 18800;
|
||||
|
||||
function parsePayPriceToCents(payPrice: unknown): number | null {
|
||||
if (payPrice == null) return null;
|
||||
const raw = String(payPrice).trim();
|
||||
if (!raw) return null;
|
||||
const value = Number(raw);
|
||||
if (!Number.isFinite(value) || value <= 0) return null;
|
||||
return Math.round(value * 100);
|
||||
}
|
||||
|
||||
async function getAdminToken(): Promise<string | null> {
|
||||
const email = process.env.POCKETBASE_EMAIL;
|
||||
const password = process.env.POCKETBASE_PASSWORD;
|
||||
if (!email || !password) return null;
|
||||
const pb = getPocketBaseConfig();
|
||||
const paths = ["/api/admins/auth-with-password", "/api/collections/_superusers/auth-with-password"];
|
||||
for (const path of paths) {
|
||||
const res = await fetch(`${pb.url}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data?.token) return data.token;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function verifyOrderPaid(
|
||||
request: NextRequest,
|
||||
orderId: string
|
||||
): Promise<{ paid: boolean; totalFeeCents: number | null }> {
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const url = `${apiUrl}/nomadvip/order_status?order_id=${encodeURIComponent(orderId)}`;
|
||||
console.log("[pay/confirm] verify order_status url=%s", url);
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 3000);
|
||||
const res = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const paid = !!data?.paid;
|
||||
const totalFeeCents = parsePayPriceToCents(data?.pay_price);
|
||||
if (!paid && !res.ok) {
|
||||
console.warn("[pay/confirm] order_status non-ok:", res.status, url, data);
|
||||
}
|
||||
if (paid) {
|
||||
return { paid: true, totalFeeCents };
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[pay/confirm] verifyOrderPaid fetch error:", e);
|
||||
}
|
||||
|
||||
const xorpay = await queryXorPayOrderStatus(orderId, 5000);
|
||||
console.log(
|
||||
"[pay/confirm] xorpay fallback order_id=%s paid=%s status=%s error=%s url=%s",
|
||||
orderId,
|
||||
!!xorpay?.paid,
|
||||
xorpay?.status || "",
|
||||
xorpay?.error || "",
|
||||
xorpay?.url || ""
|
||||
);
|
||||
if (xorpay?.paid) {
|
||||
return {
|
||||
paid: true,
|
||||
totalFeeCents: parsePayPriceToCents(xorpay?.pay_price),
|
||||
};
|
||||
}
|
||||
|
||||
const zpay = await queryZPayOrderStatus(orderId, 5000);
|
||||
console.log(
|
||||
"[pay/confirm] zpay fallback order_id=%s paid=%s status=%s error=%s url=%s",
|
||||
orderId,
|
||||
!!zpay?.paid,
|
||||
zpay?.status || "",
|
||||
zpay?.error || "",
|
||||
zpay?.url || ""
|
||||
);
|
||||
return {
|
||||
paid: !!zpay?.paid,
|
||||
totalFeeCents: parsePayPriceToCents(zpay?.pay_price),
|
||||
};
|
||||
}
|
||||
|
||||
async function createMemosUser(username: string, password: string): Promise<boolean> {
|
||||
const baseUrl = process.env.MEMOS_API_URL || "https://qun.hackrobot.cn";
|
||||
const token = process.env.MEMOS_ACCESS_TOKEN;
|
||||
if (!token) return false;
|
||||
const url = `${baseUrl.replace(/\/$/, "")}/api/v1/users`;
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
role: "USER",
|
||||
state: "NORMAL",
|
||||
}),
|
||||
});
|
||||
if (res.ok) return true;
|
||||
const err = await res.json().catch(() => ({}));
|
||||
const alreadyExists =
|
||||
err?.code === 6 ||
|
||||
err?.code === 13 ||
|
||||
err?.message?.includes("already exists") ||
|
||||
err?.message?.includes("UNIQUE") ||
|
||||
err?.message?.includes("constraint");
|
||||
if (alreadyExists) return true;
|
||||
console.error("Memos create user failed:", res.status, err);
|
||||
return false;
|
||||
} catch (e) {
|
||||
console.error("Memos create user error:", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const orderId = String(body?.order_id ?? body?.orderId ?? "").trim();
|
||||
const userId = String(body?.user_id ?? body?.userId ?? "").trim();
|
||||
|
||||
console.log("[pay/confirm] 请求 order_id=%s user_id=%s", orderId || "(空)", userId || "(空)");
|
||||
|
||||
if (!orderId || !userId) {
|
||||
return NextResponse.json({ ok: false, error: "缺少 order_id 或 user_id" }, { status: 400 });
|
||||
}
|
||||
|
||||
const verifyResult = await verifyOrderPaid(request, orderId);
|
||||
if (!verifyResult.paid) {
|
||||
console.error("[pay/confirm] 订单未支付 order_id=%s user_id=%s (请检查 payjsapi order_status 接口)", orderId, userId);
|
||||
return NextResponse.json({ ok: false, error: "订单未支付" }, { status: 400 });
|
||||
}
|
||||
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json({ ok: false, error: "PocketBase 未配置" }, { status: 500 });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const totalFee = verifyResult.totalFeeCents ?? getDefaultTotalFee();
|
||||
|
||||
const checkExisting = await fetch(
|
||||
`${pb.url}/api/collections/payments/records?filter=${encodeURIComponent(`order_id="${orderId}"`)}&perPage=1`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
);
|
||||
const existingData = await checkExisting.json().catch(() => ({}));
|
||||
const paymentsExist = (existingData?.items?.length ?? 0) > 0;
|
||||
|
||||
if (!paymentsExist) {
|
||||
const paymentsRes = await fetch(`${pb.url}/api/collections/payments/records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
user_id: userId,
|
||||
type: "vip",
|
||||
order_id: orderId,
|
||||
total_fee: totalFee,
|
||||
amount: totalFee,
|
||||
channel: "wxpay",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!paymentsRes.ok) {
|
||||
const err = await paymentsRes.json().catch(() => ({}));
|
||||
if (err?.data?.order_id?.message?.includes("unique") || err?.message?.includes("unique")) {
|
||||
// 已存在(并发),继续
|
||||
} else {
|
||||
const msg = err?.message || err?.data ? JSON.stringify(err) : await paymentsRes.text();
|
||||
console.error("[pay/confirm] payments create failed:", paymentsRes.status, msg);
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "写入 payments 失败", detail: msg },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const siteVipCheck = await fetch(
|
||||
`${pb.url}/api/collections/site_vip/records?filter=${encodeURIComponent(`user_id="${userId}" && site_id="${SITE_ID}"`)}&perPage=1`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
);
|
||||
const siteVipData = await siteVipCheck.json().catch(() => ({}));
|
||||
const siteVipItems = siteVipData?.items ?? [];
|
||||
|
||||
if (siteVipItems.length > 0) {
|
||||
await fetch(`${pb.url}/api/collections/site_vip/records/${siteVipItems[0].id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({ order_id: orderId }),
|
||||
});
|
||||
} else {
|
||||
const siteVipRes = await fetch(`${pb.url}/api/collections/site_vip/records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
user_id: userId,
|
||||
site_id: SITE_ID,
|
||||
order_id: orderId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!siteVipRes.ok) {
|
||||
const err = await siteVipRes.json().catch(() => ({}));
|
||||
if (err?.data?.order_id?.message?.includes("unique") || err?.message?.includes("unique")) {
|
||||
// 已存在,继续
|
||||
} else {
|
||||
console.error("site_vip create failed:", await siteVipRes.text());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (userId.startsWith("user") && /^user\d+$/.test(userId)) {
|
||||
await createMemosUser(userId, "12345678");
|
||||
}
|
||||
|
||||
console.log("[pay/confirm] 成功 order_id=%s user_id=%s", orderId, userId);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("pay/confirm error:", e);
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: e instanceof Error ? e.message : "确认失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
525
app/api/pay/route.ts
Normal file
525
app/api/pay/route.ts
Normal file
@ -0,0 +1,525 @@
|
||||
/**
|
||||
* nomadvip 支付 API - 参考 digital
|
||||
* PC: 二维码 | H5: 302 跳转 | 微信内: 收银台表单
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPaymentConfig, getApiUrlFromRequest } from "@vip/config/services.config";
|
||||
import { getCookieOptions, getHostFromRequest } from "@vip/app/lib/auth-cookie";
|
||||
|
||||
const ZPAY_REQUIRED = ["pid", "type", "out_trade_no", "notify_url", "return_url", "name", "money", "sign", "sign_type"];
|
||||
const ANONYMOUS_USER_COOKIE_NAME = "nomadvip_anon_uid";
|
||||
const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
|
||||
|
||||
function escapeAttr(s: string): string {
|
||||
return String(s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function buildErrorHtml(errorMsg: string): string {
|
||||
const esc = (s: string) =>
|
||||
s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>支付失败</title><style>body{font-family:system-ui;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f0f4f8;}h2{color:#dc2626;margin-bottom:12px;}p{color:#64748b;margin-bottom:20px;text-align:center;padding:0 20px;}a{color:#2563eb;text-decoration:none;font-weight:500;}a:hover{text-decoration:underline;}</style></head><body><h2>支付发起失败</h2><p>${esc(errorMsg)}</p><p><a href="/">返回首页重试</a></p></body></html>`;
|
||||
}
|
||||
|
||||
function buildPayHtml(
|
||||
payUrl: string,
|
||||
params: Record<string, unknown>,
|
||||
options?: { directToCashier?: boolean; displayName?: string; avatar?: string }
|
||||
): string {
|
||||
const flat: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v == null) continue;
|
||||
const s = String(v).trim();
|
||||
if (s === "") continue;
|
||||
flat[k] = s;
|
||||
}
|
||||
const inputs = Object.entries(flat)
|
||||
.map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}" />`)
|
||||
.join("\n");
|
||||
const direct = options?.directToCashier;
|
||||
const displayName = (options?.displayName || "当前用户").trim();
|
||||
const avatar = (options?.avatar || "").trim();
|
||||
const showPayerHint = !!avatar;
|
||||
// direct:微信内无中转,直接提交 | 非 direct:PC/H5 有中转页提示
|
||||
return direct
|
||||
? `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>支付</title><style>body{margin:0;overflow:hidden}</style></head><body><form id="f" action="${escapeAttr(payUrl)}" method="POST" enctype="application/x-www-form-urlencoded">${inputs}</form><script>document.getElementById("f").submit()</script></body></html>`
|
||||
: `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>跳转支付</title><style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;background:#f0f4f8;}.wrap{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;box-shadow:0 8px 26px rgba(15,23,42,.08);}.row{display:flex;align-items:center;gap:10px;}.av{width:30px;height:30px;border-radius:9999px;object-fit:cover;background:#e2e8f0;display:flex;align-items:center;justify-content:center;font-size:13px;}.t1{font-size:13px;color:#0f172a;font-weight:600;}.t2{font-size:12px;color:#64748b;}</style></head><body>${showPayerHint ? `<div class="wrap"><div class="row"><img class="av" src="${escapeAttr(avatar)}" alt="${escapeAttr(displayName)}" /><div><div class="t1">开通对象:${escapeAttr(displayName)}</div><div class="t2">正在为你升级 VIP,马上进入支付...</div></div></div></div>` : ""}<form id="zpayForm" action="${escapeAttr(payUrl)}" method="POST" enctype="application/x-www-form-urlencoded">${inputs}</form><script>document.getElementById("zpayForm").submit();</script></body></html>`;
|
||||
}
|
||||
|
||||
function setPayOrderCookie(res: NextResponse, orderId: string) {
|
||||
res.cookies.set("nomadvip_pay_order", `${orderId}|${Date.now()}`, { path: "/", maxAge: 900 });
|
||||
}
|
||||
|
||||
function setAnonymousUserCookie(
|
||||
res: NextResponse,
|
||||
request: NextRequest,
|
||||
userId: string
|
||||
) {
|
||||
if (!/^user\d+$/.test(userId)) {
|
||||
return;
|
||||
}
|
||||
const options = {
|
||||
...(getCookieOptions(false, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>),
|
||||
httpOnly: false,
|
||||
maxAge: ANONYMOUS_USER_COOKIE_MAX_AGE,
|
||||
};
|
||||
res.cookies.set(ANONYMOUS_USER_COOKIE_NAME, userId, options);
|
||||
}
|
||||
|
||||
async function createPayOrder(
|
||||
apiUrl: string,
|
||||
user_id: string,
|
||||
wechat_userid: string | undefined,
|
||||
return_url: string,
|
||||
total_fee: number,
|
||||
type: string,
|
||||
channel: string,
|
||||
clientIp?: string,
|
||||
provider?: string
|
||||
) {
|
||||
const payload: Record<string, unknown> = {
|
||||
user_id,
|
||||
...(wechat_userid ? { wechat_userid } : {}),
|
||||
site_id: "vip",
|
||||
total_fee,
|
||||
type,
|
||||
channel,
|
||||
return_url,
|
||||
...(clientIp && { client_ip: clientIp }),
|
||||
...(provider && { provider }),
|
||||
};
|
||||
const payh5Url = `${apiUrl}/nomadvip/payh5`;
|
||||
const payh5Timeout = Number(process.env.PAYJSAPI_PAYH5_TIMEOUT) || 60000;
|
||||
console.log("[pay] createPayOrder 请求 payjsapi url=%s timeout=%ds", payh5Url, payh5Timeout / 1000);
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), payh5Timeout);
|
||||
const res = await fetch(payh5Url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const statusOk = data?.status === "ok" || data?.status === "success" || (res.ok && (data?.xorpay_params || data?.params));
|
||||
console.log("[pay] createPayOrder 响应 http=%s status=%s hasParams=%s", res.status, data?.status, !!(data?.xorpay_params || data?.params));
|
||||
if (!res.ok || !statusOk) {
|
||||
const errMsg = data?.detail || data?.msg || data?.error || "支付创建失败";
|
||||
console.error("[pay] createPayOrder 失败:", errMsg, "body=", JSON.stringify(data).slice(0, 300));
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
// xorpay: xorpay_params + xorpay_url | zpay: params + pay_url
|
||||
const params = (data.xorpay_params ?? data.params) || {};
|
||||
const payUrl = data.xorpay_url || data.pay_url || "";
|
||||
if (!params || typeof params !== "object" || Object.keys(params).length === 0) {
|
||||
console.error("[pay] createPayOrder 参数为空 data.keys=", Object.keys(data || {}));
|
||||
throw new Error("payjsapi 未返回支付参数");
|
||||
}
|
||||
return {
|
||||
params: params as Record<string, string>,
|
||||
payUrl,
|
||||
provider: data.provider || "zpay",
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
let body: Record<string, string | number>;
|
||||
const contentType = request.headers.get("content-type") || "";
|
||||
if (contentType.includes("application/json")) {
|
||||
body = (await request.json()) as Record<string, string | number>;
|
||||
} else {
|
||||
const form = await request.formData();
|
||||
body = Object.fromEntries(form.entries()) as Record<string, string>;
|
||||
}
|
||||
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
const apiUrl = (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
console.log("[pay] 立即加入 apiUrl=%s host=%s", apiUrl, hostHeader);
|
||||
let user_id = String(body?.user_id || "").trim();
|
||||
const wechat_userid = String(body?.wechat_userid || body?.userid || "").trim();
|
||||
if (user_id.startsWith("{") && user_id.includes("data")) {
|
||||
try {
|
||||
const parsed = JSON.parse(user_id) as { data?: string };
|
||||
if (parsed?.data) user_id = String(parsed.data).trim();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
const return_url = String(body?.return_url || "").trim();
|
||||
const total_fee = Number(body?.total_fee) || payConfig.defaultAmount || 100;
|
||||
const type = String(body?.type || "vip");
|
||||
const channel = String(body?.channel || "wxpay");
|
||||
const device = String(body?.device || "pc");
|
||||
const wechatNick = String(body?.wechat_nick || body?.nick || body?.user_name || "").trim();
|
||||
const wechatAvatar = String(body?.wechat_avatar || body?.avatar || "").trim();
|
||||
// 渠道规则:pc/手机浏览器 -> zpay,仅微信内 -> xorpay
|
||||
const effectiveProvider =
|
||||
device === "wechat" ? "xorpay" : "zpay";
|
||||
const accept = request.headers.get("accept") || "";
|
||||
const wantHtml = String(body?.html) === "1" || accept.includes("text/html");
|
||||
const preferJson = String(body?.prefer_json) === "1";
|
||||
|
||||
if (!user_id) {
|
||||
if (wantHtml) {
|
||||
return new NextResponse(buildErrorHtml("缺少 user_id"), {
|
||||
status: 400,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: "缺少 user_id" }, { status: 400 });
|
||||
}
|
||||
|
||||
const origin =
|
||||
request.headers.get("x-forwarded-host")
|
||||
? `${request.headers.get("x-forwarded-proto") || "https"}://${request.headers.get("x-forwarded-host")}`
|
||||
: request.headers.get("origin") || "http://localhost:3000";
|
||||
const finalReturnUrl = return_url || `${origin}/paid`;
|
||||
|
||||
const clientIp =
|
||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
|
||||
request.headers.get("x-real-ip") ||
|
||||
"";
|
||||
|
||||
// zpay:直接走 redirect,不先调 payh5(避免 payh5 创建 zpay 订单时阻塞超时)
|
||||
// payjsapi 的 payh5/redirect 可独立调用,内部自建订单。digital/cnomadcna 仍用 payh5+redirect 流程,路由隔离互不影响。
|
||||
if (effectiveProvider === "zpay") {
|
||||
const redirectPayload = {
|
||||
user_id,
|
||||
...(wechat_userid ? { wechat_userid } : {}),
|
||||
site_id: "vip",
|
||||
total_fee,
|
||||
type,
|
||||
channel,
|
||||
return_url: finalReturnUrl,
|
||||
device,
|
||||
provider: "zpay",
|
||||
...(clientIp && { client_ip: clientIp }),
|
||||
};
|
||||
const redirectUrl = `${apiUrl}/nomadvip/payh5/redirect`;
|
||||
const redirectTimeout = Number(process.env.PAYJSAPI_REDIRECT_TIMEOUT) || 60000;
|
||||
console.log("[pay] zpay 直接 redirect url=%s timeout=%ds", redirectUrl, redirectTimeout / 1000);
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), redirectTimeout);
|
||||
const redirectRes = await fetch(redirectUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(redirectPayload),
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
|
||||
if (redirectRes.status >= 301 && redirectRes.status <= 308) {
|
||||
const location = redirectRes.headers.get("location");
|
||||
if (location) {
|
||||
const orderId = redirectRes.headers.get("x-pay-order-id")?.trim() || "";
|
||||
if (!wantHtml || (preferJson && orderId)) {
|
||||
const res = NextResponse.json({
|
||||
ok: true,
|
||||
order_id: orderId,
|
||||
redirect_url: location,
|
||||
provider: "zpay",
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
const res = NextResponse.redirect(location);
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
const resData = await redirectRes.json().catch(() => ({}));
|
||||
|
||||
if (redirectRes.status === 200 && resData?.use_form) {
|
||||
const params = (resData.params ?? resData) as Record<string, string>;
|
||||
const orderId = String(params?.out_trade_no ?? resData?.order_id ?? "").trim();
|
||||
const submitUrl = resData?.pay_url || payConfig.zpaySubmitUrl;
|
||||
const html = buildPayHtml(submitUrl, params || {}, {
|
||||
directToCashier: device === "wechat",
|
||||
displayName: wechatNick || user_id,
|
||||
avatar: wechatAvatar,
|
||||
});
|
||||
const res = new NextResponse(html, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
|
||||
if (redirectRes.status === 200 && resData?.qrcode_mode && resData?.img) {
|
||||
const userId = String(user_id || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const userNick = String(wechatNick || userId).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const userAvatar = String(wechatAvatar || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const returnUrl = String(resData.return_url || finalReturnUrl).replace(
|
||||
/[&<>"']/g,
|
||||
(c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c
|
||||
);
|
||||
const imgSrc = String(resData.img).replace(
|
||||
/[&<>"']/g,
|
||||
(c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c
|
||||
);
|
||||
const orderId = String(resData.order_id || "").replace(
|
||||
/[&<>"']/g,
|
||||
(c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c
|
||||
);
|
||||
const ch = String(resData.channel || "wxpay").toLowerCase();
|
||||
const isWx = ch === "wxpay" || ch === "wx" || ch === "wechat";
|
||||
const title = isWx ? "微信扫码支付" : "支付宝扫码支付";
|
||||
const hint = isWx ? "请使用微信扫描下方二维码完成支付" : "请使用支付宝扫描下方二维码完成支付";
|
||||
const esc = (s: string) =>
|
||||
s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const html = `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>${esc(title)}</title>
|
||||
<style>
|
||||
*{box-sizing:border-box;}
|
||||
body{font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);}
|
||||
.card{background:#fff;border-radius:20px;padding:40px;box-shadow:0 25px 50px -12px rgba(0,0,0,.25);max-width:420px;}
|
||||
h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
|
||||
.hint{color:#64748b;font-size:14px;margin-bottom:20px;}
|
||||
.wait-row{display:flex;align-items:center;justify-content:center;gap:24px;margin:20px 0;}
|
||||
.qr-wrap img{width:200px;height:200px;border-radius:12px;border:2px solid #e2e8f0;background:#fff;}
|
||||
.countdown-wrap{width:72px;height:72px;flex-shrink:0;position:relative;}
|
||||
.countdown-ring{transform:rotate(-90deg);}
|
||||
.countdown-ring circle{fill:none;stroke-width:5;transition:stroke-dashoffset .5s linear;}
|
||||
.countdown-ring .bg{stroke:#e2e8f0;}
|
||||
.countdown-ring .progress{stroke:#22c55e;stroke-linecap:round;}
|
||||
.countdown-inner{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;}
|
||||
.countdown-num{font-size:1rem;font-weight:700;color:#1e293b;line-height:1;}
|
||||
.countdown-unit{font-size:9px;color:#94a3b8;}
|
||||
.tip{font-size:13px;color:#64748b;margin-top:16px;}
|
||||
.payer{display:flex;align-items:center;justify-content:center;gap:10px;margin:0 0 14px;}
|
||||
.payer-avatar{width:30px;height:30px;border-radius:9999px;border:1px solid #e2e8f0;object-fit:cover;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:12px;}
|
||||
.payer-text{font-size:12px;color:#475569;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.success-wrap{display:none;}
|
||||
.success-wrap.show{display:block;}
|
||||
.wait-wrap.hide{display:none;}
|
||||
.success-icon{font-size:4rem;margin-bottom:16px;animation:scaleIn .4s ease;}
|
||||
.success-title{font-size:1.25rem;color:#16a34a;font-weight:600;margin-bottom:8px;}
|
||||
.success-desc{color:#64748b;font-size:14px;margin-bottom:24px;}
|
||||
.success-countdown{font-size:1.5rem;font-weight:700;color:#667eea;}
|
||||
@keyframes scaleIn{from{transform:scale(0);opacity:0;}to{transform:scale(1);opacity:1;}}
|
||||
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.7;}}
|
||||
.pulse{animation:pulse 2s ease-in-out infinite;}
|
||||
</style></head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="wait-wrap" id="waitWrap">
|
||||
<h2>${esc(title)}</h2>
|
||||
<p class="hint">${esc(hint)}</p>
|
||||
${userAvatar ? `<div class="payer"><img class="payer-avatar" src="${userAvatar}" alt="${userNick}" /><span class="payer-text">开通对象:${userNick} · 正在升级 VIP</span></div>` : ""}
|
||||
<div class="wait-row">
|
||||
<div class="countdown-wrap">
|
||||
<svg class="countdown-ring" width="72" height="72" viewBox="0 0 72 72">
|
||||
<circle class="bg" cx="36" cy="36" r="32"/>
|
||||
<circle class="progress" id="progressCircle" cx="36" cy="36" r="32" stroke-dasharray="201" stroke-dashoffset="0"/>
|
||||
</svg>
|
||||
<div class="countdown-inner">
|
||||
<span class="countdown-num" id="countdownNum">5:00</span>
|
||||
<span class="countdown-unit">分</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-wrap">
|
||||
<img src="${imgSrc}" alt="支付二维码" />
|
||||
</div>
|
||||
</div>
|
||||
<p class="tip pulse" id="tip">等待支付中...</p>
|
||||
</div>
|
||||
<div class="success-wrap" id="successWrap">
|
||||
<div class="success-icon">✅</div>
|
||||
<div class="success-title">支付成功</div>
|
||||
<div class="success-desc">感谢您的支持,VIP 权益已开通</div>
|
||||
<div class="success-countdown" id="successCountdown">10 秒后返回首页</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function(){
|
||||
var orderId="${orderId}";
|
||||
var returnUrl="${returnUrl}";
|
||||
var userId="${userId}";
|
||||
if(!orderId){return;}
|
||||
var waitWrap=document.getElementById("waitWrap");
|
||||
var successWrap=document.getElementById("successWrap");
|
||||
var tip=document.getElementById("tip");
|
||||
var countdownNum=document.getElementById("countdownNum");
|
||||
var progressCircle=document.getElementById("progressCircle");
|
||||
var successCountdown=document.getElementById("successCountdown");
|
||||
var maxT=300;
|
||||
var left=maxT;
|
||||
var circumference=2*Math.PI*32;
|
||||
function fmt(t){var m=Math.floor(t/60),s=t%60;return m+":"+(s<10?"0":"")+s;}
|
||||
var countdownTimer=setInterval(function(){
|
||||
left--;
|
||||
countdownNum.textContent=left>60?fmt(left):left;
|
||||
progressCircle.style.strokeDashoffset=circumference*(1-left/maxT);
|
||||
if(left<=0){
|
||||
clearInterval(countdownTimer);
|
||||
tip.textContent="支付超时,返回首页";
|
||||
setTimeout(function(){window.location.href="/";},800);
|
||||
}
|
||||
},1000);
|
||||
function showSuccess(){
|
||||
clearInterval(countdownTimer);
|
||||
waitWrap.classList.add("hide");
|
||||
successWrap.classList.add("show");
|
||||
var s=2;
|
||||
var t=setInterval(function(){
|
||||
s--;
|
||||
successCountdown.textContent=s>0?s+" 秒后返回首页":"返回首页中…";
|
||||
if(s<=0){
|
||||
clearInterval(t);
|
||||
try{localStorage.setItem("userId",userId);if(/^user\\d+$/.test(userId))localStorage.setItem("memosAccount",userId);localStorage.setItem("paidType","vip");if(!localStorage.getItem("emailLinked")&&!localStorage.getItem("userEmail"))localStorage.setItem("userName",userId);}catch(e){}
|
||||
window.location.href="/";
|
||||
}
|
||||
},1000);
|
||||
}
|
||||
function doConfirm(attempt){
|
||||
if(!userId||attempt>=3){showSuccess();return;}
|
||||
fetch("/api/pay/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order_id:orderId,user_id:userId})})
|
||||
.then(function(r){return r.json();})
|
||||
.then(function(cd){
|
||||
if(cd&&cd.ok){showSuccess();}
|
||||
else{setTimeout(function(){doConfirm(attempt+1);},800);}
|
||||
})
|
||||
.catch(function(){setTimeout(function(){doConfirm(attempt+1);},800);});
|
||||
}
|
||||
function check(){
|
||||
fetch("/api/pay/status?order_id="+encodeURIComponent(orderId))
|
||||
.then(function(r){return r.json();})
|
||||
.then(function(d){
|
||||
if(d.ok&&d.paid){
|
||||
doConfirm(0);return;
|
||||
}
|
||||
setTimeout(check,500);
|
||||
})
|
||||
.catch(function(){setTimeout(check,500);});
|
||||
}
|
||||
setTimeout(check,500);
|
||||
})();
|
||||
</script>
|
||||
</body></html>`;
|
||||
const res = new NextResponse(html, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
|
||||
if (redirectRes.status === 400 || redirectRes.status === 500) {
|
||||
const errMsg = resData?.detail || resData?.msg || "zpay redirect 失败";
|
||||
if (wantHtml) {
|
||||
return new NextResponse(buildErrorHtml(errMsg), {
|
||||
status: redirectRes.status,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: errMsg }, { status: redirectRes.status });
|
||||
}
|
||||
|
||||
const errMsg = resData?.detail || resData?.msg || "zpay 未返回有效响应";
|
||||
if (wantHtml) {
|
||||
return new NextResponse(buildErrorHtml(errMsg), {
|
||||
status: 500,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: errMsg }, { status: 500 });
|
||||
}
|
||||
|
||||
// xorpay:调用 payh5 获取收银台参数
|
||||
const { params, payUrl, provider } = await createPayOrder(
|
||||
apiUrl,
|
||||
user_id,
|
||||
wechat_userid || undefined,
|
||||
finalReturnUrl,
|
||||
total_fee,
|
||||
type,
|
||||
channel,
|
||||
clientIp,
|
||||
effectiveProvider
|
||||
);
|
||||
|
||||
if (!params || Object.keys(params).length === 0) {
|
||||
if (wantHtml) {
|
||||
return new NextResponse(buildErrorHtml("支付参数为空"), {
|
||||
status: 500,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: "支付参数为空" }, { status: 500 });
|
||||
}
|
||||
|
||||
// wantHtml=0:返回 JSON,供微信 fetch 后直接提交表单(无中转页)
|
||||
if (!wantHtml) {
|
||||
const orderId = String(params?.order_id || params?.out_trade_no || "").trim();
|
||||
const res = NextResponse.json({
|
||||
ok: true,
|
||||
params,
|
||||
payUrl: provider === "xorpay" ? payUrl : payConfig.zpaySubmitUrl,
|
||||
provider,
|
||||
order_id: orderId,
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
|
||||
// xorpay:直接 payh5 返回收银台参数,无需 redirect 中转
|
||||
const submitUrl = provider === "xorpay" ? payUrl : payConfig.zpaySubmitUrl;
|
||||
if (provider === "xorpay") {
|
||||
const orderId = String(params?.order_id || params?.out_trade_no || "").trim();
|
||||
const html = buildPayHtml(submitUrl, params as Record<string, unknown>, {
|
||||
directToCashier: device === "wechat" || device === "h5",
|
||||
displayName: wechatNick || user_id,
|
||||
avatar: wechatAvatar,
|
||||
});
|
||||
const res = new NextResponse(html, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
if (orderId) setPayOrderCookie(res, orderId);
|
||||
setAnonymousUserCookie(res, request, user_id);
|
||||
return res;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: false, error: "支付渠道异常" }, { status: 500 });
|
||||
} catch (e) {
|
||||
const err = e instanceof Error ? e : new Error(String(e));
|
||||
const msg = err.message || "";
|
||||
const payjsapiHint =
|
||||
"请确认 payjsapi 已启动且 nomadvip 能访问。同机部署可设 PAYMENT_API_INTERNAL_URL=http://127.0.0.1:8007";
|
||||
const hint =
|
||||
msg.includes("fetch") || msg.includes("ECONNREFUSED")
|
||||
? payjsapiHint
|
||||
: err.name === "AbortError"
|
||||
? `请求超时(30s),${payjsapiHint}`
|
||||
: msg;
|
||||
console.error("Pay API error:", err);
|
||||
const errorMsg = `支付请求失败: ${hint}`;
|
||||
const ct = request.headers.get("content-type") || "";
|
||||
const isForm = ct.includes("form") || ct.includes("x-www-form-urlencoded");
|
||||
if (isForm) {
|
||||
return new NextResponse(buildErrorHtml(errorMsg), {
|
||||
status: 500,
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: false, error: errorMsg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
78
app/api/pay/status/route.ts
Normal file
78
app/api/pay/status/route.ts
Normal file
@ -0,0 +1,78 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
import { queryXorPayOrderStatus } from "@vip/app/lib/xorpayStatus";
|
||||
import { queryZPayOrderStatus } from "@vip/app/lib/zpayStatus";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const orderId = request.nextUrl.searchParams.get("order_id");
|
||||
if (!orderId) {
|
||||
return NextResponse.json({ ok: false, error: "missing order_id" }, { status: 400 });
|
||||
}
|
||||
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const url = `${apiUrl}/nomadvip/order_status?order_id=${encodeURIComponent(orderId)}`;
|
||||
console.log("[pay/status] request order_id=%s host=%s url=%s", orderId, hostHeader, url);
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 3000);
|
||||
const res = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
}).finally(() => clearTimeout(timeout));
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const paid = !!data?.paid;
|
||||
console.log(
|
||||
"[pay/status] result order_id=%s paid=%s status=%s",
|
||||
orderId,
|
||||
paid,
|
||||
res.status
|
||||
);
|
||||
if (paid) {
|
||||
return NextResponse.json({ ok: true, paid: true });
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(
|
||||
"[pay/status] error order_id=%s error=%s",
|
||||
orderId,
|
||||
error instanceof Error ? error.message : String(error)
|
||||
);
|
||||
}
|
||||
|
||||
const xorpay = await queryXorPayOrderStatus(orderId, 5000);
|
||||
console.log(
|
||||
"[pay/status] xorpay fallback order_id=%s paid=%s status=%s error=%s url=%s",
|
||||
orderId,
|
||||
!!xorpay?.paid,
|
||||
xorpay?.status || "",
|
||||
xorpay?.error || "",
|
||||
xorpay?.url || ""
|
||||
);
|
||||
if (xorpay?.paid) {
|
||||
return NextResponse.json({ ok: true, paid: true });
|
||||
}
|
||||
|
||||
const zpay = await queryZPayOrderStatus(orderId, 5000);
|
||||
console.log(
|
||||
"[pay/status] zpay fallback order_id=%s paid=%s status=%s error=%s url=%s",
|
||||
orderId,
|
||||
!!zpay?.paid,
|
||||
zpay?.status || "",
|
||||
zpay?.error || "",
|
||||
zpay?.url || ""
|
||||
);
|
||||
if (zpay?.paid) {
|
||||
return NextResponse.json({ ok: true, paid: true });
|
||||
}
|
||||
return NextResponse.json({ ok: true, paid: false });
|
||||
}
|
||||
52
app/api/promo/recognize-discount/route.ts
Normal file
52
app/api/promo/recognize-discount/route.ts
Normal file
@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const hostHeader =
|
||||
request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
getPaymentConfig().apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const image = formData.get("image");
|
||||
if (!(image instanceof File)) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "缺少图片文件 image" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const payload = new FormData();
|
||||
payload.append("image", image, image.name || "proof.jpg");
|
||||
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const res = await fetch(`${apiUrl}/nomadvip/recognize_discount_proof`, {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: data?.error || "识别服务异常" },
|
||||
{ status: res.status }
|
||||
);
|
||||
}
|
||||
return NextResponse.json(data);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : "识别请求失败",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
529
app/api/vip/_helpers.ts
Normal file
529
app/api/vip/_helpers.ts
Normal file
@ -0,0 +1,529 @@
|
||||
import { SITE_ID, getPocketBaseConfig } from "@vip/config/services.config";
|
||||
|
||||
const VIP_EMAIL_LINK_COLLECTION = "vip_email_link";
|
||||
const PB_FETCH_TIMEOUT =
|
||||
Number(process.env.POCKETBASE_FETCH_TIMEOUT) ||
|
||||
(process.env.NODE_ENV === "development" ? 30_000 : 15_000);
|
||||
const PB_ADMIN_TOKEN_TTL_MS = Number(process.env.POCKETBASE_ADMIN_TOKEN_TTL_MS) || 55_000;
|
||||
|
||||
let adminTokenCache: { token: string; expiresAt: number } | null = null;
|
||||
|
||||
type PBRecord = Record<string, unknown>;
|
||||
|
||||
function getPBBaseUrl(): string {
|
||||
return getPocketBaseConfig().url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function escapeFilterValue(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
function uniqueStrings(values: Array<string | null | undefined>): string[] {
|
||||
return Array.from(
|
||||
new Set(
|
||||
values
|
||||
.map((value) => (typeof value === "string" ? value.trim() : ""))
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async function pbFetch(input: string, init: RequestInit = {}): Promise<Response> {
|
||||
const signal = init.signal ?? AbortSignal.timeout(PB_FETCH_TIMEOUT);
|
||||
return fetch(input, { ...init, signal });
|
||||
}
|
||||
|
||||
async function listRecords(
|
||||
collection: string,
|
||||
filter: string,
|
||||
adminToken: string,
|
||||
options: { perPage?: number; sort?: string } = {}
|
||||
): Promise<PBRecord[]> {
|
||||
const url = new URL(`${getPBBaseUrl()}/api/collections/${collection}/records`);
|
||||
url.searchParams.set("filter", filter);
|
||||
url.searchParams.set("perPage", String(options.perPage ?? 20));
|
||||
if (options.sort) {
|
||||
url.searchParams.set("sort", options.sort);
|
||||
}
|
||||
|
||||
const res = await pbFetch(url.toString(), {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return Array.isArray(data?.items) ? data.items : [];
|
||||
}
|
||||
|
||||
async function createRecord(
|
||||
collection: string,
|
||||
adminToken: string,
|
||||
body: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await pbFetch(`${getPBBaseUrl()}/api/collections/${collection}/records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
}
|
||||
|
||||
async function patchRecord(
|
||||
collection: string,
|
||||
recordId: string,
|
||||
adminToken: string,
|
||||
body: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await pbFetch(
|
||||
`${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function deleteRecord(
|
||||
collection: string,
|
||||
recordId: string,
|
||||
adminToken: string
|
||||
): Promise<void> {
|
||||
await pbFetch(
|
||||
`${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function getRecord(
|
||||
collection: string,
|
||||
recordId: string,
|
||||
adminToken: string
|
||||
): Promise<PBRecord | null> {
|
||||
const res = await pbFetch(
|
||||
`${getPBBaseUrl()}/api/collections/${collection}/records/${recordId}`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (await res.json().catch(() => null)) as PBRecord | null;
|
||||
}
|
||||
|
||||
function isVipExpired(expiresAt: unknown): boolean {
|
||||
if (typeof expiresAt !== "string" || !expiresAt.trim()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(expiresAt);
|
||||
return Number.isFinite(timestamp) ? timestamp < Date.now() : false;
|
||||
}
|
||||
|
||||
export function isAnonymousUserId(
|
||||
value: string | null | undefined
|
||||
): value is string {
|
||||
return !!value && /^user\d+$/.test(value);
|
||||
}
|
||||
|
||||
export async function getAdminToken(): Promise<string | null> {
|
||||
const email = process.env.POCKETBASE_EMAIL;
|
||||
const password = process.env.POCKETBASE_PASSWORD;
|
||||
if (!email || !password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (adminTokenCache && adminTokenCache.expiresAt > Date.now()) {
|
||||
return adminTokenCache.token;
|
||||
}
|
||||
|
||||
const baseUrl = getPBBaseUrl();
|
||||
const paths = [
|
||||
"/api/admins/auth-with-password",
|
||||
"/api/collections/_superusers/auth-with-password",
|
||||
];
|
||||
|
||||
for (const path of paths) {
|
||||
const res = await pbFetch(`${baseUrl}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (typeof data?.token === "string" && data.token) {
|
||||
adminTokenCache = {
|
||||
token: data.token,
|
||||
expiresAt: Date.now() + PB_ADMIN_TOKEN_TTL_MS,
|
||||
};
|
||||
return data.token;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function listSiteVipByUserId(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<PBRecord[]> {
|
||||
const safeUserId = escapeFilterValue(userId);
|
||||
const safeSiteId = escapeFilterValue(SITE_ID);
|
||||
return listRecords(
|
||||
"site_vip",
|
||||
`user_id = "${safeUserId}" && site_id = "${safeSiteId}"`,
|
||||
adminToken,
|
||||
{ perPage: 500, sort: "-created" }
|
||||
);
|
||||
}
|
||||
|
||||
export async function listSiteVipByOrderId(
|
||||
adminToken: string,
|
||||
orderId: string
|
||||
): Promise<PBRecord[]> {
|
||||
const safeOrderId = escapeFilterValue(orderId);
|
||||
const safeSiteId = escapeFilterValue(SITE_ID);
|
||||
return listRecords(
|
||||
"site_vip",
|
||||
`order_id = "${safeOrderId}" && site_id = "${safeSiteId}"`,
|
||||
adminToken,
|
||||
{ perPage: 500, sort: "-created" }
|
||||
);
|
||||
}
|
||||
|
||||
async function listPaymentsByOrderId(
|
||||
adminToken: string,
|
||||
orderId: string
|
||||
): Promise<PBRecord[]> {
|
||||
const safeOrderId = escapeFilterValue(orderId);
|
||||
return listRecords(
|
||||
"payments",
|
||||
`order_id = "${safeOrderId}" && type = "vip"`,
|
||||
adminToken,
|
||||
{ perPage: 20, sort: "-created" }
|
||||
);
|
||||
}
|
||||
|
||||
export async function getActiveSiteVipRecord(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<PBRecord | null> {
|
||||
const records = await listSiteVipByUserId(adminToken, userId);
|
||||
for (const record of records) {
|
||||
if (!isVipExpired(record.expires_at)) {
|
||||
return record;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function checkSiteVipByUserId(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<boolean> {
|
||||
return !!(await getActiveSiteVipRecord(adminToken, userId));
|
||||
}
|
||||
|
||||
export async function getLatestVipPayment(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<PBRecord | null> {
|
||||
const safeUserId = escapeFilterValue(userId);
|
||||
const records = await listRecords(
|
||||
"payments",
|
||||
`user_id = "${safeUserId}" && type = "vip"`,
|
||||
adminToken,
|
||||
{ perPage: 1, sort: "-created" }
|
||||
);
|
||||
return records[0] ?? null;
|
||||
}
|
||||
|
||||
export async function checkPaymentsByUserId(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<boolean> {
|
||||
return !!(await getLatestVipPayment(adminToken, userId));
|
||||
}
|
||||
|
||||
export async function hasVipByUserId(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<boolean> {
|
||||
if (!userId) {
|
||||
return false;
|
||||
}
|
||||
if (await checkSiteVipByUserId(adminToken, userId)) {
|
||||
return true;
|
||||
}
|
||||
return checkPaymentsByUserId(adminToken, userId);
|
||||
}
|
||||
|
||||
export async function ensureSiteVipForUser(
|
||||
adminToken: string,
|
||||
fromUserId: string,
|
||||
toUserId: string
|
||||
): Promise<void> {
|
||||
if (!fromUserId || !toUserId || fromUserId === toUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceRecords = await listSiteVipByUserId(adminToken, fromUserId);
|
||||
const targetRecords = await listSiteVipByUserId(adminToken, toUserId);
|
||||
const latestPayment = await getLatestVipPayment(adminToken, fromUserId);
|
||||
const orderId =
|
||||
typeof latestPayment?.order_id === "string" ? latestPayment.order_id.trim() : "";
|
||||
const orderRecords = orderId
|
||||
? await listSiteVipByOrderId(adminToken, orderId)
|
||||
: [];
|
||||
|
||||
const canonicalRecord =
|
||||
targetRecords[0] ?? sourceRecords[0] ?? orderRecords[0] ?? null;
|
||||
const canonicalRecordId =
|
||||
typeof canonicalRecord?.id === "string" ? canonicalRecord.id : "";
|
||||
|
||||
if (canonicalRecordId) {
|
||||
const nextOrderId =
|
||||
orderId ||
|
||||
(typeof canonicalRecord?.order_id === "string"
|
||||
? canonicalRecord.order_id.trim()
|
||||
: "");
|
||||
|
||||
const body: Record<string, unknown> = { user_id: toUserId, site_id: SITE_ID };
|
||||
if (nextOrderId) {
|
||||
body.order_id = nextOrderId;
|
||||
}
|
||||
|
||||
await patchRecord("site_vip", canonicalRecordId, adminToken, body);
|
||||
|
||||
const duplicateIds = new Set<string>();
|
||||
for (const record of [...targetRecords, ...sourceRecords, ...orderRecords]) {
|
||||
const recordId = typeof record.id === "string" ? record.id : "";
|
||||
if (recordId && recordId !== canonicalRecordId) {
|
||||
duplicateIds.add(recordId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const recordId of duplicateIds) {
|
||||
await deleteRecord("site_vip", recordId, adminToken);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!orderId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await createRecord("site_vip", adminToken, {
|
||||
user_id: toUserId,
|
||||
site_id: SITE_ID,
|
||||
order_id: orderId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertVipEmailLink(
|
||||
adminToken: string,
|
||||
email: string,
|
||||
userId: string,
|
||||
anonymousUserId?: string
|
||||
): Promise<void> {
|
||||
if (!email || !userId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
const safeEmail = escapeFilterValue(normalizedEmail);
|
||||
const records = await listRecords(
|
||||
VIP_EMAIL_LINK_COLLECTION,
|
||||
`email = "${safeEmail}"`,
|
||||
adminToken,
|
||||
{ perPage: 1 }
|
||||
);
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
email: normalizedEmail,
|
||||
user_id: userId,
|
||||
};
|
||||
if (anonymousUserId) {
|
||||
body.anonymous_user_id = anonymousUserId;
|
||||
}
|
||||
|
||||
const recordId = typeof records[0]?.id === "string" ? records[0].id : "";
|
||||
if (recordId) {
|
||||
await patchRecord(VIP_EMAIL_LINK_COLLECTION, recordId, adminToken, body);
|
||||
return;
|
||||
}
|
||||
|
||||
await createRecord(VIP_EMAIL_LINK_COLLECTION, adminToken, body);
|
||||
}
|
||||
|
||||
export async function findVipEmailLinkByEmail(
|
||||
adminToken: string,
|
||||
email: string
|
||||
): Promise<PBRecord | null> {
|
||||
const candidates = uniqueStrings([email, email.toLowerCase()]);
|
||||
for (const candidate of candidates) {
|
||||
const safeEmail = escapeFilterValue(candidate);
|
||||
const records = await listRecords(
|
||||
VIP_EMAIL_LINK_COLLECTION,
|
||||
`email = "${safeEmail}"`,
|
||||
adminToken,
|
||||
{ perPage: 1 }
|
||||
);
|
||||
if (records[0]) {
|
||||
return records[0];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function findVipEmailLinkByUserId(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<PBRecord | null> {
|
||||
const safeUserId = escapeFilterValue(userId);
|
||||
const records = await listRecords(
|
||||
VIP_EMAIL_LINK_COLLECTION,
|
||||
`user_id = "${safeUserId}"`,
|
||||
adminToken,
|
||||
{ perPage: 1 }
|
||||
);
|
||||
return records[0] ?? null;
|
||||
}
|
||||
|
||||
export async function findVipEmailLinkByAnonymousUserId(
|
||||
adminToken: string,
|
||||
anonymousUserId: string
|
||||
): Promise<PBRecord | null> {
|
||||
const filters = uniqueStrings([
|
||||
`anonymous_user_id = "${escapeFilterValue(anonymousUserId)}"`,
|
||||
isAnonymousUserId(anonymousUserId)
|
||||
? `user_id = "${escapeFilterValue(anonymousUserId)}"`
|
||||
: null,
|
||||
]);
|
||||
|
||||
for (const filter of filters) {
|
||||
const records = await listRecords(
|
||||
VIP_EMAIL_LINK_COLLECTION,
|
||||
filter,
|
||||
adminToken,
|
||||
{ perPage: 1 }
|
||||
);
|
||||
if (records[0]) {
|
||||
return records[0];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getUserEmailById(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<string | null> {
|
||||
const record = await getRecord("users", userId, adminToken);
|
||||
const email =
|
||||
typeof record?.email === "string" ? record.email.trim().toLowerCase() : "";
|
||||
return email || null;
|
||||
}
|
||||
|
||||
export async function findLinkedMemberFromOrder(
|
||||
adminToken: string,
|
||||
anonymousUserId: string
|
||||
): Promise<{ userId: string; email: string } | null> {
|
||||
const safeUserId = escapeFilterValue(anonymousUserId);
|
||||
const payments = await listRecords(
|
||||
"payments",
|
||||
`user_id = "${safeUserId}" && type = "vip"`,
|
||||
adminToken,
|
||||
{ perPage: 20, sort: "-created" }
|
||||
);
|
||||
|
||||
const seenOrders = new Set<string>();
|
||||
for (const payment of payments) {
|
||||
const orderId =
|
||||
typeof payment.order_id === "string" ? payment.order_id.trim() : "";
|
||||
if (!orderId || seenOrders.has(orderId)) {
|
||||
continue;
|
||||
}
|
||||
seenOrders.add(orderId);
|
||||
|
||||
const siteVipRecords = await listSiteVipByOrderId(adminToken, orderId);
|
||||
for (const record of siteVipRecords) {
|
||||
const linkedUserId =
|
||||
typeof record.user_id === "string" ? record.user_id.trim() : "";
|
||||
if (
|
||||
!linkedUserId ||
|
||||
linkedUserId === anonymousUserId ||
|
||||
isAnonymousUserId(linkedUserId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const email = await getUserEmailById(adminToken, linkedUserId);
|
||||
if (email) {
|
||||
return { userId: linkedUserId, email };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function findAnonymousUserIdForUser(
|
||||
adminToken: string,
|
||||
userId: string
|
||||
): Promise<string | null> {
|
||||
if (isAnonymousUserId(userId)) {
|
||||
return userId;
|
||||
}
|
||||
|
||||
const linkRecord = await findVipEmailLinkByUserId(adminToken, userId);
|
||||
const linkedAnonymousUserId =
|
||||
typeof linkRecord?.anonymous_user_id === "string"
|
||||
? linkRecord.anonymous_user_id.trim()
|
||||
: "";
|
||||
if (isAnonymousUserId(linkedAnonymousUserId)) {
|
||||
return linkedAnonymousUserId;
|
||||
}
|
||||
|
||||
const siteVipRecords = await listSiteVipByUserId(adminToken, userId);
|
||||
for (const record of siteVipRecords) {
|
||||
const orderId =
|
||||
typeof record.order_id === "string" ? record.order_id.trim() : "";
|
||||
if (!orderId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const payments = await listPaymentsByOrderId(adminToken, orderId);
|
||||
for (const payment of payments) {
|
||||
const anonymousUserId =
|
||||
typeof payment.user_id === "string" ? payment.user_id.trim() : "";
|
||||
if (isAnonymousUserId(anonymousUserId)) {
|
||||
return anonymousUserId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
501
app/api/vip/check-by-email/route.ts
Normal file
501
app/api/vip/check-by-email/route.ts
Normal file
@ -0,0 +1,501 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
getApiUrlFromRequest,
|
||||
getPaymentConfig,
|
||||
getPocketBaseConfig,
|
||||
} from "@vip/config/services.config";
|
||||
import {
|
||||
ensureSiteVipForUser,
|
||||
findAnonymousUserIdForUser,
|
||||
findVipEmailLinkByEmail,
|
||||
getAdminToken,
|
||||
hasVipByUserId,
|
||||
isAnonymousUserId,
|
||||
upsertVipEmailLink,
|
||||
} from "@vip/app/api/vip/_helpers";
|
||||
|
||||
type PBAuthRecord = {
|
||||
id: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
type PayjsVipEmailResult = {
|
||||
vip: boolean;
|
||||
error?: string;
|
||||
effectiveUserId?: string;
|
||||
anonymousUserId?: string;
|
||||
token?: string;
|
||||
record?: PBAuthRecord;
|
||||
};
|
||||
|
||||
type RecoveryResult = {
|
||||
vip: boolean;
|
||||
matchedUserId?: string;
|
||||
anonymousUserId?: string;
|
||||
source?: string;
|
||||
};
|
||||
|
||||
const inflightEmailChecks = new Map<string, Promise<PayjsVipEmailResult | null>>();
|
||||
|
||||
const PAYJS_CHECK_BY_EMAIL_TIMEOUT =
|
||||
Number(process.env.PAYJSAPI_CHECK_BY_EMAIL_TIMEOUT) || 20_000;
|
||||
const PAYJS_CHECK_BY_EMAIL_RETRIES =
|
||||
Math.max(0, Number(process.env.PAYJSAPI_CHECK_BY_EMAIL_RETRIES) || 1);
|
||||
|
||||
const PB_USER_LOGIN_TIMEOUT_MS =
|
||||
Number(process.env.POCKETBASE_USER_LOGIN_TIMEOUT_MS) ||
|
||||
(process.env.NODE_ENV === "development" ? 30_000 : 15_000);
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function getLocalPayApiUrl(): string {
|
||||
return (
|
||||
process.env.PAYMENT_API_INTERNAL_URL?.trim() ||
|
||||
"http://127.0.0.1:8007"
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function checkVipByEmailFromPayjsapi(
|
||||
request: NextRequest,
|
||||
email: string,
|
||||
password: string,
|
||||
userId?: string,
|
||||
wechatUserId?: string
|
||||
): Promise<PayjsVipEmailResult | null> {
|
||||
const inflightKey = `${email}::${userId || ""}::${wechatUserId || ""}`;
|
||||
const existed = inflightEmailChecks.get(inflightKey);
|
||||
if (existed) {
|
||||
return existed;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
const payConfig = getPaymentConfig();
|
||||
const primaryUrl = resolvePayApiUrl(request);
|
||||
const localUrl = getLocalPayApiUrl();
|
||||
const candidates = Array.from(
|
||||
new Set(
|
||||
[localUrl, primaryUrl, payConfig.apiUrl]
|
||||
.map((x) => (x || "").trim().replace(/\/$/, ""))
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
|
||||
for (const apiUrl of candidates) {
|
||||
for (let i = 0; i <= PAYJS_CHECK_BY_EMAIL_RETRIES; i += 1) {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/nomadvip/check_vip_by_email`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
...(userId ? { user_id: userId } : {}),
|
||||
...(wechatUserId ? { wechat_userid: wechatUserId } : {}),
|
||||
}),
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(PAYJS_CHECK_BY_EMAIL_TIMEOUT),
|
||||
});
|
||||
if (!res.ok) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!data?.vip) {
|
||||
return {
|
||||
vip: false,
|
||||
error:
|
||||
typeof data?.error === "string" && data.error.trim()
|
||||
? data.error.trim()
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
vip: true,
|
||||
effectiveUserId:
|
||||
typeof data?.effectiveUserId === "string"
|
||||
? data.effectiveUserId.trim()
|
||||
: undefined,
|
||||
anonymousUserId:
|
||||
typeof data?.anonymousUserId === "string"
|
||||
? data.anonymousUserId.trim()
|
||||
: undefined,
|
||||
token: typeof data?.token === "string" ? data.token : undefined,
|
||||
record: data?.record?.id ? data.record : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
if (i >= PAYJS_CHECK_BY_EMAIL_RETRIES) {
|
||||
console.log("[check-by-email] payjsapi request failed url=%s error=%o", apiUrl, error);
|
||||
} else {
|
||||
await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
})();
|
||||
|
||||
inflightEmailChecks.set(inflightKey, task);
|
||||
try {
|
||||
return await task;
|
||||
} finally {
|
||||
inflightEmailChecks.delete(inflightKey);
|
||||
}
|
||||
}
|
||||
|
||||
async function loginPocketBaseUser(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<{ token: string; record: PBAuthRecord }> {
|
||||
const pb = getPocketBaseConfig();
|
||||
const res = await fetch(`${pb.url}/api/collections/users/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(PB_USER_LOGIN_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({}));
|
||||
throw new Error(error?.message || "邮箱或密码错误");
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!data?.token || !data?.record?.id) {
|
||||
throw new Error("登录失败");
|
||||
}
|
||||
|
||||
return {
|
||||
token: data.token,
|
||||
record: data.record,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveRecovery(
|
||||
adminToken: string,
|
||||
email: string,
|
||||
pbUserId: string,
|
||||
requestedAnonymousUserId?: string,
|
||||
payjsResult?: PayjsVipEmailResult | null
|
||||
): Promise<RecoveryResult> {
|
||||
if (isAnonymousUserId(requestedAnonymousUserId)) {
|
||||
const requestUserHasVip = await hasVipByUserId(adminToken, requestedAnonymousUserId);
|
||||
if (requestUserHasVip) {
|
||||
return {
|
||||
vip: true,
|
||||
matchedUserId: requestedAnonymousUserId,
|
||||
anonymousUserId: requestedAnonymousUserId,
|
||||
source: "request_user_id",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const [linkRecord, fallbackAnonymousUserId] = await Promise.all([
|
||||
findVipEmailLinkByEmail(adminToken, email),
|
||||
findAnonymousUserIdForUser(adminToken, pbUserId),
|
||||
]);
|
||||
const linkedAnonymousUserId =
|
||||
typeof linkRecord?.anonymous_user_id === "string"
|
||||
? linkRecord.anonymous_user_id.trim()
|
||||
: fallbackAnonymousUserId ?? "";
|
||||
const linkedIds = Array.from(
|
||||
new Set(
|
||||
[
|
||||
linkedAnonymousUserId,
|
||||
typeof linkRecord?.user_id === "string" ? linkRecord.user_id.trim() : "",
|
||||
pbUserId,
|
||||
].filter(Boolean)
|
||||
)
|
||||
);
|
||||
|
||||
if (linkedIds.length) {
|
||||
const linkedVipChecks = await Promise.all(
|
||||
linkedIds.map(async (linkedId) => ({
|
||||
linkedId,
|
||||
vip: await hasVipByUserId(adminToken, linkedId),
|
||||
}))
|
||||
);
|
||||
const hit = linkedVipChecks.find((item) => item.vip);
|
||||
if (hit) {
|
||||
return {
|
||||
vip: true,
|
||||
matchedUserId: hit.linkedId,
|
||||
anonymousUserId: isAnonymousUserId(linkedAnonymousUserId)
|
||||
? linkedAnonymousUserId
|
||||
: isAnonymousUserId(hit.linkedId)
|
||||
? hit.linkedId
|
||||
: undefined,
|
||||
source: "vip_email_link",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const pbUserHasVip = await hasVipByUserId(adminToken, pbUserId);
|
||||
if (pbUserHasVip) {
|
||||
return {
|
||||
vip: true,
|
||||
matchedUserId: pbUserId,
|
||||
source: "pb_user_id",
|
||||
};
|
||||
}
|
||||
|
||||
const payjsCandidates = Array.from(
|
||||
new Set(
|
||||
[
|
||||
typeof payjsResult?.effectiveUserId === "string"
|
||||
? payjsResult.effectiveUserId.trim()
|
||||
: "",
|
||||
typeof payjsResult?.anonymousUserId === "string"
|
||||
? payjsResult.anonymousUserId.trim()
|
||||
: "",
|
||||
].filter(Boolean)
|
||||
)
|
||||
);
|
||||
|
||||
if (payjsCandidates.length) {
|
||||
const payjsVipChecks = await Promise.all(
|
||||
payjsCandidates.map(async (candidate) => ({
|
||||
candidate,
|
||||
vip: await hasVipByUserId(adminToken, candidate),
|
||||
}))
|
||||
);
|
||||
const hit = payjsVipChecks.find((item) => item.vip);
|
||||
if (hit) {
|
||||
return {
|
||||
vip: true,
|
||||
matchedUserId: hit.candidate,
|
||||
anonymousUserId: isAnonymousUserId(hit.candidate)
|
||||
? hit.candidate
|
||||
: typeof payjsResult?.anonymousUserId === "string" &&
|
||||
isAnonymousUserId(payjsResult.anonymousUserId.trim())
|
||||
? payjsResult.anonymousUserId.trim()
|
||||
: undefined,
|
||||
source: "payjsapi",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { vip: false };
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const email = String(body?.email ?? "").trim().toLowerCase();
|
||||
const password = String(body?.password ?? "").trim();
|
||||
const requestedAnonymousUserId = String(
|
||||
body?.user_id ?? body?.anonymousUserId ?? ""
|
||||
).trim();
|
||||
const wechatUserId = String(
|
||||
body?.wechat_userid ?? body?.userid ?? ""
|
||||
).trim();
|
||||
|
||||
console.log(
|
||||
"[check-by-email] request email=%s user_id=%s",
|
||||
email || "(empty)",
|
||||
requestedAnonymousUserId || "(empty)"
|
||||
);
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, vip: false, error: "请填写邮箱和密码" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const adminTokenPromise = getAdminToken().catch((error) => {
|
||||
console.error("[check-by-email] getAdminToken failed:", error);
|
||||
return null;
|
||||
});
|
||||
|
||||
let authData: { token: string; record: PBAuthRecord } | null = null;
|
||||
let loginError: string | null = null;
|
||||
try {
|
||||
authData = await loginPocketBaseUser(email, password);
|
||||
} catch (error) {
|
||||
loginError = error instanceof Error ? error.message : "登录失败";
|
||||
}
|
||||
|
||||
let payjsResult: PayjsVipEmailResult | null = null;
|
||||
|
||||
if (!authData) {
|
||||
payjsResult = await checkVipByEmailFromPayjsapi(
|
||||
request,
|
||||
email,
|
||||
password,
|
||||
requestedAnonymousUserId || undefined,
|
||||
wechatUserId || undefined
|
||||
);
|
||||
// PB 登录失败时,尝试使用 payjsapi 返回的 token/record 兜底恢复
|
||||
if (payjsResult?.vip && payjsResult.token && payjsResult.record?.id) {
|
||||
console.log("[check-by-email] fallback by payjsapi token email=%s", email);
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: true,
|
||||
token: payjsResult.token,
|
||||
record: payjsResult.record,
|
||||
effectiveUserId: payjsResult.record.id,
|
||||
anonymousUserId: payjsResult.anonymousUserId ?? null,
|
||||
memosAccount: payjsResult.anonymousUserId ?? null,
|
||||
source: "payjsapi_token_fallback",
|
||||
});
|
||||
}
|
||||
const msg = loginError || "登录失败";
|
||||
return NextResponse.json(
|
||||
{ ok: false, vip: false, error: msg },
|
||||
{ status: msg.includes("密码") || msg.includes("邮箱") ? 401 : 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const adminToken = await adminTokenPromise;
|
||||
if (!adminToken) {
|
||||
// 管理员 token 获取失败时,降级到 payjsapi 结果,避免直接 500
|
||||
if (!payjsResult) {
|
||||
payjsResult = await checkVipByEmailFromPayjsapi(
|
||||
request,
|
||||
email,
|
||||
password,
|
||||
requestedAnonymousUserId || undefined,
|
||||
wechatUserId || undefined
|
||||
);
|
||||
}
|
||||
if (payjsResult?.vip) {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: true,
|
||||
token: authData.token,
|
||||
record: authData.record,
|
||||
effectiveUserId: authData.record.id,
|
||||
anonymousUserId: payjsResult.anonymousUserId ?? null,
|
||||
memosAccount: payjsResult.anonymousUserId ?? null,
|
||||
source: "payjsapi_degraded",
|
||||
});
|
||||
}
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
vip: false,
|
||||
error:
|
||||
payjsResult?.error ||
|
||||
"服务繁忙,请稍后重试",
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
let recovery = await resolveRecovery(
|
||||
adminToken,
|
||||
email,
|
||||
authData.record.id,
|
||||
requestedAnonymousUserId || undefined,
|
||||
payjsResult
|
||||
);
|
||||
|
||||
if (!recovery.vip) {
|
||||
payjsResult = await checkVipByEmailFromPayjsapi(
|
||||
request,
|
||||
email,
|
||||
password,
|
||||
requestedAnonymousUserId || undefined,
|
||||
wechatUserId || undefined
|
||||
);
|
||||
recovery = await resolveRecovery(
|
||||
adminToken,
|
||||
email,
|
||||
authData.record.id,
|
||||
requestedAnonymousUserId || undefined,
|
||||
payjsResult
|
||||
);
|
||||
}
|
||||
|
||||
if (!recovery.vip) {
|
||||
console.log(
|
||||
"[check-by-email] no-vip email=%s pbUserId=%s",
|
||||
email,
|
||||
authData.record.id
|
||||
);
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
vip: false,
|
||||
error: payjsResult?.error ||
|
||||
"未找到关联的会员记录,请确认已支付并绑定邮箱;如为历史匿名订单,可填写支付时的 user_id 再登录",
|
||||
});
|
||||
}
|
||||
|
||||
let fallbackAnonymousUserId: string | undefined;
|
||||
if (
|
||||
isAnonymousUserId(requestedAnonymousUserId) &&
|
||||
(await hasVipByUserId(adminToken, requestedAnonymousUserId))
|
||||
) {
|
||||
fallbackAnonymousUserId = requestedAnonymousUserId;
|
||||
} else {
|
||||
fallbackAnonymousUserId =
|
||||
(await findAnonymousUserIdForUser(adminToken, authData.record.id)) ||
|
||||
(typeof payjsResult?.anonymousUserId === "string" &&
|
||||
isAnonymousUserId(payjsResult.anonymousUserId.trim())
|
||||
? payjsResult.anonymousUserId.trim()
|
||||
: undefined);
|
||||
}
|
||||
|
||||
const anonymousUserId =
|
||||
recovery.anonymousUserId || fallbackAnonymousUserId;
|
||||
|
||||
if (isAnonymousUserId(anonymousUserId)) {
|
||||
await ensureSiteVipForUser(adminToken, anonymousUserId, authData.record.id);
|
||||
}
|
||||
|
||||
await upsertVipEmailLink(
|
||||
adminToken,
|
||||
email,
|
||||
authData.record.id,
|
||||
anonymousUserId
|
||||
);
|
||||
|
||||
if (wechatUserId) {
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
await fetch(`${apiUrl}/nomadvip/wechat_profile`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
user_id: anonymousUserId || authData.record.id,
|
||||
email,
|
||||
wechat_userid: wechatUserId,
|
||||
}),
|
||||
cache: "no-store",
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
console.log(
|
||||
"[check-by-email] success source=%s pbUserId=%s anonymousUserId=%s",
|
||||
recovery.source ?? "pocketbase",
|
||||
authData.record.id,
|
||||
anonymousUserId ?? "(none)"
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: true,
|
||||
token: authData.token,
|
||||
record: authData.record,
|
||||
effectiveUserId: authData.record.id,
|
||||
anonymousUserId: anonymousUserId ?? null,
|
||||
memosAccount: anonymousUserId ?? null,
|
||||
source: recovery.source ?? "pocketbase",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "登录失败";
|
||||
const status = message.includes("密码") || message.includes("邮箱") ? 401 : 500;
|
||||
return NextResponse.json(
|
||||
{ ok: false, vip: false, error: message },
|
||||
{ status }
|
||||
);
|
||||
}
|
||||
}
|
||||
327
app/api/vip/check-by-user/route.ts
Normal file
327
app/api/vip/check-by-user/route.ts
Normal file
@ -0,0 +1,327 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
import {
|
||||
checkPaymentsByUserId,
|
||||
checkSiteVipByUserId,
|
||||
findLinkedMemberFromOrder,
|
||||
findVipEmailLinkByAnonymousUserId,
|
||||
getAdminToken,
|
||||
isAnonymousUserId,
|
||||
upsertVipEmailLink,
|
||||
} from "@vip/app/api/vip/_helpers";
|
||||
|
||||
type PayjsVipResult = {
|
||||
vip: boolean;
|
||||
email?: string;
|
||||
linkedUserId?: string;
|
||||
};
|
||||
|
||||
const inflightUserChecks = new Map<string, Promise<PayjsVipResult | null>>();
|
||||
type UserCheckPayload = {
|
||||
ok: boolean;
|
||||
vip: boolean;
|
||||
alreadyLinked: boolean;
|
||||
/** 服务端异常/超时时为 true,前端勿据此清空本地已登录 VIP */
|
||||
uncertain?: boolean;
|
||||
email?: string;
|
||||
linkedUserId?: string;
|
||||
};
|
||||
const inflightUserRequests = new Map<
|
||||
string,
|
||||
Promise<UserCheckPayload>
|
||||
>();
|
||||
const userCheckResultCache = new Map<
|
||||
string,
|
||||
{
|
||||
expiresAt: number;
|
||||
payload: UserCheckPayload;
|
||||
}
|
||||
>();
|
||||
const USER_CHECK_CACHE_TTL_MS = Number(process.env.CHECK_BY_USER_CACHE_TTL_MS) || 10_000;
|
||||
|
||||
async function fetchPayjsVipWithRetry(
|
||||
url: string,
|
||||
timeoutMs: number,
|
||||
retries: number
|
||||
): Promise<Response | null> {
|
||||
let lastError: unknown = null;
|
||||
for (let i = 0; i <= retries; i += 1) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return res;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (i < retries) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 250 * (i + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error("payjsapi fetch failed");
|
||||
}
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function checkVipFromPayjsapi(
|
||||
request: NextRequest,
|
||||
userId: string
|
||||
): Promise<PayjsVipResult | null> {
|
||||
const existed = inflightUserChecks.get(userId);
|
||||
if (existed) {
|
||||
return existed;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const url = `${apiUrl}/nomadvip/check_vip?user_id=${encodeURIComponent(
|
||||
userId
|
||||
)}`;
|
||||
console.log("[check-by-user] payjsapi request user_id=%s url=%s", userId, url);
|
||||
const checkTimeout = Number(process.env.PAYJSAPI_CHECK_TIMEOUT) || 15_000;
|
||||
const retries = Math.max(0, Number(process.env.PAYJSAPI_CHECK_RETRIES) || 1);
|
||||
const res = await fetchPayjsVipWithRetry(url, checkTimeout, retries);
|
||||
if (!res) {
|
||||
return null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
console.log(
|
||||
"[check-by-user] payjsapi non-ok user_id=%s status=%s",
|
||||
userId,
|
||||
res.status
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const result = {
|
||||
vip: !!data?.vip,
|
||||
email:
|
||||
typeof data?.email === "string" && data.email.trim()
|
||||
? data.email.trim().toLowerCase()
|
||||
: undefined,
|
||||
linkedUserId:
|
||||
typeof data?.linked_user_id === "string" && data.linked_user_id.trim()
|
||||
? data.linked_user_id.trim()
|
||||
: undefined,
|
||||
};
|
||||
console.log(
|
||||
"[check-by-user] payjsapi response user_id=%s vip=%s email=%s",
|
||||
userId,
|
||||
result.vip,
|
||||
result.email ?? "(none)"
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.log(
|
||||
"[check-by-user] payjsapi request failed user_id=%s error=%s",
|
||||
userId,
|
||||
error instanceof Error ? error.message : String(error)
|
||||
);
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
inflightUserChecks.set(userId, task);
|
||||
try {
|
||||
return await task;
|
||||
} finally {
|
||||
inflightUserChecks.delete(userId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const userId = String(body?.user_id ?? body?.userId ?? "").trim();
|
||||
|
||||
console.log("[check-by-user] request user_id=%s", userId || "(empty)");
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, vip: false, error: "缺少 user_id" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const cached = userCheckResultCache.get(userId);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return NextResponse.json(cached.payload);
|
||||
}
|
||||
if (cached) {
|
||||
userCheckResultCache.delete(userId);
|
||||
}
|
||||
|
||||
const inflight = inflightUserRequests.get(userId);
|
||||
if (inflight) {
|
||||
const payload = await inflight;
|
||||
return NextResponse.json(payload);
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
let payjsResult: PayjsVipResult | null = null;
|
||||
let vip = false;
|
||||
let email: string | null = null;
|
||||
let linkedUserId: string | undefined;
|
||||
let vipFromSite = false;
|
||||
let vipFromPayments = false;
|
||||
let vipSource = "none";
|
||||
|
||||
try {
|
||||
const adminToken = await getAdminToken().catch((error) => {
|
||||
console.error("[check-by-user] getAdminToken failed:", error);
|
||||
return null;
|
||||
});
|
||||
if (!adminToken) {
|
||||
payjsResult = await checkVipFromPayjsapi(request, userId);
|
||||
vip = !!payjsResult?.vip;
|
||||
email = payjsResult?.email ?? null;
|
||||
console.error("[check-by-user] missing PocketBase admin token, fallback to payjs result");
|
||||
return {
|
||||
ok: true,
|
||||
vip,
|
||||
alreadyLinked: !!email,
|
||||
email: email ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (!vip) {
|
||||
vipFromSite = await checkSiteVipByUserId(adminToken, userId);
|
||||
vip = vipFromSite;
|
||||
if (!vip) {
|
||||
vipFromPayments = await checkPaymentsByUserId(adminToken, userId);
|
||||
vip = vipFromPayments;
|
||||
}
|
||||
if (vipFromSite) {
|
||||
vipSource = "pocketbase:site_vip";
|
||||
} else if (vipFromPayments) {
|
||||
vipSource = "pocketbase:payments";
|
||||
}
|
||||
console.log(
|
||||
"[check-by-user] pb fallback user_id=%s site_vip=%s payments=%s",
|
||||
userId,
|
||||
vipFromSite,
|
||||
vipFromPayments
|
||||
);
|
||||
}
|
||||
|
||||
// 同机 PB 命中则不再打 payjsapi;仅未命中时再走 payjs(与线上极致路径一致)
|
||||
if (!vip) {
|
||||
payjsResult = await checkVipFromPayjsapi(request, userId);
|
||||
if (payjsResult?.vip) {
|
||||
vip = true;
|
||||
email = payjsResult.email ?? null;
|
||||
linkedUserId = payjsResult.linkedUserId;
|
||||
vipSource = "payjsapi";
|
||||
}
|
||||
}
|
||||
|
||||
if (isAnonymousUserId(userId)) {
|
||||
const linkRecord = await findVipEmailLinkByAnonymousUserId(adminToken, userId);
|
||||
const linkEmail =
|
||||
typeof linkRecord?.email === "string"
|
||||
? linkRecord.email.trim().toLowerCase()
|
||||
: "";
|
||||
const linkUserId =
|
||||
typeof linkRecord?.user_id === "string" ? linkRecord.user_id.trim() : "";
|
||||
|
||||
// 匿名 user_id 本身可能已迁移到真实用户,需补查映射用户的 VIP
|
||||
if (!vip && linkUserId && linkUserId !== userId) {
|
||||
const linkedVip = await checkSiteVipByUserId(adminToken, linkUserId);
|
||||
const linkedPaymentVip = linkedVip
|
||||
? true
|
||||
: await checkPaymentsByUserId(adminToken, linkUserId);
|
||||
if (linkedVip || linkedPaymentVip) {
|
||||
vip = true;
|
||||
linkedUserId = linkUserId;
|
||||
vipSource = linkedVip ? "vip_email_link:site_vip" : "vip_email_link:payments";
|
||||
}
|
||||
}
|
||||
|
||||
if (vip && linkEmail) {
|
||||
email = linkEmail;
|
||||
if (linkUserId && !isAnonymousUserId(linkUserId)) {
|
||||
linkedUserId = linkUserId;
|
||||
}
|
||||
if (!vipSource || vipSource === "none") {
|
||||
vipSource = "vip_email_link";
|
||||
}
|
||||
console.log(
|
||||
"[check-by-user] linked by vip_email_link user_id=%s linkedUserId=%s email=%s",
|
||||
userId,
|
||||
linkedUserId || "(none)",
|
||||
email
|
||||
);
|
||||
} else if (vip) {
|
||||
const linkedMember = await findLinkedMemberFromOrder(adminToken, userId);
|
||||
if (linkedMember) {
|
||||
email = linkedMember.email;
|
||||
linkedUserId = linkedMember.userId;
|
||||
await upsertVipEmailLink(
|
||||
adminToken,
|
||||
linkedMember.email,
|
||||
linkedMember.userId,
|
||||
userId
|
||||
);
|
||||
vipSource = "linked_from_order";
|
||||
console.log(
|
||||
"[check-by-user] linked by order user_id=%s linkedUserId=%s email=%s",
|
||||
userId,
|
||||
linkedUserId,
|
||||
email
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
"[check-by-user] result user_id=%s vip=%s source=%s alreadyLinked=%s linkedUserId=%s",
|
||||
userId,
|
||||
vip,
|
||||
vipSource,
|
||||
!!email,
|
||||
linkedUserId || "(none)"
|
||||
);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
vip,
|
||||
alreadyLinked: !!email,
|
||||
email: email ?? undefined,
|
||||
linkedUserId,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[check-by-user] failed:", error);
|
||||
// 勿伪装成「确定非 VIP」,否则微信/H5 弱网会误清本地态
|
||||
return {
|
||||
ok: false,
|
||||
vip: false,
|
||||
alreadyLinked: false,
|
||||
uncertain: true,
|
||||
};
|
||||
}
|
||||
})();
|
||||
|
||||
inflightUserRequests.set(userId, task);
|
||||
try {
|
||||
const payload = await task;
|
||||
// 只缓存命中结果,避免绑定邮箱后的短时 false 缓存导致需要多次刷新才恢复
|
||||
if (!payload.uncertain && payload.vip) {
|
||||
userCheckResultCache.set(userId, {
|
||||
payload,
|
||||
expiresAt: Date.now() + USER_CHECK_CACHE_TTL_MS,
|
||||
});
|
||||
}
|
||||
return NextResponse.json(payload);
|
||||
} finally {
|
||||
inflightUserRequests.delete(userId);
|
||||
}
|
||||
}
|
||||
95
app/api/vip/check/route.ts
Normal file
95
app/api/vip/check/route.ts
Normal file
@ -0,0 +1,95 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME } from "@vip/app/lib/auth-cookie";
|
||||
import {
|
||||
findVipEmailLinkByUserId,
|
||||
getActiveSiteVipRecord,
|
||||
getAdminToken,
|
||||
hasVipByUserId,
|
||||
isAnonymousUserId,
|
||||
} from "@vip/app/api/vip/_helpers";
|
||||
|
||||
type SessionPayload = {
|
||||
userId?: string;
|
||||
anonymousUserId?: string;
|
||||
};
|
||||
|
||||
function readSessionPayload(request: NextRequest): SessionPayload | null {
|
||||
const raw = request.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(Buffer.from(raw, "base64url").toString("utf-8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const payload = readSessionPayload(request);
|
||||
const userId =
|
||||
typeof payload?.userId === "string" ? payload.userId.trim() : "";
|
||||
const anonymousUserId =
|
||||
typeof payload?.anonymousUserId === "string"
|
||||
? payload.anonymousUserId.trim()
|
||||
: "";
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ ok: true, vip: false });
|
||||
}
|
||||
|
||||
try {
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
// 未配置 POCKETBASE_EMAIL/PASSWORD 等时无法校验;前端勿据此清空本地已登录态
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: false,
|
||||
adminUnavailable: true,
|
||||
});
|
||||
}
|
||||
|
||||
const userRecord = await getActiveSiteVipRecord(adminToken, userId);
|
||||
if (userRecord) {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: true,
|
||||
expires_at:
|
||||
typeof userRecord.expires_at === "string" ? userRecord.expires_at : null,
|
||||
});
|
||||
}
|
||||
|
||||
if (await hasVipByUserId(adminToken, userId)) {
|
||||
return NextResponse.json({ ok: true, vip: true, expires_at: null });
|
||||
}
|
||||
|
||||
const candidates = isAnonymousUserId(anonymousUserId)
|
||||
? [anonymousUserId]
|
||||
: [];
|
||||
if (!isAnonymousUserId(userId)) {
|
||||
const linkRecord = await findVipEmailLinkByUserId(adminToken, userId);
|
||||
const linkedAnonymousUserId =
|
||||
typeof linkRecord?.anonymous_user_id === "string"
|
||||
? linkRecord.anonymous_user_id.trim()
|
||||
: "";
|
||||
if (isAnonymousUserId(linkedAnonymousUserId)) {
|
||||
candidates.push(linkedAnonymousUserId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (await hasVipByUserId(adminToken, candidate)) {
|
||||
return NextResponse.json({ ok: true, vip: true, expires_at: null });
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, vip: false });
|
||||
} catch {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
vip: false,
|
||||
uncertain: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
32
app/api/vip/identity-diagnose/route.ts
Normal file
32
app/api/vip/identity-diagnose/route.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader =
|
||||
request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) || payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const res = await fetch(`${apiUrl}/nomadvip/identity_diagnose`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
cache: "no-store",
|
||||
}).catch(() => null);
|
||||
|
||||
if (!res) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "upstream unavailable" },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return NextResponse.json(data, { status: res.ok ? 200 : 502 });
|
||||
}
|
||||
|
||||
115
app/api/vip/linked-email/route.ts
Normal file
115
app/api/vip/linked-email/route.ts
Normal file
@ -0,0 +1,115 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
import {
|
||||
findAnonymousUserIdForUser,
|
||||
findLinkedMemberFromOrder,
|
||||
findVipEmailLinkByAnonymousUserId,
|
||||
findVipEmailLinkByUserId,
|
||||
getAdminToken,
|
||||
isAnonymousUserId,
|
||||
upsertVipEmailLink,
|
||||
} from "@vip/app/api/vip/_helpers";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function getLinkedEmailFromPayjsapi(
|
||||
request: NextRequest,
|
||||
userId: string
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const res = await fetch(
|
||||
`${apiUrl}/nomadvip/check_vip?user_id=${encodeURIComponent(userId)}`,
|
||||
{ cache: "no-store", signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
if (!res.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const email =
|
||||
typeof data?.email === "string" ? data.email.trim().toLowerCase() : "";
|
||||
return data?.vip && email ? email : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const userId = request.nextUrl.searchParams.get("user_id")?.trim() || "";
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ email: null, error: "缺少 user_id" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json({ email: null }, { status: 500 });
|
||||
}
|
||||
|
||||
const linkRecord = isAnonymousUserId(userId)
|
||||
? await findVipEmailLinkByAnonymousUserId(adminToken, userId)
|
||||
: await findVipEmailLinkByUserId(adminToken, userId);
|
||||
const linkedEmail =
|
||||
typeof linkRecord?.email === "string"
|
||||
? linkRecord.email.trim().toLowerCase()
|
||||
: "";
|
||||
const anonymousUserId =
|
||||
typeof linkRecord?.anonymous_user_id === "string" &&
|
||||
isAnonymousUserId(linkRecord.anonymous_user_id.trim())
|
||||
? linkRecord.anonymous_user_id.trim()
|
||||
: !isAnonymousUserId(userId)
|
||||
? await findAnonymousUserIdForUser(adminToken, userId)
|
||||
: isAnonymousUserId(userId)
|
||||
? userId
|
||||
: null;
|
||||
if (linkedEmail) {
|
||||
return NextResponse.json({
|
||||
email: linkedEmail,
|
||||
anonymousUserId,
|
||||
});
|
||||
}
|
||||
|
||||
if (isAnonymousUserId(userId)) {
|
||||
const linkedMember = await findLinkedMemberFromOrder(adminToken, userId);
|
||||
if (linkedMember) {
|
||||
await upsertVipEmailLink(
|
||||
adminToken,
|
||||
linkedMember.email,
|
||||
linkedMember.userId,
|
||||
userId
|
||||
);
|
||||
return NextResponse.json({
|
||||
email: linkedMember.email,
|
||||
anonymousUserId: userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const payjsEmail = await getLinkedEmailFromPayjsapi(request, userId);
|
||||
if (payjsEmail) {
|
||||
if (anonymousUserId && !isAnonymousUserId(userId)) {
|
||||
await upsertVipEmailLink(adminToken, payjsEmail, userId, anonymousUserId);
|
||||
}
|
||||
return NextResponse.json({
|
||||
email: payjsEmail,
|
||||
anonymousUserId: anonymousUserId ?? (isAnonymousUserId(userId) ? userId : null),
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ email: null, anonymousUserId: anonymousUserId ?? null });
|
||||
} catch (error) {
|
||||
console.error("[linked-email] failed:", error);
|
||||
return NextResponse.json({ email: null, anonymousUserId: null }, { status: 500 });
|
||||
}
|
||||
}
|
||||
29
app/api/vip/wechat-profile/route.ts
Normal file
29
app/api/vip/wechat-profile/route.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@vip/config/services.config";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return (
|
||||
(hostHeader ? getApiUrlFromRequest(hostHeader) : null) ||
|
||||
payConfig.apiUrl
|
||||
).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const res = await fetch(`${apiUrl}/nomadvip/wechat_profile`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
cache: "no-store",
|
||||
}).catch(() => null);
|
||||
|
||||
if (!res) {
|
||||
return NextResponse.json({ ok: false, found: false, error: "upstream unavailable" }, { status: 502 });
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return NextResponse.json(data, { status: res.ok ? 200 : 502 });
|
||||
}
|
||||
|
||||
@ -95,7 +95,7 @@ export default function ProfilePage() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
router.push("/community/login?next=/profile");
|
||||
router.push("/community/login?next=/community/profile");
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
|
||||
@ -56,6 +56,7 @@ export default function RootLayout({
|
||||
<html
|
||||
lang="zh-CN"
|
||||
className={`${outfit.variable} ${notoSansSC.variable}`}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
<body className="antialiased">
|
||||
<UmamiAnalytics />
|
||||
|
||||
1036
app/vip/HomeClient.tsx
Normal file
1036
app/vip/HomeClient.tsx
Normal file
File diff suppressed because it is too large
Load Diff
15
app/vip/HomeClientLoader.tsx
Normal file
15
app/vip/HomeClientLoader.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
const HomeClient = dynamic(() => import("./HomeClient"), {
|
||||
ssr: false,
|
||||
/** 仅纯色底,避免分包加载前白屏;真正 VIP/非 VIP 界面由 HomeClient 首帧同步读 localStorage 渲染 */
|
||||
loading: () => (
|
||||
<div className="min-h-screen bg-[var(--background)]" aria-hidden />
|
||||
),
|
||||
});
|
||||
|
||||
export function HomeClientLoader() {
|
||||
return <HomeClient />;
|
||||
}
|
||||
407
app/vip/cloudphone/cloudphone.module.css
Normal file
407
app/vip/cloudphone/cloudphone.module.css
Normal file
@ -0,0 +1,407 @@
|
||||
/* 云手机 - video.hackrobot.cn 课程落地页风格 */
|
||||
|
||||
.root {
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 50%, #e2e8f0 100%);
|
||||
color: #1e293b;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1rem 1.5rem;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.logo:hover {
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.backLink {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.backLink:hover {
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.hero {
|
||||
text-align: center;
|
||||
padding: 4rem 1.5rem 3rem;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.heroTitle {
|
||||
font-size: clamp(2rem, 5vw, 3rem);
|
||||
font-weight: 800;
|
||||
color: #0f172a;
|
||||
margin: 0 0 1rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.heroSubtitle {
|
||||
font-size: 1.1rem;
|
||||
color: #475569;
|
||||
margin: 0 0 2rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 2rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.stat {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.statValue {
|
||||
display: block;
|
||||
font-size: 2rem;
|
||||
font-weight: 800;
|
||||
color: #0284c7;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.statLabel {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.ctaBtn {
|
||||
display: inline-block;
|
||||
padding: 0.9rem 2rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
|
||||
border-radius: 9999px;
|
||||
text-decoration: none;
|
||||
box-shadow: 0 4px 14px rgba(2, 132, 199, 0.4);
|
||||
transition: transform 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
|
||||
.ctaBtn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(2, 132, 199, 0.5);
|
||||
}
|
||||
|
||||
/* Sections */
|
||||
.section {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 3rem 1.5rem;
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
text-align: center;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.sectionDesc {
|
||||
text-align: center;
|
||||
color: #64748b;
|
||||
margin: 0 0 2rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 这门课适合谁 */
|
||||
.audienceGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(1, 1fr);
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.audienceGrid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.audienceGrid {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.audienceCard {
|
||||
padding: 1.5rem;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid #f1f5f9;
|
||||
transition: box-shadow 0.2s, transform 0.2s;
|
||||
}
|
||||
|
||||
.audienceCard:hover {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.audienceIcon {
|
||||
font-size: 2rem;
|
||||
display: block;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.audienceCard h3 {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.audienceCard p {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* 学完你将获得 */
|
||||
.benefitsList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.benefitItem {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
padding: 1.25rem;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #f1f5f9;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.benefitNum {
|
||||
flex-shrink: 0;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
|
||||
color: white;
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.benefitItem h3 {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.benefitItem p {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* 实战课程 - 复刻 video.hackrobot.cn 样式 */
|
||||
.curriculum {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.curriculumBlock {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #e2e8f0;
|
||||
overflow: hidden;
|
||||
transition: box-shadow 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
.curriculumBlock:hover {
|
||||
border-color: #cbd5e1;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.curriculumHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.curriculumHeaderIcon {
|
||||
font-size: 1rem;
|
||||
color: #0284c7;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.curriculumTitle {
|
||||
flex: 1;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.curriculumCount {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: #64748b;
|
||||
background: #e2e8f0;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.curriculumList {
|
||||
margin: 0;
|
||||
padding: 0.5rem 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.curriculumItem {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.curriculumItemLink {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.65rem 1.25rem;
|
||||
color: #334155;
|
||||
text-decoration: none;
|
||||
font-size: 0.95rem;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.curriculumItemLink:hover {
|
||||
background: #f0f9ff;
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.curriculumItemLink::before {
|
||||
content: "";
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #cbd5e1;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.curriculumItemLink:hover::before {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
.curriculumTryBadge {
|
||||
font-size: 0.75rem;
|
||||
color: #0284c7;
|
||||
margin-left: 0.25rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.curriculumArrow {
|
||||
margin-left: auto;
|
||||
font-size: 0.85rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.curriculumItemLink:hover .curriculumArrow {
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
/* FAQ */
|
||||
.faq {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.faqItem {
|
||||
padding: 1rem 1.25rem;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #e2e8f0;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.faqQ {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 500;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
/* CTA Section */
|
||||
.ctaSection {
|
||||
text-align: center;
|
||||
padding: 4rem 1.5rem;
|
||||
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.ctaSection h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.ctaSection p {
|
||||
font-size: 1rem;
|
||||
color: #94a3b8;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.ctaFeatures {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.ctaSection .ctaBtn {
|
||||
background: linear-gradient(135deg, #38bdf8 0%, #0284c7 100%);
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.footer {
|
||||
text-align: center;
|
||||
padding: 2rem 1.5rem;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.footer p {
|
||||
font-size: 0.9rem;
|
||||
color: #64748b;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
font-size: 0.85rem;
|
||||
color: #0284c7;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
41
app/vip/cloudphone/components/AnimateOnScroll.tsx
Normal file
41
app/vip/cloudphone/components/AnimateOnScroll.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useEffect, useState, type ReactNode } from "react";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
delay?: number;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function AnimateOnScroll({ children, delay = 0, className = "" }: Props) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry?.isIntersecting) setVisible(true);
|
||||
},
|
||||
{ threshold: 0.08, rootMargin: "0px 0px -40px 0px" }
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={className}
|
||||
style={{
|
||||
opacity: visible ? 1 : 0,
|
||||
transform: visible ? "translateY(0)" : "translateY(24px)",
|
||||
transition: `opacity 0.6s ease-out ${delay}ms, transform 0.6s ease-out ${delay}ms`,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
app/vip/cloudphone/components/ChatFloatButton.tsx
Normal file
61
app/vip/cloudphone/components/ChatFloatButton.tsx
Normal file
@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { isPaid } from "../lib/payment";
|
||||
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
|
||||
|
||||
const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot";
|
||||
|
||||
export function ChatFloatButton() {
|
||||
const [paid, setPaid] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setPaid(isPaid());
|
||||
const onPayUpdate = () => setPaid(isPaid());
|
||||
window.addEventListener("pay:updated", onPayUpdate);
|
||||
return () => window.removeEventListener("pay:updated", onPayUpdate);
|
||||
}, []);
|
||||
|
||||
const baseClass =
|
||||
"animate__animated animate__bounceIn fixed bottom-6 right-6 z-40 flex h-12 w-12 items-center justify-center rounded-full shadow-lg transition-all hover:scale-110";
|
||||
const paidClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40";
|
||||
const lockedClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40";
|
||||
|
||||
if (paid) {
|
||||
return (
|
||||
<span className="hidden">
|
||||
<a
|
||||
href={CHAT_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={`${baseClass} ${paidClass}`}
|
||||
style={{ animationDelay: "0.5s", animationFillMode: "both" }}
|
||||
aria-label="即时问答"
|
||||
>
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
</a>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setModalOpen(true)}
|
||||
className={`${baseClass} ${lockedClass}`}
|
||||
style={{ animationDelay: "0.5s", animationFillMode: "both" }}
|
||||
aria-label="即时问答(开通VIP解锁)"
|
||||
title="即时问答"
|
||||
>
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
</button>
|
||||
<InstantQaVipModal open={modalOpen} onClose={() => setModalOpen(false)} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
68
app/vip/cloudphone/components/Footer.tsx
Normal file
68
app/vip/cloudphone/components/Footer.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { SITE_CONFIG } from "../config/course";
|
||||
import { isPaid } from "../lib/payment";
|
||||
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
|
||||
|
||||
const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot";
|
||||
|
||||
export function Footer() {
|
||||
const [paid, setPaid] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setPaid(isPaid());
|
||||
const onPayUpdate = () => setPaid(isPaid());
|
||||
window.addEventListener("pay:updated", onPayUpdate);
|
||||
return () => window.removeEventListener("pay:updated", onPayUpdate);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<footer className="animate__animated animate__fadeInUp border-t border-[var(--border)] py-6 sm:py-8" style={{ animationDelay: "0.1s", animationFillMode: "both" }}>
|
||||
<div className="mx-auto max-w-6xl px-4 sm:px-6">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-center gap-4">
|
||||
<Link href="/" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
|
||||
返回首页
|
||||
</Link>
|
||||
<Link href="/vip/cloudphone" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
|
||||
课程首页
|
||||
</Link>
|
||||
{paid ? (
|
||||
<span className="hidden">
|
||||
<a
|
||||
href={CHAT_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 rounded-full bg-[var(--accent)]/15 px-4 py-2 text-sm font-medium text-[var(--accent)] transition hover:bg-[var(--accent)]/25 hover:text-[var(--accent)]"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
即时问答
|
||||
</a>
|
||||
</span>
|
||||
) : (
|
||||
<span className="hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setModalOpen(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-full bg-[var(--accent)]/15 px-4 py-2 text-sm font-medium text-[var(--accent)] transition hover:bg-[var(--accent)]/25 hover:text-[var(--accent)]"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
即时问答
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-center text-sm text-[var(--muted-foreground)]">
|
||||
{SITE_CONFIG.footer}
|
||||
</div>
|
||||
</div>
|
||||
<InstantQaVipModal open={modalOpen} onClose={() => setModalOpen(false)} />
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
105
app/vip/cloudphone/components/Header.tsx
Normal file
105
app/vip/cloudphone/components/Header.tsx
Normal file
@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { SITE_CONFIG } from "../config/course";
|
||||
import { isPaid } from "../lib/payment";
|
||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||
import { ThemeToggle } from "@vip/app/components/ThemeToggle";
|
||||
import { InstantQaVipModal } from "@vip/app/components/InstantQaVipModal";
|
||||
|
||||
export function Header() {
|
||||
const [paid, setPaid] = useState(false);
|
||||
const [qaModalOpen, setQaModalOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
setPaid(isPaid());
|
||||
const onPayUpdate = () => setPaid(isPaid());
|
||||
window.addEventListener("pay:updated", onPayUpdate);
|
||||
return () => window.removeEventListener("pay:updated", onPayUpdate);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="animate__animated animate__fadeInDown fixed left-0 right-0 top-0 z-50 border-b border-[var(--border)] bg-[var(--background)]/90 backdrop-blur-xl" style={{ animationFillMode: "both" }}>
|
||||
<div className="mx-auto flex h-12 max-w-6xl items-center justify-between gap-2 px-3 sm:h-14 sm:gap-4 sm:px-4 md:h-16 md:px-6">
|
||||
<Link href="/vip/cloudphone" className="min-w-0 truncate text-sm font-medium sm:text-base md:text-xl">
|
||||
{SITE_CONFIG.brand}
|
||||
</Link>
|
||||
<div className="flex shrink-0 items-center gap-1.5 sm:gap-3">
|
||||
<ThemeToggle />
|
||||
{paid ? (
|
||||
<span className="hidden">
|
||||
<a
|
||||
href="https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-[var(--accent)]/40 bg-[var(--accent)]/10 px-3 py-1.5 text-xs font-medium text-[var(--accent)] transition hover:bg-[var(--accent)]/20 sm:px-4 sm:py-2 sm:text-sm"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
即时问答
|
||||
</a>
|
||||
</span>
|
||||
) : (
|
||||
<span className="hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQaModalOpen(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-[var(--accent)]/40 bg-[var(--accent)]/10 px-3 py-1.5 text-xs font-medium text-[var(--accent)] transition hover:bg-[var(--accent)]/20 sm:px-4 sm:py-2 sm:text-sm"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
即时问答
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
<Link href="/" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
|
||||
首页
|
||||
</Link>
|
||||
{paid ? (
|
||||
<Link
|
||||
href="/vip/cloudphone/course/0/0"
|
||||
className="hidden rounded-full bg-[var(--accent)] px-3 py-1.5 text-xs font-medium text-[var(--accent-foreground)] transition hover:opacity-90 sm:inline-flex sm:px-4 sm:py-2 sm:text-sm"
|
||||
>
|
||||
进入课程 →
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => triggerPay()}
|
||||
className="hidden rounded-full bg-[var(--accent)] px-3 py-1.5 text-xs font-medium text-[var(--accent-foreground)] transition hover:opacity-90 sm:inline-flex sm:px-4 sm:py-2 sm:text-sm"
|
||||
>
|
||||
立即报名 →
|
||||
</button>
|
||||
)}
|
||||
{paid ? (
|
||||
<Link
|
||||
href="/vip/cloudphone/course/0/0"
|
||||
className="inline-flex rounded-full bg-[var(--accent)] p-2 text-[var(--accent-foreground)] sm:hidden"
|
||||
aria-label="进入课程"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M5 12h14M12 5l7 7-7 7" />
|
||||
</svg>
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => triggerPay()}
|
||||
className="inline-flex rounded-full bg-[var(--accent)] p-2 text-[var(--accent-foreground)] sm:hidden"
|
||||
aria-label="立即报名"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M5 12h14M12 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<InstantQaVipModal open={qaModalOpen} onClose={() => setQaModalOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
30
app/vip/cloudphone/components/ParticleBackground.tsx
Normal file
30
app/vip/cloudphone/components/ParticleBackground.tsx
Normal file
@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* 纯 CSS 粒子背景 - 不依赖 @tsparticles
|
||||
*/
|
||||
export function ParticleBackground() {
|
||||
const dots = Array.from({ length: 30 }, (_, i) => i);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 pointer-events-none overflow-hidden"
|
||||
aria-hidden
|
||||
>
|
||||
{dots.map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="absolute rounded-full bg-[var(--accent)] opacity-[0.08] animate-pulse"
|
||||
style={{
|
||||
width: `${2 + (i % 4)}px`,
|
||||
height: `${2 + (i % 4)}px`,
|
||||
left: `${(i * 7) % 100}%`,
|
||||
top: `${(i * 11) % 100}%`,
|
||||
animationDelay: `${(i % 5) * 0.5}s`,
|
||||
animationDuration: `${2 + (i % 3)}s`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
16
app/vip/cloudphone/components/Section.tsx
Normal file
16
app/vip/cloudphone/components/Section.tsx
Normal file
@ -0,0 +1,16 @@
|
||||
import { type ReactNode } from "react";
|
||||
|
||||
type SectionProps = {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function Section({ children, className = "" }: SectionProps) {
|
||||
return (
|
||||
<section
|
||||
className={`border-t border-[var(--border)] py-12 md:py-16 lg:py-20 ${className}`}
|
||||
>
|
||||
<div className="mx-auto max-w-6xl px-4 sm:px-6">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
367
app/vip/cloudphone/components/VideoPlayer.tsx
Normal file
367
app/vip/cloudphone/components/VideoPlayer.tsx
Normal file
@ -0,0 +1,367 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
const STORAGE_PREFIX = "lms-cloudphone-video-";
|
||||
const SAVE_INTERVAL = 5000;
|
||||
const MIN_PROGRESS_TO_SHOW = 10;
|
||||
|
||||
function getStoredProgress(videoId: string): number {
|
||||
if (typeof window === "undefined") return 0;
|
||||
try {
|
||||
const raw = localStorage.getItem(`${STORAGE_PREFIX}${videoId}`);
|
||||
if (!raw) return 0;
|
||||
const data = JSON.parse(raw);
|
||||
return typeof data?.time === "number" ? data.time : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function saveProgress(videoId: string, time: number): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
localStorage.setItem(`${STORAGE_PREFIX}${videoId}`, JSON.stringify({ time }));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
type VideoPlayerProps = {
|
||||
src: string;
|
||||
poster?: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
videoId?: string;
|
||||
onComplete?: () => void;
|
||||
};
|
||||
|
||||
export function VideoPlayer({ src, poster, title, className = "", videoId, onComplete }: VideoPlayerProps) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [volume, setVolume] = useState(1);
|
||||
const [muted, setMuted] = useState(false);
|
||||
const [speed, setSpeed] = useState(1);
|
||||
const [showControls, setShowControls] = useState(true);
|
||||
const [showResumePrompt, setShowResumePrompt] = useState(false);
|
||||
const [savedTime, setSavedTime] = useState(0);
|
||||
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastSaveRef = useRef(0);
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
if (v.paused) {
|
||||
v.play();
|
||||
setPlaying(true);
|
||||
} else {
|
||||
v.pause();
|
||||
setPlaying(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleTimeUpdate = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
const time = v.currentTime;
|
||||
const dur = v.duration;
|
||||
setCurrentTime(time);
|
||||
setProgress(Number.isFinite(dur) && dur > 0 ? (time / dur) * 100 : 0);
|
||||
|
||||
if (videoId && v.currentTime > 0) {
|
||||
const now = Date.now();
|
||||
if (now - lastSaveRef.current > SAVE_INTERVAL) {
|
||||
lastSaveRef.current = now;
|
||||
saveProgress(videoId, v.currentTime);
|
||||
}
|
||||
}
|
||||
}, [videoId]);
|
||||
|
||||
const handleLoadedMetadata = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
const dur = v.duration;
|
||||
if (!Number.isFinite(dur) || dur <= 0) return;
|
||||
setDuration(dur);
|
||||
|
||||
if (videoId) {
|
||||
const stored = getStoredProgress(videoId);
|
||||
if (Number.isFinite(stored) && stored >= MIN_PROGRESS_TO_SHOW && stored < dur - 5) {
|
||||
setSavedTime(stored);
|
||||
setShowResumePrompt(true);
|
||||
}
|
||||
}
|
||||
}, [videoId]);
|
||||
|
||||
const handleEnded = useCallback(() => {
|
||||
setPlaying(false);
|
||||
setProgress(0);
|
||||
setCurrentTime(0);
|
||||
if (videoId) saveProgress(videoId, 0);
|
||||
onComplete?.();
|
||||
}, [videoId, onComplete]);
|
||||
|
||||
const handlePause = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (videoId && v && v.currentTime > 0) {
|
||||
saveProgress(videoId, v.currentTime);
|
||||
}
|
||||
}, [videoId]);
|
||||
|
||||
const handleResume = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v || savedTime <= 0) return;
|
||||
const dur = v.duration;
|
||||
if (!Number.isFinite(dur) || dur <= 0) return;
|
||||
const time = Math.min(savedTime, dur - 0.1);
|
||||
v.currentTime = time;
|
||||
setCurrentTime(time);
|
||||
setProgress((time / dur) * 100);
|
||||
v.play();
|
||||
setPlaying(true);
|
||||
setShowResumePrompt(false);
|
||||
}, [savedTime]);
|
||||
|
||||
const handleRestart = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
if (videoId) saveProgress(videoId, 0);
|
||||
v.currentTime = 0;
|
||||
setCurrentTime(0);
|
||||
setProgress(0);
|
||||
setShowResumePrompt(false);
|
||||
}, [videoId]);
|
||||
|
||||
const handleSeek = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
const dur = v.duration;
|
||||
if (!Number.isFinite(dur) || dur <= 0) return;
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
if (rect.width <= 0) return;
|
||||
const p = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
||||
const time = p * dur;
|
||||
v.currentTime = time;
|
||||
setCurrentTime(time);
|
||||
setProgress(p * 100);
|
||||
}, []);
|
||||
|
||||
const toggleMute = useCallback(() => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
v.muted = !v.muted;
|
||||
setMuted(v.muted);
|
||||
}, []);
|
||||
|
||||
const handleVolumeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const v = videoRef.current;
|
||||
if (!v) return;
|
||||
const val = parseFloat(e.target.value);
|
||||
v.volume = val;
|
||||
setVolume(val);
|
||||
setMuted(val === 0);
|
||||
}, []);
|
||||
|
||||
const cycleSpeed = useCallback(() => {
|
||||
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
|
||||
const i = speeds.indexOf(speed);
|
||||
const next = speeds[(i + 1) % speeds.length];
|
||||
const v = videoRef.current;
|
||||
if (v) v.playbackRate = next;
|
||||
setSpeed(next);
|
||||
}, [speed]);
|
||||
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
const container = videoRef.current?.parentElement;
|
||||
if (!container) return;
|
||||
if (!document.fullscreenElement) {
|
||||
container.requestFullscreen();
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showControlsTemporarily = useCallback(() => {
|
||||
setShowControls(true);
|
||||
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
|
||||
hideTimerRef.current = setTimeout(() => setShowControls(false), 3000);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => { if (hideTimerRef.current) clearTimeout(hideTimerRef.current); }, []);
|
||||
|
||||
const formatTime = (s: number) => {
|
||||
if (!Number.isFinite(s) || s < 0) return "0:00";
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = Math.floor(s % 60);
|
||||
return `${m}:${sec.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const formatResumeTime = (s: number) => {
|
||||
if (!Number.isFinite(s) || s < 0) return "0秒";
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = Math.floor(s % 60);
|
||||
if (m > 0) return `${m}分${sec}秒`;
|
||||
return `${sec}秒`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group relative overflow-hidden rounded-xl bg-black md:rounded-2xl ${className}`}
|
||||
onMouseMove={showControlsTemporarily}
|
||||
onMouseLeave={() => setShowControls(false)}
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={src}
|
||||
poster={poster}
|
||||
title={title}
|
||||
className="aspect-video w-full object-contain"
|
||||
onClick={togglePlay}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
onLoadedMetadata={handleLoadedMetadata}
|
||||
onEnded={handleEnded}
|
||||
onPause={handlePause}
|
||||
playsInline
|
||||
/>
|
||||
|
||||
{!playing && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-black/20 transition hover:bg-black/30">
|
||||
{showResumePrompt ? (
|
||||
<>
|
||||
<p className="text-center text-sm text-white/90 sm:text-base">
|
||||
上次看到 <span className="font-semibold text-white">{formatResumeTime(savedTime)}</span>
|
||||
</p>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleResume}
|
||||
className="flex items-center justify-center gap-2 rounded-xl bg-[var(--accent)] px-6 py-3.5 text-base font-medium text-black shadow-lg transition hover:scale-105 hover:opacity-95 sm:px-8"
|
||||
>
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
从上次继续
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRestart}
|
||||
className="rounded-xl border border-white/40 bg-white/10 px-5 py-3 text-sm font-medium text-white backdrop-blur transition hover:bg-white/20"
|
||||
>
|
||||
从头播放
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePlay}
|
||||
className="flex items-center justify-center"
|
||||
aria-label="播放"
|
||||
>
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-white/90 shadow-lg transition hover:scale-110 sm:h-20 sm:w-20">
|
||||
<svg
|
||||
className="ml-1 h-8 w-8 text-black sm:h-10 sm:w-10"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent p-3 transition-opacity duration-300 ${
|
||||
showControls ? "opacity-100" : "opacity-0"
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className="mb-3 h-1 cursor-pointer rounded-full bg-white/30"
|
||||
onClick={handleSeek}
|
||||
role="slider"
|
||||
aria-valuenow={progress}
|
||||
>
|
||||
<div
|
||||
className="h-full rounded-full bg-[var(--accent)] transition-all"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 sm:gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePlay}
|
||||
className="rounded p-1 text-white transition hover:bg-white/20"
|
||||
aria-label={playing ? "暂停" : "播放"}
|
||||
>
|
||||
{playing ? (
|
||||
<svg className="h-5 w-5 sm:h-6 sm:w-6" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-5 w-5 sm:h-6 sm:w-6" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<span className="min-w-[4rem] text-xs text-white/90 sm:text-sm">
|
||||
{formatTime(currentTime)} / {formatTime(duration)}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleMute}
|
||||
className="rounded p-1 text-white transition hover:bg-white/20"
|
||||
aria-label={muted ? "取消静音" : "静音"}
|
||||
>
|
||||
{muted || volume === 0 ? (
|
||||
<svg className="h-5 w-5 sm:h-6 sm:w-6" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-5 w-5 sm:h-6 sm:w-6" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.1"
|
||||
value={muted ? 0 : volume}
|
||||
onChange={handleVolumeChange}
|
||||
className="h-1 w-16 cursor-pointer accent-[var(--accent)] sm:w-20"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={cycleSpeed}
|
||||
className="rounded px-2 py-1 text-xs font-medium text-white/90 transition hover:bg-white/20 sm:text-sm"
|
||||
>
|
||||
{speed}x
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleFullscreen}
|
||||
className="ml-auto rounded p-1 text-white transition hover:bg-white/20"
|
||||
aria-label="全屏"
|
||||
>
|
||||
<svg className="h-5 w-5 sm:h-6 sm:w-6" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
app/vip/cloudphone/components/index.ts
Normal file
11
app/vip/cloudphone/components/index.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export { Header } from "./Header";
|
||||
export { Footer } from "./Footer";
|
||||
export { Section } from "./Section";
|
||||
export { AnimateOnScroll } from "./AnimateOnScroll";
|
||||
export { Hero } from "./sections/Hero";
|
||||
export { AudienceSection } from "./sections/AudienceSection";
|
||||
export { BenefitsSection } from "./sections/BenefitsSection";
|
||||
export { CurriculumSection } from "./sections/CurriculumSection";
|
||||
export { InstructorsSection } from "./sections/InstructorsSection";
|
||||
export { FAQSection } from "./sections/FAQSection";
|
||||
export { CTASection } from "./sections/CTASection";
|
||||
28
app/vip/cloudphone/components/sections/AudienceSection.tsx
Normal file
28
app/vip/cloudphone/components/sections/AudienceSection.tsx
Normal file
@ -0,0 +1,28 @@
|
||||
import { Section } from "../Section";
|
||||
import { AUDIENCE_CONFIG } from "../../config/course";
|
||||
|
||||
export function AudienceSection() {
|
||||
return (
|
||||
<Section>
|
||||
<h2 className="mb-4 text-center text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{AUDIENCE_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-10 text-center text-[var(--muted-foreground)] sm:mb-12 md:mb-16">
|
||||
{AUDIENCE_CONFIG.subtitle}
|
||||
</p>
|
||||
<div className="grid gap-4 sm:grid-cols-2 sm:gap-6 lg:grid-cols-4">
|
||||
{AUDIENCE_CONFIG.items.map((a, i) => (
|
||||
<div
|
||||
key={a.title}
|
||||
className="hover-shimmer animate__animated animate__fadeInUp rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 transition-all duration-300 hover:border-[var(--accent)]/30 hover:bg-[var(--muted)] hover:-translate-y-0.5 sm:rounded-2xl sm:p-6"
|
||||
style={{ animationDelay: `${i * 0.1}s`, animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mb-3 text-2xl sm:mb-4 sm:text-3xl">{a.emoji}</div>
|
||||
<h3 className="mb-2 font-semibold">{a.title}</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{a.desc}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
32
app/vip/cloudphone/components/sections/BenefitsSection.tsx
Normal file
32
app/vip/cloudphone/components/sections/BenefitsSection.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import { Section } from "../Section";
|
||||
import { BENEFITS_CONFIG } from "../../config/course";
|
||||
|
||||
export function BenefitsSection() {
|
||||
return (
|
||||
<Section>
|
||||
<h2 className="mb-4 text-center text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{BENEFITS_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-10 text-center text-[var(--muted-foreground)] sm:mb-12 md:mb-16">
|
||||
{BENEFITS_CONFIG.subtitle}
|
||||
</p>
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
{BENEFITS_CONFIG.items.map((b, i) => (
|
||||
<div
|
||||
key={b.num}
|
||||
className="hover-shimmer animate__animated animate__fadeInUp flex flex-col gap-4 rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 transition-all duration-300 hover:border-[var(--accent)]/30 hover:-translate-y-0.5 sm:flex-row sm:gap-6 sm:rounded-2xl sm:p-6"
|
||||
style={{ animationDelay: `${i * 0.08}s`, animationFillMode: "both" }}
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[var(--accent-muted)] text-base font-bold text-[var(--accent)] sm:h-12 sm:w-12 sm:text-lg">
|
||||
{b.num}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="mb-1 font-semibold">{b.title}</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{b.desc}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
57
app/vip/cloudphone/components/sections/CTASection.tsx
Normal file
57
app/vip/cloudphone/components/sections/CTASection.tsx
Normal file
@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { CTA_CONFIG } from "../../config/course";
|
||||
import { isPaid } from "../../lib/payment";
|
||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||
|
||||
export function CTASection() {
|
||||
const [paid, setPaid] = useState(false);
|
||||
useEffect(() => {
|
||||
setPaid(isPaid());
|
||||
const onPayUpdate = () => setPaid(isPaid());
|
||||
window.addEventListener("pay:updated", onPayUpdate);
|
||||
return () => window.removeEventListener("pay:updated", onPayUpdate);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="border-t border-[var(--border)] py-16 sm:py-20 md:py-24">
|
||||
<div className="mx-auto max-w-3xl px-4 text-center sm:px-6">
|
||||
<h2 className="mb-4 text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{CTA_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-6 text-[var(--muted-foreground)] sm:mb-8">
|
||||
{CTA_CONFIG.subtitle}
|
||||
</p>
|
||||
<div className="mb-8 flex flex-wrap justify-center gap-4 text-sm text-[var(--muted-foreground)] sm:mb-10 sm:gap-6">
|
||||
{CTA_CONFIG.badges.map((b, i) => (
|
||||
<span
|
||||
key={b}
|
||||
className="animate-float-badge rounded-full border border-[var(--border)] bg-[var(--card)] px-4 py-2"
|
||||
style={{ animationDelay: `${i * 0.2}s` }}
|
||||
>
|
||||
{b}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{paid ? (
|
||||
<Link
|
||||
href="/vip/cloudphone/course/0/0"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition-all duration-300 hover:scale-105 hover:opacity-95 hover:shadow-xl hover:shadow-[var(--accent)]/30 sm:px-10"
|
||||
>
|
||||
开始学习 →
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => triggerPay()}
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition-all duration-300 hover:scale-105 hover:opacity-95 hover:shadow-xl hover:shadow-[var(--accent)]/30 sm:px-10"
|
||||
>
|
||||
立即加入 →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
140
app/vip/cloudphone/components/sections/CurriculumSection.tsx
Normal file
140
app/vip/cloudphone/components/sections/CurriculumSection.tsx
Normal file
@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { Section } from "../Section";
|
||||
import { CURRICULUM_CONFIG } from "../../config/course";
|
||||
import { canWatchLesson } from "../../lib/payment";
|
||||
import { isBookmarked, toggleBookmark, getBookmarks, getCompletedLessons } from "../../lib/learning";
|
||||
|
||||
export function CurriculumSection() {
|
||||
const [expanded, setExpanded] = useState<Record<number, boolean>>(() =>
|
||||
Object.fromEntries(CURRICULUM_CONFIG.modules.map((_, i) => [i, i === 0]))
|
||||
);
|
||||
const [bookmarks, setBookmarks] = useState<Set<string>>(new Set());
|
||||
const [completed, setCompleted] = useState<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
setBookmarks(getBookmarks());
|
||||
setCompleted(getCompletedLessons());
|
||||
const onB = () => setBookmarks(getBookmarks());
|
||||
const onP = () => setCompleted(getCompletedLessons());
|
||||
window.addEventListener("learning:bookmarks", onB);
|
||||
window.addEventListener("learning:progress", onP);
|
||||
return () => {
|
||||
window.removeEventListener("learning:bookmarks", onB);
|
||||
window.removeEventListener("learning:progress", onP);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const toggle = (i: number) => {
|
||||
setExpanded((prev) => ({ ...prev, [i]: !prev[i] }));
|
||||
};
|
||||
|
||||
const allLessons = CURRICULUM_CONFIG.modules.flatMap((m, mi) =>
|
||||
m.lessons.map((l, li) => ({ moduleIndex: mi, lessonIndex: li, ...l, moduleTitle: m.title }))
|
||||
);
|
||||
const filteredByModule = CURRICULUM_CONFIG.modules.map((m, mi) => ({
|
||||
...m,
|
||||
lessons: allLessons.filter((l) => l.moduleIndex === mi),
|
||||
}));
|
||||
|
||||
return (
|
||||
<Section>
|
||||
<h2 className="mb-4 text-center text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{CURRICULUM_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-6 text-center text-[var(--muted-foreground)] sm:mb-8 md:mb-10">
|
||||
{CURRICULUM_CONFIG.subtitle}
|
||||
</p>
|
||||
<div className="space-y-2 md:space-y-3">
|
||||
{filteredByModule.map((c, i) => {
|
||||
const moduleIndex = CURRICULUM_CONFIG.modules.findIndex((m) => m.title === c.title);
|
||||
const isOpen = expanded[moduleIndex] ?? true;
|
||||
return (
|
||||
<div
|
||||
key={c.title}
|
||||
className="animate__animated animate__fadeInUp overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] md:rounded-2xl"
|
||||
style={{ animationDelay: `${i * 0.06}s`, animationFillMode: "both" }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(moduleIndex)}
|
||||
className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition hover:bg-[var(--muted)] sm:px-5 sm:py-4"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-base font-semibold sm:text-lg">
|
||||
<span
|
||||
className={`transition-transform duration-200 ${isOpen ? "rotate-90" : ""}`}
|
||||
>
|
||||
▶
|
||||
</span>
|
||||
<span>{c.emoji}</span>
|
||||
{c.title}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--muted-foreground)]">
|
||||
{c.lessons.length} 节
|
||||
</span>
|
||||
</button>
|
||||
{isOpen && (
|
||||
<ul className="border-t border-[var(--border)]">
|
||||
{c.lessons.map((l) => {
|
||||
const free = false; /* 暂时全部加锁 */
|
||||
const unlocked = canWatchLesson(l.moduleIndex, l.lessonIndex);
|
||||
const key = `${l.moduleIndex}-${l.lessonIndex}`;
|
||||
const bookmarked = isBookmarked(l.moduleIndex, l.lessonIndex);
|
||||
const isCompleted = completed.has(key);
|
||||
return (
|
||||
<li key={key}>
|
||||
<Link
|
||||
href={`/vip/cloudphone/course/${l.moduleIndex}/${l.lessonIndex}`}
|
||||
className="flex flex-col gap-1 px-4 py-3 transition hover:bg-[var(--muted)] sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-3"
|
||||
>
|
||||
<span className="flex items-center gap-2 truncate sm:gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toggleBookmark(l.moduleIndex, l.lessonIndex);
|
||||
}}
|
||||
className="shrink-0 text-xs"
|
||||
aria-label={bookmarked ? "取消收藏" : "收藏"}
|
||||
>
|
||||
{bookmarked ? "⭐" : "☆"}
|
||||
</button>
|
||||
<span className={unlocked ? "text-[var(--foreground)]" : "text-[var(--muted-foreground)]"}>
|
||||
{l.name}
|
||||
</span>
|
||||
{free && (
|
||||
<span className="shrink-0 rounded bg-[var(--accent)]/20 px-1.5 py-0.5 text-xs text-[var(--accent)]">
|
||||
试看
|
||||
</span>
|
||||
)}
|
||||
{isCompleted && (
|
||||
<span className="shrink-0 rounded bg-green-500/20 px-1.5 py-0.5 text-xs text-green-600 dark:text-green-400">
|
||||
✓
|
||||
</span>
|
||||
)}
|
||||
{!unlocked && (
|
||||
<span className="shrink-0 text-xs text-[var(--muted-foreground)]">
|
||||
🔒
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2 text-xs text-[var(--muted-foreground)] sm:text-sm">
|
||||
{l.duration}
|
||||
<span className="text-[var(--accent)]">→</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
43
app/vip/cloudphone/components/sections/FAQSection.tsx
Normal file
43
app/vip/cloudphone/components/sections/FAQSection.tsx
Normal file
@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Section } from "../Section";
|
||||
import { FAQ_CONFIG } from "../../config/course";
|
||||
|
||||
export function FAQSection() {
|
||||
const [openIndex, setOpenIndex] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<Section>
|
||||
<h2 className="mb-10 text-center text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{FAQ_CONFIG.title}
|
||||
</h2>
|
||||
<div className="mx-auto max-w-2xl space-y-2">
|
||||
{FAQ_CONFIG.items.map((item, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] transition"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpenIndex(openIndex === i ? null : i)}
|
||||
className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition hover:bg-[var(--muted)] sm:px-5"
|
||||
>
|
||||
<span className="font-medium">{item.q}</span>
|
||||
<span
|
||||
className={`shrink-0 text-[var(--muted-foreground)] transition-transform ${openIndex === i ? "rotate-180" : ""}`}
|
||||
>
|
||||
▼
|
||||
</span>
|
||||
</button>
|
||||
{openIndex === i && (
|
||||
<div className="border-t border-[var(--border)] px-4 py-3 text-sm text-[var(--muted-foreground)] sm:px-5">
|
||||
{item.a}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
115
app/vip/cloudphone/components/sections/Hero.tsx
Normal file
115
app/vip/cloudphone/components/sections/Hero.tsx
Normal file
@ -0,0 +1,115 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { HERO_CONFIG, CURRICULUM_CONFIG } from "../../config/course";
|
||||
import { isPaid } from "../../lib/payment";
|
||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||
import { getLastWatched, getProgress } from "../../lib/learning";
|
||||
import { ParticleBackground } from "../ParticleBackground";
|
||||
|
||||
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
|
||||
|
||||
export function Hero() {
|
||||
const [paid, setPaid] = useState(false);
|
||||
const [last, setLast] = useState<ReturnType<typeof getLastWatched>>(null);
|
||||
const [progress, setProgress] = useState({ completed: 0, percent: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
setPaid(isPaid());
|
||||
setLast(getLastWatched());
|
||||
setProgress(getProgress(TOTAL_LESSONS));
|
||||
const onPay = () => setPaid(isPaid());
|
||||
const onProgress = () => {
|
||||
setLast(getLastWatched());
|
||||
setProgress(getProgress(TOTAL_LESSONS));
|
||||
};
|
||||
window.addEventListener("pay:updated", onPay);
|
||||
window.addEventListener("learning:progress", onProgress);
|
||||
return () => {
|
||||
window.removeEventListener("pay:updated", onPay);
|
||||
window.removeEventListener("learning:progress", onProgress);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="relative overflow-hidden pt-24 pb-16 sm:pt-28 sm:pb-20 md:pt-32 md:pb-24">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,var(--gradient-accent),transparent)] animate-gradient" />
|
||||
<ParticleBackground />
|
||||
<div className="relative mx-auto max-w-4xl px-4 text-center sm:px-6">
|
||||
<h1
|
||||
className="mb-4 text-3xl font-bold tracking-tight animate__animated animate__fadeInDown sm:text-4xl md:text-5xl lg:text-6xl"
|
||||
style={{ animationDelay: "0.1s", animationFillMode: "both" }}
|
||||
>
|
||||
{HERO_CONFIG.title}
|
||||
</h1>
|
||||
<p
|
||||
className="mb-10 text-lg text-[var(--muted-foreground)] animate__animated animate__fadeInDown sm:mb-12 sm:text-xl md:text-2xl"
|
||||
style={{ animationDelay: "0.25s", animationFillMode: "both" }}
|
||||
>
|
||||
{HERO_CONFIG.subtitle}
|
||||
</p>
|
||||
<div
|
||||
className="mb-10 flex flex-wrap justify-center gap-6 animate__animated animate__fadeInDown sm:mb-12 sm:gap-8"
|
||||
style={{ animationDelay: "0.4s", animationFillMode: "both" }}
|
||||
>
|
||||
{HERO_CONFIG.stats.map((s) => (
|
||||
<div key={s.label} className="text-center transition-transform duration-300 hover:scale-105">
|
||||
<div className="text-2xl font-bold text-[var(--accent)] sm:text-3xl md:text-4xl">
|
||||
{s.value}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-[var(--muted-foreground)] sm:text-sm">
|
||||
{s.label}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
className="flex flex-wrap justify-center gap-3 animate__animated animate__fadeInDown sm:gap-4"
|
||||
style={{ animationDelay: "0.6s", animationFillMode: "both" }}
|
||||
>
|
||||
{paid && last ? (
|
||||
<Link
|
||||
href={`/vip/cloudphone/course/${last.moduleIndex}/${last.lessonIndex}`}
|
||||
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
|
||||
>
|
||||
继续学习 →
|
||||
</Link>
|
||||
) : paid ? (
|
||||
<Link
|
||||
href="/vip/cloudphone/course/0/0"
|
||||
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
|
||||
>
|
||||
进入课程 →
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => triggerPay()}
|
||||
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
|
||||
>
|
||||
立即报名 →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{paid && progress.completed > 0 && (
|
||||
<div
|
||||
className="mt-6 w-full max-w-xs animate__animated animate__fadeInDown"
|
||||
style={{ animationDelay: "0.7s", animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mb-1 flex justify-between text-xs text-[var(--muted-foreground)]">
|
||||
<span>学习进度</span>
|
||||
<span>{progress.completed}/{TOTAL_LESSONS} 节</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-[var(--muted)]">
|
||||
<div
|
||||
className="h-full rounded-full bg-[var(--accent)] transition-all"
|
||||
style={{ width: `${progress.percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
import { Section } from "../Section";
|
||||
import { INSTRUCTORS_CONFIG } from "../../config/course";
|
||||
|
||||
export function InstructorsSection() {
|
||||
return (
|
||||
<Section>
|
||||
<h2 className="mb-4 text-center text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{INSTRUCTORS_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-10 text-center text-[var(--muted-foreground)] sm:mb-12 md:mb-16">
|
||||
{INSTRUCTORS_CONFIG.subtitle}
|
||||
</p>
|
||||
<div className="grid gap-6 sm:grid-cols-2 md:gap-8 lg:grid-cols-3">
|
||||
{INSTRUCTORS_CONFIG.items.map((i) => (
|
||||
<div
|
||||
key={i.name}
|
||||
className="hover-shimmer rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 text-center transition-all duration-300 hover:-translate-y-0.5 hover:border-[var(--accent)]/30 sm:rounded-2xl sm:p-6"
|
||||
>
|
||||
<div className="mb-3 flex justify-center sm:mb-4">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-[var(--accent-muted)] text-xl font-bold text-[var(--accent)] sm:h-20 sm:w-20 sm:text-2xl">
|
||||
{i.name.slice(0, 1)}
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="mb-1 font-semibold">{i.name}</h3>
|
||||
<p className="mb-1 text-sm text-[var(--accent)]">{i.role}</p>
|
||||
<p className="mb-2 text-sm text-[var(--muted-foreground)]">
|
||||
{i.desc}
|
||||
</p>
|
||||
<span className="inline-block rounded-full bg-[var(--accent-muted)] px-3 py-1 text-xs text-[var(--accent)]">
|
||||
{i.tag}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
128
app/vip/cloudphone/config/course.ts
Normal file
128
app/vip/cloudphone/config/course.ts
Normal file
@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 云手机实战课 - 课程配置(克隆自 nomadlms)
|
||||
*/
|
||||
|
||||
export const SITE_CONFIG = {
|
||||
brand: "🌍 云手机",
|
||||
ctaUrl: "/",
|
||||
footer: "🌍 云手机 · 低成本工作室搭建指南",
|
||||
} as const;
|
||||
|
||||
export const HERO_CONFIG = {
|
||||
title: "云手机实战课",
|
||||
subtitle: "低成本工作室搭建指南 · TikTok/Youtube 无人直播,开启 24 小时赚美金",
|
||||
stats: [
|
||||
{ value: "13", label: "节实战课程" },
|
||||
{ value: "170+", label: "分钟视频" },
|
||||
{ value: "1", label: "位资深导师" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const AUDIENCE_CONFIG = {
|
||||
title: "这门课适合谁?",
|
||||
subtitle: "向往低成本自建,想用开源硬件实现无人直播的人",
|
||||
items: [
|
||||
{ emoji: "💻", title: "无人直播创业者", desc: "想用低成本硬件搭建 TikTok/Youtube 直播矩阵" },
|
||||
{ emoji: "⚙️", title: "技术极客", desc: "想自建云手机、Redroid、ARM 开发板玩转自动化" },
|
||||
{ emoji: "📱", title: "出海副业者", desc: "想摆脱云手机平台高额月费,自建开箱即用" },
|
||||
{ emoji: "🌴", title: "工作室搭建者", desc: "想低成本打造无人值守 24 小时赚美金" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const BENEFITS_CONFIG = {
|
||||
title: "学完你将获得",
|
||||
subtitle: "5大核心能力,助你自建云手机工作室",
|
||||
items: [
|
||||
{ num: "1", title: "云手机自建方案", desc: "Redroid、AOSP 安卓、ARM 开发板,从零搭建云手机" },
|
||||
{ num: "2", title: "无人直播技术栈", desc: "ffmpeg、SRS、油猴脚本,实现 24 小时自动化推流" },
|
||||
{ num: "3", title: "软路由与网络", desc: "科学上网、静态住宅 IP,出海必备基础设施" },
|
||||
{ num: "4", title: "硬件选型与成本", desc: "开发板、采集卡、配件,一套成本不过千" },
|
||||
{ num: "5", title: "VIP 社群支持", desc: "加入异度星球,获取部署教程与即时答疑" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const CURRICULUM_CONFIG = {
|
||||
title: "实战课程",
|
||||
subtitle: "从入门到进阶,完整搭建云手机工作室",
|
||||
modules: [
|
||||
{
|
||||
emoji: "🚀",
|
||||
title: "基础篇 · 云手机入门",
|
||||
lessons: [
|
||||
{ name: "01 从0到1:安卓镜像安装与首次开机", duration: "08:32" },
|
||||
{ name: "02 性能翻倍:安卓存储扩容实操", duration: "12:15" },
|
||||
],
|
||||
},
|
||||
{
|
||||
emoji: "⚙️",
|
||||
title: "技术篇 · Redroid 与 AOSP",
|
||||
lessons: [
|
||||
{ name: "03 竖屏直播必备:系统显示方向设置", duration: "15:20" },
|
||||
{ name: "04 一次搞定 Root:Magisk + 模块安装", duration: "18:00" },
|
||||
{ name: "05 防风控第一步:机型参数改造", duration: "14:30" },
|
||||
],
|
||||
},
|
||||
{
|
||||
emoji: "📺",
|
||||
title: "直播篇 · 无人推流",
|
||||
lessons: [
|
||||
{ name: "06 降低风控命中:GPS 精准定位", duration: "16:00" },
|
||||
{ name: "07 无人直播入门:录播素材循环推流", duration: "12:45" },
|
||||
{ name: "08 TikTok 实战开播:完整流程演示", duration: "11:20" },
|
||||
{ name: "09 TikTok 进阶优化:稳定推流与细节调优", duration: "20:00" },
|
||||
],
|
||||
},
|
||||
{
|
||||
emoji: "🌐",
|
||||
title: "网络篇 · 出海基础",
|
||||
lessons: [
|
||||
{ name: "10 软路由与科学上网", duration: "13:00" },
|
||||
{ name: "11 静态住宅 IP 配置", duration: "10:30" },
|
||||
],
|
||||
},
|
||||
{
|
||||
emoji: "🏆",
|
||||
title: "进阶篇 · 产品化",
|
||||
lessons: [
|
||||
{ name: "12 HDMI 辅助板方案", duration: "15:00" },
|
||||
{ name: "13 多设备群控与远控", duration: "12:00" },
|
||||
],
|
||||
},
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const INSTRUCTORS_CONFIG = {
|
||||
title: "资深导师授课",
|
||||
subtitle: "异度世界带你开启云手机工作室之旅",
|
||||
items: [
|
||||
{
|
||||
name: "异度世界",
|
||||
role: "数字游民先行者",
|
||||
desc: "5年旅居经验,低成本工作室实践",
|
||||
tag: "课程主理",
|
||||
},
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const CTA_CONFIG = {
|
||||
title: "准备好开启你的云手机工作室了吗?",
|
||||
subtitle: "加入异度星球 VIP,解锁云手机实战课 + 电子书 + 即时答疑",
|
||||
badges: ["实战视频", "永久回看", "社群答疑"],
|
||||
} as const;
|
||||
|
||||
export const FAQ_CONFIG = {
|
||||
title: "常见问题",
|
||||
items: [
|
||||
{ q: "课程可以永久回看吗?", a: "可以,VIP 会员永久有效,随时回看。" },
|
||||
{ q: "适合零基础吗?", a: "适合。课程从入门到进阶,前 2 节可免费试看。" },
|
||||
{ q: "有社群答疑吗?", a: "有,VIP 加入异度星球专属社群,即时答疑。" },
|
||||
{ q: "支持退款吗?", a: "虚拟数字交付,不支持退款。" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const DOWNLOAD_CONFIG = {
|
||||
enabled: true,
|
||||
url: "https://pan.baidu.com/s/example",
|
||||
title: "课程资料下载",
|
||||
buttonText: "前往网盘下载",
|
||||
} as const;
|
||||
382
app/vip/cloudphone/config/lessons.ts
Normal file
382
app/vip/cloudphone/config/lessons.ts
Normal file
@ -0,0 +1,382 @@
|
||||
/**
|
||||
* 云手机课程章节详情配置(克隆自 nomadlms)
|
||||
*/
|
||||
|
||||
const SAMPLE_VIDEO = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
|
||||
|
||||
const LESSON_MARKDOWNS: Record<string, string> = {
|
||||
"0-0": `# 01 从0到1:安卓镜像安装与首次开机
|
||||
|
||||
对应电子书章节:\`硬件选择\` -> \`刷入安卓系统\`。
|
||||
|
||||
## 你会完成什么
|
||||
|
||||
- 准备 TF 卡、读卡器、开发板电源与网线
|
||||
- 下载开发板安卓镜像(AOSP)
|
||||
- 用 Balena Etcher 刷写 img 并首次开机
|
||||
|
||||
## 实操步骤
|
||||
|
||||
1. 将 img 镜像写入 TF 卡
|
||||
2. TF 卡插回开发板,接通电源和网线
|
||||
3. 首次启动后确认系统已进入桌面并可调试
|
||||
|
||||
## 避坑提醒
|
||||
|
||||
- 刷机前优先确认镜像版本与板型匹配
|
||||
- 首次开机时间可能较长,不要中途断电
|
||||
`,
|
||||
"0-1": `# 02 性能翻倍:安卓存储扩容实操
|
||||
|
||||
对应电子书章节:\`硬件选择\` 与存储相关说明(TF/SSD 组合)。
|
||||
|
||||
## 核心目标
|
||||
|
||||
- 解决默认系统空间不足导致的安装失败
|
||||
- 保证后续安装模块、素材、脚本有足够空间
|
||||
|
||||
## 推荐方案
|
||||
|
||||
- TF 卡至少 64GB
|
||||
- 优先使用 USB3.0 读卡器提升刷写效率
|
||||
- 有条件时搭配 SSD 作为素材盘
|
||||
|
||||
## 执行清单
|
||||
|
||||
- [ ] 检查系统可用容量
|
||||
- [ ] 清理无用预装与缓存
|
||||
- [ ] 预留直播素材和日志空间
|
||||
`,
|
||||
"1-0": `# 03 竖屏直播必备:系统显示方向设置
|
||||
|
||||
对应电子书章节:\`业务场景:无人直播\` 中摄像头与画面链路实践。
|
||||
|
||||
## 为什么先做竖屏
|
||||
|
||||
- TikTok 直播以竖屏为主
|
||||
- 先固定方向,后续采集与推流才稳定
|
||||
|
||||
## 操作要点
|
||||
|
||||
1. 在系统中关闭自动旋转
|
||||
2. 固定竖屏分辨率
|
||||
3. 使用测试素材验证采集画面方向
|
||||
|
||||
## 验证标准
|
||||
|
||||
- 开播预览无横竖屏抖动
|
||||
- 推流端与手机端画面方向一致
|
||||
`,
|
||||
"1-1": `# 04 一次搞定 Root:Magisk + 模块安装
|
||||
|
||||
对应电子书章节:\`获取root权限\` 与 \`安装lsposed环境\`。
|
||||
|
||||
## 实操流程
|
||||
|
||||
1. 从镜像提取 \`boot.img\`
|
||||
2. 在安卓端用 Magisk 修补镜像
|
||||
3. 通过刷写工具或 adb dd 回刷补丁镜像
|
||||
4. 重启验证 Root 生效
|
||||
|
||||
## 关键命令(电子书同源)
|
||||
|
||||
\`\`\`bash
|
||||
adb shell
|
||||
su
|
||||
dd if=/sdcard/magisk_patched.img of=/dev/block/mmcblk0p9 bs=4M
|
||||
sync
|
||||
reboot
|
||||
\`\`\`
|
||||
|
||||
## 后续动作
|
||||
|
||||
- 安装 LSPosed,准备模块化能力
|
||||
- 记录可回滚镜像,避免系统损坏
|
||||
`,
|
||||
"1-2": `# 05 防风控第一步:机型参数改造
|
||||
|
||||
对应电子书章节:\`修改机型\`。
|
||||
|
||||
## 目标
|
||||
|
||||
- 降低平台对异常设备指纹的识别概率
|
||||
- 让账号环境更贴近真实移动设备
|
||||
|
||||
## 建议流程
|
||||
|
||||
1. 安装改机工具并授予 Root 权限
|
||||
2. 进入设备信息伪装,选择目标机型
|
||||
3. 重启系统并重新检查参数是否生效
|
||||
|
||||
## 风险提示
|
||||
|
||||
- 机型参数、IP、GPS 需要协同一致
|
||||
- 不建议频繁切换机型,避免触发异常行为
|
||||
`,
|
||||
"2-0": `# 06 降低风控命中:GPS 精准定位
|
||||
|
||||
对应电子书章节:\`GPS定位\`。
|
||||
|
||||
## 为什么必须做
|
||||
|
||||
- GPS 与 IP 国家/城市不一致,容易触发风控
|
||||
- 直播账号稳定性与定位一致性强相关
|
||||
|
||||
## 操作步骤
|
||||
|
||||
1. 安装定位工具并配置 Mock Location
|
||||
2. 通过地图搜索目标区域并手动校准
|
||||
3. 启动模拟定位后再打开直播 App
|
||||
|
||||
## 检查清单
|
||||
|
||||
- [ ] GPS 城市与代理 IP 所在地区一致
|
||||
- [ ] 时间时区与账号地区一致
|
||||
- [ ] 开播前再次确认定位未漂移
|
||||
`,
|
||||
"2-1": `# 07 无人直播入门:录播素材循环推流
|
||||
|
||||
对应电子书章节:\`业务场景:无人直播\` 与 \`录播mp4素材\`。
|
||||
|
||||
## 核心链路
|
||||
|
||||
1. Linux 辅助板播放素材
|
||||
2. HDMI 输出到采集卡
|
||||
3. 采集卡通过 USB 输入安卓板,识别为摄像头
|
||||
|
||||
## 示例命令
|
||||
|
||||
\`\`\`bash
|
||||
ffplay -loop 0 -vf "transpose=2,scale=640:-1,format=yuv420p" -fs -threads 6 xxx.mp4
|
||||
\`\`\`
|
||||
|
||||
## 实战建议
|
||||
|
||||
- 先用短素材跑通链路,再换长素材
|
||||
- 分辨率和码率不要一步拉满,先求稳定
|
||||
`,
|
||||
"2-2": `# 08 TikTok 实战开播:完整流程演示
|
||||
|
||||
对应电子书章节:\`业务场景:无人直播\` 与 \`辅助板linux配置\`。
|
||||
|
||||
## 开播前准备
|
||||
|
||||
- 辅助板已安装视频/音频驱动与 ffmpeg
|
||||
- 安卓端已完成 Root、改机、定位
|
||||
- 直播账号完成基础养号与资料设置
|
||||
|
||||
## 标准流程
|
||||
|
||||
1. 启动素材源或直播流
|
||||
2. 在 TikTok 端预览并确认摄像头输入
|
||||
3. 开播后观察前 10 分钟数据与风控提示
|
||||
|
||||
## 观察重点
|
||||
|
||||
- 是否弹验证窗口
|
||||
- 是否出现明显限流
|
||||
- 进房、停留、互动是否正常
|
||||
`,
|
||||
"2-3": `# 09 TikTok 进阶优化:稳定推流与细节调优
|
||||
|
||||
对应电子书章节:\`obs推流/srs拉流\`。
|
||||
|
||||
## 进阶目标
|
||||
|
||||
- 降低延迟与卡顿
|
||||
- 提升长时段推流稳定性
|
||||
|
||||
## SRS 部署思路
|
||||
|
||||
- 在辅助板部署 SRS
|
||||
- OBS 走 SRT 推流,辅助板本地拉流喂给安卓摄像头
|
||||
|
||||
## 拉流脚本示例
|
||||
|
||||
\`\`\`bash
|
||||
ffplay -fflags nobuffer -flags low_delay -framedrop \
|
||||
-probesize 32 -analyzeduration 0 -sync ext -infbuf \
|
||||
-vf "setpts=PTS-STARTPTS" \
|
||||
'srt://127.0.0.1:10080?streamid=#!::r=live/livestream,m=request&latency=10'
|
||||
\`\`\`
|
||||
`,
|
||||
"3-0": `# 10 软路由与科学上网
|
||||
|
||||
对应电子书章节:\`魔法上网\`。
|
||||
|
||||
## 为什么是软路由优先
|
||||
|
||||
- 电子书实测:代理 APK 在部分场景难过风控
|
||||
- 软路由链路更稳定,适合长期业务运行
|
||||
|
||||
## 推荐组合
|
||||
|
||||
- 海外 VPS(中转)
|
||||
- 静态住宅 IP(落地)
|
||||
- Clash Meta(链式代理)
|
||||
|
||||
## 操作顺序
|
||||
|
||||
1. 购买 VPS 与域名
|
||||
2. 购买静态住宅 IP
|
||||
3. 配置链式代理与策略路由
|
||||
`,
|
||||
"3-1": `# 11 静态住宅 IP 配置
|
||||
|
||||
对应电子书章节:\`静态住宅ip\` 与 \`链式代理\`。
|
||||
|
||||
## 核心原则
|
||||
|
||||
- 便宜节点通常不能国内直连,必须走中转
|
||||
- IP、GPS、机型要形成一致的“环境画像”
|
||||
|
||||
## 配置要点
|
||||
|
||||
- 落地节点使用静态住宅 IP
|
||||
- 中转与落地分层,避免单点故障
|
||||
- 业务账号固定绑定线路,不频繁切换
|
||||
|
||||
## 验证指标
|
||||
|
||||
- DNS、出口国家、时区一致
|
||||
- 连续开播无大规模验证弹窗
|
||||
`,
|
||||
"4-0": `# 12 HDMI 辅助板方案
|
||||
|
||||
对应电子书章节:\`如果需要直播\` 与 \`业务场景:无人直播\`。
|
||||
|
||||
## 方案价值
|
||||
|
||||
- 把外部视频信号稳定送进安卓端“摄像头”
|
||||
- 满足 TikTok 对移动端直播形态的偏好
|
||||
|
||||
## 硬件清单
|
||||
|
||||
- Linux 辅助板(如 R3S)
|
||||
- 视频采集卡
|
||||
- HDMI 线
|
||||
- 安卓开发板(主控)
|
||||
|
||||
## 连接示意
|
||||
|
||||
\`素材源 -> HDMI -> 采集卡 -> 安卓板 USB\`
|
||||
|
||||
确认安卓相机可预览即代表链路打通。
|
||||
`,
|
||||
"4-1": `# 13 多设备群控与远控
|
||||
|
||||
对应电子书章节:\`远程控制\`、\`内网穿透 frp\`、\`应用多开/系统多开\`。
|
||||
|
||||
## 目标
|
||||
|
||||
- 一台电脑管理多台安卓设备
|
||||
- 降低人工重复操作成本
|
||||
|
||||
## 常见工具链
|
||||
|
||||
- qtscrcpy / escrcpy:图形远控与群控
|
||||
- frp-panel:外网访问与设备穿透
|
||||
- 安卓虚拟机:低成本扩展多开能力
|
||||
|
||||
## 交付标准
|
||||
|
||||
- 可以批量连接设备并执行统一操作
|
||||
- 关键节点支持日志与异常回溯
|
||||
`,
|
||||
};
|
||||
|
||||
export type LessonDetail = {
|
||||
name: string;
|
||||
duration: string;
|
||||
videoUrl: string;
|
||||
markdown: string;
|
||||
};
|
||||
|
||||
export const LESSONS_MAP: Record<string, LessonDetail> = {
|
||||
"0-0": {
|
||||
name: "01 从0到1:安卓镜像安装与首次开机",
|
||||
duration: "08:32",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/1. 安装安卓img_20260326_095335_848.mp4",
|
||||
markdown: LESSON_MARKDOWNS["0-0"],
|
||||
},
|
||||
"0-1": {
|
||||
name: "02 性能翻倍:安卓存储扩容实操",
|
||||
duration: "12:15",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/2. 安卓扩容_20260326_095426_1002.mp4",
|
||||
markdown: LESSON_MARKDOWNS["0-1"],
|
||||
},
|
||||
"1-0": {
|
||||
name: "03 竖屏直播必备:系统显示方向设置",
|
||||
duration: "15:20",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/3. 设置竖屏_20260326_095414_979.mp4",
|
||||
markdown: LESSON_MARKDOWNS["1-0"],
|
||||
},
|
||||
"1-1": {
|
||||
name: "04 一次搞定 Root:Magisk + 模块安装",
|
||||
duration: "18:00",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/4. 安装magisk以及模块_20260326_095427_1018.mp4",
|
||||
markdown: LESSON_MARKDOWNS["1-1"],
|
||||
},
|
||||
"1-2": {
|
||||
name: "05 防风控第一步:机型参数改造",
|
||||
duration: "14:30",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/5. 修改机型参数_20260326_095438_1051.mp4",
|
||||
markdown: LESSON_MARKDOWNS["1-2"],
|
||||
},
|
||||
"2-0": {
|
||||
name: "06 降低风控命中:GPS 精准定位",
|
||||
duration: "16:00",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/6. gps定位_20260326_095430_1031.mp4",
|
||||
markdown: LESSON_MARKDOWNS["2-0"],
|
||||
},
|
||||
"2-1": {
|
||||
name: "07 无人直播入门:录播素材循环推流",
|
||||
duration: "12:45",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/7无人直播-录播_20260326_100335_2814.mp4",
|
||||
markdown: LESSON_MARKDOWNS["2-1"],
|
||||
},
|
||||
"2-2": {
|
||||
name: "08 TikTok 实战开播:完整流程演示",
|
||||
duration: "11:20",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/8. tiktok直播_20260326_095441_1064.mp4",
|
||||
markdown: LESSON_MARKDOWNS["2-2"],
|
||||
},
|
||||
"2-3": {
|
||||
name: "09 TikTok 进阶优化:稳定推流与细节调优",
|
||||
duration: "20:00",
|
||||
videoUrl: "https://minioweb.hackrobot.cn/hackrobot/9. tiktok直播-2_20260326_095403_943.mp4",
|
||||
markdown: LESSON_MARKDOWNS["2-3"],
|
||||
},
|
||||
"3-0": {
|
||||
name: "10 软路由与科学上网",
|
||||
duration: "13:00",
|
||||
videoUrl: SAMPLE_VIDEO,
|
||||
markdown: LESSON_MARKDOWNS["3-0"],
|
||||
},
|
||||
"3-1": {
|
||||
name: "11 静态住宅 IP 配置",
|
||||
duration: "10:30",
|
||||
videoUrl: SAMPLE_VIDEO,
|
||||
markdown: LESSON_MARKDOWNS["3-1"],
|
||||
},
|
||||
"4-0": {
|
||||
name: "12 HDMI 辅助板方案",
|
||||
duration: "15:00",
|
||||
videoUrl: SAMPLE_VIDEO,
|
||||
markdown: LESSON_MARKDOWNS["4-0"],
|
||||
},
|
||||
"4-1": {
|
||||
name: "13 多设备群控与远控",
|
||||
duration: "12:00",
|
||||
videoUrl: SAMPLE_VIDEO,
|
||||
markdown: LESSON_MARKDOWNS["4-1"],
|
||||
},
|
||||
};
|
||||
|
||||
export function getLessonKey(moduleIndex: number, lessonIndex: number): string {
|
||||
return `${moduleIndex}-${lessonIndex}`;
|
||||
}
|
||||
|
||||
export function getLesson(moduleIndex: number, lessonIndex: number): LessonDetail | null {
|
||||
return LESSONS_MAP[getLessonKey(moduleIndex, lessonIndex)] ?? null;
|
||||
}
|
||||
@ -0,0 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback, useRef } from "react";
|
||||
import { marked } from "marked";
|
||||
import styles from "./lesson-markdown.module.css";
|
||||
|
||||
type TocItem = { level: number; text: string; id: string };
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.replace(/[^\p{L}\p{N}\s-]/gu, "")
|
||||
.replace(/\s+/g, "-")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function extractToc(content: string): TocItem[] {
|
||||
const items: TocItem[] = [];
|
||||
const lines = content.split("\n");
|
||||
let idCounter = 0;
|
||||
for (const line of lines) {
|
||||
const h1 = line.match(/^# (.+)$/);
|
||||
const h2 = line.match(/^## (.+)$/);
|
||||
if (h1) {
|
||||
items.push({ level: 1, text: h1[1].replace(/#{1,6}\s/g, "").trim(), id: `h-${idCounter++}` });
|
||||
} else if (h2) {
|
||||
items.push({ level: 2, text: h2[1].replace(/#{1,6}\s/g, "").trim(), id: `h-${idCounter++}` });
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function markdownToHtml(content: string): string {
|
||||
const raw = marked.parse(content, { breaks: true, gfm: true }) as string;
|
||||
let html = raw
|
||||
.replace(/<img /g, '<img loading="lazy" decoding="async" ')
|
||||
.replace(/<a href=/g, '<a href=');
|
||||
// 给 h1/h2 添加 id
|
||||
html = html.replace(/<h1>([^<]*)<\/h1>/gi, (_, text) => {
|
||||
const t = text.replace(/<[^>]+>/g, "").trim();
|
||||
return `<h1 id="${slugify(t)}" class="scroll-mt-24">${text}</h1>`;
|
||||
});
|
||||
html = html.replace(/<h2>([^<]*)<\/h2>/gi, (_, text) => {
|
||||
const t = text.replace(/<[^>]+>/g, "").trim();
|
||||
return `<h2 id="${slugify(t)}" class="scroll-mt-24">${text}</h2>`;
|
||||
});
|
||||
html = html.replace(/<a href="([^"]+)"([^>]*)>/g, '<a href="$1" target="_blank" rel="noopener noreferrer"$2>');
|
||||
html = html.replace(/<pre>\s*<code([^>]*)>/g, `<pre class="${styles.codeBlock}"><code$1>`);
|
||||
return html;
|
||||
}
|
||||
|
||||
export function LessonMarkdown({ content }: { content: string }) {
|
||||
const [readProgress, setReadProgress] = useState(0);
|
||||
const [showBackTop, setShowBackTop] = useState(false);
|
||||
const [showToc, setShowToc] = useState(false);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const toc = extractToc(content);
|
||||
const html = markdownToHtml(content);
|
||||
|
||||
useEffect(() => {
|
||||
let ticking = false;
|
||||
const onScroll = () => {
|
||||
if (ticking) return;
|
||||
ticking = true;
|
||||
requestAnimationFrame(() => {
|
||||
const scrollTop = window.scrollY || document.documentElement.scrollTop;
|
||||
const docHeight = document.documentElement.scrollHeight - window.innerHeight;
|
||||
setReadProgress(docHeight > 0 ? Math.min(100, (scrollTop / docHeight) * 100) : 0);
|
||||
setShowBackTop(scrollTop > 400);
|
||||
ticking = false;
|
||||
});
|
||||
};
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => window.removeEventListener("scroll", onScroll);
|
||||
}, []);
|
||||
|
||||
const handleTocJump = useCallback((index: number) => {
|
||||
setShowToc(false);
|
||||
const root = contentRef.current;
|
||||
if (!root) return;
|
||||
const headings = root.querySelectorAll("h1, h2");
|
||||
const el = headings[index] as HTMLElement;
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={styles.readingProgress} style={{ width: `${readProgress}%` }} />
|
||||
|
||||
<div
|
||||
ref={contentRef}
|
||||
className={`${styles.markdownBody} markdown-body`}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={`${styles.drawerMask} ${showToc ? styles.drawerMaskOpen : ""}`}
|
||||
onClick={() => setShowToc(false)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<aside className={`${styles.drawer} ${showToc ? styles.drawerOpen : ""}`}>
|
||||
<div className={styles.drawerTitle}>目录</div>
|
||||
{toc.map((item, i) => (
|
||||
<div
|
||||
key={item.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={item.level === 2 ? `${styles.drawerItem} ${styles.drawerItemH2}` : styles.drawerItem}
|
||||
onClick={() => handleTocJump(i)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") handleTocJump(i);
|
||||
}}
|
||||
>
|
||||
{item.text}
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
{showBackTop && (
|
||||
<>
|
||||
{toc.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.tocButton}
|
||||
onClick={() => setShowToc(true)}
|
||||
aria-label="打开目录"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.backToTop}
|
||||
onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
|
||||
aria-label="回到顶部"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M18 15l-6-6-6 6" />
|
||||
</svg>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,333 @@
|
||||
.readingProgress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, var(--accent) 0%, #fbbf24 100%);
|
||||
z-index: 100;
|
||||
transition: width 0.15s linear;
|
||||
border-radius: 0 3px 3px 0;
|
||||
}
|
||||
|
||||
.backToTop {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
cursor: pointer;
|
||||
z-index: 50;
|
||||
color: var(--accent);
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.backToTop:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.tocButton {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 84px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
cursor: pointer;
|
||||
z-index: 50;
|
||||
color: var(--accent);
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.tocButton:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.drawerMask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
z-index: 140;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerMaskOpen {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 280px;
|
||||
max-width: 85vw;
|
||||
background: var(--background);
|
||||
border-left: 1px solid var(--border);
|
||||
box-shadow: -4px 0 24px rgba(0, 0, 0, 0.15);
|
||||
z-index: 150;
|
||||
padding: 80px 0 24px;
|
||||
overflow-y: auto;
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerOpen {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.drawerTitle {
|
||||
padding: 0 20px 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--muted-foreground);
|
||||
border-bottom: 1px solid var(--border);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.drawerItem {
|
||||
padding: 10px 20px;
|
||||
font-size: 14px;
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.drawerItem:hover {
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.drawerItemH2 {
|
||||
padding-left: 28px;
|
||||
font-size: 13px;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.markdownBody {
|
||||
font-size: 16px;
|
||||
line-height: 1.85;
|
||||
color: var(--foreground);
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
color: var(--foreground);
|
||||
margin: 28px 0 12px;
|
||||
padding-bottom: 0;
|
||||
border-bottom: none;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.markdownBody h1:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.markdownBody h1::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 40px;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, var(--accent), #fbbf24);
|
||||
border-radius: 3px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--foreground);
|
||||
margin: 24px 0 10px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.markdownBody h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
margin: 20px 0 8px;
|
||||
}
|
||||
|
||||
.markdownBody h4,
|
||||
.markdownBody h5,
|
||||
.markdownBody h6 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
margin: 16px 0 6px;
|
||||
}
|
||||
|
||||
.markdownBody p {
|
||||
font-size: 1rem;
|
||||
margin-bottom: 14px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.markdownBody blockquote {
|
||||
position: relative;
|
||||
margin: 24px 0;
|
||||
padding: 16px 20px 16px 24px;
|
||||
border-left: none;
|
||||
background: var(--muted);
|
||||
border-radius: 0 12px 12px 0;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.markdownBody blockquote::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 4px;
|
||||
background: var(--accent);
|
||||
border-radius: 0 2px 2px 0;
|
||||
}
|
||||
|
||||
.markdownBody pre.codeBlock {
|
||||
margin: 24px 0;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
border-radius: 8px;
|
||||
background: #282c34;
|
||||
}
|
||||
|
||||
.markdownBody pre.codeBlock code {
|
||||
display: block;
|
||||
padding: 16px;
|
||||
font-size: 0.875em;
|
||||
line-height: 1.6;
|
||||
color: #abb2bf;
|
||||
}
|
||||
|
||||
|
||||
.markdownBody p code,
|
||||
.markdownBody li code {
|
||||
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
padding: 0.2em 0.4em;
|
||||
background: var(--muted);
|
||||
color: var(--foreground);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.markdownBody a {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdownBody a:hover {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.markdownBody img {
|
||||
display: block;
|
||||
margin: 28px auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.markdownBody ul,
|
||||
.markdownBody ol {
|
||||
margin: 16px 0;
|
||||
padding-left: 28px;
|
||||
}
|
||||
|
||||
.markdownBody li {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.markdownBody table {
|
||||
width: 100%;
|
||||
margin: 24px 0;
|
||||
border-collapse: collapse;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.markdownBody th {
|
||||
background: var(--muted);
|
||||
font-weight: 600;
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.markdownBody td {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.markdownBody tr:nth-child(even) {
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.markdownBody hr {
|
||||
border: none;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
margin: 28px 0;
|
||||
}
|
||||
|
||||
.markdownBody strong {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.markdownBody input[type="checkbox"] {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.markdownBody {
|
||||
font-size: 17px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 1.75rem;
|
||||
margin: 32px 0 14px;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 1.35rem;
|
||||
margin: 28px 0 12px;
|
||||
}
|
||||
|
||||
.markdownBody h3 {
|
||||
font-size: 1.2rem;
|
||||
margin: 24px 0 10px;
|
||||
}
|
||||
|
||||
.backToTop,
|
||||
.tocButton {
|
||||
bottom: 32px;
|
||||
right: 32px;
|
||||
}
|
||||
|
||||
.tocButton {
|
||||
right: 92px;
|
||||
}
|
||||
}
|
||||
146
app/vip/cloudphone/course/[moduleIndex]/[lessonIndex]/page.tsx
Normal file
146
app/vip/cloudphone/course/[moduleIndex]/[lessonIndex]/page.tsx
Normal file
@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||
import { Header } from "../../../components";
|
||||
import { VideoPlayer } from "../../../components/VideoPlayer";
|
||||
import { LessonMarkdown } from "./LessonMarkdown";
|
||||
import { LessonLayout } from "@vip/app/components/content/LessonLayout";
|
||||
import { getLesson } from "../../../config/lessons";
|
||||
import { canWatchLesson } from "../../../lib/payment";
|
||||
import { setLastWatched, markCompleted, getCompletedLessons } from "../../../lib/learning";
|
||||
import { CURRICULUM_CONFIG, DOWNLOAD_CONFIG } from "../../../config/course";
|
||||
import { CLOUDPHONE_COURSE_CONFIG } from "@vip/config/content.config";
|
||||
import { getPrevNextLesson } from "@vip/lib/content/course-utils";
|
||||
|
||||
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
|
||||
|
||||
export default function LessonPage() {
|
||||
const params = useParams();
|
||||
const moduleIndex = Number(params.moduleIndex);
|
||||
const lessonIndex = Number(params.lessonIndex);
|
||||
|
||||
const lesson = getLesson(moduleIndex, lessonIndex);
|
||||
const unlocked = canWatchLesson(moduleIndex, lessonIndex);
|
||||
const isFreeTrial = false; /* 暂时全部加锁,仅 VIP 可看 */
|
||||
const [completed, setCompleted] = useState(() => getCompletedLessons().size);
|
||||
const { prev: prevLesson, next: nextLesson } = getPrevNextLesson(
|
||||
CURRICULUM_CONFIG.modules,
|
||||
moduleIndex,
|
||||
lessonIndex
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (lesson && unlocked) setLastWatched(moduleIndex, lessonIndex, lesson.name);
|
||||
}, [moduleIndex, lessonIndex, lesson?.name, unlocked]);
|
||||
|
||||
useEffect(() => {
|
||||
const onProgress = () => setCompleted(getCompletedLessons().size);
|
||||
window.addEventListener("learning:progress", onProgress);
|
||||
return () => window.removeEventListener("learning:progress", onProgress);
|
||||
}, []);
|
||||
|
||||
if (!lesson || isNaN(moduleIndex) || isNaN(lessonIndex)) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header />
|
||||
<main className="pt-20 pb-16">
|
||||
<div className="mx-auto max-w-4xl px-4 py-16 text-center">
|
||||
<h1 className="mb-4 text-2xl font-bold">章节不存在</h1>
|
||||
<p className="mb-6 text-[var(--muted-foreground)]">请检查链接或返回课程首页</p>
|
||||
<Link
|
||||
href="/vip/cloudphone"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
← 返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<Header />
|
||||
<LessonLayout
|
||||
courseConfig={CLOUDPHONE_COURSE_CONFIG}
|
||||
moduleIndex={moduleIndex}
|
||||
lessonIndex={lessonIndex}
|
||||
lessonName={lesson.name}
|
||||
lessonDuration={lesson.duration}
|
||||
isFreeTrial={isFreeTrial}
|
||||
unlocked={unlocked}
|
||||
totalLessons={TOTAL_LESSONS}
|
||||
completedCount={completed}
|
||||
prevLesson={prevLesson}
|
||||
nextLesson={nextLesson}
|
||||
courseHomeHref="/vip/cloudphone"
|
||||
payHref="#"
|
||||
>
|
||||
<div className="animate__animated animate__fadeInUp relative mb-12" style={{ animationDelay: "0.2s", animationFillMode: "both" }}>
|
||||
{unlocked ? (
|
||||
<VideoPlayer
|
||||
src={lesson.videoUrl}
|
||||
title={lesson.name}
|
||||
videoId={`cloudphone-${moduleIndex}-${lessonIndex}`}
|
||||
className="shadow-xl"
|
||||
onComplete={() => markCompleted(moduleIndex, lessonIndex)}
|
||||
/>
|
||||
) : (
|
||||
<div className="relative overflow-hidden rounded-xl bg-black md:rounded-2xl">
|
||||
<div className="aspect-video flex flex-col items-center justify-center gap-4 bg-zinc-900">
|
||||
<span className="text-6xl">🔒</span>
|
||||
<p className="text-lg text-white/90">报名解锁本章节</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => triggerPay()}
|
||||
className="rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
立即报名
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{unlocked && (
|
||||
<div className="animate__animated animate__fadeInUp relative rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm md:rounded-2xl md:p-8" style={{ animationDelay: "0.3s", animationFillMode: "both" }}>
|
||||
<h2 className="mb-6 flex items-center gap-2 text-lg font-semibold">
|
||||
<svg className="h-5 w-5 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
配套文档
|
||||
</h2>
|
||||
<LessonMarkdown content={lesson.markdown} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{DOWNLOAD_CONFIG.enabled && unlocked && (
|
||||
<div className="mt-8 rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm md:rounded-2xl md:p-8">
|
||||
<h2 className="mb-4 flex items-center gap-2 text-lg font-semibold">
|
||||
<svg className="h-5 w-5 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
{DOWNLOAD_CONFIG.title}
|
||||
</h2>
|
||||
<p className="mb-4 text-sm text-[var(--muted-foreground)]">课程配套资料已上传至网盘,报名后可前往下载</p>
|
||||
<Link
|
||||
href={DOWNLOAD_CONFIG.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
{DOWNLOAD_CONFIG.buttonText}
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</LessonLayout>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
20
app/vip/cloudphone/layout.tsx
Normal file
20
app/vip/cloudphone/layout.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import { ChatFloatButton } from "./components/ChatFloatButton";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "云手机 | 低成本工作室搭建指南",
|
||||
description: "云手机实战课:用开源硬件打造云手机,TikTok无人直播、Youtube运营自动化。",
|
||||
};
|
||||
|
||||
export default function CloudphoneLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<ChatFloatButton />
|
||||
</>
|
||||
);
|
||||
}
|
||||
141
app/vip/cloudphone/lib/learning.ts
Normal file
141
app/vip/cloudphone/lib/learning.ts
Normal file
@ -0,0 +1,141 @@
|
||||
/**
|
||||
* 学习进度、继续学习、收藏、笔记 - localStorage(克隆自 nomadlms)
|
||||
*/
|
||||
|
||||
const PREFIX = "lms-cloudphone-";
|
||||
const KEY_LAST = `${PREFIX}last`;
|
||||
const KEY_COMPLETED = `${PREFIX}completed`;
|
||||
const KEY_BOOKMARKS = `${PREFIX}bookmarks`;
|
||||
const KEY_NOTES = `${PREFIX}notes`;
|
||||
const KEY_RATING = `${PREFIX}rating`;
|
||||
|
||||
export type LastWatched = { moduleIndex: number; lessonIndex: number; name: string };
|
||||
|
||||
export function getLastWatched(): LastWatched | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_LAST);
|
||||
if (!raw) return null;
|
||||
const d = JSON.parse(raw);
|
||||
if (typeof d?.moduleIndex !== "number" || typeof d?.lessonIndex !== "number") return null;
|
||||
return { moduleIndex: d.moduleIndex, lessonIndex: d.lessonIndex, name: d.name || "" };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setLastWatched(m: number, l: number, name: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
localStorage.setItem(KEY_LAST, JSON.stringify({ moduleIndex: m, lessonIndex: l, name }));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function getCompletedLessons(): Set<string> {
|
||||
if (typeof window === "undefined") return new Set();
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_COMPLETED);
|
||||
if (!raw) return new Set();
|
||||
const arr = JSON.parse(raw);
|
||||
return new Set(Array.isArray(arr) ? arr : []);
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
export function markCompleted(moduleIndex: number, lessonIndex: number): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
const set = getCompletedLessons();
|
||||
set.add(`${moduleIndex}-${lessonIndex}`);
|
||||
localStorage.setItem(KEY_COMPLETED, JSON.stringify([...set]));
|
||||
window.dispatchEvent(new CustomEvent("learning:progress"));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function getProgress(totalLessons: number): { completed: number; percent: number } {
|
||||
const set = getCompletedLessons();
|
||||
const completed = set.size;
|
||||
return { completed, percent: totalLessons > 0 ? Math.round((completed / totalLessons) * 100) : 0 };
|
||||
}
|
||||
|
||||
export function getBookmarks(): Set<string> {
|
||||
if (typeof window === "undefined") return new Set();
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_BOOKMARKS);
|
||||
if (!raw) return new Set();
|
||||
const arr = JSON.parse(raw);
|
||||
return new Set(Array.isArray(arr) ? arr : []);
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
export function toggleBookmark(moduleIndex: number, lessonIndex: number): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
try {
|
||||
const set = getBookmarks();
|
||||
const key = `${moduleIndex}-${lessonIndex}`;
|
||||
if (set.has(key)) set.delete(key);
|
||||
else set.add(key);
|
||||
localStorage.setItem(KEY_BOOKMARKS, JSON.stringify([...set]));
|
||||
window.dispatchEvent(new CustomEvent("learning:bookmarks"));
|
||||
return set.has(key);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isBookmarked(moduleIndex: number, lessonIndex: number): boolean {
|
||||
return getBookmarks().has(`${moduleIndex}-${lessonIndex}`);
|
||||
}
|
||||
|
||||
export function getNote(moduleIndex: number, lessonIndex: number): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_NOTES);
|
||||
if (!raw) return "";
|
||||
const map = JSON.parse(raw);
|
||||
return map[`${moduleIndex}-${lessonIndex}`] ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function setNote(moduleIndex: number, lessonIndex: number, text: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_NOTES);
|
||||
const map = raw ? JSON.parse(raw) : {};
|
||||
map[`${moduleIndex}-${lessonIndex}`] = text;
|
||||
localStorage.setItem(KEY_NOTES, JSON.stringify(map));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function getRating(): { stars: number; comment: string } | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY_RATING);
|
||||
if (!raw) return null;
|
||||
const d = JSON.parse(raw);
|
||||
return { stars: d?.stars ?? 0, comment: d?.comment ?? "" };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setRating(stars: number, comment: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
localStorage.setItem(KEY_RATING, JSON.stringify({ stars, comment }));
|
||||
window.dispatchEvent(new CustomEvent("learning:rating"));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
22
app/vip/cloudphone/lib/payment.ts
Normal file
22
app/vip/cloudphone/lib/payment.ts
Normal file
@ -0,0 +1,22 @@
|
||||
/**
|
||||
* 支付状态 - 适配 nomadvip paidType(克隆自 nomadlms)
|
||||
*
|
||||
* CTA 校验逻辑:有本地 paidType=vip 时优先使用;无则点击「立即加入」直接进入支付流程
|
||||
*/
|
||||
|
||||
/** nomadvip 使用 paidType=vip 表示已支付 */
|
||||
export function isPaid(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
return localStorage.getItem("paidType") === "vip";
|
||||
}
|
||||
|
||||
/** 暂时全部加锁,仅 VIP 可看(原前 2 节试看已关闭) */
|
||||
export function isFreeTrial(_moduleIndex: number, _lessonIndex: number): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 章节是否可观看 */
|
||||
export function canWatchLesson(moduleIndex: number, lessonIndex: number): boolean {
|
||||
if (isFreeTrial(moduleIndex, lessonIndex)) return true;
|
||||
return isPaid();
|
||||
}
|
||||
32
app/vip/cloudphone/page.tsx
Normal file
32
app/vip/cloudphone/page.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Header,
|
||||
Hero,
|
||||
Footer,
|
||||
AudienceSection,
|
||||
BenefitsSection,
|
||||
CurriculumSection,
|
||||
AnimateOnScroll,
|
||||
} from "./components";
|
||||
|
||||
export default function CloudphonePage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<Header />
|
||||
<main>
|
||||
<Hero />
|
||||
<AnimateOnScroll delay={0}>
|
||||
<AudienceSection />
|
||||
</AnimateOnScroll>
|
||||
<AnimateOnScroll delay={100}>
|
||||
<BenefitsSection />
|
||||
</AnimateOnScroll>
|
||||
<AnimateOnScroll delay={0}>
|
||||
<CurriculumSection />
|
||||
</AnimateOnScroll>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
64
app/vip/cloudphone/pay/page.tsx
Normal file
64
app/vip/cloudphone/pay/page.tsx
Normal file
@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense, useEffect } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Header } from "../components";
|
||||
|
||||
function PayContent() {
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && searchParams.get("test") === "ok") {
|
||||
localStorage.setItem("paidType", "vip");
|
||||
window.dispatchEvent(new CustomEvent("pay:updated"));
|
||||
window.location.href = "/vip/cloudphone";
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
if (searchParams.get("test") === "ok") {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-[var(--background)]">
|
||||
<p className="text-[var(--muted-foreground)]">正在跳转...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<Header />
|
||||
<main className="flex min-h-[80vh] flex-col items-center justify-center px-4">
|
||||
<h1 className="animate__animated animate__fadeInDown mb-2 text-2xl font-bold" style={{ animationDelay: "0.1s", animationFillMode: "both" }}>报名云手机实战课</h1>
|
||||
<p className="animate__animated animate__fadeInUp mb-6 text-[var(--muted-foreground)]" style={{ animationDelay: "0.2s", animationFillMode: "both" }}>
|
||||
加入异度星球 VIP,解锁全部 13 节视频 + 电子书 + 社群答疑
|
||||
</p>
|
||||
<div className="animate__animated animate__zoomIn mb-8 flex flex-col gap-3 sm:flex-row sm:gap-4" style={{ animationDelay: "0.35s", animationFillMode: "both" }}>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center justify-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
|
||||
>
|
||||
前往首页完成支付 →
|
||||
</Link>
|
||||
</div>
|
||||
<p className="mb-4 text-xs text-[var(--muted-foreground)]">
|
||||
测试:<Link href="/vip/cloudphone/pay?test=ok" className="text-[var(--accent)] underline">点击模拟支付成功</Link>
|
||||
</p>
|
||||
<Link href="/vip/cloudphone" className="text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
|
||||
返回课程首页
|
||||
</Link>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PayPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="flex min-h-screen items-center justify-center bg-[var(--background)]">
|
||||
<p className="text-[var(--muted-foreground)]">加载中...</p>
|
||||
</div>
|
||||
}>
|
||||
<PayContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
47
app/vip/components/HomeBootOverlay.tsx
Normal file
47
app/vip/components/HomeBootOverlay.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
type HomeBootOverlayProps = {
|
||||
visible: boolean;
|
||||
/** 默认:正在同步会员状态… */
|
||||
subtitle?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 全屏加载(登录验证、首屏等按需使用)
|
||||
*/
|
||||
export function HomeBootOverlay({ visible, subtitle }: HomeBootOverlayProps) {
|
||||
if (!visible) return null;
|
||||
|
||||
const line = subtitle ?? "正在同步会员状态…";
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[200] flex flex-col items-center justify-center gap-6 bg-[var(--background)]/92 backdrop-blur-md"
|
||||
aria-busy="true"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="relative flex h-20 w-20 items-center justify-center">
|
||||
<div
|
||||
className="absolute inset-0 animate-spin rounded-full border-2 border-amber-500/20 border-t-amber-500"
|
||||
style={{ animationDuration: "1.05s" }}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-2 animate-spin rounded-full border-2 border-transparent border-b-amber-400/50"
|
||||
style={{ animationDuration: "0.75s", animationDirection: "reverse" }}
|
||||
/>
|
||||
<span
|
||||
className="animate__animated animate__pulse animate__infinite text-3xl drop-shadow-sm"
|
||||
aria-hidden
|
||||
>
|
||||
🌍
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-1 px-6 text-center">
|
||||
<p className="text-base font-semibold tracking-wide text-[var(--foreground)]">
|
||||
异度星球
|
||||
</p>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{line}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
80
app/vip/components/InstantQaVipModal.tsx
Normal file
80
app/vip/components/InstantQaVipModal.tsx
Normal file
@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { triggerPay } from "@vip/app/lib/triggerPay";
|
||||
import styles from "@vip/app/vip/components/vip.module.css";
|
||||
|
||||
type InstantQaVipModalProps = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export function InstantQaVipModal({ open, onClose }: InstantQaVipModalProps) {
|
||||
useEffect(() => {
|
||||
if (open) document.body.style.overflow = "hidden";
|
||||
else document.body.style.overflow = "";
|
||||
return () => { document.body.style.overflow = ""; };
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const handleUnlock = () => {
|
||||
onClose();
|
||||
triggerPay();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="qa-vip-modal-title"
|
||||
>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div
|
||||
className="relative w-full max-w-[360px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl animate__animated animate__fadeIn animate__faster"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[var(--accent)]/20 text-xl">
|
||||
💬
|
||||
</span>
|
||||
<h2 id="qa-vip-modal-title" className="text-lg font-semibold text-[var(--foreground)]" style={{ margin: 0 }}>
|
||||
即时问答
|
||||
</h2>
|
||||
</div>
|
||||
<p className="mb-6 text-sm leading-relaxed text-[var(--muted-foreground)]">
|
||||
即时问答是会员专享的贴心服务,开通后即可获得一对一技术咨询支持,随时解答你的疑问~
|
||||
</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleUnlock}
|
||||
className={`${styles.btnPrimary} ${styles.btnLarge} w-full`}
|
||||
>
|
||||
立即开通 →
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="w-full rounded-full border border-[var(--border)] py-2.5 text-sm text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
|
||||
>
|
||||
稍后再说
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
503
app/vip/components/NetdiskDownloadsSection.module.css
Normal file
503
app/vip/components/NetdiskDownloadsSection.module.css
Normal file
@ -0,0 +1,503 @@
|
||||
.section {
|
||||
margin: 0 auto;
|
||||
max-width: 76rem;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
.wrap {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 1.1rem;
|
||||
border: 1px solid var(--border);
|
||||
background: linear-gradient(180deg, color-mix(in oklab, var(--card), transparent 0%) 0%, color-mix(in oklab, var(--card), transparent 6%) 100%);
|
||||
box-shadow: 0 12px 34px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.wrap::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(1200px 420px at 20% -10%, color-mix(in oklab, var(--accent), transparent 75%) 0%, transparent 60%),
|
||||
radial-gradient(900px 380px at 95% 10%, color-mix(in oklab, #7c3aed, transparent 78%) 0%, transparent 55%);
|
||||
pointer-events: none;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1.1rem 1.1rem 0.7rem;
|
||||
}
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin-top: 0.25rem;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.badgeRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.gridWrap {
|
||||
padding: 0.55rem 1.1rem 1.05rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 25%);
|
||||
color: var(--foreground);
|
||||
padding: 0.3rem 0.55rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.vipChip {
|
||||
border: 1px solid color-mix(in oklab, var(--accent), transparent 55%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 85%);
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.guestChip {
|
||||
border: 1px solid color-mix(in oklab, var(--muted-foreground), transparent 55%);
|
||||
background: color-mix(in oklab, var(--card), transparent 40%);
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
margin-top: 0.65rem;
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: 0.72rem;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted-foreground);
|
||||
border-radius: 999px;
|
||||
padding: 0.2rem 0.45rem;
|
||||
}
|
||||
|
||||
.toggleBtn {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 10%);
|
||||
color: var(--foreground);
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.toggleBtn:hover {
|
||||
border-color: color-mix(in oklab, var(--accent), transparent 55%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 88%);
|
||||
}
|
||||
|
||||
.toggleBtn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.chev {
|
||||
transition: transform 160ms ease;
|
||||
}
|
||||
|
||||
.chevOpen {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.panel {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 0.55rem 0.55rem 0.65rem;
|
||||
width: 100%;
|
||||
align-self: stretch;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.panelHint {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.hintText {
|
||||
font-size: 0.8rem;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.links {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.linkRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.6rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.9rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
background: color-mix(in oklab, var(--card), transparent 0%);
|
||||
}
|
||||
|
||||
.provider {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 6rem;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.providerDot {
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.dotBaidu {
|
||||
background: #3b82f6;
|
||||
}
|
||||
|
||||
.dotQuark {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
.linkTextWrap {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
font-size: 0.79rem;
|
||||
color: var(--foreground);
|
||||
opacity: 0.95;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.mutedMono {
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.pillBtn {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 10%);
|
||||
color: var(--foreground);
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.55rem;
|
||||
font-size: 0.79rem;
|
||||
line-height: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.pillBtn:hover {
|
||||
border-color: color-mix(in oklab, var(--accent), transparent 55%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 88%);
|
||||
}
|
||||
|
||||
.pillBtn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.pillBtnDisabled,
|
||||
.pillBtnDisabled:hover,
|
||||
.pillBtnDisabled:active {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
border-color: var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 25%);
|
||||
}
|
||||
|
||||
.guestCta {
|
||||
margin-top: 0.7rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid color-mix(in oklab, var(--accent), transparent 58%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 90%);
|
||||
color: var(--accent);
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.guestBlur {
|
||||
filter: blur(6px);
|
||||
opacity: 0.6;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.footerNote {
|
||||
position: relative;
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 0.75rem 1.1rem 1.05rem;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.iconRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
padding-top: 0.25rem;
|
||||
}
|
||||
|
||||
.netdiskIconBtn {
|
||||
appearance: none;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 0%);
|
||||
color: var(--foreground);
|
||||
width: 46px;
|
||||
height: 38px;
|
||||
border-radius: 12px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: transform 160ms ease, border-color 160ms ease, background 160ms ease, opacity 160ms ease;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.netdiskIconBtn:hover {
|
||||
border-color: color-mix(in oklab, var(--accent), transparent 55%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 92%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.netdiskIconBtn:active {
|
||||
transform: translateY(0px) scale(0.98);
|
||||
}
|
||||
|
||||
.netdiskIconBtnDisabled,
|
||||
.netdiskIconBtnDisabled:hover,
|
||||
.netdiskIconBtnDisabled:active {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
border-color: var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 25%);
|
||||
}
|
||||
|
||||
.iconColorBaidu {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.iconColorQuark {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.modalOverlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
z-index: 50;
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: min(560px, 100%);
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.25);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.modalHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.9rem 1rem 0.7rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.modalTitleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.modalIcon {
|
||||
color: var(--accent);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modalTitle {
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.modalCloseBtn {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 0%);
|
||||
width: 36px;
|
||||
height: 34px;
|
||||
border-radius: 12px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.modalCloseBtn:hover {
|
||||
border-color: color-mix(in oklab, var(--accent), transparent 55%);
|
||||
background: color-mix(in oklab, var(--accent), transparent 92%);
|
||||
}
|
||||
|
||||
.modalBody {
|
||||
padding: 0.9rem 1rem 1rem;
|
||||
}
|
||||
|
||||
.modalPre {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
font-size: 0.86rem;
|
||||
color: var(--foreground);
|
||||
background: color-mix(in oklab, var(--card), transparent 0%);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 0.75rem 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.modalRow {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 0.55rem 0;
|
||||
border-bottom: 1px solid color-mix(in oklab, var(--border), transparent 0%);
|
||||
}
|
||||
|
||||
.modalRow:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.modalLabel {
|
||||
flex: 0 0 auto;
|
||||
width: 72px;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.86rem;
|
||||
padding-top: 0.1rem;
|
||||
}
|
||||
|
||||
.modalMono {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
font-size: 0.86rem;
|
||||
color: var(--foreground);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.modalActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.65rem;
|
||||
padding: 0.9rem 1rem 1rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.modalCopyBtn {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 0%);
|
||||
color: var(--foreground);
|
||||
border-radius: 14px;
|
||||
padding: 0.55rem 0.85rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modalCopyBtn:hover {
|
||||
border-color: color-mix(in oklab, var(--accent), transparent 55%);
|
||||
}
|
||||
|
||||
.modalOpenBtn {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--accent);
|
||||
color: var(--accent-foreground);
|
||||
border-radius: 14px;
|
||||
padding: 0.55rem 0.85rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.modalOpenBtn:hover {
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
.modalOpenBtnDisabled,
|
||||
.modalOpenBtnDisabled:hover {
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in oklab, var(--card), transparent 15%);
|
||||
color: var(--muted-foreground);
|
||||
cursor: not-allowed;
|
||||
opacity: 0.65;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
205
app/vip/components/NetdiskDownloadsSection.tsx
Normal file
205
app/vip/components/NetdiskDownloadsSection.tsx
Normal file
@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import vipStyles from "@vip/app/vip/components/vip.module.css";
|
||||
import styles from "./NetdiskDownloadsSection.module.css";
|
||||
import { Copyable } from "@vip/app/vip/components/Copyable";
|
||||
import { NETDISK_RESOURCES, type NetdiskLink, type NetdiskResource } from "@vip/app/config/netdisk-downloads";
|
||||
|
||||
type Variant = "vip" | "guest";
|
||||
|
||||
type ModalState = {
|
||||
resource: NetdiskResource;
|
||||
link: NetdiskLink;
|
||||
} | null;
|
||||
|
||||
function DownloadIcon() {
|
||||
return (
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M12 3v12" />
|
||||
<path d="m17 10-5 5-5-5" />
|
||||
<path d="M21 21H3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function buildCopyText(resource: NetdiskResource, link: NetdiskLink) {
|
||||
if (link.copyText?.trim()) return link.copyText.trim();
|
||||
const url = link.url?.trim() || "";
|
||||
const code = link.code?.trim() || "";
|
||||
const codeLabel = link.codeLabel || "提取码";
|
||||
|
||||
// 复制内容尽量“无歧义”,不写百度/夸克字样(避免用户认为需要转发“带品牌”)
|
||||
return [resource.title, url, code ? `${codeLabel}: ${code}` : ""].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function getResourceEmoji(resource: NetdiskResource) {
|
||||
if (resource.id === "system-firmware") return "🧱";
|
||||
if (resource.id === "software-tools") return "🛠️";
|
||||
return "📦";
|
||||
}
|
||||
|
||||
export function NetdiskDownloadsSection({ variant, onRequireVip }: { variant: Variant; onRequireVip?: () => void }) {
|
||||
const [open, setOpen] = useState<Record<string, boolean>>({});
|
||||
const [modal, setModal] = useState<ModalState>(null);
|
||||
const locked = variant === "guest";
|
||||
|
||||
useEffect(() => {
|
||||
if (!modal) return;
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setModal(null);
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [modal]);
|
||||
|
||||
const getLinkByProvider = (resource: NetdiskResource, provider: NetdiskLink["provider"]) => {
|
||||
return resource.links.find((l) => l.provider === provider) || null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={vipStyles.section} aria-label="网盘下载">
|
||||
<h2 className={vipStyles.sectionTitle}>网盘下载</h2>
|
||||
|
||||
<div className={`${vipStyles.topicGrid} animate__animated animate__fadeInUp`} style={{ animationDelay: "0.2s", animationFillMode: "both" }}>
|
||||
{NETDISK_RESOURCES.map((r) => {
|
||||
const isOpen = !!open[r.id];
|
||||
const emoji = getResourceEmoji(r);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className={vipStyles.topicCard}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
if (locked) {
|
||||
onRequireVip?.();
|
||||
return;
|
||||
}
|
||||
setOpen((m) => ({ ...m, [r.id]: !m[r.id] }));
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
if (locked) onRequireVip?.();
|
||||
else setOpen((m) => ({ ...m, [r.id]: !m[r.id] }));
|
||||
}
|
||||
}}
|
||||
aria-expanded={variant === "vip" ? isOpen : undefined}
|
||||
style={{ textAlign: "center", cursor: "pointer", opacity: locked ? 0.98 : 1 }}
|
||||
>
|
||||
{locked && <span className={vipStyles.topicLock} title="会员专享">🔒</span>}
|
||||
|
||||
<span className={vipStyles.topicCardInner}>
|
||||
<span className={vipStyles.topicIcon} aria-hidden="true">
|
||||
{emoji}
|
||||
</span>
|
||||
<span className={vipStyles.topicTitle}>{r.title}</span>
|
||||
</span>
|
||||
|
||||
{variant === "vip" && isOpen && (
|
||||
<div id={`netdisk-panel-${r.id}`} className={styles.panel} role="region" aria-label={`${r.title} 链接`}>
|
||||
{(() => {
|
||||
const quark = getLinkByProvider(r, "quark");
|
||||
const quarkUrl = quark?.url?.trim() || "";
|
||||
|
||||
return (
|
||||
<div className={styles.iconRow} aria-label="下载图标">
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.netdiskIconBtn} ${!quarkUrl ? styles.netdiskIconBtnDisabled : ""}`}
|
||||
onClick={() => {
|
||||
if (!quark || !quarkUrl) return;
|
||||
setModal({ resource: r, link: quark });
|
||||
}}
|
||||
disabled={!quarkUrl}
|
||||
aria-disabled={!quarkUrl}
|
||||
title={quarkUrl ? "打开夸克网盘分享" : "链接待补充"}
|
||||
>
|
||||
<span className={styles.iconColorQuark} aria-hidden="true">
|
||||
<DownloadIcon />
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{modal && (
|
||||
<div
|
||||
className={styles.modalOverlay}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="分享链接弹窗"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) setModal(null);
|
||||
}}
|
||||
>
|
||||
<div className={styles.modal}>
|
||||
<div className={styles.modalHeader}>
|
||||
<div className={styles.modalTitleRow}>
|
||||
<span className={styles.modalIcon} aria-hidden="true">
|
||||
<DownloadIcon />
|
||||
</span>
|
||||
<div className={styles.modalTitle}>{modal.resource.title}</div>
|
||||
</div>
|
||||
<button type="button" className={styles.modalCloseBtn} onClick={() => setModal(null)} aria-label="关闭">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M18 6 6 18" />
|
||||
<path d="M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={styles.modalBody}>
|
||||
<div className={styles.modalPre} aria-label="网盘分享内容">
|
||||
{buildCopyText(modal.resource, modal.link)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.modalActions}>
|
||||
<Copyable
|
||||
text={buildCopyText(modal.resource, modal.link)}
|
||||
className={styles.modalCopyBtn}
|
||||
>
|
||||
复制
|
||||
</Copyable>
|
||||
|
||||
{modal.link.url ? (
|
||||
<Link
|
||||
className={styles.modalOpenBtn}
|
||||
href={modal.link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="打开分享链接"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M14 3h7v7" />
|
||||
<path d="M10 14L21 3" />
|
||||
<path d="M21 14v7H3V3h7" />
|
||||
</svg>
|
||||
</Link>
|
||||
) : (
|
||||
<span className={`${styles.modalOpenBtn} ${styles.modalOpenBtnDisabled}`} aria-disabled="true">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M14 3h7v7" />
|
||||
<path d="M10 14L21 3" />
|
||||
<path d="M21 14v7H3V3h7" />
|
||||
</svg>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
36
app/vip/components/ThemeToggle.tsx
Normal file
36
app/vip/components/ThemeToggle.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "../providers/ThemeProvider";
|
||||
|
||||
const SunIcon = () => (
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
const MoonIcon = () => (
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
|
||||
const toggle = () => {
|
||||
setTheme(resolvedTheme === "dark" ? "light" : "dark");
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
className="flex items-center justify-center rounded-full p-2 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
|
||||
aria-label={resolvedTheme === "dark" ? "切换至日间模式" : "切换至夜间模式"}
|
||||
title={resolvedTheme === "dark" ? "日间" : "夜间"}
|
||||
>
|
||||
{resolvedTheme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
294
app/vip/components/content/EbookViewer.module.css
Normal file
294
app/vip/components/content/EbookViewer.module.css
Normal file
@ -0,0 +1,294 @@
|
||||
/* 电子书阅读器 - 支持深色主题,可复用到 digital/nomadvip/nomadlms */
|
||||
|
||||
.readingProgress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, var(--accent) 0%, #00f2fe 100%);
|
||||
z-index: 201;
|
||||
transition: width 0.15s linear;
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
|
||||
.readingTime {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: var(--muted-foreground);
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.headerSpacer {
|
||||
width: 100%;
|
||||
height: 88px;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
height: 88px;
|
||||
background: var(--card);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.headerLeft {
|
||||
width: 100px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.headerLeft:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.headerMiddle {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.headerRight {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
margin-right: 8px;
|
||||
background: var(--accent-muted, rgba(245, 158, 11, 0.15));
|
||||
border-radius: 50%;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.headerRight:hover {
|
||||
background: var(--accent-muted, rgba(245, 158, 11, 0.25));
|
||||
}
|
||||
|
||||
.headerRightActive {
|
||||
background: var(--accent) !important;
|
||||
color: var(--accent-foreground) !important;
|
||||
}
|
||||
|
||||
.headerRightText {
|
||||
display: none;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.chunkEnter {
|
||||
animation: chunkAppear 0.5s ease-out both;
|
||||
}
|
||||
|
||||
@keyframes chunkAppear {
|
||||
from { opacity: 0; transform: translateY(20px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.chunkPlaceholder {
|
||||
background: var(--muted);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.8s ease infinite;
|
||||
border-radius: 12px;
|
||||
margin: 24px 0;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.backToTop {
|
||||
position: fixed;
|
||||
bottom: 120px;
|
||||
right: 30px;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
background: var(--card);
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
cursor: pointer;
|
||||
z-index: 50;
|
||||
color: var(--accent);
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.backToTop:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.book {
|
||||
padding: 30px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.markdownBody {
|
||||
font-size: 16px !important;
|
||||
line-height: 1.85 !important;
|
||||
color: var(--foreground) !important;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 24px !important;
|
||||
font-weight: 800;
|
||||
color: var(--foreground);
|
||||
margin: 28px 0 10px;
|
||||
}
|
||||
|
||||
.markdownBody h1::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 40px;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, var(--accent), #00f2fe);
|
||||
border-radius: 3px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 21px !important;
|
||||
font-weight: 700;
|
||||
color: var(--foreground);
|
||||
margin: 22px 0 9px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.markdownBody h3 { font-size: 18px !important; font-weight: 600; margin: 18px 0 7px; }
|
||||
.markdownBody h4, .markdownBody h5, .markdownBody h6 { font-size: 16px !important; margin: 14px 0 6px; }
|
||||
.markdownBody p { font-size: 16px !important; margin-bottom: 10px; line-height: 1.9; }
|
||||
|
||||
.markdownBody blockquote {
|
||||
margin: 28px 0;
|
||||
padding: 20px 24px 20px 30px;
|
||||
background: var(--muted);
|
||||
border-radius: 0 12px 12px 0;
|
||||
color: var(--muted-foreground);
|
||||
border-left: 4px solid var(--accent);
|
||||
}
|
||||
|
||||
.markdownBody pre {
|
||||
margin: 28px 0;
|
||||
padding: 28px 24px;
|
||||
background: var(--background);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.markdownBody pre code {
|
||||
font-family: var(--font-geist-mono), monospace;
|
||||
font-size: 13px !important;
|
||||
color: var(--foreground);
|
||||
background: none !important;
|
||||
}
|
||||
|
||||
.markdownBody code {
|
||||
font-family: var(--font-geist-mono), monospace;
|
||||
font-size: 14px !important;
|
||||
padding: 2px 6px;
|
||||
background: var(--muted);
|
||||
color: var(--accent);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.markdownBody a { color: var(--accent); }
|
||||
.markdownBody a:hover { text-decoration: underline; }
|
||||
.markdownBody img { display: block; margin: 28px auto; max-width: 100%; border-radius: 8px; }
|
||||
.markdownBody ul, .markdownBody ol { margin: 16px 0; padding-left: 40px; }
|
||||
.markdownBody table { width: 100%; margin: 28px 0; border-collapse: collapse; border-radius: 8px; }
|
||||
.markdownBody th { background: var(--muted); font-weight: 600; padding: 16px 20px; border: 1px solid var(--border); }
|
||||
.markdownBody td { padding: 14px 20px; border: 1px solid var(--border); }
|
||||
|
||||
.drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 280px;
|
||||
max-width: 85vw;
|
||||
background: var(--card);
|
||||
border-left: 1px solid var(--border);
|
||||
box-shadow: -4px 0 24px rgba(0, 0, 0, 0.15);
|
||||
z-index: 150;
|
||||
padding-top: 88px;
|
||||
overflow-y: auto;
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerOpen { transform: translateX(0); }
|
||||
|
||||
.drawerMask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
z-index: 140;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerMaskOpen {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.drawerItem {
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
font-size: 15px;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.drawerItem:hover {
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.headerSpacer { height: 56px; }
|
||||
.header { height: 56px; }
|
||||
.progressBar { top: 56px; }
|
||||
.headerMiddle { font-size: 18px; }
|
||||
.headerRight {
|
||||
width: auto;
|
||||
height: 34px;
|
||||
padding: 0 14px;
|
||||
margin-right: 16px;
|
||||
border-radius: 17px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.headerRightText { display: inline; }
|
||||
.book { padding: 30px 60px; }
|
||||
.markdownBody { max-width: 800px; margin: 0 auto; }
|
||||
.markdownBody h1 { font-size: 28px !important; }
|
||||
.markdownBody h2 { font-size: 23px !important; }
|
||||
.drawer { padding-top: 56px; width: 300px; }
|
||||
.backToTop { width: 44px; height: 44px; bottom: 40px; right: 40px; }
|
||||
}
|
||||
200
app/vip/components/content/EbookViewer.tsx
Normal file
200
app/vip/components/content/EbookViewer.tsx
Normal file
@ -0,0 +1,200 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useRef, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import type { EbookData } from "@vip/lib/content/ebook";
|
||||
import type { EbookConfig } from "@vip/lib/content/config";
|
||||
import "github-markdown-css/github-markdown.css";
|
||||
import styles from "./EbookViewer.module.css";
|
||||
|
||||
function LazyChunk({
|
||||
html,
|
||||
estimatedHeight,
|
||||
forceVisible,
|
||||
}: {
|
||||
html: string;
|
||||
estimatedHeight: number;
|
||||
forceVisible: boolean;
|
||||
}) {
|
||||
const [visible, setVisible] = useState(forceVisible);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const show = forceVisible || visible;
|
||||
|
||||
useEffect(() => {
|
||||
if (forceVisible || visible) return;
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setVisible(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: "1200px 0px" }
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [forceVisible, visible]);
|
||||
|
||||
if (show) {
|
||||
return (
|
||||
<div
|
||||
className={`${styles.chunkEnter} animate__animated animate__fadeInUp`}
|
||||
style={{ animationDuration: "0.5s", animationFillMode: "both" }}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div ref={ref} className={styles.chunkPlaceholder} style={{ minHeight: estimatedHeight }} />
|
||||
);
|
||||
}
|
||||
|
||||
type EbookViewerProps = {
|
||||
data: EbookData;
|
||||
config: EbookConfig;
|
||||
};
|
||||
|
||||
export function EbookViewer({ data, config }: EbookViewerProps) {
|
||||
const [showDrawer, setShowDrawer] = useState(false);
|
||||
const [readProgress, setReadProgress] = useState(0);
|
||||
const [showBackTop, setShowBackTop] = useState(false);
|
||||
const [forceShowAll, setForceShowAll] = useState(false);
|
||||
const [readingTimeLeft, setReadingTimeLeft] = useState<number | null>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { chunks, headers } = data;
|
||||
const estimatedMin = config.estimatedMinutes ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
let ticking = false;
|
||||
const onScroll = () => {
|
||||
if (ticking) return;
|
||||
ticking = true;
|
||||
requestAnimationFrame(() => {
|
||||
const scrollTop = window.scrollY || document.documentElement.scrollTop;
|
||||
const docHeight = document.documentElement.scrollHeight - window.innerHeight;
|
||||
setReadProgress(docHeight > 0 ? Math.min(100, (scrollTop / docHeight) * 100) : 0);
|
||||
setShowBackTop(scrollTop > 600);
|
||||
if (estimatedMin && docHeight > 0) {
|
||||
const remaining = Math.max(0, estimatedMin * (1 - scrollTop / docHeight));
|
||||
setReadingTimeLeft(Math.ceil(remaining));
|
||||
}
|
||||
ticking = false;
|
||||
});
|
||||
};
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => window.removeEventListener("scroll", onScroll);
|
||||
}, [estimatedMin]);
|
||||
|
||||
const handleJump = useCallback((index: number) => {
|
||||
setForceShowAll(true);
|
||||
setShowDrawer(false);
|
||||
const run = () => {
|
||||
const root = contentRef.current;
|
||||
if (!root) return;
|
||||
const h1s = root.querySelectorAll("h1");
|
||||
const h2s = root.querySelectorAll("h2");
|
||||
const targets = h1s.length > 0 ? h1s : h2s;
|
||||
const el = targets[index] as HTMLElement;
|
||||
if (el) {
|
||||
try {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
} catch {
|
||||
const top =
|
||||
el.getBoundingClientRect().top +
|
||||
(window.pageYOffset || document.documentElement.scrollTop) -
|
||||
60;
|
||||
window.scrollTo({ top: Math.max(0, top), behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
run();
|
||||
setTimeout(run, 100);
|
||||
setTimeout(run, 300);
|
||||
setTimeout(run, 600);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={styles.readingProgress} style={{ width: `${readProgress}%` }} />
|
||||
|
||||
<div className={styles.headerSpacer} />
|
||||
<header className={`${styles.header} animate__animated animate__fadeInDown`} style={{ animationFillMode: "both" }}>
|
||||
<Link href={config.backHref} className={styles.headerLeft} aria-label="返回">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
</Link>
|
||||
<div className={styles.headerMiddle}>
|
||||
{config.title}
|
||||
{readingTimeLeft !== null && readingTimeLeft > 0 && (
|
||||
<span className={styles.readingTime}> · 约 {readingTimeLeft} 分钟</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.headerRight} ${showDrawer ? styles.headerRightActive : ""}`}
|
||||
onClick={() => setShowDrawer(!showDrawer)}
|
||||
aria-label="目录"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
<span className={styles.headerRightText}>目录</span>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className={styles.book}>
|
||||
<div ref={contentRef} className={`markdown-body ${styles.markdownBody}`}>
|
||||
{chunks.map((chunk, i) => (
|
||||
<LazyChunk
|
||||
key={i}
|
||||
html={chunk.html}
|
||||
estimatedHeight={chunk.estimatedHeight}
|
||||
forceVisible={forceShowAll || i === 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`${styles.drawerMask} ${showDrawer ? styles.drawerMaskOpen : ""}`}
|
||||
onClick={() => setShowDrawer(false)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<aside className={`${styles.drawer} ${showDrawer ? styles.drawerOpen : ""}`}>
|
||||
{headers.map((titleItem, index) => (
|
||||
<div
|
||||
key={index}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={styles.drawerItem}
|
||||
onClick={() => handleJump(index)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") handleJump(index);
|
||||
}}
|
||||
>
|
||||
{titleItem}
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
{showBackTop && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.backToTop}
|
||||
onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
|
||||
aria-label="回到顶部"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M18 15l-6-6-6 6" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
151
app/vip/components/content/LessonLayout.tsx
Normal file
151
app/vip/components/content/LessonLayout.tsx
Normal file
@ -0,0 +1,151 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { CourseConfig } from "@vip/lib/content/config";
|
||||
|
||||
type LessonLayoutProps = {
|
||||
courseConfig: CourseConfig;
|
||||
moduleIndex: number;
|
||||
lessonIndex: number;
|
||||
lessonName: string;
|
||||
lessonDuration: string;
|
||||
isFreeTrial: boolean;
|
||||
unlocked: boolean;
|
||||
totalLessons: number;
|
||||
completedCount: number;
|
||||
prevLesson: { moduleIndex: number; lessonIndex: number } | null;
|
||||
nextLesson: { moduleIndex: number; lessonIndex: number } | null;
|
||||
courseHomeHref: string;
|
||||
payHref: string;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export function LessonLayout({
|
||||
courseConfig,
|
||||
moduleIndex,
|
||||
lessonIndex,
|
||||
lessonName,
|
||||
lessonDuration,
|
||||
isFreeTrial,
|
||||
unlocked,
|
||||
totalLessons,
|
||||
completedCount,
|
||||
prevLesson,
|
||||
nextLesson,
|
||||
courseHomeHref,
|
||||
payHref,
|
||||
children,
|
||||
}: LessonLayoutProps) {
|
||||
const router = useRouter();
|
||||
const courseBase = courseHomeHref.replace(/\/$/, "");
|
||||
const lessonBase = courseBase.includes("/course") ? courseBase : `${courseBase}/course`;
|
||||
const progressPercent = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (e.target && (e.target as HTMLElement).tagName === "INPUT") return;
|
||||
if (e.key === "ArrowLeft" && prevLesson) {
|
||||
router.push(`${lessonBase}/${prevLesson.moduleIndex}/${prevLesson.lessonIndex}`);
|
||||
} else if (e.key === "ArrowRight" && nextLesson) {
|
||||
router.push(`${lessonBase}/${nextLesson.moduleIndex}/${nextLesson.lessonIndex}`);
|
||||
}
|
||||
},
|
||||
[prevLesson, nextLesson, lessonBase, router]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [handleKeyDown]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<main className="pt-14 pb-16 md:pt-16">
|
||||
<div className="mx-auto max-w-4xl px-4 sm:px-6">
|
||||
{/* 进度条 */}
|
||||
<div className="mb-6">
|
||||
<div className="flex justify-between text-xs text-[var(--muted-foreground)] mb-1">
|
||||
<span>学习进度</span>
|
||||
<span>{completedCount}/{totalLessons} 节 · {progressPercent}%</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-[var(--muted)]">
|
||||
<div
|
||||
className="h-full rounded-full bg-[var(--accent)] transition-all duration-300"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 导航 */}
|
||||
<nav className="mb-6 flex items-center gap-2 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.back()}
|
||||
className="flex items-center gap-1 text-[var(--muted-foreground)] transition hover:text-[var(--foreground)]"
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
返回
|
||||
</button>
|
||||
<span className="text-[var(--muted-foreground)]">/</span>
|
||||
<Link href={courseHomeHref} className="text-[var(--muted-foreground)] transition hover:text-[var(--foreground)]">
|
||||
课程首页
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
{/* 标题 */}
|
||||
<h1 className="mb-2 flex items-center gap-2 text-xl font-bold sm:text-2xl md:text-3xl">
|
||||
{lessonName}
|
||||
{isFreeTrial && (
|
||||
<span className="rounded bg-[var(--accent)]/20 px-2 py-0.5 text-sm font-normal text-[var(--accent)]">
|
||||
试看
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="mb-8 text-sm text-[var(--muted-foreground)]">时长 {lessonDuration}</p>
|
||||
|
||||
{/* 内容区 */}
|
||||
{children}
|
||||
|
||||
{/* 上/下一节 */}
|
||||
<div className="mt-12 flex flex-col gap-3 sm:flex-row sm:justify-between">
|
||||
{prevLesson ? (
|
||||
<Link
|
||||
href={`${courseBase}/course/${prevLesson.moduleIndex}/${prevLesson.lessonIndex}`}
|
||||
className="flex items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm font-medium transition hover:border-[var(--accent)]/50"
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
上一节
|
||||
</Link>
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
{nextLesson ? (
|
||||
<Link
|
||||
href={`${courseBase}/course/${nextLesson.moduleIndex}/${nextLesson.lessonIndex}`}
|
||||
className="flex items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm font-medium transition hover:border-[var(--accent)]/50 ml-auto"
|
||||
>
|
||||
下一节
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href={courseHomeHref}
|
||||
className="flex items-center gap-2 rounded-xl bg-[var(--accent)] px-4 py-3 text-sm font-medium text-[var(--accent-foreground)] transition hover:opacity-90 ml-auto"
|
||||
>
|
||||
返回课程首页
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
64
app/vip/config/netdisk-downloads.ts
Normal file
64
app/vip/config/netdisk-downloads.ts
Normal file
@ -0,0 +1,64 @@
|
||||
export type NetdiskProvider = "baidu" | "quark";
|
||||
|
||||
export type NetdiskLink = {
|
||||
provider: NetdiskProvider;
|
||||
label: string;
|
||||
url?: string;
|
||||
codeLabel?: string;
|
||||
code?: string;
|
||||
/**
|
||||
* 弹窗内“一键复制”的整段内容(用于网盘 App 识别/导入)。
|
||||
* 为空时会回退到 title + url + code 的组合文案。
|
||||
*/
|
||||
copyText?: string;
|
||||
};
|
||||
|
||||
export type NetdiskResource = {
|
||||
id: string;
|
||||
title: string;
|
||||
desc: string;
|
||||
tags: string[];
|
||||
links: NetdiskLink[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 首页「网盘下载」模块配置(独立于现有业务/课程/电子书)
|
||||
* - 你后续只需要把 url / code 填完整即可
|
||||
*/
|
||||
export const NETDISK_RESOURCES: NetdiskResource[] = [
|
||||
{
|
||||
id: "system-firmware",
|
||||
title: "系统固件(镜像/驱动/依赖包)",
|
||||
desc: "系统镜像、固件与驱动相关资源,适合装机/刷机/修复。",
|
||||
tags: ["系统固件", "镜像", "驱动"],
|
||||
links: [
|
||||
{
|
||||
provider: "quark",
|
||||
label: "夸克网盘",
|
||||
url: "https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV",
|
||||
codeLabel: "提取码",
|
||||
code: "PLgV",
|
||||
copyText:
|
||||
"我用夸克网盘给你分享了「r3s-armbian-ubuntu.7z」,点击链接或复制整段内容,打开「夸克APP」即可获取。\n/~4adf3Xsf3S~:/\n链接:https://pan.quark.cn/s/3c8439859b8b?pwd=PLgV\n提取码:PLgV",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "software-tools",
|
||||
title: "软件工具(常用安装包)",
|
||||
desc: "常用软件与安装包合集(例如刷机/写盘/远控/解压等)。",
|
||||
tags: ["软件", "安装包", "合集"],
|
||||
links: [
|
||||
{
|
||||
provider: "quark",
|
||||
label: "夸克网盘",
|
||||
url: "https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD",
|
||||
codeLabel: "提取码",
|
||||
code: "dLwD",
|
||||
copyText:
|
||||
"我用夸克网盘给你分享了「无人直播助手 1.0.1.exe.zip」,点击链接或复制整段内容,打开「夸克APP」即可获取。\n/b43c3XtQ8y:/\n链接:https://pan.quark.cn/s/f46a37ac3937?pwd=dLwD\n提取码:dLwD",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
754
app/vip/data/cloudphone.md
Normal file
754
app/vip/data/cloudphone.md
Normal file
@ -0,0 +1,754 @@
|
||||
# 无人直播教程
|
||||
|
||||
2016年1月14日更新
|
||||
|
||||
## Youtube直播
|
||||
|
||||
首先推荐arm开发板 [香橙派4pro](http://www.orangepi.cn/html/hardWare/computerAndMicrocontrollers/details/Orange-Pi-4-Pro.html) ,4gb版本 260元左右
|
||||
|
||||
可以使用技术栈实现无人直播
|
||||
|
||||
- [shellcrash](https://github.com/juewuy/ShellCrash)
|
||||
|
||||
- python+ffmpeg (实时转播)
|
||||
|
||||
- [docker-chrome浏览器 ](https://github.com/m1k1o/neko)+ (油猴脚本外挂[auto dismiss](https://greasyfork.org/zh-CN/scripts/557378-youtube-studio-auto-dismiss))
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 刷linux系统
|
||||
|
||||
准备`TF 卡`一张,建议64gb
|
||||
|
||||
买一个usb3.0的`读卡器`
|
||||
|
||||
在官方网站的百度网盘下载 `ubuntu server` 操作系统
|
||||
|
||||
在电脑下载软件` balenaEtcher`
|
||||
|
||||
<img title="" src="https://minioweb.hackrobot.cn/hackrobot/20260114234337_20260114_234355_341.png" alt="20260114234337_20260114_234355_341.png" width="435">
|
||||
|
||||
把系统镜像,刷写到TF 后,
|
||||
|
||||
开发板插网线,插电,就可以ssh登录了,账号密码 `orangepi`
|
||||
|
||||
```
|
||||
ssh orangepi@开发板ip地址
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## shellcrash
|
||||
|
||||

|
||||
|
||||
shellcrash可以看作`飞机`,加油之后科学上网才能飞往美国(全球其他国家)
|
||||
|
||||
加油步骤
|
||||
|
||||
- 去[nomadro.com](https://nomadro.com/),买vps服务器 和 静态住宅ip
|
||||
|
||||
- 谷歌搜索 [八合一](https://github.com/mack-a/v2ray-agent)`一键脚本`
|
||||
|
||||
进入香橙派系统后,复制一下命令并回车
|
||||
|
||||
```
|
||||
export url='https://testingcf.jsdelivr.net/gh/juewuy/ShellCrash@master' \
|
||||
&& wget -q --no-check-certificate -O /tmp/install.sh $url/install.sh \
|
||||
&& bash /tmp/install.sh \
|
||||
&& . /etc/profile &> /dev/null
|
||||
```
|
||||
|
||||
按照提示,进行安装
|
||||
|
||||
---
|
||||
|
||||
## chrome浏览器
|
||||
|
||||
在电脑的浏览器,可以实时打开开发板里面的docker容器浏览器
|
||||
|
||||

|
||||
|
||||
> 数据持久化
|
||||
|
||||
```
|
||||
mkdir -p ~/neko-chromium-profile
|
||||
chown -R 1000:1000 ~/neko-chromium-profile
|
||||
```
|
||||
|
||||
> 自定义策略
|
||||
|
||||
让浏览器可以运行外挂脚本
|
||||
|
||||
```
|
||||
mkdir -p ~/neko-policies/managed
|
||||
chown -R 1000:1000 ~/neko-policies
|
||||
```
|
||||
|
||||
写入配置文件
|
||||
|
||||
```
|
||||
cat <<EOF > ~/neko-policies/managed/policies.json
|
||||
{
|
||||
"ExtensionInstallForcelist": [
|
||||
"dhdgffkkebhmkfjojejmpbldmpobfkfo;https://clients2.google.com/service/update2/crx"
|
||||
],
|
||||
"ExtensionInstallAllowlist": [
|
||||
"*"
|
||||
],
|
||||
"ExtensionInstallBlocklist": [],
|
||||
"DownloadRestrictions": 0,
|
||||
"AllowFileSelectionDialogs": true,
|
||||
"URLAllowlist": ["file:///home/neko/Downloads/*"],
|
||||
"DefaultCookiesSetting": 4,
|
||||
"RestoreOnStartup": 4,
|
||||
"RestoreOnStartupURLs": ["https://nomadro.com"]
|
||||
}
|
||||
EOF
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# 前言
|
||||
|
||||
## 🚀 数字游民:地理套利与自动化杠杆
|
||||
> 低成本工作室
|
||||
|
||||
自建`云手机`集群,实现tiktok无人直播,youtube运营自动化,以及saas开发(web3)
|
||||
|
||||

|
||||
|
||||
> 📱系统安装
|
||||
|
||||
- 开源硬件选择 (百元级),
|
||||
|
||||
- 刷入安卓系统(Android)
|
||||
|
||||
- 获取root权限(magisk面具)
|
||||
|
||||
- lsposed环境 (xposed外挂模块)
|
||||
|
||||
- 谷歌框架
|
||||
|
||||
> 🚫风控设置
|
||||
|
||||
- 机型参数修改
|
||||
|
||||
- 静态住宅ip (链式代理)
|
||||
|
||||
- gps定位 (fake location)
|
||||
|
||||
- 权限控制
|
||||
|
||||
- 安卓虚拟机 (多开系统)
|
||||
|
||||
> 💻远程控制
|
||||
|
||||
- frp内网穿透
|
||||
|
||||
- scrcpy (adb远控)
|
||||
|
||||
- qscrcpy(群控)
|
||||
|
||||
> 💰应用场景
|
||||
|
||||
- 无人直播
|
||||
|
||||
- RPA自动化
|
||||
|
||||
- 聊天机器人
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 视频教程
|
||||
|
||||
> 百度网盘下载
|
||||
|
||||
```
|
||||
链接: https://pan.baidu.com/s/1DFsdtgL-pvQt22U4MNXjHg?pwd=call
|
||||
|
||||
提取码: call
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 硬件选择
|
||||
|
||||
> 百元级开发板
|
||||
|
||||
rk3576芯片的开发,是目前性价比较高的选择
|
||||
|
||||
`nanopiM5`的 4gb 399
|
||||
|
||||
ps: radxa A7A 的7gb版本只要 280左右
|
||||
|
||||
但是 A7A 的系统root需要编译内核源码,且没有谷歌框架
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/M5_01-900x630.jpg" title="" alt="M5_01-900x630.jpg" width="360">
|
||||
|
||||
M5相比较4D有以下区别
|
||||
|
||||
- 支持M2 ssd固态硬盘
|
||||
|
||||
- 双网口,可以做软路由openwrt
|
||||
|
||||
- 安卓镜像默认支持谷歌框架
|
||||
|
||||
为什么不选择 二手手机,或者 主板机
|
||||
|
||||
二手手机不是标准品,型号和系统都是定制的,解锁BL越来越难
|
||||
|
||||
国内基本已经不开放,不可拆卸的电池,会因发热造成巨大的安全隐患
|
||||
|
||||
主板机,一般是成套出售,动辄几千元,适合有规模化业务的"商家"
|
||||
|
||||
而开发板,属于开源硬件, AOSP安卓属于开源系统,方便购买和定制化
|
||||
|
||||
综合来说,推荐nanopiM5
|
||||
|
||||
官方文档地址
|
||||
|
||||
https://wiki.friendlyelec.com/wiki/index.php/NanoPi_M5/zh
|
||||
|
||||
系统固件下载地址
|
||||
|
||||
https://wiki.friendlyelec.com/wiki/index.php/NanoPi_M5/zh#.E4.B8.8B.E8.BD.BD.E5.9B.BA.E4.BB.B6
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919083929.png" title="" alt="20250919083929.png" width="257">
|
||||
|
||||
> 刷入安卓系统
|
||||
|
||||
目前基本用tf卡可以直接刷入img镜像文件
|
||||
|
||||
使用`Balena Etcher`软件,windows/mac系统都可以使用
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025_30qwrfqwrfqr….png" title="" alt="2025_30qwrfqwrfqr….png" width="361">
|
||||
|
||||
tf卡读取,最好购买一个`SD/TF读写器`,插入电脑主机的usb即可
|
||||
|
||||
刷入img文件后
|
||||
|
||||
将开发板,插电开机,并接入网线
|
||||
|
||||
建议购买开发板时,一并购买支持蓝牙wifi的配件
|
||||
|
||||
这样可以设置无线连接
|
||||
|
||||
### 配件清单
|
||||
|
||||
- 双头usb: 有线调试
|
||||
|
||||
- TF卡 64gb+ USB3.0读卡器:刷安卓系统
|
||||
|
||||
- 电源typec
|
||||
|
||||
- wifi模块:建议有,可以无线adb远控
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-07-29 08_20_41-Phone-192.168.31.184_5557.png" title="" alt="2025-07-29 08_20_41-Phone-192.168.31.184_5557.png" width="207">
|
||||
|
||||
> 如果需要直播
|
||||
|
||||
- linux辅助板 `nanopiR3S`
|
||||
|
||||
- 视频采集卡
|
||||
|
||||
- HDMI线
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-25 16_13_58-.png" title="" alt="2025-08-25 16_13_58-.png" width="312">
|
||||
|
||||
M5只有2个usb接口(上/下)
|
||||
|
||||
- usb-上, 接入双头usb,另一头插电脑usb
|
||||
|
||||
- usb下- 接才 视频采集卡的usb
|
||||
|
||||
直播的原理,就是把 视频信号,通过hdmi=>视频采集卡=>M5安卓usb(下)
|
||||
|
||||
---
|
||||
|
||||
> 获取root权限
|
||||
|
||||

|
||||
|
||||
安卓的系统的优势在于开放性
|
||||
|
||||
但是商业手机,都限制了bl锁,以及内置电池
|
||||
|
||||
让系统失去了可玩性
|
||||
|
||||
通过tF卡刷入的aosp安卓镜像, 可以用工具 读取出boot.img
|
||||
|
||||
- 在安卓系统下载magisk.apk安装
|
||||
|
||||
https://minioweb.hackrobot.cn/hackrobot/magiskdelta.apk
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/wtwtwetwetwetwtwetwetwetet.jpg" title="" alt="wtwtwetwetwetwtwetwetwetet.jpg" width="114">
|
||||
|
||||
用magisk修复boot.img, 比如生成magiskboot.img
|
||||
|
||||
> boot.img
|
||||
|
||||
直接把M5的安卓镜像解压,就可以看到
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919133758.png" title="" alt="20250919133758.png" width="359">
|
||||
|
||||
解压后看到
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919133938.png" title="" alt="20250919133938.png" width="343">
|
||||
|
||||
然后用磁盘管理工具,将magiskboot.img 刷入系统
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-07-29 08_23_10-Phone-192.168.31.184_5557.png" title="" alt="2025-07-29 08_23_10-Phone-192.168.31.184_5557.png" width="201">
|
||||
|
||||
或者在电脑使用adb shell的dd
|
||||
|
||||
```
|
||||
adb shell
|
||||
su
|
||||
dd if=/sdcard/magisk_patched.img of=/dev/block/mmcblk0p9 bs=4M
|
||||
```
|
||||
|
||||
重启
|
||||
|
||||
```
|
||||
sync
|
||||
reboot
|
||||
```
|
||||
|
||||
重启后,就有了root权限
|
||||
|
||||
开发板的aosp安卓完全`不必申请解锁bl`
|
||||
|
||||
ps: 详细操作,可以参考视频教程演示
|
||||
|
||||
---
|
||||
|
||||
> 安装lsposed环境
|
||||
|
||||
lsposed是xposed外挂模块的环境
|
||||
|
||||
下载zip安装包:
|
||||
|
||||
https://github.com/LSPosed/LSPosed/releases/download/v1.9.2/LSPosed-v1.9.2-7024-zygisk-release.zip
|
||||
|
||||
在magisk软件里, 点击 设置, 刷入即可
|
||||
|
||||
重启后,即可进入lsposed
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/lsposeddd.png" title="" alt="lsposeddd.png" width="263">
|
||||
|
||||
---
|
||||
|
||||
# 魔法上网
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-25 23_23_08-Pixel 7 Pro.png" title="" alt="2025-08-25 23_23_08-Pixel 7 Pro.png" width="189">
|
||||
|
||||
> vps服务器
|
||||
|
||||
如果想要出海浏览
|
||||
|
||||
只需要买一台海外的vps服务器,比如 [vultr](https://www.vultr.com/?ref=8985003),每月5$
|
||||
|
||||
> 静态住宅ip
|
||||
|
||||
但是如果想做业务,赚美金
|
||||
|
||||
一定需要`静态住宅ip`,来避免风控,
|
||||
|
||||
可以在[proxycheap](https://app.proxy-cheap.com/r/bmcMoY),3$/月
|
||||
|
||||
> 域名
|
||||
|
||||
即时不搭建网站,关于魔法线路,也需要配置域名
|
||||
|
||||
可以在[namesilo](https://www.namesilo.com) 购买
|
||||
|
||||
把dns,交给[cloudflare](https://cloudflare.com)托管
|
||||
|
||||
### 链式代理
|
||||
|
||||
> 中转线路+落地节点
|
||||
|
||||
为什么一定要中转?
|
||||
|
||||
因为便宜的静态住宅ip一般只提供`http/socks`连接
|
||||
|
||||
在国内是绝对无法直连的
|
||||
|
||||
但是通过中国国家的服务器,链式代理,到目标国家落地
|
||||
|
||||
就可以避免风控
|
||||
|
||||
建议使用clash meta,文档- [虚空终端](https://wiki.metacubex.one)
|
||||
|
||||
### 操作步骤
|
||||
|
||||
- 1.买vps服务器
|
||||
|
||||
- 2.买域名
|
||||
|
||||
- 3.买静态住宅ip
|
||||
|
||||
- 4.服务器部署中转脚本: [八合一脚本](https://github.com/mack-a/v2ray-agent),建议Hysteria2协议
|
||||
|
||||
- 5.在任何设备,使用`clash meta`,配置yaml信息: vps中转+静态ip
|
||||
|
||||
- 6.clash`链式代理`: `dialer-proxy`
|
||||
|
||||
提示: 目前在云手机测试,代理api并没有过tiktok风控,建议从`软路由`测试
|
||||
|
||||
软路由系统是`openwrt`
|
||||
|
||||
可以买nanopi双网口开发板进行配置,比如`R2S`
|
||||
|
||||

|
||||
|
||||
> 注意📣
|
||||
|
||||
实际测试中,开发板的aosp的代理apk,并不能过tiktok的风控
|
||||
|
||||
`目前稳定的方案还是软路由`
|
||||
|
||||
如下图所示,非软路由=>红窗风控
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-19 01_33_37-Phone-192.168.31.79_5555.png" title="" alt="2025-08-19 01_33_37-Phone-192.168.31.79_5555.png" width="172">
|
||||
|
||||
---
|
||||
|
||||
# 修改机型
|
||||
|
||||
> 爱玩机工具箱
|
||||
|
||||
apk下载地址:
|
||||
https://minioweb.hackrobot.cn/hackrobot/IWanSetting-com.byyoung.setting-S-22.0.9.9.apk
|
||||
|
||||
> 主界面
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-19 21_51_33-Phone-e03d27478bc6d71e.png" title="" alt="2025-08-19 21_51_33-Phone-e03d27478bc6d71e.png" width="222">
|
||||
|
||||
> 选择-设备信息伪装
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919134709.png" title="" alt="20250919134709.png" width="232">
|
||||
|
||||
> 选择机型-重启
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-19 21_51_45-Phone-e03d27478bc6d71e.png" title="" alt="2025-08-19 21_51_45-Phone-e03d27478bc6d71e.png" width="220">
|
||||
|
||||
---
|
||||
|
||||
# GPS定位
|
||||
|
||||
> gps与ip不一致,容易风控
|
||||
|
||||
fakelocation下载地址:
|
||||
|
||||
http://fakeloc.cc/app
|
||||
|
||||
该软件是收费软件,自行斟酌
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919134951.png" title="" alt="20250919134951.png" width="155">
|
||||
|
||||
> 使用教程
|
||||
|
||||
选择 通过 谷歌/百度/高德 地图,搜索地名定位
|
||||
|
||||
手动确认浮标
|
||||
|
||||
点击 `start mock`就可以
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-25 15_00_17-Pixel 7 Pro.png" title="" alt="2025-08-25 15_00_17-Pixel 7 Pro.png" width="321">
|
||||
|
||||
---
|
||||
|
||||
# 远程控制
|
||||
|
||||
> qtscrcpy
|
||||
|
||||
通过路由器后台网址,可以看到安卓开发板的ip地址
|
||||
|
||||
在电脑下载qtscrcpy软件
|
||||
|
||||
https://github.com/barry-ran/QtScrcpy
|
||||
|
||||
通过adb连接手机
|
||||
|
||||
```
|
||||
adb connect 安卓ip:5555
|
||||
```
|
||||
|
||||
就可以控制安卓了
|
||||
|
||||

|
||||
|
||||
> escrcpy
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-19 10_45_58-.png" title="" alt="2025-08-19 10_45_58-.png" width="498">
|
||||
|
||||
---
|
||||
|
||||
## 内网穿透:frp
|
||||
|
||||
> 开源的frp
|
||||
|
||||
比如手写配置的frp,我更推荐`frp panel`
|
||||
|
||||
可视化wen管理,下载地址
|
||||
|
||||
https://github.com/VaalaCat/frp-panel
|
||||
|
||||
中文文档
|
||||
|
||||
https://vaala.cat/frp-panel
|
||||
|
||||

|
||||
|
||||
> ps: 建议购买 `腾讯云轻量服务器`
|
||||
|
||||
首先创建一个`docker-compose.yaml`文件,写入以下内容
|
||||
|
||||
```
|
||||
services:
|
||||
frpp-master:
|
||||
image: vaalacat/frp-panel:latest
|
||||
network_mode: host
|
||||
environment:
|
||||
APP_GLOBAL_SECRET: your_secret
|
||||
MASTER_RPC_HOST: 1.2.3.4 #服务器的外部IP或域名
|
||||
MASTER_RPC_PORT: 9001
|
||||
MASTER_API_HOST: 1.2.3.4 #服务器的外部IP或域名
|
||||
MASTER_API_PORT: 9000
|
||||
MASTER_API_SCHEME: http
|
||||
volumes:
|
||||
- ./data:/data # 数据存储位置
|
||||
restart: unless-stopped
|
||||
command: master
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 应用多开/ 系统多开
|
||||
|
||||
> 安卓虚拟机
|
||||
|
||||
市面上有很多专注于安卓虚拟机的公司,比如
|
||||
|
||||
- vmos虚拟机
|
||||
|
||||
- 光速虚拟机
|
||||
|
||||
其本质是1个apk,安装后,可以`虚拟`无限多的安卓系统
|
||||
|
||||
并且系统内置了magisk/谷歌/改机/gps定位等基础套件
|
||||
|
||||
由于版权关系,无法提供下载地址
|
||||
|
||||
但可以在 海鲜市场搜索: `安卓虚拟机`
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
# 业务场景: 无人直播
|
||||
|
||||
> 无人直播
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-19 10_48_50-2025-08-09 12_07_51-Phone-192.168.31.197_5555.png.png" title="" alt="2025-08-19 10_48_50-2025-08-09 12_07_51-Phone-192.168.31.197_5555.png.png" width="243">
|
||||
|
||||
其实这套设备和系统的搭配,核心是`无人直播`
|
||||
|
||||
- tiktok的风控比较严格
|
||||
|
||||
基于linux系统的docker版的开源`redroid`,无法满足`相机和selinux的风控`
|
||||
|
||||
如果只是想实现xposed的微信机器人,或者挂游戏,可以考虑redroid,成本更低
|
||||
|
||||
> 核心原理
|
||||
|
||||
1. 在linux辅助板,使用ffmpeg播放`视频素材`,或者`直播流`
|
||||
|
||||
2. 通过硬件hdml=>视频采集=>安卓开发板的usb
|
||||
|
||||
3. 由于安卓usb支持uvc协议,被系统识别为`前后摄像头`
|
||||
|
||||
这样就可以实现实时`剪辑/更换/循环`视频流
|
||||
|
||||
ps: 无论是官方的直播伴侣,还是ffmpeg/obs通过rtmp协议推流,都`比不过手机的权重`,前者要么10分钟弹出验证,要么限流
|
||||
|
||||
---
|
||||
|
||||
## 辅助板linux配置
|
||||
|
||||
> armbian系统
|
||||
|
||||
https://www.armbian.com/
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/qweqq12r12r23r23r.png" title="" alt="qweqq12r12r23r23r.png" width="274">
|
||||
|
||||
> 安装视频驱动
|
||||
|
||||
<img title="" src="https://minioweb.hackrobot.cn/hackrobot/download.jpg" alt="download.jpg" width="194">
|
||||
|
||||
```
|
||||
sudo apt install kmscube -y
|
||||
```
|
||||
|
||||
> 安装音频驱动
|
||||
|
||||
<img title="" src="https://minioweb.hackrobot.cn/hackrobot/2025-08-05 10_49_22-Cmder.png" alt="2025-08-05 10_49_22-Cmder.png" width="195">
|
||||
|
||||
```
|
||||
sudo apt install pulseaudio -y
|
||||
```
|
||||
|
||||
> 安装ffmpeg
|
||||
|
||||
```
|
||||
sudo apt install ffmpeg -y
|
||||
```
|
||||
|
||||
## 录播mp4素材
|
||||
|
||||
```
|
||||
ffplay -loop 0 -vf "transpose=2,scale=640:-1,format=yuv420p" -fs -threads 6 xxx.mp4
|
||||
```
|
||||
|
||||
可以打开安卓的摄像头验证
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250908011308.png" title="" alt="20250908011308.png" width="389">
|
||||
|
||||
---
|
||||
|
||||
## obs推流/srs拉流
|
||||
|
||||
> srs直播服务器
|
||||
|
||||

|
||||
在linux辅助板,部署srs直播服务器
|
||||
|
||||
https://github.com/ossrs/srs
|
||||
|
||||
docker部署
|
||||
|
||||
```
|
||||
sudo docker run -d \
|
||||
--name srs \
|
||||
--restart=always \
|
||||
-p 1935:1935 \
|
||||
-p 1985:1985 \
|
||||
-p 8080:8080 \
|
||||
-p 10080:10080/udp \
|
||||
registry.cn-hangzhou.aliyuncs.com/ossrs/srs:5 ./objs/srs -c conf/srt.conf
|
||||
```
|
||||
|
||||
OBS通过srt协议推流
|
||||
|
||||
```
|
||||
srt://ip:10080?streamid=#!::r=live/livestream,m=publish
|
||||
```
|
||||
|
||||

|
||||
|
||||
> linux拉流脚本
|
||||
|
||||
可以新建live.sh
|
||||
|
||||
```
|
||||
nano live.sh
|
||||
```
|
||||
|
||||
内容是
|
||||
|
||||
```
|
||||
ffplay -fflags nobuffer -flags low_delay -framedrop \
|
||||
-probesize 32 -analyzeduration 0 -sync ext -infbuf \
|
||||
-vf "setpts=PTS-STARTPTS" \
|
||||
'srt://127.0.0.1:10080?streamid=#!::r=live/livestream,m=request&latency=10'
|
||||
```
|
||||
|
||||
只要 sh live.sh就可以拉直播流了,安卓摄像头会收到信号
|
||||
|
||||
---
|
||||
|
||||
# 其他业务
|
||||
|
||||
## 小红书RPA自动化
|
||||
|
||||
RPA自动化的核心,在于`系统证书`,不然无法抓取https数据
|
||||
|
||||
首先用`charles`分析接口
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-12 12_53_04-.png" title="" alt="2025-08-12 12_53_04-.png" width="255">
|
||||
|
||||
然后就可以使用linux辅助板的`mitmproxy`进行自动化
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/mitwwwmproxy.png" title="" alt="mitwwwmproxy.png" width="279">
|
||||
|
||||
---
|
||||
|
||||
## 微信机器人
|
||||
|
||||
> 使用xposed模块
|
||||
|
||||
WAuxiliary_Public
|
||||
|
||||
https://github.com/HdShare/WAuxiliary_Public
|
||||
|
||||
该软件的辅助插件
|
||||
|
||||
[WAuxiliary Plugin](https://hdshare.github.io/WAuxiliary_Plugin/)
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20250919145025.png" title="" alt="20250919145025.png" width="162">
|
||||
|
||||
不同自己写代码,引入插件就可以实现各种功能
|
||||
|
||||
当然,也可以接触ai,编写java代码
|
||||
|
||||
---
|
||||
|
||||
# 其他设备:树莓派 raspberry pi
|
||||
|
||||
基于以上描述,其实只要是安卓,获取root权限
|
||||
|
||||
就可以改机型/ip/gps过风控检测
|
||||
|
||||
比如 树莓派的`lineageos`,也是开源安卓系统,一直维护
|
||||
|
||||
下载地址:
|
||||
|
||||
https://konstakang.com/
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/2025-08-26 16_14_45-Pixel 7 Pro.png" title="" alt="2025-08-26 16_14_45-Pixel 7 Pro.png" width="198">
|
||||
|
||||
只是一个爱折腾的人,如果寻求专业的解决方案,请购买市面上
|
||||
|
||||
专业的云手机服务商
|
||||
|
||||
---
|
||||
|
||||
# 最后
|
||||
|
||||
> 公众号: 异度世界
|
||||
|
||||
概括`云手机`
|
||||
|
||||
- 开源硬件:arm开发板`安装`开源系统aosp`的安卓
|
||||
|
||||
- 获取root权限
|
||||
|
||||
- 使用magisk和lsposed管理外挂模块
|
||||
|
||||
- 过风控: 机型参数/代理ip/gps定位/uvs摄像头
|
||||
|
||||
- frp内网穿透
|
||||
|
||||
- qtscrcpy图形管理和群控
|
||||
|
||||
6358
app/vip/data/ebook.md
Normal file
6358
app/vip/data/ebook.md
Normal file
File diff suppressed because it is too large
Load Diff
117
app/vip/data/vip.mock.ts
Normal file
117
app/vip/data/vip.mock.ts
Normal file
@ -0,0 +1,117 @@
|
||||
/**
|
||||
* VIP 首页 Mock 数据 - 集中管理
|
||||
* 后续可替换为 api.hackrobot.cn 真实接口
|
||||
*/
|
||||
|
||||
import { CURRICULUM_CONFIG } from "@vip/app/cloudphone/config/course";
|
||||
|
||||
/** 视频课程总数:从所有课程配置汇总计算 */
|
||||
const TOTAL_VIDEOS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
|
||||
|
||||
export const ASSET_STATS = {
|
||||
topics: 4,
|
||||
ebooks: 2,
|
||||
videos: TOTAL_VIDEOS,
|
||||
updateFrequency: "每周",
|
||||
} as const;
|
||||
|
||||
export const TOPICS = [
|
||||
{
|
||||
id: "ebook",
|
||||
icon: "📖",
|
||||
title: "电子书",
|
||||
desc: "知识沉淀·随时阅读",
|
||||
href: "/vip/ebook",
|
||||
},
|
||||
{
|
||||
id: "cloudphone",
|
||||
icon: "🎬",
|
||||
title: "视频教程",
|
||||
desc: "实战演练·即学即用",
|
||||
href: "/vip/cloudphone",
|
||||
},
|
||||
{
|
||||
id: "community",
|
||||
icon: "👥",
|
||||
title: "私密社群",
|
||||
desc: "抱团出海",
|
||||
href: "https://qun.hackrobot.cn",
|
||||
},
|
||||
{
|
||||
id: "tools",
|
||||
icon: "🛒",
|
||||
title: "设备自助下单",
|
||||
desc: "开箱即用",
|
||||
href: "https://store.hackrobot.cn/",
|
||||
locked: true,
|
||||
},
|
||||
] as const;
|
||||
|
||||
/** 模块展示 - 首页展示用,电子书/视频教程点击滚动到同页对应区块 */
|
||||
export const TOPICS_DISPLAY = [
|
||||
{ id: "ebook", icon: "📖", title: "电子书", desc: "知识沉淀·随时阅读", href: "#ebooks" },
|
||||
{ id: "cloudphone", icon: "🎬", title: "视频教程", desc: "实战演练·即学即用", href: "#video-courses" },
|
||||
{ id: "community", icon: "👥", title: "私密社群", desc: "抱团出海", href: "https://qun.hackrobot.cn", locked: true },
|
||||
{ id: "tools", icon: "🛒", title: "设备自助下单", desc: "开箱即用", href: "https://store.hackrobot.cn/", locked: true },
|
||||
] as const;
|
||||
|
||||
/** 电子书展示 - 首页展示用 */
|
||||
export const EBOOKS_DISPLAY = [
|
||||
{ id: "1", title: "数字游民", desc: "地理套利与自动化杠杆", href: "/vip/ebook", free: true },
|
||||
{ id: "2", title: "云手机", desc: "低成本工作室搭建指南", href: "/vip/ebook/cloudphone", locked: true },
|
||||
] as const;
|
||||
|
||||
/** 视频教程展示(首页),至少 4 个 */
|
||||
export const VIDEO_COURSES_DISPLAY = [
|
||||
{ id: "cloudphone", icon: "☁️", title: "云手机", desc: "低成本自建云手机,TikTok/YouTube 无人直播实战指南", href: "/vip/cloudphone" },
|
||||
{ id: "livestream", icon: "📺", title: "无人直播", desc: "TikTok/YouTube 无人直播,24 小时自动化", href: "/vip/topic/livestream" },
|
||||
{ id: "indie", icon: "🛠️", title: "独立开发", desc: "从想法到产品,独立开发者全流程指南", href: "/vip/topic/indie" },
|
||||
{ id: "aiagent", icon: "🤖", title: "AI Agent", desc: "AIGC 与智能体,Vibe Coding 跨界创造", href: "/vip/topic/aiagent" },
|
||||
] as const;
|
||||
|
||||
export const COMPARE_ITEMS = [
|
||||
{ feature: "电子书", single: "按需开通", member: "全解锁" },
|
||||
{ feature: "视频教程", single: "按需开通", member: "全解锁" },
|
||||
{ feature: "私密社群", single: "—", member: "✓" },
|
||||
{ feature: "即时问答", single: "—", member: "✓" },
|
||||
{ feature: "持续更新", single: "—", member: "✓" },
|
||||
] as const;
|
||||
|
||||
export const COMMUNITY_PREVIEW = [
|
||||
{ icon: "👥", text: "私密社群,抱团出海" },
|
||||
{ icon: "💬", text: "即时问答,技术咨询" },
|
||||
{ icon: "🎪", text: "线下沙龙,面交对接" },
|
||||
] as const;
|
||||
|
||||
export const FAQ_ITEMS = [
|
||||
{
|
||||
q: "会员包含哪些内容?",
|
||||
a: "电子书、视频教程、私密社群、即时问答、设备自助下单等全部解锁,并享受持续更新。",
|
||||
},
|
||||
{
|
||||
q: "如何加入?",
|
||||
a: "点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。",
|
||||
},
|
||||
{
|
||||
q: "为什么越早加入越划算?",
|
||||
a: "会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。",
|
||||
},
|
||||
] as const;
|
||||
|
||||
/** 已登录控制台用 */
|
||||
export const RECENT_UPDATES = [
|
||||
{ id: "1", title: "云手机·第3章更新", date: "3月10日", href: "/vip/cloudphone/course/2/0" },
|
||||
{ id: "2", title: "电子书·地理套利补充", date: "3月8日", href: "/vip/ebook" },
|
||||
{ id: "3", title: "模板库·RPA 脚本新增", date: "3月5日", href: null },
|
||||
] as const;
|
||||
|
||||
export const COMMUNITY_HIGHLIGHTS = [
|
||||
{ id: "1", text: "本周社群讨论:出海合规要点", href: "https://qun.hackrobot.cn" },
|
||||
{ id: "2", text: "问答精选:云手机多开方案", href: "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot" },
|
||||
] as const;
|
||||
|
||||
export const WEEKLY_ACTIONS = [
|
||||
{ id: "1", text: "完成云手机第2章", href: "/vip/cloudphone/course/1/0", priority: 1 },
|
||||
{ id: "2", text: "阅读电子书地理套利篇", href: "/vip/ebook", priority: 2 },
|
||||
{ id: "3", text: "加入社群参与讨论", href: "https://qun.hackrobot.cn", priority: 3 },
|
||||
] as const;
|
||||
230
app/vip/ebook/EbookClient.tsx
Normal file
230
app/vip/ebook/EbookClient.tsx
Normal file
@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useRef, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import type { EbookData } from "@vip/app/lib/ebook";
|
||||
import "github-markdown-css/github-markdown.css";
|
||||
import styles from "./ebook.module.css";
|
||||
|
||||
function LazyChunk({
|
||||
html,
|
||||
estimatedHeight,
|
||||
forceVisible,
|
||||
}: {
|
||||
html: string;
|
||||
estimatedHeight: number;
|
||||
forceVisible: boolean;
|
||||
}) {
|
||||
const [visible, setVisible] = useState(forceVisible);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const show = forceVisible || visible;
|
||||
|
||||
useEffect(() => {
|
||||
if (forceVisible || visible) return;
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setVisible(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: "1200px 0px" }
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [forceVisible, visible]);
|
||||
|
||||
if (show) {
|
||||
return (
|
||||
<div
|
||||
className={`${styles.chunkEnter} animate__animated animate__fadeInUp`}
|
||||
style={{ animationDuration: "0.5s", animationFillMode: "both" }}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={styles.chunkPlaceholder}
|
||||
style={{ minHeight: estimatedHeight }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EbookClient({
|
||||
data,
|
||||
title = "数字游民",
|
||||
backHref = "/",
|
||||
}: {
|
||||
data: EbookData;
|
||||
title?: string;
|
||||
backHref?: string;
|
||||
}) {
|
||||
const [showDrawer, setShowDrawer] = useState(false);
|
||||
const [readProgress, setReadProgress] = useState(0);
|
||||
const [showBackTop, setShowBackTop] = useState(false);
|
||||
const [forceShowAll, setForceShowAll] = useState(false);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { chunks, headers } = data;
|
||||
|
||||
useEffect(() => {
|
||||
let ticking = false;
|
||||
const onScroll = () => {
|
||||
if (ticking) return;
|
||||
ticking = true;
|
||||
requestAnimationFrame(() => {
|
||||
const scrollTop =
|
||||
window.scrollY || document.documentElement.scrollTop;
|
||||
const docHeight =
|
||||
document.documentElement.scrollHeight - window.innerHeight;
|
||||
setReadProgress(
|
||||
docHeight > 0 ? Math.min(100, (scrollTop / docHeight) * 100) : 0
|
||||
);
|
||||
setShowBackTop(scrollTop > 600);
|
||||
ticking = false;
|
||||
});
|
||||
};
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => window.removeEventListener("scroll", onScroll);
|
||||
}, []);
|
||||
|
||||
const handleJump = useCallback(
|
||||
(index: number) => {
|
||||
setForceShowAll(true);
|
||||
setShowDrawer(false);
|
||||
|
||||
const run = () => {
|
||||
const root = contentRef.current;
|
||||
if (!root) return;
|
||||
const h1s = root.querySelectorAll("h1");
|
||||
const h2s = root.querySelectorAll("h2");
|
||||
const targets = h1s.length > 0 ? h1s : h2s;
|
||||
const el = targets[index] as HTMLElement;
|
||||
if (el) {
|
||||
try {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
} catch {
|
||||
const top =
|
||||
el.getBoundingClientRect().top +
|
||||
(window.pageYOffset || document.documentElement.scrollTop) -
|
||||
60;
|
||||
window.scrollTo({ top: Math.max(0, top), behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
setTimeout(run, 100);
|
||||
setTimeout(run, 300);
|
||||
setTimeout(run, 600);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={styles.readingProgress}
|
||||
style={{ width: `${readProgress}%` }}
|
||||
/>
|
||||
|
||||
<div className={styles.headerSpacer} />
|
||||
<header className={`${styles.header} animate__animated animate__fadeInDown`} style={{ animationFillMode: "both" }}>
|
||||
<Link href={backHref} className={styles.headerLeft} aria-label="返回首页">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
</Link>
|
||||
<div className={styles.headerMiddle}>{title}</div>
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.headerRight} ${showDrawer ? styles.headerRightActive : ""}`}
|
||||
onClick={() => setShowDrawer(!showDrawer)}
|
||||
aria-label="目录"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
<span className={styles.headerRightText}>目录</span>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className={styles.book}>
|
||||
<div ref={contentRef} className={`markdown-body ${styles.markdownBody}`}>
|
||||
{chunks.map((chunk, i) => (
|
||||
<LazyChunk
|
||||
key={i}
|
||||
html={chunk.html}
|
||||
estimatedHeight={chunk.estimatedHeight}
|
||||
forceVisible={forceShowAll || i === 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`${styles.drawerMask} ${showDrawer ? styles.drawerMaskOpen : ""}`}
|
||||
onClick={() => setShowDrawer(false)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<aside
|
||||
className={`${styles.drawer} ${showDrawer ? styles.drawerOpen : ""}`}
|
||||
>
|
||||
{headers.map((titleItem, index) => (
|
||||
<div
|
||||
key={index}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={styles.drawerItem}
|
||||
onClick={() => handleJump(index)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") handleJump(index);
|
||||
}}
|
||||
>
|
||||
{titleItem}
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
{showBackTop && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.backToTop}
|
||||
onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
|
||||
aria-label="回到顶部"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M18 15l-6-6-6 6" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
23
app/vip/ebook/cloudphone/page.tsx
Normal file
23
app/vip/ebook/cloudphone/page.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { parseEbookMarkdown, estimateReadingMinutes } from "@vip/lib/content/ebook";
|
||||
import { EbookViewer } from "@vip/app/components/content/EbookViewer";
|
||||
import { CLOUDPHONE_EBOOK_CONFIG } from "@vip/config/content.config";
|
||||
import { resolveVipDataFile } from "@vip/app/lib/resolveVipDataFile";
|
||||
|
||||
export const metadata = {
|
||||
title: "云手机 | 低成本工作室搭建指南",
|
||||
description: "云手机:低成本自建云手机,TikTok/YouTube 无人直播,Redroid、AOSP、ffmpeg、SRS 从零搭建。",
|
||||
};
|
||||
|
||||
export default function CloudphoneEbookPage() {
|
||||
const mdPath = resolveVipDataFile("cloudphone.md");
|
||||
const source = readFileSync(mdPath, "utf-8");
|
||||
const data = parseEbookMarkdown(source);
|
||||
const textLen = data.chunks.reduce((s, c) => s + c.html.replace(/<[^>]+>/g, "").length, 0);
|
||||
const config = {
|
||||
...CLOUDPHONE_EBOOK_CONFIG,
|
||||
estimatedMinutes: estimateReadingMinutes(textLen),
|
||||
};
|
||||
|
||||
return <EbookViewer data={data} config={config} />;
|
||||
}
|
||||
487
app/vip/ebook/ebook.module.css
Normal file
487
app/vip/ebook/ebook.module.css
Normal file
@ -0,0 +1,487 @@
|
||||
/* 复刻 digital /ebook 电子书样式 */
|
||||
|
||||
.readingProgress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
|
||||
z-index: 201;
|
||||
transition: width 0.15s linear;
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
|
||||
.headerSpacer {
|
||||
width: 100%;
|
||||
height: 88px;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
height: 88px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.headerLeft {
|
||||
width: 100px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #1a1a2e;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.headerMiddle {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #1a1a2e;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.headerRight {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #4facfe;
|
||||
cursor: pointer;
|
||||
margin-right: 10px;
|
||||
background: #f0f7ff;
|
||||
border-radius: 50%;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.headerRight:hover {
|
||||
background: #dceeff;
|
||||
}
|
||||
|
||||
.headerRightActive {
|
||||
background: #4facfe !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
.headerRightText {
|
||||
display: none;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.chunkEnter {
|
||||
animation: chunkAppear 0.5s ease-out both;
|
||||
}
|
||||
|
||||
@keyframes chunkAppear {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.chunkPlaceholder {
|
||||
background: linear-gradient(90deg, #f6f7f8 25%, #edeef1 37%, #f6f7f8 63%);
|
||||
background-size: 400% 100%;
|
||||
animation: shimmer 1.8s ease infinite;
|
||||
border-radius: 12px;
|
||||
margin: 24px 0;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.backToTop {
|
||||
position: fixed;
|
||||
bottom: 120px;
|
||||
right: 30px;
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
cursor: pointer;
|
||||
z-index: 50;
|
||||
animation: fadeInUp 0.3s ease;
|
||||
color: #4facfe;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.backToTop:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
@keyframes fadeInUp {
|
||||
from { opacity: 0; transform: translateY(16px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.book {
|
||||
padding: 30px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.markdownBody {
|
||||
font-size: 16px !important;
|
||||
line-height: 1.85 !important;
|
||||
color: #2c3e50 !important;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 24px !important;
|
||||
font-weight: 800;
|
||||
color: #1a1a2e;
|
||||
margin: 28px 0 10px;
|
||||
padding-bottom: 0;
|
||||
border-bottom: none;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.markdownBody h1::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 40px;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, #4facfe, #00f2fe);
|
||||
border-radius: 3px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 21px !important;
|
||||
font-weight: 700;
|
||||
color: #2c3e50;
|
||||
margin: 22px 0 9px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.markdownBody h3 {
|
||||
font-size: 18px !important;
|
||||
font-weight: 600;
|
||||
color: #34495e;
|
||||
margin: 18px 0 7px;
|
||||
}
|
||||
|
||||
.markdownBody h4,
|
||||
.markdownBody h5,
|
||||
.markdownBody h6 {
|
||||
font-size: 16px !important;
|
||||
font-weight: 600;
|
||||
color: #4a5568;
|
||||
margin: 14px 0 6px;
|
||||
}
|
||||
|
||||
.markdownBody p {
|
||||
font-size: 16px !important;
|
||||
margin-bottom: 10px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.markdownBody blockquote {
|
||||
position: relative;
|
||||
margin: 28px 0;
|
||||
padding: 20px 24px 20px 30px;
|
||||
border-left: none;
|
||||
background: linear-gradient(135deg, #f8fbff 0%, #f0f7ff 100%);
|
||||
border-radius: 0 12px 12px 0;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.markdownBody blockquote::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 6px;
|
||||
background: linear-gradient(180deg, #4facfe, #00f2fe);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.markdownBody pre {
|
||||
position: relative;
|
||||
margin: 28px 0;
|
||||
padding: 28px 24px 24px;
|
||||
background: #1e1e2e;
|
||||
border-radius: 12px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.markdownBody pre::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, #4facfe, #00f2fe);
|
||||
border-radius: 12px 12px 0 0;
|
||||
}
|
||||
|
||||
.markdownBody pre code {
|
||||
font-family: "SF Mono", "Fira Code", Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 13px !important;
|
||||
line-height: 1.6;
|
||||
color: #e2e8f0;
|
||||
background: none !important;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdownBody code {
|
||||
font-family: "SF Mono", "Fira Code", Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 14px !important;
|
||||
padding: 2px 6px;
|
||||
background: #f1f5f9;
|
||||
color: #e53e3e;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.markdownBody a {
|
||||
color: #4facfe;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdownBody a:hover {
|
||||
color: #2b8de3;
|
||||
border-bottom: 1px solid #4facfe;
|
||||
}
|
||||
|
||||
.markdownBody img {
|
||||
display: block;
|
||||
margin: 28px auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.markdownBody ul,
|
||||
.markdownBody ol {
|
||||
margin: 16px 0;
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
.markdownBody table {
|
||||
width: 100%;
|
||||
margin: 28px 0;
|
||||
border-collapse: collapse;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.markdownBody th {
|
||||
background: linear-gradient(135deg, #f8fafc, #edf2f7);
|
||||
font-weight: 600;
|
||||
padding: 16px 20px;
|
||||
text-align: left;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.markdownBody td {
|
||||
padding: 14px 20px;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.markdownBody tr:nth-child(even) {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 280px;
|
||||
max-width: 85vw;
|
||||
background: #fff;
|
||||
box-shadow: -4px 0 24px rgba(0, 0, 0, 0.1);
|
||||
z-index: 150;
|
||||
padding-top: 88px;
|
||||
overflow-y: auto;
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerOpen {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.drawerMask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
z-index: 140;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.drawerMaskOpen {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.drawerItem {
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #f5f5f5;
|
||||
color: #2c3e50;
|
||||
cursor: pointer;
|
||||
font-size: 15px;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.drawerItem:hover {
|
||||
background: #f0f7ff;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.headerSpacer {
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.header {
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.headerMiddle {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.headerRight {
|
||||
width: auto;
|
||||
height: 34px;
|
||||
padding: 0 14px;
|
||||
margin-right: 16px;
|
||||
gap: 5px;
|
||||
border-radius: 17px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.headerRightText {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.book {
|
||||
padding: 30px 60px;
|
||||
}
|
||||
|
||||
.markdownBody {
|
||||
font-size: 16px !important;
|
||||
line-height: 1.8 !important;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 28px !important;
|
||||
margin: 36px 0 14px;
|
||||
}
|
||||
|
||||
.markdownBody h1::after {
|
||||
width: 50px;
|
||||
height: 3px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 23px !important;
|
||||
margin: 28px 0 12px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.markdownBody h3 {
|
||||
font-size: 19px !important;
|
||||
margin: 22px 0 10px;
|
||||
}
|
||||
|
||||
.markdownBody p {
|
||||
font-size: 16px !important;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.markdownBody pre code {
|
||||
font-size: 14px !important;
|
||||
}
|
||||
|
||||
.markdownBody code {
|
||||
font-size: 14px !important;
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.backToTop {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
bottom: 40px;
|
||||
right: 40px;
|
||||
}
|
||||
|
||||
.drawer {
|
||||
padding-top: 56px;
|
||||
width: 300px;
|
||||
}
|
||||
|
||||
.drawerItem {
|
||||
font-size: 14px;
|
||||
padding: 14px 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.book {
|
||||
padding: 30px 80px;
|
||||
}
|
||||
|
||||
.markdownBody {
|
||||
width: 720px;
|
||||
font-size: 17px !important;
|
||||
line-height: 1.85 !important;
|
||||
}
|
||||
|
||||
.markdownBody h1 {
|
||||
font-size: 30px !important;
|
||||
}
|
||||
|
||||
.markdownBody h2 {
|
||||
font-size: 25px !important;
|
||||
}
|
||||
|
||||
.markdownBody h3 {
|
||||
font-size: 20px !important;
|
||||
}
|
||||
|
||||
.markdownBody p {
|
||||
font-size: 17px !important;
|
||||
}
|
||||
|
||||
.markdownBody img.loaded:hover {
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
23
app/vip/ebook/page.tsx
Normal file
23
app/vip/ebook/page.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { parseEbookMarkdown, estimateReadingMinutes } from "@vip/lib/content/ebook";
|
||||
import { EbookViewer } from "@vip/app/components/content/EbookViewer";
|
||||
import { EBOOK_CONFIG } from "@vip/config/content.config";
|
||||
import { resolveVipDataFile } from "@vip/app/lib/resolveVipDataFile";
|
||||
|
||||
export const metadata = {
|
||||
title: "电子书 | 数字游民",
|
||||
description: "数字游民:地理套利与自动化杠杆,低成本工作室、云手机、无人直播、出海掘金。",
|
||||
};
|
||||
|
||||
export default function EbookPage() {
|
||||
const mdPath = resolveVipDataFile("ebook.md");
|
||||
const source = readFileSync(mdPath, "utf-8");
|
||||
const data = parseEbookMarkdown(source);
|
||||
const textLen = data.chunks.reduce((s, c) => s + c.html.replace(/<[^>]+>/g, "").length, 0);
|
||||
const config = {
|
||||
...EBOOK_CONFIG,
|
||||
estimatedMinutes: estimateReadingMinutes(textLen),
|
||||
};
|
||||
|
||||
return <EbookViewer data={data} config={config} />;
|
||||
}
|
||||
839
app/vip/home.module.css
Normal file
839
app/vip/home.module.css
Normal file
@ -0,0 +1,839 @@
|
||||
/* 异度星球 - 温暖自然风格 */
|
||||
|
||||
.root {
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(180deg, #faf9f7 0%, #f5f3f0 50%, #ebe8e4 100%);
|
||||
color: #292524;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.root {
|
||||
background: linear-gradient(180deg, #faf9f7 0%, #f5f3f0 100%);
|
||||
color: #292524;
|
||||
}
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1rem 1.5rem;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.header {
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
.logo {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: #292524;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.logo:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.nav a {
|
||||
font-size: 0.9rem;
|
||||
color: #78716c;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav a:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* Loading */
|
||||
.loading {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
background: #faf9f7;
|
||||
}
|
||||
|
||||
.loadingSpinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid #e7e5e4;
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Main */
|
||||
.main {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1.5rem 2rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.main {
|
||||
padding: 0 1rem 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.hero {
|
||||
text-align: center;
|
||||
padding: 2rem 0 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.hero {
|
||||
padding: 1.5rem 0 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.heroBadge {
|
||||
display: inline-block;
|
||||
font-size: 0.875rem;
|
||||
color: #78716c;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
padding: 0.35rem 0.85rem;
|
||||
border-radius: 9999px;
|
||||
margin-bottom: 1rem;
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
.heroTitle {
|
||||
font-size: clamp(2.5rem, 6vw, 4rem);
|
||||
font-weight: 700;
|
||||
color: #292524;
|
||||
margin: 0 0 0.5rem;
|
||||
letter-spacing: -0.01em;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.heroTitle {
|
||||
font-size: clamp(2rem, 10vw, 2.5rem);
|
||||
color: #292524;
|
||||
}
|
||||
.heroBadge {
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
border-color: #e7e5e4;
|
||||
color: #78716c;
|
||||
}
|
||||
.heroSubtitle {
|
||||
color: #57534e;
|
||||
}
|
||||
}
|
||||
|
||||
.heroSubtitle {
|
||||
font-size: 1.125rem;
|
||||
color: #57534e;
|
||||
max-width: 540px;
|
||||
margin: 0 auto 0.25rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.heroCta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btnPrimary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.75rem 1.75rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--accent-foreground);
|
||||
background: var(--accent);
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
transition: opacity 0.2s, transform 0.15s;
|
||||
}
|
||||
|
||||
.btnPrimary:hover {
|
||||
opacity: 0.95;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btnSecondary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.75rem 1.5rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 500;
|
||||
color: #57534e;
|
||||
background: white;
|
||||
border: 1px solid #e7e5e4;
|
||||
border-radius: 12px;
|
||||
text-decoration: none;
|
||||
transition: border-color 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.btnSecondary:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.btnLarge {
|
||||
padding: 1rem 2.5rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
/* Stats */
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 1rem;
|
||||
padding: 2rem 0;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.stats {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.stat {
|
||||
text-align: center;
|
||||
padding: 1.25rem;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
.statValue {
|
||||
display: block;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--accent);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.statLabel {
|
||||
font-size: 0.875rem;
|
||||
color: #78716c;
|
||||
}
|
||||
|
||||
/* Sections */
|
||||
.section {
|
||||
padding: 1.5rem 0;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.section {
|
||||
padding: 1rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
.sectionTightTop {
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: #292524;
|
||||
margin: 0 0 0.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.section h2 {
|
||||
font-size: 1.35rem;
|
||||
color: #292524;
|
||||
}
|
||||
.sectionDesc {
|
||||
color: #57534e;
|
||||
}
|
||||
}
|
||||
|
||||
.sectionDesc {
|
||||
text-align: center;
|
||||
color: #78716c;
|
||||
max-width: 600px;
|
||||
margin: 0 auto 1rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* Features */
|
||||
.features {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 1rem;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.features {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.featureCard {
|
||||
padding: 1.25rem;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid #e7e5e4;
|
||||
transition: box-shadow 0.2s, transform 0.2s;
|
||||
}
|
||||
|
||||
.featureCard:hover {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.featureCard {
|
||||
background: white;
|
||||
border-color: #e7e5e4;
|
||||
border-radius: 12px;
|
||||
padding: 1rem;
|
||||
}
|
||||
.featureCard h3 {
|
||||
color: #292524;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.featureCard p {
|
||||
color: #57534e;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.featureIcon {
|
||||
font-size: 2rem;
|
||||
display: block;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.featureCard h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: #292524;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.featureCard p {
|
||||
font-size: 0.9rem;
|
||||
color: #57534e;
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Unlock 内容 - 6 项可视化 */
|
||||
.unlockGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.unlockGrid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 900px) {
|
||||
.unlockGrid {
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.unlockGrid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.unlockCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem 0.75rem;
|
||||
background: white;
|
||||
border-radius: 14px;
|
||||
border: 2px dashed #d6d3d1;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all 0.25s ease;
|
||||
font-family: inherit;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.unlockCard:hover {
|
||||
border-color: var(--accent);
|
||||
border-style: solid;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.unlockCardDisabled {
|
||||
pointer-events: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.unlockCardDisabled:hover {
|
||||
border-color: #d6d3d1;
|
||||
border-style: dashed;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.unlockIcon {
|
||||
font-size: 2.25rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.unlockTitle {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
color: #292524;
|
||||
}
|
||||
|
||||
.unlockDesc {
|
||||
font-size: 0.8rem;
|
||||
color: #57534e;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.unlockCard {
|
||||
background: white;
|
||||
border-color: #d6d3d1;
|
||||
border-style: dashed;
|
||||
padding: 0.75rem 0.5rem;
|
||||
border-radius: 10px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.unlockCard:hover {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
.unlockIcon {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
.unlockTitle {
|
||||
font-size: 0.9rem;
|
||||
color: #292524;
|
||||
}
|
||||
.unlockDesc {
|
||||
font-size: 0.7rem;
|
||||
color: #57534e;
|
||||
}
|
||||
}
|
||||
|
||||
.unlockCta {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.unlockCta .btnPrimary {
|
||||
padding: 1rem 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
/* CTA Section */
|
||||
.sectionCta {
|
||||
padding: 1rem 0 2rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.sectionCta {
|
||||
padding: 0.75rem 0 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ctaCard {
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem;
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
text-align: center;
|
||||
color: #292524;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
.ctaCard h2 {
|
||||
color: #292524;
|
||||
font-size: 1.35rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.ctaCard p {
|
||||
font-size: 0.9rem;
|
||||
color: #57534e;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.ctaNote {
|
||||
font-size: 0.8rem !important;
|
||||
color: #78716c !important;
|
||||
margin-bottom: 1.5rem !important;
|
||||
}
|
||||
|
||||
.ctaCard .btnPrimary {
|
||||
background: #059669;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.ctaCard .btnPrimary:hover {
|
||||
background: #047857;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.ctaCard {
|
||||
padding: 1.25rem 1rem;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.ctaCard h2 {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
.ctaCard p {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Tools */
|
||||
.tools {
|
||||
padding: 2rem 0;
|
||||
}
|
||||
|
||||
.tools h2 {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: #292524;
|
||||
text-align: center;
|
||||
margin: 0 0 1.5rem;
|
||||
}
|
||||
|
||||
.toolsGrid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1.5rem;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.toolItem {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem 1.5rem;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #e7e5e4;
|
||||
font-size: 0.9rem;
|
||||
color: #57534e;
|
||||
}
|
||||
|
||||
/* VIP Success */
|
||||
.vipSuccess {
|
||||
min-height: 60vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem 1.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipSuccess {
|
||||
min-height: calc(100vh - 60px);
|
||||
padding: 1.5rem 1rem;
|
||||
align-items: flex-start;
|
||||
padding-top: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.vipSuccessCard {
|
||||
max-width: 420px;
|
||||
width: 100%;
|
||||
padding: 2.5rem;
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipSuccessCard {
|
||||
max-width: 100%;
|
||||
padding: 1.5rem 1.25rem;
|
||||
background: white;
|
||||
border: 1px solid #e7e5e4;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
}
|
||||
|
||||
.vipSuccessIcon {
|
||||
font-size: 3rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipSuccessIcon {
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.vipSuccessCard h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #292524;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipSuccessCard h1 {
|
||||
font-size: 1.35rem;
|
||||
color: #292524;
|
||||
}
|
||||
}
|
||||
|
||||
.vipSuccessDesc {
|
||||
font-size: 0.95rem;
|
||||
color: #57534e;
|
||||
margin: 0 0 1.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipSuccessDesc {
|
||||
color: #57534e;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCode {
|
||||
text-align: left;
|
||||
padding: 1.25rem;
|
||||
background: #faf9f7;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCode {
|
||||
padding: 1rem;
|
||||
background: #faf9f7;
|
||||
border: 1px solid #e7e5e4;
|
||||
border-radius: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCodeRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.vipCodeRow:last-of-type {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCodeRow {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.6rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCodeRow span {
|
||||
color: #57534e;
|
||||
min-width: 4rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCodeRow span {
|
||||
color: #57534e;
|
||||
min-width: 3.5rem;
|
||||
width: 100%;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCodeRow code {
|
||||
flex: 1;
|
||||
font-family: ui-sans-serif, system-ui, sans-serif;
|
||||
background: white;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCodeRow code {
|
||||
flex: 1 1 100%;
|
||||
background: white;
|
||||
color: #292524;
|
||||
padding: 0.4rem 0.6rem;
|
||||
font-size: 0.8rem;
|
||||
border: 1px solid #e7e5e4;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCodeRow button {
|
||||
padding: 0.25rem 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
background: var(--accent);
|
||||
color: var(--accent-foreground);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.vipCodeRow button:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCodeRow button {
|
||||
padding: 0.35rem 0.85rem;
|
||||
background: var(--accent);
|
||||
border-radius: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.vipCta {
|
||||
display: block;
|
||||
text-align: center;
|
||||
margin-top: 1rem;
|
||||
padding: 0.75rem;
|
||||
background: var(--accent);
|
||||
color: var(--accent-foreground);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
border-radius: 10px;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.vipCta:hover {
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipCta {
|
||||
margin-top: 1rem;
|
||||
padding: 0.9rem 1rem;
|
||||
background: var(--accent);
|
||||
border-radius: 12px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.vipCta:hover {
|
||||
opacity: 0.95;
|
||||
}
|
||||
}
|
||||
|
||||
.vipTip {
|
||||
font-size: 0.8rem;
|
||||
color: #78716c;
|
||||
margin: 1rem 0 0 !important;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.vipTip {
|
||||
font-size: 0.75rem;
|
||||
color: #78716c;
|
||||
margin-top: 0.75rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.footer {
|
||||
text-align: center;
|
||||
padding: 1.25rem 0;
|
||||
border-top: 1px solid #e7e5e4;
|
||||
}
|
||||
|
||||
.footer p {
|
||||
font-size: 0.9rem;
|
||||
color: #78716c;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
font-size: 0.85rem;
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* 夜间模式 - :global(.dark) 匹配 html 上的 class */
|
||||
:global(.dark) .root {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
:global(.dark) .logo { color: var(--foreground); }
|
||||
:global(.dark) .logo:hover { color: var(--accent); }
|
||||
:global(.dark) .nav a { color: var(--muted-foreground); }
|
||||
:global(.dark) .nav a:hover { color: var(--accent); }
|
||||
:global(.dark) .loading { background: var(--background); color: var(--foreground); }
|
||||
:global(.dark) .loadingSpinner { border-color: var(--border); border-top-color: var(--accent); }
|
||||
:global(.dark) .heroBadge { color: var(--muted-foreground); background: var(--card); border-color: var(--border); }
|
||||
:global(.dark) .heroTitle { color: var(--foreground); }
|
||||
:global(.dark) .heroSubtitle { color: var(--muted-foreground); }
|
||||
:global(.dark) .section h2 { color: var(--foreground); }
|
||||
:global(.dark) .sectionDesc { color: var(--muted-foreground); }
|
||||
:global(.dark) .stat { background: var(--card); border-color: var(--border); }
|
||||
:global(.dark) .statValue { color: var(--accent); }
|
||||
:global(.dark) .statLabel { color: var(--muted-foreground); }
|
||||
:global(.dark) .featureCard { background: var(--card); border-color: var(--border); }
|
||||
:global(.dark) .featureCard h3 { color: var(--foreground); }
|
||||
:global(.dark) .featureCard p { color: var(--muted-foreground); }
|
||||
:global(.dark) .unlockCard { background: var(--card); border-color: var(--border); }
|
||||
:global(.dark) .unlockCard:hover { border-color: var(--accent); }
|
||||
:global(.dark) .unlockTitle { color: var(--foreground); }
|
||||
:global(.dark) .unlockDesc { color: var(--muted-foreground); }
|
||||
:global(.dark) .toolItem { background: var(--card); border-color: var(--border); color: var(--muted-foreground); }
|
||||
:global(.dark) .tools h2 { color: var(--foreground); }
|
||||
:global(.dark) .vipSuccessCard { background: var(--card); }
|
||||
:global(.dark) .vipSuccessCard h1 { color: var(--foreground); }
|
||||
:global(.dark) .vipSuccessDesc { color: var(--muted-foreground); }
|
||||
:global(.dark) .vipCode { background: var(--muted); border-color: var(--border); }
|
||||
:global(.dark) .vipCodeRow span { color: var(--muted-foreground); }
|
||||
:global(.dark) .vipCodeRow code { background: var(--background); }
|
||||
:global(.dark) .vipTip { color: var(--muted-foreground); }
|
||||
:global(.dark) .footer { border-color: var(--border); }
|
||||
:global(.dark) .footer p { color: var(--muted-foreground); }
|
||||
:global(.dark) .footer a { color: var(--accent); }
|
||||
12
app/vip/https-upgrade.ts
Normal file
12
app/vip/https-upgrade.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* 微信等环境可能以 http 打开 vip 域名,导致 Cookie/支付与 https 不一致。
|
||||
* 在任意 JS 执行前立即跳转到 https(middleware 之外的兜底)。
|
||||
*/
|
||||
export const httpsUpgradeScript = `
|
||||
(function(){
|
||||
var h=location.hostname;
|
||||
if(h!=="vip.hackrobot.cn"&&h!=="www.vip.hackrobot.cn")return;
|
||||
if(location.protocol!=="http:")return;
|
||||
location.replace("https://"+h+location.pathname+location.search+location.hash);
|
||||
})();
|
||||
`;
|
||||
50
app/vip/index-content.ts
Normal file
50
app/vip/index-content.ts
Normal file
@ -0,0 +1,50 @@
|
||||
export const indexMd = `
|
||||
<img title="" src="https://minioweb.hackrobot.cn/hackrobot/image_20251231_015321_20586.jpg" alt="image_20251231_015321_20586.jpg" width="271">
|
||||
|
||||
🌟你将收获:
|
||||
🚀 业务方向:无人直播、RPA 自动化、web开发
|
||||
|
||||
⚙️ 技术杠杆:云手机、PVE 虚拟化、服务器集群
|
||||
|
||||
🌐 海外平台:YouTube、TikTok、SaaS 运营实战
|
||||
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
📖 解锁=>电子书+视频教程
|
||||
|
||||
1️⃣[《数字游民》:地理套利 + 自动化杠杆](https://hackrobot.cn)
|
||||
|
||||
2️⃣ [《云手机》:低成本工作室搭建指南](https://android.hackrobot.cn)
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20260101205143_20260101_205202_1552.png" title="" alt="20260101205143_20260101_205202_1552.png" width="180">
|
||||
|
||||
|
||||
|
||||
📱设备自助下单(开箱即用)
|
||||
|
||||
<img title="" src="https://minioweb.hackrobot.cn/hackrobot/wqdq_20260101_212749_8560.jpg" alt="wqdq_20260101_212749_8560.jpg" width="282">
|
||||
|
||||
|
||||
|
||||
📚 即时问答 (技术咨询)
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20260101203904_20260101_204741_699.png" title="" alt="20260101203904_20260101_204741_699.png" width="284">
|
||||
|
||||
㊙️私密社群
|
||||
|
||||
<img src="https://minioweb.hackrobot.cn/hackrobot/20260101204456_20260101_204802_768.png" title="" alt="20260101204456_20260101_204802_768.png" width="186">
|
||||
|
||||
<br/>
|
||||
|
||||
🚫 内容不适合想躺赚、现金流紧张的人
|
||||
|
||||
💰 价格随参与人数阶梯式调整
|
||||
(维护与答疑成本随规模增长)
|
||||
|
||||
📌 本内容为虚拟数字交付
|
||||
不支持退款
|
||||
|
||||
👉 **限时特惠,3月12日恢复**
|
||||
`;
|
||||
231
app/vip/index.module.css
Normal file
231
app/vip/index.module.css
Normal file
@ -0,0 +1,231 @@
|
||||
/* markdown-body from github-markdown-css */
|
||||
.markVip {
|
||||
padding-left: 50px;
|
||||
padding-right: 50px;
|
||||
}
|
||||
|
||||
.markVip img {
|
||||
display: block;
|
||||
margin: 10px auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.markVip p,
|
||||
.markVip li,
|
||||
.markVip h1,
|
||||
.markVip h2,
|
||||
.markVip h3 {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.index {
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.indexBook {
|
||||
min-height: 150px;
|
||||
display: flex;
|
||||
flex-direction: column-reverse;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.indexBookLeft {
|
||||
min-width: 300px;
|
||||
min-height: 150px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.leftTitle {
|
||||
font-size: 25px;
|
||||
font-weight: 700;
|
||||
color: #69b1ff;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.card {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cardItem {
|
||||
padding: 10px;
|
||||
width: 250px;
|
||||
margin-bottom: 10px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
background-color: #f0f5ff;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.cardItemLeft {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-right: 20px;
|
||||
}
|
||||
|
||||
.cardItemLeftImg {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.cardItemRight {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cardItemRightUp {
|
||||
width: 100%;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
font-weight: 700;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.cardItemRightDown {
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
font-size: 15px;
|
||||
flex-wrap: wrap;
|
||||
color: #262626;
|
||||
}
|
||||
|
||||
.leftBtn {
|
||||
margin-top: 15px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.startRead {
|
||||
width: 250px;
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: white;
|
||||
background: linear-gradient(135deg, #69b1ff 0%, #4096ff 100%);
|
||||
border: none;
|
||||
border-radius: 9999px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.startRead:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.indexBookImg {
|
||||
margin-top: 15px;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
}
|
||||
|
||||
.bookImg {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.svgItems {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
/* H5 下隐藏「解锁vip」按钮下方模块(无人直播、RPA自动化、聊天机器人) */
|
||||
@media (max-width: 768px) {
|
||||
.svgItems {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.svgItem {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.bookImgItem {
|
||||
width: 350px;
|
||||
height: 350px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.bookImgText {
|
||||
margin-top: 20px;
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
.vipcode {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.vipcode button {
|
||||
margin: 8px 0;
|
||||
padding: 8px 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@media (min-width: 1536px) {
|
||||
.index {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.indexBook {
|
||||
width: 100%;
|
||||
max-width: 1400px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background-color: #f0f5ff;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.indexBookLeft .card {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.indexBookLeft .leftBtn .startRead {
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
.indexBookImg .bookImg {
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.svgItems {
|
||||
width: 100%;
|
||||
max-width: 1400px;
|
||||
margin-top: 80px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
14
app/vip/layout.tsx
Normal file
14
app/vip/layout.tsx
Normal file
@ -0,0 +1,14 @@
|
||||
import "@vip/app/globals.css";
|
||||
import { ThemeProvider } from "@vip/app/providers/ThemeProvider";
|
||||
import { httpsUpgradeScript } from "@vip/app/https-upgrade";
|
||||
import { themeInitScript } from "@vip/app/theme-init";
|
||||
|
||||
export default function VipLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="vip-root min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<script dangerouslySetInnerHTML={{ __html: httpsUpgradeScript }} />
|
||||
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
|
||||
<ThemeProvider>{children}</ThemeProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
33
app/vip/lib/auth-cookie.ts
Normal file
33
app/vip/lib/auth-cookie.ts
Normal file
@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 认证 Cookie 配置
|
||||
* 生产: AUTH_COOKIE_DOMAIN 实现跨子域 SSO
|
||||
* 本地 IP: 自动设置 domain 实现多端口共享(3000/3001/3002)
|
||||
*/
|
||||
|
||||
const COOKIE_NAME = "pb_session";
|
||||
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
||||
|
||||
export { COOKIE_NAME, COOKIE_MAX_AGE };
|
||||
|
||||
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
|
||||
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
|
||||
return host.split(",")[0].trim().replace(/:\d+$/, "");
|
||||
}
|
||||
|
||||
export function getCookieOptions(clear = false, requestHost?: string) {
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
|
||||
const opts: Record<string, unknown> = {
|
||||
path: "/",
|
||||
maxAge: clear ? 0 : COOKIE_MAX_AGE,
|
||||
secure: isProd,
|
||||
sameSite: "lax" as const,
|
||||
httpOnly: true,
|
||||
};
|
||||
if (domain && isProd) {
|
||||
opts.domain = domain;
|
||||
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
|
||||
opts.domain = requestHost;
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
43
app/vip/lib/ebook.ts
Normal file
43
app/vip/lib/ebook.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { marked } from "marked";
|
||||
|
||||
export interface EbookChunk {
|
||||
html: string;
|
||||
estimatedHeight: number;
|
||||
}
|
||||
|
||||
export interface EbookData {
|
||||
chunks: EbookChunk[];
|
||||
headers: string[];
|
||||
}
|
||||
|
||||
export function parseEbookMarkdown(source: string): EbookData {
|
||||
const html = marked.parse(source, { breaks: true, gfm: true }) as string;
|
||||
const lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');
|
||||
|
||||
let rawChunks = lazyHtml.split(/(?=<h1[\s>])/i).filter((c) => c.trim());
|
||||
if (rawChunks.length <= 1) {
|
||||
rawChunks = lazyHtml.split(/(?=<h2[\s>])/i).filter((c) => c.trim());
|
||||
}
|
||||
|
||||
const headers: string[] = [];
|
||||
const headerRegex = /<h1[^>]*>(.*?)<\/h1>/gi;
|
||||
let m;
|
||||
while ((m = headerRegex.exec(lazyHtml)) !== null) {
|
||||
headers.push(m[1].replace(/<[^>]+>/g, ""));
|
||||
}
|
||||
if (headers.length === 0) {
|
||||
const h2Regex = /<h2[^>]*>(.*?)<\/h2>/gi;
|
||||
while ((m = h2Regex.exec(lazyHtml)) !== null) {
|
||||
headers.push(m[1].replace(/<[^>]+>/g, ""));
|
||||
}
|
||||
}
|
||||
|
||||
const chunks: EbookChunk[] = rawChunks.map((chunkHtml) => {
|
||||
const imgCount = (chunkHtml.match(/<img\b/g) || []).length;
|
||||
const textLen = chunkHtml.replace(/<[^>]+>/g, "").length;
|
||||
const estimatedHeight = Math.max(300, Math.round(textLen * 0.6 + imgCount * 350));
|
||||
return { html: chunkHtml, estimatedHeight };
|
||||
});
|
||||
|
||||
return { chunks, headers };
|
||||
}
|
||||
25
app/vip/lib/payEnv.ts
Normal file
25
app/vip/lib/payEnv.ts
Normal file
@ -0,0 +1,25 @@
|
||||
/**
|
||||
* VIP pay env — thin re-export of shared @nomadro/pay (modular decoupling).
|
||||
* Prefer importing from @nomadro/pay in new code.
|
||||
*/
|
||||
export {
|
||||
isWeChat,
|
||||
isMobile,
|
||||
getPayEnv,
|
||||
getRecommendedChannel,
|
||||
mustUseWxPay,
|
||||
type PayEnv,
|
||||
type PayChannel,
|
||||
} from "@nomadro/pay";
|
||||
|
||||
import { getPayEnv as _getPayEnv, type PayEnv } from "@nomadro/pay";
|
||||
|
||||
export function getDeviceFromEnv(env: PayEnv): "pc" | "h5" | "wechat" {
|
||||
if (env === "wechat") return "wechat";
|
||||
return env === "pc" ? "pc" : "h5";
|
||||
}
|
||||
|
||||
/** @deprecated use getPayEnv from @nomadro/pay */
|
||||
export function detectPayEnv(): PayEnv {
|
||||
return _getPayEnv();
|
||||
}
|
||||
123
app/vip/lib/pocketbase/auth.ts
Normal file
123
app/vip/lib/pocketbase/auth.ts
Normal file
@ -0,0 +1,123 @@
|
||||
/**
|
||||
* PocketBase 认证服务 - 邮箱登录、注册
|
||||
*/
|
||||
|
||||
import { getPocketBaseConfig } from "@vip/config/services.config";
|
||||
import { PB_STORAGE_KEYS } from "./constants";
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AuthResult {
|
||||
token: string;
|
||||
record: AuthUser;
|
||||
}
|
||||
|
||||
function getPBUrl(): string {
|
||||
return getPocketBaseConfig().url;
|
||||
}
|
||||
|
||||
export async function pbLogin(
|
||||
identity: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const url = getPBUrl();
|
||||
const res = await fetch(`${url}/api/collections/users/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err?.message || "登录失败");
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!data?.token) throw new Error("登录响应异常");
|
||||
return { token: data.token, record: data.record };
|
||||
}
|
||||
|
||||
/** 从 PocketBase 错误响应中提取可读错误信息 */
|
||||
function parsePBError(err: { message?: string; data?: Record<string, { message?: string; code?: string }> }): string {
|
||||
const data = err?.data;
|
||||
if (data && typeof data === "object" && Object.keys(data).length > 0) {
|
||||
const first = Object.values(data)[0];
|
||||
if (first?.message) {
|
||||
const code = first.code;
|
||||
if (code === "validation_not_unique") {
|
||||
return "该邮箱已被注册,请直接登录";
|
||||
}
|
||||
if (code === "validation_required") {
|
||||
return "请填写必填项";
|
||||
}
|
||||
if (code?.startsWith("validation_")) {
|
||||
return first.message;
|
||||
}
|
||||
return first.message;
|
||||
}
|
||||
}
|
||||
if (err?.message === "Failed to create record.") {
|
||||
return "注册失败,该邮箱可能已被使用,请尝试直接登录";
|
||||
}
|
||||
return err?.message || "注册失败";
|
||||
}
|
||||
|
||||
export async function pbRegister(
|
||||
email: string,
|
||||
password: string,
|
||||
passwordConfirm: string
|
||||
): Promise<AuthResult> {
|
||||
const url = getPBUrl();
|
||||
const res = await fetch(`${url}/api/collections/users/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
passwordConfirm,
|
||||
live_allowed: true,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(parsePBError(err));
|
||||
}
|
||||
return pbLogin(email, password);
|
||||
}
|
||||
|
||||
export function pbSaveAuth(token: string, record: AuthUser): void {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.setItem(PB_STORAGE_KEYS.token, token);
|
||||
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
|
||||
}
|
||||
|
||||
/** 登出 - 清除本地存储和根域 Cookie */
|
||||
export async function pbLogout(): Promise<void> {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.removeItem(PB_STORAGE_KEYS.token);
|
||||
localStorage.removeItem(PB_STORAGE_KEYS.user);
|
||||
try {
|
||||
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoredUserEmail(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(PB_STORAGE_KEYS.user);
|
||||
if (!raw) return null;
|
||||
const user = JSON.parse(raw);
|
||||
return user?.email ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoredToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return localStorage.getItem(PB_STORAGE_KEYS.token);
|
||||
}
|
||||
1
app/vip/lib/pocketbase/config.ts
Normal file
1
app/vip/lib/pocketbase/config.ts
Normal file
@ -0,0 +1 @@
|
||||
export { getPocketBaseConfig } from "@vip/config/services.config";
|
||||
5
app/vip/lib/pocketbase/constants.ts
Normal file
5
app/vip/lib/pocketbase/constants.ts
Normal file
@ -0,0 +1,5 @@
|
||||
/** localStorage 存储 key */
|
||||
export const PB_STORAGE_KEYS = {
|
||||
token: "pb_token",
|
||||
user: "pb_user",
|
||||
} as const;
|
||||
11
app/vip/lib/pocketbase/index.ts
Normal file
11
app/vip/lib/pocketbase/index.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export {
|
||||
pbLogin,
|
||||
pbRegister,
|
||||
pbSaveAuth,
|
||||
pbLogout,
|
||||
getStoredUserEmail,
|
||||
getStoredToken,
|
||||
} from "./auth";
|
||||
export type { AuthUser, AuthResult } from "./auth";
|
||||
export { PB_STORAGE_KEYS } from "./constants";
|
||||
export { getPocketBaseConfig } from "./config";
|
||||
343
app/vip/lib/triggerPay.ts
Normal file
343
app/vip/lib/triggerPay.ts
Normal file
@ -0,0 +1,343 @@
|
||||
/**
|
||||
* 共享支付触发逻辑 - 与首页「立即加入」效果一致
|
||||
* 供首页、课程页、云手机页等所有「立即报名」按钮使用,直接发起支付,不跳转首页
|
||||
*
|
||||
* 校验逻辑:
|
||||
* - 页面有本地存储(登录资料 + paidType=vip)时,优先使用本地存储并立即展示;后台悄悄校验,若 user 被删或 VIP 被撤则更新本地状态
|
||||
* - 无身份标识和 VIP 权限等存储时,点击按钮直接进入支付流程,不校验本地 userId
|
||||
*/
|
||||
import { getPayEnv, getDeviceFromEnv } from "@vip/app/lib/payEnv";
|
||||
import { getPaymentConfig } from "@vip/config/services.config";
|
||||
|
||||
const ANONYMOUS_USER_COOKIE = "nomadvip_anon_uid";
|
||||
const ANONYMOUS_USER_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
|
||||
const PAY_ORDER_COOKIE = "nomadvip_pay_order";
|
||||
const PAY_ORDER_MAX_AGE = 60 * 15;
|
||||
const VIP_PAY_TEST_MODE_KEY = "vipPayTestMode";
|
||||
const PAY_LAUNCH_OVERLAY_ID = "nomadvip-pay-launch-overlay";
|
||||
|
||||
function getStorage(key: string): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return localStorage.getItem(key);
|
||||
}
|
||||
|
||||
function setStorage(key: string, value: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.setItem(key, value);
|
||||
}
|
||||
|
||||
function getCookie(name: string): string | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
function setAnonymousUserCookie(userId: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (!/^user\d+$/.test(userId)) return;
|
||||
const secure = window.location.protocol === "https:" ? "; Secure" : "";
|
||||
document.cookie = `${ANONYMOUS_USER_COOKIE}=${encodeURIComponent(
|
||||
userId
|
||||
)}; Path=/; Max-Age=${ANONYMOUS_USER_COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
|
||||
}
|
||||
|
||||
function setPayOrderCookie(orderId: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId) return;
|
||||
const secure = window.location.protocol === "https:" ? "; Secure" : "";
|
||||
document.cookie = `${PAY_ORDER_COOKIE}=${encodeURIComponent(
|
||||
`${normalizedOrderId}|${Date.now()}`
|
||||
)}; Path=/; Max-Age=${PAY_ORDER_MAX_AGE}; SameSite=Lax${secure}`;
|
||||
}
|
||||
|
||||
function getDisplayProfile() {
|
||||
const wechatNick = (getStorage("wechatNick") || "").trim();
|
||||
const userName = (getStorage("userName") || "").trim();
|
||||
const userEmail = (getStorage("userEmail") || "").trim();
|
||||
const wechatAvatar = (getStorage("wechatAvatar") || "").trim();
|
||||
const displayName = wechatNick || userName || userEmail || "当前用户";
|
||||
return { displayName, avatar: wechatAvatar || "" };
|
||||
}
|
||||
|
||||
function showPayLaunchOverlay(displayName: string, avatar?: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (!(avatar || "").trim()) return;
|
||||
const prev = document.getElementById(PAY_LAUNCH_OVERLAY_ID);
|
||||
if (prev) prev.remove();
|
||||
const safeName = displayName.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const safeAvatar = (avatar || "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] || c);
|
||||
const node = document.createElement("div");
|
||||
node.id = PAY_LAUNCH_OVERLAY_ID;
|
||||
node.style.cssText = "position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(15,23,42,.28);pointer-events:none;";
|
||||
node.innerHTML = `
|
||||
<div style="display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:12px;background:#0f172a;color:#e2e8f0;box-shadow:0 10px 30px rgba(2,6,23,.35);max-width:90vw;">
|
||||
<img src="${safeAvatar}" alt="${safeName}" style="width:30px;height:30px;border-radius:9999px;object-fit:cover;border:1px solid rgba(148,163,184,.5);" />
|
||||
<div style="font-size:13px;line-height:1.35;">
|
||||
<div style="font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:56vw;">开通对象:${safeName}</div>
|
||||
<div style="opacity:.88;">正在为你升级 VIP,马上进入支付...</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(node);
|
||||
window.setTimeout(() => {
|
||||
const current = document.getElementById(PAY_LAUNCH_OVERLAY_ID);
|
||||
if (current) current.remove();
|
||||
}, 2400);
|
||||
}
|
||||
|
||||
function savePendingOrder(orderId: string): void {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId) return;
|
||||
setPayOrderCookie(normalizedOrderId);
|
||||
setStorage(PAY_ORDER_COOKIE, `${normalizedOrderId}|${Date.now()}`);
|
||||
}
|
||||
|
||||
function getStoredAnonymousUserId(): string | null {
|
||||
const memosAccount = getStorage("memosAccount");
|
||||
if (memosAccount && /^user\d+$/.test(memosAccount)) return memosAccount;
|
||||
const userId = getStorage("userId");
|
||||
if (userId && /^user\d+$/.test(userId)) return userId;
|
||||
const cookieUserId = getCookie(ANONYMOUS_USER_COOKIE);
|
||||
if (cookieUserId && /^user\d+$/.test(cookieUserId)) {
|
||||
setStorage("memosAccount", cookieUserId);
|
||||
return cookieUserId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 同步获取 userId,用于微信内立即表单提交,避免异步导致手势失效 */
|
||||
function getOrCreateUserIdSync(): string {
|
||||
const anonymousUserId = getStoredAnonymousUserId();
|
||||
if (anonymousUserId) {
|
||||
setStorage("userId", anonymousUserId);
|
||||
setAnonymousUserCookie(anonymousUserId);
|
||||
return anonymousUserId;
|
||||
}
|
||||
let userId = getStorage("userId");
|
||||
if (userId?.startsWith("{") && userId.includes("data")) {
|
||||
try {
|
||||
const parsed = JSON.parse(userId) as { data?: string };
|
||||
if (parsed?.data) {
|
||||
userId = parsed.data;
|
||||
setStorage("userId", userId);
|
||||
}
|
||||
} catch {
|
||||
userId = null;
|
||||
}
|
||||
}
|
||||
if (!userId) {
|
||||
userId = `user${Date.now()}`;
|
||||
setStorage("userId", userId);
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
async function getOrCreateUserId(): Promise<string> {
|
||||
const syncId = getOrCreateUserIdSync();
|
||||
if (syncId && !syncId.startsWith("user")) {
|
||||
return syncId;
|
||||
}
|
||||
try {
|
||||
const meRes = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" });
|
||||
const meData = await meRes.json();
|
||||
if (meData?.user?.id) {
|
||||
setStorage("userId", meData.user.id);
|
||||
return meData.user.id;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return syncId;
|
||||
}
|
||||
|
||||
function redirectToPayZpay(params: {
|
||||
user_id: string;
|
||||
wechat_userid?: string;
|
||||
wechat_nick?: string;
|
||||
wechat_avatar?: string;
|
||||
return_url: string;
|
||||
total_fee: number;
|
||||
type: string;
|
||||
channel: "alipay" | "wxpay";
|
||||
device: "pc" | "h5" | "wechat";
|
||||
}) {
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = "/api/pay";
|
||||
form.target = "_self";
|
||||
form.style.display = "none";
|
||||
const fields: [string, string][] = [
|
||||
["user_id", params.user_id],
|
||||
...(params.wechat_userid ? [["wechat_userid", params.wechat_userid] as [string, string]] : []),
|
||||
...(params.wechat_nick ? [["wechat_nick", params.wechat_nick] as [string, string]] : []),
|
||||
...(params.wechat_avatar ? [["wechat_avatar", params.wechat_avatar] as [string, string]] : []),
|
||||
["return_url", params.return_url],
|
||||
["total_fee", String(params.total_fee)],
|
||||
["type", params.type],
|
||||
["channel", params.channel],
|
||||
["device", params.device],
|
||||
["provider", "zpay"],
|
||||
["html", "1"],
|
||||
];
|
||||
fields.forEach(([k, v]) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = v;
|
||||
form.appendChild(input);
|
||||
});
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
}
|
||||
|
||||
async function redirectToPayZpayH5(
|
||||
params: {
|
||||
user_id: string;
|
||||
wechat_userid?: string;
|
||||
wechat_nick?: string;
|
||||
wechat_avatar?: string;
|
||||
return_url: string;
|
||||
total_fee: number;
|
||||
type: string;
|
||||
channel: "alipay" | "wxpay";
|
||||
},
|
||||
onPendingOrder?: (orderId: string) => void
|
||||
): Promise<string | null> {
|
||||
const res = await fetch("/api/pay", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...params,
|
||||
device: "h5",
|
||||
provider: "zpay",
|
||||
html: "0",
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!data?.ok) {
|
||||
alert(data?.error || "支付发起失败");
|
||||
return null;
|
||||
}
|
||||
const hasRedirect = !!data?.redirect_url;
|
||||
const hasParams = !!data?.params && !!data?.payUrl;
|
||||
if (!hasRedirect && !hasParams) {
|
||||
alert(data?.error || "支付发起失败");
|
||||
return null;
|
||||
}
|
||||
const orderId = data?.order_id?.trim() || null;
|
||||
if (orderId) {
|
||||
savePendingOrder(orderId);
|
||||
onPendingOrder?.(orderId);
|
||||
}
|
||||
if (data?.redirect_url) {
|
||||
window.location.href = data.redirect_url;
|
||||
return orderId;
|
||||
}
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = data.payUrl;
|
||||
form.target = "_self";
|
||||
form.style.display = "none";
|
||||
for (const [k, v] of Object.entries(data.params as Record<string, string>)) {
|
||||
if (v == null) continue;
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = String(v);
|
||||
form.appendChild(input);
|
||||
}
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
document.body.removeChild(form);
|
||||
return orderId;
|
||||
}
|
||||
|
||||
/** 微信内:同步表单 POST 到 /api/pay,避免异步 fetch 后 form.submit 被微信拦截 */
|
||||
function payWechatXorpaySync(params: {
|
||||
user_id: string;
|
||||
wechat_userid?: string;
|
||||
wechat_nick?: string;
|
||||
wechat_avatar?: string;
|
||||
return_url: string;
|
||||
total_fee: number;
|
||||
type: string;
|
||||
channel: "alipay" | "wxpay";
|
||||
}) {
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = "/api/pay";
|
||||
form.target = "_self";
|
||||
form.style.display = "none";
|
||||
const fields: [string, string][] = [
|
||||
["user_id", params.user_id],
|
||||
...(params.wechat_userid ? [["wechat_userid", params.wechat_userid] as [string, string]] : []),
|
||||
...(params.wechat_nick ? [["wechat_nick", params.wechat_nick] as [string, string]] : []),
|
||||
...(params.wechat_avatar ? [["wechat_avatar", params.wechat_avatar] as [string, string]] : []),
|
||||
["return_url", params.return_url],
|
||||
["total_fee", String(params.total_fee)],
|
||||
["type", params.type],
|
||||
["channel", params.channel],
|
||||
["device", "wechat"],
|
||||
["provider", "xorpay"],
|
||||
["html", "1"],
|
||||
];
|
||||
fields.forEach(([k, v]) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = v;
|
||||
form.appendChild(input);
|
||||
});
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发支付 - 与首页「立即加入」效果一致,直接发起支付流程
|
||||
* @param onPendingOrder 可选,H5 支付时收到 order_id 的回调(用于轮询)
|
||||
*/
|
||||
export async function triggerPay(
|
||||
onPendingOrder?: (orderId: string) => void
|
||||
): Promise<void> {
|
||||
const userId =
|
||||
typeof navigator !== "undefined" && /MicroMessenger/i.test(navigator.userAgent)
|
||||
? getOrCreateUserIdSync()
|
||||
: await getOrCreateUserId();
|
||||
if (/^user\d+$/.test(userId)) {
|
||||
setStorage("memosAccount", userId);
|
||||
setStorage("userId", userId);
|
||||
setAnonymousUserCookie(userId);
|
||||
}
|
||||
const returnUrl = `${window.location.origin}/paid`;
|
||||
const env = getPayEnv();
|
||||
const device = getDeviceFromEnv(env);
|
||||
const wechatUserId =
|
||||
(getStorage("wechatUserId") || "").trim() ||
|
||||
(getStorage("userid") || "").trim();
|
||||
const isPayTestMode = getStorage(VIP_PAY_TEST_MODE_KEY) === "1";
|
||||
const totalFee = isPayTestMode ? 100 : getPaymentConfig().defaultAmount ?? 8800;
|
||||
const profile = getDisplayProfile();
|
||||
const shouldShowLaunchOverlay =
|
||||
device !== "wechat" && !!(profile.avatar || "").trim();
|
||||
if (shouldShowLaunchOverlay) {
|
||||
showPayLaunchOverlay(profile.displayName, profile.avatar);
|
||||
}
|
||||
const base = {
|
||||
user_id: userId,
|
||||
wechat_userid: wechatUserId || undefined,
|
||||
wechat_nick: profile.displayName,
|
||||
wechat_avatar: profile.avatar || undefined,
|
||||
return_url: returnUrl,
|
||||
total_fee: totalFee,
|
||||
type: "vip",
|
||||
channel: "wxpay" as const,
|
||||
};
|
||||
if (device === "wechat") {
|
||||
payWechatXorpaySync(base);
|
||||
} else if (device === "h5") {
|
||||
await redirectToPayZpayH5(base, onPendingOrder);
|
||||
} else {
|
||||
redirectToPayZpay({ ...base, device });
|
||||
}
|
||||
}
|
||||
158
app/vip/lib/usePayStatusPoll.ts
Normal file
158
app/vip/lib/usePayStatusPoll.ts
Normal file
@ -0,0 +1,158 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const COOKIE_NAME = "nomadvip_pay_order";
|
||||
const STORAGE_NAME = "nomadvip_pay_order";
|
||||
const POLL_INTERVAL_MS = 1200;
|
||||
const MAX_POLLS = 30;
|
||||
const MAX_AGE_MS = 15 * 60 * 1000;
|
||||
|
||||
function getCookie(name: string): string | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
function clearCookie(name: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
document.cookie = `${name}=; path=/; max-age=0`;
|
||||
}
|
||||
|
||||
function getStorage(name: string): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(name);
|
||||
}
|
||||
|
||||
function removeStorage(name: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(name);
|
||||
}
|
||||
|
||||
function clearPendingOrder(): void {
|
||||
clearCookie(COOKIE_NAME);
|
||||
removeStorage(STORAGE_NAME);
|
||||
}
|
||||
|
||||
function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
||||
if (!raw?.trim()) return [null, false];
|
||||
const parts = raw.split("|");
|
||||
const orderId = parts[0]?.trim() || raw.trim();
|
||||
const ts = parts[1] ? parseInt(parts[1], 10) : NaN;
|
||||
if (!orderId) return [null, false];
|
||||
if (Number.isNaN(ts)) return [orderId, false];
|
||||
if (Date.now() - ts > MAX_AGE_MS) return [orderId, false];
|
||||
return [orderId, true];
|
||||
}
|
||||
|
||||
export function usePayStatusPoll(
|
||||
onPaid: (orderId?: string) => void,
|
||||
onTimeout?: () => void,
|
||||
orderIdFromState?: string | null
|
||||
): boolean {
|
||||
const [polling, setPolling] = useState(false);
|
||||
const onPaidRef = useRef(onPaid);
|
||||
const onTimeoutRef = useRef(onTimeout);
|
||||
onPaidRef.current = onPaid;
|
||||
onTimeoutRef.current = onTimeout;
|
||||
|
||||
useEffect(() => {
|
||||
const orderId =
|
||||
orderIdFromState !== undefined
|
||||
? orderIdFromState?.trim() || null
|
||||
: (() => {
|
||||
const cookieRaw = getCookie(COOKIE_NAME);
|
||||
const [cookieOrderId, cookieValid] = parsePayOrderCookie(cookieRaw);
|
||||
if (cookieValid) {
|
||||
return cookieOrderId;
|
||||
}
|
||||
|
||||
const storageRaw = getStorage(STORAGE_NAME);
|
||||
const [storageOrderId, storageValid] = parsePayOrderCookie(storageRaw);
|
||||
return storageValid ? storageOrderId : null;
|
||||
})();
|
||||
|
||||
if (!orderId) {
|
||||
if (
|
||||
orderIdFromState === undefined &&
|
||||
(getCookie(COOKIE_NAME) || getStorage(STORAGE_NAME))
|
||||
) {
|
||||
clearPendingOrder();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setPolling(true);
|
||||
let attempts = 0;
|
||||
let stopped = false;
|
||||
let timer: number | undefined;
|
||||
let inFlight = false;
|
||||
|
||||
const stop = () => {
|
||||
stopped = true;
|
||||
if (timer) window.clearTimeout(timer);
|
||||
};
|
||||
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
if (inFlight) {
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
if (attempts > MAX_POLLS) {
|
||||
stop();
|
||||
clearPendingOrder();
|
||||
setPolling(false);
|
||||
onTimeoutRef.current?.();
|
||||
return;
|
||||
}
|
||||
|
||||
inFlight = true;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/pay/status?order_id=${encodeURIComponent(orderId)}`,
|
||||
{ cache: "no-store" }
|
||||
);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (data?.ok && data?.paid) {
|
||||
stop();
|
||||
clearPendingOrder();
|
||||
setPolling(false);
|
||||
onPaidRef.current(orderId);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// ignore and continue polling
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
|
||||
scheduleNext();
|
||||
};
|
||||
|
||||
const scheduleNext = () => {
|
||||
if (stopped) return;
|
||||
timer = window.setTimeout(tick, POLL_INTERVAL_MS);
|
||||
};
|
||||
|
||||
const handleResume = () => {
|
||||
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
||||
return;
|
||||
}
|
||||
void tick();
|
||||
};
|
||||
|
||||
document.addEventListener("visibilitychange", handleResume);
|
||||
window.addEventListener("pageshow", handleResume);
|
||||
window.addEventListener("focus", handleResume);
|
||||
void tick();
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleResume);
|
||||
window.removeEventListener("pageshow", handleResume);
|
||||
window.removeEventListener("focus", handleResume);
|
||||
stop();
|
||||
};
|
||||
}, [orderIdFromState]);
|
||||
|
||||
return polling;
|
||||
}
|
||||
70
app/vip/lib/xorpayStatus.ts
Normal file
70
app/vip/lib/xorpayStatus.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import { createHash } from "crypto";
|
||||
|
||||
const XORPAY_AID = process.env.XORPAY_AID || "8220";
|
||||
const XORPAY_SECRET =
|
||||
process.env.XORPAY_SECRET || "afcacd99570945f88de62624aaa3578e";
|
||||
const XORPAY_QUERY_URL =
|
||||
process.env.XORPAY_QUERY_URL || "https://xorpay.com/api/query2";
|
||||
const XORPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.XORPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type XorPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
/** 网关返回的实付金额(元),有则用于换算分;无则由调用方回退默认金额 */
|
||||
pay_price?: string | number | null;
|
||||
};
|
||||
|
||||
function buildXorPaySign(orderId: string): string {
|
||||
return createHash("md5")
|
||||
.update(`${orderId}${XORPAY_SECRET}`, "utf8")
|
||||
.digest("hex")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export async function queryXorPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = XORPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<XorPayStatusResult | null> {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId || !XORPAY_AID || !XORPAY_SECRET) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(
|
||||
`${XORPAY_QUERY_URL.replace(/\/$/, "")}/${encodeURIComponent(XORPAY_AID)}`
|
||||
);
|
||||
url.searchParams.set("order_id", normalizedOrderId);
|
||||
url.searchParams.set("sign", buildXorPaySign(normalizedOrderId));
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString(), {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const status = String(data?.status || "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
|
||||
return {
|
||||
ok: res.ok,
|
||||
paid: res.ok && (status === "payed" || status === "success"),
|
||||
status,
|
||||
url: url.toString(),
|
||||
error: res.ok ? undefined : `status=${res.status}`,
|
||||
pay_price: data?.pay_price ?? data?.price ?? null,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
65
app/vip/lib/zpayStatus.ts
Normal file
65
app/vip/lib/zpayStatus.ts
Normal file
@ -0,0 +1,65 @@
|
||||
const ZPAY_PID = process.env.ZPAY_PID || "2025121809351743";
|
||||
const ZPAY_KEY = process.env.ZPAY_KEY || "tpEi7wWIWI2kXiYVTpIG6j7it0mjVW89";
|
||||
const ZPAY_QUERY_URL =
|
||||
process.env.ZPAY_QUERY_URL || "https://zpayz.cn/api.php";
|
||||
const ZPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.ZPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type ZPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
/** 网关返回的实付金额(元),字段名因接口而异 */
|
||||
pay_price?: string | number | null;
|
||||
};
|
||||
|
||||
export async function queryZPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = ZPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<ZPayStatusResult | null> {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId || !ZPAY_PID || !ZPAY_KEY) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(ZPAY_QUERY_URL);
|
||||
url.searchParams.set("act", "order");
|
||||
url.searchParams.set("pid", ZPAY_PID);
|
||||
url.searchParams.set("key", ZPAY_KEY);
|
||||
url.searchParams.set("out_trade_no", normalizedOrderId);
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString(), {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
const code = String(data?.code || "").trim();
|
||||
const status = String(data?.status || "").trim();
|
||||
|
||||
const payPrice =
|
||||
data?.pay_price ?? data?.money ?? data?.price ?? data?.amount ?? null;
|
||||
|
||||
return {
|
||||
ok: res.ok,
|
||||
paid: res.ok && code === "1" && status === "1",
|
||||
status,
|
||||
url: url.toString(),
|
||||
error:
|
||||
res.ok && code === "1"
|
||||
? undefined
|
||||
: String(data?.msg || `status=${res.status}`),
|
||||
pay_price: payPrice,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
9
app/vip/page.tsx
Normal file
9
app/vip/page.tsx
Normal file
@ -0,0 +1,9 @@
|
||||
import { HomeClientLoader } from "./HomeClientLoader";
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<HomeClientLoader />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
336
app/vip/paid/page.tsx
Normal file
336
app/vip/paid/page.tsx
Normal file
@ -0,0 +1,336 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { usePayStatusPoll } from "@vip/app/lib/usePayStatusPoll";
|
||||
|
||||
const COOKIE_NAME = "nomadvip_pay_order";
|
||||
const DEFAULT_PASSWORD = "12345678";
|
||||
|
||||
function getCookie(name: string): string | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
function isAnonymousUserId(value: string | null | undefined): value is string {
|
||||
return !!value && /^user\d+$/.test(value);
|
||||
}
|
||||
|
||||
function parseUserIdFromOrderId(orderId: string): string {
|
||||
if (!orderId?.includes("_order_")) return "";
|
||||
const prefix = orderId.split("_order_")[0];
|
||||
const parts = prefix.split("_");
|
||||
return parts.length >= 2 ? parts.slice(0, -1).join("_") : "";
|
||||
}
|
||||
|
||||
function getOrderIdFromPage(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const fromUrl =
|
||||
params.get("order_id") || params.get("out_trade_no") || params.get("orderId");
|
||||
if (fromUrl?.trim()) return fromUrl.trim();
|
||||
const raw = getCookie(COOKIE_NAME);
|
||||
if (!raw?.trim()) return null;
|
||||
return raw.split("|")[0]?.trim() || null;
|
||||
}
|
||||
|
||||
function persistAnonymousVip(userId: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.setItem("userId", userId);
|
||||
localStorage.setItem("memosAccount", userId);
|
||||
localStorage.setItem("paidType", "vip");
|
||||
if (localStorage.getItem("emailLinked") !== "1" && !localStorage.getItem("userEmail")) {
|
||||
localStorage.setItem("userName", userId);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmOrder(orderId: string, userId: string): Promise<boolean> {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
try {
|
||||
const res = await fetch("/api/pay/confirm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ order_id: orderId, user_id: userId }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (data?.ok) return true;
|
||||
} catch (error) {
|
||||
console.error("pay/confirm request error:", error);
|
||||
}
|
||||
|
||||
if (attempt < 2) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function SuccessPanel({ anonymousUserId }: { anonymousUserId: string | null }) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!anonymousUserId || !isAnonymousUserId(anonymousUserId)) {
|
||||
const timer = window.setTimeout(() => {
|
||||
window.location.href = "/";
|
||||
}, 600);
|
||||
return () => window.clearTimeout(timer);
|
||||
}
|
||||
}, [anonymousUserId]);
|
||||
|
||||
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
if (!normalizedEmail || !anonymousUserId) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/link-email", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: normalizedEmail,
|
||||
password: DEFAULT_PASSWORD,
|
||||
anonymousUserId,
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok || !data?.ok || !data?.token || !data?.record?.id) {
|
||||
setError(data?.error || "绑定邮箱失败");
|
||||
return;
|
||||
}
|
||||
|
||||
const { pbSaveAuth } = await import("@vip/app/lib/pocketbase");
|
||||
pbSaveAuth(data.token, data.record);
|
||||
|
||||
await fetch("/api/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
token: data.token,
|
||||
record: data.record,
|
||||
anonymousUserId,
|
||||
}),
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
localStorage.setItem("memosAccount", anonymousUserId);
|
||||
localStorage.setItem("userId", data.record.id);
|
||||
localStorage.setItem("userEmail", data.record.email || normalizedEmail);
|
||||
localStorage.setItem("userName", data.record.email || normalizedEmail);
|
||||
localStorage.setItem("emailLinked", "1");
|
||||
localStorage.setItem("paidType", "vip");
|
||||
|
||||
window.location.href = "/";
|
||||
} catch (submitError) {
|
||||
console.error("link-email failed:", submitError);
|
||||
setError("绑定邮箱失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-[#f0f4f8] px-4">
|
||||
<div
|
||||
className="animate__animated animate__zoomIn w-full max-w-md rounded-2xl bg-white p-10 text-center shadow-lg"
|
||||
style={{ animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-emerald-50 text-5xl">
|
||||
✓
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold text-slate-800">支付成功</h2>
|
||||
<p className="mt-3 text-slate-500">
|
||||
最后一步,绑定邮箱后再进入 VIP。后续可以在多个站点共用同一账号。
|
||||
</p>
|
||||
{isAnonymousUserId(anonymousUserId) ? (
|
||||
<form onSubmit={handleSubmit} className="mt-6 text-left">
|
||||
<p className="mb-2 text-sm text-slate-600">
|
||||
默认密码为 {DEFAULT_PASSWORD}。绑定后会把当前匿名会员迁移到统一邮箱账号。
|
||||
</p>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
placeholder="your@email.com"
|
||||
required
|
||||
disabled={loading}
|
||||
className="mb-3 w-full rounded-lg border border-slate-300 px-4 py-2 text-slate-800"
|
||||
/>
|
||||
{error ? <p className="mb-3 text-sm text-red-500">{error}</p> : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-full bg-sky-500 px-6 py-2 font-semibold text-white hover:bg-sky-600 disabled:opacity-60"
|
||||
>
|
||||
{loading ? "处理中..." : "绑定邮箱并进入 VIP"}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<p className="mt-2 text-xs text-slate-400">正在返回首页</p>
|
||||
<a
|
||||
href="/"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
window.location.href = "/";
|
||||
}}
|
||||
className="mt-8 inline-flex items-center gap-2 rounded-full bg-sky-500 px-8 py-3 font-semibold text-white transition-colors hover:bg-sky-600"
|
||||
>
|
||||
返回首页
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PaidPage() {
|
||||
const [status, setStatus] = useState<
|
||||
"pending" | "success" | "fail" | "confirm_fail"
|
||||
>("pending");
|
||||
const [confirmedUserId, setConfirmedUserId] = useState<string | null>(null);
|
||||
const orderIdFromUrlOrCookie = getOrderIdFromPage();
|
||||
|
||||
usePayStatusPoll(
|
||||
async (orderId) => {
|
||||
const finalOrderId = (orderId || orderIdFromUrlOrCookie || "").trim();
|
||||
const candidateUserId =
|
||||
parseUserIdFromOrderId(finalOrderId) || localStorage.getItem("userId");
|
||||
|
||||
if (!finalOrderId || !candidateUserId) {
|
||||
setStatus("confirm_fail");
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = await confirmOrder(finalOrderId, candidateUserId);
|
||||
if (confirmed) {
|
||||
persistAnonymousVip(candidateUserId);
|
||||
setConfirmedUserId(candidateUserId);
|
||||
}
|
||||
setStatus(confirmed ? "success" : "confirm_fail");
|
||||
},
|
||||
() => {
|
||||
window.location.href = "/";
|
||||
},
|
||||
orderIdFromUrlOrCookie
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get("fail") === "1") {
|
||||
setStatus("fail");
|
||||
return;
|
||||
}
|
||||
|
||||
if (params.get("paid") !== "1") {
|
||||
return;
|
||||
}
|
||||
|
||||
const orderId = getOrderIdFromPage();
|
||||
const candidateUserId =
|
||||
(orderId ? parseUserIdFromOrderId(orderId) : "") || localStorage.getItem("userId");
|
||||
|
||||
if (!orderId || !candidateUserId) {
|
||||
setStatus("confirm_fail");
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
const confirmed = await confirmOrder(orderId, candidateUserId);
|
||||
if (confirmed) {
|
||||
persistAnonymousVip(candidateUserId);
|
||||
setConfirmedUserId(candidateUserId);
|
||||
}
|
||||
setStatus(confirmed ? "success" : "confirm_fail");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
if (status === "pending") {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-[#f0f4f8] px-4">
|
||||
<div
|
||||
className="animate__animated animate__fadeInUp w-full max-w-md rounded-2xl bg-white p-10 text-center shadow-lg"
|
||||
style={{ animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mx-auto mb-5 flex h-16 w-16 animate-spin items-center justify-center rounded-full border-4 border-sky-200 border-t-sky-500" />
|
||||
<h2 className="text-xl font-bold text-slate-800">正在确认支付结果</h2>
|
||||
<p className="mt-3 text-sm text-slate-500">
|
||||
正在写入会员记录,请稍候。
|
||||
<br />
|
||||
支付完成后会继续进入邮箱绑定。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === "success") {
|
||||
const anonymousUserId =
|
||||
confirmedUserId ||
|
||||
(typeof window !== "undefined" ? localStorage.getItem("userId") : null);
|
||||
return <SuccessPanel anonymousUserId={anonymousUserId} />;
|
||||
}
|
||||
|
||||
if (status === "confirm_fail") {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-[#f0f4f8] px-4">
|
||||
<div
|
||||
className="animate__animated animate__zoomIn w-full max-w-md rounded-2xl bg-white p-10 text-center shadow-lg"
|
||||
style={{ animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-amber-50 text-5xl">
|
||||
!
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold text-slate-800">支付已确认,权益开通中</h2>
|
||||
<p className="mt-3 text-slate-500">
|
||||
订单已支付,但会员写入可能有延迟。请稍后刷新首页,或联系管理员处理。
|
||||
</p>
|
||||
<a
|
||||
href="/"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
window.location.href = "/";
|
||||
}}
|
||||
className="mt-8 inline-flex items-center gap-2 rounded-full bg-sky-500 px-8 py-3 font-semibold text-white transition-colors hover:bg-sky-600"
|
||||
>
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-[#f0f4f8] px-4">
|
||||
<div
|
||||
className="animate__animated animate__zoomIn w-full max-w-md rounded-2xl bg-white p-10 text-center shadow-lg"
|
||||
style={{ animationFillMode: "both" }}
|
||||
>
|
||||
<div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-rose-50 text-5xl">
|
||||
!
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold text-slate-800">支付未完成</h2>
|
||||
<p className="mt-3 text-slate-500">
|
||||
当前没有确认到成功支付记录。你可以返回首页重新发起支付。
|
||||
</p>
|
||||
<a
|
||||
href="/"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
window.location.href = "/";
|
||||
}}
|
||||
className="mt-8 inline-flex items-center gap-2 rounded-full bg-sky-500 px-8 py-3 font-semibold text-white transition-colors hover:bg-sky-600"
|
||||
>
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
app/vip/providers/ThemeProvider.tsx
Normal file
84
app/vip/providers/ThemeProvider.tsx
Normal file
@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
export type ThemeMode = "light" | "dark" | "system";
|
||||
|
||||
type ThemeContextValue = {
|
||||
theme: ThemeMode;
|
||||
resolvedTheme: "light" | "dark";
|
||||
setTheme: (theme: ThemeMode) => void;
|
||||
};
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
const STORAGE_KEY = "nomadvip-theme";
|
||||
|
||||
function getSystemTheme(): "light" | "dark" {
|
||||
if (typeof window === "undefined") return "light";
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
}
|
||||
|
||||
function getStoredTheme(): ThemeMode {
|
||||
if (typeof window === "undefined") return "system";
|
||||
return (localStorage.getItem(STORAGE_KEY) as ThemeMode) || "system";
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<ThemeMode>("system");
|
||||
const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">("light");
|
||||
|
||||
const applyTheme = useCallback((mode: "light" | "dark") => {
|
||||
const root = document.documentElement;
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(mode);
|
||||
setResolvedTheme(mode);
|
||||
}, []);
|
||||
|
||||
const setTheme = useCallback(
|
||||
(newTheme: ThemeMode) => {
|
||||
setThemeState(newTheme);
|
||||
localStorage.setItem(STORAGE_KEY, newTheme);
|
||||
const resolved =
|
||||
newTheme === "system" ? getSystemTheme() : newTheme;
|
||||
applyTheme(resolved);
|
||||
},
|
||||
[applyTheme]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = getStoredTheme();
|
||||
setThemeState(stored);
|
||||
const resolved = stored === "system" ? getSystemTheme() : stored;
|
||||
applyTheme(resolved);
|
||||
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const handler = () => {
|
||||
if (getStoredTheme() === "system") {
|
||||
applyTheme(media.matches ? "dark" : "light");
|
||||
}
|
||||
};
|
||||
media.addEventListener("change", handler);
|
||||
return () => media.removeEventListener("change", handler);
|
||||
}, [applyTheme]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const ctx = useContext(ThemeContext);
|
||||
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
|
||||
return ctx;
|
||||
}
|
||||
10
app/vip/theme-init.ts
Normal file
10
app/vip/theme-init.ts
Normal file
@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 主题初始化 - 在 React 水合前执行,避免主题闪烁
|
||||
*/
|
||||
export const themeInitScript = `
|
||||
(function() {
|
||||
var theme = localStorage.getItem('nomadvip-theme');
|
||||
var resolved = theme === 'light' ? 'light' : (theme === 'dark' ? 'dark' : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
|
||||
document.documentElement.classList.add(resolved);
|
||||
})();
|
||||
`;
|
||||
27
app/vip/topic/[topicId]/layout.tsx
Normal file
27
app/vip/topic/[topicId]/layout.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ topicId: string }>;
|
||||
}): Promise<Metadata> {
|
||||
const { topicId } = await params;
|
||||
const titles: Record<string, string> = {
|
||||
cloudphone: "云手机 | 低成本自建云手机",
|
||||
livestream: "无人直播 | TikTok/YouTube 24小时自动化",
|
||||
indie: "独立开发 | 课程筹备",
|
||||
aiagent: "AI Agent | 课程筹备",
|
||||
};
|
||||
return {
|
||||
title: titles[topicId] ?? "模块 | 异度星球",
|
||||
description: "异度星球 VIP 会员专属视频教程模块",
|
||||
};
|
||||
}
|
||||
|
||||
export default function TopicLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
54
app/vip/topic/[topicId]/page.tsx
Normal file
54
app/vip/topic/[topicId]/page.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { TopicHeader } from "../components/TopicHeader";
|
||||
import { TopicBreadcrumb } from "../components/TopicBreadcrumb";
|
||||
import { TopicHero } from "../components/TopicHero";
|
||||
import { TopicCurriculum } from "../components/TopicCurriculum";
|
||||
import { TopicComingSoon } from "../components/TopicComingSoon";
|
||||
import { TopicFooter } from "../components/TopicFooter";
|
||||
import { getTopicConfig } from "../config";
|
||||
import { ChatFloatButton } from "@vip/app/cloudphone/components/ChatFloatButton";
|
||||
|
||||
export default function TopicPage() {
|
||||
const params = useParams();
|
||||
const topicId = String(params?.topicId ?? "");
|
||||
const config = getTopicConfig(topicId);
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<TopicHeader topicId="cloudphone" />
|
||||
<main className="pt-20 pb-16">
|
||||
<div className="mx-auto max-w-4xl px-4 py-16 text-center">
|
||||
<h1 className="mb-4 text-2xl font-bold">模块不存在</h1>
|
||||
<p className="mb-6 text-[var(--muted-foreground)]">请检查链接或返回首页</p>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
← 返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
|
||||
<TopicHeader topicId={topicId} />
|
||||
<ChatFloatButton />
|
||||
<main>
|
||||
<div className="mx-auto max-w-6xl px-4 pt-20 sm:px-6 md:px-6">
|
||||
<TopicBreadcrumb topicId={topicId} />
|
||||
</div>
|
||||
<TopicHero topicId={topicId} />
|
||||
<TopicCurriculum topicId={topicId} />
|
||||
<TopicComingSoon topicId={topicId} />
|
||||
<TopicFooter topicId={topicId} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
30
app/vip/topic/components/TopicBreadcrumb.tsx
Normal file
30
app/vip/topic/components/TopicBreadcrumb.tsx
Normal file
@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { getTopicConfig } from "../config";
|
||||
|
||||
type TopicBreadcrumbProps = {
|
||||
topicId: string;
|
||||
};
|
||||
|
||||
export function TopicBreadcrumb({ topicId }: TopicBreadcrumbProps) {
|
||||
const config = getTopicConfig(topicId);
|
||||
if (!config) return null;
|
||||
|
||||
return (
|
||||
<nav
|
||||
className="mb-6 flex flex-wrap items-center gap-2 text-sm text-[var(--muted-foreground)]"
|
||||
aria-label="面包屑"
|
||||
>
|
||||
<Link href="/" className="transition hover:text-[var(--foreground)]">
|
||||
首页
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<Link href="/#topics" className="transition hover:text-[var(--foreground)]">
|
||||
模块
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span className="text-[var(--foreground)] font-medium">{config.title}</span>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
31
app/vip/topic/components/TopicComingSoon.tsx
Normal file
31
app/vip/topic/components/TopicComingSoon.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { getTopicConfig } from "../config";
|
||||
|
||||
type TopicComingSoonProps = {
|
||||
topicId: string;
|
||||
};
|
||||
|
||||
export function TopicComingSoon({ topicId }: TopicComingSoonProps) {
|
||||
const config = getTopicConfig(topicId);
|
||||
if (!config?.externalUrl) return null;
|
||||
|
||||
return (
|
||||
<section className="border-t border-[var(--border)] py-16 md:py-24">
|
||||
<div className="mx-auto max-w-2xl px-4 text-center sm:px-6">
|
||||
<div className="mb-6 text-6xl">{config.icon}</div>
|
||||
<h2 className="mb-4 text-xl font-bold sm:text-2xl">课程筹备</h2>
|
||||
<p className="mb-8 text-[var(--muted-foreground)]">{config.desc}</p>
|
||||
<Link
|
||||
href={config.externalUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
了解更多 →
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
260
app/vip/topic/components/TopicCurriculum.tsx
Normal file
260
app/vip/topic/components/TopicCurriculum.tsx
Normal file
@ -0,0 +1,260 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { getTopicCurriculum } from "../config";
|
||||
import { canWatchLesson, isPaid } from "@vip/app/cloudphone/lib/payment";
|
||||
import { isBookmarked, toggleBookmark, getBookmarks, getCompletedLessons } from "@vip/app/cloudphone/lib/learning";
|
||||
|
||||
type TopicCurriculumProps = {
|
||||
topicId: string;
|
||||
};
|
||||
|
||||
export function TopicCurriculum({ topicId }: TopicCurriculumProps) {
|
||||
const [expanded, setExpanded] = useState<Record<number, boolean>>({});
|
||||
const [bookmarks, setBookmarks] = useState<Set<string>>(new Set());
|
||||
const [completed, setCompleted] = useState<Set<string>>(new Set());
|
||||
const [paid, setPaid] = useState(false);
|
||||
const [showUpdatingModal, setShowUpdatingModal] = useState(false);
|
||||
const [updatingLessonName, setUpdatingLessonName] = useState("");
|
||||
|
||||
const curriculum = getTopicCurriculum(topicId);
|
||||
|
||||
useEffect(() => {
|
||||
setBookmarks(getBookmarks());
|
||||
setCompleted(getCompletedLessons());
|
||||
setPaid(isPaid());
|
||||
const onB = () => setBookmarks(getBookmarks());
|
||||
const onP = () => setCompleted(getCompletedLessons());
|
||||
const onPayUpdate = () => setPaid(isPaid());
|
||||
window.addEventListener("learning:bookmarks", onB);
|
||||
window.addEventListener("learning:progress", onP);
|
||||
window.addEventListener("pay:updated", onPayUpdate);
|
||||
return () => {
|
||||
window.removeEventListener("learning:bookmarks", onB);
|
||||
window.removeEventListener("learning:progress", onP);
|
||||
window.removeEventListener("pay:updated", onPayUpdate);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const curr = getTopicCurriculum(topicId);
|
||||
if (curr?.modules?.length) {
|
||||
setExpanded((prev) => {
|
||||
const next = { ...prev };
|
||||
curr.modules.forEach((_, i) => {
|
||||
if (next[i] === undefined) next[i] = i === 0;
|
||||
});
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [topicId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showUpdatingModal) return;
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setShowUpdatingModal(false);
|
||||
};
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.body.style.overflow = prevOverflow;
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [showUpdatingModal]);
|
||||
|
||||
const toggle = (i: number) => {
|
||||
setExpanded((prev) => ({ ...prev, [i]: !prev[i] }));
|
||||
};
|
||||
|
||||
if (!curriculum?.hasContent || !curriculum.modules.length) return null;
|
||||
|
||||
const modules = curriculum.modules;
|
||||
const isLivestreamTopic = topicId === "livestream";
|
||||
const isLivestreamUpdating = isLivestreamTopic && paid;
|
||||
|
||||
const openUpdatingModal = (lessonName: string) => {
|
||||
setUpdatingLessonName(lessonName);
|
||||
setShowUpdatingModal(true);
|
||||
};
|
||||
|
||||
const closeUpdatingModal = () => {
|
||||
setShowUpdatingModal(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="border-t border-[var(--border)] py-12 md:py-16 lg:py-20">
|
||||
<div className="mx-auto max-w-6xl px-4 sm:px-6">
|
||||
<h2 className="mb-4 text-center text-xl font-bold sm:text-2xl md:text-3xl">实战课程</h2>
|
||||
<p className="mb-6 text-center text-[var(--muted-foreground)] sm:mb-8 md:mb-10">
|
||||
从入门到进阶,完整学习路径
|
||||
</p>
|
||||
<div className="space-y-2 md:space-y-3">
|
||||
{modules.map((module, i) => {
|
||||
const isOpen = expanded[i] ?? true;
|
||||
return (
|
||||
<div
|
||||
key={module.title}
|
||||
className="animate__animated animate__fadeInUp overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-sm transition-all duration-200 hover:border-[var(--accent)]/30 hover:shadow-md md:rounded-2xl"
|
||||
style={{ animationDelay: `${i * 0.06}s`, animationFillMode: "both" }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(i)}
|
||||
className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition hover:bg-[var(--muted)]/50 sm:px-5 sm:py-4"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-base font-semibold sm:text-lg">
|
||||
<span
|
||||
className={`inline-block transition-transform duration-200 ${isOpen ? "rotate-90" : ""}`}
|
||||
>
|
||||
▶
|
||||
</span>
|
||||
<span>{module.emoji}</span>
|
||||
{module.title}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--muted-foreground)]">{module.lessons.length} 节</span>
|
||||
</button>
|
||||
{isOpen && (
|
||||
<ul className="border-t border-[var(--border)]">
|
||||
{module.lessons.map((lesson, li) => {
|
||||
const origMod = module.originalModuleIndex;
|
||||
const free = false; /* 暂时全部加锁 */
|
||||
const unlocked = canWatchLesson(origMod, li);
|
||||
const key = `${origMod}-${li}`;
|
||||
const bookmarked = isBookmarked(origMod, li);
|
||||
const isCompleted = completed.has(key);
|
||||
const textClass = unlocked ? "text-[var(--foreground)]" : "text-[var(--muted-foreground)]";
|
||||
return (
|
||||
<li key={key}>
|
||||
{isLivestreamUpdating ? (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
if (paid) openUpdatingModal(lesson.name);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
if (paid) openUpdatingModal(lesson.name);
|
||||
}
|
||||
}}
|
||||
className="flex w-full flex-col gap-1 px-4 py-3 text-left transition hover:bg-[var(--muted)]/50 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-3"
|
||||
>
|
||||
<span className="flex items-center gap-2 truncate sm:gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toggleBookmark(origMod, li);
|
||||
}}
|
||||
className="shrink-0 text-xs"
|
||||
aria-label={bookmarked ? "取消收藏" : "收藏"}
|
||||
>
|
||||
{bookmarked ? "⭐" : "☆"}
|
||||
</button>
|
||||
<span className={textClass}>{lesson.name}</span>
|
||||
<span className="shrink-0 text-xs text-amber-500">🛠️</span>
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2 text-xs text-[var(--muted-foreground)] sm:text-sm">
|
||||
{lesson.duration}
|
||||
<span>···</span>
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<Link
|
||||
href={`/vip/cloudphone/course/${origMod}/${li}`}
|
||||
className="flex flex-col gap-1 px-4 py-3 transition hover:bg-[var(--muted)]/50 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-3"
|
||||
>
|
||||
<span className="flex items-center gap-2 truncate sm:gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toggleBookmark(origMod, li);
|
||||
}}
|
||||
className="shrink-0 text-xs"
|
||||
aria-label={bookmarked ? "取消收藏" : "收藏"}
|
||||
>
|
||||
{bookmarked ? "⭐" : "☆"}
|
||||
</button>
|
||||
<span className={textClass}>{lesson.name}</span>
|
||||
{free && (
|
||||
<span className="shrink-0 rounded bg-[var(--accent)]/20 px-1.5 py-0.5 text-xs text-[var(--accent)]">
|
||||
试看
|
||||
</span>
|
||||
)}
|
||||
{isCompleted && (
|
||||
<span className="shrink-0 rounded bg-green-500/20 px-1.5 py-0.5 text-xs text-green-600 dark:text-green-400">
|
||||
✓
|
||||
</span>
|
||||
)}
|
||||
{!unlocked && (
|
||||
<span className="shrink-0 text-xs text-[var(--muted-foreground)]">🔒</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2 text-xs text-[var(--muted-foreground)] sm:text-sm">
|
||||
{lesson.duration}
|
||||
<span className="text-[var(--accent)]">→</span>
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{showUpdatingModal && (
|
||||
<div
|
||||
className="fixed inset-0 z-[70] flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="课程更新提示"
|
||||
onClick={closeUpdatingModal}
|
||||
>
|
||||
<div className="absolute inset-0 bg-black/50 backdrop-blur-[2px] animate__animated animate__fadeIn" />
|
||||
<div
|
||||
className="animate__animated animate__fadeInUp relative w-full max-w-md rounded-2xl border border-amber-400/30 bg-[var(--card)] p-6 shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-full bg-amber-500/15 text-2xl text-amber-500">
|
||||
🚧
|
||||
</div>
|
||||
<h3 className="mb-2 text-xl font-bold text-[var(--foreground)]">正在更新</h3>
|
||||
<p className="mb-2 text-sm text-[var(--muted-foreground)]">
|
||||
<span className="font-medium text-[var(--foreground)]">{updatingLessonName}</span> 正在升级内容,
|
||||
将在完成后第一时间开放。
|
||||
</p>
|
||||
<p className="mb-6 text-sm text-[var(--muted-foreground)]">
|
||||
现在可以先学习「云手机」课程,后续会自动同步最新章节。
|
||||
</p>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeUpdatingModal}
|
||||
className="rounded-full border border-[var(--border)] px-4 py-2 text-sm text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
|
||||
>
|
||||
稍后再看
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeUpdatingModal}
|
||||
className="rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
|
||||
>
|
||||
我知道了
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user