Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
2b574f7957
commit
ffa456afdf
48
.cursor/rules/audience-cn-intl.mdc
Normal file
48
.cursor/rules/audience-cn-intl.mdc
Normal file
@ -0,0 +1,48 @@
|
||||
---
|
||||
description: 中文/国际受众模块化 — 支付登录关注文案VIP埋点等全进模块
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 受众模块化(强制)
|
||||
|
||||
## SoT
|
||||
|
||||
`src/modules/audience/`
|
||||
|
||||
| 路径 | 职责 |
|
||||
|------|------|
|
||||
| `detect.ts` | 微信 UA + is-china-user 识别 |
|
||||
| `cn/` | 中文用户:支付/登录/关注/文案/VIP/埋点/社群 |
|
||||
| `intl/` | 国际用户(.com 默认):同上全套 |
|
||||
| `resolve.ts` | `resolveAudienceBundle()` 合并远程 `audience.*` |
|
||||
| `index.ts` | **唯一公共面** |
|
||||
|
||||
## 产品姿态
|
||||
|
||||
- **intl**:`.com` 默认(英语为主 + 多语言 UI)
|
||||
- **cn**:必须特殊对待(微信内置 / is-china-user 命中)
|
||||
|
||||
## 开发铁律
|
||||
|
||||
```ts
|
||||
import { resolveAudienceBundle, useAudienceModule } from "~/modules/audience"
|
||||
const { module, lane, profile } = resolveAudienceBundle()
|
||||
// module.pay / .login / .follow / .copy / .vip / .track / .social
|
||||
```
|
||||
|
||||
**禁止**在页面散落 `if (isChina)` / `if (locale === "zh")` 决定支付网关、登录方式、关注渠道、VIP CTA。
|
||||
|
||||
新增能力(支付、登录、关注、文案、VIP、埋点、社群、小册 PDF/加密货币、运营位…)→ **同时改 `cn/` 与 `intl/`**,再经 `AudienceModule` 类型约束。
|
||||
|
||||
小册变现:`module.ebook.showPdfBuy` / `showCryptoSupport` — **仅 intl**;中文用户禁止展示 Download Edition / Buy Now $29 / Coffee·Lunch·Sponsor。
|
||||
|
||||
## 后台
|
||||
|
||||
登录后全屏选模块 → `/cn/*` | `/intl/*`(`admin.nomadro.com`)。
|
||||
|
||||
## 识别
|
||||
|
||||
1. 微信 / 企业微信内置 → cn
|
||||
2. `is-china-user` → cn
|
||||
3. 否则 → intl
|
||||
勿用 UI locale 反推受众轨。
|
||||
41
.cursor/rules/com-first-deploy.mdc
Normal file
41
.cursor/rules/com-first-deploy.mdc
Normal file
@ -0,0 +1,41 @@
|
||||
---
|
||||
description: .com 美国机为开发发版核心;.cn 独立同步;Taro→三端小程序链路
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 核心机与发版顺序(强制)
|
||||
|
||||
## 一句话
|
||||
|
||||
**本仓开发与默认发版核心是 `nomadro.com`(美国 VPS),不是 `.cn`。**
|
||||
|
||||
## 双站关系
|
||||
|
||||
| 站 | 机 | 角色 |
|
||||
|---|---|---|
|
||||
| **`.com`** | 美国 VPS(如 `108.174.50.68`) | **主开发 / 默认部署目标** |
|
||||
| **`.cn`** | 中国机 `82.157.112.245` | 独立生产;**仅在 .com 中文轨测稳后**再同步 |
|
||||
|
||||
- `.com` 内分 **中文用户 / 国际用户**(`src/modules/audience/{cn,intl}`,`resolveAudienceBundle()`)。
|
||||
- `.com` 中文用户体验测好 → 再同步到 `.cn` 与中国服务器。
|
||||
- **`.com` 中文轨与 `.cn` 服务器彼此独立**(库、配置、进程、发版互不顶替)。禁止「只发 82 就当 .com 已上线」。
|
||||
- 用户说「部署上线」且未点名域名 → **默认发 `.com` / 美国机**;发 `.cn` 必须明确说 `.cn` / 中国机 / 82。
|
||||
|
||||
## 产品复制链(中国三端)
|
||||
|
||||
```
|
||||
.com(Next · 受众 cn/intl)
|
||||
└─ 中文轨测稳 → 同步 .cn(Next · 中国机,独立)
|
||||
└─ Taro H5(apps/miniprogram/h5)对齐 .cn 体验
|
||||
└─ Taro 多端编译 → 微信 / 抖音 / 小红书
|
||||
```
|
||||
|
||||
- **微信小程序**是中国核心;抖音、小红书跟 Taro H5 SoT。
|
||||
- 小程序 **禁止 web-view** 承载业务(见 `no-webview-content.mdc`)。
|
||||
- `.com` 树 `apps/com/*` **无小程序**;小程序只走 `apps/miniprogram/*`。
|
||||
|
||||
## 反模式
|
||||
|
||||
- 默认 `deploy_*_82.py` / 只冒烟 `nomadro.cn` 却对用户说「已上线」
|
||||
- 把 `.cn` 当主站、把 `.com` 当镜像
|
||||
- 用 UI locale 代替受众轨;或假定 `.com` 中文与 `.cn` 共享同一后端
|
||||
@ -16,7 +16,9 @@ alwaysApply: true
|
||||
|
||||
统一经 FastAPI(`apps/api`)写 PocketBase;前端勿直连商户密钥。
|
||||
|
||||
## 多语言
|
||||
## 多语言与受众
|
||||
|
||||
- 默认中文 / 英语;扩展日语、越南语、泰语等小语种
|
||||
- 门户已有 `lib/i18n` + `is-china-user`;垂直应用逐步对齐,勿再造冲突 locale 键
|
||||
- **`.com`**:国际(英语为主)默认;中文用户特殊对待(见 `audience-cn-intl.mdc`)
|
||||
- UI 语言:中文 / 英语;扩展日语、越南语、泰语等小语种
|
||||
- 支付分流跟 **`detectAudience().isChina`**(含微信内置),**不要**跟 UI locale
|
||||
- 门户:`lib/i18n` + `lib/audience` + `is-china-user`;垂直应用对齐,勿再造冲突 locale 键
|
||||
|
||||
63
.cursor/skills/nomadro-platform/SKILL.md
Normal file
63
.cursor/skills/nomadro-platform/SKILL.md
Normal file
@ -0,0 +1,63 @@
|
||||
---
|
||||
name: nomadro-platform
|
||||
description: >-
|
||||
Use Nomadro public API / SDK / MCP tools for nomadro.com (US primary).
|
||||
Health, remote-config, social map/meetups/gigs/join, VIP check, nav links.
|
||||
Prefer MCP tools or GET https://nomadro.com/api/public/v1/* .
|
||||
---
|
||||
|
||||
# Nomadro Platform
|
||||
|
||||
## Deploy truth
|
||||
|
||||
- **Core**: `https://nomadro.com` (US). Default for agents and SDK `baseUrl`.
|
||||
- **China mirror**: `https://nomadro.cn` — independent; sync only after `.com` cn-audience is stable.
|
||||
- Audience lanes: `cn` | `intl` via `src/modules/audience`.
|
||||
|
||||
## Surfaces (same tool list)
|
||||
|
||||
| Surface | Entry |
|
||||
|---|---|
|
||||
| Docs UI | `https://nomadro.com/developers` (Scalar) |
|
||||
| OpenAPI | `GET /api/public/v1/openapi.json` |
|
||||
| Tools | `GET /api/public/v1/tools` |
|
||||
| SDK | `@nomadro/sdk` → `createNomadroClient({ baseUrl })` |
|
||||
| MCP | `pnpm mcp` / `node packages/mcp/src/cli.mjs` |
|
||||
| WeChat skill | `apps/miniprogram/weapp/ai-pkg/socialSkill` |
|
||||
|
||||
Tool SoT: `packages/sdk/tools.json`
|
||||
|
||||
## When to call which tool
|
||||
|
||||
- Platform probe → `health` / `getMeta` / `getConfig`
|
||||
- Map / cities → `listMapCities` / `searchCities` → handoff `/social/map`
|
||||
- Video rooms → `listMeetups` / `openMeetup` (no web-view in miniprograms)
|
||||
- Gigs → `listGigs` / `applyGig` (name+contact required)
|
||||
- Paid community join (not VIP) → `joinSocial` → `/social/join`
|
||||
- VIP membership → `checkVip` with email
|
||||
- Nav catalog → `listNavLinks`
|
||||
|
||||
## MCP config (Cursor)
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"nomadro": {
|
||||
"command": "node",
|
||||
"args": ["packages/mcp/src/cli.mjs"],
|
||||
"env": {
|
||||
"NOMADRO_PUBLIC_ORIGIN": "https://nomadro.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Optional: `NOMADRO_PUBLIC_API_KEY`, `NOMADRO_SOCIAL_GUEST_ID`.
|
||||
|
||||
## Constraints
|
||||
|
||||
1. Do not treat `.cn` as the default ship target.
|
||||
2. Social join ≠ VIP (`__social_join__` vs `__vip__`).
|
||||
3. Miniprogram content must stay native (no business web-view).
|
||||
4. Prefer returning `pagePath` handoffs so users complete pay/forms in UI.
|
||||
8
.gitignore
vendored
8
.gitignore
vendored
@ -42,6 +42,14 @@ node_modules/
|
||||
|
||||
# remote-config 本地备份(写入时自动生成)
|
||||
/data/backups/
|
||||
/data/notify/
|
||||
/data/work/
|
||||
/data/coffee/
|
||||
|
||||
# secondary-dev upstream clones (reference only)
|
||||
/apps/work/upstream/
|
||||
/apps/notify/upstream/
|
||||
/apps/coffee/upstream/
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
|
||||
@ -10,6 +10,8 @@ Follow `.cursor/rules/*.mdc`。
|
||||
|---|---|
|
||||
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
|
||||
| Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 |
|
||||
| Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 |
|
||||
| Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 |
|
||||
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
|
||||
| Unified API | `apps/api` |
|
||||
| Admin SPA (.cn) | `apps/admin` → `admin.nomadro.cn`(微信 / 抖音) |
|
||||
|
||||
112
README.md
112
README.md
@ -7,12 +7,14 @@
|
||||
```
|
||||
src/ Next.js 门户 .cn(app 路由壳 + modules 业务)
|
||||
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(仅 .cn 备案线)
|
||||
apps/api/ 统一 FastAPI(ebook + community + pay + social + work)
|
||||
apps/api/ 统一 FastAPI(ebook + community + pay + social + work + notify)
|
||||
apps/admin/ admin.nomadro.cn 管理 SPA(微信 / 抖音)
|
||||
apps/com/ .com 源码隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
|
||||
apps/work/ 远程工作参考 upstream / overlay(Planka · Etherpad;产品 UI 不跑 iframe)
|
||||
apps/notify/ 通知参考 upstream(Novu;产品 UI 不跑 iframe)
|
||||
apps/coffee/ 咖啡聊预约参考 upstream(Cal.com;产品 UI 不跑 iframe)
|
||||
packages/ @nomadro/pay · pb · sdk
|
||||
data/ 远程配置等运行时数据(含 social.db · work.sqlite3)
|
||||
data/ 远程配置等运行时数据(含 social.db · work/notify/coffee.sqlite3)
|
||||
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
```
|
||||
|
||||
@ -23,6 +25,8 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
|
||||
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
|
||||
| **远程工作** | `/social/work` | `src/modules/work` · FastAPI `work_svc` `/api/work/v1`(看板 + 文档) |
|
||||
| **通知** | `/notifications` · `/social/notify` | `src/modules/notify` · FastAPI `notify_svc` `/api/notify/v1`(收件箱 + 工作流) |
|
||||
| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
|
||||
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
|
||||
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
|
||||
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
|
||||
@ -30,6 +34,69 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
|
||||
`.cn` 后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗集成在 **`/douyin/modules`**。`.com` 未备案,**无**小程序后台。
|
||||
|
||||
## 技术栈(Next 门户 + FastAPI)
|
||||
|
||||
### 前端(`src/` · Next.js)
|
||||
|
||||
| 层 | 技术 |
|
||||
|---|---|
|
||||
| 框架 | Next.js 16(App Router)· React 19 · TypeScript · pnpm workspace |
|
||||
| 样式 | Tailwind CSS 4 · Sass · 模块 CSS |
|
||||
| 主题 | `next-themes`(日/夜防闪烁) |
|
||||
| 动效 / 图标 | Framer Motion · animate.css · Lucide |
|
||||
| 地图 | MapLibre GL · h3-js |
|
||||
| 实时 | Centrifuge(对接 Centrifugo)· socket.io-client |
|
||||
| Markdown / 编辑 | react-markdown · marked · markdown-it · Gravity UI Markdown · Diplodoc · highlight.js |
|
||||
| DnD / 组件库 | `@hello-pangea/dnd` · Ant Design · Gravity UI · Semantic UI React |
|
||||
| 3D | three.js |
|
||||
| i18n / 受众 | i18next · `is-china-user` · `src/modules/audience/{cn,intl}` |
|
||||
| 其它 | PocketBase JS SDK · QR · PhotoSwipe · `@nomadro/{pay,pb,sdk}` |
|
||||
|
||||
业务垂直在 `src/modules/{nav,ebook,community,social,work,notify,vip,audience}`;`src/app` 只挂路由。同源 API 经 Next Route Handler 反代到 FastAPI(如 `/api/work/v1`、`/api/notify/v1`)。
|
||||
|
||||
### 后端(`apps/api` · FastAPI)
|
||||
|
||||
| 层 | 技术 |
|
||||
|---|---|
|
||||
| 运行时 | FastAPI · Uvicorn |
|
||||
| 服务 | `ebook_svc` · `community_svc` · `pay_svc` · `social_svc` · `work_svc` · `notify_svc` · `coffee_svc` |
|
||||
| 独立进程 | `social_main :8020` · `work_main :8021` · `notify_main :8023` · `coffee_main :8024`(主 API 另有统一入口) |
|
||||
| 数据 | PocketBase(账号/订单等)· SQLite(social / work / notify / coffee) |
|
||||
| 对象存储 | SeaweedFS S3(`s3.nomadro.com`;社群 / 加入头像共用 `S3_*`) |
|
||||
| 支付 | 海外 Creem / NOWPayments;国内 zpay · xpay/xorpay;密钥只走 API |
|
||||
|
||||
### 周边同仓
|
||||
|
||||
| 端 | 技术 |
|
||||
|---|---|
|
||||
| 小程序 | Taro 4 + React(H5 SoT → 微信 / 抖音 / 小红书);**禁止 web-view 承载业务** |
|
||||
| 管理后台 | Vite SPA(`apps/admin` · `apps/com/admin`) |
|
||||
| 运维常见 | Nginx / Caddy · Docker · Umami · Uptime-Kuma · ntfy · SeaweedFS / MinIO |
|
||||
|
||||
## 开源对照(域模型二次开发)
|
||||
|
||||
原则:**读开源域模型后自研进 Nomadro**,同域原生页;**禁止** iframe / 二级域硬嵌官方 UI。上游仅对照:`pnpm work:fetch` · `pnpm notify:fetch`。
|
||||
|
||||
| 开源项目 | 用途 | Nomadro 落点 |
|
||||
|---|---|---|
|
||||
| [Planka](https://github.com/plankanban/planka) | 看板域模型 | `/social/work/boards` · `work_svc` |
|
||||
| [Etherpad](https://github.com/ether/etherpad) | 协作文档 / 修订 | `/social/work/pads` · `work_svc` |
|
||||
| [Novu](https://github.com/novuhq/novu) | 通知工作流 / Inbox | `/social/notify` · `/notifications` · `notify_svc` |
|
||||
| [Cal.com](https://github.com/calcom/cal.com) | 预约 / 日程 / 时段 | `/social/coffeechat` · `coffee_svc` |
|
||||
| MiroTalk | 视频厅(白标同域) | 社群活动直播 / join |
|
||||
| Centrifugo | 实时推送 | Social 聊天 WebSocket |
|
||||
| PocketBase | BaaS / 鉴权与业务库 | `@nomadro/pb` · 支付写库 |
|
||||
| Taro | 多端小程序 | `apps/miniprogram/*` |
|
||||
| MapLibre | 地图 | `/social/map` 等 |
|
||||
| three.js | 3D | 门户 / H5(游戏模块冷冻) |
|
||||
| Umami | 分析 | 运维 |
|
||||
| Uptime-Kuma | 可用性监控 | 运维 |
|
||||
| ntfy | 运维通知 | 运维 |
|
||||
| SeaweedFS / MinIO | 对象存储(头像 / 社群媒体 → `s3.nomadro.com`) | `social_svc` · `community_svc` |
|
||||
| Caddy | 反代(可选) | 运维 |
|
||||
|
||||
细节:[`apps/work/README.md`](apps/work/README.md) · [`apps/notify/README.md`](apps/notify/README.md)。
|
||||
|
||||
### 微信后台(admin.nomadro.cn/wechat)
|
||||
|
||||
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。
|
||||
@ -95,6 +162,8 @@ pnpm dev:tt # 抖音小程序
|
||||
pnpm dev:admin # 管理后台 :5173
|
||||
pnpm dev:api # FastAPI(需先建 apps/api/.venv)
|
||||
pnpm dev:work-api # 远程工作 work_svc :8021(看板 / 文档)
|
||||
pnpm dev:notify-api # 通知 notify_svc :8023(收件箱 / 工作流)
|
||||
pnpm dev:coffee-api # 咖啡聊 coffee_svc :8024(预约 / 时段)
|
||||
|
||||
pnpm build:portal
|
||||
pnpm build:admin
|
||||
@ -130,6 +199,8 @@ pnpm dev:api
|
||||
|
||||
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。
|
||||
|
||||
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。
|
||||
|
||||
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
|
||||
|
||||
### 远程工作(`/social/work`)
|
||||
@ -149,7 +220,40 @@ pnpm dev # http://localhost:3000/social/work
|
||||
|
||||
数据:`data/work/work.sqlite3`(或 `WORK_DATA_DIR`)。参考 upstream:`pnpm work:fetch`(仅对照,产品不跑 Docker Planka UI)。细节见 [`apps/work/README.md`](apps/work/README.md)。
|
||||
|
||||
| 层 | 线上(82) | 说明 |
|
||||
### 通知(`/notifications` · `/social/notify`)
|
||||
|
||||
读 **Novu** 域模型后自研。用户向收件箱与编排控制台分离;同域原生页,**禁止** iframe。
|
||||
|
||||
| 能力 | 路由 | 说明 |
|
||||
|------|------|------|
|
||||
| 全部通知 | `/social/notifications`(根路径 `/notifications` 重定向) | 分类:社交 / 搭子 / 项目 / 系统;点击跳转;全部/单条已读;删除 |
|
||||
| 偏好设置 | `/social/notifications/settings` | 免打扰 · 邮件订阅 · 浏览器推送授权 |
|
||||
| 顶部铃铛 | SiteShell | 未读角标,轮询 `/api/notify/v1/inbox/unread` |
|
||||
| 编排控制台 | `/social/notify` | 工作流 / 订阅者 / 主题 / 活动(Novu 二次开发) |
|
||||
|
||||
```bash
|
||||
pnpm dev:notify-api # :8023 · NOTIFY_API_URL → /api/notify/v1
|
||||
pnpm notify:fetch # 可选对照源码
|
||||
pnpm dev # http://localhost:3000/notifications
|
||||
```
|
||||
|
||||
数据:`data/notify/notify.sqlite3`。细节见 [`apps/notify/README.md`](apps/notify/README.md)。
|
||||
|
||||
### 咖啡聊预约(`/social/coffeechat`)
|
||||
|
||||
读 **Cal.com** 域模型后自研:Host · EventType · Schedule/Availability · Slots · Booking。同域原生页;咖啡馆点位仍见 `/social/places?tab=cafes`。
|
||||
|
||||
```bash
|
||||
pnpm dev:coffee-api # :8024 · COFFEE_API_URL → /api/coffee/v1
|
||||
pnpm coffee:fetch # 可选对照源码
|
||||
pnpm dev # http://localhost:3000/social/coffeechat
|
||||
```
|
||||
|
||||
数据:`data/coffee/coffee.sqlite3`。细节见 [`apps/coffee/README.md`](apps/coffee/README.md)。
|
||||
|
||||
**`.com`(美国机,默认发版)**:`python deploy/work/deploy_us.py` → 门户 `nomadro` `:4003` + `nomadro-work` `:8021`;nginx `^~ /api/work/` **直连** work_svc(勿经 Next,避免 `Connection: upgrade` 导致 503)。冒烟:`https://nomadro.com/social/work` · `/api/work/v1/boards`。
|
||||
|
||||
| 层 | 线上(82 · `.cn`) | 说明 |
|
||||
|---|---|---|
|
||||
| 门户 | `nomadro.service` `:4003` | `/social/*`;前端发版须**本地确认后再上线** |
|
||||
| Social API | `nomadro-social.service` `:8020` | `apps/api/social_main.py`;nginx `/api/social/` |
|
||||
@ -223,6 +327,8 @@ pnpm dev # http://localhost:3000/social/work
|
||||
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
|
||||
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
|
||||
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
|
||||
| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
|
||||
| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
|
||||
|
||||
提审上传:
|
||||
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
Vite + React SPA。业务 API 经同源反代到 **`nomadmini-api`** / `apps/api`。
|
||||
|
||||
> **`.com` Web 后台已源码隔离**:见 [`apps/com`](../com) → `admin.nomadro.com`(美国 VPS,无微信/抖音)。勿把小程序能力做到 `.com` 树,也勿把 `.com` 合回本包。
|
||||
|
||||
## 本地
|
||||
|
||||
```bash
|
||||
|
||||
@ -120,8 +120,8 @@ WX_APP_KEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
|
||||
WX_SANDBOX_APP_KEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
|
||||
WX_PAY_ENV=0
|
||||
JWT_SECRET=nomadro-jwt-prod-2026
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=Xiao4669805
|
||||
ADMIN_USERNAME=hackrobot
|
||||
ADMIN_PASSWORD=Xiao4669805@
|
||||
PB_URL=http://127.0.0.1:8090
|
||||
PB_ADMIN_EMAIL=admin@nomadro.cn
|
||||
PB_ADMIN_PASSWORD=Xiao4669805
|
||||
|
||||
@ -4,7 +4,7 @@ import { api, setToken } from '../api'
|
||||
|
||||
export default function Login() {
|
||||
const nav = useNavigate()
|
||||
const [username, setUsername] = useState('admin')
|
||||
const [username, setUsername] = useState('hackrobot')
|
||||
const [password, setPassword] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
@ -125,7 +125,7 @@ const empty: VipCfg = {
|
||||
gameEnabled: false,
|
||||
joinGroupAction: 'popup',
|
||||
vipWebBridgeEnabled: false,
|
||||
vipPriceFen: 29800,
|
||||
vipPriceFen: 8800,
|
||||
vipProductId: 'tiktok',
|
||||
vipCta: '立即加入',
|
||||
vipOfferKey: 'tiktok',
|
||||
|
||||
42
apps/api/coffee_main.py
Normal file
42
apps/api/coffee_main.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""Nomadro coffeechat booking API — Cal.com-domain secondary-dev."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
SERVICES = ROOT / "services"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
from coffee_svc.config import COFFEE_ENABLED # noqa: E402
|
||||
from coffee_svc.routers import router as coffee_router # noqa: E402
|
||||
from coffee_svc.store import init_db # noqa: E402
|
||||
|
||||
app = FastAPI(title="nomadro-coffee", docs_url="/docs", redoc_url=None)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _startup() -> None:
|
||||
if COFFEE_ENABLED:
|
||||
init_db()
|
||||
|
||||
|
||||
if COFFEE_ENABLED:
|
||||
app.include_router(coffee_router, prefix="/api/coffee/v1")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"ok": True, "service": "nomadro-coffee", "coffee": bool(COFFEE_ENABLED)}
|
||||
42
apps/api/notify_main.py
Normal file
42
apps/api/notify_main.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""Nomadro notify API — Novu-domain workflows + inbox (secondary-dev)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
SERVICES = ROOT / "services"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
from notify_svc.config import NOTIFY_ENABLED # noqa: E402
|
||||
from notify_svc.routers import router as notify_router # noqa: E402
|
||||
from notify_svc.store import init_db # noqa: E402
|
||||
|
||||
app = FastAPI(title="nomadro-notify", docs_url="/docs", redoc_url=None)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _startup() -> None:
|
||||
if NOTIFY_ENABLED:
|
||||
init_db()
|
||||
|
||||
|
||||
if NOTIFY_ENABLED:
|
||||
app.include_router(notify_router, prefix="/api/notify/v1")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"ok": True, "service": "nomadro-notify", "notify": bool(NOTIFY_ENABLED)}
|
||||
@ -16,6 +16,7 @@ email-validator==2.2.0
|
||||
boto3==1.35.99
|
||||
sqlalchemy
|
||||
pocketbase
|
||||
h3
|
||||
requests
|
||||
minio
|
||||
opencv-python-headless
|
||||
|
||||
1
apps/api/services/coffee_svc/__init__.py
Normal file
1
apps/api/services/coffee_svc/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Nomadro coffeechat booking — Cal.com-domain secondary-dev."""
|
||||
21
apps/api/services/coffee_svc/config.py
Normal file
21
apps/api/services/coffee_svc/config.py
Normal file
@ -0,0 +1,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
COFFEE_ENABLED = os.getenv("COFFEE_ENABLED", "1").strip().lower() not in {
|
||||
"0",
|
||||
"false",
|
||||
"no",
|
||||
"off",
|
||||
}
|
||||
|
||||
DATA_DIR = Path(os.getenv("COFFEE_DATA_DIR", "/var/lib/nomadro/coffee"))
|
||||
if not DATA_DIR.exists():
|
||||
DATA_DIR = (
|
||||
Path(os.getenv("COFFEE_DATA_DIR_LOCAL", "")).resolve()
|
||||
if os.getenv("COFFEE_DATA_DIR_LOCAL")
|
||||
else Path.cwd() / "data" / "coffee"
|
||||
)
|
||||
|
||||
DB_PATH = DATA_DIR / "coffee.sqlite3"
|
||||
3
apps/api/services/coffee_svc/routers/__init__.py
Normal file
3
apps/api/services/coffee_svc/routers/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .api import router
|
||||
|
||||
__all__ = ["router"]
|
||||
142
apps/api/services/coffee_svc/routers/api.py
Normal file
142
apps/api/services/coffee_svc/routers/api.py
Normal file
@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from coffee_svc import store
|
||||
|
||||
router = APIRouter(tags=["coffee"])
|
||||
|
||||
|
||||
class SchedulePatch(BaseModel):
|
||||
availability: list[dict[str, Any]] | None = None
|
||||
timezone: str | None = None
|
||||
name: str | None = None
|
||||
|
||||
|
||||
class EventTypeIn(BaseModel):
|
||||
slug: str = Field(min_length=1, max_length=80)
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
description: str = ""
|
||||
length_minutes: int = Field(default=30, ge=5, le=480)
|
||||
slot_interval: int = Field(default=15, ge=5, le=60)
|
||||
locations: list[dict[str, Any]] = Field(default_factory=list)
|
||||
active: bool = True
|
||||
buffer_before: int = 0
|
||||
buffer_after: int = 0
|
||||
|
||||
|
||||
class BookingIn(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=80)
|
||||
event_slug: str = Field(min_length=1, max_length=80)
|
||||
start: str = Field(min_length=1, max_length=40)
|
||||
attendee_name: str = Field(min_length=1, max_length=120)
|
||||
attendee_email: str | None = None
|
||||
attendee_device: str | None = None
|
||||
location: str | None = None
|
||||
notes: str = ""
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health():
|
||||
return {"ok": True, "service": "nomadro-coffee", "inspiredBy": ["cal.com"]}
|
||||
|
||||
|
||||
@router.get("/hosts")
|
||||
def hosts():
|
||||
return {"ok": True, "hosts": store.list_hosts()}
|
||||
|
||||
|
||||
@router.get("/hosts/{username}")
|
||||
def host(username: str):
|
||||
h = store.get_host(username)
|
||||
if not h:
|
||||
raise HTTPException(404, "host_not_found")
|
||||
return {"ok": True, "host": h}
|
||||
|
||||
|
||||
@router.get("/hosts/{username}/schedule")
|
||||
def schedule(username: str):
|
||||
s = store.get_schedule(username)
|
||||
if not s:
|
||||
raise HTTPException(404, "schedule_not_found")
|
||||
return {"ok": True, "schedule": s}
|
||||
|
||||
|
||||
@router.patch("/hosts/{username}/schedule")
|
||||
def patch_schedule(username: str, body: SchedulePatch):
|
||||
try:
|
||||
s = store.update_schedule(
|
||||
username,
|
||||
availability=body.availability,
|
||||
timezone_name=body.timezone,
|
||||
name=body.name,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "schedule": s}
|
||||
|
||||
|
||||
@router.get("/hosts/{username}/event-types/{slug}")
|
||||
def event_type(username: str, slug: str):
|
||||
e = store.get_event_type(username, slug)
|
||||
if not e:
|
||||
raise HTTPException(404, "event_type_not_found")
|
||||
return {"ok": True, "event_type": e}
|
||||
|
||||
|
||||
@router.post("/hosts/{username}/event-types")
|
||||
def create_event_type(username: str, body: EventTypeIn):
|
||||
try:
|
||||
e = store.upsert_event_type(username, body.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "event_type": e}
|
||||
|
||||
|
||||
@router.get("/hosts/{username}/event-types/{slug}/slots")
|
||||
def slots(
|
||||
username: str,
|
||||
slug: str,
|
||||
day: str = Query(..., description="YYYY-MM-DD in host local timezone"),
|
||||
):
|
||||
try:
|
||||
return store.available_slots(username, slug, day)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.get("/bookings")
|
||||
def bookings(
|
||||
host: str | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
):
|
||||
return {"ok": True, "bookings": store.list_bookings(host_username=host, status=status)}
|
||||
|
||||
|
||||
@router.get("/bookings/{booking_id}")
|
||||
def booking(booking_id: str):
|
||||
b = store.get_booking(booking_id)
|
||||
if not b:
|
||||
raise HTTPException(404, "booking_not_found")
|
||||
return {"ok": True, "booking": b}
|
||||
|
||||
|
||||
@router.post("/bookings")
|
||||
def book(body: BookingIn):
|
||||
try:
|
||||
b = store.create_booking(body.model_dump())
|
||||
except ValueError as e:
|
||||
code = 409 if str(e) == "slot_unavailable" else 400
|
||||
raise HTTPException(code, str(e)) from e
|
||||
return {"ok": True, "booking": b}
|
||||
|
||||
|
||||
@router.post("/bookings/{booking_id}/cancel")
|
||||
def cancel(booking_id: str):
|
||||
b = store.cancel_booking(booking_id)
|
||||
if not b:
|
||||
raise HTTPException(404, "booking_not_found")
|
||||
return {"ok": True, "booking": b}
|
||||
719
apps/api/services/coffee_svc/store.py
Normal file
719
apps/api/services/coffee_svc/store.py
Normal file
@ -0,0 +1,719 @@
|
||||
"""
|
||||
SQLite store — domain shaped after Cal.com
|
||||
(User/Host · EventType · Schedule · Availability · Booking · Attendee · Slot).
|
||||
Secondary-dev reimplementation for Nomadro coffeechat (not upstream Cal runtime).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .config import DATA_DIR, DB_PATH
|
||||
|
||||
try:
|
||||
from ebook_svc.core.sqlite_util import connect as _connect
|
||||
except Exception: # pragma: no cover
|
||||
|
||||
def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
|
||||
p = Path(path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
c = sqlite3.connect(str(p), timeout=timeout)
|
||||
c.row_factory = sqlite3.Row
|
||||
c.execute("PRAGMA journal_mode=WAL")
|
||||
return c
|
||||
|
||||
|
||||
WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
|
||||
# Cal.com uses 0=Sunday … Python weekday() is 0=Monday — map carefully
|
||||
PY_TO_CAL = {0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun"}
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def _id(prefix: str) -> str:
|
||||
return f"{prefix}_{uuid.uuid4().hex[:10]}"
|
||||
|
||||
|
||||
def _conn() -> sqlite3.Connection:
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
return _connect(DB_PATH)
|
||||
|
||||
|
||||
def _json(v: Any) -> str:
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
|
||||
|
||||
def _parse(s: str | None, default: Any = None) -> Any:
|
||||
if not s:
|
||||
return default if default is not None else {}
|
||||
try:
|
||||
return json.loads(s)
|
||||
except Exception:
|
||||
return default if default is not None else {}
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
with _conn() as c:
|
||||
c.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS hosts (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
bio TEXT NOT NULL DEFAULT '',
|
||||
avatar TEXT,
|
||||
timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai',
|
||||
city TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS schedules (
|
||||
id TEXT PRIMARY KEY,
|
||||
host_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL DEFAULT 'Working hours',
|
||||
timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai',
|
||||
availability_json TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
FOREIGN KEY(host_id) REFERENCES hosts(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS event_types (
|
||||
id TEXT PRIMARY KEY,
|
||||
host_id TEXT NOT NULL,
|
||||
schedule_id TEXT NOT NULL,
|
||||
slug TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
length_minutes INTEGER NOT NULL DEFAULT 30,
|
||||
slot_interval INTEGER NOT NULL DEFAULT 15,
|
||||
buffer_before INTEGER NOT NULL DEFAULT 0,
|
||||
buffer_after INTEGER NOT NULL DEFAULT 0,
|
||||
locations_json TEXT NOT NULL DEFAULT '[]',
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE(host_id, slug),
|
||||
FOREIGN KEY(host_id) REFERENCES hosts(id),
|
||||
FOREIGN KEY(schedule_id) REFERENCES schedules(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bookings (
|
||||
id TEXT PRIMARY KEY,
|
||||
uid TEXT NOT NULL UNIQUE,
|
||||
event_type_id TEXT NOT NULL,
|
||||
host_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'accepted',
|
||||
start_utc TEXT NOT NULL,
|
||||
end_utc TEXT NOT NULL,
|
||||
location TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
attendee_name TEXT NOT NULL,
|
||||
attendee_email TEXT,
|
||||
attendee_device TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
cancelled_at TEXT,
|
||||
FOREIGN KEY(event_type_id) REFERENCES event_types(id),
|
||||
FOREIGN KEY(host_id) REFERENCES hosts(id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_host_start
|
||||
ON bookings(host_id, start_utc);
|
||||
"""
|
||||
)
|
||||
_seed(c)
|
||||
|
||||
|
||||
def _default_availability() -> list[dict[str, Any]]:
|
||||
"""Cal.com-style weekly windows (local schedule timezone)."""
|
||||
windows = [{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 600, "endTime": 720}]
|
||||
# 10:00–12:00 and 14:00–18:00 as minutes from midnight
|
||||
windows.append(
|
||||
{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 840, "endTime": 1080}
|
||||
)
|
||||
windows.append({"days": ["sat"], "startTime": 660, "endTime": 900})
|
||||
return windows
|
||||
|
||||
|
||||
def _seed(c: sqlite3.Connection) -> None:
|
||||
if c.execute("SELECT 1 FROM hosts LIMIT 1").fetchone():
|
||||
return
|
||||
now = _now()
|
||||
hosts = [
|
||||
("host_alice", "alice", "Alice Chen", "成都远程 · 爱咖啡闲聊产品与出海", "Chengdu", "Asia/Shanghai"),
|
||||
("host_bob", "bob", "Bob Rivera", "EN/ZH · coffee or video walkthrough", "Chiang Mai", "Asia/Bangkok"),
|
||||
("host_guest", "guest", "Guest Nomad", "演示主持人 · 可约 30 分钟咖啡聊", "Shenzhen", "Asia/Shanghai"),
|
||||
]
|
||||
for hid, user, name, bio, city, tz in hosts:
|
||||
c.execute(
|
||||
"""INSERT INTO hosts(id,username,name,bio,avatar,timezone,city,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)""",
|
||||
(hid, user, name, bio, None, tz, city, now),
|
||||
)
|
||||
sid = f"sch_{user}"
|
||||
c.execute(
|
||||
"""INSERT INTO schedules(id,host_id,name,timezone,availability_json,created_at)
|
||||
VALUES(?,?,?,?,?,?)""",
|
||||
(sid, hid, "Working hours", tz, _json(_default_availability()), now),
|
||||
)
|
||||
events = [
|
||||
(
|
||||
f"et_{user}_coffee",
|
||||
"coffee-30",
|
||||
"☕ 咖啡聊 30′",
|
||||
"同城咖啡馆或语音闲聊,认识一下就好。",
|
||||
30,
|
||||
[
|
||||
{"type": "inPerson", "label": "咖啡馆(见面后定)"},
|
||||
{"type": "link", "label": "语音/视频", "link": "/social/meetup"},
|
||||
],
|
||||
),
|
||||
(
|
||||
f"et_{user}_video",
|
||||
"video-45",
|
||||
"📹 视频深聊 45′",
|
||||
"产品 / 副业 / 旅居经验,线上视频。",
|
||||
45,
|
||||
[{"type": "link", "label": "Nomadro 视频厅", "link": "/social/meetup"}],
|
||||
),
|
||||
]
|
||||
for eid, slug, title, desc, length, locs in events:
|
||||
c.execute(
|
||||
"""INSERT INTO event_types(
|
||||
id,host_id,schedule_id,slug,title,description,length_minutes,
|
||||
slot_interval,buffer_before,buffer_after,locations_json,active,created_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
eid,
|
||||
hid,
|
||||
sid,
|
||||
slug,
|
||||
title,
|
||||
desc,
|
||||
length,
|
||||
15,
|
||||
0,
|
||||
0,
|
||||
_json(locs),
|
||||
1,
|
||||
now,
|
||||
),
|
||||
)
|
||||
|
||||
# sample booking tomorrow 10:00 Asia/Shanghai for alice coffee
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
tomorrow = datetime.now(tz).date() + timedelta(days=1)
|
||||
start_local = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 10, 0, tzinfo=tz)
|
||||
end_local = start_local + timedelta(minutes=30)
|
||||
c.execute(
|
||||
"""INSERT INTO bookings(
|
||||
id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes,
|
||||
attendee_name,attendee_email,attendee_device,created_at,cancelled_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
_id("bk"),
|
||||
_id("uid"),
|
||||
"et_alice_coffee",
|
||||
"host_alice",
|
||||
"☕ 咖啡聊 30′",
|
||||
"accepted",
|
||||
start_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
end_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"咖啡馆(见面后定)",
|
||||
"种子预约",
|
||||
"Demo Attendee",
|
||||
"demo@nomadro.com",
|
||||
None,
|
||||
now,
|
||||
None,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# —— hosts / event types ——
|
||||
|
||||
|
||||
def list_hosts() -> list[dict[str, Any]]:
|
||||
with _conn() as c:
|
||||
rows = c.execute("SELECT * FROM hosts ORDER BY username").fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
n = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM event_types WHERE host_id=? AND active=1",
|
||||
(r["id"],),
|
||||
).fetchone()["n"]
|
||||
out.append(_host_out(dict(r), event_count=n))
|
||||
return out
|
||||
|
||||
|
||||
def get_host(username: str) -> dict[str, Any] | None:
|
||||
with _conn() as c:
|
||||
r = c.execute(
|
||||
"SELECT * FROM hosts WHERE username=? OR id=?",
|
||||
(username, username),
|
||||
).fetchone()
|
||||
if not r:
|
||||
return None
|
||||
events = [
|
||||
_event_out(dict(e))
|
||||
for e in c.execute(
|
||||
"SELECT * FROM event_types WHERE host_id=? AND active=1 ORDER BY length_minutes",
|
||||
(r["id"],),
|
||||
).fetchall()
|
||||
]
|
||||
h = _host_out(dict(r), event_count=len(events))
|
||||
h["event_types"] = events
|
||||
return h
|
||||
|
||||
|
||||
def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"username": r["username"],
|
||||
"name": r["name"],
|
||||
"bio": r.get("bio") or "",
|
||||
"avatar": r.get("avatar"),
|
||||
"timezone": r.get("timezone") or "Asia/Shanghai",
|
||||
"city": r.get("city") or "",
|
||||
"event_count": event_count,
|
||||
"created_at": r.get("created_at"),
|
||||
}
|
||||
|
||||
|
||||
def get_event_type(username: str, slug: str) -> dict[str, Any] | None:
|
||||
with _conn() as c:
|
||||
h = c.execute(
|
||||
"SELECT * FROM hosts WHERE username=? OR id=?",
|
||||
(username, username),
|
||||
).fetchone()
|
||||
if not h:
|
||||
return None
|
||||
e = c.execute(
|
||||
"SELECT * FROM event_types WHERE host_id=? AND slug=?",
|
||||
(h["id"], slug),
|
||||
).fetchone()
|
||||
if not e:
|
||||
return None
|
||||
out = _event_out(dict(e))
|
||||
out["host"] = _host_out(dict(h))
|
||||
sch = c.execute(
|
||||
"SELECT * FROM schedules WHERE id=?", (e["schedule_id"],)
|
||||
).fetchone()
|
||||
if sch:
|
||||
out["schedule"] = _schedule_out(dict(sch))
|
||||
return out
|
||||
|
||||
|
||||
def _event_out(r: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"host_id": r["host_id"],
|
||||
"schedule_id": r["schedule_id"],
|
||||
"slug": r["slug"],
|
||||
"title": r["title"],
|
||||
"description": r.get("description") or "",
|
||||
"length_minutes": int(r["length_minutes"]),
|
||||
"slot_interval": int(r.get("slot_interval") or 15),
|
||||
"buffer_before": int(r.get("buffer_before") or 0),
|
||||
"buffer_after": int(r.get("buffer_after") or 0),
|
||||
"locations": _parse(r.get("locations_json"), []),
|
||||
"active": bool(r.get("active")),
|
||||
"created_at": r.get("created_at"),
|
||||
}
|
||||
|
||||
|
||||
def _schedule_out(r: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"host_id": r["host_id"],
|
||||
"name": r["name"],
|
||||
"timezone": r["timezone"],
|
||||
"availability": _parse(r.get("availability_json"), []),
|
||||
"created_at": r["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def get_schedule(host_username: str) -> dict[str, Any] | None:
|
||||
with _conn() as c:
|
||||
h = c.execute(
|
||||
"SELECT * FROM hosts WHERE username=? OR id=?",
|
||||
(host_username, host_username),
|
||||
).fetchone()
|
||||
if not h:
|
||||
return None
|
||||
s = c.execute(
|
||||
"SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1",
|
||||
(h["id"],),
|
||||
).fetchone()
|
||||
return _schedule_out(dict(s)) if s else None
|
||||
|
||||
|
||||
def update_schedule(
|
||||
host_username: str,
|
||||
*,
|
||||
availability: list[dict[str, Any]] | None = None,
|
||||
timezone_name: str | None = None,
|
||||
name: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
with _conn() as c:
|
||||
h = c.execute(
|
||||
"SELECT * FROM hosts WHERE username=? OR id=?",
|
||||
(host_username, host_username),
|
||||
).fetchone()
|
||||
if not h:
|
||||
raise ValueError("host_not_found")
|
||||
s = c.execute(
|
||||
"SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1",
|
||||
(h["id"],),
|
||||
).fetchone()
|
||||
if not s:
|
||||
raise ValueError("schedule_not_found")
|
||||
avail = (
|
||||
_json(availability)
|
||||
if availability is not None
|
||||
else s["availability_json"]
|
||||
)
|
||||
tz = timezone_name or s["timezone"]
|
||||
nm = name or s["name"]
|
||||
c.execute(
|
||||
"UPDATE schedules SET availability_json=?, timezone=?, name=? WHERE id=?",
|
||||
(avail, tz, nm, s["id"]),
|
||||
)
|
||||
if timezone_name:
|
||||
c.execute(
|
||||
"UPDATE hosts SET timezone=? WHERE id=?",
|
||||
(timezone_name, h["id"]),
|
||||
)
|
||||
row = c.execute("SELECT * FROM schedules WHERE id=?", (s["id"],)).fetchone()
|
||||
return _schedule_out(dict(row))
|
||||
|
||||
|
||||
def upsert_event_type(
|
||||
host_username: str,
|
||||
data: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
slug = (data.get("slug") or "").strip()
|
||||
title = (data.get("title") or "").strip()
|
||||
if not slug or not title:
|
||||
raise ValueError("slug_and_title_required")
|
||||
with _conn() as c:
|
||||
h = c.execute(
|
||||
"SELECT * FROM hosts WHERE username=? OR id=?",
|
||||
(host_username, host_username),
|
||||
).fetchone()
|
||||
if not h:
|
||||
raise ValueError("host_not_found")
|
||||
sch = c.execute(
|
||||
"SELECT id FROM schedules WHERE host_id=? LIMIT 1",
|
||||
(h["id"],),
|
||||
).fetchone()
|
||||
if not sch:
|
||||
raise ValueError("schedule_not_found")
|
||||
existing = c.execute(
|
||||
"SELECT * FROM event_types WHERE host_id=? AND slug=?",
|
||||
(h["id"], slug),
|
||||
).fetchone()
|
||||
length = int(data.get("length_minutes") or 30)
|
||||
interval = int(data.get("slot_interval") or 15)
|
||||
locs = data.get("locations") or [
|
||||
{"type": "inPerson", "label": "咖啡馆(见面后定)"}
|
||||
]
|
||||
now = _now()
|
||||
if existing:
|
||||
c.execute(
|
||||
"""UPDATE event_types SET title=?,description=?,length_minutes=?,
|
||||
slot_interval=?,locations_json=?,active=? WHERE id=?""",
|
||||
(
|
||||
title,
|
||||
data.get("description") or "",
|
||||
length,
|
||||
interval,
|
||||
_json(locs),
|
||||
1 if data.get("active", True) else 0,
|
||||
existing["id"],
|
||||
),
|
||||
)
|
||||
eid = existing["id"]
|
||||
else:
|
||||
eid = _id("et")
|
||||
c.execute(
|
||||
"""INSERT INTO event_types(
|
||||
id,host_id,schedule_id,slug,title,description,length_minutes,
|
||||
slot_interval,buffer_before,buffer_after,locations_json,active,created_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
eid,
|
||||
h["id"],
|
||||
sch["id"],
|
||||
slug,
|
||||
title,
|
||||
data.get("description") or "",
|
||||
length,
|
||||
interval,
|
||||
int(data.get("buffer_before") or 0),
|
||||
int(data.get("buffer_after") or 0),
|
||||
_json(locs),
|
||||
1,
|
||||
now,
|
||||
),
|
||||
)
|
||||
row = c.execute("SELECT * FROM event_types WHERE id=?", (eid,)).fetchone()
|
||||
return _event_out(dict(row))
|
||||
|
||||
|
||||
# —— slots (Cal.com getSchedule / availableSlots parity) ——
|
||||
|
||||
|
||||
def _parse_utc(s: str) -> datetime:
|
||||
if s.endswith("Z"):
|
||||
s = s[:-1] + "+00:00"
|
||||
return datetime.fromisoformat(s).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def available_slots(
|
||||
username: str,
|
||||
event_slug: str,
|
||||
day: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Return bookable UTC slots for a local calendar day (YYYY-MM-DD)."""
|
||||
et = get_event_type(username, event_slug)
|
||||
if not et or not et.get("active"):
|
||||
raise ValueError("event_type_not_found")
|
||||
host = et["host"]
|
||||
sch = et.get("schedule") or {}
|
||||
tz_name = sch.get("timezone") or host.get("timezone") or "Asia/Shanghai"
|
||||
try:
|
||||
tz = ZoneInfo(tz_name)
|
||||
except Exception:
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
tz_name = "Asia/Shanghai"
|
||||
|
||||
try:
|
||||
day_d = date.fromisoformat(day)
|
||||
except ValueError as e:
|
||||
raise ValueError("invalid_day") from e
|
||||
|
||||
length = int(et["length_minutes"])
|
||||
interval = int(et.get("slot_interval") or 15)
|
||||
buf_before = int(et.get("buffer_before") or 0)
|
||||
buf_after = int(et.get("buffer_after") or 0)
|
||||
cal_day = PY_TO_CAL[day_d.weekday()]
|
||||
windows = [
|
||||
w
|
||||
for w in (sch.get("availability") or [])
|
||||
if cal_day in (w.get("days") or [])
|
||||
]
|
||||
if not windows:
|
||||
return {
|
||||
"ok": True,
|
||||
"day": day,
|
||||
"timezone": tz_name,
|
||||
"slots": [],
|
||||
"event_type": {"slug": et["slug"], "length_minutes": length},
|
||||
}
|
||||
|
||||
# busy from accepted bookings that day (host local)
|
||||
day_start = datetime(day_d.year, day_d.month, day_d.day, 0, 0, tzinfo=tz)
|
||||
day_end = day_start + timedelta(days=1)
|
||||
with _conn() as c:
|
||||
busy_rows = c.execute(
|
||||
"""SELECT start_utc,end_utc FROM bookings
|
||||
WHERE host_id=? AND status='accepted'
|
||||
AND start_utc < ? AND end_utc > ?""",
|
||||
(
|
||||
host["id"],
|
||||
day_end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
day_start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
),
|
||||
).fetchall()
|
||||
busy = [(_parse_utc(b["start_utc"]), _parse_utc(b["end_utc"])) for b in busy_rows]
|
||||
|
||||
now_utc = datetime.now(timezone.utc)
|
||||
slots: list[dict[str, str]] = []
|
||||
for w in windows:
|
||||
start_m = int(w.get("startTime") or 0)
|
||||
end_m = int(w.get("endTime") or 0)
|
||||
cursor = day_start + timedelta(minutes=start_m)
|
||||
window_end = day_start + timedelta(minutes=end_m)
|
||||
while cursor + timedelta(minutes=length) <= window_end:
|
||||
slot_start = cursor
|
||||
slot_end = cursor + timedelta(minutes=length)
|
||||
slot_start_utc = slot_start.astimezone(timezone.utc)
|
||||
slot_end_utc = slot_end.astimezone(timezone.utc)
|
||||
# past
|
||||
if slot_start_utc <= now_utc + timedelta(minutes=5):
|
||||
cursor += timedelta(minutes=interval)
|
||||
continue
|
||||
# overlap busy with buffers
|
||||
blocked = False
|
||||
for b0, b1 in busy:
|
||||
a0 = slot_start_utc - timedelta(minutes=buf_before)
|
||||
a1 = slot_end_utc + timedelta(minutes=buf_after)
|
||||
if a0 < b1 and a1 > b0:
|
||||
blocked = True
|
||||
break
|
||||
if not blocked:
|
||||
slots.append(
|
||||
{
|
||||
"start": slot_start_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"end": slot_end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"local": slot_start.strftime("%H:%M"),
|
||||
}
|
||||
)
|
||||
cursor += timedelta(minutes=interval)
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"day": day,
|
||||
"timezone": tz_name,
|
||||
"slots": slots,
|
||||
"event_type": {
|
||||
"slug": et["slug"],
|
||||
"title": et["title"],
|
||||
"length_minutes": length,
|
||||
},
|
||||
"host": {"username": host["username"], "name": host["name"]},
|
||||
}
|
||||
|
||||
|
||||
# —— bookings ——
|
||||
|
||||
|
||||
def create_booking(data: dict[str, Any]) -> dict[str, Any]:
|
||||
username = (data.get("username") or "").strip()
|
||||
slug = (data.get("event_slug") or data.get("slug") or "").strip()
|
||||
start = (data.get("start") or "").strip()
|
||||
attendee_name = (data.get("attendee_name") or "").strip()
|
||||
if not username or not slug or not start or not attendee_name:
|
||||
raise ValueError("username_slug_start_attendee_required")
|
||||
|
||||
et = get_event_type(username, slug)
|
||||
if not et or not et.get("active"):
|
||||
raise ValueError("event_type_not_found")
|
||||
|
||||
start_utc = _parse_utc(start if "T" in start else start + "Z")
|
||||
end_utc = start_utc + timedelta(minutes=int(et["length_minutes"]))
|
||||
day = start_utc.astimezone(
|
||||
ZoneInfo(et["host"].get("timezone") or "Asia/Shanghai")
|
||||
).date().isoformat()
|
||||
|
||||
# re-validate slot still free
|
||||
avail = available_slots(username, slug, day)
|
||||
ok_starts = {s["start"] for s in avail["slots"]}
|
||||
start_key = start_utc.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
if start_key not in ok_starts:
|
||||
raise ValueError("slot_unavailable")
|
||||
|
||||
locs = et.get("locations") or []
|
||||
loc_label = data.get("location") or (
|
||||
locs[0].get("label") if locs else "Coffeechat"
|
||||
)
|
||||
now = _now()
|
||||
bid = _id("bk")
|
||||
uid = _id("uid")
|
||||
with _conn() as c:
|
||||
c.execute(
|
||||
"""INSERT INTO bookings(
|
||||
id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes,
|
||||
attendee_name,attendee_email,attendee_device,created_at,cancelled_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
bid,
|
||||
uid,
|
||||
et["id"],
|
||||
et["host"]["id"],
|
||||
et["title"],
|
||||
"accepted",
|
||||
start_key,
|
||||
end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
loc_label,
|
||||
data.get("notes") or "",
|
||||
attendee_name,
|
||||
data.get("attendee_email"),
|
||||
data.get("attendee_device"),
|
||||
now,
|
||||
None,
|
||||
),
|
||||
)
|
||||
return get_booking(bid) # type: ignore[return-value]
|
||||
|
||||
|
||||
def get_booking(booking_id: str) -> dict[str, Any] | None:
|
||||
with _conn() as c:
|
||||
r = c.execute(
|
||||
"SELECT * FROM bookings WHERE id=? OR uid=?",
|
||||
(booking_id, booking_id),
|
||||
).fetchone()
|
||||
if not r:
|
||||
return None
|
||||
h = c.execute("SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],)).fetchone()
|
||||
return _booking_out(dict(r), host=dict(h) if h else None)
|
||||
|
||||
|
||||
def list_bookings(
|
||||
*,
|
||||
host_username: str | None = None,
|
||||
status: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
with _conn() as c:
|
||||
q = "SELECT b.* FROM bookings b"
|
||||
args: list[Any] = []
|
||||
if host_username:
|
||||
q += " JOIN hosts h ON h.id=b.host_id WHERE (h.username=? OR h.id=?)"
|
||||
args.extend([host_username, host_username])
|
||||
else:
|
||||
q += " WHERE 1=1"
|
||||
if status:
|
||||
q += " AND b.status=?"
|
||||
args.append(status)
|
||||
q += " ORDER BY b.start_utc DESC LIMIT 100"
|
||||
rows = c.execute(q, args).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
h = c.execute(
|
||||
"SELECT username,name,city FROM hosts WHERE id=?",
|
||||
(r["host_id"],),
|
||||
).fetchone()
|
||||
out.append(_booking_out(dict(r), host=dict(h) if h else None))
|
||||
return out
|
||||
|
||||
|
||||
def cancel_booking(booking_id: str) -> dict[str, Any] | None:
|
||||
with _conn() as c:
|
||||
r = c.execute(
|
||||
"SELECT id FROM bookings WHERE id=? OR uid=?",
|
||||
(booking_id, booking_id),
|
||||
).fetchone()
|
||||
if not r:
|
||||
return None
|
||||
c.execute(
|
||||
"UPDATE bookings SET status='cancelled', cancelled_at=? WHERE id=?",
|
||||
(_now(), r["id"]),
|
||||
)
|
||||
return get_booking(r["id"])
|
||||
|
||||
|
||||
def _booking_out(r: dict[str, Any], host: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"uid": r["uid"],
|
||||
"event_type_id": r["event_type_id"],
|
||||
"host_id": r["host_id"],
|
||||
"host": host,
|
||||
"title": r["title"],
|
||||
"status": r["status"],
|
||||
"start": r["start_utc"],
|
||||
"end": r["end_utc"],
|
||||
"location": r.get("location") or "",
|
||||
"notes": r.get("notes") or "",
|
||||
"attendee": {
|
||||
"name": r["attendee_name"],
|
||||
"email": r.get("attendee_email"),
|
||||
"device": r.get("attendee_device"),
|
||||
},
|
||||
"created_at": r["created_at"],
|
||||
"cancelled_at": r.get("cancelled_at"),
|
||||
}
|
||||
@ -33,8 +33,8 @@ class Settings(BaseSettings):
|
||||
|
||||
# JWT / Admin
|
||||
jwt_secret: str = "nomadro-jwt-local-dev-2026"
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = "Xiao4669805"
|
||||
admin_username: str = "hackrobot"
|
||||
admin_password: str = "Xiao4669805@"
|
||||
|
||||
# PocketBase
|
||||
pb_url: str = "http://127.0.0.1:8090"
|
||||
|
||||
@ -26,11 +26,11 @@ PRODUCT_OFFERS: list[dict[str, Any]] = [
|
||||
"label": "tiktok",
|
||||
"name": "tiktok",
|
||||
"product_id": "tiktok",
|
||||
"price_fen": 29800,
|
||||
"price_fen": 8800,
|
||||
"unlock_percent": 30,
|
||||
"free": False,
|
||||
"image": "props/tiktok.png",
|
||||
"remark": "已发布 · ¥298",
|
||||
"remark": "已发布 · ¥88",
|
||||
},
|
||||
{
|
||||
"key": "youtube",
|
||||
|
||||
@ -91,6 +91,12 @@ app.include_router(weapp_switches_admin.router)
|
||||
app.include_router(social_ops_admin.router)
|
||||
app.include_router(social_ugc_admin.router)
|
||||
app.include_router(community_admin.router)
|
||||
# 运营:ntfy 状态 / 试推(admin.nomadro.com)
|
||||
from ebook_svc.routers import ops_admin # noqa: E402
|
||||
from ebook_svc.routers import audience_admin # noqa: E402
|
||||
|
||||
app.include_router(ops_admin.router)
|
||||
app.include_router(audience_admin.router)
|
||||
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
||||
app.include_router(public_config.router)
|
||||
|
||||
|
||||
38
apps/api/services/ebook_svc/routers/audience_admin.py
Normal file
38
apps/api/services/ebook_svc/routers/audience_admin.py
Normal file
@ -0,0 +1,38 @@
|
||||
"""受众分轨 — admin.nomadro.com/audience(中文用户 / 国际)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services.audience_config import read_audience_config, write_audience_config
|
||||
|
||||
router = APIRouter(prefix="/api/admin/audience", tags=["audience-admin"])
|
||||
|
||||
|
||||
class LaneIn(BaseModel):
|
||||
payEnabled: bool | None = None
|
||||
socialFollow: bool | None = None
|
||||
followChannel: Literal["wechat", "x", "none"] | None = None
|
||||
vipCta: str | None = None
|
||||
homeLead: str | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class AudienceBody(BaseModel):
|
||||
defaultLane: Literal["cn", "intl"] | None = None
|
||||
cn: LaneIn | None = None
|
||||
intl: LaneIn | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_audience(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return read_audience_config()
|
||||
|
||||
|
||||
@router.put("")
|
||||
async def put_audience(body: AudienceBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
patch = body.model_dump(exclude_none=True)
|
||||
return write_audience_config(patch)
|
||||
46
apps/api/services/ebook_svc/routers/ops_admin.py
Normal file
46
apps/api/services/ebook_svc/routers/ops_admin.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""运营:ntfy 状态 / 试推 — admin.nomadro.com 与 .cn 共用。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services import ntfy as ntfy_svc
|
||||
|
||||
router = APIRouter(prefix="/api/admin/ops", tags=["ops-admin"])
|
||||
|
||||
|
||||
class NtfyTestBody(BaseModel):
|
||||
title: str = Field(default="[WebAdmin] 试推", max_length=80)
|
||||
message: str = Field(default="admin.nomadro.com 通知通路正常", max_length=500)
|
||||
priority: int = Field(default=3, ge=1, le=5)
|
||||
tags: str | None = Field(default="white_check_mark,globe_with_meridians")
|
||||
|
||||
|
||||
@router.get("/ntfy")
|
||||
async def ntfy_status(_: str = Depends(require_admin)) -> dict:
|
||||
base = (settings.ntfy_base_url or "").rstrip("/")
|
||||
topic = (settings.ntfy_topic or "").strip().strip("/")
|
||||
return {
|
||||
"enabled": bool(settings.ntfy_enabled),
|
||||
"baseUrl": base,
|
||||
"topic": topic,
|
||||
"hasToken": bool((settings.ntfy_token or "").strip()),
|
||||
"publicHint": "https://ntfy.nomadro.cn/" + topic if topic else "",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/ntfy/test")
|
||||
async def ntfy_test(body: NtfyTestBody, _: str = Depends(require_admin)) -> dict:
|
||||
ok = await ntfy_svc.notify(
|
||||
body.message,
|
||||
title=body.title[:80],
|
||||
tags=body.tags,
|
||||
priority=body.priority,
|
||||
)
|
||||
return {
|
||||
"ok": ok,
|
||||
"enabled": bool(settings.ntfy_enabled),
|
||||
"topic": (settings.ntfy_topic or "").strip(),
|
||||
}
|
||||
128
apps/api/services/ebook_svc/services/audience_config.py
Normal file
128
apps/api/services/ebook_svc/services/audience_config.py
Normal file
@ -0,0 +1,128 @@
|
||||
"""受众分轨 remote-config.audience — .com 国际优先,中文用户特殊对待。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
|
||||
DEFAULT_CN: dict[str, Any] = {
|
||||
"payEnabled": True,
|
||||
"socialFollow": True,
|
||||
"followChannel": "wechat",
|
||||
"vipCta": "立即加入 · ¥88",
|
||||
"homeLead": "",
|
||||
"note": "中文用户特殊线:微信内置 / is-china-user;支付走 zpay/xpay",
|
||||
}
|
||||
|
||||
DEFAULT_INTL: dict[str, Any] = {
|
||||
"payEnabled": True,
|
||||
"socialFollow": True,
|
||||
"followChannel": "x",
|
||||
"vipCta": "Join VIP",
|
||||
"homeLead": "",
|
||||
"note": ".com 默认国际线(英语为主);Creem / NOWPayments",
|
||||
}
|
||||
|
||||
DEFAULT_AUDIENCE: dict[str, Any] = {
|
||||
"defaultLane": "intl",
|
||||
"cn": deepcopy(DEFAULT_CN),
|
||||
"intl": deepcopy(DEFAULT_INTL),
|
||||
}
|
||||
|
||||
|
||||
def _read_raw() -> dict[str, Any]:
|
||||
path = resolve_config_file()
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _write_raw(out: dict[str, Any]) -> None:
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
if path.is_file():
|
||||
bak = path.with_suffix(path.suffix + f".bak-{out['updatedAt'].replace(':', '-')}")
|
||||
try:
|
||||
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
from ebook_svc.services.config_live import notify_config_written
|
||||
|
||||
notify_config_written(out)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _norm_lane(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
||||
m = raw if isinstance(raw, dict) else {}
|
||||
out = deepcopy(fallback)
|
||||
if "payEnabled" in m:
|
||||
out["payEnabled"] = bool(m["payEnabled"])
|
||||
if "socialFollow" in m:
|
||||
out["socialFollow"] = bool(m["socialFollow"])
|
||||
ch = m.get("followChannel")
|
||||
if ch in ("wechat", "x", "none"):
|
||||
out["followChannel"] = ch
|
||||
if "vipCta" in m and m["vipCta"] is not None:
|
||||
out["vipCta"] = str(m["vipCta"])
|
||||
if "homeLead" in m and m["homeLead"] is not None:
|
||||
out["homeLead"] = str(m["homeLead"])
|
||||
if "note" in m and m["note"] is not None:
|
||||
out["note"] = str(m["note"])
|
||||
return out
|
||||
|
||||
|
||||
def read_audience_config() -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
a = raw.get("audience") if isinstance(raw.get("audience"), dict) else {}
|
||||
lane = a.get("defaultLane")
|
||||
default_lane = lane if lane in ("cn", "intl") else "intl"
|
||||
return {
|
||||
"ok": True,
|
||||
"defaultLane": default_lane,
|
||||
"cn": _norm_lane(a.get("cn"), DEFAULT_CN),
|
||||
"intl": _norm_lane(a.get("intl"), DEFAULT_INTL),
|
||||
"detection": {
|
||||
"lib": "is-china-user",
|
||||
"wechatUa": "micromessenger",
|
||||
"repo": "https://github.com/yArna/isChinaUser",
|
||||
"note": ".com 国际优先;微信内置或 is-china-user 命中 → cn 特殊线",
|
||||
},
|
||||
"version": raw.get("version"),
|
||||
"updatedAt": raw.get("updatedAt"),
|
||||
"configPath": str(resolve_config_file()),
|
||||
}
|
||||
|
||||
|
||||
def write_audience_config(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
out: dict[str, Any] = dict(raw) if raw else {"version": 2}
|
||||
cur = out.get("audience") if isinstance(out.get("audience"), dict) else {}
|
||||
audience = {
|
||||
"defaultLane": cur.get("defaultLane") or "intl",
|
||||
"cn": _norm_lane(cur.get("cn"), DEFAULT_CN),
|
||||
"intl": _norm_lane(cur.get("intl"), DEFAULT_INTL),
|
||||
}
|
||||
if patch.get("defaultLane") in ("cn", "intl"):
|
||||
audience["defaultLane"] = patch["defaultLane"]
|
||||
if isinstance(patch.get("cn"), dict):
|
||||
audience["cn"] = _norm_lane(patch["cn"], audience["cn"])
|
||||
if isinstance(patch.get("intl"), dict):
|
||||
audience["intl"] = _norm_lane(patch["intl"], audience["intl"])
|
||||
out["audience"] = audience
|
||||
_write_raw(out)
|
||||
return read_audience_config()
|
||||
@ -98,6 +98,13 @@ CLIENT_LABEL = {
|
||||
"h5": "H5",
|
||||
"miniapp": "小程序",
|
||||
"api": "API",
|
||||
"web": "Web",
|
||||
"web_com": "nomadro.com",
|
||||
"web_cn": "nomadro.cn",
|
||||
"web_intl": "Web·intl",
|
||||
"web_cn_tag": "Web·cn",
|
||||
"vip_web": "VIP Web",
|
||||
"web_local": "localhost",
|
||||
"wx_push": "微信推送",
|
||||
}
|
||||
|
||||
@ -105,8 +112,22 @@ CLIENT_NTFY_TAGS = {
|
||||
"tt": "tiktok",
|
||||
"weapp": "wechat",
|
||||
"h5": "globe_with_meridians",
|
||||
"web": "globe_with_meridians",
|
||||
"web_com": "globe_with_meridians",
|
||||
"web_cn": "globe_with_meridians",
|
||||
"web_intl": "globe_with_meridians",
|
||||
"web_local": "globe_with_meridians",
|
||||
"vip_web": "globe_with_meridians",
|
||||
}
|
||||
|
||||
# 门户 Web 由 Next /api/track 负责 ntfy;此处只入库,避免双推 + page_view 刷屏
|
||||
_WEB_STORE_ONLY_PREFIXES = ("web", "vip_web")
|
||||
|
||||
|
||||
def _web_store_only(client: str | None) -> bool:
|
||||
c = (client or "").strip().lower()
|
||||
return any(c == p or c.startswith(f"{p}_") for p in _WEB_STORE_ONLY_PREFIXES)
|
||||
|
||||
|
||||
def _short_openid(openid: str | None) -> str:
|
||||
if not openid:
|
||||
@ -213,7 +234,7 @@ async def ingest_events(
|
||||
except Exception:
|
||||
logger.exception("track save failed")
|
||||
|
||||
if name in NTFY_ALWAYS:
|
||||
if name in NTFY_ALWAYS and not _web_store_only(client_key):
|
||||
ntfy_title = _title(name, client=client_key)
|
||||
if name == "wx_push" and ev.get("label"):
|
||||
ntfy_title = f"[{_channel_label(client_key)}] {ev['label']}"[:80]
|
||||
|
||||
@ -22,7 +22,7 @@ DEFAULT_VIP = {
|
||||
"gameEnabled": False,
|
||||
# VIP 跳转默认关 → 加群仍弹窗(现网);后台可开 vip
|
||||
"joinGroupAction": "popup",
|
||||
"vipPriceFen": 29800,
|
||||
"vipPriceFen": 8800,
|
||||
"vipProductId": "tiktok",
|
||||
# CTA 不含价格;价格由方案卡片/后台展示
|
||||
"vipCta": "立即加入",
|
||||
|
||||
@ -196,6 +196,11 @@ def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
base = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
|
||||
modules[key] = _norm_mod(val, base)
|
||||
|
||||
# 防止补丁写入后兄弟模块丢失 / 首页入口被清空:始终补齐 MODULE_KEYS
|
||||
for key in MODULE_KEYS:
|
||||
modules[key] = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
|
||||
modules["game"] = {**DEFAULT_MODULES["game"], "enabled": False}
|
||||
|
||||
if isinstance(patch.get("flags"), dict):
|
||||
fp = patch["flags"]
|
||||
if "payEnabled" in fp:
|
||||
|
||||
1
apps/api/services/notify_svc/__init__.py
Normal file
1
apps/api/services/notify_svc/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Nomadro notify — Novu-domain secondary-dev (workflows · subscribers · inbox)."""
|
||||
21
apps/api/services/notify_svc/config.py
Normal file
21
apps/api/services/notify_svc/config.py
Normal file
@ -0,0 +1,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
NOTIFY_ENABLED = os.getenv("NOTIFY_ENABLED", "1").strip().lower() not in {
|
||||
"0",
|
||||
"false",
|
||||
"no",
|
||||
"off",
|
||||
}
|
||||
|
||||
DATA_DIR = Path(os.getenv("NOTIFY_DATA_DIR", "/var/lib/nomadro/notify"))
|
||||
if not DATA_DIR.exists():
|
||||
DATA_DIR = (
|
||||
Path(os.getenv("NOTIFY_DATA_DIR_LOCAL", "")).resolve()
|
||||
if os.getenv("NOTIFY_DATA_DIR_LOCAL")
|
||||
else Path.cwd() / "data" / "notify"
|
||||
)
|
||||
|
||||
DB_PATH = DATA_DIR / "notify.sqlite3"
|
||||
3
apps/api/services/notify_svc/routers/__init__.py
Normal file
3
apps/api/services/notify_svc/routers/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .api import router
|
||||
|
||||
__all__ = ["router"]
|
||||
295
apps/api/services/notify_svc/routers/api.py
Normal file
295
apps/api/services/notify_svc/routers/api.py
Normal file
@ -0,0 +1,295 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from notify_svc import store
|
||||
|
||||
router = APIRouter(tags=["notify"])
|
||||
|
||||
|
||||
class SubscriberIn(BaseModel):
|
||||
subscriber_id: str = Field(min_length=1, max_length=120)
|
||||
email: str | None = None
|
||||
phone: str | None = None
|
||||
first_name: str | None = None
|
||||
last_name: str | None = None
|
||||
avatar: str | None = None
|
||||
locale: str | None = "zh"
|
||||
data: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class TopicIn(BaseModel):
|
||||
key: str = Field(min_length=1, max_length=80)
|
||||
name: str = Field(default="", max_length=200)
|
||||
|
||||
|
||||
class TopicMemberIn(BaseModel):
|
||||
subscriber_id: str = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
class StepIn(BaseModel):
|
||||
id: str | None = None
|
||||
type: str = "in_app"
|
||||
name: str = ""
|
||||
position: float | None = None
|
||||
active: bool = True
|
||||
template: dict[str, Any] = Field(default_factory=dict)
|
||||
filters: list[Any] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WorkflowIn(BaseModel):
|
||||
workflow_id: str = Field(min_length=1, max_length=120)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
description: str = ""
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
steps: list[StepIn] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WorkflowPatch(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
active: bool | None = None
|
||||
tags: list[str] | None = None
|
||||
steps: list[StepIn] | None = None
|
||||
|
||||
|
||||
class TriggerIn(BaseModel):
|
||||
workflow_id: str = Field(min_length=1, max_length=120)
|
||||
subscriber_id: str | None = None
|
||||
topic_key: str | None = None
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class PrefsIn(BaseModel):
|
||||
channels: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class MessagePatch(BaseModel):
|
||||
read: bool | None = None
|
||||
archived: bool | None = None
|
||||
deleted: bool | None = None
|
||||
|
||||
|
||||
class ReadAllIn(BaseModel):
|
||||
subscriber_id: str = "guest"
|
||||
category: str | None = None
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health():
|
||||
return {"ok": True, "service": "nomadro-notify", "inspiredBy": ["novu"]}
|
||||
|
||||
|
||||
@router.get("/subscribers")
|
||||
def subscribers():
|
||||
return {"ok": True, "subscribers": store.list_subscribers()}
|
||||
|
||||
|
||||
@router.get("/subscribers/{subscriber_id}")
|
||||
def subscriber(subscriber_id: str):
|
||||
s = store.get_subscriber(subscriber_id)
|
||||
if not s:
|
||||
raise HTTPException(404, "subscriber_not_found")
|
||||
return {"ok": True, "subscriber": s}
|
||||
|
||||
|
||||
@router.post("/subscribers")
|
||||
def create_subscriber(body: SubscriberIn):
|
||||
try:
|
||||
s = store.upsert_subscriber(body.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "subscriber": s}
|
||||
|
||||
|
||||
@router.put("/subscribers/{subscriber_id}")
|
||||
def update_subscriber(subscriber_id: str, body: SubscriberIn):
|
||||
data = body.model_dump()
|
||||
data["subscriber_id"] = subscriber_id
|
||||
try:
|
||||
s = store.upsert_subscriber(data)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "subscriber": s}
|
||||
|
||||
|
||||
@router.delete("/subscribers/{subscriber_id}")
|
||||
def remove_subscriber(subscriber_id: str):
|
||||
if not store.delete_subscriber(subscriber_id):
|
||||
raise HTTPException(404, "subscriber_not_found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/subscribers/{subscriber_id}/preferences")
|
||||
def get_prefs(subscriber_id: str):
|
||||
p = store.get_preferences(subscriber_id)
|
||||
if not p:
|
||||
raise HTTPException(404, "subscriber_not_found")
|
||||
return {"ok": True, "preferences": p}
|
||||
|
||||
|
||||
@router.put("/subscribers/{subscriber_id}/preferences")
|
||||
def put_prefs(subscriber_id: str, body: PrefsIn):
|
||||
try:
|
||||
p = store.set_preferences(subscriber_id, body.channels)
|
||||
except ValueError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
return {"ok": True, "preferences": p}
|
||||
|
||||
|
||||
@router.get("/topics")
|
||||
def topics():
|
||||
return {"ok": True, "topics": store.list_topics()}
|
||||
|
||||
|
||||
@router.post("/topics")
|
||||
def create_topic(body: TopicIn):
|
||||
try:
|
||||
t = store.create_topic(body.key, body.name)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "topic": t}
|
||||
|
||||
|
||||
@router.post("/topics/{topic_key}/subscribers")
|
||||
def topic_add(topic_key: str, body: TopicMemberIn):
|
||||
try:
|
||||
t = store.add_topic_subscriber(topic_key, body.subscriber_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "topic": t}
|
||||
|
||||
|
||||
@router.delete("/topics/{topic_key}/subscribers/{subscriber_id}")
|
||||
def topic_remove(topic_key: str, subscriber_id: str):
|
||||
if not store.remove_topic_subscriber(topic_key, subscriber_id):
|
||||
raise HTTPException(404, "not_found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/workflows")
|
||||
def workflows():
|
||||
return {"ok": True, "workflows": store.list_workflows()}
|
||||
|
||||
|
||||
@router.get("/workflows/{workflow_id}")
|
||||
def workflow(workflow_id: str):
|
||||
w = store.get_workflow(workflow_id)
|
||||
if not w:
|
||||
raise HTTPException(404, "workflow_not_found")
|
||||
return {"ok": True, "workflow": w}
|
||||
|
||||
|
||||
@router.post("/workflows")
|
||||
def create_workflow(body: WorkflowIn):
|
||||
try:
|
||||
w = store.create_workflow(
|
||||
body.workflow_id,
|
||||
body.name,
|
||||
body.description,
|
||||
[s.model_dump() for s in body.steps] if body.steps else None,
|
||||
body.tags,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "workflow": w}
|
||||
|
||||
|
||||
@router.patch("/workflows/{workflow_id}")
|
||||
def patch_workflow(workflow_id: str, body: WorkflowPatch):
|
||||
patch = body.model_dump(exclude_unset=True)
|
||||
if "steps" in patch and patch["steps"] is not None:
|
||||
patch["steps"] = [s if isinstance(s, dict) else s for s in patch["steps"]]
|
||||
w = store.update_workflow(workflow_id, patch)
|
||||
if not w:
|
||||
raise HTTPException(404, "workflow_not_found")
|
||||
return {"ok": True, "workflow": w}
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}")
|
||||
def remove_workflow(workflow_id: str):
|
||||
if not store.delete_workflow(workflow_id):
|
||||
raise HTTPException(404, "workflow_not_found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/events/trigger")
|
||||
def trigger(body: TriggerIn):
|
||||
try:
|
||||
result = store.trigger_event(
|
||||
workflow_id=body.workflow_id,
|
||||
subscriber_id=body.subscriber_id,
|
||||
topic_key=body.topic_key,
|
||||
payload=body.payload,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, **result}
|
||||
|
||||
|
||||
@router.get("/inbox")
|
||||
def inbox(
|
||||
subscriber_id: str = Query(default="guest"),
|
||||
include_archived: bool = False,
|
||||
category: str | None = Query(default=None),
|
||||
):
|
||||
return {
|
||||
"ok": True,
|
||||
"subscriber_id": subscriber_id,
|
||||
"unread": store.unread_count(subscriber_id),
|
||||
"unread_by_category": store.unread_by_category(subscriber_id),
|
||||
"messages": store.list_inbox(
|
||||
subscriber_id,
|
||||
include_archived=include_archived,
|
||||
category=category,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/inbox/unread")
|
||||
def inbox_unread(subscriber_id: str = Query(default="guest")):
|
||||
return {
|
||||
"ok": True,
|
||||
"subscriber_id": subscriber_id,
|
||||
"unread": store.unread_count(subscriber_id),
|
||||
"unread_by_category": store.unread_by_category(subscriber_id),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/inbox/read-all")
|
||||
def inbox_read_all(body: ReadAllIn):
|
||||
n = store.mark_all_read(body.subscriber_id, body.category)
|
||||
return {
|
||||
"ok": True,
|
||||
"updated": n,
|
||||
"unread": store.unread_count(body.subscriber_id),
|
||||
"unread_by_category": store.unread_by_category(body.subscriber_id),
|
||||
}
|
||||
|
||||
|
||||
@router.patch("/inbox/{message_id}")
|
||||
def patch_inbox(message_id: str, body: MessagePatch):
|
||||
m = store.patch_message(message_id, body.model_dump(exclude_unset=True))
|
||||
if not m:
|
||||
raise HTTPException(404, "message_not_found")
|
||||
return {"ok": True, "message": m}
|
||||
|
||||
|
||||
@router.delete("/inbox/{message_id}")
|
||||
def delete_inbox(message_id: str):
|
||||
if not store.delete_message(message_id):
|
||||
raise HTTPException(404, "message_not_found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/activity")
|
||||
def activity(limit: int = Query(default=50, ge=1, le=200)):
|
||||
return {"ok": True, "activity": store.list_activity(limit)}
|
||||
|
||||
|
||||
@router.get("/integrations")
|
||||
def integrations():
|
||||
return {"ok": True, "integrations": store.list_integrations()}
|
||||
1312
apps/api/services/notify_svc/store.py
Normal file
1312
apps/api/services/notify_svc/store.py
Normal file
File diff suppressed because it is too large
Load Diff
@ -62,6 +62,21 @@ def reset_provider():
|
||||
_provider_instance = None
|
||||
|
||||
|
||||
def _overseas_provider(preferred: str | None = None) -> PaymentProvider:
|
||||
"""海外:显式 nowpayments 优先;否则 Creem → 加密货币 NOWPayments 回退。"""
|
||||
pref = (preferred or "").strip().lower()
|
||||
if pref == "nowpayments":
|
||||
return get_payment_provider_by_name("nowpayments")
|
||||
if pref == "creem":
|
||||
if (CREEM_API_KEY or "").strip():
|
||||
return get_payment_provider_by_name("creem")
|
||||
# Creem 未配密钥时自动改走加密支付
|
||||
return get_payment_provider_by_name("nowpayments")
|
||||
if (CREEM_API_KEY or "").strip():
|
||||
return get_payment_provider_by_name("creem")
|
||||
return get_payment_provider_by_name("nowpayments")
|
||||
|
||||
|
||||
def resolve_provider(
|
||||
device: str | None = None,
|
||||
req_provider: str | None = None,
|
||||
@ -70,18 +85,20 @@ def resolve_provider(
|
||||
) -> PaymentProvider:
|
||||
"""
|
||||
根据区域 + 设备解析支付渠道:
|
||||
- region=overseas → creem(可用 nowpayments 显式覆盖)
|
||||
- region=overseas → creem(无密钥则 nowpayments;可显式 nowpayments)
|
||||
- 微信内(device=wechat 或 UA 含 MicroMessenger) → xorpay
|
||||
- PC/手机浏览器 → zpay
|
||||
显式传入的 provider 优先。
|
||||
显式传入的 provider 优先(海外缺 Creem 密钥时回退加密货币)。
|
||||
"""
|
||||
req = (req_provider or "").strip().lower()
|
||||
if req in _CN_NAMES or req in _OVERSEAS_NAMES:
|
||||
if req in _OVERSEAS_NAMES:
|
||||
return _overseas_provider(req)
|
||||
if req in _CN_NAMES:
|
||||
return get_payment_provider_by_name(req)
|
||||
|
||||
reg = (region or "").strip().lower()
|
||||
if reg in ("overseas", "intl", "global"):
|
||||
return get_payment_provider_by_name("creem")
|
||||
return _overseas_provider(None)
|
||||
|
||||
dev = (device or "pc").lower()
|
||||
if dev == "wechat":
|
||||
|
||||
@ -2,11 +2,15 @@
|
||||
ZPAY 支付渠道实现
|
||||
文档: https://z-pay.cn/doc.html
|
||||
支持:页面跳转支付、API 接口支付、异步通知验签
|
||||
|
||||
美国 VPS 常被 zpayz.cn CDN 掐断 POST;优先 z-pay.cn / api.z-pay.cn。
|
||||
可用环境变量覆盖:ZPAY_MAPI_URL / ZPAY_SUBMIT_URL / ZPAY_API_BASE
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import requests
|
||||
|
||||
@ -14,6 +18,23 @@ from .base import PaymentProvider
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 多域名:海外机优先通的排前面;国内机三个一般都能用
|
||||
_DEFAULT_MAPI_URLS = (
|
||||
"https://z-pay.cn/mapi.php",
|
||||
"https://api.z-pay.cn/mapi.php",
|
||||
"https://zpayz.cn/mapi.php",
|
||||
)
|
||||
_DEFAULT_SUBMIT_URLS = (
|
||||
"https://z-pay.cn/submit.php",
|
||||
"https://api.z-pay.cn/submit.php",
|
||||
"https://zpayz.cn/submit.php",
|
||||
)
|
||||
_DEFAULT_API_BASES = (
|
||||
"https://z-pay.cn",
|
||||
"https://api.z-pay.cn",
|
||||
"https://zpayz.cn",
|
||||
)
|
||||
|
||||
|
||||
def _is_internal_ip(ip: Optional[str]) -> bool:
|
||||
"""判断是否为内网 IP,ZPAY 可能拒收导致 Ubuntu 部署失败"""
|
||||
@ -27,16 +48,29 @@ def _is_internal_ip(ip: Optional[str]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _split_urls(raw: str | None, defaults: tuple[str, ...]) -> List[str]:
|
||||
if raw and raw.strip():
|
||||
return [u.strip() for u in raw.split(",") if u.strip()]
|
||||
return list(defaults)
|
||||
|
||||
|
||||
class ZPayProvider(PaymentProvider):
|
||||
"""ZPAY 支付(易支付兼容接口)"""
|
||||
|
||||
# API 地址
|
||||
SUBMIT_URL = "https://zpayz.cn/submit.php" # 页面跳转
|
||||
MAPI_URL = "https://zpayz.cn/mapi.php" # API 接口
|
||||
|
||||
def __init__(self, pid: str, key: str):
|
||||
self.pid = pid
|
||||
self.key = key
|
||||
self.mapi_urls = _split_urls(os.getenv("ZPAY_MAPI_URL"), _DEFAULT_MAPI_URLS)
|
||||
self.submit_urls = _split_urls(os.getenv("ZPAY_SUBMIT_URL"), _DEFAULT_SUBMIT_URLS)
|
||||
self.api_bases = _split_urls(os.getenv("ZPAY_API_BASE"), _DEFAULT_API_BASES)
|
||||
|
||||
@property
|
||||
def SUBMIT_URL(self) -> str:
|
||||
return self.submit_urls[0]
|
||||
|
||||
@property
|
||||
def MAPI_URL(self) -> str:
|
||||
return self.mapi_urls[0]
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@ -141,71 +175,73 @@ class ZPayProvider(PaymentProvider):
|
||||
params["sign_type"] = "MD5"
|
||||
params["sign"] = self._md5_sign(params)
|
||||
|
||||
try:
|
||||
resp = requests.post(self.MAPI_URL, data=params, timeout=15)
|
||||
except requests.exceptions.SSLError as e:
|
||||
logger.error("ZPAY SSL 错误(Ubuntu 可能 CA 证书不全): %s", e, exc_info=True)
|
||||
return {
|
||||
"status": "error",
|
||||
"provider": self.name,
|
||||
"msg": f"连接 zpayz.cn SSL 失败: {e}。Ubuntu 请安装 ca-certificates: apt install ca-certificates",
|
||||
}
|
||||
except requests.RequestException as e:
|
||||
logger.error("ZPAY 连接失败: %s", e, exc_info=True)
|
||||
return {
|
||||
"status": "error",
|
||||
"provider": self.name,
|
||||
"msg": f"连接 zpayz.cn 失败: {e}。请检查服务器网络、防火墙或 DNS。",
|
||||
}
|
||||
|
||||
try:
|
||||
result = resp.json()
|
||||
except Exception:
|
||||
result = {}
|
||||
# ZPAY 可能返回二次编码的 JSON(body 为 JSON 字符串),需再次解析
|
||||
if isinstance(result, str):
|
||||
last_err = ""
|
||||
resp = None
|
||||
result: Dict[str, Any] = {}
|
||||
for mapi_url in self.mapi_urls:
|
||||
try:
|
||||
result = json.loads(result)
|
||||
resp = requests.post(mapi_url, data=params, timeout=15)
|
||||
except requests.exceptions.SSLError as e:
|
||||
last_err = f"SSL 失败 ({mapi_url}): {e}"
|
||||
logger.warning("ZPAY SSL: %s", last_err)
|
||||
continue
|
||||
except requests.RequestException as e:
|
||||
last_err = f"连接失败 ({mapi_url}): {e}"
|
||||
logger.warning("ZPAY 连接: %s", last_err)
|
||||
continue
|
||||
|
||||
try:
|
||||
result = resp.json()
|
||||
except Exception:
|
||||
result = {}
|
||||
if not isinstance(result, dict):
|
||||
result = {}
|
||||
# 部分环境下 ZPAY 将成功数据放在 msg 中(msg 为 JSON 字符串)
|
||||
msg_val = result.get("msg")
|
||||
if isinstance(msg_val, str) and msg_val.strip().startswith("{"):
|
||||
# ZPAY 可能返回二次编码的 JSON(body 为 JSON 字符串),需再次解析
|
||||
if isinstance(result, str):
|
||||
try:
|
||||
result = json.loads(result)
|
||||
except Exception:
|
||||
result = {}
|
||||
if not isinstance(result, dict):
|
||||
result = {}
|
||||
# 部分环境下 ZPAY 将成功数据放在 msg 中(msg 为 JSON 字符串)
|
||||
msg_val = result.get("msg")
|
||||
if isinstance(msg_val, str) and msg_val.strip().startswith("{"):
|
||||
try:
|
||||
inner = json.loads(msg_val)
|
||||
if isinstance(inner, dict) and int(float(inner.get("code", 0))) == 1:
|
||||
result = inner
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
inner = json.loads(msg_val)
|
||||
if isinstance(inner, dict) and int(float(inner.get("code", 0))) == 1:
|
||||
result = inner
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
code = int(float(result.get("code", 0)))
|
||||
except (TypeError, ValueError):
|
||||
code = 0
|
||||
if code == 1:
|
||||
return {
|
||||
"status": "ok",
|
||||
"provider": self.name,
|
||||
"payurl": result.get("payurl"),
|
||||
"payurl2": result.get("payurl2"), # 微信 H5,手机浏览器打开可唤醒微信
|
||||
"qrcode": result.get("qrcode"),
|
||||
"img": result.get("img"),
|
||||
"O_id": result.get("O_id"),
|
||||
"trade_no": result.get("trade_no"),
|
||||
}
|
||||
err_msg = result.get("msg", resp.text)
|
||||
logger.error(
|
||||
"ZPAY create_order_api 失败 status=%s code=%s msg=%s resp_text=%s",
|
||||
resp.status_code,
|
||||
code,
|
||||
err_msg,
|
||||
resp.text[:500] if resp.text else "",
|
||||
)
|
||||
code = int(float(result.get("code", 0)))
|
||||
except (TypeError, ValueError):
|
||||
code = 0
|
||||
if code == 1:
|
||||
logger.info("ZPAY mapi ok via %s", mapi_url)
|
||||
return {
|
||||
"status": "ok",
|
||||
"provider": self.name,
|
||||
"payurl": result.get("payurl"),
|
||||
"payurl2": result.get("payurl2"), # 微信 H5,手机浏览器打开可唤醒微信
|
||||
"qrcode": result.get("qrcode"),
|
||||
"img": result.get("img"),
|
||||
"O_id": result.get("O_id"),
|
||||
"trade_no": result.get("trade_no"),
|
||||
"mapi_url": mapi_url,
|
||||
}
|
||||
last_err = str(result.get("msg") or (resp.text if resp is not None else "") or "unknown")
|
||||
logger.warning(
|
||||
"ZPAY mapi 业务失败 url=%s status=%s code=%s msg=%s",
|
||||
mapi_url,
|
||||
getattr(resp, "status_code", None),
|
||||
code,
|
||||
last_err[:300],
|
||||
)
|
||||
|
||||
logger.error("ZPAY create_order_api 全部域名失败: %s", last_err)
|
||||
return {
|
||||
"status": "error",
|
||||
"provider": self.name,
|
||||
"msg": err_msg,
|
||||
"msg": last_err or "ZPAY mapi 不可用",
|
||||
}
|
||||
|
||||
def verify_notify(self, data: Dict[str, Any]) -> bool:
|
||||
@ -229,22 +265,28 @@ class ZPayProvider(PaymentProvider):
|
||||
|
||||
def query_order_status(self, out_trade_no: str, timeout: int = 15) -> Dict[str, Any]:
|
||||
"""查询 ZPAY 订单支付状态(供 nomadvip/digital/cnomadcna/nomadlms 共用)"""
|
||||
url = f"https://zpayz.cn/api.php?act=order&pid={self.pid}&key={self.key}&out_trade_no={out_trade_no}"
|
||||
try:
|
||||
resp = requests.get(url, timeout=timeout)
|
||||
result = resp.json() if resp.ok else {}
|
||||
except Exception as e:
|
||||
return {"paid": False, "error": str(e)}
|
||||
try:
|
||||
code = result.get("code", 0)
|
||||
code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
|
||||
except (ValueError, TypeError):
|
||||
code = 0
|
||||
if code != 1:
|
||||
return {"paid": False, "msg": result.get("msg", "查询失败")}
|
||||
try:
|
||||
status = int(result.get("status", 0))
|
||||
except (ValueError, TypeError):
|
||||
status = 0
|
||||
money = result.get("money") or result.get("pay_price") or ""
|
||||
return {"paid": status == 1, "status": status, "pay_price": str(money) if money else ""}
|
||||
last_err = ""
|
||||
result: Dict[str, Any] = {}
|
||||
for base in self.api_bases:
|
||||
url = f"{base.rstrip('/')}/api.php?act=order&pid={self.pid}&key={self.key}&out_trade_no={out_trade_no}"
|
||||
try:
|
||||
resp = requests.get(url, timeout=timeout)
|
||||
result = resp.json() if resp.ok else {}
|
||||
except Exception as e:
|
||||
last_err = str(e)
|
||||
continue
|
||||
try:
|
||||
code = result.get("code", 0)
|
||||
code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
|
||||
except (ValueError, TypeError):
|
||||
code = 0
|
||||
if code != 1:
|
||||
last_err = str(result.get("msg", "查询失败"))
|
||||
continue
|
||||
try:
|
||||
status = int(result.get("status", 0))
|
||||
except (ValueError, TypeError):
|
||||
status = 0
|
||||
money = result.get("money") or result.get("pay_price") or ""
|
||||
return {"paid": status == 1, "status": status, "pay_price": str(money) if money else ""}
|
||||
return {"paid": False, "error": last_err or "查询失败"}
|
||||
|
||||
@ -124,6 +124,16 @@ async def nomadvip_payh5(item: dict, request: Request):
|
||||
}
|
||||
name = type_map.get(pay_type, "VIP会员充值")
|
||||
notify_url = _get_notify_path(provider.name)
|
||||
# 海外金额:fen→美元展示数值(与前端 intl 定价一致,先按元数值当 USD)
|
||||
overseas_extra = None
|
||||
if provider.name in ("creem", "nowpayments"):
|
||||
overseas_extra = {
|
||||
"amount_cents": max(100, int(round(float(total_fee_yuan) * 100))),
|
||||
"currency": "USD",
|
||||
"price_amount": float(total_fee_yuan),
|
||||
"price_currency": "usd",
|
||||
"product_name": name,
|
||||
}
|
||||
result = provider.create_order(
|
||||
order_id=order_id,
|
||||
name=name,
|
||||
@ -132,7 +142,31 @@ async def nomadvip_payh5(item: dict, request: Request):
|
||||
notify_url=notify_url,
|
||||
return_url=item.get("return_url"),
|
||||
client_ip=item.get("client_ip"),
|
||||
extra=overseas_extra,
|
||||
)
|
||||
# Creem 未配置时回退加密货币 NOWPayments
|
||||
if (
|
||||
provider.name == "creem"
|
||||
and result.get("ok") is False
|
||||
and "CREEM_API_KEY" in str(result.get("error") or "")
|
||||
):
|
||||
provider = get_payment_provider_by_name("nowpayments")
|
||||
notify_url = _get_notify_path(provider.name)
|
||||
result = provider.create_order(
|
||||
order_id=order_id,
|
||||
name=name,
|
||||
total_fee_yuan=total_fee_yuan,
|
||||
pay_type=channel,
|
||||
notify_url=notify_url,
|
||||
return_url=item.get("return_url"),
|
||||
client_ip=item.get("client_ip"),
|
||||
extra=overseas_extra,
|
||||
)
|
||||
logging.warning(
|
||||
"[payjsapi] payh5 creem missing key → fallback nowpayments order_id=%s ok=%s",
|
||||
order_id,
|
||||
result.get("ok"),
|
||||
)
|
||||
logging.info(
|
||||
"[payjsapi] payh5 created order_id=%s provider=%s notify_url=%s return_url=%s",
|
||||
order_id,
|
||||
@ -154,9 +188,15 @@ async def nomadvip_payh5(item: dict, request: Request):
|
||||
redirect_url = result.get("redirect_url") or result.get("pay_url") or ""
|
||||
if provider.name in ("creem", "nowpayments"):
|
||||
if result.get("ok") is False:
|
||||
err = result.get("error") or "overseas pay failed"
|
||||
if "not configured" in str(err).lower():
|
||||
err = (
|
||||
f"{err}. Configure CREEM_API_KEY and/or NOWPAYMENTS_API_KEY "
|
||||
"on US pay_svc (.com overseas)."
|
||||
)
|
||||
return {
|
||||
"status": "error",
|
||||
"error": result.get("error") or "overseas pay failed",
|
||||
"error": err,
|
||||
"provider": provider.name,
|
||||
}
|
||||
return {
|
||||
|
||||
@ -1 +1,4 @@
|
||||
"""游民社区独立后端 — 与 community/ebook/pay 数据完全隔离。"""
|
||||
"""游民社区独立后端 — 与 community/ebook/pay 数据完全隔离。
|
||||
|
||||
IM 协议见 ``contract.py``:服务端无 UI 假设;Web / 微信小程序任意换皮。
|
||||
"""
|
||||
|
||||
@ -8,6 +8,10 @@ _ROOT = Path(__file__).resolve().parents[4] # nomadro/
|
||||
_DEFAULT_DB = _ROOT / "data" / "social" / "social.db"
|
||||
|
||||
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT_DB))).resolve()
|
||||
SOCIAL_UPLOAD_DIR = Path(
|
||||
os.getenv("SOCIAL_UPLOAD_DIR", str(SOCIAL_DB_PATH.parent / "uploads"))
|
||||
).resolve()
|
||||
SOCIAL_UPLOAD_MAX_BYTES = int(os.getenv("SOCIAL_UPLOAD_MAX_BYTES", str(25 * 1024 * 1024)))
|
||||
SOCIAL_ENABLED = os.getenv("SOCIAL_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
# Centrifugo(实时层;缺省关,部署后用环境变量打开)
|
||||
@ -36,3 +40,34 @@ LIVE_STREAM_SECRET = os.getenv(
|
||||
)
|
||||
LIVE_MAX_PEERS = int(os.getenv("LIVE_MAX_PEERS", "6"))
|
||||
LIVE_PEER_TTL_SEC = int(os.getenv("LIVE_PEER_TTL_SEC", "45"))
|
||||
|
||||
# Geo discovery (MapLibre / Photon / H3 + PocketBase trips)
|
||||
PHOTON_BASE_URL = os.getenv(
|
||||
"PHOTON_BASE_URL",
|
||||
"https://photon.komoot.io",
|
||||
).rstrip("/")
|
||||
PHOTON_TIMEOUT_SEC = float(os.getenv("PHOTON_TIMEOUT_SEC", "6"))
|
||||
H3_CITY_RES = int(os.getenv("H3_CITY_RES", "4"))
|
||||
H3_NEAR_RES = int(os.getenv("H3_NEAR_RES", "7"))
|
||||
# PocketBase for social_trips (same env family as pay_svc)
|
||||
_pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL")
|
||||
_pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL")
|
||||
if _pb_internal:
|
||||
PB_URL = _pb_internal.rstrip("/")
|
||||
elif _pb_explicit:
|
||||
PB_URL = _pb_explicit.rstrip("/")
|
||||
else:
|
||||
PB_URL = "http://127.0.0.1:8090"
|
||||
PB_ADMIN_EMAIL = (
|
||||
os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or ""
|
||||
)
|
||||
PB_ADMIN_PASSWORD = (
|
||||
os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or ""
|
||||
)
|
||||
SOCIAL_TRIPS_COLLECTION = os.getenv("SOCIAL_TRIPS_COLLECTION", "social_trips")
|
||||
SOCIAL_GEO_USE_PB = os.getenv("SOCIAL_GEO_USE_PB", "true").lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
|
||||
67
apps/api/services/social_svc/contract.py
Normal file
67
apps/api/services/social_svc/contract.py
Normal file
@ -0,0 +1,67 @@
|
||||
"""Nomadro Social IM — server contract (UI-agnostic).
|
||||
|
||||
Frontends (Web / 微信小程序 / future apps) MUST treat this as the only SoT.
|
||||
No UI assumptions: display names, layouts, emoji pickers live entirely in clients.
|
||||
|
||||
Transport
|
||||
---------
|
||||
- REST: ``/api/social/v1/*``
|
||||
- Realtime: Centrifugo channel ``social:{channelId}``
|
||||
- Auth peer: header ``X-Social-Guest-Id`` (or ``?guest=``)
|
||||
|
||||
HTTP (chat core)
|
||||
----------------
|
||||
GET /health
|
||||
GET /realtime/token?channel_id=
|
||||
GET /channels/{id}/desc
|
||||
GET /channels/{id}/messages?since=&before=&limit=&q=
|
||||
POST /channels/{id}/messages body: {author, text?, clientId?, replyTo?, attachments?, mentions?}
|
||||
PATCH /channels/{id}/messages/{msgId} body: {text} # edit
|
||||
POST /channels/{id}/messages/{msgId}/recall
|
||||
POST /channels/{id}/messages/{msgId}/react body: {emoji}
|
||||
POST /channels/{id}/messages/{msgId}/pin body: {pinned?}
|
||||
POST /channels/{id}/messages/{msgId}/report body: {reason?}
|
||||
POST /channels/{id}/presence body: {nick?} # soft online heartbeat
|
||||
POST /channels/{id}/notes body: {what: recv|read|kp, seq?}
|
||||
POST /channels/{id}/upload multipart file → attachment descriptor
|
||||
GET /files/{fileId} stream uploaded bytes
|
||||
|
||||
Centrifugo publications (JSON)
|
||||
------------------------------
|
||||
{"type":"chat.message","message":{…full message…}}
|
||||
{"type":"chat.note","what":"recv|read|kp","seq":N,"guestId":"...","at":"..."}
|
||||
|
||||
Message fields
|
||||
--------------
|
||||
- ``seq``: monotonic int per channel (Tinode-inspired sync cursor)
|
||||
- ``clientId``: client idempotency key (optional but recommended)
|
||||
- ``replyTo``: {id, author, text, seq?}
|
||||
- ``attachments``: [{id, kind, url, name, mime, size}]
|
||||
- ``reactions``: {emoji: [guestId, …]}
|
||||
- ``mentions``: [name, …]
|
||||
- ``editedAt`` / ``recalled`` / ``pinned``
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
IM_PROTOCOL = "nomadro.im.v1"
|
||||
IM_FEATURES = (
|
||||
"seq",
|
||||
"clientId",
|
||||
"since",
|
||||
"before",
|
||||
"note.recv",
|
||||
"note.read",
|
||||
"note.kp",
|
||||
"centrifugo",
|
||||
"replyTo",
|
||||
"attachments",
|
||||
"upload",
|
||||
"recall",
|
||||
"react",
|
||||
"edit",
|
||||
"pin",
|
||||
"search",
|
||||
"mentions",
|
||||
"report",
|
||||
"presence",
|
||||
)
|
||||
229
apps/api/services/social_svc/geo_cities.py
Normal file
229
apps/api/services/social_svc/geo_cities.py
Normal file
@ -0,0 +1,229 @@
|
||||
"""Seed cities with approximate lat/lng for map aggregation (no personal GPS)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# Offline seed mirrored by src/modules/social/lib/cities.ts
|
||||
SEED_CITIES: list[dict[str, Any]] = [
|
||||
{
|
||||
"id": "dali",
|
||||
"name": "大理",
|
||||
"country": "中国",
|
||||
"emoji": "🏔️",
|
||||
"vibe": "苍山洱海 · 慢生活",
|
||||
"members": 520,
|
||||
"meetupCount": 12,
|
||||
"costHint": "¥3,000/月起",
|
||||
"wifiMbps": 50,
|
||||
"tags": ["热门", "便宜", "山城"],
|
||||
"hot": True,
|
||||
"lat": 25.6065,
|
||||
"lng": 100.2679,
|
||||
},
|
||||
{
|
||||
"id": "chengdu",
|
||||
"name": "成都",
|
||||
"country": "中国",
|
||||
"emoji": "🌶️",
|
||||
"vibe": "天府之国 · 美食慢节奏",
|
||||
"members": 680,
|
||||
"meetupCount": 18,
|
||||
"costHint": "¥4,500/月起",
|
||||
"wifiMbps": 80,
|
||||
"tags": ["热门", "美食", "宜居"],
|
||||
"hot": True,
|
||||
"lat": 30.5728,
|
||||
"lng": 104.0668,
|
||||
},
|
||||
{
|
||||
"id": "hangzhou",
|
||||
"name": "杭州",
|
||||
"country": "中国",
|
||||
"emoji": "🏞️",
|
||||
"vibe": "西湖 · 互联网重镇",
|
||||
"members": 560,
|
||||
"meetupCount": 14,
|
||||
"costHint": "¥6,000/月起",
|
||||
"wifiMbps": 100,
|
||||
"tags": ["热门", "高速网络"],
|
||||
"hot": True,
|
||||
"lat": 30.2741,
|
||||
"lng": 120.1551,
|
||||
},
|
||||
{
|
||||
"id": "kunming",
|
||||
"name": "昆明",
|
||||
"country": "中国",
|
||||
"emoji": "🌸",
|
||||
"vibe": "四季如春 · 通往东南亚",
|
||||
"members": 380,
|
||||
"meetupCount": 8,
|
||||
"costHint": "¥3,500/月起",
|
||||
"wifiMbps": 55,
|
||||
"tags": ["温暖", "便宜"],
|
||||
"hot": False,
|
||||
"lat": 25.0389,
|
||||
"lng": 102.7183,
|
||||
},
|
||||
{
|
||||
"id": "shenzhen",
|
||||
"name": "深圳",
|
||||
"country": "中国",
|
||||
"emoji": "🚀",
|
||||
"vibe": "科技创新 · 创业友好",
|
||||
"members": 850,
|
||||
"meetupCount": 22,
|
||||
"costHint": "¥8,000/月起",
|
||||
"wifiMbps": 120,
|
||||
"tags": ["热门", "高速网络", "一线城市"],
|
||||
"hot": True,
|
||||
"lat": 22.5431,
|
||||
"lng": 114.0579,
|
||||
},
|
||||
{
|
||||
"id": "xiamen",
|
||||
"name": "厦门",
|
||||
"country": "中国",
|
||||
"emoji": "🏝️",
|
||||
"vibe": "海滨花园 · 鼓浪屿",
|
||||
"members": 320,
|
||||
"meetupCount": 7,
|
||||
"costHint": "¥5,500/月起",
|
||||
"wifiMbps": 70,
|
||||
"tags": ["海滨", "温暖"],
|
||||
"hot": False,
|
||||
"lat": 24.4798,
|
||||
"lng": 118.0894,
|
||||
},
|
||||
{
|
||||
"id": "shanghai",
|
||||
"name": "上海",
|
||||
"country": "中国",
|
||||
"emoji": "🌆",
|
||||
"vibe": "国际大都市 · 文化交汇",
|
||||
"members": 1200,
|
||||
"meetupCount": 28,
|
||||
"costHint": "¥10,000/月起",
|
||||
"wifiMbps": 110,
|
||||
"tags": ["一线城市", "热门"],
|
||||
"hot": True,
|
||||
"lat": 31.2304,
|
||||
"lng": 121.4737,
|
||||
},
|
||||
{
|
||||
"id": "lijiang",
|
||||
"name": "丽江",
|
||||
"country": "中国",
|
||||
"emoji": "🏯",
|
||||
"vibe": "玉龙雪山 · 古城慢旅",
|
||||
"members": 280,
|
||||
"meetupCount": 5,
|
||||
"costHint": "¥3,200/月起",
|
||||
"wifiMbps": 45,
|
||||
"tags": ["便宜", "山城"],
|
||||
"hot": False,
|
||||
"lat": 26.8721,
|
||||
"lng": 100.2299,
|
||||
},
|
||||
{
|
||||
"id": "chiangmai",
|
||||
"name": "清迈",
|
||||
"country": "泰国",
|
||||
"emoji": "🌿",
|
||||
"vibe": "Nimman · 游民大本营",
|
||||
"members": 940,
|
||||
"meetupCount": 36,
|
||||
"costHint": "฿18,000/月起",
|
||||
"wifiMbps": 90,
|
||||
"tags": ["热门", "友好社区", "高速网络"],
|
||||
"hot": True,
|
||||
"lat": 18.7883,
|
||||
"lng": 98.9853,
|
||||
},
|
||||
{
|
||||
"id": "bali",
|
||||
"name": "巴厘岛",
|
||||
"country": "印尼",
|
||||
"emoji": "🌴",
|
||||
"vibe": "Canggu · 冲浪与 cowork",
|
||||
"members": 720,
|
||||
"meetupCount": 24,
|
||||
"costHint": "Rp8jt/月起",
|
||||
"wifiMbps": 60,
|
||||
"tags": ["海滨", "温暖", "热门"],
|
||||
"hot": True,
|
||||
"lat": -8.6478,
|
||||
"lng": 115.1385,
|
||||
},
|
||||
{
|
||||
"id": "lisbon",
|
||||
"name": "里斯本",
|
||||
"country": "葡萄牙",
|
||||
"emoji": "🌊",
|
||||
"vibe": "阳光海岸 · 欧洲时区",
|
||||
"members": 610,
|
||||
"meetupCount": 16,
|
||||
"costHint": "€1,200/月起",
|
||||
"wifiMbps": 100,
|
||||
"tags": ["海滨", "友好社区"],
|
||||
"hot": False,
|
||||
"lat": 38.7223,
|
||||
"lng": -9.1393,
|
||||
},
|
||||
{
|
||||
"id": "penang",
|
||||
"name": "槟城",
|
||||
"country": "马来西亚",
|
||||
"emoji": "🍜",
|
||||
"vibe": "美食 · 海风开放工位",
|
||||
"members": 260,
|
||||
"meetupCount": 6,
|
||||
"costHint": "RM2,800/月起",
|
||||
"wifiMbps": 100,
|
||||
"tags": ["美食", "便宜"],
|
||||
"hot": False,
|
||||
"lat": 5.4141,
|
||||
"lng": 100.3288,
|
||||
},
|
||||
]
|
||||
|
||||
_BY_ID = {c["id"]: c for c in SEED_CITIES}
|
||||
_BY_NAME = {c["name"]: c for c in SEED_CITIES}
|
||||
|
||||
|
||||
def list_seed_cities() -> list[dict[str, Any]]:
|
||||
return [dict(c) for c in SEED_CITIES]
|
||||
|
||||
|
||||
def get_seed_city(city_id: str) -> dict[str, Any] | None:
|
||||
c = _BY_ID.get((city_id or "").strip())
|
||||
return dict(c) if c else None
|
||||
|
||||
|
||||
def resolve_city_id(city: str, city_id: str | None = None) -> str | None:
|
||||
if city_id and city_id in _BY_ID:
|
||||
return city_id
|
||||
name = (city or "").split("·")[0].strip()
|
||||
hit = _BY_NAME.get(name)
|
||||
return hit["id"] if hit else None
|
||||
|
||||
|
||||
def city_public(c: dict[str, Any], *, extras: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
out = {
|
||||
"id": c["id"],
|
||||
"name": c["name"],
|
||||
"country": c["country"],
|
||||
"emoji": c.get("emoji", ""),
|
||||
"vibe": c.get("vibe", ""),
|
||||
"lat": c["lat"],
|
||||
"lng": c["lng"],
|
||||
"memberCount": int(c.get("members") or 0),
|
||||
"meetupCount": int(c.get("meetupCount") or 0),
|
||||
"costHint": c.get("costHint", ""),
|
||||
"wifiMbps": c.get("wifiMbps"),
|
||||
"tags": list(c.get("tags") or []),
|
||||
"hot": bool(c.get("hot")),
|
||||
}
|
||||
if extras:
|
||||
out.update(extras)
|
||||
return out
|
||||
25
apps/api/services/social_svc/geo_h3.py
Normal file
25
apps/api/services/social_svc/geo_h3.py
Normal file
@ -0,0 +1,25 @@
|
||||
"""H3 cell helpers — soft-dep on `h3` package; rounded fallback otherwise."""
|
||||
from __future__ import annotations
|
||||
|
||||
from .config import H3_CITY_RES, H3_NEAR_RES
|
||||
|
||||
try:
|
||||
import h3 # type: ignore
|
||||
|
||||
def latlng_to_cell(lat: float, lng: float, res: int | None = None) -> str:
|
||||
r = H3_CITY_RES if res is None else res
|
||||
return str(h3.latlng_to_cell(float(lat), float(lng), int(r)))
|
||||
|
||||
def near_cell(lat: float, lng: float) -> str:
|
||||
return latlng_to_cell(lat, lng, H3_NEAR_RES)
|
||||
|
||||
except Exception: # pragma: no cover
|
||||
|
||||
def latlng_to_cell(lat: float, lng: float, res: int | None = None) -> str:
|
||||
r = H3_CITY_RES if res is None else res
|
||||
# Coarse grid fallback (~res 4–5 order of magnitude)
|
||||
step = 0.5 if r <= 4 else 0.2 if r <= 5 else 0.05
|
||||
return f"g{r}:{round(float(lat) / step) * step:.4f}:{round(float(lng) / step) * step:.4f}"
|
||||
|
||||
def near_cell(lat: float, lng: float) -> str:
|
||||
return latlng_to_cell(lat, lng, H3_NEAR_RES)
|
||||
330
apps/api/services/social_svc/geo_pb.py
Normal file
330
apps/api/services/social_svc/geo_pb.py
Normal file
@ -0,0 +1,330 @@
|
||||
"""PocketBase `social_trips` — primary SoT when admin credentials work."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .config import (
|
||||
PB_ADMIN_EMAIL,
|
||||
PB_ADMIN_PASSWORD,
|
||||
PB_URL,
|
||||
SOCIAL_GEO_USE_PB,
|
||||
SOCIAL_TRIPS_COLLECTION,
|
||||
)
|
||||
|
||||
log = logging.getLogger("social_svc.geo_pb")
|
||||
|
||||
_token: str | None = None
|
||||
_token_at = 0.0
|
||||
_ensured = False
|
||||
|
||||
|
||||
def pb_enabled() -> bool:
|
||||
return bool(
|
||||
SOCIAL_GEO_USE_PB
|
||||
and PB_URL
|
||||
and PB_ADMIN_EMAIL
|
||||
and PB_ADMIN_PASSWORD
|
||||
)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
|
||||
|
||||
|
||||
def _auth_token() -> str | None:
|
||||
global _token, _token_at
|
||||
if not pb_enabled():
|
||||
return None
|
||||
if _token and (time.time() - _token_at) < 300:
|
||||
return _token
|
||||
base = PB_URL.rstrip("/")
|
||||
try:
|
||||
with httpx.Client(timeout=8.0) as client:
|
||||
# PB 0.22+ superusers; fall back to legacy admins
|
||||
for path in (
|
||||
"/api/collections/_superusers/auth-with-password",
|
||||
"/api/admins/auth-with-password",
|
||||
):
|
||||
r = client.post(
|
||||
f"{base}{path}",
|
||||
json={"identity": PB_ADMIN_EMAIL, "password": PB_ADMIN_PASSWORD},
|
||||
)
|
||||
if r.status_code < 400:
|
||||
data = r.json()
|
||||
tok = data.get("token")
|
||||
if tok:
|
||||
_token = str(tok)
|
||||
_token_at = time.time()
|
||||
return _token
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("pb auth failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _headers() -> dict[str, str] | None:
|
||||
tok = _auth_token()
|
||||
if not tok:
|
||||
return None
|
||||
return {"Authorization": tok}
|
||||
|
||||
|
||||
def ensure_collection() -> bool:
|
||||
"""Best-effort create `social_trips` collection if missing."""
|
||||
global _ensured
|
||||
if _ensured:
|
||||
return True
|
||||
headers = _headers()
|
||||
if not headers:
|
||||
return False
|
||||
base = PB_URL.rstrip("/")
|
||||
name = SOCIAL_TRIPS_COLLECTION
|
||||
try:
|
||||
with httpx.Client(timeout=12.0) as client:
|
||||
chk = client.get(f"{base}/api/collections/{name}", headers=headers)
|
||||
if chk.status_code == 200:
|
||||
_ensured = True
|
||||
return True
|
||||
body = {
|
||||
"name": name,
|
||||
"type": "base",
|
||||
"listRule": "",
|
||||
"viewRule": "",
|
||||
"createRule": "",
|
||||
"updateRule": "",
|
||||
"deleteRule": "",
|
||||
"fields": [
|
||||
{"name": "guest_id", "type": "text", "required": True},
|
||||
{"name": "city_id", "type": "text", "required": False},
|
||||
{"name": "city", "type": "text", "required": True},
|
||||
{"name": "country", "type": "text", "required": False},
|
||||
{"name": "lat", "type": "number", "required": False},
|
||||
{"name": "lng", "type": "number", "required": False},
|
||||
{"name": "h3_cell", "type": "text", "required": False},
|
||||
{"name": "arrival_date", "type": "text", "required": False},
|
||||
{"name": "departure_date", "type": "text", "required": False},
|
||||
{
|
||||
"name": "visibility",
|
||||
"type": "select",
|
||||
"required": True,
|
||||
"maxSelect": 1,
|
||||
"values": ["public", "friends", "private"],
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "select",
|
||||
"required": True,
|
||||
"maxSelect": 1,
|
||||
"values": ["here", "planned", "past"],
|
||||
},
|
||||
{"name": "updated_at", "type": "text", "required": True},
|
||||
],
|
||||
"indexes": [
|
||||
"CREATE INDEX idx_social_trips_guest ON social_trips (guest_id)",
|
||||
"CREATE INDEX idx_social_trips_city ON social_trips (city_id)",
|
||||
],
|
||||
}
|
||||
# PocketBase 0.22+ uses `fields`; older used `schema`
|
||||
created = client.post(
|
||||
f"{base}/api/collections",
|
||||
headers=headers,
|
||||
json=body,
|
||||
)
|
||||
if created.status_code >= 400:
|
||||
body_legacy = {
|
||||
"name": name,
|
||||
"type": "base",
|
||||
"listRule": None,
|
||||
"viewRule": None,
|
||||
"createRule": None,
|
||||
"updateRule": None,
|
||||
"deleteRule": None,
|
||||
"schema": [
|
||||
{"name": "guest_id", "type": "text", "required": True},
|
||||
{"name": "city_id", "type": "text", "required": False},
|
||||
{"name": "city", "type": "text", "required": True},
|
||||
{"name": "country", "type": "text", "required": False},
|
||||
{"name": "lat", "type": "number", "required": False},
|
||||
{"name": "lng", "type": "number", "required": False},
|
||||
{"name": "h3_cell", "type": "text", "required": False},
|
||||
{"name": "arrival_date", "type": "text", "required": False},
|
||||
{"name": "departure_date", "type": "text", "required": False},
|
||||
{
|
||||
"name": "visibility",
|
||||
"type": "select",
|
||||
"required": True,
|
||||
"options": {"maxSelect": 1, "values": ["public", "friends", "private"]},
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "select",
|
||||
"required": True,
|
||||
"options": {"maxSelect": 1, "values": ["here", "planned", "past"]},
|
||||
},
|
||||
{"name": "updated_at", "type": "text", "required": True},
|
||||
],
|
||||
}
|
||||
created = client.post(
|
||||
f"{base}/api/collections",
|
||||
headers=headers,
|
||||
json=body_legacy,
|
||||
)
|
||||
if created.status_code < 400:
|
||||
_ensured = True
|
||||
log.info("created PocketBase collection %s", name)
|
||||
return True
|
||||
log.warning("pb create collection failed: %s %s", created.status_code, created.text[:200])
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("pb ensure_collection: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _rec_to_trip(rec: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": rec.get("id") or "",
|
||||
"guest_id": rec.get("guest_id") or "",
|
||||
"city_id": rec.get("city_id") or "",
|
||||
"city": rec.get("city") or "",
|
||||
"country": rec.get("country") or "",
|
||||
"lat": rec.get("lat"),
|
||||
"lng": rec.get("lng"),
|
||||
"h3_cell": rec.get("h3_cell") or "",
|
||||
"arrival_date": rec.get("arrival_date") or "",
|
||||
"departure_date": rec.get("departure_date") or "",
|
||||
"visibility": rec.get("visibility") or "public",
|
||||
"status": rec.get("status") or "planned",
|
||||
"updated_at": rec.get("updated_at") or "",
|
||||
}
|
||||
|
||||
|
||||
def list_trips(
|
||||
*,
|
||||
guest_id: str | None = None,
|
||||
city_id: str | None = None,
|
||||
visibility: str | None = "public",
|
||||
status: str | None = None,
|
||||
limit: int = 200,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""Return trips from PB, or None if PB unavailable (caller falls back to SQLite)."""
|
||||
headers = _headers()
|
||||
if not headers:
|
||||
return None
|
||||
ensure_collection()
|
||||
filters: list[str] = []
|
||||
if guest_id:
|
||||
filters.append(f'guest_id="{guest_id}"')
|
||||
if city_id:
|
||||
filters.append(f'city_id="{city_id}"')
|
||||
if visibility:
|
||||
filters.append(f'visibility="{visibility}"')
|
||||
if status:
|
||||
filters.append(f'status="{status}"')
|
||||
params: dict[str, Any] = {
|
||||
"page": 1,
|
||||
"perPage": max(1, min(limit, 500)),
|
||||
"sort": "-updated_at",
|
||||
}
|
||||
if filters:
|
||||
params["filter"] = " && ".join(filters)
|
||||
base = PB_URL.rstrip("/")
|
||||
col = SOCIAL_TRIPS_COLLECTION
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
r = client.get(
|
||||
f"{base}/api/collections/{col}/records",
|
||||
headers=headers,
|
||||
params=params,
|
||||
)
|
||||
if r.status_code >= 400:
|
||||
return None
|
||||
items = r.json().get("items") or []
|
||||
return [_rec_to_trip(x) for x in items if isinstance(x, dict)]
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("pb list_trips: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def upsert_trip(trip: dict[str, Any]) -> dict[str, Any] | None:
|
||||
headers = _headers()
|
||||
if not headers:
|
||||
return None
|
||||
ensure_collection()
|
||||
base = PB_URL.rstrip("/")
|
||||
col = SOCIAL_TRIPS_COLLECTION
|
||||
payload = {
|
||||
"guest_id": trip["guest_id"],
|
||||
"city_id": trip.get("city_id") or "",
|
||||
"city": trip["city"],
|
||||
"country": trip.get("country") or "",
|
||||
"lat": trip.get("lat"),
|
||||
"lng": trip.get("lng"),
|
||||
"h3_cell": trip.get("h3_cell") or "",
|
||||
"arrival_date": trip.get("arrival_date") or "",
|
||||
"departure_date": trip.get("departure_date") or "",
|
||||
"visibility": trip.get("visibility") or "public",
|
||||
"status": trip.get("status") or "planned",
|
||||
"updated_at": trip.get("updated_at") or _now(),
|
||||
}
|
||||
tid = trip.get("id") or ""
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
if tid:
|
||||
r = client.patch(
|
||||
f"{base}/api/collections/{col}/records/{tid}",
|
||||
headers=headers,
|
||||
json=payload,
|
||||
)
|
||||
if r.status_code >= 400:
|
||||
# maybe id is sqlite-local; create new
|
||||
r = client.post(
|
||||
f"{base}/api/collections/{col}/records",
|
||||
headers=headers,
|
||||
json=payload,
|
||||
)
|
||||
else:
|
||||
r = client.post(
|
||||
f"{base}/api/collections/{col}/records",
|
||||
headers=headers,
|
||||
json=payload,
|
||||
)
|
||||
if r.status_code >= 400:
|
||||
log.warning("pb upsert_trip failed: %s", r.text[:200])
|
||||
return None
|
||||
return _rec_to_trip(r.json())
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("pb upsert_trip: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def delete_trip(trip_id: str, guest_id: str) -> bool | None:
|
||||
"""True deleted, False not found/forbidden, None PB down."""
|
||||
headers = _headers()
|
||||
if not headers:
|
||||
return None
|
||||
ensure_collection()
|
||||
base = PB_URL.rstrip("/")
|
||||
col = SOCIAL_TRIPS_COLLECTION
|
||||
try:
|
||||
with httpx.Client(timeout=8.0) as client:
|
||||
get = client.get(
|
||||
f"{base}/api/collections/{col}/records/{trip_id}",
|
||||
headers=headers,
|
||||
)
|
||||
if get.status_code == 404:
|
||||
return False
|
||||
if get.status_code >= 400:
|
||||
return None
|
||||
rec = get.json()
|
||||
if (rec.get("guest_id") or "") != guest_id:
|
||||
return False
|
||||
d = client.delete(
|
||||
f"{base}/api/collections/{col}/records/{trip_id}",
|
||||
headers=headers,
|
||||
)
|
||||
return d.status_code < 400
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("pb delete_trip: %s", exc)
|
||||
return None
|
||||
382
apps/api/services/social_svc/geo_store.py
Normal file
382
apps/api/services/social_svc/geo_store.py
Normal file
@ -0,0 +1,382 @@
|
||||
"""Trips store: SQLite always; PocketBase preferred SoT when reachable."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from . import geo_pb
|
||||
from .geo_cities import (
|
||||
city_public,
|
||||
get_seed_city,
|
||||
list_seed_cities,
|
||||
resolve_city_id,
|
||||
)
|
||||
from .geo_h3 import latlng_to_cell
|
||||
from .store import db
|
||||
|
||||
|
||||
def _uid() -> str:
|
||||
return f"trip_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
|
||||
|
||||
|
||||
def ensure_trips_schema() -> None:
|
||||
with db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS trips (
|
||||
id TEXT PRIMARY KEY,
|
||||
guest_id TEXT NOT NULL,
|
||||
city_id TEXT,
|
||||
city TEXT NOT NULL,
|
||||
country TEXT,
|
||||
lat REAL,
|
||||
lng REAL,
|
||||
h3_cell TEXT,
|
||||
arrival_date TEXT,
|
||||
departure_date TEXT,
|
||||
visibility TEXT NOT NULL DEFAULT 'public',
|
||||
status TEXT NOT NULL DEFAULT 'planned',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _row_trip(r: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"id": r["id"],
|
||||
"guest_id": r["guest_id"],
|
||||
"city_id": r["city_id"] or "",
|
||||
"city": r["city"],
|
||||
"country": r["country"] or "",
|
||||
"lat": r["lat"],
|
||||
"lng": r["lng"],
|
||||
"h3_cell": r["h3_cell"] or "",
|
||||
"arrival_date": r["arrival_date"] or "",
|
||||
"departure_date": r["departure_date"] or "",
|
||||
"visibility": r["visibility"] or "public",
|
||||
"status": r["status"] or "planned",
|
||||
"updated_at": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def list_trips_sqlite(
|
||||
*,
|
||||
guest_id: str | None = None,
|
||||
city_id: str | None = None,
|
||||
visibility: str | None = None,
|
||||
status: str | None = None,
|
||||
limit: int = 200,
|
||||
) -> list[dict[str, Any]]:
|
||||
ensure_trips_schema()
|
||||
clauses: list[str] = []
|
||||
args: list[Any] = []
|
||||
if guest_id:
|
||||
clauses.append("guest_id = ?")
|
||||
args.append(guest_id)
|
||||
if city_id:
|
||||
clauses.append("city_id = ?")
|
||||
args.append(city_id)
|
||||
if visibility:
|
||||
clauses.append("visibility = ?")
|
||||
args.append(visibility)
|
||||
if status:
|
||||
clauses.append("status = ?")
|
||||
args.append(status)
|
||||
where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
|
||||
sql = f"SELECT * FROM trips{where} ORDER BY updated_at DESC LIMIT ?"
|
||||
args.append(max(1, min(limit, 500)))
|
||||
with db() as conn:
|
||||
rows = conn.execute(sql, args).fetchall()
|
||||
return [_row_trip(r) for r in rows]
|
||||
|
||||
|
||||
def list_trips(**kwargs: Any) -> list[dict[str, Any]]:
|
||||
pb = geo_pb.list_trips(**kwargs)
|
||||
if pb is not None:
|
||||
return pb
|
||||
return list_trips_sqlite(**kwargs)
|
||||
|
||||
|
||||
def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]:
|
||||
ensure_trips_schema()
|
||||
with db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO trips (
|
||||
id, guest_id, city_id, city, country, lat, lng, h3_cell,
|
||||
arrival_date, departure_date, visibility, status, updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
city_id=excluded.city_id,
|
||||
city=excluded.city,
|
||||
country=excluded.country,
|
||||
lat=excluded.lat,
|
||||
lng=excluded.lng,
|
||||
h3_cell=excluded.h3_cell,
|
||||
arrival_date=excluded.arrival_date,
|
||||
departure_date=excluded.departure_date,
|
||||
visibility=excluded.visibility,
|
||||
status=excluded.status,
|
||||
updated_at=excluded.updated_at
|
||||
""",
|
||||
(
|
||||
trip["id"],
|
||||
trip["guest_id"],
|
||||
trip.get("city_id") or "",
|
||||
trip["city"],
|
||||
trip.get("country") or "",
|
||||
trip.get("lat"),
|
||||
trip.get("lng"),
|
||||
trip.get("h3_cell") or "",
|
||||
trip.get("arrival_date") or "",
|
||||
trip.get("departure_date") or "",
|
||||
trip.get("visibility") or "public",
|
||||
trip.get("status") or "planned",
|
||||
trip.get("updated_at") or _now(),
|
||||
),
|
||||
)
|
||||
return trip
|
||||
|
||||
|
||||
def create_trip(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
city = (payload.get("city") or "").strip()
|
||||
if not city:
|
||||
raise ValueError("city required")
|
||||
city_id = (payload.get("city_id") or "").strip() or resolve_city_id(city) or ""
|
||||
seed = get_seed_city(city_id) if city_id else None
|
||||
lat = payload.get("lat")
|
||||
lng = payload.get("lng")
|
||||
if lat is None and seed:
|
||||
lat = seed["lat"]
|
||||
if lng is None and seed:
|
||||
lng = seed["lng"]
|
||||
country = (payload.get("country") or "").strip() or (seed or {}).get("country") or ""
|
||||
h3_cell = ""
|
||||
if lat is not None and lng is not None:
|
||||
h3_cell = latlng_to_cell(float(lat), float(lng))
|
||||
trip = {
|
||||
"id": _uid(),
|
||||
"guest_id": guest_id,
|
||||
"city_id": city_id,
|
||||
"city": city,
|
||||
"country": country,
|
||||
"lat": float(lat) if lat is not None else None,
|
||||
"lng": float(lng) if lng is not None else None,
|
||||
"h3_cell": h3_cell,
|
||||
"arrival_date": (payload.get("arrival_date") or "").strip()[:10],
|
||||
"departure_date": (payload.get("departure_date") or "").strip()[:10],
|
||||
"visibility": (payload.get("visibility") or "public").strip() or "public",
|
||||
"status": (payload.get("status") or "planned").strip() or "planned",
|
||||
"updated_at": _now(),
|
||||
}
|
||||
if trip["visibility"] not in {"public", "friends", "private"}:
|
||||
trip["visibility"] = "public"
|
||||
if trip["status"] not in {"here", "planned", "past"}:
|
||||
trip["status"] = "planned"
|
||||
pb = geo_pb.upsert_trip(trip)
|
||||
if pb:
|
||||
# keep local mirror with PB id
|
||||
trip = pb
|
||||
save_trip_sqlite(trip)
|
||||
return trip
|
||||
|
||||
|
||||
def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
existing = None
|
||||
for t in list_trips(guest_id=guest_id, visibility=None, limit=500):
|
||||
if t["id"] == trip_id:
|
||||
existing = t
|
||||
break
|
||||
if not existing:
|
||||
# try sqlite only
|
||||
rows = list_trips_sqlite(guest_id=guest_id, visibility=None, limit=500)
|
||||
existing = next((t for t in rows if t["id"] == trip_id), None)
|
||||
if not existing:
|
||||
return None
|
||||
city = (payload.get("city") or existing["city"]).strip()
|
||||
city_id = (payload.get("city_id") if "city_id" in payload else existing.get("city_id")) or ""
|
||||
city_id = str(city_id).strip() or resolve_city_id(city) or ""
|
||||
seed = get_seed_city(city_id) if city_id else None
|
||||
lat = payload.get("lat", existing.get("lat"))
|
||||
lng = payload.get("lng", existing.get("lng"))
|
||||
if lat is None and seed:
|
||||
lat = seed["lat"]
|
||||
if lng is None and seed:
|
||||
lng = seed["lng"]
|
||||
trip = {
|
||||
**existing,
|
||||
"city": city,
|
||||
"city_id": city_id,
|
||||
"country": (payload.get("country") if "country" in payload else existing.get("country"))
|
||||
or (seed or {}).get("country")
|
||||
or "",
|
||||
"lat": float(lat) if lat is not None else None,
|
||||
"lng": float(lng) if lng is not None else None,
|
||||
"arrival_date": (
|
||||
payload.get("arrival_date")
|
||||
if "arrival_date" in payload
|
||||
else existing.get("arrival_date")
|
||||
)
|
||||
or "",
|
||||
"departure_date": (
|
||||
payload.get("departure_date")
|
||||
if "departure_date" in payload
|
||||
else existing.get("departure_date")
|
||||
)
|
||||
or "",
|
||||
"visibility": (
|
||||
payload.get("visibility")
|
||||
if "visibility" in payload
|
||||
else existing.get("visibility")
|
||||
)
|
||||
or "public",
|
||||
"status": (payload.get("status") if "status" in payload else existing.get("status"))
|
||||
or "planned",
|
||||
"updated_at": _now(),
|
||||
}
|
||||
if trip["lat"] is not None and trip["lng"] is not None:
|
||||
trip["h3_cell"] = latlng_to_cell(float(trip["lat"]), float(trip["lng"]))
|
||||
pb = geo_pb.upsert_trip(trip)
|
||||
if pb:
|
||||
trip = pb
|
||||
save_trip_sqlite(trip)
|
||||
return trip
|
||||
|
||||
|
||||
def delete_trip(guest_id: str, trip_id: str) -> bool:
|
||||
pb = geo_pb.delete_trip(trip_id, guest_id)
|
||||
ensure_trips_schema()
|
||||
with db() as conn:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM trips WHERE id = ? AND guest_id = ?",
|
||||
(trip_id, guest_id),
|
||||
)
|
||||
local = cur.rowcount > 0
|
||||
if pb is True:
|
||||
return True
|
||||
if pb is False and not local:
|
||||
return False
|
||||
return local or pb is not False
|
||||
|
||||
|
||||
def map_cities() -> list[dict[str, Any]]:
|
||||
"""City aggregation for map — seed counts + live trip overlays (no personal coords)."""
|
||||
trips = list_trips(visibility="public", limit=500)
|
||||
live_by_city: dict[str, dict[str, int]] = {}
|
||||
for t in trips:
|
||||
cid = t.get("city_id") or resolve_city_id(t.get("city") or "") or ""
|
||||
if not cid:
|
||||
continue
|
||||
bucket = live_by_city.setdefault(cid, {"here": 0, "planned": 0})
|
||||
st = t.get("status") or "planned"
|
||||
if st == "here":
|
||||
bucket["here"] += 1
|
||||
elif st == "planned":
|
||||
bucket["planned"] += 1
|
||||
out = []
|
||||
for c in list_seed_cities():
|
||||
live = live_by_city.get(c["id"], {})
|
||||
extras = {
|
||||
"arrivingSoon": int(live.get("planned") or 0),
|
||||
"currentlyHere": int(live.get("here") or 0),
|
||||
"h3": latlng_to_cell(c["lat"], c["lng"]),
|
||||
# bump seed memberCount with live presence signal (display only)
|
||||
"memberCount": int(c.get("members") or 0) + int(live.get("here") or 0),
|
||||
}
|
||||
out.append(city_public(c, extras=extras))
|
||||
return out
|
||||
|
||||
|
||||
def city_detail(city_id: str) -> dict[str, Any] | None:
|
||||
seed = get_seed_city(city_id)
|
||||
if not seed:
|
||||
return None
|
||||
trips = list_trips(city_id=city_id, visibility="public", limit=200)
|
||||
here = [t for t in trips if t.get("status") == "here"]
|
||||
planned = [t for t in trips if t.get("status") == "planned"]
|
||||
base = city_public(
|
||||
seed,
|
||||
extras={
|
||||
"currentlyHere": len(here),
|
||||
"arrivingSoon": len(planned),
|
||||
"h3": latlng_to_cell(seed["lat"], seed["lng"]),
|
||||
"memberCount": int(seed.get("members") or 0) + len(here),
|
||||
},
|
||||
)
|
||||
base["recentArrivals"] = [
|
||||
{
|
||||
"guestId": t["guest_id"][:8] + "…",
|
||||
"city": t["city"],
|
||||
"status": t["status"],
|
||||
"arrival_date": t.get("arrival_date") or "",
|
||||
"departure_date": t.get("departure_date") or "",
|
||||
}
|
||||
for t in (here + planned)[:12]
|
||||
]
|
||||
return base
|
||||
|
||||
|
||||
def _parse_ymd(s: str) -> date | None:
|
||||
s = (s or "").strip()[:10]
|
||||
if len(s) < 10:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(s)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def travel_overlaps(guest_id: str) -> list[dict[str, Any]]:
|
||||
mine = list_trips(guest_id=guest_id, visibility=None, limit=100)
|
||||
mine = [t for t in mine if t.get("visibility") != "private"]
|
||||
others = [
|
||||
t
|
||||
for t in list_trips(visibility="public", limit=500)
|
||||
if t.get("guest_id") != guest_id
|
||||
]
|
||||
out: list[dict[str, Any]] = []
|
||||
for a in mine:
|
||||
a0, a1 = _parse_ymd(a.get("arrival_date") or ""), _parse_ymd(a.get("departure_date") or "")
|
||||
if not a0 or not a1 or a1 < a0:
|
||||
continue
|
||||
for b in others:
|
||||
if (a.get("city_id") and b.get("city_id") and a["city_id"] != b["city_id"]) or (
|
||||
not a.get("city_id")
|
||||
and (a.get("city") or "").split("·")[0].strip()
|
||||
!= (b.get("city") or "").split("·")[0].strip()
|
||||
):
|
||||
continue
|
||||
b0, b1 = _parse_ymd(b.get("arrival_date") or ""), _parse_ymd(
|
||||
b.get("departure_date") or ""
|
||||
)
|
||||
if not b0 or not b1 or b1 < b0:
|
||||
continue
|
||||
start = max(a0, b0)
|
||||
end = min(a1, b1)
|
||||
if end < start:
|
||||
continue
|
||||
days = (end - start).days + 1
|
||||
out.append(
|
||||
{
|
||||
"city": a.get("city") or b.get("city"),
|
||||
"cityId": a.get("city_id") or b.get("city_id") or "",
|
||||
"overlapDays": days,
|
||||
"from": start.isoformat(),
|
||||
"to": end.isoformat(),
|
||||
"otherGuest": (b.get("guest_id") or "")[:8] + "…",
|
||||
"myTripId": a["id"],
|
||||
"theirStatus": b.get("status") or "",
|
||||
}
|
||||
)
|
||||
out.sort(key=lambda x: (-int(x["overlapDays"]), x["from"]))
|
||||
return out[:50]
|
||||
45
apps/api/services/social_svc/im.py
Normal file
45
apps/api/services/social_svc/im.py
Normal file
@ -0,0 +1,45 @@
|
||||
"""Tinode-inspired IM primitives on Nomadro social stack.
|
||||
|
||||
Borrowed ideas (not code) from tinode/chat:
|
||||
- per-topic monotonic ``seq`` for sync / unread / pagination
|
||||
- clientId idempotent publish
|
||||
- note.recv / note.read watermarks
|
||||
- lightweight rate limit before fan-out
|
||||
|
||||
Transport stays Centrifugo; persistence stays SQLite (isolated social.db).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
# guest -> timestamps of recent posts (process-local; fine for single social worker)
|
||||
_RATE: dict[str, deque[float]] = defaultdict(deque)
|
||||
_RATE_LOCK = Lock()
|
||||
_RATE_WINDOW_SEC = 60.0
|
||||
_RATE_MAX = 30 # msgs / window / guest
|
||||
|
||||
|
||||
def check_rate(guest_id: str) -> None:
|
||||
"""Raise ValueError if guest exceeds send rate."""
|
||||
now = time.time()
|
||||
key = (guest_id or "").strip() or "_"
|
||||
with _RATE_LOCK:
|
||||
q = _RATE[key]
|
||||
while q and now - q[0] > _RATE_WINDOW_SEC:
|
||||
q.popleft()
|
||||
if len(q) >= _RATE_MAX:
|
||||
raise ValueError("发送过快,请稍后再试")
|
||||
q.append(now)
|
||||
|
||||
|
||||
def note_event(what: str, seq: int, guest_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"type": "chat.note",
|
||||
"what": what, # recv | read | kp
|
||||
"seq": int(seq),
|
||||
"guestId": guest_id,
|
||||
"at": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),
|
||||
}
|
||||
73
apps/api/services/social_svc/photon.py
Normal file
73
apps/api/services/social_svc/photon.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""Server-side Photon geocoder proxy (no browser CORS / key leakage)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .config import PHOTON_BASE_URL, PHOTON_TIMEOUT_SEC
|
||||
|
||||
log = logging.getLogger("social_svc.photon")
|
||||
|
||||
|
||||
def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None:
|
||||
props = f.get("properties") or {}
|
||||
geom = f.get("geometry") or {}
|
||||
coords = geom.get("coordinates") or []
|
||||
if len(coords) < 2:
|
||||
return None
|
||||
lng, lat = float(coords[0]), float(coords[1])
|
||||
name = (
|
||||
props.get("name")
|
||||
or props.get("city")
|
||||
or props.get("town")
|
||||
or props.get("village")
|
||||
or props.get("county")
|
||||
or ""
|
||||
).strip()
|
||||
if not name:
|
||||
return None
|
||||
country = (props.get("country") or "").strip()
|
||||
state = (props.get("state") or props.get("county") or "").strip()
|
||||
osm_id = props.get("osm_id")
|
||||
osm_type = props.get("osm_type") or ""
|
||||
cid = f"photon:{osm_type}{osm_id}" if osm_id is not None else f"photon:{lat:.4f},{lng:.4f}"
|
||||
return {
|
||||
"id": cid,
|
||||
"name": name,
|
||||
"country": country,
|
||||
"state": state,
|
||||
"lat": lat,
|
||||
"lng": lng,
|
||||
"osmKey": props.get("osm_key"),
|
||||
"osmValue": props.get("osm_value"),
|
||||
"source": "photon",
|
||||
}
|
||||
|
||||
|
||||
async def search_cities(q: str, *, limit: int = 8, lang: str = "zh") -> list[dict[str, Any]]:
|
||||
query = (q or "").strip()
|
||||
if len(query) < 2:
|
||||
return []
|
||||
base = (PHOTON_BASE_URL or "").rstrip("/")
|
||||
if not base:
|
||||
return []
|
||||
url = f"{base}/api/"
|
||||
params = {"q": query, "limit": max(1, min(limit, 20)), "lang": lang or "zh"}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=PHOTON_TIMEOUT_SEC) as client:
|
||||
res = await client.get(url, params=params)
|
||||
res.raise_for_status()
|
||||
data = res.json()
|
||||
except Exception as exc: # pragma: no cover
|
||||
log.warning("photon search failed: %s", exc)
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for f in data.get("features") or []:
|
||||
if not isinstance(f, dict):
|
||||
continue
|
||||
n = _norm_feature(f)
|
||||
if n:
|
||||
out.append(n)
|
||||
return out
|
||||
@ -77,5 +77,18 @@ async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool
|
||||
return await _publish(channel_id, {"type": "chat.message", "message": message})
|
||||
|
||||
|
||||
async def publish_chat_note(
|
||||
channel_id: str,
|
||||
*,
|
||||
what: str,
|
||||
seq: int,
|
||||
guest_id: str,
|
||||
) -> bool:
|
||||
"""Tinode-like {note}: recv / read / kp (typing)."""
|
||||
from social_svc.im import note_event
|
||||
|
||||
return await _publish(channel_id, note_event(what, seq, guest_id))
|
||||
|
||||
|
||||
async def publish_live_event(channel_id: str, event: str, payload: dict[str, Any]) -> bool:
|
||||
return await _publish(channel_id, {"type": f"live.{event}", **payload})
|
||||
|
||||
@ -1,3 +1,10 @@
|
||||
from .api import router
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .api import router as _api
|
||||
from .geo import router as _geo
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(_api)
|
||||
router.include_router(_geo)
|
||||
|
||||
__all__ = ["router"]
|
||||
|
||||
@ -1,15 +1,20 @@
|
||||
"""游民社区 API — 前缀 /api/social/v1,与 /api/v1 社群隔离。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, File, Form, Header, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from social_svc import live, store
|
||||
from social_svc.config import SOCIAL_ENABLED
|
||||
from social_svc.config import SOCIAL_ENABLED, SOCIAL_UPLOAD_MAX_BYTES
|
||||
from social_svc.realtime import (
|
||||
issue_connection_token,
|
||||
publish_chat_message,
|
||||
publish_chat_note,
|
||||
publish_live_event,
|
||||
)
|
||||
|
||||
@ -26,10 +31,55 @@ def _guest(
|
||||
return gid
|
||||
|
||||
|
||||
class ReplyToIn(BaseModel):
|
||||
id: str = Field(min_length=1, max_length=80)
|
||||
author: str = Field(default="游民", max_length=48)
|
||||
text: str = Field(default="", max_length=240)
|
||||
seq: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class AttachmentIn(BaseModel):
|
||||
id: str = Field(default="", max_length=80)
|
||||
kind: str = Field(default="file", max_length=16)
|
||||
url: str = Field(min_length=1, max_length=800)
|
||||
name: str = Field(default="file", max_length=160)
|
||||
mime: str = Field(default="application/octet-stream", max_length=120)
|
||||
size: int = Field(default=0, ge=0, le=50 * 1024 * 1024)
|
||||
|
||||
|
||||
class MessageIn(BaseModel):
|
||||
author: str = Field(default="游民", max_length=48)
|
||||
text: str = Field(min_length=1, max_length=2000)
|
||||
text: str = Field(default="", max_length=2000)
|
||||
clientId: str | None = Field(default=None, min_length=1, max_length=80)
|
||||
replyTo: ReplyToIn | None = None
|
||||
attachments: list[AttachmentIn] = Field(default_factory=list)
|
||||
mentions: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class EditMessageIn(BaseModel):
|
||||
text: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
class ReactIn(BaseModel):
|
||||
emoji: str = Field(min_length=1, max_length=16)
|
||||
|
||||
|
||||
class PinIn(BaseModel):
|
||||
pinned: bool = True
|
||||
|
||||
|
||||
class ReportIn(BaseModel):
|
||||
reason: str = Field(default="", max_length=240)
|
||||
|
||||
|
||||
class PresenceIn(BaseModel):
|
||||
nick: str = Field(default="游民", max_length=48)
|
||||
|
||||
|
||||
class NoteIn(BaseModel):
|
||||
"""Tinode {note}: recv / read / kp (typing keepalive)."""
|
||||
what: str = Field(min_length=2, max_length=8)
|
||||
seq: int = Field(default=0, ge=0)
|
||||
|
||||
|
||||
class ReviewIn(BaseModel):
|
||||
@ -47,6 +97,15 @@ class RosterIn(BaseModel):
|
||||
linktree: str = Field(default="", max_length=240)
|
||||
skills: str = Field(default="", max_length=200)
|
||||
bio: str = Field(default="", max_length=2000)
|
||||
avatar: str = Field(default="", max_length=500)
|
||||
# extra join fields accepted but not all persisted as columns
|
||||
gender: str = Field(default="", max_length=16)
|
||||
relationship: str = Field(default="", max_length=32)
|
||||
education: str = Field(default="", max_length=32)
|
||||
graduation: str = Field(default="", max_length=32)
|
||||
wechat: str = Field(default="", max_length=64)
|
||||
intents: str = Field(default="", max_length=240)
|
||||
updatedAt: str = Field(default="", max_length=40)
|
||||
|
||||
|
||||
class FeedbackIn(BaseModel):
|
||||
@ -68,8 +127,12 @@ async def social_health():
|
||||
return {"ok": False, "module": "social", "enabled": False}
|
||||
h = store.health()
|
||||
from social_svc.config import CENTRIFUGO_ENABLED
|
||||
from social_svc.contract import IM_FEATURES, IM_PROTOCOL
|
||||
|
||||
h["centrifugo"] = bool(CENTRIFUGO_ENABLED)
|
||||
h["imProtocol"] = IM_PROTOCOL
|
||||
h["imFeatures"] = list(IM_FEATURES)
|
||||
h["uiAgnostic"] = True
|
||||
return h
|
||||
|
||||
|
||||
@ -83,10 +146,42 @@ async def realtime_token(
|
||||
return issue_connection_token(peer, channel_id)
|
||||
|
||||
|
||||
@router.get("/channels/{channel_id}/desc")
|
||||
def get_channel_desc(
|
||||
channel_id: str,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
"""Tinode-like topic desc: seq + recv/read/unread for current peer."""
|
||||
peer = None
|
||||
try:
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
except HTTPException:
|
||||
peer = None
|
||||
return store.channel_desc(channel_id, peer)
|
||||
|
||||
|
||||
@router.get("/channels/{channel_id}/messages")
|
||||
def get_messages(channel_id: str, limit: int = 100):
|
||||
def get_messages(
|
||||
channel_id: str,
|
||||
limit: int = 100,
|
||||
since: int | None = Query(default=None, ge=0),
|
||||
before: int | None = Query(default=None, ge=0),
|
||||
q: str | None = Query(default=None, max_length=80),
|
||||
):
|
||||
store.init_db()
|
||||
return {"items": store.list_messages(channel_id, limit)}
|
||||
items = store.list_messages(
|
||||
channel_id, limit, since=since, before=before, q=q
|
||||
)
|
||||
desc = store.channel_desc(channel_id)
|
||||
return {"items": items, "seq": desc["seq"]}
|
||||
|
||||
|
||||
async def _publish_msg(channel_id: str, saved: dict[str, Any]) -> None:
|
||||
try:
|
||||
await publish_chat_message(channel_id, saved)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/messages")
|
||||
@ -97,18 +192,311 @@ async def post_message(
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
if not body.text.strip():
|
||||
raise HTTPException(status_code=400, detail="empty text")
|
||||
if not body.text.strip() and not body.attachments:
|
||||
raise HTTPException(status_code=400, detail="empty message")
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.add_message(channel_id, body.author, body.text, peer, body.clientId)
|
||||
return store.add_message(
|
||||
channel_id,
|
||||
body.author,
|
||||
body.text,
|
||||
peer,
|
||||
body.clientId,
|
||||
reply_to=body.replyTo.model_dump() if body.replyTo else None,
|
||||
attachments=[a.model_dump() for a in body.attachments],
|
||||
mentions=body.mentions,
|
||||
)
|
||||
|
||||
try:
|
||||
saved = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
# 实时推送失败不影响落库成功
|
||||
detail = str(exc)
|
||||
if "过快" in detail:
|
||||
code = 429
|
||||
elif "empty" in detail:
|
||||
code = 400
|
||||
else:
|
||||
code = 409
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
await _publish_msg(channel_id, saved)
|
||||
return saved
|
||||
|
||||
|
||||
@router.patch("/channels/{channel_id}/messages/{msg_id}")
|
||||
async def patch_message(
|
||||
channel_id: str,
|
||||
msg_id: str,
|
||||
body: EditMessageIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.edit_message(channel_id, msg_id, peer, body.text)
|
||||
|
||||
try:
|
||||
await publish_chat_message(channel_id, saved)
|
||||
saved = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
code = 403 if "not your" in detail else 404 if "not found" in detail else 400
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
await _publish_msg(channel_id, saved)
|
||||
return saved
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/messages/{msg_id}/recall")
|
||||
async def recall_message(
|
||||
channel_id: str,
|
||||
msg_id: str,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.recall_message(channel_id, msg_id, peer)
|
||||
|
||||
try:
|
||||
saved = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
code = 403 if "not your" in detail else 404 if "not found" in detail else 400
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
await _publish_msg(channel_id, saved)
|
||||
return saved
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/messages/{msg_id}/react")
|
||||
async def react_message(
|
||||
channel_id: str,
|
||||
msg_id: str,
|
||||
body: ReactIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.react_message(channel_id, msg_id, peer, body.emoji)
|
||||
|
||||
try:
|
||||
saved = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
code = 404 if "not found" in detail else 400
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
await _publish_msg(channel_id, saved)
|
||||
return saved
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/messages/{msg_id}/pin")
|
||||
async def pin_message(
|
||||
channel_id: str,
|
||||
msg_id: str,
|
||||
body: PinIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.pin_message(channel_id, msg_id, peer, body.pinned)
|
||||
|
||||
try:
|
||||
saved = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
code = 404 if "not found" in detail else 400
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
await _publish_msg(channel_id, saved)
|
||||
return saved
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/messages/{msg_id}/report")
|
||||
async def report_message(
|
||||
channel_id: str,
|
||||
msg_id: str,
|
||||
body: ReportIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.report_message(channel_id, msg_id, peer, body.reason)
|
||||
|
||||
try:
|
||||
return await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
code = 404 if "not found" in detail else 400
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/presence")
|
||||
async def post_presence(
|
||||
channel_id: str,
|
||||
body: PresenceIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
return store.touch_presence(channel_id, peer, body.nick)
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_media(
|
||||
file: UploadFile = File(...),
|
||||
purpose: str = Form(default="avatar"),
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
"""Guest-friendly image upload → SeaweedFS S3 (fallback local)."""
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
ctype = (file.content_type or "").lower()
|
||||
if not ctype.startswith("image/"):
|
||||
raise HTTPException(status_code=400, detail="仅支持图片")
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(status_code=400, detail="空文件")
|
||||
max_avatar = min(SOCIAL_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
|
||||
|
||||
def persist():
|
||||
from social_svc.s3_upload import upload_bytes
|
||||
|
||||
return upload_bytes(
|
||||
raw,
|
||||
filename=file.filename or "avatar.jpg",
|
||||
content_type=file.content_type or "image/jpeg",
|
||||
purpose=(purpose or "avatar")[:40],
|
||||
guest_id=peer,
|
||||
max_size=max_avatar,
|
||||
)
|
||||
|
||||
try:
|
||||
result = await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail=f"上传失败: {exc}") from exc
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"success": True,
|
||||
"url": result.url,
|
||||
"object_key": result.object_key,
|
||||
"size": result.size,
|
||||
"content_type": result.content_type,
|
||||
"storage": result.storage,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/files/avatar/{name}")
|
||||
def get_local_avatar(name: str):
|
||||
"""Serve locally-fallback avatar files when S3 is unavailable."""
|
||||
from social_svc.config import SOCIAL_UPLOAD_DIR
|
||||
|
||||
safe = Path(name).name
|
||||
if safe != name or ".." in name:
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
path = SOCIAL_UPLOAD_DIR / "avatars" / safe
|
||||
if not path.is_file():
|
||||
raise HTTPException(status_code=404, detail="not found")
|
||||
return FileResponse(path)
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/upload")
|
||||
async def upload_file(
|
||||
channel_id: str,
|
||||
file: UploadFile = File(...),
|
||||
kind: str = Form(default="file"),
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(status_code=400, detail="empty file")
|
||||
if len(raw) > SOCIAL_UPLOAD_MAX_BYTES:
|
||||
raise HTTPException(status_code=413, detail="file too large")
|
||||
mime = file.content_type or "application/octet-stream"
|
||||
guessed = kind
|
||||
if guessed == "file":
|
||||
if mime.startswith("image/"):
|
||||
guessed = "image"
|
||||
elif mime.startswith("video/"):
|
||||
guessed = "video"
|
||||
elif mime.startswith("audio/"):
|
||||
guessed = "audio"
|
||||
|
||||
def persist():
|
||||
store.init_db()
|
||||
return store.save_upload(
|
||||
channel_id,
|
||||
peer,
|
||||
kind=guessed,
|
||||
name=file.filename or "file",
|
||||
mime=mime,
|
||||
data=raw,
|
||||
)
|
||||
|
||||
try:
|
||||
return await run_in_threadpool(persist)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/files/{file_id}")
|
||||
def get_file(file_id: str):
|
||||
store.init_db()
|
||||
meta = store.get_file(file_id)
|
||||
if not meta:
|
||||
raise HTTPException(status_code=404, detail="file not found")
|
||||
path = Path(meta["path"])
|
||||
if not path.is_file():
|
||||
raise HTTPException(status_code=404, detail="file missing")
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=meta["mime"],
|
||||
filename=meta["name"],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/channels/{channel_id}/notes")
|
||||
async def post_note(
|
||||
channel_id: str,
|
||||
body: NoteIn,
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
"""Tinode {note}: recv/read persist; kp (typing) is fan-out only."""
|
||||
peer = _guest(x_social_guest_id, guest)
|
||||
what = body.what.strip().lower()
|
||||
if what == "kp":
|
||||
try:
|
||||
await publish_chat_note(channel_id, what="kp", seq=0, guest_id=peer)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "what": "kp"}
|
||||
if what not in {"recv", "read"}:
|
||||
raise HTTPException(status_code=400, detail="what must be recv|read|kp")
|
||||
try:
|
||||
saved = await run_in_threadpool(
|
||||
lambda: store.set_note(channel_id, peer, what, body.seq)
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
try:
|
||||
await publish_chat_note(
|
||||
channel_id, what=what, seq=saved["seq"], guest_id=peer
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return saved
|
||||
|
||||
230
apps/api/services/social_svc/routers/geo.py
Normal file
230
apps/api/services/social_svc/routers/geo.py
Normal file
@ -0,0 +1,230 @@
|
||||
"""Geo discovery API — map cities, Photon search, trips, overlaps."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from social_svc import geo_store, photon
|
||||
from social_svc.config import SOCIAL_ENABLED
|
||||
from social_svc.geo_cities import list_seed_cities, city_public
|
||||
|
||||
router = APIRouter(tags=["social-geo"])
|
||||
|
||||
|
||||
def _guest(
|
||||
x_social_guest_id: str | None,
|
||||
guest_q: str | None = None,
|
||||
) -> str:
|
||||
gid = (x_social_guest_id or guest_q or "").strip()
|
||||
if not gid or len(gid) > 80:
|
||||
raise HTTPException(status_code=400, detail="missing X-Social-Guest-Id")
|
||||
return gid
|
||||
|
||||
|
||||
class TripIn(BaseModel):
|
||||
city: str = Field(min_length=1, max_length=80)
|
||||
city_id: str = Field(default="", max_length=64)
|
||||
country: str = Field(default="", max_length=64)
|
||||
lat: float | None = None
|
||||
lng: float | None = None
|
||||
arrival_date: str = Field(default="", max_length=10)
|
||||
departure_date: str = Field(default="", max_length=10)
|
||||
visibility: str = Field(default="public", max_length=16)
|
||||
status: str = Field(default="planned", max_length=16)
|
||||
|
||||
|
||||
class TripPatch(BaseModel):
|
||||
city: str | None = Field(default=None, max_length=80)
|
||||
city_id: str | None = Field(default=None, max_length=64)
|
||||
country: str | None = Field(default=None, max_length=64)
|
||||
lat: float | None = None
|
||||
lng: float | None = None
|
||||
arrival_date: str | None = Field(default=None, max_length=10)
|
||||
departure_date: str | None = Field(default=None, max_length=10)
|
||||
visibility: str | None = Field(default=None, max_length=16)
|
||||
status: str | None = Field(default=None, max_length=16)
|
||||
|
||||
|
||||
@router.get("/map/cities")
|
||||
async def map_cities(
|
||||
west: float | None = None,
|
||||
south: float | None = None,
|
||||
east: float | None = None,
|
||||
north: float | None = None,
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
items = await run_in_threadpool(geo_store.map_cities)
|
||||
if None not in (west, south, east, north):
|
||||
items = [
|
||||
c
|
||||
for c in items
|
||||
if west <= float(c["lng"]) <= east and south <= float(c["lat"]) <= north # type: ignore[operator]
|
||||
]
|
||||
return {"items": items, "source": "seed+trips"}
|
||||
|
||||
|
||||
@router.get("/cities/search")
|
||||
async def cities_search(
|
||||
q: str = Query(default="", max_length=80),
|
||||
limit: int = Query(default=8, ge=1, le=20),
|
||||
lang: str = Query(default="zh", max_length=8),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
query = (q or "").strip().lower()
|
||||
seed_hits = []
|
||||
if query:
|
||||
for c in list_seed_cities():
|
||||
hay = f"{c['name']} {c['country']} {' '.join(c.get('tags') or [])}".lower()
|
||||
if query in hay:
|
||||
seed_hits.append(city_public(c, extras={"source": "seed"}))
|
||||
photon_hits = await photon.search_cities(q, limit=limit, lang=lang)
|
||||
# Prefer seed ids when names collide
|
||||
seed_names = {c["name"] for c in seed_hits}
|
||||
merged = list(seed_hits)
|
||||
for p in photon_hits:
|
||||
if p["name"] in seed_names:
|
||||
continue
|
||||
merged.append(p)
|
||||
return {"items": merged[:limit], "q": q}
|
||||
|
||||
|
||||
@router.get("/cities/{city_id}")
|
||||
async def city_detail(city_id: str):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
item = await run_in_threadpool(geo_store.city_detail, city_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="city not found")
|
||||
return {"item": item}
|
||||
|
||||
|
||||
@router.get("/people")
|
||||
async def people_geo(
|
||||
city: str = Query(default="", max_length=80),
|
||||
cityId: str = Query(default="", max_length=64),
|
||||
status: str = Query(default="", max_length=16),
|
||||
profession: str = Query(default="", max_length=80),
|
||||
interest: str = Query(default="", max_length=80),
|
||||
language: str = Query(default="", max_length=40),
|
||||
currentlyHere: bool = Query(default=False),
|
||||
arrivingSoon: bool = Query(default=False),
|
||||
limit: int = Query(default=40, ge=1, le=100),
|
||||
):
|
||||
"""Public trip-backed presence filter (no lat/lng). Seed roster still lives client-side."""
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
|
||||
def _run() -> list[dict[str, Any]]:
|
||||
vis = "public"
|
||||
st = None
|
||||
if currentlyHere:
|
||||
st = "here"
|
||||
elif arrivingSoon:
|
||||
st = "planned"
|
||||
elif status in {"here", "planned", "past"}:
|
||||
st = status
|
||||
trips = geo_store.list_trips(
|
||||
city_id=cityId or None,
|
||||
visibility=vis,
|
||||
status=st,
|
||||
limit=limit * 3,
|
||||
)
|
||||
out: list[dict[str, Any]] = []
|
||||
for t in trips:
|
||||
if city and city.lower() not in (t.get("city") or "").lower():
|
||||
continue
|
||||
# profession/interest/language reserved for roster join later
|
||||
_ = (profession, interest, language)
|
||||
out.append(
|
||||
{
|
||||
"guestId": (t.get("guest_id") or "")[:10],
|
||||
"city": t.get("city"),
|
||||
"cityId": t.get("city_id") or "",
|
||||
"status": t.get("status"),
|
||||
"arrival_date": t.get("arrival_date") or "",
|
||||
"departure_date": t.get("departure_date") or "",
|
||||
"h3Res": t.get("h3_cell") or "",
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
items = await run_in_threadpool(_run)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.get("/travel-overlaps")
|
||||
async def travel_overlaps(
|
||||
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
||||
guest_id: str | None = Query(default=None),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
gid = _guest(x_social_guest_id, guest_id)
|
||||
items = await run_in_threadpool(geo_store.travel_overlaps, gid)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.get("/trips")
|
||||
async def list_my_trips(
|
||||
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
||||
guest_id: str | None = Query(default=None),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
gid = _guest(x_social_guest_id, guest_id)
|
||||
items = await run_in_threadpool(
|
||||
lambda: geo_store.list_trips(guest_id=gid, visibility=None, limit=100)
|
||||
)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.post("/trips")
|
||||
async def create_trip(
|
||||
body: TripIn,
|
||||
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
gid = _guest(x_social_guest_id)
|
||||
try:
|
||||
item = await run_in_threadpool(geo_store.create_trip, gid, body.model_dump())
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return {"item": item}
|
||||
|
||||
|
||||
@router.patch("/trips/{trip_id}")
|
||||
async def patch_trip(
|
||||
trip_id: str,
|
||||
body: TripPatch,
|
||||
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
gid = _guest(x_social_guest_id)
|
||||
payload = {k: v for k, v in body.model_dump().items() if v is not None}
|
||||
item = await run_in_threadpool(geo_store.update_trip, gid, trip_id, payload)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="trip not found")
|
||||
return {"item": item}
|
||||
|
||||
|
||||
@router.delete("/trips/{trip_id}")
|
||||
async def remove_trip(
|
||||
trip_id: str,
|
||||
x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
|
||||
):
|
||||
if not SOCIAL_ENABLED:
|
||||
raise HTTPException(status_code=503, detail="social disabled")
|
||||
gid = _guest(x_social_guest_id)
|
||||
ok = await run_in_threadpool(geo_store.delete_trip, gid, trip_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="trip not found")
|
||||
return {"ok": True}
|
||||
133
apps/api/services/social_svc/s3_upload.py
Normal file
133
apps/api/services/social_svc/s3_upload.py
Normal file
@ -0,0 +1,133 @@
|
||||
"""Avatar / media upload via SeaweedFS S3 (s3.nomadro.com), with local fallback."""
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import os
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from social_svc.config import SOCIAL_UPLOAD_DIR
|
||||
|
||||
|
||||
@dataclass
|
||||
class UploadResult:
|
||||
url: str
|
||||
object_key: str
|
||||
size: int
|
||||
content_type: str
|
||||
storage: str # "s3" | "local"
|
||||
|
||||
|
||||
def _env(name: str, *alts: str, default: str = "") -> str:
|
||||
for key in (name, *alts):
|
||||
val = (os.getenv(key) or "").strip()
|
||||
if val:
|
||||
return val
|
||||
return default
|
||||
|
||||
|
||||
def s3_enabled() -> bool:
|
||||
"""Same SeaweedFS defaults as community_svc (s3.nomadro.com → :8333)."""
|
||||
if _env("S3_ENABLED", default="true").lower() not in {"1", "true", "yes", "on"}:
|
||||
return False
|
||||
# Access key defaults to nomadweb (US SeaweedFS); secret must come from env on prod.
|
||||
return bool(
|
||||
_env("S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb")
|
||||
and _env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY")
|
||||
)
|
||||
|
||||
|
||||
def _client():
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_env("S3_ENDPOINT", default="http://127.0.0.1:8333").rstrip("/"),
|
||||
aws_access_key_id=_env(
|
||||
"S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb"
|
||||
),
|
||||
aws_secret_access_key=_env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY"),
|
||||
region_name=_env("S3_REGION", default="us-east-1"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
|
||||
|
||||
def _object_key(filename: str, purpose: str, guest_id: str) -> str:
|
||||
suffix = Path(filename or "upload.bin").suffix.lower() or ".jpg"
|
||||
if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
|
||||
suffix = ".jpg"
|
||||
day = datetime.now(timezone.utc).strftime("%Y/%m/%d")
|
||||
prefix = (os.getenv("S3_UPLOAD_PREFIX") or "social").strip("/")
|
||||
purpose_part = (purpose or "avatar").replace("/", "-")[:40]
|
||||
guest = "".join(c for c in guest_id if c.isalnum() or c in "_-")[:32] or "guest"
|
||||
return f"{prefix}/{purpose_part}/{day}/{guest}_{uuid.uuid4().hex}{suffix}"
|
||||
|
||||
|
||||
def public_url_for_key(key: str) -> str:
|
||||
base = _env(
|
||||
"S3_PUBLIC_URL", default="https://s3.nomadro.com"
|
||||
).rstrip("/")
|
||||
bucket = _env("S3_BUCKET", default="nomadweb").strip("/")
|
||||
return f"{base}/{bucket}/{quote(key, safe='/')}"
|
||||
|
||||
|
||||
def upload_bytes(
|
||||
data: bytes,
|
||||
*,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
purpose: str,
|
||||
guest_id: str,
|
||||
max_size: int,
|
||||
) -> UploadResult:
|
||||
if not data:
|
||||
raise ValueError("empty file")
|
||||
if len(data) > max_size:
|
||||
raise ValueError(f"file too large (max {max_size // 1024 // 1024}MB)")
|
||||
|
||||
ctype = content_type or mimetypes.guess_type(filename or "")[0] or "image/jpeg"
|
||||
if not ctype.startswith("image/"):
|
||||
raise ValueError("only images allowed")
|
||||
|
||||
key = _object_key(filename, purpose, guest_id)
|
||||
|
||||
if s3_enabled():
|
||||
bucket = _env("S3_BUCKET", default="nomadweb")
|
||||
client = _client()
|
||||
try:
|
||||
try:
|
||||
client.put_object(
|
||||
Bucket=bucket,
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=ctype,
|
||||
ACL="public-read",
|
||||
)
|
||||
except Exception:
|
||||
client.put_object(Bucket=bucket, Key=key, Body=data, ContentType=ctype)
|
||||
return UploadResult(
|
||||
url=public_url_for_key(key),
|
||||
object_key=key,
|
||||
size=len(data),
|
||||
content_type=ctype,
|
||||
storage="s3",
|
||||
)
|
||||
except Exception:
|
||||
# Fall through to local if SeaweedFS is briefly unreachable
|
||||
pass
|
||||
|
||||
# Local fallback (dev / S3 off / S3 error)
|
||||
path = SOCIAL_UPLOAD_DIR / "avatars" / Path(key).name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return UploadResult(
|
||||
url=f"/api/social/v1/files/avatar/{path.name}",
|
||||
object_key=str(path),
|
||||
size=len(data),
|
||||
content_type=ctype,
|
||||
storage="local",
|
||||
)
|
||||
@ -10,7 +10,7 @@ from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from .config import SOCIAL_DB_PATH
|
||||
from .config import SOCIAL_DB_PATH, SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
|
||||
|
||||
try:
|
||||
from ebook_svc.core.sqlite_util import connect as _connect
|
||||
@ -60,6 +60,20 @@ def init_db() -> None:
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS channel_meta (
|
||||
channel_id TEXT PRIMARY KEY,
|
||||
next_seq INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS channel_read (
|
||||
guest_id TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
recv_seq INTEGER NOT NULL DEFAULT 0,
|
||||
read_seq INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (guest_id, channel_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cafe_reviews (
|
||||
id TEXT PRIMARY KEY,
|
||||
cafe_id TEXT NOT NULL,
|
||||
@ -81,6 +95,7 @@ def init_db() -> None:
|
||||
linktree TEXT,
|
||||
skills TEXT,
|
||||
bio TEXT,
|
||||
avatar TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
@ -102,61 +117,681 @@ def init_db() -> None:
|
||||
guest_id TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS trips (
|
||||
id TEXT PRIMARY KEY,
|
||||
guest_id TEXT NOT NULL,
|
||||
city_id TEXT,
|
||||
city TEXT NOT NULL,
|
||||
country TEXT,
|
||||
lat REAL,
|
||||
lng REAL,
|
||||
h3_cell TEXT,
|
||||
arrival_date TEXT,
|
||||
departure_date TEXT,
|
||||
visibility TEXT NOT NULL DEFAULT 'public',
|
||||
status TEXT NOT NULL DEFAULT 'planned',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status);
|
||||
"""
|
||||
)
|
||||
# migrate older DBs missing seq / client_id / meta
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()}
|
||||
if "seq" not in cols:
|
||||
conn.execute("ALTER TABLE messages ADD COLUMN seq INTEGER")
|
||||
if "client_id" not in cols:
|
||||
conn.execute("ALTER TABLE messages ADD COLUMN client_id TEXT")
|
||||
if "meta" not in cols:
|
||||
conn.execute("ALTER TABLE messages ADD COLUMN meta TEXT")
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_messages_channel_seq ON messages(channel_id, seq)"
|
||||
)
|
||||
roster_cols = {r[1] for r in conn.execute("PRAGMA table_info(roster)").fetchall()}
|
||||
if "avatar" not in roster_cols:
|
||||
conn.execute("ALTER TABLE roster ADD COLUMN avatar TEXT")
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS files (
|
||||
id TEXT PRIMARY KEY,
|
||||
channel_id TEXT NOT NULL,
|
||||
guest_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
mime TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_files_channel ON files(channel_id, created_at);
|
||||
"""
|
||||
)
|
||||
_backfill_seq(conn)
|
||||
try:
|
||||
from . import geo_pb
|
||||
|
||||
geo_pb.ensure_collection()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]:
|
||||
with db() as conn:
|
||||
def _parse_meta(raw: str | None) -> dict[str, Any]:
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _dump_meta(meta: dict[str, Any] | None) -> str:
|
||||
return json.dumps(meta or {}, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
_MSG_COLS = "id, channel_id, author, text, guest_id, created_at, seq, client_id, meta"
|
||||
|
||||
|
||||
def _backfill_seq(conn: sqlite3.Connection) -> None:
|
||||
"""Assign monotonic seq to legacy rows (Tinode-style topic seq)."""
|
||||
channels = conn.execute(
|
||||
"SELECT DISTINCT channel_id FROM messages WHERE seq IS NULL OR seq = 0"
|
||||
).fetchall()
|
||||
for ch in channels:
|
||||
cid = ch["channel_id"]
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, channel_id, author, text, guest_id, created_at
|
||||
SELECT id FROM messages
|
||||
WHERE channel_id = ? AND (seq IS NULL OR seq = 0)
|
||||
ORDER BY created_at ASC, rowid ASC
|
||||
""",
|
||||
(cid,),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
continue
|
||||
meta = conn.execute(
|
||||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (cid,)
|
||||
).fetchone()
|
||||
start = int(meta["next_seq"]) if meta else 1
|
||||
for i, r in enumerate(rows):
|
||||
conn.execute("UPDATE messages SET seq = ? WHERE id = ?", (start + i, r["id"]))
|
||||
nxt = start + len(rows)
|
||||
if meta:
|
||||
cur = int(meta["next_seq"] or 1)
|
||||
if nxt > cur:
|
||||
conn.execute(
|
||||
"UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
|
||||
(nxt, cid),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
|
||||
(cid, nxt),
|
||||
)
|
||||
|
||||
|
||||
def _row_message(r: sqlite3.Row) -> dict[str, Any]:
|
||||
item: dict[str, Any] = {
|
||||
"id": r["id"],
|
||||
"channelId": r["channel_id"],
|
||||
"author": r["author"],
|
||||
"text": r["text"],
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
"seq": int(r["seq"] or 0),
|
||||
}
|
||||
try:
|
||||
cid = r["client_id"]
|
||||
except (IndexError, KeyError):
|
||||
cid = None
|
||||
if cid:
|
||||
item["clientId"] = cid
|
||||
try:
|
||||
meta_raw = r["meta"]
|
||||
except (IndexError, KeyError):
|
||||
meta_raw = None
|
||||
meta = _parse_meta(meta_raw)
|
||||
# Element-like fields flattened for clients
|
||||
if meta.get("replyTo"):
|
||||
item["replyTo"] = meta["replyTo"]
|
||||
if meta.get("attachments"):
|
||||
item["attachments"] = meta["attachments"]
|
||||
if meta.get("reactions"):
|
||||
item["reactions"] = meta["reactions"]
|
||||
if meta.get("mentions"):
|
||||
item["mentions"] = meta["mentions"]
|
||||
if meta.get("editedAt"):
|
||||
item["editedAt"] = meta["editedAt"]
|
||||
if meta.get("recalled"):
|
||||
item["recalled"] = True
|
||||
item["text"] = ""
|
||||
if meta.get("pinned"):
|
||||
item["pinned"] = True
|
||||
if meta.get("pinnedAt"):
|
||||
item["pinnedAt"] = meta["pinnedAt"]
|
||||
if meta.get("reported"):
|
||||
item["reported"] = True
|
||||
return item
|
||||
|
||||
|
||||
def _get_message(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
|
||||
return conn.execute(
|
||||
f"SELECT {_MSG_COLS} FROM messages WHERE id = ?", (msg_id,)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _get_message_row(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
|
||||
return _get_message(conn, msg_id)
|
||||
|
||||
|
||||
def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]:
|
||||
"""Tinode-like topic desc: latest seq + caller's recv/read watermarks."""
|
||||
init_db()
|
||||
with db() as conn:
|
||||
meta = conn.execute(
|
||||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
if meta:
|
||||
seq = max(0, int(meta["next_seq"]) - 1)
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
seq = int(row["m"] or 0)
|
||||
recv = read = 0
|
||||
if guest_id:
|
||||
mark = conn.execute(
|
||||
"""
|
||||
SELECT recv_seq, read_seq FROM channel_read
|
||||
WHERE guest_id = ? AND channel_id = ?
|
||||
""",
|
||||
(guest_id, channel_id),
|
||||
).fetchone()
|
||||
if mark:
|
||||
recv = int(mark["recv_seq"] or 0)
|
||||
read = int(mark["read_seq"] or 0)
|
||||
peers = online_peers(channel_id)
|
||||
return {
|
||||
"channelId": channel_id,
|
||||
"seq": seq,
|
||||
"recv": recv,
|
||||
"read": read,
|
||||
"unread": max(0, seq - read),
|
||||
"online": len(peers),
|
||||
"peers": peers,
|
||||
}
|
||||
|
||||
|
||||
def list_messages(
|
||||
channel_id: str,
|
||||
limit: int = 100,
|
||||
*,
|
||||
since: int | None = None,
|
||||
before: int | None = None,
|
||||
q: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""History with Tinode-style seq cursors (since exclusive, before exclusive)."""
|
||||
lim = max(1, min(int(limit or 100), 500))
|
||||
needle = (q or "").strip()[:80]
|
||||
with db() as conn:
|
||||
if needle:
|
||||
like = f"%{needle}%"
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {_MSG_COLS}
|
||||
FROM messages
|
||||
WHERE channel_id = ?
|
||||
AND COALESCE(json_extract(meta, '$.recalled'), 0) = 0
|
||||
AND (text LIKE ? OR author LIKE ?)
|
||||
ORDER BY COALESCE(seq, 0) DESC, rowid DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(channel_id, like, like, lim),
|
||||
).fetchall()
|
||||
return [_row_message(r) for r in reversed(rows)]
|
||||
if since is not None and since > 0:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {_MSG_COLS}
|
||||
FROM messages
|
||||
WHERE channel_id = ? AND seq IS NOT NULL AND seq > ?
|
||||
ORDER BY seq ASC
|
||||
LIMIT ?
|
||||
""",
|
||||
(channel_id, since, lim),
|
||||
).fetchall()
|
||||
return [_row_message(r) for r in rows]
|
||||
if before is not None and before > 0:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {_MSG_COLS}
|
||||
FROM messages
|
||||
WHERE channel_id = ? AND seq IS NOT NULL AND seq < ?
|
||||
ORDER BY seq DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(channel_id, before, lim),
|
||||
).fetchall()
|
||||
return [_row_message(r) for r in reversed(rows)]
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {_MSG_COLS}
|
||||
FROM messages
|
||||
WHERE channel_id = ?
|
||||
ORDER BY created_at DESC, rowid DESC
|
||||
ORDER BY COALESCE(seq, 0) DESC, rowid DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(channel_id, max(1, min(limit, 500))),
|
||||
(channel_id, lim),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"channelId": r["channel_id"],
|
||||
"author": r["author"],
|
||||
"text": r["text"],
|
||||
"guestId": r["guest_id"],
|
||||
"at": r["created_at"],
|
||||
}
|
||||
for r in reversed(rows)
|
||||
return [_row_message(r) for r in reversed(rows)]
|
||||
|
||||
|
||||
def _normalize_reply(reply_to: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not reply_to or not isinstance(reply_to, dict):
|
||||
return None
|
||||
rid = str(reply_to.get("id") or "").strip()
|
||||
if not rid:
|
||||
return None
|
||||
return {
|
||||
"id": rid[:80],
|
||||
"author": str(reply_to.get("author") or "游民").strip()[:48] or "游民",
|
||||
"text": str(reply_to.get("text") or "").strip()[:240],
|
||||
"seq": int(reply_to.get("seq") or 0) or None,
|
||||
}
|
||||
|
||||
|
||||
def _normalize_attachments(items: list[Any] | None) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for raw in (items or [])[:8]:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
url = str(raw.get("url") or "").strip()
|
||||
kind = str(raw.get("kind") or "file").strip().lower()
|
||||
if kind not in {"image", "video", "file", "audio"}:
|
||||
kind = "file"
|
||||
if not url or len(url) > 800:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"id": str(raw.get("id") or _uid("att"))[:80],
|
||||
"kind": kind,
|
||||
"url": url,
|
||||
"name": str(raw.get("name") or "file").strip()[:160] or "file",
|
||||
"mime": str(raw.get("mime") or "application/octet-stream").strip()[:120],
|
||||
"size": max(0, min(int(raw.get("size") or 0), 50 * 1024 * 1024)),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def add_message(
|
||||
channel_id: str,
|
||||
author: str,
|
||||
text: str,
|
||||
guest_id: str,
|
||||
client_id: str | None = None,
|
||||
*,
|
||||
reply_to: dict[str, Any] | None = None,
|
||||
attachments: list[Any] | None = None,
|
||||
mentions: list[Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from social_svc.im import check_rate
|
||||
|
||||
check_rate(guest_id)
|
||||
body = (text or "").strip()[:2000]
|
||||
atts = _normalize_attachments(attachments)
|
||||
if not body and not atts:
|
||||
raise ValueError("empty message")
|
||||
reply = _normalize_reply(reply_to)
|
||||
mention_list = [
|
||||
str(m).strip()[:48]
|
||||
for m in (mentions or [])[:12]
|
||||
if str(m).strip()
|
||||
]
|
||||
meta: dict[str, Any] = {}
|
||||
if reply:
|
||||
meta["replyTo"] = reply
|
||||
if atts:
|
||||
meta["attachments"] = atts
|
||||
if mention_list:
|
||||
meta["mentions"] = mention_list
|
||||
|
||||
|
||||
def add_message(channel_id: str, author: str, text: str, guest_id: str, client_id: str | None = None) -> dict[str, Any]:
|
||||
msg_id = (
|
||||
"msg_"
|
||||
+ hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]
|
||||
if client_id
|
||||
else _uid("msg")
|
||||
)
|
||||
item = {
|
||||
"id": ("msg_" + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]) if client_id else _uid("msg"),
|
||||
"id": msg_id,
|
||||
"channelId": channel_id,
|
||||
"author": (author or "游民").strip()[:48] or "游民",
|
||||
"text": text.strip()[:2000],
|
||||
"text": body,
|
||||
"guestId": guest_id,
|
||||
"at": _now(),
|
||||
"seq": 0,
|
||||
}
|
||||
with db() as conn:
|
||||
existing = _get_message(conn, msg_id)
|
||||
if existing:
|
||||
if existing["text"] != item["text"] or existing["author"] != item["author"]:
|
||||
raise ValueError("同一请求标识不能用于不同消息")
|
||||
out = _row_message(existing)
|
||||
if client_id:
|
||||
out["clientId"] = client_id
|
||||
return out
|
||||
|
||||
ch_meta = conn.execute(
|
||||
"SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
|
||||
).fetchone()
|
||||
if ch_meta:
|
||||
seq = int(ch_meta["next_seq"])
|
||||
conn.execute(
|
||||
"UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
|
||||
(seq + 1, channel_id),
|
||||
)
|
||||
else:
|
||||
seq = 1
|
||||
conn.execute(
|
||||
"INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
|
||||
(channel_id, 2),
|
||||
)
|
||||
item["seq"] = seq
|
||||
conn.execute(
|
||||
f"""
|
||||
INSERT INTO messages({_MSG_COLS})
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
item["id"],
|
||||
item["channelId"],
|
||||
item["author"],
|
||||
item["text"],
|
||||
guest_id,
|
||||
item["at"],
|
||||
seq,
|
||||
client_id,
|
||||
_dump_meta(meta),
|
||||
),
|
||||
)
|
||||
out = {**item, **{k: v for k, v in {
|
||||
"clientId": client_id,
|
||||
"replyTo": reply,
|
||||
"attachments": atts or None,
|
||||
"mentions": mention_list or None,
|
||||
}.items() if v}}
|
||||
return out
|
||||
|
||||
|
||||
def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]:
|
||||
body = (text or "").strip()[:2000]
|
||||
if not body:
|
||||
raise ValueError("empty text")
|
||||
with db() as conn:
|
||||
row = _get_message(conn, msg_id)
|
||||
if not row or row["channel_id"] != channel_id:
|
||||
raise ValueError("message not found")
|
||||
if row["guest_id"] != guest_id:
|
||||
raise ValueError("not your message")
|
||||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||||
if meta.get("recalled"):
|
||||
raise ValueError("recalled")
|
||||
meta["editedAt"] = _now()
|
||||
conn.execute(
|
||||
"UPDATE messages SET text = ?, meta = ? WHERE id = ?",
|
||||
(body, _dump_meta(meta), msg_id),
|
||||
)
|
||||
row = _get_message(conn, msg_id)
|
||||
return _row_message(row) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]:
|
||||
"""Element-style redact: clear body, keep shell for timeline continuity."""
|
||||
with db() as conn:
|
||||
row = _get_message(conn, msg_id)
|
||||
if not row or row["channel_id"] != channel_id:
|
||||
raise ValueError("message not found")
|
||||
if row["guest_id"] != guest_id:
|
||||
raise ValueError("not your message")
|
||||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||||
meta["recalled"] = True
|
||||
meta["recalledAt"] = _now()
|
||||
meta.pop("attachments", None)
|
||||
meta.pop("reactions", None)
|
||||
conn.execute(
|
||||
"UPDATE messages SET text = '', meta = ? WHERE id = ?",
|
||||
(_dump_meta(meta), msg_id),
|
||||
)
|
||||
row = _get_message(conn, msg_id)
|
||||
return _row_message(row) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def react_message(
|
||||
channel_id: str, msg_id: str, guest_id: str, emoji: str
|
||||
) -> dict[str, Any]:
|
||||
"""Toggle annotation reaction (Element / Matrix m.annotation pattern)."""
|
||||
key = (emoji or "").strip()[:16]
|
||||
if not key:
|
||||
raise ValueError("empty emoji")
|
||||
with db() as conn:
|
||||
row = _get_message(conn, msg_id)
|
||||
if not row or row["channel_id"] != channel_id:
|
||||
raise ValueError("message not found")
|
||||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||||
if meta.get("recalled"):
|
||||
raise ValueError("recalled")
|
||||
reactions: dict[str, list[str]] = dict(meta.get("reactions") or {})
|
||||
holders = list(reactions.get(key) or [])
|
||||
if guest_id in holders:
|
||||
holders = [g for g in holders if g != guest_id]
|
||||
else:
|
||||
holders.append(guest_id)
|
||||
if holders:
|
||||
reactions[key] = holders[:64]
|
||||
else:
|
||||
reactions.pop(key, None)
|
||||
if reactions:
|
||||
meta["reactions"] = reactions
|
||||
else:
|
||||
meta.pop("reactions", None)
|
||||
conn.execute(
|
||||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||||
(_dump_meta(meta), msg_id),
|
||||
)
|
||||
row = _get_message(conn, msg_id)
|
||||
return _row_message(row) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def pin_message(
|
||||
channel_id: str, msg_id: str, guest_id: str, pinned: bool = True
|
||||
) -> dict[str, Any]:
|
||||
with db() as conn:
|
||||
row = _get_message(conn, msg_id)
|
||||
if not row or row["channel_id"] != channel_id:
|
||||
raise ValueError("message not found")
|
||||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||||
if meta.get("recalled"):
|
||||
raise ValueError("recalled")
|
||||
if pinned:
|
||||
meta["pinned"] = True
|
||||
meta["pinnedAt"] = _now()
|
||||
meta["pinnedBy"] = guest_id
|
||||
else:
|
||||
meta.pop("pinned", None)
|
||||
meta.pop("pinnedAt", None)
|
||||
meta.pop("pinnedBy", None)
|
||||
conn.execute(
|
||||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||||
(_dump_meta(meta), msg_id),
|
||||
)
|
||||
row = _get_message(conn, msg_id)
|
||||
return _row_message(row) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def save_upload(
|
||||
channel_id: str,
|
||||
guest_id: str,
|
||||
*,
|
||||
kind: str,
|
||||
name: str,
|
||||
mime: str,
|
||||
data: bytes,
|
||||
) -> dict[str, Any]:
|
||||
from social_svc.config import SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
|
||||
|
||||
if len(data) > SOCIAL_UPLOAD_MAX_BYTES:
|
||||
raise ValueError("file too large")
|
||||
if kind not in {"image", "video", "file", "audio"}:
|
||||
kind = "file"
|
||||
file_id = _uid("file")
|
||||
safe_name = "".join(c for c in (name or "file") if c.isalnum() or c in "._- ")[:120] or "file"
|
||||
root = SOCIAL_UPLOAD_DIR / channel_id
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
path = root / f"{file_id}_{safe_name}"
|
||||
path.write_bytes(data)
|
||||
item = {
|
||||
"id": file_id,
|
||||
"kind": kind,
|
||||
"name": safe_name,
|
||||
"mime": (mime or "application/octet-stream")[:120],
|
||||
"size": len(data),
|
||||
"url": f"/api/social/v1/files/{file_id}",
|
||||
}
|
||||
with db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO messages(id, channel_id, author, text, guest_id, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO files(id, channel_id, guest_id, kind, name, mime, size, path, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(item["id"], item["channelId"], item["author"], item["text"], guest_id, item["at"]),
|
||||
(
|
||||
file_id,
|
||||
channel_id,
|
||||
guest_id,
|
||||
kind,
|
||||
safe_name,
|
||||
item["mime"],
|
||||
item["size"],
|
||||
str(path),
|
||||
_now(),
|
||||
),
|
||||
)
|
||||
row = conn.execute("SELECT * FROM messages WHERE id = ?", (item["id"],)).fetchone()
|
||||
if row["text"] != item["text"] or row["author"] != item["author"]:
|
||||
raise ValueError("同一请求标识不能用于不同消息")
|
||||
item["at"] = row["created_at"]
|
||||
if client_id:
|
||||
item["clientId"] = client_id
|
||||
return item
|
||||
|
||||
|
||||
def get_file(file_id: str) -> dict[str, Any] | None:
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT * FROM files WHERE id = ?", (file_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": row["id"],
|
||||
"channelId": row["channel_id"],
|
||||
"kind": row["kind"],
|
||||
"name": row["name"],
|
||||
"mime": row["mime"],
|
||||
"size": row["size"],
|
||||
"path": row["path"],
|
||||
}
|
||||
|
||||
|
||||
# Element-like soft presence (TTL heartbeat; UI-agnostic)
|
||||
_PRESENCE: dict[str, dict[str, dict[str, Any]]] = {}
|
||||
_PRESENCE_TTL_SEC = 45
|
||||
|
||||
|
||||
def touch_presence(
|
||||
channel_id: str, guest_id: str, nick: str = ""
|
||||
) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
room = _PRESENCE.setdefault(channel_id, {})
|
||||
room[guest_id] = {
|
||||
"guestId": guest_id,
|
||||
"nick": (nick or "游民").strip()[:48] or "游民",
|
||||
"at": now,
|
||||
}
|
||||
# prune
|
||||
dead = [gid for gid, meta in room.items() if now - float(meta["at"]) > _PRESENCE_TTL_SEC]
|
||||
for gid in dead:
|
||||
room.pop(gid, None)
|
||||
peers = online_peers(channel_id)
|
||||
return {"channelId": channel_id, "online": len(peers), "peers": peers}
|
||||
|
||||
|
||||
def online_peers(channel_id: str) -> list[dict[str, Any]]:
|
||||
now = time.time()
|
||||
room = _PRESENCE.get(channel_id) or {}
|
||||
out: list[dict[str, Any]] = []
|
||||
for gid, meta in list(room.items()):
|
||||
if now - float(meta["at"]) > _PRESENCE_TTL_SEC:
|
||||
room.pop(gid, None)
|
||||
continue
|
||||
out.append({"guestId": gid, "nick": meta.get("nick") or "游民"})
|
||||
out.sort(key=lambda p: p["nick"])
|
||||
return out[:64]
|
||||
|
||||
|
||||
def report_message(
|
||||
channel_id: str, msg_id: str, guest_id: str, reason: str = ""
|
||||
) -> dict[str, Any]:
|
||||
with db() as conn:
|
||||
row = _get_message(conn, msg_id)
|
||||
if not row or row["channel_id"] != channel_id:
|
||||
raise ValueError("message not found")
|
||||
meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
|
||||
reporters = list(meta.get("reporters") or [])
|
||||
if guest_id not in reporters:
|
||||
reporters.append(guest_id)
|
||||
meta["reported"] = True
|
||||
meta["reporters"] = reporters[:64]
|
||||
meta["reportReason"] = (reason or "").strip()[:240]
|
||||
meta["reportedAt"] = _now()
|
||||
conn.execute(
|
||||
"UPDATE messages SET meta = ? WHERE id = ?",
|
||||
(_dump_meta(meta), msg_id),
|
||||
)
|
||||
row = _get_message(conn, msg_id)
|
||||
return _row_message(row) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]:
|
||||
"""Persist recv/read watermark (Tinode {note})."""
|
||||
what = (what or "").strip().lower()
|
||||
if what not in {"recv", "read"}:
|
||||
raise ValueError("what must be recv or read")
|
||||
seq = max(0, int(seq))
|
||||
init_db()
|
||||
now = _now()
|
||||
with db() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT recv_seq, read_seq FROM channel_read
|
||||
WHERE guest_id = ? AND channel_id = ?
|
||||
""",
|
||||
(guest_id, channel_id),
|
||||
).fetchone()
|
||||
recv = int(row["recv_seq"]) if row else 0
|
||||
read = int(row["read_seq"]) if row else 0
|
||||
if what == "recv":
|
||||
recv = max(recv, seq)
|
||||
else:
|
||||
read = max(read, seq)
|
||||
recv = max(recv, read)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO channel_read(guest_id, channel_id, recv_seq, read_seq, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(guest_id, channel_id) DO UPDATE SET
|
||||
recv_seq = excluded.recv_seq,
|
||||
read_seq = excluded.read_seq,
|
||||
updated_at = excluded.updated_at
|
||||
""",
|
||||
(guest_id, channel_id, recv, read, now),
|
||||
)
|
||||
return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read}
|
||||
|
||||
|
||||
def list_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]:
|
||||
with db() as conn:
|
||||
rows = conn.execute(
|
||||
@ -227,6 +862,7 @@ def get_roster(guest_id: str) -> dict[str, Any] | None:
|
||||
r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone()
|
||||
if not r:
|
||||
return None
|
||||
keys = set(r.keys())
|
||||
return {
|
||||
"guestId": r["guest_id"],
|
||||
"name": r["name"],
|
||||
@ -236,12 +872,20 @@ def get_roster(guest_id: str) -> dict[str, Any] | None:
|
||||
"linktree": r["linktree"] or "",
|
||||
"skills": r["skills"] or "",
|
||||
"bio": r["bio"] or "",
|
||||
"avatar": (r["avatar"] if "avatar" in keys else "") or "",
|
||||
"updatedAt": r["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
updated = _now()
|
||||
avatar = str(payload.get("avatar") or "").strip()[:500]
|
||||
if avatar and not (
|
||||
avatar.startswith("https://")
|
||||
or avatar.startswith("http://")
|
||||
or avatar.startswith("/api/social/")
|
||||
):
|
||||
avatar = ""
|
||||
row = {
|
||||
"guestId": guest_id,
|
||||
"name": str(payload.get("name") or "").strip()[:64] or "游民",
|
||||
@ -251,13 +895,14 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"linktree": str(payload.get("linktree") or "").strip()[:240],
|
||||
"skills": str(payload.get("skills") or "").strip()[:200],
|
||||
"bio": str(payload.get("bio") or "").strip()[:2000],
|
||||
"avatar": avatar,
|
||||
"updatedAt": updated,
|
||||
}
|
||||
with db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(guest_id) DO UPDATE SET
|
||||
name=excluded.name,
|
||||
title=excluded.title,
|
||||
@ -266,6 +911,7 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
linktree=excluded.linktree,
|
||||
skills=excluded.skills,
|
||||
bio=excluded.bio,
|
||||
avatar=excluded.avatar,
|
||||
updated_at=excluded.updated_at
|
||||
""",
|
||||
(
|
||||
@ -277,6 +923,7 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
row["linktree"],
|
||||
row["skills"],
|
||||
row["bio"],
|
||||
row["avatar"],
|
||||
updated,
|
||||
),
|
||||
)
|
||||
|
||||
@ -32,10 +32,14 @@ if SOCIAL_ENABLED:
|
||||
@app.get("/health")
|
||||
def health():
|
||||
from social_svc.config import CENTRIFUGO_ENABLED
|
||||
from social_svc.contract import IM_FEATURES, IM_PROTOCOL
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"service": "nomadro-social",
|
||||
"social": bool(SOCIAL_ENABLED),
|
||||
"centrifugo": bool(CENTRIFUGO_ENABLED),
|
||||
"imProtocol": IM_PROTOCOL,
|
||||
"imFeatures": list(IM_FEATURES),
|
||||
"uiAgnostic": True,
|
||||
}
|
||||
|
||||
37
apps/coffee/README.md
Normal file
37
apps/coffee/README.md
Normal file
@ -0,0 +1,37 @@
|
||||
# Coffeechat booking — Cal.com-domain secondary-dev
|
||||
|
||||
读开源 **Cal.com** 域模型后自研,挂游民社区 `/social/coffeechat`(Fair Use;非 iframe / 非原样塞 upstream UI):
|
||||
|
||||
| Cal.com 概念 | Nomadro | API |
|
||||
|---|---|---|
|
||||
| User / Host | 主持人公开页 | `GET /api/coffee/v1/hosts/:user` |
|
||||
| EventType | 咖啡聊 / 视频聊等时长类型 | `.../event-types/:slug` |
|
||||
| Schedule + Availability | 周内可约窗口(分钟) | `.../schedule` |
|
||||
| availableSlots | 按日生成空档 | `.../slots?day=` |
|
||||
| Booking + Attendee | 预约确认 / 取消 | `POST /bookings` |
|
||||
|
||||
## 本地
|
||||
|
||||
```bash
|
||||
pnpm coffee:fetch # 可选对照 → apps/coffee/upstream/cal.com
|
||||
pnpm dev:coffee-api # uvicorn coffee_main:app :8024
|
||||
pnpm dev # http://localhost:3000/social/coffeechat
|
||||
```
|
||||
|
||||
## 产品路由
|
||||
|
||||
| 路由 | 说明 |
|
||||
|---|---|
|
||||
| `/social/coffeechat` | 品牌落地 · 主持人列表 |
|
||||
| `/social/coffeechat/:user` | 事件类型列表 |
|
||||
| `/social/coffeechat/:user/:slug` | 选日 → 时段 → 确认 |
|
||||
| `/social/coffeechat/manage` | 演示主持人日程与预约 |
|
||||
| `/social/coffeechat/bookings/:id` | 预约详情 / 取消 |
|
||||
|
||||
数据:`data/coffee/coffee.sqlite3`。咖啡馆地图仍见 `/social/places?tab=cafes`。
|
||||
|
||||
## 反模式
|
||||
|
||||
- iframe / 嵌入官方 Cal.com
|
||||
- 跳 `cal.` 二级域
|
||||
- 把整包 Cal monorepo UI 硬塞进 Next
|
||||
49
apps/coffee/scripts/fetch-upstream.mjs
Normal file
49
apps/coffee/scripts/fetch-upstream.mjs
Normal file
@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Shallow-clone Cal.com into apps/coffee/upstream/ for secondary development.
|
||||
* Does not commit upstream into git.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const upstream = join(root, "upstream");
|
||||
|
||||
const REPOS = [
|
||||
{
|
||||
name: "cal.com",
|
||||
url: "https://github.com/calcom/cal.com.git",
|
||||
branch: "main",
|
||||
},
|
||||
];
|
||||
|
||||
mkdirSync(upstream, { recursive: true });
|
||||
|
||||
function run(cmd, args) {
|
||||
console.log(`$ ${cmd} ${args.join(" ")}`);
|
||||
const r = spawnSync(cmd, args, { stdio: "inherit", shell: false });
|
||||
if (r.status !== 0) process.exit(r.status || 1);
|
||||
}
|
||||
|
||||
for (const repo of REPOS) {
|
||||
const dest = join(upstream, repo.name);
|
||||
if (existsSync(join(dest, ".git"))) {
|
||||
console.log(`[skip] ${repo.name} already cloned — pull --ff-only`);
|
||||
run("git", ["-C", dest, "pull", "--ff-only", "origin", repo.branch]);
|
||||
continue;
|
||||
}
|
||||
if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
|
||||
run("git", [
|
||||
"clone",
|
||||
"--depth",
|
||||
"1",
|
||||
"--branch",
|
||||
repo.branch,
|
||||
repo.url,
|
||||
dest,
|
||||
]);
|
||||
}
|
||||
|
||||
console.log("DONE fetch-upstream →", upstream);
|
||||
68
apps/com/README.md
Normal file
68
apps/com/README.md
Normal file
@ -0,0 +1,68 @@
|
||||
# Nomadro `.com`(美国 VPS · 源码隔离)
|
||||
|
||||
与 **`.cn` 备案线完全隔离**:本目录只服务 **未备案的 `.com` Web**,**禁止**微信 / 抖音 / 小红书小程序业务与后台入口。
|
||||
|
||||
| 项 | `.cn`(国内) | `.com`(本目录) |
|
||||
|---|---|---|
|
||||
| 门户 | 仓库根 `src/` Next → `nomadro.cn` | 美国 VPS 单独部署(勿与 `.cn` 同进程混部) |
|
||||
| 管理后台 | [`apps/admin`](../admin) → `admin.nomadro.cn`(微信 / 抖音) | [`apps/com/admin`](./admin) → **`admin.nomadro.com`(仅 Web)** |
|
||||
| 小程序 | `apps/miniprogram/*` | **无** |
|
||||
|
||||
## 子包
|
||||
|
||||
| 路径 | 域名 | 说明 |
|
||||
|------|------|------|
|
||||
| `admin/` | `admin.nomadro.com` | Vite SPA,Web 运营模块 |
|
||||
|
||||
后续若在美国机再拆门户,可在本目录新增 `portal/` 等,仍勿回写进 `apps/admin` / 小程序树。
|
||||
|
||||
## 本地
|
||||
|
||||
```bash
|
||||
# 仓库根
|
||||
pnpm install
|
||||
pnpm dev:admin-com # http://127.0.0.1:5174
|
||||
pnpm build:admin-com
|
||||
```
|
||||
|
||||
### 线上分工(美国 VPS)
|
||||
|
||||
| 站点 | 前端 | 后端 |
|
||||
|------|------|------|
|
||||
| `https://nomadro.com` | **本机** `pnpm dev`(`:3000`)调试 | **线上** `https://api.nomadro.com` |
|
||||
| `https://admin.nomadro.com` | **线上** 静态 SPA(`apps/com/admin`) | **线上** 同上 API |
|
||||
|
||||
本地门户:根目录 `.env.local` 设 `API_URL=https://api.nomadro.com`,然后 `pnpm dev`。
|
||||
|
||||
### 埋点 / ntfy(nomadro.com)
|
||||
|
||||
| 层 | 作用 |
|
||||
|---|---|
|
||||
| 前端 `PortalAnalytics` + `~/lib/analytics/track` | 会话、路由 PV、`data-track` CTA、异常;受众 props |
|
||||
| Next `POST /api/track` | 关键事件推 `ntfy.nomadro.cn`(标题带 `[nomadro.com]`),并转发 `API_URL/api/track` 入库 |
|
||||
| Umami | `NEXT_PUBLIC_UMAMI_WEBSITE_ID` 聚合浏览(可选) |
|
||||
| `admin.nomadro.com` → 埋点 / ntfy | Events 回放 + 试推 |
|
||||
|
||||
`.env.local` 建议:`NTFY_BASE_URL` / `NTFY_TOPIC`(可选 `NTFY_TOPIC_COM`)/ Umami website id。
|
||||
|
||||
部署 `.com` 管理后台:
|
||||
|
||||
```bash
|
||||
python apps/admin/deploy/_deploy_admin_com_us.py
|
||||
```
|
||||
|
||||
登录:`hackrobot` / `Xiao4669805@`
|
||||
|
||||
## 受众(强制)
|
||||
|
||||
- **`.com` 默认 intl(英语 / 多语言)**;中文用户走 **cn 特殊线**
|
||||
- 模块 SoT:`src/modules/audience/{cn,intl}` — 支付 / 登录 / 关注 / 文案 / VIP / 埋点 / 社群
|
||||
- 调用:`resolveAudienceBundle()` / `useAudienceModule()`;禁止页面 `if (isChina)`
|
||||
- 后台:登录后选 `/cn` 或 `/intl`
|
||||
|
||||
## 铁律
|
||||
|
||||
- 不在本树引入 `weapp` / `tt` / Taro 小程序页面或开关
|
||||
- 不与 `admin.nomadro.cn` 共用前端源码目录(可各自调 API,token 键隔离)
|
||||
- 部署目标:美国 VPS;勿把本包静态资源发到 `.cn` 小程序后台目录
|
||||
- 功能按 `audience === 'cn' | 'intl'` 开发,禁止用 UI locale 反推支付
|
||||
29
apps/com/admin/README.md
Normal file
29
apps/com/admin/README.md
Normal file
@ -0,0 +1,29 @@
|
||||
# admin.nomadro.com(Web 运营台)
|
||||
|
||||
包名:`@nomadro/admin-com`。源码在 `apps/com/admin`,与 `apps/admin`(`.cn` 微信/抖音)隔离。
|
||||
|
||||
**生产**:前后端都在美国机(`admin.nomadro.com` + `api.nomadro.com`)。
|
||||
|
||||
## 能力
|
||||
|
||||
流程:登录 → **全屏选模块** → 进入该模块壳。
|
||||
|
||||
| 页 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| 选模块 | `/` | 登录后中间页(无侧栏) |
|
||||
| 中文用户 | `/cn/*` | 特殊线运营壳 |
|
||||
| 国际用户 | `/intl/*` | 默认线运营壳 |
|
||||
| 子页 | `…/switches|events|orders|users|ntfy|docs` | 模块内工具 |
|
||||
|
||||
## 部署
|
||||
|
||||
```bash
|
||||
pnpm build:admin-com
|
||||
python apps/admin/deploy/_deploy_admin_com_us.py
|
||||
# ntfy 试推 API(增量)
|
||||
python apps/admin/deploy/_deploy_ops_admin_us.py
|
||||
```
|
||||
|
||||
登录:`hackrobot` / `Xiao4669805@`
|
||||
|
||||
本地一般不启本包;门户调试见 [`apps/com/README.md`](../README.md)。
|
||||
18
apps/com/admin/index.html
Normal file
18
apps/com/admin/index.html
Normal file
@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1"
|
||||
/>
|
||||
<meta name="theme-color" content="#0c0c0f" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="description" content="Nomadro .com Web 管理后台(美国 VPS · 无小程序)" />
|
||||
<title>Nomadro Admin · .com</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
23
apps/com/admin/package.json
Normal file
23
apps/com/admin/package.json
Normal file
@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@nomadro/admin-com",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0 --port 5174",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host 0.0.0.0 --port 5174"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1",
|
||||
"react-router-dom": "6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "18.3.12",
|
||||
"@types/react-dom": "18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.11"
|
||||
}
|
||||
}
|
||||
80
apps/com/admin/src/App.tsx
Normal file
80
apps/com/admin/src/App.tsx
Normal file
@ -0,0 +1,80 @@
|
||||
import { Navigate, Route, Routes, useParams } from 'react-router-dom'
|
||||
import { getToken } from './api/client'
|
||||
import Login from './pages/Login'
|
||||
import ModuleSelect from './pages/ModuleSelect'
|
||||
import WebLayout from './components/WebLayout'
|
||||
import Docs from './pages/Docs'
|
||||
import Switches from './pages/Switches'
|
||||
import Events from './pages/Events'
|
||||
import Orders from './pages/Orders'
|
||||
import Users from './pages/Users'
|
||||
import Ntfy from './pages/Ntfy'
|
||||
import LaneHub, { type LaneKey } from './pages/LaneHub'
|
||||
|
||||
/**
|
||||
* https://admin.nomadro.com
|
||||
* 登录 → 选模块 → /cn | /intl(对齐 .cn:登录 → PlatformSelect → /wechat|/douyin)
|
||||
*/
|
||||
function Private({ children }: { children: React.ReactNode }) {
|
||||
if (!getToken()) return <Navigate to="/login" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
function LaneGuard({ children }: { children: React.ReactNode }) {
|
||||
const { lane } = useParams()
|
||||
if (lane !== 'cn' && lane !== 'intl') return <Navigate to="/" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
function LaneHome() {
|
||||
const { lane } = useParams()
|
||||
return <LaneHub lane={lane as LaneKey} />
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<Private>
|
||||
<ModuleSelect />
|
||||
</Private>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/:lane"
|
||||
element={
|
||||
<Private>
|
||||
<LaneGuard>
|
||||
<WebLayout />
|
||||
</LaneGuard>
|
||||
</Private>
|
||||
}
|
||||
>
|
||||
<Route index element={<LaneHome />} />
|
||||
<Route path="switches" element={<Switches />} />
|
||||
<Route path="events" element={<Events />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="ntfy" element={<Ntfy />} />
|
||||
<Route path="docs" element={<Docs />} />
|
||||
</Route>
|
||||
|
||||
{/* 旧路径 → 先选模块 */}
|
||||
<Route path="/audience" element={<Navigate to="/" replace />} />
|
||||
<Route path="/modules" element={<Navigate to="/" replace />} />
|
||||
<Route path="/switches" element={<Navigate to="/" replace />} />
|
||||
<Route path="/events" element={<Navigate to="/" replace />} />
|
||||
<Route path="/orders" element={<Navigate to="/" replace />} />
|
||||
<Route path="/users" element={<Navigate to="/" replace />} />
|
||||
<Route path="/ntfy" element={<Navigate to="/" replace />} />
|
||||
<Route path="/docs" element={<Navigate to="/" replace />} />
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
37
apps/com/admin/src/api/client.ts
Normal file
37
apps/com/admin/src/api/client.ts
Normal file
@ -0,0 +1,37 @@
|
||||
/** admin.nomadro.com — token 与 .cn admin 隔离 */
|
||||
const TOKEN_KEY = 'nomadro_admin_com_token'
|
||||
|
||||
export const API_BASE = import.meta.env.VITE_API_BASE || ''
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
export function setToken(t: string) {
|
||||
localStorage.setItem(TOKEN_KEY, t)
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(init.headers as Record<string, string> | undefined),
|
||||
}
|
||||
const token = getToken()
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
|
||||
if (res.status === 401) {
|
||||
clearToken()
|
||||
if (!path.includes('/login')) window.location.href = '/login'
|
||||
}
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
const err = data as { detail?: string; message?: string }
|
||||
throw new Error(err.detail || err.message || '请求失败')
|
||||
}
|
||||
return data as T
|
||||
}
|
||||
113
apps/com/admin/src/components/Charts.tsx
Normal file
113
apps/com/admin/src/components/Charts.tsx
Normal file
@ -0,0 +1,113 @@
|
||||
/** Lightweight SVG charts — no chart lib dependency. */
|
||||
|
||||
type Point = { date: string; value: number }
|
||||
|
||||
function niceMax(n: number) {
|
||||
if (n <= 0) return 1
|
||||
const p = 10 ** Math.floor(Math.log10(n))
|
||||
return Math.ceil(n / p) * p
|
||||
}
|
||||
|
||||
export function SparkBars({
|
||||
title,
|
||||
subtitle,
|
||||
points,
|
||||
format = (v) => String(v),
|
||||
accent = '#f59e0b',
|
||||
}: {
|
||||
title: string
|
||||
subtitle?: string
|
||||
points: Point[]
|
||||
format?: (v: number) => string
|
||||
accent?: string
|
||||
}) {
|
||||
const w = 560
|
||||
const h = 160
|
||||
const pad = { t: 12, r: 8, b: 28, l: 8 }
|
||||
const max = niceMax(Math.max(...points.map((p) => p.value), 0))
|
||||
const bw = points.length ? (w - pad.l - pad.r) / points.length : 0
|
||||
const innerH = h - pad.t - pad.b
|
||||
|
||||
return (
|
||||
<div className="com-chart">
|
||||
<div className="com-chart-head">
|
||||
<div>
|
||||
<strong>{title}</strong>
|
||||
{subtitle ? <span className="com-chart-sub">{subtitle}</span> : null}
|
||||
</div>
|
||||
<span className="com-chart-max">峰值 {format(max)}</span>
|
||||
</div>
|
||||
<svg viewBox={`0 0 ${w} ${h}`} className="com-chart-svg" role="img" aria-label={title}>
|
||||
{points.map((p, i) => {
|
||||
const barH = max ? (p.value / max) * innerH : 0
|
||||
const x = pad.l + i * bw + bw * 0.15
|
||||
const y = pad.t + innerH - barH
|
||||
const showLabel = i === 0 || i === points.length - 1 || i % 3 === 0
|
||||
return (
|
||||
<g key={p.date}>
|
||||
<rect
|
||||
x={x}
|
||||
y={y}
|
||||
width={bw * 0.7}
|
||||
height={Math.max(barH, p.value > 0 ? 2 : 0)}
|
||||
rx={3}
|
||||
fill={accent}
|
||||
opacity={0.85}
|
||||
>
|
||||
<title>
|
||||
{p.date}: {format(p.value)}
|
||||
</title>
|
||||
</rect>
|
||||
{showLabel ? (
|
||||
<text
|
||||
x={x + bw * 0.35}
|
||||
y={h - 8}
|
||||
textAnchor="middle"
|
||||
fill="currentColor"
|
||||
fontSize={10}
|
||||
opacity={0.55}
|
||||
>
|
||||
{p.date.slice(5)}
|
||||
</text>
|
||||
) : null}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function RankList({
|
||||
title,
|
||||
items,
|
||||
}: {
|
||||
title: string
|
||||
items: Array<{ name: string; count: number }>
|
||||
}) {
|
||||
const max = Math.max(...items.map((i) => i.count), 1)
|
||||
return (
|
||||
<div className="com-chart">
|
||||
<div className="com-chart-head">
|
||||
<strong>{title}</strong>
|
||||
</div>
|
||||
<ul className="com-rank">
|
||||
{items.length ? (
|
||||
items.map((it) => (
|
||||
<li key={it.name}>
|
||||
<div className="com-rank-row">
|
||||
<span className="com-rank-name">{it.name || '(empty)'}</span>
|
||||
<span className="com-rank-n">{it.count}</span>
|
||||
</div>
|
||||
<div className="com-rank-track">
|
||||
<i style={{ width: `${(it.count / max) * 100}%` }} />
|
||||
</div>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li className="com-rank-empty">暂无数据</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
128
apps/com/admin/src/components/WebLayout.tsx
Normal file
128
apps/com/admin/src/components/WebLayout.tsx
Normal file
@ -0,0 +1,128 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { clearToken } from '../api/client'
|
||||
import type { LaneKey } from '../pages/LaneHub'
|
||||
|
||||
type NavItem = { to: string; end?: boolean; ico: string; label: string }
|
||||
|
||||
const LANE_META: Record<LaneKey, { title: string; sub: string; mark: string }> = {
|
||||
cn: { title: '中文用户', sub: 'Chinese · 特殊对待', mark: '中' },
|
||||
intl: { title: '国际用户', sub: 'International · English', mark: 'EN' },
|
||||
}
|
||||
|
||||
function laneNav(lane: LaneKey): NavItem[] {
|
||||
const p = `/${lane}`
|
||||
return [
|
||||
{ to: p, end: true, ico: '◈', label: '模块总览' },
|
||||
{ to: `${p}/switches`, ico: '⏻', label: '动态开关' },
|
||||
{ to: `${p}/events`, ico: '📊', label: '埋点' },
|
||||
{ to: `${p}/orders`, ico: '🧾', label: '订单' },
|
||||
{ to: `${p}/users`, ico: '👥', label: '用户' },
|
||||
{ to: `${p}/ntfy`, ico: '🔔', label: 'ntfy' },
|
||||
{ to: `${p}/docs`, ico: '✓', label: '部署说明' },
|
||||
]
|
||||
}
|
||||
|
||||
function titleFromPath(lane: LaneKey, pathname: string) {
|
||||
const items = laneNav(lane)
|
||||
const hit = items.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
|
||||
const mod = LANE_META[lane].title
|
||||
return hit && !hit.end ? `${mod} · ${hit.label}` : mod
|
||||
}
|
||||
|
||||
/** 已选模块后的壳:只显示当前模块侧栏;切模块回选择页 */
|
||||
export default function WebLayout() {
|
||||
const nav = useNavigate()
|
||||
const { pathname } = useLocation()
|
||||
const { lane: laneParam } = useParams()
|
||||
const lane: LaneKey = laneParam === 'cn' ? 'cn' : 'intl'
|
||||
const meta = LANE_META[lane]
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setOpen(false)
|
||||
}, [pathname])
|
||||
|
||||
useEffect(() => {
|
||||
document.body.style.overflow = open ? 'hidden' : ''
|
||||
return () => {
|
||||
document.body.style.overflow = ''
|
||||
}
|
||||
}, [open])
|
||||
|
||||
function logout() {
|
||||
clearToken()
|
||||
nav('/login')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
|
||||
<header className="com-topbar">
|
||||
<button
|
||||
type="button"
|
||||
className="com-topbar-menu"
|
||||
aria-label={open ? '关闭菜单' : '打开菜单'}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</button>
|
||||
<div className="com-topbar-brand">
|
||||
<span className="com-topbar-mark">{meta.mark}</span>
|
||||
<div>
|
||||
<div className="com-topbar-title">{meta.title}</div>
|
||||
<div className="com-topbar-sub">{titleFromPath(lane, pathname)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="com-topbar-action" onClick={() => nav('/')}>
|
||||
换模块
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{open && (
|
||||
<button type="button" className="com-nav-scrim" aria-label="关闭菜单" onClick={() => setOpen(false)} />
|
||||
)}
|
||||
|
||||
<aside className="com-side" aria-hidden={!open}>
|
||||
<div className="com-logo">
|
||||
<span className="com-mark">{meta.mark}</span>
|
||||
<div>
|
||||
<div className="com-title">{meta.title}</div>
|
||||
<div className="com-sub">{meta.sub}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" className="com-pill com-pill-btn" onClick={() => nav('/')}>
|
||||
<span className="com-pill-dot" />
|
||||
切换模块 · 中文 / 国际
|
||||
</button>
|
||||
|
||||
<nav className="com-nav">
|
||||
{laneNav(lane).map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.end}
|
||||
className={({ isActive }) => (isActive ? 'active' : '')}
|
||||
>
|
||||
<span className="com-nav-ico" aria-hidden>
|
||||
{item.ico}
|
||||
</span>
|
||||
{item.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<button type="button" className="com-logout" onClick={logout}>
|
||||
退出登录
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<main className="com-main">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
13
apps/com/admin/src/main.tsx
Normal file
13
apps/com/admin/src/main.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './styles.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
32
apps/com/admin/src/pages/Docs.tsx
Normal file
32
apps/com/admin/src/pages/Docs.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
export default function Docs() {
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head">
|
||||
<div>
|
||||
<h1>部署说明</h1>
|
||||
<p>源码与发布目标都与 .cn 隔离。</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>本地</h2>
|
||||
<pre className="com-pre">{`pnpm install
|
||||
pnpm dev:admin-com # :5174
|
||||
pnpm build:admin-com`}</pre>
|
||||
</section>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>线上</h2>
|
||||
<ul className="com-list">
|
||||
<li>
|
||||
静态产物:<code>apps/com/admin/dist</code> → 美国 VPS · <code>admin.nomadro.com</code>
|
||||
</li>
|
||||
<li>
|
||||
勿发布到 <code>/www/wwwroot/admin.nomadro.cn</code>(那是 .cn 微信/抖音后台)
|
||||
</li>
|
||||
<li>门户 Next 若在美国机,与仓库根 <code>src/</code> 的 .cn 部署分开构建、分开进程</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
257
apps/com/admin/src/pages/Events.tsx
Normal file
257
apps/com/admin/src/pages/Events.tsx
Normal file
@ -0,0 +1,257 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type TrackEvent = {
|
||||
id: number
|
||||
name: string
|
||||
page: string | null
|
||||
label: string | null
|
||||
props: Record<string, unknown>
|
||||
openid: string
|
||||
client: string
|
||||
ts: number
|
||||
created_at: number
|
||||
}
|
||||
|
||||
const FILTERS = [
|
||||
'',
|
||||
'session_start',
|
||||
'page_view',
|
||||
'btn_click',
|
||||
'read_start',
|
||||
'unlock_click',
|
||||
'pay_start',
|
||||
'pay_success',
|
||||
'pay_fail',
|
||||
'pay_cancel',
|
||||
'pay_order_created',
|
||||
'pay_deliver',
|
||||
'pay_click',
|
||||
'buy_click',
|
||||
'login_ok',
|
||||
'login_fail',
|
||||
'error',
|
||||
'app_launch',
|
||||
'join_group_open',
|
||||
'follow_show',
|
||||
'follow_click',
|
||||
'share_x',
|
||||
'feedback_submit',
|
||||
'book_complete',
|
||||
]
|
||||
|
||||
const CLIENTS = ['', 'web_com', 'web_intl', 'web_cn', 'web', 'h5', 'weapp', 'tt', 'api', 'vip_web']
|
||||
|
||||
function clientLabel(c: string) {
|
||||
if (c === 'tt') return '抖音'
|
||||
if (c === 'weapp') return '微信'
|
||||
if (c === 'web_com') return 'nomadro.com'
|
||||
if (c === 'web_intl') return 'Web·intl'
|
||||
if (c === 'web_cn') return 'Web·cn'
|
||||
if (c === 'vip_web') return 'VIP Web'
|
||||
if (c === 'h5' || c === 'web') return 'Web/H5'
|
||||
return c || '全部'
|
||||
}
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts < 1e12 ? ts * 1000 : ts)
|
||||
return d.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function shortId(id: string, n = 8) {
|
||||
if (!id) return '—'
|
||||
return id.length <= n ? id : `…${id.slice(-n)}`
|
||||
}
|
||||
|
||||
function tone(name: string) {
|
||||
if (name.includes('success') || name === 'login_ok' || name === 'pay_deliver') return 'ok'
|
||||
if (name.includes('fail') || name === 'error' || name === 'login_fail') return 'bad'
|
||||
if (name.includes('cancel')) return 'warn'
|
||||
if (name.startsWith('pay_') || name.startsWith('join_')) return 'info'
|
||||
return 'muted'
|
||||
}
|
||||
|
||||
export default function Events() {
|
||||
const [events, setEvents] = useState<TrackEvent[]>([])
|
||||
const [filter, setFilter] = useState('')
|
||||
const [clientFilter, setClientFilter] = useState('')
|
||||
const [q, setQ] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [openId, setOpenId] = useState<number | null>(null)
|
||||
const [auto, setAuto] = useState(false)
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
const qs = new URLSearchParams({ limit: '200' })
|
||||
if (filter) qs.set('name', filter)
|
||||
if (clientFilter) qs.set('client', clientFilter)
|
||||
api<TrackEvent[]>(`/api/admin/track-events?${qs}`)
|
||||
.then(setEvents)
|
||||
.catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [filter, clientFilter])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (!auto) return
|
||||
const t = window.setInterval(load, 12000)
|
||||
return () => window.clearInterval(t)
|
||||
}, [auto, load])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const needle = q.trim().toLowerCase()
|
||||
if (!needle) return events
|
||||
return events.filter((ev) => {
|
||||
const blob = [ev.name, ev.page, ev.label, ev.openid, ev.client, JSON.stringify(ev.props || {})]
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
return blob.includes(needle)
|
||||
})
|
||||
}, [events, q])
|
||||
|
||||
const topNames = useMemo(() => {
|
||||
const map = new Map<string, number>()
|
||||
for (const ev of events) map.set(ev.name, (map.get(ev.name) || 0) + 1)
|
||||
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)
|
||||
}, [events])
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>埋点事件</h1>
|
||||
<p>行为与支付链路回放;关键事件会同步推 ntfy。</p>
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className={`com-btn com-btn-ghost${auto ? ' is-on' : ''}`}
|
||||
onClick={() => setAuto((v) => !v)}
|
||||
>
|
||||
{auto ? '自动刷新 · 开' : '自动刷新 · 关'}
|
||||
</button>
|
||||
<button type="button" className="com-btn" onClick={load} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid">
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">当前结果</span>
|
||||
<strong>{filtered.length}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">渠道</span>
|
||||
<strong style={{ fontSize: 16 }}>{clientLabel(clientFilter)}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">高频</span>
|
||||
<span className="com-stat-note" style={{ marginTop: 6, lineHeight: 1.5 }}>
|
||||
{topNames.length ? topNames.map(([n, c]) => `${n}×${c}`).join(' · ') : '—'}
|
||||
</span>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
{topNames.length ? (
|
||||
<div className="com-chip-row">
|
||||
<button type="button" className={`com-chip${!filter ? ' is-on' : ''}`} onClick={() => setFilter('')}>
|
||||
全部事件
|
||||
</button>
|
||||
{topNames.map(([n, c]) => (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className={`com-chip${filter === n ? ' is-on' : ''}`}
|
||||
onClick={() => setFilter(n)}
|
||||
>
|
||||
{n} · {c}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="com-toolbar">
|
||||
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
|
||||
{FILTERS.map((f) => (
|
||||
<option key={f || 'all'} value={f}>
|
||||
{f || '全部事件类型'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
|
||||
{CLIENTS.map((c) => (
|
||||
<option key={c || 'all'} value={c}>
|
||||
{clientLabel(c)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
placeholder="搜索 page / label / openid / props"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="com-table-wrap">
|
||||
{filtered.length ? (
|
||||
<table className="com-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>事件</th>
|
||||
<th>页面</th>
|
||||
<th>标签</th>
|
||||
<th>用户</th>
|
||||
<th>端</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((ev) => {
|
||||
const open = openId === ev.id
|
||||
const propsText = Object.keys(ev.props || {}).length
|
||||
? JSON.stringify(ev.props, null, 2)
|
||||
: ''
|
||||
return (
|
||||
<tr key={ev.id}>
|
||||
<td>{fmtTime(ev.ts || ev.created_at)}</td>
|
||||
<td>
|
||||
<span className={`com-badge tone-${tone(ev.name)}`}>{ev.name}</span>
|
||||
{open && propsText ? <pre className="com-detail">{propsText}</pre> : null}
|
||||
</td>
|
||||
<td>{ev.page || '—'}</td>
|
||||
<td>{ev.label || '—'}</td>
|
||||
<td>{shortId(ev.openid)}</td>
|
||||
<td>{clientLabel(ev.client)}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn-sm"
|
||||
disabled={!propsText}
|
||||
onClick={() => setOpenId(open ? null : ev.id)}
|
||||
>
|
||||
{open ? '收起' : '属性'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="com-empty">{loading ? '加载中…' : '暂无埋点数据'}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
267
apps/com/admin/src/pages/LaneHub.tsx
Normal file
267
apps/com/admin/src/pages/LaneHub.tsx
Normal file
@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 单受众模块运营台:/cn 或 /intl
|
||||
* 入口级区分中文用户 vs 国际(英语为主),再进开关 / 埋点等。
|
||||
*/
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
|
||||
export type LaneKey = 'cn' | 'intl'
|
||||
|
||||
type Lane = {
|
||||
payEnabled: boolean
|
||||
socialFollow: boolean
|
||||
followChannel: 'wechat' | 'x' | 'none'
|
||||
vipCta: string
|
||||
homeLead: string
|
||||
note?: string
|
||||
}
|
||||
|
||||
type AudienceCfg = {
|
||||
defaultLane: 'cn' | 'intl'
|
||||
cn: Lane
|
||||
intl: Lane
|
||||
version?: number
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
const META: Record<
|
||||
LaneKey,
|
||||
{
|
||||
title: string
|
||||
titleEn: string
|
||||
eyebrow: string
|
||||
detect: string
|
||||
pay: string
|
||||
follow: string
|
||||
accent: string
|
||||
}
|
||||
> = {
|
||||
cn: {
|
||||
title: '中文用户',
|
||||
titleEn: 'Chinese',
|
||||
eyebrow: '特殊对待 · Special lane',
|
||||
detect: '微信内置 MicroMessenger / is-china-user → 本模块',
|
||||
pay: 'zpay · 微信内 xpay',
|
||||
follow: '公众号二维码',
|
||||
accent: 'cn',
|
||||
},
|
||||
intl: {
|
||||
title: '国际用户',
|
||||
titleEn: 'International',
|
||||
eyebrow: '.com 默认 · English-first',
|
||||
detect: '非中文信号 → 本模块(日/越/泰可切语言)',
|
||||
pay: 'Creem · NOWPayments',
|
||||
follow: 'X / Twitter',
|
||||
accent: 'intl',
|
||||
},
|
||||
}
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
label: string
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<label className="com-switch" title={label}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
aria-label={label}
|
||||
/>
|
||||
<span className="com-switch-track">
|
||||
<span className="com-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
const meta = META[lane]
|
||||
const [cfg, setCfg] = useState<AudienceCfg | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [vipCta, setVipCta] = useState('')
|
||||
const [homeLead, setHomeLead] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<AudienceCfg>('/api/admin/audience')
|
||||
setCfg(data)
|
||||
const L = data[lane]
|
||||
setVipCta(L.vipCta)
|
||||
setHomeLead(L.homeLead)
|
||||
}, [lane])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
async function patchLane(partial: Partial<Lane>, okHint: string) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<AudienceCfg>('/api/admin/audience', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ [lane]: partial }),
|
||||
})
|
||||
setCfg(data)
|
||||
setVipCta(data[lane].vipCta)
|
||||
setHomeLead(data[lane].homeLead)
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
await load().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const L = cfg?.[lane]
|
||||
const other: LaneKey = lane === 'cn' ? 'intl' : 'cn'
|
||||
|
||||
const tools = [
|
||||
{ to: `/${lane}/switches`, ico: '⏻', title: '动态开关', desc: '页面 / flag / VIP 入口' },
|
||||
{ to: `/${lane}/events`, ico: '📊', title: '埋点', desc: '本轨相关行为回放' },
|
||||
{ to: `/${lane}/orders`, ico: '🧾', title: '订单', desc: '支付与发货' },
|
||||
{ to: `/${lane}/users`, ico: '👥', title: '用户', desc: '解锁与干预' },
|
||||
{ to: `/${lane}/ntfy`, ico: '🔔', title: 'ntfy', desc: '通知试推' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className={`com-page com-lane-hub com-lane-hub--${meta.accent}`}>
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<div className="com-lane-eyebrow">{meta.eyebrow}</div>
|
||||
<h1>
|
||||
{meta.title} <span className="com-lane-en">{meta.titleEn}</span>
|
||||
</h1>
|
||||
<p>
|
||||
{meta.detect}
|
||||
<br />
|
||||
支付 {meta.pay} · 关注 {meta.follow}
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className="com-chip com-chip-ok">模块 /{lane}</span>
|
||||
{cfg?.defaultLane === lane ? <span className="com-chip">识别失败时默认</span> : null}
|
||||
{cfg?.version != null ? <span className="com-chip">v{cfg.version}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
<Link className="com-btn com-btn-ghost" to="/">
|
||||
换模块 · {META[other].title}
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-hub-grid" style={{ marginBottom: 18 }}>
|
||||
{tools.map((t) => (
|
||||
<Link key={t.to} to={t.to} className="com-hub com-hub-primary">
|
||||
<span className="com-hub-ico" aria-hidden>
|
||||
{t.ico}
|
||||
</span>
|
||||
<strong>{t.title}</strong>
|
||||
<span>{t.desc}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!L ? (
|
||||
<div className="com-panel">加载本轨配置…</div>
|
||||
) : (
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<h2>本轨开关与文案</h2>
|
||||
<p>{L.note || '写入 remote-config.audience.' + lane}</p>
|
||||
</div>
|
||||
|
||||
<div className="com-flag-list">
|
||||
<div className="com-flag-row">
|
||||
<div>
|
||||
<strong>支付 CTA</strong>
|
||||
<p>{meta.pay}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={L.payEnabled}
|
||||
disabled={busy}
|
||||
label="pay"
|
||||
onChange={(v) => void patchLane({ payEnabled: v }, `支付已${v ? '开' : '关'}`)}
|
||||
/>
|
||||
</div>
|
||||
<div className="com-flag-row">
|
||||
<div>
|
||||
<strong>关注引导</strong>
|
||||
<p>{meta.follow}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={L.socialFollow}
|
||||
disabled={busy}
|
||||
label="follow"
|
||||
onChange={(v) => void patchLane({ socialFollow: v }, `关注已${v ? '开' : '关'}`)}
|
||||
/>
|
||||
</div>
|
||||
<div className="com-flag-row">
|
||||
<div>
|
||||
<strong>关注渠道</strong>
|
||||
<p>本轨默认渠道</p>
|
||||
</div>
|
||||
<select
|
||||
className="com-select"
|
||||
disabled={busy}
|
||||
value={L.followChannel}
|
||||
onChange={(e) =>
|
||||
void patchLane(
|
||||
{ followChannel: e.target.value as Lane['followChannel'] },
|
||||
`渠道 → ${e.target.value}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="wechat">微信公众号</option>
|
||||
<option value="x">X / Twitter</option>
|
||||
<option value="none">不弹</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="com-form-grid" style={{ marginTop: 14 }}>
|
||||
<label className="com-field">
|
||||
<span>VIP CTA</span>
|
||||
<input value={vipCta} disabled={busy} onChange={(e) => setVipCta(e.target.value)} />
|
||||
</label>
|
||||
<label className="com-field" style={{ gridColumn: '1 / -1' }}>
|
||||
<span>首页导语</span>
|
||||
<textarea
|
||||
className="com-textarea"
|
||||
rows={3}
|
||||
value={homeLead}
|
||||
disabled={busy}
|
||||
onChange={(e) => setHomeLead(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() => void patchLane({ vipCta, homeLead }, '文案已保存')}
|
||||
>
|
||||
保存文案
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
63
apps/com/admin/src/pages/Login.tsx
Normal file
63
apps/com/admin/src/pages/Login.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import { FormEvent, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { api, setToken } from '../api/client'
|
||||
|
||||
export default function Login() {
|
||||
const nav = useNavigate()
|
||||
const [username, setUsername] = useState('hackrobot')
|
||||
const [password, setPassword] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<{ token: string }>('/api/admin/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
setToken(data.token)
|
||||
nav('/')
|
||||
} catch (ex: unknown) {
|
||||
setErr(ex instanceof Error ? ex.message : '登录失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="login-bg" />
|
||||
<form className="login-card" onSubmit={onSubmit}>
|
||||
<div className="login-brand">
|
||||
<span className="login-mark">W</span>
|
||||
<div>
|
||||
<h1>Nomadro · .com</h1>
|
||||
<p>Web 管理后台 · admin.nomadro.com · 美国 VPS</p>
|
||||
</div>
|
||||
</div>
|
||||
<label>
|
||||
用户名
|
||||
<input value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />
|
||||
</label>
|
||||
<label>
|
||||
密码
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
enterKeyHint="go"
|
||||
/>
|
||||
</label>
|
||||
{err && <div className="error">{err}</div>}
|
||||
<button type="submit" disabled={loading}>
|
||||
{loading ? '登录中…' : '进入 Web 控制台'}
|
||||
</button>
|
||||
<p className="login-hint">本站无微信 / 抖音小程序模块(.com 未备案)</p>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
75
apps/com/admin/src/pages/ModuleSelect.tsx
Normal file
75
apps/com/admin/src/pages/ModuleSelect.tsx
Normal file
@ -0,0 +1,75 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { clearToken } from '../api/client'
|
||||
|
||||
/**
|
||||
* 登录后中间页:先选模块,再进壳。
|
||||
* 对齐 admin.nomadro.cn 的 PlatformSelect(微信 / 抖音)。
|
||||
*/
|
||||
export default function ModuleSelect() {
|
||||
const nav = useNavigate()
|
||||
|
||||
function logout() {
|
||||
clearToken()
|
||||
nav('/login')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modsel-page">
|
||||
<div className="modsel-bg" />
|
||||
<div className="modsel-inner">
|
||||
<div className="modsel-brand">
|
||||
<span className="modsel-mark">W</span>
|
||||
<div>
|
||||
<h1>选择运营模块</h1>
|
||||
<p>
|
||||
<code>admin.nomadro.com</code> · 登录后先选受众模块
|
||||
<br />
|
||||
<span className="modsel-note">中文用户特殊对待 · 国际线为 .com 默认</span>
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="modsel-logout" onClick={logout}>
|
||||
退出
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="modsel-grid">
|
||||
<button
|
||||
type="button"
|
||||
className="modsel-card modsel-card--cn"
|
||||
onClick={() => nav('/cn')}
|
||||
>
|
||||
<span className="modsel-card-top">
|
||||
<span className="modsel-ico" aria-hidden>
|
||||
中
|
||||
</span>
|
||||
<span className="modsel-badge">CN</span>
|
||||
</span>
|
||||
<strong>中文用户</strong>
|
||||
<span className="modsel-desc">
|
||||
微信内置 / is-china-user · zpay·xpay · 公众号
|
||||
</span>
|
||||
<span className="modsel-cta">进入中文模块 →</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="modsel-card modsel-card--intl"
|
||||
onClick={() => nav('/intl')}
|
||||
>
|
||||
<span className="modsel-card-top">
|
||||
<span className="modsel-ico modsel-ico--intl" aria-hidden>
|
||||
EN
|
||||
</span>
|
||||
<span className="modsel-badge modsel-badge--intl">INTL</span>
|
||||
</span>
|
||||
<strong>国际用户</strong>
|
||||
<span className="modsel-desc">
|
||||
English-first · Creem·NOWPayments · X · 多语言
|
||||
</span>
|
||||
<span className="modsel-cta">Enter International →</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
137
apps/com/admin/src/pages/Ntfy.tsx
Normal file
137
apps/com/admin/src/pages/Ntfy.tsx
Normal file
@ -0,0 +1,137 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type NtfyStatus = {
|
||||
enabled: boolean
|
||||
baseUrl: string
|
||||
topic: string
|
||||
hasToken: boolean
|
||||
publicHint: string
|
||||
}
|
||||
|
||||
export default function Ntfy() {
|
||||
const [status, setStatus] = useState<NtfyStatus | null>(null)
|
||||
const [title, setTitle] = useState('[WebAdmin] 试推')
|
||||
const [message, setMessage] = useState('admin.nomadro.com 通知通路正常')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api<NtfyStatus>('/api/admin/ops/ntfy')
|
||||
.then(setStatus)
|
||||
.catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
async function sendTest() {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const res = await api<{ ok: boolean; topic: string }>('/api/admin/ops/ntfy/test', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, message, priority: 3 }),
|
||||
})
|
||||
setMsg(res.ok ? `已推送到 topic「${res.topic || status?.topic || '—'}」` : '推送失败(检查 ntfy 服务与 token)')
|
||||
await load()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '试推失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>ntfy 通知</h1>
|
||||
<p>
|
||||
关键埋点 / 支付会自动推送。此处查看通路状态并可手动试推。订阅:{' '}
|
||||
<code>ntfy.nomadro.cn</code>
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={load} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新状态'}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid">
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">开关</span>
|
||||
<strong>{status ? (status.enabled ? '已启用' : '已关闭') : '…'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">Topic</span>
|
||||
<strong style={{ fontSize: 16 }}>{status?.topic || '—'}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">Token</span>
|
||||
<strong style={{ fontSize: 16 }}>{status?.hasToken ? '已配置' : '未配置'}</strong>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>通路信息</h2>
|
||||
<ul className="com-list">
|
||||
<li>
|
||||
机内地址:<code>{status?.baseUrl || '—'}</code>
|
||||
</li>
|
||||
<li>
|
||||
公开订阅:{' '}
|
||||
{status?.publicHint ? (
|
||||
<a href={status.publicHint} target="_blank" rel="noreferrer">
|
||||
{status.publicHint}
|
||||
</a>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</li>
|
||||
<li>门户 nomadro.com:会话 / 支付 / 登录 / 关注 / 购买 / 异常 → Next <code>/api/track</code> 推 ntfy,并转发 API 入库</li>
|
||||
<li>小程序关键事件仍由 API track 服务推送;Web 客户端只入库避免双推</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>手动试推</h2>
|
||||
<div className="com-form-grid">
|
||||
<label className="com-field">
|
||||
<span>标题</span>
|
||||
<input value={title} onChange={(e) => setTitle(e.target.value)} disabled={busy} />
|
||||
</label>
|
||||
<label className="com-field" style={{ gridColumn: '1 / -1' }}>
|
||||
<span>正文</span>
|
||||
<textarea
|
||||
className="com-textarea"
|
||||
rows={4}
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy || !status?.enabled}
|
||||
onClick={() => void sendTest()}
|
||||
>
|
||||
{busy ? '推送中…' : '发送测试通知'}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
207
apps/com/admin/src/pages/Orders.tsx
Normal file
207
apps/com/admin/src/pages/Orders.tsx
Normal file
@ -0,0 +1,207 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type Order = {
|
||||
out_trade_no: string
|
||||
wx_order_id: string | null
|
||||
openid: string
|
||||
book_id: string
|
||||
amount_fen: number
|
||||
status: string
|
||||
delivered: number
|
||||
created_at: number
|
||||
}
|
||||
|
||||
type StatusTab = 'all' | 'paid' | 'pending' | 'other'
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts < 1e12 ? ts * 1000 : ts)
|
||||
return d.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function fmtYuan(fen: number) {
|
||||
return `¥${(fen / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function shortId(id: string, n = 10) {
|
||||
if (!id) return '—'
|
||||
return id.length <= n ? id : `…${id.slice(-n)}`
|
||||
}
|
||||
|
||||
function statusLabel(status: string) {
|
||||
const s = (status || '').toLowerCase()
|
||||
if (s.includes('paid') || s.includes('success')) return '已支付'
|
||||
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return '待支付'
|
||||
if (s.includes('cancel')) return '已取消'
|
||||
if (s.includes('fail')) return '失败'
|
||||
if (s.includes('refund')) return '退款'
|
||||
return status || '未知'
|
||||
}
|
||||
|
||||
function statusTone(status: string) {
|
||||
const s = (status || '').toLowerCase()
|
||||
if (s.includes('paid') || s.includes('success')) return 'ok'
|
||||
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return 'warn'
|
||||
if (s.includes('fail') || s.includes('cancel') || s.includes('refund')) return 'bad'
|
||||
return 'muted'
|
||||
}
|
||||
|
||||
function isPaid(status: string) {
|
||||
const s = (status || '').toLowerCase()
|
||||
return s.includes('paid') || s.includes('success')
|
||||
}
|
||||
|
||||
function isPending(status: string) {
|
||||
const s = (status || '').toLowerCase()
|
||||
return s.includes('pend') || s.includes('creat') || s.includes('wait')
|
||||
}
|
||||
|
||||
export default function Orders() {
|
||||
const [orders, setOrders] = useState<Order[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [err, setErr] = useState('')
|
||||
const [q, setQ] = useState('')
|
||||
const [tab, setTab] = useState<StatusTab>('all')
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api<Order[]>('/api/admin/orders')
|
||||
.then(setOrders)
|
||||
.catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
const stats = useMemo(() => {
|
||||
let paid = 0
|
||||
let pending = 0
|
||||
let amount = 0
|
||||
for (const o of orders) {
|
||||
if (isPaid(o.status)) {
|
||||
paid += 1
|
||||
amount += o.amount_fen || 0
|
||||
} else if (isPending(o.status)) pending += 1
|
||||
}
|
||||
return { total: orders.length, paid, pending, amount }
|
||||
}, [orders])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const needle = q.trim().toLowerCase()
|
||||
return orders.filter((o) => {
|
||||
if (tab === 'paid' && !isPaid(o.status)) return false
|
||||
if (tab === 'pending' && !isPending(o.status)) return false
|
||||
if (tab === 'other' && (isPaid(o.status) || isPending(o.status))) return false
|
||||
if (!needle) return true
|
||||
const blob = [o.out_trade_no, o.openid, o.book_id, o.status, o.wx_order_id || ''].join(' ').toLowerCase()
|
||||
return blob.includes(needle)
|
||||
})
|
||||
}, [orders, q, tab])
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>订单列表</h1>
|
||||
<p>支付与发货状态;可按 openid / 单号搜索。</p>
|
||||
</div>
|
||||
<button type="button" className="com-btn" onClick={load} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid">
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">全部</span>
|
||||
<strong>{stats.total}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">已支付</span>
|
||||
<strong>{stats.paid}</strong>
|
||||
</article>
|
||||
<article className="com-stat com-stat-warn">
|
||||
<span className="com-stat-label">待支付</span>
|
||||
<strong>{stats.pending}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">成交额</span>
|
||||
<strong>{fmtYuan(stats.amount)}</strong>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div className="com-tabs">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['paid', '已支付'],
|
||||
['pending', '待支付'],
|
||||
['other', '其他'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
className={`com-tab${tab === k ? ' is-on' : ''}`}
|
||||
onClick={() => setTab(k)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
placeholder="搜索单号 / openid / book_id"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="com-table-wrap">
|
||||
{filtered.length ? (
|
||||
<table className="com-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>单号</th>
|
||||
<th>用户</th>
|
||||
<th>商品</th>
|
||||
<th>金额</th>
|
||||
<th>状态</th>
|
||||
<th>发货</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((o) => (
|
||||
<tr key={o.out_trade_no}>
|
||||
<td>{fmtTime(o.created_at)}</td>
|
||||
<td>
|
||||
<code>{shortId(o.out_trade_no, 14)}</code>
|
||||
</td>
|
||||
<td>{shortId(o.openid)}</td>
|
||||
<td>{o.book_id === '__vip__' ? 'VIP' : o.book_id || '—'}</td>
|
||||
<td>{fmtYuan(o.amount_fen || 0)}</td>
|
||||
<td>
|
||||
<span className={`com-badge tone-${statusTone(o.status)}`}>
|
||||
{statusLabel(o.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td>{o.delivered ? '已发' : '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="com-empty">{loading ? '加载中…' : '暂无订单'}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
364
apps/com/admin/src/pages/Switches.tsx
Normal file
364
apps/com/admin/src/pages/Switches.tsx
Normal file
@ -0,0 +1,364 @@
|
||||
/**
|
||||
* Web 动态开关 — 写入 remote-config;门户 / H5 约数秒热更新。
|
||||
* 不引入微信提审 / 抖音专属控件。
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
|
||||
|
||||
type SwitchesCfg = {
|
||||
modules: Record<string, Mod>
|
||||
flags: {
|
||||
payEnabled: boolean
|
||||
socialFollow: boolean
|
||||
offlineBadge: boolean
|
||||
joinGroupAction: 'popup' | 'vip'
|
||||
memoTrialBrowse?: boolean
|
||||
joinGroupWechat?: boolean
|
||||
}
|
||||
copy: {
|
||||
homeBrand: string
|
||||
homeTagline: string
|
||||
homeLead: string
|
||||
vipCta: string
|
||||
wechatOaName?: string
|
||||
memoUnlockCta?: string
|
||||
}
|
||||
vipEntries: Record<string, boolean>
|
||||
vipHero?: {
|
||||
heroEyebrow: string
|
||||
heroTitleAccent: string
|
||||
heroTitleRest: string
|
||||
heroLead: string
|
||||
}
|
||||
version?: number
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
type TabKey = 'pages' | 'flags' | 'vip' | 'copy'
|
||||
|
||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'pages', label: '页面' },
|
||||
{ key: 'flags', label: '功能' },
|
||||
{ key: 'vip', label: 'VIP 入口' },
|
||||
{ key: 'copy', label: '文案' },
|
||||
]
|
||||
|
||||
const PAGE_MODS = [
|
||||
{ key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' },
|
||||
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' },
|
||||
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册阅读' },
|
||||
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
|
||||
{ key: 'social', label: '游民社区', ico: '💕', desc: '社交大厅;关则拦截入口' },
|
||||
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地;关则加群改弹引导' },
|
||||
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
|
||||
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
|
||||
] as const
|
||||
|
||||
const VIP_ENTRIES = [
|
||||
{ key: 'showStats', label: '数据条', desc: '落地页统计数字' },
|
||||
{ key: 'showTopics', label: '模块入口', desc: '社群 / 商城卡片' },
|
||||
{ key: 'showVideos', label: '视频教程', desc: '视频课区块' },
|
||||
{ key: 'showEbooks', label: '电子书', desc: '电子书区块' },
|
||||
{ key: 'showCompare', label: '对比表', desc: '单买 vs 会员' },
|
||||
{ key: 'showFaq', label: 'FAQ', desc: '常见问题' },
|
||||
{ key: 'showCta', label: '开通 CTA', desc: '底部立即加入' },
|
||||
{ key: 'reviewMode', label: '审核模式', desc: '隐藏促销诱导' },
|
||||
] as const
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
label: string
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<label className="com-switch" title={label}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
aria-label={label}
|
||||
/>
|
||||
<span className="com-switch-track">
|
||||
<span className="com-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Switches() {
|
||||
const [cfg, setCfg] = useState<SwitchesCfg | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [tab, setTab] = useState<TabKey>('pages')
|
||||
const [draftCopy, setDraftCopy] = useState({
|
||||
homeBrand: '',
|
||||
homeTagline: '',
|
||||
homeLead: '',
|
||||
vipCta: '',
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<SwitchesCfg>('/api/admin/weapp/switches')
|
||||
setCfg(data)
|
||||
setDraftCopy({
|
||||
homeBrand: data.copy?.homeBrand || '',
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<SwitchesCfg>('/api/admin/weapp/switches', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
setCfg(data)
|
||||
setDraftCopy({
|
||||
homeBrand: data.copy?.homeBrand || '',
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
})
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
await load().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onCount = useMemo(() => {
|
||||
if (!cfg) return 0
|
||||
return PAGE_MODS.filter((m) => cfg.modules[m.key]?.enabled !== false).length
|
||||
}, [cfg])
|
||||
|
||||
if (!cfg) {
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head">
|
||||
<h1>动态开关</h1>
|
||||
<p>加载远程配置…</p>
|
||||
</header>
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head">
|
||||
<h1>动态开关</h1>
|
||||
<p>
|
||||
页面显隐、功能 flag、VIP 入口与文案。写入 remote-config,Web 端热更新。
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className="com-chip">版本 v{cfg.version ?? '—'}</span>
|
||||
<span className="com-chip com-chip-ok">
|
||||
页面开启 {onCount}/{PAGE_MODS.length}
|
||||
</span>
|
||||
{cfg.updatedAt ? <span className="com-chip">{cfg.updatedAt}</span> : null}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<nav className="com-tabs" aria-label="开关分类">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
className={`com-tab${tab === t.key ? ' is-on' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === 'pages' ? (
|
||||
<section className="com-panel">
|
||||
<h2>页面模块</h2>
|
||||
<p className="com-panel-desc">关闭后对应入口隐藏或拦截</p>
|
||||
<div className="com-switch-grid">
|
||||
{PAGE_MODS.map((m) => {
|
||||
const on = cfg.modules[m.key]?.enabled !== false
|
||||
return (
|
||||
<article key={m.key} className={`com-switch-card${on ? ' is-on' : ' is-off'}`}>
|
||||
<div className="com-switch-card-top">
|
||||
<span className="com-hub-ico" aria-hidden>
|
||||
{m.ico}
|
||||
</span>
|
||||
<Switch
|
||||
checked={on}
|
||||
disabled={busy}
|
||||
label={m.label}
|
||||
onChange={(v) => {
|
||||
if (m.key === 'vip') {
|
||||
void patch(
|
||||
{
|
||||
modules: { vip: { enabled: v } },
|
||||
flags: { joinGroupAction: v ? 'vip' : 'popup' },
|
||||
},
|
||||
v ? 'VIP 已开启 · 加群跳会员' : 'VIP 已关闭 · 加群改弹窗',
|
||||
)
|
||||
return
|
||||
}
|
||||
void patch(
|
||||
{ modules: { [m.key]: { enabled: v } } },
|
||||
`${m.label}已${v ? '开启' : '关闭'}`,
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<strong>{m.label}</strong>
|
||||
<p>{m.desc}</p>
|
||||
<span className={`com-status ${on ? 'on' : 'off'}`}>{on ? 'ON' : 'OFF'}</span>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'flags' ? (
|
||||
<section className="com-panel">
|
||||
<h2>功能 Flag</h2>
|
||||
<div className="com-flag-list">
|
||||
{(
|
||||
[
|
||||
{ key: 'payEnabled', label: '支付总开关', desc: '关闭后隐藏付费 CTA' },
|
||||
{ key: 'socialFollow', label: '关注引导', desc: '公众号 / X 关注弹窗' },
|
||||
{ key: 'offlineBadge', label: '离线角标', desc: '展示「本地数据」提示' },
|
||||
] as const
|
||||
).map((f) => {
|
||||
const on = Boolean(cfg.flags[f.key])
|
||||
return (
|
||||
<div key={f.key} className="com-flag-row">
|
||||
<div>
|
||||
<strong>{f.label}</strong>
|
||||
<p>{f.desc}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={on}
|
||||
disabled={busy}
|
||||
label={f.label}
|
||||
onChange={(v) =>
|
||||
void patch({ flags: { [f.key]: v } }, `${f.label}已${v ? '开启' : '关闭'}`)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div className="com-flag-row">
|
||||
<div>
|
||||
<strong>加群行为</strong>
|
||||
<p>popup=弹窗 · vip=跳会员页</p>
|
||||
</div>
|
||||
<select
|
||||
className="com-select"
|
||||
disabled={busy}
|
||||
value={cfg.flags.joinGroupAction || 'vip'}
|
||||
onChange={(e) =>
|
||||
void patch(
|
||||
{ flags: { joinGroupAction: e.target.value } },
|
||||
`加群行为 → ${e.target.value}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="vip">跳 VIP</option>
|
||||
<option value="popup">弹窗</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'vip' ? (
|
||||
<section className="com-panel">
|
||||
<h2>VIP 落地入口</h2>
|
||||
<div className="com-flag-list">
|
||||
{VIP_ENTRIES.map((f) => {
|
||||
const on = cfg.vipEntries?.[f.key] !== false
|
||||
return (
|
||||
<div key={f.key} className="com-flag-row">
|
||||
<div>
|
||||
<strong>{f.label}</strong>
|
||||
<p>{f.desc}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={on}
|
||||
disabled={busy}
|
||||
label={f.label}
|
||||
onChange={(v) =>
|
||||
void patch(
|
||||
{ vipEntries: { [f.key]: v } },
|
||||
`${f.label}已${v ? '开启' : '关闭'}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'copy' ? (
|
||||
<section className="com-panel">
|
||||
<h2>门户文案</h2>
|
||||
<div className="com-form-grid">
|
||||
{(
|
||||
[
|
||||
['homeBrand', '品牌名'],
|
||||
['homeTagline', '副标题'],
|
||||
['homeLead', '导语'],
|
||||
['vipCta', 'VIP CTA'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
value={draftCopy[key]}
|
||||
disabled={busy}
|
||||
onChange={(e) => setDraftCopy((d) => ({ ...d, [key]: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() => void patch({ copy: draftCopy }, '文案已保存')}
|
||||
>
|
||||
保存文案
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
276
apps/com/admin/src/pages/Users.tsx
Normal file
276
apps/com/admin/src/pages/Users.tsx
Normal file
@ -0,0 +1,276 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
type UnlockRow = { book_id: string; unlocked_at: number; source: string }
|
||||
|
||||
type UserRow = {
|
||||
openid: string
|
||||
nickname?: string | null
|
||||
status?: string
|
||||
notes?: string | null
|
||||
updated_at: number
|
||||
unlocked_default: boolean
|
||||
unlocked_vip?: boolean
|
||||
unlocks: UnlockRow[]
|
||||
}
|
||||
|
||||
type Tab = 'all' | 'unlocked' | 'vip' | 'locked' | 'blocked'
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts < 1e12 ? ts * 1000 : ts)
|
||||
return d.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function shortId(id: string, n = 10) {
|
||||
if (!id) return '—'
|
||||
return id.length <= n ? id : `…${id.slice(-n)}`
|
||||
}
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<UserRow[]>([])
|
||||
const [q, setQ] = useState('')
|
||||
const [tab, setTab] = useState<Tab>('all')
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [manualOpenid, setManualOpenid] = useState('')
|
||||
|
||||
const refresh = useCallback(async (search = q) => {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
try {
|
||||
const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
|
||||
setUsers(await api<UserRow[]>(`/api/admin/users${qs}`))
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [q])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh('')
|
||||
}, [])
|
||||
|
||||
const counts = useMemo(() => {
|
||||
let unlocked = 0
|
||||
let vip = 0
|
||||
let locked = 0
|
||||
let blocked = 0
|
||||
for (const u of users) {
|
||||
if ((u.status || 'active') === 'blocked') blocked += 1
|
||||
if (u.unlocked_vip) vip += 1
|
||||
if (u.unlocked_default) unlocked += 1
|
||||
else locked += 1
|
||||
}
|
||||
return { total: users.length, unlocked, vip, locked, blocked }
|
||||
}, [users])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return users.filter((u) => {
|
||||
if (tab === 'unlocked') return u.unlocked_default
|
||||
if (tab === 'vip') return Boolean(u.unlocked_vip)
|
||||
if (tab === 'locked') return !u.unlocked_default
|
||||
if (tab === 'blocked') return (u.status || 'active') === 'blocked'
|
||||
return true
|
||||
})
|
||||
}, [users, tab])
|
||||
|
||||
async function unlock(openid: string) {
|
||||
setBusy(openid)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid, book_id: 'default' }),
|
||||
})
|
||||
setMsg(`已解锁 ${shortId(openid)}`)
|
||||
await refresh()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '解锁失败')
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(openid: string) {
|
||||
setBusy(openid)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
await api('/api/admin/revoke-unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid, book_id: 'default' }),
|
||||
})
|
||||
setMsg(`已撤销 ${shortId(openid)}`)
|
||||
await refresh()
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '撤销失败')
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head com-page-head-row">
|
||||
<div>
|
||||
<h1>用户列表</h1>
|
||||
<p>解锁状态、封禁与人工干预。</p>
|
||||
</div>
|
||||
<button type="button" className="com-btn" onClick={() => void refresh()} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-stat-grid com-stat-grid-5">
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">全部</span>
|
||||
<strong>{counts.total}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">已解锁</span>
|
||||
<strong>{counts.unlocked}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">VIP</span>
|
||||
<strong>{counts.vip}</strong>
|
||||
</article>
|
||||
<article className="com-stat">
|
||||
<span className="com-stat-label">未解锁</span>
|
||||
<strong>{counts.locked}</strong>
|
||||
</article>
|
||||
<article className="com-stat com-stat-warn">
|
||||
<span className="com-stat-label">封禁</span>
|
||||
<strong>{counts.blocked}</strong>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div className="com-tabs">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['unlocked', '已解锁'],
|
||||
['vip', 'VIP'],
|
||||
['locked', '未解锁'],
|
||||
['blocked', '封禁'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
className={`com-tab${tab === k ? ' is-on' : ''}`}
|
||||
onClick={() => setTab(k)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
placeholder="搜索 openid / 昵称"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void refresh()
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => void refresh()}>
|
||||
搜索
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section className="com-panel">
|
||||
<h2>手动解锁</h2>
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
value={manualOpenid}
|
||||
placeholder="粘贴 openid"
|
||||
onChange={(e) => setManualOpenid(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={!manualOpenid.trim() || Boolean(busy)}
|
||||
onClick={() => void unlock(manualOpenid.trim())}
|
||||
>
|
||||
解锁 default
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="com-table-wrap">
|
||||
{filtered.length ? (
|
||||
<table className="com-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>用户</th>
|
||||
<th>昵称</th>
|
||||
<th>状态</th>
|
||||
<th>解锁</th>
|
||||
<th>更新</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((u) => (
|
||||
<tr key={u.openid}>
|
||||
<td>
|
||||
<code>{shortId(u.openid)}</code>
|
||||
</td>
|
||||
<td>{u.nickname || '—'}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`com-badge tone-${
|
||||
(u.status || 'active') === 'blocked' ? 'bad' : 'ok'
|
||||
}`}
|
||||
>
|
||||
{u.status || 'active'}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{u.unlocked_vip ? 'VIP' : u.unlocked_default ? 'default' : '—'}
|
||||
</td>
|
||||
<td>{fmtTime(u.updated_at)}</td>
|
||||
<td>
|
||||
<div className="com-row-actions">
|
||||
{!u.unlocked_default ? (
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn-sm"
|
||||
disabled={busy === u.openid}
|
||||
onClick={() => void unlock(u.openid)}
|
||||
>
|
||||
解锁
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn-sm"
|
||||
disabled={busy === u.openid}
|
||||
onClick={() => void revoke(u.openid)}
|
||||
>
|
||||
撤销
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="com-empty">{loading ? '加载中…' : '暂无用户'}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
1128
apps/com/admin/src/styles.css
Normal file
1128
apps/com/admin/src/styles.css
Normal file
File diff suppressed because it is too large
Load Diff
9
apps/com/admin/src/vite-env.d.ts
vendored
Normal file
9
apps/com/admin/src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
20
apps/com/admin/tsconfig.json
Normal file
20
apps/com/admin/tsconfig.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react/index.d.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
32
apps/com/admin/vite.config.ts
Normal file
32
apps/com/admin/vite.config.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
/**
|
||||
* admin.nomadro.com — Web only; isolated from apps/admin (.cn)
|
||||
* 本地调试默认反代美国 VPS API(后端在服务器,前端本机)。
|
||||
* 若要打本地 API:设 VITE_DEV_API=http://127.0.0.1:8080
|
||||
*/
|
||||
const DEV_API = process.env.VITE_DEV_API || 'https://api.nomadro.com'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5174,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: DEV_API,
|
||||
changeOrigin: true,
|
||||
secure: true,
|
||||
},
|
||||
'/health': {
|
||||
target: DEV_API,
|
||||
changeOrigin: true,
|
||||
secure: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
},
|
||||
})
|
||||
|
||||
@ -208,7 +208,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
homeBrand: 'nomadro',
|
||||
homeTagline: '',
|
||||
homeLead: '',
|
||||
vipPriceFen: 29800,
|
||||
vipPriceFen: 8800,
|
||||
vipProductId: 'tiktok',
|
||||
vipCta: '立即加入',
|
||||
wechatOaName: '异度世界',
|
||||
|
||||
@ -233,5 +233,12 @@ export const TEAM_KIND_LABEL: Record<SocialTeamKind, string> = {
|
||||
fulltime: "全职机会",
|
||||
};
|
||||
|
||||
/** Same box as nomadro.cn (82.x). Prefer .cn — avoid .com→107 hop. */
|
||||
export const MIROTALK_URL = 'https://mirotalk.nomadro.cn'
|
||||
/**
|
||||
* 自研 MiroTalk:生产同域 `/join`(nginx → :9300),禁止跳 mirotalk.*。
|
||||
* H5 在浏览器里用当前 origin;小程序原生厅走 LivePusher,不依赖此 URL。
|
||||
*/
|
||||
export const MIROTALK_URL =
|
||||
typeof window !== 'undefined' &&
|
||||
/^(www\.)?nomadro\.(cn|com)$/.test(window.location.hostname)
|
||||
? window.location.origin
|
||||
: 'https://nomadro.cn'
|
||||
|
||||
@ -26,7 +26,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "独立设计师",
|
||||
city: "清迈 · Nimman",
|
||||
tags: ["咖啡局", "设计", "日出"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/65.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "喜欢把 cowork 聊成真实见面。周末常去 Graph Table,也爱清晨骑车去山上看雾。",
|
||||
vibe: "温柔 · 有品味",
|
||||
online: true,
|
||||
@ -46,7 +46,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "全栈 / SaaS",
|
||||
city: "里斯本",
|
||||
tags: ["Next.js", "夜跑", "冲浪"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/32.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1681097561932-36d0df02b379?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "白天写代码,傍晚海边。欢迎 Coffeechat 聊产品与出海。",
|
||||
vibe: "阳光 · 靠谱",
|
||||
online: true,
|
||||
@ -65,7 +65,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "内容创业者",
|
||||
city: "巴厘岛 · Canggu",
|
||||
tags: ["Vlog", "瑜伽", "出海"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/44.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1524548209323-6fb4a0d4a4a3?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "镜头前很活泼,线下更爱深度聊天。常在 Canggu cowork。",
|
||||
vibe: "活力",
|
||||
online: false,
|
||||
@ -81,7 +81,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "产品经理",
|
||||
city: "东京 / 远程",
|
||||
tags: ["B2B", "胶片", "拉面"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/75.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1540569014015-19a7be504e3a?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "时差玩家。开视频见面时很稳,私下爱胶片机。",
|
||||
vibe: "干净 · 有梗",
|
||||
online: true,
|
||||
@ -97,7 +97,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "增长黑客",
|
||||
city: "曼谷",
|
||||
tags: ["增长", "夜市", "泰语"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/68.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1515191627608-9f04cf8dc9d1?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "把增长聊成故事。欢迎约路边摊。",
|
||||
vibe: "聪明 · 飒",
|
||||
online: true,
|
||||
@ -113,7 +113,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "独立开发者",
|
||||
city: "成都 → 清迈",
|
||||
tags: ["Flutter", "火锅", "副业"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/52.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1672155411493-d36070f0c8f8?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "刚到东南亚第三周,想认识本地局朋友。",
|
||||
vibe: "真诚 · 幽默",
|
||||
online: false,
|
||||
@ -129,7 +129,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "摄影师",
|
||||
city: "大城 / 曼谷",
|
||||
tags: ["旅拍", "胶片", "咖啡"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/21.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1634552516330-ab1ccc0f605e?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "擅长拍人。可以帮你拍「游民证件照」。",
|
||||
vibe: "氛围感",
|
||||
online: true,
|
||||
@ -148,7 +148,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "跨境电商",
|
||||
city: "槟城",
|
||||
tags: ["TikTok", "冲浪", "搞钱"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/22.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1611580839246-23c8de2e04aa?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "白天看数据,傍晚冲浪。社群里最活跃的那几个之一。",
|
||||
vibe: "热情 · 靠谱",
|
||||
online: true,
|
||||
@ -164,7 +164,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "UX 研究员",
|
||||
city: "柏林",
|
||||
tags: ["访谈", "市集", "播客"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/33.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1549286386-efeff0dde84c?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "欧洲时区,擅长把陌生人聊成朋友。",
|
||||
vibe: "知性",
|
||||
online: false,
|
||||
@ -180,7 +180,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "AI 工程师",
|
||||
city: "首尔 / 远程",
|
||||
tags: ["Agent", "开源", "咖啡"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/41.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1557862921-37829c790f19?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "技术宅但不社恐。经常来开视频见面。",
|
||||
vibe: "稳 · 有趣",
|
||||
online: true,
|
||||
@ -196,7 +196,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "咖啡馆主理人",
|
||||
city: "大理",
|
||||
tags: ["手冲", "音乐会", "徒步"],
|
||||
avatar: "https://randomuser.me/api/portraits/women/90.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1544168190-79c17527004f?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "店在古城边。来大理一定请你喝手冲。",
|
||||
vibe: "松弛",
|
||||
online: true,
|
||||
@ -212,7 +212,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
|
||||
title: "游民教练",
|
||||
city: "里斯本",
|
||||
tags: ["签证", "地理套利", "跑步"],
|
||||
avatar: "https://randomuser.me/api/portraits/men/11.jpg",
|
||||
avatar: "https://images.unsplash.com/photo-1615109398623-88346a601842?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
bio: "帮过上百人规划第一站。Coffeechat 从不冷场。",
|
||||
vibe: "温暖",
|
||||
online: false,
|
||||
|
||||
@ -1,9 +1,16 @@
|
||||
/** Community chat: persistent outbox, explicit retries, HTTP + WebSocket. */
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
|
||||
import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatMessage } from '@/services/socialApi'
|
||||
import {
|
||||
createSocialRequestId,
|
||||
getSocialGuestId,
|
||||
socialApi,
|
||||
type SocialChatAttachment,
|
||||
type SocialChatMessage,
|
||||
type SocialChatReplyTo,
|
||||
} from '@/services/socialApi'
|
||||
import { connectChatRealtime } from '@/services/socialRealtime'
|
||||
import { mergeChatMessages } from '@/services/socialChatState'
|
||||
import { maxChatSeq, mergeChatMessages } from '@/services/socialChatState'
|
||||
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
|
||||
import { getCachedRemoteConfig } from '@/services/remoteConfig'
|
||||
import { isSocialFeatureEnabled, resolveSocialOps } from '@/utils/socialOps'
|
||||
@ -21,11 +28,15 @@ export function useSocialChat(channelId: string) {
|
||||
})
|
||||
const [status, setStatus] = useState<ChatLinkStatus>('connecting')
|
||||
const [sending, setSending] = useState(false)
|
||||
const [typingPeers, setTypingPeers] = useState<string[]>([])
|
||||
const [online, setOnline] = useState(0)
|
||||
const lock = useRef(false)
|
||||
const active = useRef(channelId)
|
||||
const mounted = useRef(false)
|
||||
const initializedKey = useRef('')
|
||||
const visible = useRef(true)
|
||||
const typingBeat = useRef(0)
|
||||
const typingClear = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const refreshRef = useRef<() => Promise<void>>(async () => {})
|
||||
active.current = channelId
|
||||
|
||||
@ -52,14 +63,26 @@ export function useSocialChat(channelId: string) {
|
||||
let realtime = false
|
||||
let failures = 0
|
||||
let nextRefresh = 0
|
||||
const refresh = async () => {
|
||||
let lastSeq = 0
|
||||
const refresh = async (mode: 'full' | 'since' = 'since') => {
|
||||
if (cancelled || refreshing || !visible.current) return
|
||||
refreshing = true
|
||||
try {
|
||||
const response = await socialApi.listMessages(channelId)
|
||||
const since = mode === 'since' && lastSeq > 0 ? lastSeq : undefined
|
||||
const response = await socialApi.listMessages(channelId, {
|
||||
limit: since ? 200 : 100,
|
||||
since,
|
||||
})
|
||||
if (cancelled) return
|
||||
if (!Array.isArray(response.items)) throw new Error('消息格式异常')
|
||||
setMessages((current) => mergeChatMessages(current, response.items, guest))
|
||||
setMessages((current) => {
|
||||
const next = mergeChatMessages(current, response.items, guest)
|
||||
lastSeq = Math.max(lastSeq, maxChatSeq(next), Number(response.seq || 0))
|
||||
return next
|
||||
})
|
||||
if (lastSeq > 0) {
|
||||
void socialApi.postNote(channelId, 'read', lastSeq).catch(() => undefined)
|
||||
}
|
||||
failures = 0
|
||||
nextRefresh = 0
|
||||
setStatus(realtime ? 'live' : 'polling')
|
||||
@ -77,22 +100,49 @@ export function useSocialChat(channelId: string) {
|
||||
setSending(false)
|
||||
lock.current = false
|
||||
setStatus('connecting')
|
||||
void refresh()
|
||||
const beatPresence = () => {
|
||||
void socialApi.presence(channelId, nick).then((info) => {
|
||||
if (!cancelled) setOnline(Number(info.online || 0))
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
void refresh('full')
|
||||
beatPresence()
|
||||
const timer = setInterval(() => {
|
||||
if (Date.now() >= nextRefresh) void refresh()
|
||||
}, 8000)
|
||||
if (Date.now() >= nextRefresh) void refresh('since')
|
||||
}, 12000)
|
||||
const presenceTimer = setInterval(beatPresence, 20000)
|
||||
const realtimeOn = isSocialFeatureEnabled(
|
||||
resolveSocialOps(getCachedRemoteConfig()),
|
||||
'chatRealtime',
|
||||
)
|
||||
if (realtimeOn) {
|
||||
void connectChatRealtime(channelId, (item) => {
|
||||
if (cancelled) return
|
||||
setMessages((current) => mergeChatMessages(current, [item], guest))
|
||||
}, (connected) => {
|
||||
realtime = connected
|
||||
if (!cancelled) setStatus(connected ? 'live' : 'polling')
|
||||
}).then((connection) => {
|
||||
void connectChatRealtime(
|
||||
channelId,
|
||||
(item) => {
|
||||
if (cancelled) return
|
||||
setMessages((current) => {
|
||||
const next = mergeChatMessages(current, [item], guest)
|
||||
lastSeq = Math.max(lastSeq, maxChatSeq(next))
|
||||
return next
|
||||
})
|
||||
if (item.seq) {
|
||||
void socialApi.postNote(channelId, 'recv', item.seq).catch(() => undefined)
|
||||
}
|
||||
},
|
||||
(connected) => {
|
||||
realtime = connected
|
||||
if (!cancelled) setStatus(connected ? 'live' : 'polling')
|
||||
},
|
||||
(note) => {
|
||||
if (cancelled || note.guestId === guest) return
|
||||
if (note.what !== 'kp') return
|
||||
setTypingPeers((prev) => (prev.includes(note.guestId) ? prev : [...prev, note.guestId]))
|
||||
if (typingClear.current) clearTimeout(typingClear.current)
|
||||
typingClear.current = setTimeout(() => {
|
||||
setTypingPeers((prev) => prev.filter((id) => id !== note.guestId))
|
||||
}, 2800)
|
||||
},
|
||||
).then((connection) => {
|
||||
if (cancelled) connection?.disconnect()
|
||||
else stopWs = connection?.disconnect
|
||||
}).catch(() => { if (!cancelled) setStatus('polling') })
|
||||
@ -103,9 +153,15 @@ export function useSocialChat(channelId: string) {
|
||||
cancelled = true
|
||||
mounted.current = false
|
||||
clearInterval(timer)
|
||||
clearInterval(presenceTimer)
|
||||
if (typingClear.current) clearTimeout(typingClear.current)
|
||||
stopWs?.()
|
||||
}
|
||||
}, [channelId, guest, outboxKey, draftKey])
|
||||
}, [channelId, guest, nick, outboxKey, draftKey])
|
||||
|
||||
const mergeOne = useCallback((saved: SocialChatMessage) => {
|
||||
setMessages((current) => mergeChatMessages(current, [{ ...saved, guestId: saved.guestId || guest }], guest))
|
||||
}, [guest])
|
||||
|
||||
const deliver = useCallback(async (item: SocialChatMessage) => {
|
||||
if (lock.current) return false
|
||||
@ -113,12 +169,19 @@ export function useSocialChat(channelId: string) {
|
||||
setSending(true)
|
||||
setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'pending' as const } : m))
|
||||
try {
|
||||
const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId)
|
||||
const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId, {
|
||||
replyTo: item.replyTo,
|
||||
attachments: item.attachments,
|
||||
mentions: item.mentions,
|
||||
})
|
||||
if (!saved?.id) throw new Error('发送结果异常')
|
||||
const pending = readSocialLocal<SocialChatMessage[]>(outboxKey, [])
|
||||
if (Array.isArray(pending)) writeSocialLocal(outboxKey, pending.filter((message) => message.id !== item.id && (!item.clientId || message.clientId !== item.clientId)))
|
||||
if (!mounted.current || active.current !== channelId) return true
|
||||
setMessages((current) => mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest))
|
||||
setMessages((current) => {
|
||||
const next = mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest)
|
||||
return next
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
if (!mounted.current || active.current !== channelId) return false
|
||||
@ -134,15 +197,23 @@ export function useSocialChat(channelId: string) {
|
||||
}
|
||||
}, [channelId, guest, outboxKey])
|
||||
|
||||
const send = useCallback(async () => {
|
||||
const send = useCallback(async (opts?: {
|
||||
replyTo?: SocialChatReplyTo | null
|
||||
attachments?: SocialChatAttachment[]
|
||||
mentions?: string[]
|
||||
}) => {
|
||||
const text = draft.trim()
|
||||
if (!text || text.length > 2000 || lock.current) return false
|
||||
const atts = opts?.attachments || []
|
||||
if ((!text && !atts.length) || text.length > 2000 || lock.current) return false
|
||||
const clientId = createSocialRequestId()
|
||||
const mentions = opts?.mentions || Array.from(text.matchAll(/@([\w\u4e00-\u9fff-]{1,24})/g)).map((m) => m[1])
|
||||
const item: SocialChatMessage = {
|
||||
id: `local_${clientId}`, clientId, channelId, author: nick.trim().slice(0, 24) || '游民',
|
||||
text, at: new Date().toISOString(), guestId: guest, mine: true, delivery: 'pending',
|
||||
replyTo: opts?.replyTo || undefined,
|
||||
attachments: atts.length ? atts : undefined,
|
||||
mentions: mentions.length ? mentions : undefined,
|
||||
}
|
||||
// Save before clearing the input so navigating away cannot lose unsent text.
|
||||
const existing = readSocialLocal<SocialChatMessage[]>(outboxKey, [])
|
||||
if (!writeSocialLocal(outboxKey, [...(Array.isArray(existing) ? existing : []), { ...item, delivery: 'local' }].slice(-50))) {
|
||||
void Taro.showToast({ title: '本地保存失败,请保留输入后重试', icon: 'none' })
|
||||
@ -160,5 +231,86 @@ export function useSocialChat(channelId: string) {
|
||||
if (item) await deliver(item)
|
||||
}, [deliver, messages])
|
||||
|
||||
return { messages, draft, setDraft, nick, setNick, status, sending, send, retryLocal, refresh: () => refreshRef.current() }
|
||||
const editMessage = useCallback(async (msgId: string, text: string) => {
|
||||
try {
|
||||
mergeOne(await socialApi.editMessage(channelId, msgId, text))
|
||||
return true
|
||||
} catch {
|
||||
void Taro.showToast({ title: '编辑失败', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
}, [channelId, mergeOne])
|
||||
|
||||
const recallMessage = useCallback(async (msgId: string) => {
|
||||
try {
|
||||
mergeOne(await socialApi.recallMessage(channelId, msgId))
|
||||
return true
|
||||
} catch {
|
||||
void Taro.showToast({ title: '撤回失败', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
}, [channelId, mergeOne])
|
||||
|
||||
const reactMessage = useCallback(async (msgId: string, emoji: string) => {
|
||||
try {
|
||||
mergeOne(await socialApi.reactMessage(channelId, msgId, emoji))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}, [channelId, mergeOne])
|
||||
|
||||
const pinMessage = useCallback(async (msgId: string, pinned = true) => {
|
||||
try {
|
||||
mergeOne(await socialApi.pinMessage(channelId, msgId, pinned))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}, [channelId, mergeOne])
|
||||
|
||||
const upload = useCallback(
|
||||
(filePath: string, kind?: string, name?: string) => socialApi.upload(channelId, filePath, kind, name),
|
||||
[channelId],
|
||||
)
|
||||
|
||||
const reportMessage = useCallback(async (msgId: string, reason = '') => {
|
||||
try {
|
||||
await socialApi.reportMessage(channelId, msgId, reason)
|
||||
void Taro.showToast({ title: '已提交举报', icon: 'none' })
|
||||
return true
|
||||
} catch {
|
||||
void Taro.showToast({ title: '举报失败', icon: 'none' })
|
||||
return false
|
||||
}
|
||||
}, [channelId])
|
||||
|
||||
const notifyTyping = useCallback(() => {
|
||||
const now = Date.now()
|
||||
if (now - typingBeat.current < 1800) return
|
||||
typingBeat.current = now
|
||||
void socialApi.postNote(channelId, 'kp', 0).catch(() => undefined)
|
||||
}, [channelId])
|
||||
|
||||
return {
|
||||
messages,
|
||||
draft,
|
||||
setDraft,
|
||||
nick,
|
||||
setNick,
|
||||
status,
|
||||
sending,
|
||||
send,
|
||||
retryLocal,
|
||||
editMessage,
|
||||
recallMessage,
|
||||
reactMessage,
|
||||
pinMessage,
|
||||
reportMessage,
|
||||
upload,
|
||||
online,
|
||||
typingPeers,
|
||||
notifyTyping,
|
||||
refresh: () => refreshRef.current(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -159,6 +159,13 @@
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
.im-typing {
|
||||
flex: 0 0 auto;
|
||||
padding: 0.25rem 0.9rem;
|
||||
font-size: 0.7rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.im-anchor {
|
||||
height: 1PX;
|
||||
width: 100%;
|
||||
@ -219,3 +226,189 @@
|
||||
.soc-taro-root.im-root[data-theme] .im-input { min-width: 0; }
|
||||
.soc-taro-root.im-root[data-theme] .im-bubble.is-mine { background: var(--social-raised); border-color: var(--social-accent); }
|
||||
.soc-taro-root.im-root[data-theme='light'] .im-fail { color: #926000; }
|
||||
|
||||
.im-bubble.is-pinned {
|
||||
outline: 1PX solid rgba(245, 158, 11, 0.45);
|
||||
}
|
||||
.im-quote {
|
||||
margin-bottom: 0.35rem;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-left: 2PX solid #f59e0b;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 0 0.5rem 0.5rem 0;
|
||||
}
|
||||
.im-quote-a {
|
||||
display: block;
|
||||
font-size: 0.7rem;
|
||||
color: #f59e0b;
|
||||
}
|
||||
.im-quote-t {
|
||||
display: block;
|
||||
font-size: 0.72rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
.im-recalled {
|
||||
font-style: italic;
|
||||
color: #94a3b8;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.im-atts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
.im-att-image,
|
||||
.im-att-video {
|
||||
width: 100%;
|
||||
max-width: 16rem;
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
.im-att-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 2.75rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: #fbbf24;
|
||||
font-size: 0.85rem;
|
||||
border: 0;
|
||||
}
|
||||
.im-reactions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.3rem;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
.im-react-chip {
|
||||
padding: 0.15rem 0.45rem;
|
||||
border-radius: 999PX;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.im-react-chip.is-mine {
|
||||
outline: 1PX solid #f59e0b;
|
||||
}
|
||||
.im-pinned {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
padding: 0.35rem 0.75rem;
|
||||
}
|
||||
.im-pinned-item {
|
||||
text-align: left;
|
||||
min-height: 2.25rem;
|
||||
padding: 0.35rem 0.65rem;
|
||||
border-radius: 999PX;
|
||||
border: 1PX solid rgba(245, 158, 11, 0.35);
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
color: #f8fafc;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.im-chip-row,
|
||||
.im-pending {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.35rem 0.75rem;
|
||||
font-size: 0.75rem;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.im-chip-row button,
|
||||
.im-pending-item {
|
||||
min-height: 2.25rem;
|
||||
padding: 0.25rem 0.65rem;
|
||||
border: 0;
|
||||
border-radius: 999PX;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #e2e8f0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.im-composer-tools {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
padding: 0.25rem 0.75rem 0;
|
||||
}
|
||||
.im-tool {
|
||||
min-width: 2.75rem;
|
||||
min-height: 2.75rem;
|
||||
border: 0;
|
||||
border-radius: 0.85rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
font-size: 1.15rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.im-emoji-sheet {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-top: 1PX solid rgba(255, 255, 255, 0.06);
|
||||
background: #080c14;
|
||||
}
|
||||
.im-emoji-btn {
|
||||
min-width: 2.75rem;
|
||||
min-height: 2.75rem;
|
||||
border: 0;
|
||||
border-radius: 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
font-size: 1.25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.im-action-sheet {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
}
|
||||
.im-action-panel {
|
||||
width: 100%;
|
||||
max-width: 40rem;
|
||||
padding: 0.85rem 0.85rem calc(0.85rem + env(safe-area-inset-bottom, 0PX));
|
||||
border-radius: 1.1rem 1.1rem 0 0;
|
||||
background: #101826;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.im-action-title {
|
||||
text-align: center;
|
||||
font-size: 0.8rem;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.im-quick-react {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.im-action-btn {
|
||||
min-height: 2.85rem;
|
||||
border: 0;
|
||||
border-radius: 0.85rem;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: #f8fafc;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.im-action-btn.is-danger {
|
||||
color: #f87171;
|
||||
}
|
||||
.im-action-btn.is-cancel {
|
||||
margin-top: 0.25rem;
|
||||
background: transparent;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
@ -1,14 +1,19 @@
|
||||
import { useSocialPage } from '@/hooks/useSocialPage'
|
||||
import { useSocialContent } from '@/hooks/useSocialContent'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Input, ScrollView, Text } from '@tarojs/components'
|
||||
import { Image, Input, ScrollView, Text, Video } from '@tarojs/components'
|
||||
import Taro from '@tarojs/taro'
|
||||
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||
import { H5Box } from '@/components/H5Box'
|
||||
import { useSocialChat } from '@/hooks/useSocialChat'
|
||||
import { usePageShare } from '@/utils/pageShare'
|
||||
import { usePageTrack } from '@/hooks/usePageTrack'
|
||||
import type { SocialChatMessage } from '@/services/socialApi'
|
||||
import {
|
||||
getSocialGuestId,
|
||||
type SocialChatAttachment,
|
||||
type SocialChatMessage,
|
||||
type SocialChatReplyTo,
|
||||
} from '@/services/socialApi'
|
||||
import { H5El } from '../_components/H5El'
|
||||
import { goSocialPage } from '@/utils/socialNavigation'
|
||||
import '@/styles/social-next/entry'
|
||||
@ -17,6 +22,8 @@ import './index.scss'
|
||||
|
||||
/** 唯一总频道 */
|
||||
const LOBBY = 'general'
|
||||
const EMOJIS = ['👋', '☕', '🌍', '✨', '🙌', '❤️', '💻', '🌴', '🚀', '🌙', '👍', '😂', '🔥', '💪', '✅']
|
||||
const QUICK_REACT = ['👍', '❤️', '😂', '😮', '🔥', '👏']
|
||||
|
||||
function statusLabel(s: string) {
|
||||
if (s === 'live') return '实时'
|
||||
@ -32,33 +39,98 @@ function formatTime(iso?: string) {
|
||||
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function Atts({ items }: { items: SocialChatAttachment[] }) {
|
||||
return (
|
||||
<H5Box className='im-atts'>
|
||||
{items.map((att) => {
|
||||
if (att.kind === 'image') {
|
||||
return (
|
||||
<Image
|
||||
key={att.id}
|
||||
className='im-att-image'
|
||||
src={att.url}
|
||||
mode='widthFix'
|
||||
onClick={() => void Taro.previewImage({ urls: [att.url], current: att.url })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (att.kind === 'video') {
|
||||
return <Video key={att.id} className='im-att-video' src={att.url} controls showCenterPlayBtn />
|
||||
}
|
||||
return (
|
||||
<H5El
|
||||
key={att.id}
|
||||
as='button'
|
||||
className='im-att-file'
|
||||
onClick={() => {
|
||||
void Taro.setClipboardData({ data: att.url })
|
||||
void Taro.showToast({ title: '已复制文件链接', icon: 'none' })
|
||||
}}
|
||||
>
|
||||
<Text>📎 {att.name}</Text>
|
||||
</H5El>
|
||||
)
|
||||
})}
|
||||
</H5Box>
|
||||
)
|
||||
}
|
||||
|
||||
function Bubble({
|
||||
m,
|
||||
onRetry,
|
||||
onOpen,
|
||||
}: {
|
||||
m: SocialChatMessage
|
||||
onRetry: (id: string) => void
|
||||
onOpen: (m: SocialChatMessage) => void
|
||||
}) {
|
||||
return (
|
||||
<H5Box
|
||||
className={`im-bubble${m.mine ? ' is-mine' : ''}${
|
||||
m.delivery === 'local' ? ' is-fail' : ''
|
||||
}`}
|
||||
}${m.pinned ? ' is-pinned' : ''}`}
|
||||
onClick={() => {
|
||||
if (m.delivery === 'local') onRetry(m.id)
|
||||
else if (!m.recalled) onOpen(m)
|
||||
}}
|
||||
onLongPress={() => {
|
||||
if (!m.recalled && m.delivery !== 'local') onOpen(m)
|
||||
}}
|
||||
>
|
||||
{!m.mine ? (
|
||||
<Text className='im-author'>{m.author || '游民'}</Text>
|
||||
{!m.mine ? <Text className='im-author'>{m.author || '游民'}</Text> : null}
|
||||
{m.replyTo ? (
|
||||
<H5Box className='im-quote'>
|
||||
<Text className='im-quote-a'>{m.replyTo.author}</Text>
|
||||
<Text className='im-quote-t'>{m.replyTo.text.slice(0, 80)}</Text>
|
||||
</H5Box>
|
||||
) : null}
|
||||
{m.recalled ? (
|
||||
<Text className='im-recalled'>消息已撤回</Text>
|
||||
) : (
|
||||
<>
|
||||
{m.text ? <Text className='im-text'>{m.text}</Text> : null}
|
||||
{m.attachments?.length ? <Atts items={m.attachments} /> : null}
|
||||
</>
|
||||
)}
|
||||
{m.reactions && Object.keys(m.reactions).length ? (
|
||||
<H5Box className='im-reactions'>
|
||||
{Object.entries(m.reactions).map(([emoji, guests]) => (
|
||||
<Text
|
||||
key={emoji}
|
||||
className={`im-react-chip${guests.includes(getSocialGuestId()) ? ' is-mine' : ''}`}
|
||||
>
|
||||
{emoji} {guests.length}
|
||||
</Text>
|
||||
))}
|
||||
</H5Box>
|
||||
) : null}
|
||||
<Text className='im-text'>{m.text}</Text>
|
||||
<H5Box className='im-meta'>
|
||||
<Text>{formatTime(m.at)}</Text>
|
||||
{m.editedAt ? <Text>已编辑</Text> : null}
|
||||
{m.pinned ? <Text>📌</Text> : null}
|
||||
{m.delivery === 'pending' ? <Text>发送中</Text> : null}
|
||||
{m.delivery === 'local' ? (
|
||||
<Text className='im-fail'>未送达 · 点重试</Text>
|
||||
) : null}
|
||||
{m.mine && m.delivery === 'sent' ? <Text>已送达</Text> : null}
|
||||
{m.delivery === 'local' ? <Text className='im-fail'>未送达 · 点重试</Text> : null}
|
||||
{m.mine && m.delivery === 'sent' && !m.recalled ? <Text>已送达</Text> : null}
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
)
|
||||
@ -79,6 +151,15 @@ function SocialChatLobby() {
|
||||
sending,
|
||||
send,
|
||||
retryLocal,
|
||||
editMessage,
|
||||
recallMessage,
|
||||
reactMessage,
|
||||
pinMessage,
|
||||
reportMessage,
|
||||
upload,
|
||||
online,
|
||||
typingPeers,
|
||||
notifyTyping,
|
||||
refresh,
|
||||
} = useSocialChat(LOBBY)
|
||||
|
||||
@ -86,7 +167,13 @@ function SocialChatLobby() {
|
||||
const nearBottom = useRef(true)
|
||||
const [unread, setUnread] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
const [emojiOpen, setEmojiOpen] = useState(false)
|
||||
const [reply, setReply] = useState<SocialChatReplyTo | null>(null)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [pendingAtts, setPendingAtts] = useState<SocialChatAttachment[]>([])
|
||||
const [sheetMsg, setSheetMsg] = useState<SocialChatMessage | null>(null)
|
||||
const lastId = messages[messages.length - 1]?.id
|
||||
const pinned = messages.filter((m) => m.pinned && !m.recalled).slice(0, 3)
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
@ -101,12 +188,15 @@ function SocialChatLobby() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastId) return
|
||||
if (!nearBottom.current && !messages[messages.length - 1]?.mine) { setUnread(true); return }
|
||||
if (!nearBottom.current && !messages[messages.length - 1]?.mine) {
|
||||
setUnread(true)
|
||||
return
|
||||
}
|
||||
const t = setTimeout(() => setScrollInto(`msg_${lastId}`), 48)
|
||||
return () => clearTimeout(t)
|
||||
}, [lastId, messages.length])
|
||||
|
||||
const canSend = Boolean(draft.trim()) && !sending
|
||||
const canSend = (Boolean(draft.trim()) || pendingAtts.length > 0 || Boolean(editingId)) && !sending
|
||||
|
||||
const onSend = async () => {
|
||||
if (!canSend) return
|
||||
@ -115,22 +205,80 @@ function SocialChatLobby() {
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const ok = await send()
|
||||
if (ok) setScrollInto('chat_bottom')
|
||||
if (editingId) {
|
||||
const ok = await editMessage(editingId, draft.trim())
|
||||
if (ok) {
|
||||
setEditingId(null)
|
||||
setDraft('')
|
||||
}
|
||||
return
|
||||
}
|
||||
const ok = await send({ replyTo: reply, attachments: pendingAtts })
|
||||
if (ok) {
|
||||
setReply(null)
|
||||
setPendingAtts([])
|
||||
setEmojiOpen(false)
|
||||
setScrollInto('chat_bottom')
|
||||
}
|
||||
}
|
||||
|
||||
const pickMedia = async (kind: 'image' | 'video' | 'file') => {
|
||||
try {
|
||||
if (kind === 'image' || kind === 'video') {
|
||||
const res = await Taro.chooseMedia({
|
||||
count: 3,
|
||||
mediaType: kind === 'image' ? ['image'] : ['video'],
|
||||
sourceType: ['album', 'camera'],
|
||||
})
|
||||
for (const file of res.tempFiles.slice(0, 3)) {
|
||||
const att = await upload(file.tempFilePath, kind, file.tempFilePath.split('/').pop())
|
||||
setPendingAtts((prev) => [...prev, att].slice(-8))
|
||||
}
|
||||
return
|
||||
}
|
||||
const res = await Taro.chooseMessageFile({ count: 1, type: 'file' })
|
||||
const f = res.tempFiles[0]
|
||||
if (!f) return
|
||||
const att = await upload(f.path, 'file', f.name)
|
||||
setPendingAtts((prev) => [...prev, att].slice(-8))
|
||||
} catch {
|
||||
void Taro.showToast({ title: '选择或上传失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
const openActions = (m: SocialChatMessage) => {
|
||||
setSheetMsg(m)
|
||||
}
|
||||
|
||||
return (
|
||||
<H5Box className='soc-taro-root social-root im-root social-weapp' data-theme={theme} style={pageStyle}>
|
||||
<H5Box className='im-header'>
|
||||
<H5El as='button' className='im-back' onClick={() => goSocialPage('/pages/social/index')}>← 社区</H5El>
|
||||
<H5El as='button' className='im-back' onClick={() => goSocialPage('/pages/social/index')}>
|
||||
← 社区
|
||||
</H5El>
|
||||
<Text className='im-header-title'>{pages.chat?.title || '游民大厅'}</Text>
|
||||
<H5El as='button' className='im-reconnect' disabled={refreshing} onClick={async () => {
|
||||
setRefreshing(true); try { await refresh() } finally { setRefreshing(false) }
|
||||
}}>{refreshing ? '连接中…' : '刷新'}</H5El>
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-reconnect'
|
||||
disabled={refreshing}
|
||||
onClick={async () => {
|
||||
setRefreshing(true)
|
||||
try {
|
||||
await refresh()
|
||||
} finally {
|
||||
setRefreshing(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{refreshing ? '连接中…' : '刷新'}
|
||||
</H5El>
|
||||
</H5Box>
|
||||
<H5Box className='im-status-row'>
|
||||
<H5Box className={`im-pill is-${status}`}>
|
||||
<Text>{statusLabel(status)}</Text>
|
||||
<Text>
|
||||
{statusLabel(status)}
|
||||
{online > 0 ? ` · ${online}在线` : ''}
|
||||
</Text>
|
||||
</H5Box>
|
||||
<Input
|
||||
className='im-nick'
|
||||
@ -150,6 +298,21 @@ function SocialChatLobby() {
|
||||
/>
|
||||
</H5Box>
|
||||
|
||||
{pinned.length ? (
|
||||
<H5Box className='im-pinned'>
|
||||
{pinned.map((m) => (
|
||||
<H5El
|
||||
key={m.id}
|
||||
as='button'
|
||||
className='im-pinned-item'
|
||||
onClick={() => setScrollInto(`msg_${m.id}`)}
|
||||
>
|
||||
<Text>📌 {m.author}: {(m.text || '附件').slice(0, 28)}</Text>
|
||||
</H5El>
|
||||
))}
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
<ScrollView
|
||||
scrollY
|
||||
className='im-thread'
|
||||
@ -159,12 +322,19 @@ function SocialChatLobby() {
|
||||
showScrollbar={false}
|
||||
onScroll={(event) => {
|
||||
const detail = event.detail as { scrollHeight: number; scrollTop: number }
|
||||
// Obtain the actual viewport so incoming messages do not pull users away from history.
|
||||
Taro.createSelectorQuery().select('.im-thread').boundingClientRect((rect: any) => {
|
||||
if (rect?.height) nearBottom.current = detail.scrollHeight - detail.scrollTop - rect.height < 100
|
||||
}).exec()
|
||||
Taro.createSelectorQuery()
|
||||
.select('.im-thread')
|
||||
.boundingClientRect((rect: any) => {
|
||||
if (rect?.height)
|
||||
nearBottom.current =
|
||||
detail.scrollHeight - detail.scrollTop - rect.height < 100
|
||||
})
|
||||
.exec()
|
||||
}}
|
||||
onScrollToLower={() => {
|
||||
nearBottom.current = true
|
||||
setUnread(false)
|
||||
}}
|
||||
onScrollToLower={() => { nearBottom.current = true; setUnread(false) }}
|
||||
>
|
||||
{messages.length === 0 ? (
|
||||
<H5Box className='im-empty'>
|
||||
@ -181,22 +351,115 @@ function SocialChatLobby() {
|
||||
<H5Box className='im-list'>
|
||||
{messages.map((m) => (
|
||||
<H5Box key={m.id} id={`msg_${m.id}`} className='im-row-wrap'>
|
||||
<Bubble m={m} onRetry={(id) => void retryLocal(id)} />
|
||||
<Bubble
|
||||
m={m}
|
||||
onRetry={(id) => void retryLocal(id)}
|
||||
onOpen={openActions}
|
||||
/>
|
||||
</H5Box>
|
||||
))}
|
||||
<H5Box id='chat_bottom' className='im-anchor' />
|
||||
</H5Box>
|
||||
)}
|
||||
</ScrollView>
|
||||
{unread ? <H5El as='button' className='im-new-messages' onClick={() => {
|
||||
nearBottom.current = true; setUnread(false); setScrollInto('chat_bottom')
|
||||
}}>有新消息 · 回到最新 ↓</H5El> : null}
|
||||
{unread ? (
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-new-messages'
|
||||
onClick={() => {
|
||||
nearBottom.current = true
|
||||
setUnread(false)
|
||||
setScrollInto('chat_bottom')
|
||||
}}
|
||||
>
|
||||
有新消息 · 回到最新 ↓
|
||||
</H5El>
|
||||
) : null}
|
||||
{typingPeers.length ? (
|
||||
<H5Box className='im-typing'>
|
||||
<Text>有人正在输入…</Text>
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
{editingId ? (
|
||||
<H5Box className='im-chip-row'>
|
||||
<Text>编辑消息</Text>
|
||||
<H5El
|
||||
as='button'
|
||||
onClick={() => {
|
||||
setEditingId(null)
|
||||
setDraft('')
|
||||
}}
|
||||
>
|
||||
取消
|
||||
</H5El>
|
||||
</H5Box>
|
||||
) : null}
|
||||
{reply && !editingId ? (
|
||||
<H5Box className='im-chip-row'>
|
||||
<Text>
|
||||
回复 {reply.author}:{reply.text.slice(0, 36)}
|
||||
</Text>
|
||||
<H5El as='button' onClick={() => setReply(null)}>
|
||||
取消
|
||||
</H5El>
|
||||
</H5Box>
|
||||
) : null}
|
||||
{pendingAtts.length ? (
|
||||
<H5Box className='im-pending'>
|
||||
{pendingAtts.map((att) => (
|
||||
<H5El
|
||||
key={att.id}
|
||||
as='button'
|
||||
className='im-pending-item'
|
||||
onClick={() => setPendingAtts((p) => p.filter((x) => x.id !== att.id))}
|
||||
>
|
||||
<Text>
|
||||
{att.kind === 'image' ? '🖼' : att.kind === 'video' ? '🎬' : '📎'} {att.name} ×
|
||||
</Text>
|
||||
</H5El>
|
||||
))}
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
{emojiOpen ? (
|
||||
<H5Box className='im-emoji-sheet'>
|
||||
{EMOJIS.map((emoji) => (
|
||||
<H5El
|
||||
key={emoji}
|
||||
as='button'
|
||||
className='im-emoji-btn'
|
||||
onClick={() => {
|
||||
setDraft((d) => (d + emoji).slice(0, 2000))
|
||||
setEmojiOpen(false)
|
||||
}}
|
||||
>
|
||||
<Text>{emoji}</Text>
|
||||
</H5El>
|
||||
))}
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
<H5Box className='im-composer-tools'>
|
||||
<H5El as='button' className='im-tool' onClick={() => setEmojiOpen((v) => !v)}>
|
||||
<Text>😀</Text>
|
||||
</H5El>
|
||||
<H5El as='button' className='im-tool' onClick={() => void pickMedia('image')}>
|
||||
<Text>🖼</Text>
|
||||
</H5El>
|
||||
<H5El as='button' className='im-tool' onClick={() => void pickMedia('video')}>
|
||||
<Text>🎬</Text>
|
||||
</H5El>
|
||||
<H5El as='button' className='im-tool' onClick={() => void pickMedia('file')}>
|
||||
<Text>📎</Text>
|
||||
</H5El>
|
||||
</H5Box>
|
||||
|
||||
<H5Box className='im-composer'>
|
||||
<Input
|
||||
className='im-input'
|
||||
value={draft}
|
||||
placeholder='说点什么…'
|
||||
placeholder='说点什么… @昵称'
|
||||
confirmType='send'
|
||||
maxlength={2000}
|
||||
adjustPosition
|
||||
@ -204,18 +467,136 @@ function SocialChatLobby() {
|
||||
onFocus={() => {
|
||||
setTimeout(() => setScrollInto('chat_bottom'), 120)
|
||||
}}
|
||||
onInput={(e) => setDraft(e.detail.value)}
|
||||
onInput={(e) => {
|
||||
setDraft(e.detail.value)
|
||||
notifyTyping()
|
||||
}}
|
||||
onConfirm={() => void onSend()}
|
||||
/>
|
||||
<H5El as='button' disabled={!canSend} aria-label='发送消息'
|
||||
className={`im-send${canSend ? ' is-on' : ''}${
|
||||
sending ? ' is-busy' : ''
|
||||
}`}
|
||||
<H5El
|
||||
as='button'
|
||||
disabled={!canSend}
|
||||
aria-label='发送消息'
|
||||
className={`im-send${canSend ? ' is-on' : ''}${sending ? ' is-busy' : ''}`}
|
||||
onClick={() => void onSend()}
|
||||
>
|
||||
<Text>{sending ? '…' : '发送'}</Text>
|
||||
<Text>{sending ? '…' : editingId ? '保存' : '发送'}</Text>
|
||||
</H5El>
|
||||
</H5Box>
|
||||
|
||||
{sheetMsg ? (
|
||||
<H5Box className='im-action-sheet' onClick={() => setSheetMsg(null)}>
|
||||
<H5Box
|
||||
className='im-action-panel'
|
||||
onClick={() => {
|
||||
/* keep sheet open when tapping panel */
|
||||
}}
|
||||
>
|
||||
<Text className='im-action-title'>消息操作</Text>
|
||||
<H5Box className='im-quick-react'>
|
||||
{QUICK_REACT.map((emoji) => (
|
||||
<H5El
|
||||
key={emoji}
|
||||
as='button'
|
||||
className='im-emoji-btn'
|
||||
onClick={() => {
|
||||
void reactMessage(sheetMsg.id, emoji)
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>{emoji}</Text>
|
||||
</H5El>
|
||||
))}
|
||||
</H5Box>
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
setReply({
|
||||
id: sheetMsg.id,
|
||||
author: sheetMsg.author,
|
||||
text: sheetMsg.text || sheetMsg.attachments?.[0]?.name || '',
|
||||
seq: sheetMsg.seq,
|
||||
})
|
||||
setEditingId(null)
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>回复</Text>
|
||||
</H5El>
|
||||
{sheetMsg.mine ? (
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
setEditingId(sheetMsg.id)
|
||||
setDraft(sheetMsg.text)
|
||||
setReply(null)
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>编辑</Text>
|
||||
</H5El>
|
||||
) : null}
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
void pinMessage(sheetMsg.id, !sheetMsg.pinned)
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>{sheetMsg.pinned ? '取消置顶' : '置顶'}</Text>
|
||||
</H5El>
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
void Taro.setClipboardData({ data: sheetMsg.text || '' })
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>复制</Text>
|
||||
</H5El>
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
setDraft(`转发 ${sheetMsg.author}:\n${sheetMsg.text}`.slice(0, 2000))
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>转发</Text>
|
||||
</H5El>
|
||||
{sheetMsg.mine ? (
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn is-danger'
|
||||
onClick={() => {
|
||||
void recallMessage(sheetMsg.id)
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>撤回</Text>
|
||||
</H5El>
|
||||
) : (
|
||||
<H5El
|
||||
as='button'
|
||||
className='im-action-btn'
|
||||
onClick={() => {
|
||||
void reportMessage(sheetMsg.id, 'spam')
|
||||
setSheetMsg(null)
|
||||
}}
|
||||
>
|
||||
<Text>举报</Text>
|
||||
</H5El>
|
||||
)}
|
||||
<H5El as='button' className='im-action-btn is-cancel' onClick={() => setSheetMsg(null)}>
|
||||
<Text>取消</Text>
|
||||
</H5El>
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
) : null}
|
||||
</H5Box>
|
||||
)
|
||||
}
|
||||
|
||||
@ -3,5 +3,97 @@
|
||||
|
||||
/* 页面级微调:主体视觉在 social-next/weapp-bridge */
|
||||
.soc-taro-root.social-weapp .social-mobile-dock {
|
||||
padding-bottom: calc(8PX + env(safe-area-inset-bottom, 0PX));
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
border-radius: 0;
|
||||
padding: 0.375rem 0.5rem calc(0.5rem + env(safe-area-inset-bottom, 0PX));
|
||||
border: none;
|
||||
border-top: 1PX solid rgba(255, 255, 255, 0.08);
|
||||
box-shadow: 0 -0.5rem 1.75rem rgba(0, 0, 0, 0.14);
|
||||
}
|
||||
|
||||
.soc-taro-root.social-weapp .social-mobile-dock a[aria-current='page'] {
|
||||
color: #f59e0b;
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer.social-home-footer {
|
||||
padding: 0.5rem 0 calc(5.5rem + env(safe-area-inset-bottom, 0PX));
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-grid-rings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.875rem;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-brand {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-brand p {
|
||||
margin: 0.5rem auto 0;
|
||||
max-width: 16rem;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-links h4 {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-links a,
|
||||
.soc-taro-root .footer-links .social-footer-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.5rem;
|
||||
padding: 0 1rem;
|
||||
border-radius: 999px;
|
||||
border: 1PX solid rgba(255, 255, 255, 0.1);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.soc-taro-root .footer-bottom {
|
||||
text-align: center;
|
||||
padding: 0.5rem 0 0.25rem;
|
||||
border: none;
|
||||
font-size: 0.6875rem;
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.soc-taro-root .connection-invite {
|
||||
margin: 0.75rem 0.875rem 0.5rem;
|
||||
padding: 1.25rem 1.125rem;
|
||||
border-radius: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.875rem;
|
||||
}
|
||||
|
||||
.soc-taro-root .connection-invite-orbit {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.soc-taro-root .connection-invite .connection-join,
|
||||
.soc-taro-root .connection-invite .btn {
|
||||
width: 100%;
|
||||
min-height: 3rem;
|
||||
margin: 0;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@ -76,10 +76,11 @@ function SocialHome() {
|
||||
const [creation, setCreation] = useState<{ item: SocialEbook | SocialVideo; kind: 'ebook' | 'video' } | null>(null)
|
||||
const { copy, roster, meetups, gigs, ebooks, videos, promoUrl, hiddenSections, featureOn, sectionOn } =
|
||||
useSocialContent()
|
||||
const datePreview = useMemo(
|
||||
() => roster.filter((m) => m.online).slice(0, 3),
|
||||
[roster],
|
||||
)
|
||||
const datePreview = useMemo(() => {
|
||||
const women = roster.filter((m) => m.gender === 'f')
|
||||
const rest = roster.filter((m) => m.gender !== 'f' && m.online)
|
||||
return [...women, ...rest].slice(0, 3)
|
||||
}, [roster])
|
||||
const cities = SOCIAL_CITIES.filter((c) => c.hot).slice(0, 8)
|
||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||
const rootStyle = useMemo(
|
||||
@ -655,14 +656,14 @@ function SocialHome() {
|
||||
) : null}
|
||||
</H5El>
|
||||
|
||||
<H5El as='footer' className='footer'>
|
||||
<H5El as='footer' className='footer social-home-footer'>
|
||||
<H5El className='container'>
|
||||
<H5El className='footer-grid footer-grid-rings'>
|
||||
<H5El className='footer-brand'>
|
||||
<H5El as='strong'>nomadro · 游民社区</H5El>
|
||||
<H5El as='p'>认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事</H5El>
|
||||
</H5El>
|
||||
<H5El className='footer-links'>
|
||||
<H5El className='footer-links footer-links-primary'>
|
||||
<H5El as='h4'>认识人</H5El>
|
||||
<H5El as='a' href='#people' onClick={() => goPage('/pages/social/people/index')}>
|
||||
想见的人
|
||||
@ -670,28 +671,12 @@ function SocialHome() {
|
||||
<H5El as='a' href='#date' onClick={() => goPage('/pages/social/date/index')}>
|
||||
认识一下
|
||||
</H5El>
|
||||
<H5El as='a' href='#chat' onClick={() => goPage('/pages/social/chat/index')}>
|
||||
大家聊天
|
||||
</H5El>
|
||||
</H5El>
|
||||
<H5El className='footer-links'>
|
||||
<H5El as='h4'>见面 · 做事</H5El>
|
||||
<H5El
|
||||
as='a'
|
||||
href='#cities'
|
||||
onClick={() => goPage('/pages/social/people/index?mode=cafe')}
|
||||
as='button'
|
||||
className='social-footer-link'
|
||||
onClick={() => setJoinOpen(true)}
|
||||
>
|
||||
找城市见面
|
||||
</H5El>
|
||||
<H5El
|
||||
as='a'
|
||||
href='#team'
|
||||
onClick={() => goPage('/pages/social/team/index')}
|
||||
>
|
||||
找搭子做事
|
||||
</H5El>
|
||||
<H5El as='a' href='#home' onClick={() => goPage('/pages/home/index')}>
|
||||
门户首页
|
||||
加入社区
|
||||
</H5El>
|
||||
</H5El>
|
||||
</H5El>
|
||||
|
||||
@ -43,8 +43,8 @@ function joinMiro(room: string, name: string) {
|
||||
name,
|
||||
notify: '0',
|
||||
chat: '0',
|
||||
audio: '0',
|
||||
video: '0',
|
||||
audio: '1',
|
||||
video: '1',
|
||||
}
|
||||
const query = Object.entries(params).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
|
||||
return `${MIROTALK_URL.replace(/\/$/, '')}/join?${query}`
|
||||
|
||||
@ -17,9 +17,12 @@ export function createSocialRequestId(): string {
|
||||
return `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`
|
||||
}
|
||||
|
||||
/** IM SoT on US (.com); .cn kept as weapp 合法域名 fallback only. */
|
||||
const SOCIAL_BASES = Array.from(
|
||||
new Set(
|
||||
[
|
||||
'https://nomadro.com',
|
||||
'https://api.nomadro.com',
|
||||
API_BASE.replace(/\/$/, ''),
|
||||
'https://api.nomadro.cn',
|
||||
WEB_BASE.replace(/\/$/, ''),
|
||||
@ -61,7 +64,7 @@ function errText(e: unknown, fallback: string) {
|
||||
|
||||
async function req<T>(
|
||||
path: string,
|
||||
init?: { method?: 'GET' | 'POST' | 'PUT'; data?: Record<string, unknown> },
|
||||
init?: { method?: 'GET' | 'POST' | 'PUT' | 'PATCH'; data?: Record<string, unknown> },
|
||||
): Promise<T> {
|
||||
const gid = guestId()
|
||||
const qs = path.includes('?') ? `&guest=${encodeURIComponent(gid)}` : `?guest=${encodeURIComponent(gid)}`
|
||||
@ -134,16 +137,41 @@ export type LiveJoinResult = {
|
||||
engine: string
|
||||
}
|
||||
|
||||
export type SocialChatAttachment = {
|
||||
id: string
|
||||
kind: 'image' | 'video' | 'file' | 'audio'
|
||||
url: string
|
||||
name: string
|
||||
mime: string
|
||||
size: number
|
||||
}
|
||||
|
||||
export type SocialChatReplyTo = {
|
||||
id: string
|
||||
author: string
|
||||
text: string
|
||||
seq?: number | null
|
||||
}
|
||||
|
||||
export type SocialChatMessage = {
|
||||
id: string
|
||||
channelId: string
|
||||
author: string
|
||||
text: string
|
||||
at: string
|
||||
/** Tinode-like monotonic seq per channel */
|
||||
seq?: number
|
||||
guestId?: string
|
||||
mine?: boolean
|
||||
delivery?: 'sent' | 'local' | 'pending'
|
||||
clientId?: string
|
||||
replyTo?: SocialChatReplyTo
|
||||
attachments?: SocialChatAttachment[]
|
||||
reactions?: Record<string, string[]>
|
||||
mentions?: string[]
|
||||
editedAt?: string
|
||||
recalled?: boolean
|
||||
pinned?: boolean
|
||||
}
|
||||
|
||||
export type SocialRealtimeToken = {
|
||||
@ -210,15 +238,121 @@ export const socialApi = {
|
||||
`/realtime/token?channel_id=${encodeURIComponent(channelId)}`,
|
||||
),
|
||||
|
||||
listMessages: (channelId: string) =>
|
||||
req<{ items: SocialChatMessage[] }>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages`,
|
||||
),
|
||||
listMessages: (
|
||||
channelId: string,
|
||||
opts?: { limit?: number; since?: number; before?: number; q?: string },
|
||||
) => {
|
||||
const q = new URLSearchParams()
|
||||
if (opts?.limit) q.set('limit', String(opts.limit))
|
||||
if (opts?.since != null) q.set('since', String(opts.since))
|
||||
if (opts?.before != null) q.set('before', String(opts.before))
|
||||
if (opts?.q) q.set('q', opts.q)
|
||||
const qs = q.toString()
|
||||
return req<{ items: SocialChatMessage[]; seq?: number }>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ''}`,
|
||||
)
|
||||
},
|
||||
|
||||
sendMessage: (channelId: string, author: string, text: string, clientId?: string) =>
|
||||
sendMessage: (
|
||||
channelId: string,
|
||||
author: string,
|
||||
text: string,
|
||||
clientId?: string,
|
||||
extra?: {
|
||||
replyTo?: SocialChatReplyTo | null
|
||||
attachments?: SocialChatAttachment[]
|
||||
mentions?: string[]
|
||||
},
|
||||
) =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages`,
|
||||
{ method: 'POST', data: { author, text, ...(clientId ? { clientId } : {}) } },
|
||||
{
|
||||
method: 'POST',
|
||||
data: {
|
||||
author,
|
||||
text,
|
||||
...(clientId ? { clientId } : {}),
|
||||
...(extra?.replyTo ? { replyTo: extra.replyTo } : {}),
|
||||
...(extra?.attachments?.length ? { attachments: extra.attachments } : {}),
|
||||
...(extra?.mentions?.length ? { mentions: extra.mentions } : {}),
|
||||
},
|
||||
},
|
||||
),
|
||||
|
||||
editMessage: (channelId: string, msgId: string, text: string) =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}`,
|
||||
{ method: 'PATCH', data: { text } },
|
||||
),
|
||||
|
||||
recallMessage: (channelId: string, msgId: string) =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/recall`,
|
||||
{ method: 'POST', data: {} },
|
||||
),
|
||||
|
||||
reactMessage: (channelId: string, msgId: string, emoji: string) =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/react`,
|
||||
{ method: 'POST', data: { emoji } },
|
||||
),
|
||||
|
||||
pinMessage: (channelId: string, msgId: string, pinned = true) =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/pin`,
|
||||
{ method: 'POST', data: { pinned } },
|
||||
),
|
||||
|
||||
reportMessage: (channelId: string, msgId: string, reason = '') =>
|
||||
req<SocialChatMessage>(
|
||||
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/report`,
|
||||
{ method: 'POST', data: { reason } },
|
||||
),
|
||||
|
||||
presence: (channelId: string, nick?: string) =>
|
||||
req<{ channelId: string; online: number; peers: Array<{ guestId: string; nick: string }> }>(
|
||||
`/channels/${encodeURIComponent(channelId)}/presence`,
|
||||
{ method: 'POST', data: { nick: nick || '游民' } },
|
||||
),
|
||||
|
||||
upload: (channelId: string, filePath: string, kind = 'file', name = 'file') =>
|
||||
new Promise<SocialChatAttachment>((resolve, reject) => {
|
||||
const gid = guestId()
|
||||
const bases = preferredBase
|
||||
? [preferredBase, ...SOCIAL_BASES.filter((b) => b !== preferredBase)]
|
||||
: SOCIAL_BASES
|
||||
const tryAt = (i: number) => {
|
||||
if (i >= bases.length) {
|
||||
reject(new Error('upload failed'))
|
||||
return
|
||||
}
|
||||
Taro.uploadFile({
|
||||
url: `${bases[i]}/api/social/v1/channels/${encodeURIComponent(channelId)}/upload?guest=${encodeURIComponent(gid)}`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData: { kind },
|
||||
header: { 'X-Social-Guest-Id': gid },
|
||||
success: (res) => {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
try {
|
||||
const data = JSON.parse(String(res.data || '{}')) as SocialChatAttachment
|
||||
if (bases[i]) preferredBase = bases[i]
|
||||
resolve({ ...data, name: data.name || name })
|
||||
} catch (e) {
|
||||
reject(e)
|
||||
}
|
||||
} else tryAt(i + 1)
|
||||
},
|
||||
fail: () => tryAt(i + 1),
|
||||
})
|
||||
}
|
||||
tryAt(0)
|
||||
}),
|
||||
|
||||
postNote: (channelId: string, what: 'recv' | 'read' | 'kp', seq = 0) =>
|
||||
req<{ ok?: boolean; what: string; seq?: number }>(
|
||||
`/channels/${encodeURIComponent(channelId)}/notes`,
|
||||
{ method: 'POST', data: { what, seq } },
|
||||
),
|
||||
|
||||
applyGig: async (gigId: string, payload: GigApplyPayload) => {
|
||||
|
||||
@ -1,5 +1,14 @@
|
||||
import type { SocialChatMessage } from './socialApi'
|
||||
|
||||
export function maxChatSeq(items: SocialChatMessage[]): number {
|
||||
let m = 0
|
||||
for (const item of items) {
|
||||
const s = Number(item.seq || 0)
|
||||
if (s > m) m = s
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
export function mergeChatMessages(current: SocialChatMessage[], incoming: SocialChatMessage[], guest: string): SocialChatMessage[] {
|
||||
const byId = new Map(current.map((item) => [item.id, item]))
|
||||
for (const item of incoming) {
|
||||
@ -11,5 +20,12 @@ export function mergeChatMessages(current: SocialChatMessage[], incoming: Social
|
||||
}
|
||||
byId.set(item.id, { ...item, mine: item.guestId === guest, delivery: 'sent' })
|
||||
}
|
||||
return Array.from(byId.values()).sort((a, b) => a.at.localeCompare(b.at)).slice(-300)
|
||||
return Array.from(byId.values())
|
||||
.sort((a, b) => {
|
||||
const sa = Number(a.seq || 0)
|
||||
const sb = Number(b.seq || 0)
|
||||
if (sa && sb && sa !== sb) return sa - sb
|
||||
return String(a.at).localeCompare(String(b.at))
|
||||
})
|
||||
.slice(-300)
|
||||
}
|
||||
|
||||
@ -3,8 +3,21 @@ import Taro from '@tarojs/taro'
|
||||
import { socialApi, type SocialChatMessage } from './socialApi'
|
||||
|
||||
type PubHandler = (message: SocialChatMessage) => void
|
||||
export type SocialChatNote = {
|
||||
type?: string
|
||||
what: 'recv' | 'read' | 'kp'
|
||||
guestId: string
|
||||
seq?: number
|
||||
channelId?: string
|
||||
}
|
||||
type NoteHandler = (note: SocialChatNote) => void
|
||||
|
||||
export async function connectChatRealtime(channelId: string, onMessage: PubHandler, onConnection?: (connected: boolean) => void): Promise<{ disconnect: () => void } | null> {
|
||||
export async function connectChatRealtime(
|
||||
channelId: string,
|
||||
onMessage: PubHandler,
|
||||
onConnection?: (connected: boolean) => void,
|
||||
onNote?: NoteHandler,
|
||||
): Promise<{ disconnect: () => void } | null> {
|
||||
let info
|
||||
try { info = await socialApi.realtimeToken(channelId) } catch { return null }
|
||||
if (!info?.ok || !info.enabled || !info.token || !info.wsUrl) return null
|
||||
@ -54,8 +67,13 @@ export async function connectChatRealtime(channelId: string, onMessage: PubHandl
|
||||
resolve({ disconnect: stop })
|
||||
}
|
||||
const publication = message.push?.pub?.data
|
||||
const item = publication?.type === 'chat.message' ? publication.message : publication
|
||||
if (item?.id && item.channelId === channelId) onMessage(item)
|
||||
if (publication?.type === 'chat.note' && onNote) {
|
||||
const note = publication as SocialChatNote
|
||||
if (note.what && note.guestId) onNote(note)
|
||||
} else {
|
||||
const item = publication?.type === 'chat.message' ? publication.message : publication
|
||||
if (item?.id && item.channelId === channelId) onMessage(item)
|
||||
}
|
||||
if (!Object.keys(message).length) {
|
||||
try { task.send({ data: '{}' }) } catch { failed() }
|
||||
}
|
||||
|
||||
@ -183,7 +183,7 @@ function VipLanding() {
|
||||
/** 抖音无支付:全免费,不展示锁/不拉支付 */
|
||||
const payOk = cfg.flags.payEnabled !== false
|
||||
const freeMode = !payOk
|
||||
const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 29800
|
||||
const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 8800
|
||||
const productId = cfg.copy.vipProductId || 'vip_membership'
|
||||
const cta = freeMode ? '本端免费开放' : cfg.copy.vipCta || '立即加入'
|
||||
const brand = cfg.copy.homeBrand || 'nomadro'
|
||||
|
||||
@ -1,12 +1,15 @@
|
||||
# 游民社区 socialSkill
|
||||
|
||||
帮助用户完成 nomadro 游民社区三件事:加群收费、开语音视频、找搭子申请。
|
||||
帮助用户完成 nomadro 游民社区:加群收费、开语音视频、找搭子申请、看地图城市。
|
||||
|
||||
与 Web 公开面同源:`https://nomadro.com/api/public/v1/*`(工具表见 `packages/sdk/tools.json`)。
|
||||
|
||||
## 何时使用
|
||||
|
||||
- 用户想加入游民社区、付费入群、认识同频的人 → `joinSocialCommunity`
|
||||
- 用户想开视频/语音、参加线上见面、进入某场 meetup → `listMeetupRooms` / `openMeetupLive`
|
||||
- 用户想找搭子、兼职、志愿、共创、报名岗位 → `listTeamGigs` / `applyTeamGig`
|
||||
- 用户想看全球城市 / 地图 → `listMapCities`(Web 接力 `/social/map`)
|
||||
|
||||
## 重要约束
|
||||
|
||||
@ -14,6 +17,7 @@
|
||||
2. 微信内视频用原生 live-pusher(RTC)+ 接力页;不要建议 web-view。
|
||||
3. 申请岗位必须有称呼与联系方式;简介可选。失败时说明已先留本机,可重试。
|
||||
4. 优先返回 handoff / page-link,让用户点进小程序接力页完成支付或填表。
|
||||
5. 默认数据源 `.com`;`.cn` 为独立中国站。
|
||||
|
||||
## 离线兜底
|
||||
|
||||
|
||||
@ -2,12 +2,13 @@
|
||||
"apis": [
|
||||
{
|
||||
"name": "joinSocialCommunity",
|
||||
"description": "加入游民社区(加群收费,微信虚拟支付)。与 VIP 会员、community 付费体系不同。返回加群说明与接力到支付页。",
|
||||
"description": "加入游民社区(加群收费,微信虚拟支付)。与 VIP 会员、community 付费体系不同。返回加群说明与接力到支付页。对齐公开 API GET /api/public/v1/social/join。",
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"componentPath": "components/join-card/index",
|
||||
"pagePath": "/pages/social/index"
|
||||
}
|
||||
},
|
||||
"http": { "method": "GET", "path": "/api/public/v1/social/join" }
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
@ -35,12 +36,13 @@
|
||||
},
|
||||
{
|
||||
"name": "listMeetupRooms",
|
||||
"description": "列出可开语音/视频的线上见面场次(MiroTalk / 微信 live-pusher RTC)。",
|
||||
"description": "列出可开语音/视频的线上见面场次。对齐 GET /api/public/v1/social/meetups。",
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"componentPath": "components/meetup-list/index",
|
||||
"pagePath": "/pages/social/meetup/index"
|
||||
}
|
||||
},
|
||||
"http": { "method": "GET", "path": "/api/public/v1/social/meetups" }
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
@ -66,11 +68,15 @@
|
||||
},
|
||||
{
|
||||
"name": "openMeetupLive",
|
||||
"description": "打开指定场次的语音视频厅。微信内原生 live-pusher;H5 为 MiroTalk WebRTC。",
|
||||
"description": "打开指定场次的语音视频厅。微信内原生 live-pusher;H5 为 MiroTalk。对齐 GET /api/public/v1/social/meetups/{meetupId}。",
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"componentPath": "components/meetup-live-card/index",
|
||||
"pagePath": "/pages/social/meetup-live/index"
|
||||
},
|
||||
"http": {
|
||||
"method": "GET",
|
||||
"path": "/api/public/v1/social/meetups/{meetupId}"
|
||||
}
|
||||
},
|
||||
"inputSchema": {
|
||||
@ -102,12 +108,13 @@
|
||||
},
|
||||
{
|
||||
"name": "listTeamGigs",
|
||||
"description": "列出找搭子/共创机会(志愿、兼职、全职),供用户挑选后申请。",
|
||||
"description": "列出找搭子/共创机会。对齐 GET /api/public/v1/social/gigs。",
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"componentPath": "components/gig-list/index",
|
||||
"pagePath": "/pages/social/team/index"
|
||||
}
|
||||
},
|
||||
"http": { "method": "GET", "path": "/api/public/v1/social/gigs" }
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
@ -135,13 +142,17 @@
|
||||
},
|
||||
{
|
||||
"name": "applyTeamGig",
|
||||
"description": "提交找搭子/共创申请表。需称呼与联系方式;可接力到申请页补全。",
|
||||
"description": "提交找搭子/共创申请。对齐 POST /api/public/v1/social/gigs/{gigId}/apply。",
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"componentPath": "components/apply-card/index",
|
||||
"pagePath": "/pages/social/team/index"
|
||||
},
|
||||
"context": { "query": true }
|
||||
"context": { "query": true },
|
||||
"http": {
|
||||
"method": "POST",
|
||||
"path": "/api/public/v1/social/gigs/{gigId}/apply"
|
||||
}
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
@ -165,6 +176,34 @@
|
||||
"linkText": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "listMapCities",
|
||||
"description": "全球城市地图点位。对齐 GET /api/public/v1/social/cities;H5/Web 打开 /social/map。",
|
||||
"_meta": {
|
||||
"http": { "method": "GET", "path": "/api/public/v1/social/cities" }
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"west": { "type": "number" },
|
||||
"south": { "type": "number" },
|
||||
"east": { "type": "number" },
|
||||
"north": { "type": "number" }
|
||||
}
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": { "type": "array" },
|
||||
"pagePath": {
|
||||
"type": "string",
|
||||
"format": "page-link",
|
||||
"x-link-text-field": "linkText"
|
||||
},
|
||||
"linkText": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
36
apps/notify/README.md
Normal file
36
apps/notify/README.md
Normal file
@ -0,0 +1,36 @@
|
||||
# Notify — Novu-domain secondary-dev (Next + FastAPI)
|
||||
|
||||
读开源 **Novu** 域模型后自研,模块化进 Nomadro(Fair Use;非 iframe / 非原样塞 upstream UI):
|
||||
|
||||
| 能力 | 参考源码 | UI | API |
|
||||
|------|----------|----|-----|
|
||||
| Inbox | Novu Inbox / messages | `/social/notifications`(分类 · 已读 · 删除) | FastAPI `notify_svc` `/api/notify/v1` |
|
||||
| Settings | Preferences / channels | `/social/notifications/settings` | 免打扰 · 邮件 · 浏览器推送 |
|
||||
| Workflows | Workflow + steps (in_app / email / sms / push / chat / delay / digest) | `/social/notify/workflows` | 同上 |
|
||||
| Subscribers / Topics | Subscriber · Topic | `/social/notify/subscribers` · `/topics` | 同上 |
|
||||
| Trigger / Activity | Event · Notification · Jobs | `/social/notify/activity` | `POST /events/trigger` |
|
||||
|
||||
## 本地
|
||||
|
||||
```bash
|
||||
pnpm notify:fetch # 可选:对照源码 → apps/notify/upstream/novu
|
||||
pnpm dev:notify-api # uvicorn notify_main:app :8023
|
||||
pnpm dev # http://localhost:3000/notifications
|
||||
```
|
||||
|
||||
门户经 `src/app/api/notify/v1/[[...path]]` 同源代理到 `NOTIFY_API_URL`(默认 `http://127.0.0.1:8023`)。顶部铃铛在 `SiteShell`。
|
||||
|
||||
## 首期范围
|
||||
|
||||
- **用户收件箱**:分类(社交/搭子/项目/系统)、点击跳转、全部/单条已读、删除
|
||||
- **偏好**:免打扰、邮件订阅、浏览器推送授权
|
||||
- **In-App**:即时写入收件箱;编排台仍在 `/social/notify`
|
||||
- **Workflow 编辑与触发**:订阅者或 Topic fan-out
|
||||
- **外发通道**(email / sms / push / chat):记录 `queued_stub` 投递意图,不接真实供应商
|
||||
- **Delay / Digest / Throttle**:步骤可编排,执行记 `skipped_recorded`
|
||||
|
||||
## 数据与反模式
|
||||
|
||||
- SQLite:`data/notify/notify.sqlite3`(或 `NOTIFY_DATA_DIR`)
|
||||
- Upstream 仅参考:`apps/notify/upstream/*`(`pnpm notify:fetch`)
|
||||
- **禁止** iframe / 二级域 / 跑官方 Novu Docker UI 当产品页
|
||||
49
apps/notify/scripts/fetch-upstream.mjs
Normal file
49
apps/notify/scripts/fetch-upstream.mjs
Normal file
@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Shallow-clone Novu into apps/notify/upstream/ for secondary development.
|
||||
* Does not commit upstream into git.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const upstream = join(root, "upstream");
|
||||
|
||||
const REPOS = [
|
||||
{
|
||||
name: "novu",
|
||||
url: "https://github.com/novuhq/novu.git",
|
||||
branch: "next",
|
||||
},
|
||||
];
|
||||
|
||||
mkdirSync(upstream, { recursive: true });
|
||||
|
||||
function run(cmd, args, cwd) {
|
||||
console.log(`$ ${cmd} ${args.join(" ")}`);
|
||||
const r = spawnSync(cmd, args, { cwd, stdio: "inherit", shell: false });
|
||||
if (r.status !== 0) process.exit(r.status || 1);
|
||||
}
|
||||
|
||||
for (const repo of REPOS) {
|
||||
const dest = join(upstream, repo.name);
|
||||
if (existsSync(join(dest, ".git"))) {
|
||||
console.log(`[skip] ${repo.name} already cloned — pull --ff-only`);
|
||||
run("git", ["-C", dest, "pull", "--ff-only", "origin", repo.branch]);
|
||||
continue;
|
||||
}
|
||||
if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
|
||||
run("git", [
|
||||
"clone",
|
||||
"--depth",
|
||||
"1",
|
||||
"--branch",
|
||||
repo.branch,
|
||||
repo.url,
|
||||
dest,
|
||||
]);
|
||||
}
|
||||
|
||||
console.log("DONE fetch-upstream →", upstream);
|
||||
@ -14,7 +14,18 @@ pnpm dev:work-api # uvicorn work_main:app :8021
|
||||
pnpm dev # http://localhost:3000/social/work
|
||||
```
|
||||
|
||||
门户经 `src/app/api/work/v1/[[...path]]` 同源代理到 `WORK_API_URL`(默认 `http://127.0.0.1:8021`)。
|
||||
门户经 `src/app/api/work/v1/[[...path]]` 同源代理到 `WORK_API_URL`(默认 `http://127.0.0.1:8021`)。代理只转发 `content-type` / `authorization`,避免把 nginx 的 `Connection: upgrade` 带给 uvicorn。
|
||||
|
||||
## 生产(`.com` / 美国机)
|
||||
|
||||
```bash
|
||||
pnpm exec next build
|
||||
python deploy/work/deploy_us.py
|
||||
```
|
||||
|
||||
- systemd:`nomadro-work` → `127.0.0.1:8021`
|
||||
- nginx:`deploy/work/nginx-work-api.conf` → `location ^~ /api/work/` 直连 8021(与 `/api/social/` 同模式)
|
||||
- 页面仍走门户 `:4003`;API 不经过 Next
|
||||
|
||||
## 看板能力(Planka 对齐子集)
|
||||
|
||||
|
||||
@ -59,9 +59,9 @@
|
||||
"homeBrand": "nomadro",
|
||||
"homeTagline": "",
|
||||
"homeLead": "",
|
||||
"vipPriceFen": 29800,
|
||||
"vipPriceFen": 8800,
|
||||
"vipProductId": "tiktok",
|
||||
"vipCta": "立即加入 · ¥298",
|
||||
"vipCta": "立即加入 · ¥88",
|
||||
"vipOfferKey": "tiktok",
|
||||
"wechatOaName": "异度世界",
|
||||
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
|
||||
|
||||
60
deploy/coffee/_smoke_local.py
Normal file
60
deploy/coffee/_smoke_local.py
Normal file
@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import urllib.request
|
||||
from datetime import date, timedelta
|
||||
|
||||
BASE = "http://127.0.0.1:8024/api/coffee/v1"
|
||||
|
||||
|
||||
def req(method: str, path: str, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
r = urllib.request.Request(
|
||||
BASE + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers={"Content-Type": "application/json"} if body is not None else {},
|
||||
)
|
||||
with urllib.request.urlopen(r, timeout=10) as res:
|
||||
return json.loads(res.read().decode())
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("hosts", [h["username"] for h in req("GET", "/hosts")["hosts"]])
|
||||
h = req("GET", "/hosts/alice")["host"]
|
||||
print("alice events", [e["slug"] for e in h["event_types"]])
|
||||
day = None
|
||||
slot = None
|
||||
for i in range(0, 10):
|
||||
d = (date.today() + timedelta(days=i)).isoformat()
|
||||
s = req("GET", f"/hosts/alice/event-types/coffee-30/slots?day={d}")
|
||||
if s["slots"]:
|
||||
day = d
|
||||
slot = s["slots"][0]
|
||||
break
|
||||
print("day", day, "slot", slot)
|
||||
assert day and slot
|
||||
bk = req(
|
||||
"POST",
|
||||
"/bookings",
|
||||
{
|
||||
"username": "alice",
|
||||
"event_slug": "coffee-30",
|
||||
"start": slot["start"],
|
||||
"attendee_name": "Smoke Tester",
|
||||
"attendee_email": "smoke@nomadro.com",
|
||||
"notes": "cal secondary-dev",
|
||||
},
|
||||
)
|
||||
print("booked", bk["booking"]["id"], bk["booking"]["status"])
|
||||
s2 = req("GET", f"/hosts/alice/event-types/coffee-30/slots?day={day}")
|
||||
assert slot["start"] not in {x["start"] for x in s2["slots"]}
|
||||
print("slot_removed_ok")
|
||||
c = req("POST", f"/bookings/{bk['booking']['id']}/cancel")
|
||||
print("cancel", c["booking"]["status"])
|
||||
print("OK")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -53,6 +53,18 @@ curl -H "Title: test" -d "hello" https://ntfy.nomadro.cn/nomadro
|
||||
|
||||
健康检查:`deploy/observability/healthcheck.sh`(建议 cron 每 5 分钟),失败/恢复边沿推 ntfy。
|
||||
|
||||
## vip.hackrobot.cn(129 旁路)
|
||||
|
||||
- 埋点 sidecar:`pm2 vip-track` · `/opt/vip-track` · 独立 `events.db`
|
||||
- ntfy topic:`vip-hackrobot`(订阅需 `hackrobot` 账号;见 `apps/admin/deploy/_vip_track_assets/README.md`)
|
||||
- 安全部署:`python apps/admin/deploy/_push_vip_track_v2.py`(不重启业务 `vip`)
|
||||
|
||||
## vip.hackrobot.cn(129 旁路)
|
||||
|
||||
- 埋点 sidecar:`pm2 vip-track` · `/opt/vip-track` · 独立 `events.db`
|
||||
- ntfy topic:`vip-hackrobot`(订阅需 `hackrobot` 账号;见 `apps/admin/deploy/_vip_track_assets/README.md`)
|
||||
- 安全部署:`python apps/admin/deploy/_push_vip_track_v2.py`(不重启业务 `vip`)
|
||||
|
||||
## 门户部署(日常)
|
||||
|
||||
1. 本地 `pnpm build`
|
||||
|
||||
@ -10,7 +10,11 @@
|
||||
|
||||
First HTML visit without a cookie gets a same-origin sniff page that sets `nomadro_route` and reloads.
|
||||
|
||||
Detection matches `is-china-user` language + timezone signals (any Chinese language in `navigator.languages` counts).
|
||||
Detection(对齐 `src/lib/audience.ts`):
|
||||
|
||||
1. WeChat / WeCom in-app UA (`MicroMessenger` / `wxwork`) → Chinese lane
|
||||
2. Else `is-china-user` language + timezone sniff (any Chinese in `navigator.languages`)
|
||||
3. Else English / intl → WordPress
|
||||
|
||||
Router listens on `127.0.0.1:4403`.
|
||||
|
||||
|
||||
@ -103,7 +103,16 @@ function sniffHtml() {
|
||||
} catch (e2) {}
|
||||
return false;
|
||||
}
|
||||
var china = byLang() || byTz();
|
||||
function byWeChat() {
|
||||
try {
|
||||
var ua = navigator.userAgent || "";
|
||||
// 微信 / 企业微信内置 → 强制中文用户特殊线
|
||||
if (/micromessenger/i.test(ua) || /wxwork|wecom/i.test(ua)) return true;
|
||||
} catch (e) {}
|
||||
return false;
|
||||
}
|
||||
// 对齐 src/lib/audience.ts:微信内置优先,再语言/时区(is-china-user)
|
||||
var china = byWeChat() || byLang() || byTz();
|
||||
var value = china ? "zh" : "en";
|
||||
document.cookie = "${COOKIE}=" + value + "; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax";
|
||||
location.replace(location.pathname + location.search + location.hash);
|
||||
@ -129,6 +138,10 @@ function resolveTarget(req) {
|
||||
if (route === "zh") return NEXT;
|
||||
if (route === "en") return WP;
|
||||
|
||||
// 无 cookie 时:微信 UA 直接进中文线,避免再 sniff 丢上下文
|
||||
const ua = String(req.headers["user-agent"] || "");
|
||||
if (/micromessenger/i.test(ua) || /wxwork|wecom/i.test(ua)) return NEXT;
|
||||
|
||||
if (wantsHtml(req)) return "SNIFF";
|
||||
|
||||
const lang = String(req.headers["accept-language"] || "").toLowerCase();
|
||||
|
||||
@ -60,13 +60,18 @@ python deploy/social/deploy_local_build_82.py
|
||||
- `SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db`
|
||||
- `NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn`(`/etc/nomadro/portal.env`)
|
||||
- Centrifugo:`CENTRIFUGO_*`(见 `/etc/nomadro/centrifugo.env`,可并入 `portal.env`)
|
||||
- 头像 / 媒体(美国机 SeaweedFS,与 community 共用):`S3_ENABLED` · `S3_ENDPOINT=http://127.0.0.1:8333` · `S3_PUBLIC_URL=https://s3.nomadro.com` · `S3_BUCKET=nomadweb` · `S3_ACCESS_KEY` · `S3_SECRET_KEY` · `S3_UPLOAD_PREFIX=social`
|
||||
|
||||
**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。发版线:`test7`(H5 深优见根 `README.md`);当前开发:`test8`。
|
||||
**加入头像**:`POST /api/social/v1/upload`(multipart `file` + `purpose=avatar`,头 `X-Social-Guest-Id`)→ 公网 URL 或本地 `/api/social/v1/files/avatar/*`。
|
||||
|
||||
**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。当前开发 / 提审:`test9`(见根 `README.md`)。
|
||||
|
||||
**H5(≤900px)**:`src/modules/social/app/h5.css` 最后加载;Ways 竖列表(群组聊天优先)、底栏聊天在「认识」左侧、滑卡/composer 避开 dock。
|
||||
|
||||
冒烟:
|
||||
- `https://nomadro.cn/social` → 200
|
||||
- `https://nomadro.cn/social/map` · `/social/places` → 200
|
||||
- `GET /api/social/v1/map/cities` → 200(种子城)
|
||||
- `https://nomadro.cn/social/chat` · `/social/date` → 200(手机视口)
|
||||
- `https://mirotalk.nomadro.cn/join?...` → 200(勿再用 `.com`)
|
||||
- `GET /api/social/v1/health` → `centrifugo: true`
|
||||
@ -91,12 +96,11 @@ python deploy/social/deploy_local_build_82.py
|
||||
| 域名 | IP | 说明 |
|
||||
|---|---|---|
|
||||
| `nomadro.cn` | **82.157.112.245** | 门户直连 |
|
||||
| `mirotalk.nomadro.cn` | **82.157.112.245** | 本机 nginx → `127.0.0.1:9300`(**推荐进房 URL**) |
|
||||
| `mirotalk.nomadro.com` | 107.173.30.245 | 旧边车 Caddy 反代,多一跳,慢 |
|
||||
| `nomadro.cn/join` · `nomadro.com/join` | 同机 nginx → `127.0.0.1:9300` | **推荐进房 URL(同域 iframe,禁止跳二级域)** |
|
||||
| `mirotalk.nomadro.cn` | **82.157.112.245** | 兼容旧链;新进房勿再用 |
|
||||
| `mirotalk.nomadro.com` | 同 US / 旧边车 | 兼容旧链;新进房勿再用 |
|
||||
|
||||
门户默认用 **`https://mirotalk.nomadro.cn`**(与主站同机)。`ALLOWED_EMBED_ORIGINS` 在 82 上 MiroTalk `.env`;`.com` 边车 CSP 在 107:`/etc/caddy/sites/mirotalk.nomadro.com.caddy`。
|
||||
|
||||
本地 `pnpm dev`(:3000)活动页应可 iframe;若仍被拒,`MeetupLiveClient` 会本页 `location.assign` 进入(不新开标签)。
|
||||
门户默认 **`window.location.origin`**(同域 `/join`)。`ALLOWED_EMBED_ORIGINS` 在 MiroTalk `.env`。`MeetupLiveClient` **始终页内 iframe**,绝不 `location.assign` 到 `mirotalk.*`。
|
||||
|
||||
### 白标(去 MiroTalk 品牌 / 禁弹窗)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user