Lock Hub to China-only cities and document the cn audience gate.

Hard-enable hubCnOnly, drop foreign cities from default seeds/map/coffeechat, and keep intl cities in separate INT L catalogs until globalization reopens.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-29 00:03:11 +08:00
parent 4ad87fd4ab
commit d971a1f3e6
276 changed files with 97013 additions and 179 deletions

136
README.md
View File

@ -4,76 +4,114 @@
>
> | 域名 | 是什么 | 不是什么 |
> |------|--------|----------|
> | [admin.hackrobot.cn](https://admin.hackrobot.cn/) | **VIP 运营台**(服务 [vip.hackrobot.cn](https://vip.hackrobot.cn/):线索 / 拉黑存档 / LIVE 在线与弹窗通知) | 不是 Nomadro 微信/抖音后台 |
> | [admin.nomadro.cn](https://admin.nomadro.cn/) | Nomadro **中国站**管理 SPA(pps/admin:微信 / 抖音) | 不是 VIP 运营台;禁止用它的包覆盖 hackrobot |
> | [admin.nomadro.com](https://admin.nomadro.com/) | Nomadro **国际站**管理 SPA(pps/com/admin,美国 VPS,无小程序) | 与上两者均独立 |
> | [admin.hackrobot.cn](https://admin.hackrobot.cn/) | **VIP 运营台**(服务 [vip.hackrobot.cn](https://vip.hackrobot.cn/):线索 / 拉黑存档 / LIVE 在线与弹窗通知)· 腾讯云 `129.204.21.129` | 不是 Nomadro 微信/抖音后台 |
> | [admin.nomadro.cn](https://admin.nomadro.cn/) | Nomadro **中国站**管理 SPA(`apps/admin`:微信 / 抖音 / 小红书线)· 中国机 `82.157.112.245` | 不是 VIP 运营台;禁止用它的包覆盖 hackrobot |
> | [admin.nomadro.com](https://admin.nomadro.com/) | Nomadro **`.com` Web 运营台**(`apps/com/admin`,美国 VPS)· **登录后强制选轨:中文 `/cn`(Hub)↔ 国际 `/intl`(Social)** | 与上两者均独立;无小程序 |
>
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 \.cursor/rules/admin-hosts-never-confuse.mdc\。
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 `.cursor/rules/admin-hosts-never-confuse.mdc`。
2026-11-22:微信小册**提审态默认免费**,且与正式付费数据隔离 — `platforms.weapp.bookAudit.reviewMode` 开启时读独立 `audit*` 书(永远 `is_free` / 不可下单 / 不读正式 `unlocks`·`__vip__`);关闭后重新拉正式已购与 VIP,互不粘态。weapp App 挂远程配置 WS + 1s 轮询,后台开关约 1s 热更新。API 已推 `api.nomadro.cn`(`_push_audit_free_isolate.py`);体验包须本轮许可后再 `build:weapp` 上传。
数字游民操作系统。**主开发与默认发版**:[nomadro.com](https://nomadro.com)(美国 VPS)。**中国独立站**:[nomadro.cn](https://nomadro.cn)(腾讯云 `82.157.112.245`,与 `.com` 中文轨 UI/UX/功能对齐后独立同步)。**VIP 隔离产品**:[vip.hackrobot.cn](https://vip.hackrobot.cn/) / [admin.hackrobot.cn](https://admin.hackrobot.cn/)(`129.204.21.129`)。
2026-11-15:VIP 运营台实时能力 — dmin.hackrobot.cn LIVE 在线/弹窗通知(ops token ↔ /api/admin/live)、用户拉黑/曾拉黑 tag 与身份提示;**写死** dmin.hackrobot.cn 与 dmin.nomadro.cn 永远禁止混淆。资产 pps/admin/deploy/_vip_live_assets/ · API live_ops/ops_live。
## 产品逻辑(SoT)
### 双站与受众
| 站 | 机 | 角色 |
|---|---|---|
| **nomadro.com** | 美国 VPS(如 `108.174.50.68`) | 主开发 / 默认部署;站内再分 **中文用户 / 国际用户** |
| **nomadro.cn** | `82.157.112.245` | 中国独立生产;对齐 `.com` **中文**体验后再发;库/进程互不顶替 |
| **vip.hackrobot.cn** | `129.204.21.129` | 独立 VIP 产品 + 运营台;禁止与 Nomadro admin 混发 |
2026-11-10:`test14` 收尾(`8935269` / tag `2026-11-10`)后切换 `test15` 开发。基线含社区主题 1–4、后台体验主题切换、反馈图片灯箱、招聘首页底部化、本地皮肤调试小球。见 [test14 收尾](docs/test14-closeout.md) · [test15 开发](docs/test15-development.md)。
`.com` 受众识别(`src/modules/audience`,**勿用 UI locale 反推**):
2026-11-09:`test14` 门户、后端及 `.com` 管理后台已获许可并部署美国机。门户构建 `T9G517UdX-JND3zgNO3SD`;修复生产通知/预约代理自循环,公网接口恢复 200。门户/后台静态资源哈希、服务健康与后台鉴权验证通过,`.cn` 未同步。备份与验收见 [test14 上线记录](docs/test14-release.md)。
1. 微信 / 企业微信内置 → **cn**
2. `is-china-user` → **cn**
3. 否则 → **intl**
2026-11-09:`test13` 收尾后切换 `test14`,仅优化门户/后端/后台功能与构建,不调整前端视觉、不部署生产。修复首页重写循环、迁移 Next.js 16 `proxy`、统一本地 `.com` API/配置默认值、修复 Strict Mode 埋点监听及后台请求异常处理、为共享 PocketBase 凭证增加并发保护与一次 401 恢复,并修复 `.cn` 后台构建类型冲突。范围与验证见 [test14 开发记录](docs/test14-development.md)。
| 受众 | 首页 | 社区产品 | 支付 | 关注 |
|------|------|----------|------|------|
| **intl**(默认) | `/` → **Social** `/social` | **Social** 英文游民社区 | Creem / NOWPayments | X |
| **cn** | `/` → **Portal** `/portal` | **Hub** `/hub`(独立副本,**勿改 `/social` 业务**) | zpay · 微信内 xpay | 公众号二维码 |
2026-11-08:远程工作门禁 + Work UX + 语言水合修复并部署 `.com` — `/social/work` 未加入社区不可用(登录/注册/补资料,与约会同门禁);Pads/Boards 增强(收藏复制删除、专注预览快捷键、看板筛选模板);`LocaleProvider`/`LanguageSwitcher` 首帧固定 zh 消除 hydration mismatch;反馈页英文短语补全。本地构建上传门户 `.next` + `admin.nomadro.com` + API/social;`.cn` 未同步。
支付分流跟 `detectAudience().isChina`,**不要**跟 UI 语言。
2026-11-07:Work Pads 深度定制(Etherpad 域模型 → Next 原生)— `/social/work/pads`:作者色条、行号、在场名单、侧栏聊天、时间轴浏览/还原、冲突提示、导入导出、Ctrl/⌘+S、删除;API `presence`/`chat`/`DELETE` + Welcome pad;work 服务补 PocketBase 鉴权。无 iframe。
### 中文公开三大模块(其余后台可关)
2026-11-07:Google 增长 OAuth UX 修复 — 未配 Client 时不再展示灰掉的「用 Google 账号授权」;改为红条提示 +「① 保存客户端」为主按钮,保存成功后再出现「② 用 Google 账号授权」。
门户 `/portal` Hero 主入口(远程 `modules.*` 可动态隐藏):
2026-11-07:用户分析补全环境特征并部署 `.com` — 埋点写入 IP(服务端)+ UA/浏览器/系统/设备/屏幕/时区/语言等;后台「访客明细 → 看明细」展示环境特征卡与时间线;API `track-analytics` / `track-visitor`。
| # | 产品 | 路由 | 说明 |
|---|------|------|------|
| 1 | 出海导航 | `/nav` | `src/modules/nav` |
| 2 | 数字游民小册 | `/book` | `src/modules/ebook` + 离线 `ebook-content` |
| 3 | 游民社区 | **`/hub`** | 中文独立 Hub;**不是** `/social` |
2026-11-07:产品分析 — 门户接入 [PostHog](https://github.com/PostHog/posthog)(`posthog-js`)与开源 [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) visitorId;经 `PortalAnalytics` + `src/lib/analytics/*` 镜像现有 `/api/track`;远程配置 `flags.posthog*` / `fingerprintEnabled` + env `NEXT_PUBLIC_POSTHOG_KEY`。未配 key 时 PostHog 静默跳过。
旅居社群 `/community`、VIP `/vip` 等仍保留,默认可由后台开关隐藏。
2026-11-07:Google 增长自动化 — 后台「增长 → Google 增长」支持粘贴片段 / 同步 env / 一键写入;API `/api/admin/google/{status,parse,auto-link}`;`ca-pub` 自动补 `ads.txt` publisher;保留手填。门户 `GoogleTags` + `/sitemap.xml` `/robots.txt` `/ads.txt`。文字厅双语与咖啡聊离线兜底见 [`src/modules/social/README.md`](src/modules/social/README.md)。
### Social vs Hub(强制分治)
2026-11-05:UI/UX 与预约、通知功能升级已上线 .com,详见 [本轮发布与验收记录](docs/uiux-upgrade-2026-11-05.md),包括当前构建、备份位置及功能边界。
| | **Social(国际)** | **Hub(中文)** |
|---|---|---|
| 门户 | `/social` · `src/modules/social` | `/hub` · `src/modules/hub`(从 social **只读 fork**,独立演进) |
| API | `/api/social/v1` · `social_main :8020` | `/api/hub/v1` · `hub_main :8025` |
| 数据 | `social_*` / `social.db` | `hub_*` / 独立库 |
| 后台 | **admin.nomadro.com → `/intl/social/*`** | **admin.nomadro.com → `/cn/hub/*`** |
| 铁律 | 国际默认产品;**勿把中文门户链到 `/social`** | 中文门户「游民社区」→ `/hub/home`;改 Hub **禁止**顺手改 Social |
数字游民操作系统(主开发与默认发版:[nomadro.com](https://nomadro.com);中国独立站:[nomadro.cn](https://nomadro.cn))。
### 多端复制链(中国)
2026-11 平台升级已部署至 `.com` 门户、API 与 [Web 管理后台](https://admin.nomadro.com)。升级内容、验收范围、构建编号与回滚位置见 [升级记录](docs/platform-upgrade-2026-11.md)。`.cn` 未同步本次发版。
```
.com(Next · audience cn/intl)
└─ 中文轨测稳 → 同步 .cn(Next · 82,独立)
└─ Taro H5(apps/miniprogram/h5)对齐 .cn
└─ 编译 → 微信小程序 / 抖音小程序 / 小红书小工具
管理:admin.nomadro.cn(微信 / 抖音);全端禁止 web-view 承载业务
```
**归档禁发:** 分支 `test12`(Codex 实验改动)已冻结,**永远不要上线**;见 [docs/archive/test12-NEVER-DEPLOY.md](docs/archive/test12-NEVER-DEPLOY.md) 与 tag `archive/test12-never-deploy`。
本地:`pnpm dev`(门户)· `pnpm dev:h5`(Taro PC/H5)· `pnpm dev:weapp` / `dev:tt` · `pnpm build:xhs`。
### 管理后台三套(永不互盖)
| 后台 | 源码 | 职责 |
|------|------|------|
| [admin.nomadro.com](https://admin.nomadro.com/) | `apps/com/admin` | Web:登录 → 选 **中文轨(Hub)** 或 **国际轨(Social)**;侧栏互不混挂;误入对方路径自动改写 |
| [admin.nomadro.cn](https://admin.nomadro.cn/) | `apps/admin` | 中国:`/wechat` · `/douyin` · 小程序运营 |
| [admin.hackrobot.cn](https://admin.hackrobot.cn/) | `apps/hackrobot/*` | VIP LIVE / 拉黑 / 线索 |
---
**近期 changelog(摘要)**:**Hub 中文锁**(`hubCnOnly` 写死开)· 城市目录 / 地图 / 咖啡聊 **只留中国**(清迈/巴厘岛/里斯本/槟城移出默认种子)· Hub 独立上线 · admin.nomadro.com 真分轨(cn→`/cn/hub/*` · intl→`/intl/social/*`)· 微信小册提审免费隔离 · VIP LIVE · 细节见 [`docs/`](docs/) · [`src/modules/hub/README.md`](src/modules/hub/README.md)。**归档禁发:** `test12` — [docs/archive/test12-NEVER-DEPLOY.md](docs/archive/test12-NEVER-DEPLOY.md)。
## 架构
```
src/ Next.js 门户 .cn(app 路由壳 + modules 业务)
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(仅 .cn 备案线)
apps/api/ 统一 FastAPI(ebook + community + pay + social + work + notify)
apps/admin/ admin.nomadro.cn 管理 SPA(微信 / 抖音)
apps/com/ .com 源码隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
apps/work/ 远程工作参考 upstream / overlay(Planka · Etherpad;产品 UI 不跑 iframe)
apps/notify/ 通知参考 upstream(Novu;产品 UI 不跑 iframe)
apps/coffee/ 咖啡聊预约参考 upstream(Cal.com;产品 UI 不跑 iframe)
src/ Next.js 门户(app 路由壳 + modules 业务;.com 主 / .cn 同步)
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(中国备案线)
apps/api/ 统一 FastAPI(ebook + community + pay + social + hub + work + notify + coffee)
apps/admin/ admin.nomadro.cn(微信 / 抖音)
apps/com/ .com 隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
apps/hackrobot/ VIP 隔离树 → vip.hackrobot.cn / admin.hackrobot.cn(129)
apps/work|notify|coffee/ 开源域模型对照(产品 UI 禁 iframe)
packages/ @nomadro/pay · pb · sdk
data/ 远程配置等运行时数据(含 social.db · work/notify/coffee.sqlite3)
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
data/ remote-config · social/hub/work/notify/coffee 运行时库
scripts/ 本地开发 / 清理 / .com 本地构建部署
```
| 产品 | 门户路由 | 源码 |
|------|----------|------|
| 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) |
| 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` |
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
| **远程工作** | `/social/work` | `src/modules/work` · FastAPI `work_svc` `/api/work/v1`(看板 + 文档) |
| **通知** | `/notifications` · `/social/notify` | `src/modules/notify` · FastAPI `notify_svc` `/api/notify/v1`(收件箱 + 工作流) |
| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
| 导航 | `/nav` | `src/modules/nav` |
| 小册 | `/book` | `src/modules/ebook` + `ebook-content` |
| 旅居社群 | `/community` | `src/modules/community`(**勿改名**) |
| **Social(国际游民社区)** | `/social` | `src/modules/social` · `/api/social/v1` · `:8020` |
| **Hub(中文游民社区)** | `/hub` | `src/modules/hub` · `/api/hub/v1` · `:8025` · 后台仅 `/cn/hub/*` |
| 远程工作 | `/social/work` | `src/modules/work` · `work_svc` `:8021` |
| 通知 | `/notifications` · `/social/notify` | `src/modules/notify` · `notify_svc` `:8023` |
| 咖啡聊 | `/social/coffeechat` | `src/modules/coffee` · `coffee_svc` `:8024` |
| VIP(门户) | `/vip` | `src/modules/vip` |
| **VIP(hackrobot)** | vip.hackrobot.cn | `apps/hackrobot/{vip,admin-site,nomadmini}` |
| 后台 .com | admin.nomadro.com | `apps/com/admin`(`/cn` Hub · `/intl` Social) |
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
| **VIP 运营台** | **admin.hackrobot.cn** | 独立 VIP SPA(vip.hackrobot.cn);**禁止**与 admin.nomadro.cn 混淆;LIVE/拉黑见 _vip_live_assets |
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
| API | api.nomadro.cn | `apps/api` |
`.cn` 后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗集成在 **`/douyin/modules`**。`.com` 未备案,**无**小程序后台。
`.cn` 后台:`/wechat/*` · `/douyin/*`。`.com` **无**小程序后台。
## 技术栈(Next 门户 + FastAPI)
@ -208,9 +246,12 @@ pnpm dev:api # FastAPI(需先建 apps/api/.venv)
pnpm dev:work-api # 仅本机联调 work_svc :8021;日常 pnpm dev 直连线上 nomadro.com
pnpm dev:notify-api # 通知 notify_svc :8023(收件箱 / 工作流)
pnpm dev:coffee-api # 咖啡聊 coffee_svc :8024(预约 / 时段)
pnpm dev:hub-api # 中文 Hub hub_svc :8025(独立于 social)
pnpm dev:admin-com # admin.nomadro.com 本地(Vite)
pnpm build:portal
pnpm build:admin
pnpm build:admin-com # .com Web 运营台
pnpm build:xhs # 小红书离线包 → apps/miniprogram/xhs/release
pnpm typecheck
pnpm clean # 清 .next / dist
@ -237,15 +278,20 @@ pnpm dev:api
- 审核冻结分支:`pre4`(历史审核包);历史微信提审包:`test9` + tag `2026-11-02`
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
- **当前开发分支:`test14`**(微信小册提审隔离与热更新在此迭代;历史定版 tag 仍见 `test9`)
- **当前开发分支:`test15`**(Hub 中文受众锁与国内城市目录;历史定版 tag 仍见 `test9`)
### 游民社区(`/social`)
### 游民社区 · Social(`/social`,国际)与 Hub(`/hub`,中文)
与旅居社群 `/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)。
与旅居社群 `/community` **完全独立**。
- **Social(intl)**:`src/modules/social` + `/api/social/v1`(`social_main :8020`,库 `data/social/social.db`)。`.com` **非中文**默认首页入口。后台仅 **`/intl/social/*`**。
- **Hub(cn)**:`src/modules/hub` + `/api/hub/v1`(`hub_main :8025`)。从 Social **只读 fork**;中文门户「游民社区」→ `/hub/home`。后台仅 **`/cn/hub/*`**。改 Hub **禁止**顺手改 Social 业务代码。
- **中文锁(当前)**:`isHubCnOnly()` 写死开启 → UI 强制中文、屏蔽语言切换;地理 `HUB_CN_GEO_CODES=["CN"]`;`/hub/places` `/hub/map` `/hub/coffeechat` `/hub/people` 等城市轨 **只出国内城**(国际城保留在 `HUB_CITIES_INTL` / `SOCIAL_CITIES_INTL`,默认不进目录)。聊天中文受众只要一个「游民大厅」。
- `SOCIAL_ENABLED=false` / Hub 挂载失败不影响 ebook / community / pay。增量部署见 [`deploy/social/README.md`](deploy/social/README.md) · [`src/modules/hub/README.md`](src/modules/hub/README.md)。
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。**人脸门禁**(默认开):头像需**单人正脸**;优先 InsightFace 检测 + RGB 活体。**现场自拍核验**(推荐):`POST /api/social/v1/avatar/challenge` 收正脸+转头两帧,校验同人 embedding + 转头幅度后再存头像。关检测:`SOCIAL_AVATAR_FACE_CHECK=false`;关活体:`SOCIAL_AVATAR_LIVENESS=false`。
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
**地理发现**:Social `/social/map` · `/social/places`(`GET /api/social/v1/map/cities`);Hub `/hub/map` · `/hub/places`(`GET /api/hub/v1/map/cities`,种子默认仅中国)。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
**文字厅(`/social/chat`)**:Centrifugo WS 优先(`/rt` 反代 · token `/api/social/v1/realtime/token`),失败降级轮询。侧栏为 Lobby + **国家频道**(多语言国名,不做大洲分组)。消息能力:未读分隔、在线 presence、发送中态、@提及、转发、已读回执、频道 rail 实时。气泡内 **MessageBilingual**:原文 + 当前 UI 语言译文同框(细线分隔,非第二气泡);不展示活动条 / 置顶条。本地:`pnpm` 起 Next `:3000` + `social_main :8020` + Centrifugo(见 `deploy/social/centrifugo`)。

View File

@ -0,0 +1,193 @@
"""/hub locale + geo ops — modular remote-config surface.
Writes only copy.hubLocale / copy.hubGeo; leaves catalogs & orders alone.
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime, timezone
from typing import Any
from ebook_svc.services.tt_platform_config import resolve_config_file
# Keep in sync with src/modules/hub/locale/catalog.ts
LOCALE_CATALOG: list[dict[str, str]] = [
{"id": "zh", "label": "中文"},
{"id": "en", "label": "English"},
{"id": "ja", "label": "日本語"},
{"id": "ko", "label": "한국어"},
{"id": "vi", "label": "Tiếng Việt"},
{"id": "th", "label": "ไทย"},
{"id": "id", "label": "Bahasa Indonesia"},
{"id": "ms", "label": "Bahasa Melayu"},
{"id": "es", "label": "Español"},
{"id": "pt", "label": "Português"},
{"id": "fr", "label": "Français"},
{"id": "de", "label": "Deutsch"},
{"id": "it", "label": "Italiano"},
{"id": "ru", "label": "Русский"},
{"id": "ar", "label": "العربية"},
{"id": "hi", "label": "हिन्दी"},
{"id": "tr", "label": "Türkçe"},
{"id": "nl", "label": "Nederlands"},
{"id": "pl", "label": "Polski"},
{"id": "uk", "label": "Українська"},
]
LOCALE_IDS = {x["id"] for x in LOCALE_CATALOG}
# Keep in sync with src/modules/hub/geo/countries.ts
COUNTRY_CATALOG: list[dict[str, str]] = [
{"code": "CN", "nameZh": "中国", "nameEn": "China", "emoji": "🇨🇳", "lane": "cn"},
{"code": "TH", "nameZh": "泰国", "nameEn": "Thailand", "emoji": "🇹🇭", "lane": "intl"},
{"code": "ID", "nameZh": "印尼", "nameEn": "Indonesia", "emoji": "🇮🇩", "lane": "intl"},
{"code": "MY", "nameZh": "马来西亚", "nameEn": "Malaysia", "emoji": "🇲🇾", "lane": "intl"},
{"code": "PT", "nameZh": "葡萄牙", "nameEn": "Portugal", "emoji": "🇵🇹", "lane": "intl"},
{"code": "JP", "nameZh": "日本", "nameEn": "Japan", "emoji": "🇯🇵", "lane": "intl"},
{"code": "KR", "nameZh": "韩国", "nameEn": "South Korea", "emoji": "🇰🇷", "lane": "intl"},
{"code": "DE", "nameZh": "德国", "nameEn": "Germany", "emoji": "🇩🇪", "lane": "intl"},
{"code": "ES", "nameZh": "西班牙", "nameEn": "Spain", "emoji": "🇪🇸", "lane": "intl"},
{"code": "VN", "nameZh": "越南", "nameEn": "Vietnam", "emoji": "🇻🇳", "lane": "intl"},
]
COUNTRY_CODES = {x["code"] for x in COUNTRY_CATALOG}
CITY_SEED: list[dict[str, str]] = [
{"id": "dali", "name": "大理", "country": "CN"},
{"id": "chengdu", "name": "成都", "country": "CN"},
{"id": "hangzhou", "name": "杭州", "country": "CN"},
{"id": "kunming", "name": "昆明", "country": "CN"},
{"id": "shenzhen", "name": "深圳", "country": "CN"},
{"id": "xiamen", "name": "厦门", "country": "CN"},
{"id": "shanghai", "name": "上海", "country": "CN"},
{"id": "lijiang", "name": "丽江", "country": "CN"},
]
CITY_IDS = {x["id"] for x in CITY_SEED}
def _read_raw() -> dict[str, Any]:
path = resolve_config_file()
if not path.is_file():
return {}
try:
import json
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:
import json
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-locale-geo-{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_locale(raw: Any) -> dict[str, Any]:
src = raw if isinstance(raw, dict) else {}
enabled_in = src.get("enabled")
enabled: list[str] = []
if isinstance(enabled_in, list):
for item in enabled_in:
sid = str(item or "").strip()
if sid in LOCALE_IDS:
enabled.append(sid)
fallback = str(src.get("fallback") or "en").strip()
if fallback not in LOCALE_IDS:
fallback = "en"
mt = src.get("mtEnabled")
return {
"enabled": enabled,
"mtEnabled": True if mt is None else bool(mt),
"fallback": fallback,
}
def _norm_geo(raw: Any) -> dict[str, Any]:
src = raw if isinstance(raw, dict) else {}
countries: list[str] = []
if isinstance(src.get("enabledCountries"), list):
for item in src["enabledCountries"]:
code = str(item or "").strip().upper()
if code in COUNTRY_CODES:
countries.append(code)
featured: list[str] = []
if isinstance(src.get("featuredCityIds"), list):
for item in src["featuredCityIds"]:
cid = str(item or "").strip()
if cid in CITY_IDS:
featured.append(cid)
return {
"enabledCountries": countries,
"featuredCityIds": featured,
}
def read_locale_geo() -> dict[str, Any]:
raw = _read_raw()
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
locale = _norm_locale(copy.get("hubLocale"))
geo = _norm_geo(copy.get("hubGeo"))
return {
"ok": True,
"locale": locale,
"geo": geo,
"meta": {
"locales": LOCALE_CATALOG,
"countries": COUNTRY_CATALOG,
"cities": CITY_SEED,
},
"version": raw.get("version"),
"updatedAt": raw.get("updatedAt"),
"configPath": str(resolve_config_file()),
}
def write_locale_geo(patch: dict[str, Any]) -> dict[str, Any]:
raw = _read_raw()
out: dict[str, Any] = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
copy = dict(out.get("copy") or {})
locale = _norm_locale(copy.get("hubLocale"))
geo = _norm_geo(copy.get("hubGeo"))
if isinstance(patch.get("locale"), dict):
lp = patch["locale"]
if "enabled" in lp:
locale = _norm_locale({**locale, "enabled": lp.get("enabled")})
if "mtEnabled" in lp:
locale["mtEnabled"] = bool(lp.get("mtEnabled"))
if "fallback" in lp:
locale = _norm_locale({**locale, "fallback": lp.get("fallback")})
if isinstance(patch.get("geo"), dict):
gp = patch["geo"]
if "enabledCountries" in gp:
geo = _norm_geo({**geo, "enabledCountries": gp.get("enabledCountries")})
if "featuredCityIds" in gp:
geo = _norm_geo({**geo, "featuredCityIds": gp.get("featuredCityIds")})
copy["hubLocale"] = locale
copy["hubGeo"] = geo
out["copy"] = copy
_write_raw(out)
return read_locale_geo()

View File

@ -59,10 +59,6 @@ CITY_SEED: list[dict[str, str]] = [
{"id": "xiamen", "name": "厦门", "country": "CN"},
{"id": "shanghai", "name": "上海", "country": "CN"},
{"id": "lijiang", "name": "丽江", "country": "CN"},
{"id": "chiangmai", "name": "清迈", "country": "TH"},
{"id": "bali", "name": "巴厘岛", "country": "ID"},
{"id": "lisbon", "name": "里斯本", "country": "PT"},
{"id": "penang", "name": "槟城", "country": "MY"},
]
CITY_IDS = {x["id"] for x in CITY_SEED}

View File

@ -0,0 +1,4 @@
"""Nomadro Hub 独立后端 — 与 community/ebook/pay 数据完全隔离。
IM 协议见 ``contract.py``:服务端无 UI 假设;Web / 微信小程序任意换皮。
"""

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,442 @@
"""Skill swap · meetup reviews · report/block · wrapped — PocketBase only."""
from __future__ import annotations
from typing import Any
from nomadro_pb import get_pb, pb_quote
from nomadro_pb.ensure import ensure_selected
from hub_svc import pb_data
from hub_svc.pb_data import _now, _uid
C_SKILLS = "hub_skill_posts"
C_REVIEWS = "hub_meetup_reviews"
C_BLOCKS = "hub_blocks"
C_REPORTS = "hub_reports"
def ensure_community_tables() -> None:
from hub_svc.pb_data import HUB_COLLECTION_NAMES
ensure_selected(HUB_COLLECTION_NAMES)
def create_skill_post(
guest_id: str,
*,
author: str,
city: str,
offer: str,
want: str,
note: str = "",
) -> dict[str, Any]:
ensure_community_tables()
item = {
"id": _uid("sk"),
"guestId": guest_id,
"author": (author or "游民").strip()[:64] or "游民",
"city": (city or "").strip()[:64],
"offer": (offer or "").strip()[:200],
"want": (want or "").strip()[:200],
"note": (note or "").strip()[:800],
"status": "open",
"createdAt": _now(),
}
if not item["offer"] or not item["want"]:
raise ValueError("请填写能提供什么、想换什么")
rec = get_pb().create(
C_SKILLS,
{
"guest_id": guest_id,
"author": item["author"],
"city": item["city"],
"offer": item["offer"],
"want": item["want"],
"note": item["note"],
"status": "open",
"created_at": item["createdAt"],
},
)
item["id"] = rec.get("id") or item["id"]
return item
def list_skill_posts(*, city: str = "", limit: int = 60) -> list[dict[str, Any]]:
ensure_community_tables()
limit = max(1, min(int(limit or 60), 120))
filt = 'status="open"'
rows = get_pb().list_all(C_SKILLS, filter=filt, sort="-created_at", hard_limit=200)
city_f = city.strip().lower()
out = []
for r in rows:
if city_f and city_f not in (r.get("city") or "").lower():
continue
out.append(
{
"id": r.get("id"),
"guestId": r.get("guest_id"),
"author": r.get("author"),
"city": r.get("city") or "",
"offer": r.get("offer"),
"want": r.get("want"),
"note": r.get("note") or "",
"status": r.get("status"),
"createdAt": r.get("created_at"),
}
)
if len(out) >= limit:
break
return out
def close_skill_post(guest_id: str, post_id: str) -> dict[str, Any]:
ensure_community_tables()
r = get_pb().first(C_SKILLS, filter=f"id={pb_quote(post_id)}")
if not r:
# PB id filter uses record id field
try:
r = get_pb().request(
"GET", f"/api/collections/{C_SKILLS}/records/{post_id}", admin=True
)
except Exception:
r = None
if not r:
raise ValueError("帖子不存在")
if r.get("guest_id") != guest_id:
raise ValueError("只能关闭自己的帖子")
get_pb().update(C_SKILLS, r["id"], {"status": "closed"})
return {"ok": True, "id": post_id, "status": "closed"}
def create_meetup_review(
from_guest: str,
*,
to_guest: str,
to_name: str = "",
booking_id: str = "",
punctuality: int,
chemistry: int,
professionalism: int,
text: str = "",
) -> dict[str, Any]:
ensure_community_tables()
if from_guest == to_guest:
raise ValueError("不能评价自己")
for n in (punctuality, chemistry, professionalism):
if not 1 <= int(n) <= 5:
raise ValueError("评分须为 1–5")
if booking_id:
hit = get_pb().first(
C_REVIEWS,
filter=(
f"booking_id={pb_quote(booking_id)} && "
f"from_guest={pb_quote(from_guest)} && "
f"to_guest={pb_quote(to_guest)}"
),
)
if hit:
raise ValueError("你已经评价过这次见面")
item = {
"id": _uid("rv"),
"bookingId": (booking_id or "").strip()[:80],
"fromGuest": from_guest,
"toGuest": to_guest,
"toName": (to_name or "").strip()[:64],
"punctuality": int(punctuality),
"chemistry": int(chemistry),
"professionalism": int(professionalism),
"text": (text or "").strip()[:800],
"createdAt": _now(),
}
rec = get_pb().create(
C_REVIEWS,
{
"booking_id": item["bookingId"],
"from_guest": from_guest,
"to_guest": to_guest,
"to_name": item["toName"],
"punctuality": item["punctuality"],
"chemistry": item["chemistry"],
"professionalism": item["professionalism"],
"text": item["text"],
"created_at": item["createdAt"],
},
)
item["id"] = rec.get("id") or item["id"]
return item
def reviews_for_guest(guest_id: str, limit: int = 40) -> dict[str, Any]:
ensure_community_tables()
limit = max(1, min(int(limit or 40), 100))
rows = get_pb().list_all(
C_REVIEWS,
filter=f"to_guest={pb_quote(guest_id)}",
sort="-created_at",
hard_limit=limit,
)
items = [
{
"id": r.get("id"),
"bookingId": r.get("booking_id") or "",
"fromGuest": r.get("from_guest"),
"toGuest": r.get("to_guest"),
"toName": r.get("to_name") or "",
"punctuality": r.get("punctuality"),
"chemistry": r.get("chemistry"),
"professionalism": r.get("professionalism"),
"text": r.get("text") or "",
"createdAt": r.get("created_at"),
"avg": round(
(
float(r.get("punctuality") or 0)
+ float(r.get("chemistry") or 0)
+ float(r.get("professionalism") or 0)
)
/ 3,
2,
),
}
for r in rows
]
if not items:
return {"guestId": guest_id, "count": 0, "averages": None, "items": []}
n = len(items)
averages = {
"punctuality": round(sum(i["punctuality"] for i in items) / n, 2),
"chemistry": round(sum(i["chemistry"] for i in items) / n, 2),
"professionalism": round(sum(i["professionalism"] for i in items) / n, 2),
"overall": round(sum(i["avg"] for i in items) / n, 2),
}
return {"guestId": guest_id, "count": n, "averages": averages, "items": items}
def block_user(guest_id: str, blocked_guest: str, reason: str = "") -> dict[str, Any]:
ensure_community_tables()
if guest_id == blocked_guest:
raise ValueError("不能屏蔽自己")
get_pb().upsert(
C_BLOCKS,
filter=(
f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}"
),
payload={
"guest_id": guest_id,
"blocked_guest": blocked_guest,
"reason": (reason or "").strip()[:200],
"created_at": _now(),
},
)
return {"ok": True, "blockedGuest": blocked_guest}
def unblock_user(guest_id: str, blocked_guest: str) -> dict[str, Any]:
ensure_community_tables()
r = get_pb().first(
C_BLOCKS,
filter=(
f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}"
),
)
if r:
get_pb().delete(C_BLOCKS, r["id"])
return {"ok": True}
def list_blocks(guest_id: str) -> list[dict[str, Any]]:
ensure_community_tables()
rows = get_pb().list_all(
C_BLOCKS, filter=f"guest_id={pb_quote(guest_id)}", sort="-created_at"
)
return [
{
"blockedGuest": r.get("blocked_guest"),
"reason": r.get("reason") or "",
"createdAt": r.get("created_at"),
}
for r in rows
]
def is_blocked(viewer: str, other: str) -> bool:
ensure_community_tables()
a = get_pb().first(
C_BLOCKS,
filter=f"guest_id={pb_quote(viewer)} && blocked_guest={pb_quote(other)}",
)
if a:
return True
b = get_pb().first(
C_BLOCKS,
filter=f"guest_id={pb_quote(other)} && blocked_guest={pb_quote(viewer)}",
)
return bool(b)
def create_report(
guest_id: str,
*,
target_guest: str,
target_name: str = "",
reason: str,
detail: str = "",
) -> dict[str, Any]:
ensure_community_tables()
if guest_id == target_guest:
raise ValueError("不能举报自己")
reason = (reason or "").strip()[:80]
if not reason:
raise ValueError("请选择举报原因")
item = {
"id": _uid("rp"),
"guestId": guest_id,
"targetGuest": target_guest,
"targetName": (target_name or "").strip()[:64],
"reason": reason,
"detail": (detail or "").strip()[:1000],
"status": "open",
"createdAt": _now(),
}
rec = get_pb().create(
C_REPORTS,
{
"guest_id": guest_id,
"target_guest": target_guest,
"target_name": item["targetName"],
"reason": reason,
"detail": item["detail"],
"status": "open",
"result_note": "",
"created_at": item["createdAt"],
"resolved_at": "",
},
)
item["id"] = rec.get("id") or item["id"]
return item
def resolve_report(
report_id: str, *, status: str = "resolved", result_note: str = ""
) -> dict[str, Any]:
ensure_community_tables()
try:
r = get_pb().request(
"GET", f"/api/collections/{C_REPORTS}/records/{report_id}", admin=True
)
except Exception as exc:
raise ValueError("举报不存在") from exc
now = _now()
get_pb().update(
C_REPORTS,
report_id,
{
"status": status,
"result_note": (result_note or "").strip()[:500],
"resolved_at": now if status != "open" else "",
},
)
return {
"id": report_id,
"guestId": r.get("guest_id"),
"targetGuest": r.get("target_guest"),
"status": status,
"resultNote": result_note,
"resolvedAt": now,
}
def list_reports(*, status: str = "open", limit: int = 40) -> list[dict[str, Any]]:
ensure_community_tables()
limit = max(1, min(int(limit or 40), 100))
filt = f"status={pb_quote(status)}" if status else None
rows = get_pb().list_all(C_REPORTS, filter=filt, sort="-created_at", hard_limit=limit)
return [
{
"id": r.get("id"),
"guestId": r.get("guest_id"),
"targetGuest": r.get("target_guest"),
"targetName": r.get("target_name") or "",
"reason": r.get("reason"),
"detail": r.get("detail") or "",
"status": r.get("status"),
"resultNote": r.get("result_note") or "",
"createdAt": r.get("created_at"),
"resolvedAt": r.get("resolved_at") or "",
}
for r in rows
]
def wrapped_stats(guest_id: str, year: int | None = None) -> dict[str, Any]:
ensure_community_tables()
from datetime import datetime, timezone
y = year or datetime.now(timezone.utc).year
prefix = f"{y}-"
roster = pb_data.get_roster(guest_id) or {}
cities: list[str] = []
if roster.get("city"):
cities = [roster["city"]]
try:
from hub_svc import geo_pb
trips = geo_pb.list_trips_for_guest(guest_id) if hasattr(geo_pb, "list_trips_for_guest") else []
for t in trips or []:
c = t.get("city") or ""
if c and c not in cities:
cities.append(c)
except Exception:
pass
reviews = get_pb().list_all(
C_REVIEWS,
filter=f"(from_guest={pb_quote(guest_id)} || to_guest={pb_quote(guest_id)})",
hard_limit=500,
)
reviews = [r for r in reviews if str(r.get("created_at") or "").startswith(prefix)]
skills = get_pb().list_all(
C_SKILLS, filter=f"guest_id={pb_quote(guest_id)}", hard_limit=200
)
skills = [s for s in skills if str(s.get("created_at") or "").startswith(prefix)]
peers = set()
for r in reviews:
a, b = r.get("from_guest"), r.get("to_guest")
if a == guest_id and b:
peers.add(b)
elif b == guest_id and a:
peers.add(a)
return {
"year": y,
"name": roster.get("name") or "游民",
"homeCity": roster.get("city") or "",
"cities": cities[:24],
"cityCount": len(cities),
"peopleMet": len(peers),
"meetups": len(reviews),
"skillPosts": len(skills),
"livenessVerified": (roster.get("livenessStatus") or "") == "verified",
}
def city_digest_payload(city: str, limit: int = 8) -> dict[str, Any]:
ensure_community_tables()
city = (city or "").strip()
people = (
pb_data.list_discovery_roster(city=city, limit=limit) if city else []
)
skills = list_skill_posts(city=city, limit=5) if city else list_skill_posts(limit=5)
lines = []
for p in people[:5]:
lines.append(
f"· {p.get('name')} · {p.get('city') or city} · {p.get('lookingFor') or p.get('title') or ''}"
)
for s in skills[:3]:
lines.append(
f"· 互换:{s['offer']} ↔ {s['want']}({s.get('city') or '全球'})"
)
return {
"city": city or "全球",
"peopleCount": len(people),
"skillCount": len(skills),
"digestText": "\n".join(lines)
if lines
else "这周同城还比较安静,去发一条技能互换吧。",
}

View File

@ -0,0 +1,86 @@
from __future__ import annotations
import os
from pathlib import Path
# 默认写在仓库 data/hub,与 PocketBase / community 目录分离
_ROOT = Path(__file__).resolve().parents[4] # nomadro/
_DEFAULT_DB = _ROOT / "data" / "hub" / "hub.db"
HUB_DB_PATH = Path(os.getenv("HUB_DB_PATH", str(_DEFAULT_DB))).resolve()
HUB_UPLOAD_DIR = Path(
os.getenv("HUB_UPLOAD_DIR", str(HUB_DB_PATH.parent / "uploads"))
).resolve()
HUB_UPLOAD_MAX_BYTES = int(os.getenv("HUB_UPLOAD_MAX_BYTES", str(25 * 1024 * 1024)))
HUB_ENABLED = os.getenv("HUB_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
# Centrifugo(实时层;缺省关,部署后用环境变量打开)
CENTRIFUGO_ENABLED = os.getenv("CENTRIFUGO_ENABLED", "false").lower() in {"1", "true", "yes", "on"}
CENTRIFUGO_API_URL = os.getenv("CENTRIFUGO_API_URL", "http://127.0.0.1:8008/api").rstrip("/")
CENTRIFUGO_API_KEY = os.getenv("CENTRIFUGO_API_KEY", "")
CENTRIFUGO_TOKEN_SECRET = os.getenv("CENTRIFUGO_TOKEN_SECRET", "")
# 浏览器 WebSocket(经 nginx 反代,与门户同域)
CENTRIFUGO_WS_URL = os.getenv(
"CENTRIFUGO_WS_URL",
"wss://nomadro.cn/rt/connection/websocket",
)
# 原生音视频厅(SRS RTMP 推 / HTTP-FLV 拉)— 微信 LivePusher/LivePlayer
LIVE_RTMP_PUSH_BASE = os.getenv(
"LIVE_RTMP_PUSH_BASE",
"rtmp://82.157.112.245/live",
)
LIVE_HTTP_PLAY_BASE = os.getenv(
"LIVE_HTTP_PLAY_BASE",
"https://nomadro.cn/live",
)
LIVE_STREAM_SECRET = os.getenv(
"LIVE_STREAM_SECRET",
os.getenv("CENTRIFUGO_TOKEN_SECRET", "nomadro-live-dev-secret"),
)
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 — .com/US defaults to same-box 8090; never hardcode hackrobot.cn
try:
from nomadro_pb.config import ( # type: ignore
PB_ADMIN_EMAIL as _PB_EMAIL,
PB_ADMIN_PASSWORD as _PB_PASS,
PB_URL as _PB_URL,
)
PB_URL = _PB_URL
PB_ADMIN_EMAIL = _PB_EMAIL
PB_ADMIN_PASSWORD = _PB_PASS
except Exception:
_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 ""
)
HUB_TRIPS_COLLECTION = os.getenv("HUB_TRIPS_COLLECTION", "hub_trips")
HUB_GEO_USE_PB = os.getenv("HUB_GEO_USE_PB", "true").lower() in {
"1",
"true",
"yes",
"on",
}

View 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/hub/v1/*``
- Realtime: Centrifugo channel ``hub:{channelId}``(与 social_svc ``social:`` 隔离)
- Auth peer: header ``X-Hub-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",
)

View File

@ -0,0 +1,492 @@
"""Avatar face gate — detect + optional InsightFace RGB liveness.
Env / remote-config:
flags.hubAvatarFaceCheck admin SSE/WS switch (preferred)
HUB_AVATAR_FACE_CHECK on|off env fallback (default off)
HUB_AVATAR_FACE_ENGINE auto|insightface|opencv (default auto)
HUB_AVATAR_FACE_STRICT fail closed when no engine (default off)
HUB_AVATAR_FACE_MIN min faces (default 1)
HUB_AVATAR_FACE_MAX max faces (default 1 — reject group photos)
HUB_AVATAR_LIVENESS on|off (default on; InsightFace addon)
HUB_AVATAR_LIVENESS_THRESHOLD 0..1 (default 0.5)
HUB_AVATAR_INSIGHTFACE_MODEL buffalo_l|buffalo_sc (default buffalo_l)
"""
from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass
import cv2
import numpy as np
log = logging.getLogger("hub_svc.face_check")
_lock = threading.Lock()
_insight_app = None
_insight_failed = False
_insight_liveness = False
@dataclass
class FaceCheckResult:
ok: bool
faces: int
engine: str
detail: str = ""
is_live: bool | None = None
live_score: float | None = None
def _env_bool(name: str, default: bool) -> bool:
raw = (os.getenv(name) or "").strip().lower()
if not raw:
return default
return raw in {"1", "true", "yes", "on"}
def face_check_enabled(purpose: str) -> bool:
if (purpose or "").strip().lower() not in {"avatar", "roster", "profile"}:
return False
# Remote-config (admin SSE/WS) wins when present; env is offline fallback.
try:
from hub_svc.remote_flags import hub_avatar_face_check_enabled
remote = hub_avatar_face_check_enabled()
if remote is not None:
return bool(remote)
except Exception:
pass
# Default OFF for test phase; set HUB_AVATAR_FACE_CHECK=on to force without admin.
return _env_bool("HUB_AVATAR_FACE_CHECK", False)
def _engine_pref() -> str:
return (os.getenv("HUB_AVATAR_FACE_ENGINE") or "auto").strip().lower()
def _min_faces() -> int:
try:
return max(1, int(os.getenv("HUB_AVATAR_FACE_MIN") or "1"))
except ValueError:
return 1
def _max_faces() -> int:
try:
return max(_min_faces(), int(os.getenv("HUB_AVATAR_FACE_MAX") or "1"))
except ValueError:
return 1
def _liveness_on() -> bool:
return _env_bool("HUB_AVATAR_LIVENESS", True)
def _liveness_threshold() -> float:
try:
v = float(os.getenv("HUB_AVATAR_LIVENESS_THRESHOLD") or "0.5")
except ValueError:
v = 0.5
return min(0.99, max(0.05, v))
def _decode_bgr(data: bytes):
arr = np.frombuffer(data, dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
return img
def _providers() -> list[str]:
providers = ["CPUExecutionProvider"]
try:
from onnxruntime import get_available_providers
avail = set(get_available_providers())
if "CUDAExecutionProvider" in avail:
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
except Exception:
pass
return providers
def _get_insightface():
global _insight_app, _insight_failed, _insight_liveness
if _insight_failed:
return None
if _insight_app is not None:
return _insight_app
with _lock:
if _insight_failed:
return None
if _insight_app is not None:
return _insight_app
try:
from insightface.app import FaceAnalysis
name = (os.getenv("HUB_AVATAR_INSIGHTFACE_MODEL") or "buffalo_l").strip()
providers = _providers()
want_live = _liveness_on()
addons: tuple[str, ...] = ("liveness",) if want_live else ()
try:
app = FaceAnalysis(
name=name,
providers=providers,
addons=addons,
liveness_mode="normal",
liveness_threshold=_liveness_threshold(),
)
_insight_liveness = bool(addons) and "liveness" in app.addons
except Exception as live_exc:
# Model package without addon download — fall back to detection only
log.warning("insightface liveness init failed, detection-only: %s", live_exc)
app = FaceAnalysis(name=name, providers=providers)
_insight_liveness = False
ctx_id = 0 if providers[0].startswith("CUDA") else -1
app.prepare(ctx_id=ctx_id, det_size=(640, 640))
_insight_app = app
log.info(
"insightface ready model=%s providers=%s liveness=%s",
name,
providers,
_insight_liveness,
)
return _insight_app
except Exception as exc:
_insight_failed = True
log.warning("insightface unavailable: %s", exc)
return None
def _analyze_insightface(img) -> FaceCheckResult:
app = _get_insightface()
if app is None:
raise RuntimeError("insightface not loaded")
faces = app.get(img) or []
n = len(faces)
need = _min_faces()
cap = _max_faces()
if n < need:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface",
detail="未检测到人脸,请上传本人清晰正脸照片",
)
if n > cap:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface",
detail="请只上传一张本人正脸(不要合影)",
)
face = faces[0]
is_live = None
live_score = None
live = getattr(face, "liveness", None)
if live is not None:
is_live = getattr(live, "is_live", None)
try:
live_score = float(getattr(live, "live_score", None) or getattr(live, "score", 0) or 0)
except (TypeError, ValueError):
live_score = None
status = getattr(live, "status", None)
reason = getattr(live, "reason", None) or ""
if is_live is False:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail="未通过真人检测,请用前置摄像头现场自拍(勿用网图/截图)",
is_live=False,
live_score=live_score,
)
if status == "input_rejected":
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail=str(reason) or "人脸区域不足,请靠近镜头、露出完整正脸再拍",
is_live=False,
live_score=live_score,
)
if _liveness_on() and _insight_liveness and is_live is not True:
# Addon loaded but face missing live flag — treat as fail-closed
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail="真人检测未完成,请重新自拍一张正脸",
is_live=False,
live_score=live_score,
)
engine = "insightface+liveness" if is_live is True else "insightface"
return FaceCheckResult(
ok=True,
faces=n,
engine=engine,
is_live=is_live,
live_score=live_score,
)
def _haar_cascade_path() -> str:
from pathlib import Path
bundled = (
Path(__file__).resolve().parent
/ "assets"
/ "haarcascade_frontalface_default.xml"
)
if bundled.is_file():
return str(bundled)
data_dir = getattr(getattr(cv2, "data", None), "haarcascades", "") or ""
candidate = data_dir + "haarcascade_frontalface_default.xml"
if data_dir and Path(candidate).is_file():
return candidate
raise RuntimeError("haar cascade xml not found (bundle assets/)")
def _count_opencv(img) -> int:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
cascade = cv2.CascadeClassifier(_haar_cascade_path())
if cascade.empty():
raise RuntimeError("opencv haar cascade missing")
h, w = gray.shape[:2]
max_side = 960
if max(h, w) > max_side:
scale = max_side / float(max(h, w))
gray = cv2.resize(gray, (int(w * scale), int(h * scale)))
faces = cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(48, 48),
flags=cv2.CASCADE_SCALE_IMAGE,
)
return len(faces)
def check_face(
data: bytes,
*,
require_liveness: bool | None = None,
) -> FaceCheckResult:
"""Return face / liveness result; does not raise for soft failures.
require_liveness=None → follow HUB_AVATAR_LIVENESS_REQUIRE (legacy).
Album upload should pass require_liveness=False (presence only).
Live challenge uses require_liveness=True.
"""
img = _decode_bgr(data)
if img is None or img.size == 0:
return FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片")
want_live = (
_liveness_on() and _env_bool("HUB_AVATAR_LIVENESS_REQUIRE", True)
if require_liveness is None
else bool(require_liveness)
)
pref = _engine_pref()
engines: list[str] = []
if pref == "insightface":
engines = ["insightface"]
elif pref == "opencv":
engines = ["opencv"]
else:
engines = ["insightface", "opencv"]
last_err = ""
for eng in engines:
try:
if eng == "insightface":
result = _analyze_insightface(img)
if not want_live and result.faces >= _min_faces():
# Presence-only: keep face count even if RGB liveness failed
if not result.ok and result.faces > 0:
return FaceCheckResult(
ok=True,
faces=result.faces,
engine=result.engine or "insightface",
detail="人脸已识别,请继续现场实拍核验",
is_live=result.is_live,
live_score=result.live_score,
)
return result
n = _count_opencv(img)
need = _min_faces()
cap = _max_faces()
if n < need:
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="未检测到人脸,请上传本人清晰正脸照片",
)
if n > cap:
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="请只上传一张本人正脸(不要合影)",
)
if want_live and _liveness_on():
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="请用摄像头现场自拍以完成真人验证",
)
return FaceCheckResult(ok=True, faces=n, engine="opencv")
except Exception as exc:
last_err = str(exc)
log.warning("face engine %s failed: %s", eng, exc)
continue
# Fail closed: never stamp face_ok=true when no detector ran.
# Upload path still persists the file with face_ok=false when gate is off.
log.warning("face check unavailable (%s); marking no-face", last_err or "no engine")
return FaceCheckResult(
ok=False,
faces=0,
engine="none",
detail=f"人脸检测不可用: {last_err or 'no engine'}",
)
def assert_avatar_has_face(
data: bytes,
*,
require_liveness: bool | None = None,
) -> FaceCheckResult:
"""Raise ValueError when check fails."""
result = check_face(data, require_liveness=require_liveness)
if not result.ok:
raise ValueError(result.detail or "未检测到人脸")
return result
@dataclass
class ChallengeResult:
ok: bool
detail: str = ""
similarity: float | None = None
yaw_delta: float | None = None
front: FaceCheckResult | None = None
turn: FaceCheckResult | None = None
def _cosine(a, b) -> float:
a = np.asarray(a, dtype=np.float32).ravel()
b = np.asarray(b, dtype=np.float32).ravel()
denom = float(np.linalg.norm(a) * np.linalg.norm(b) + 1e-9)
return float(np.dot(a, b) / denom)
def _yaw_proxy(kps) -> float:
"""Nose offset vs eye midpoint, normalized by eye distance (≈ yaw proxy)."""
pts = np.asarray(kps, dtype=np.float32)
if pts.shape[0] < 3:
return 0.0
le, re, nose = pts[0], pts[1], pts[2]
mid_x = (float(le[0]) + float(re[0])) * 0.5
eye_w = abs(float(re[0]) - float(le[0])) + 1e-6
return (float(nose[0]) - mid_x) / eye_w
def _extract_face_features(data: bytes):
"""Return (FaceCheckResult, embedding|None, yaw|None)."""
img = _decode_bgr(data)
if img is None or img.size == 0:
return (
FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片"),
None,
None,
)
# Prefer insightface for embeddings; also runs liveness when enabled
try:
app = _get_insightface()
if app is None:
raise RuntimeError("insightface not loaded")
faces = app.get(img) or []
base = _analyze_insightface(img)
if not base.ok or not faces:
return base, None, None
face = faces[0]
emb = getattr(face, "normed_embedding", None)
if emb is None:
emb = getattr(face, "embedding", None)
yaw = _yaw_proxy(getattr(face, "kps", None)) if getattr(face, "kps", None) is not None else None
return base, emb, yaw
except Exception as exc:
log.warning("challenge feature extract failed: %s", exc)
# Fall back to presence-only (no identity match)
presence = check_face(data)
return presence, None, None
def verify_pose_challenge(front_bytes: bytes, turn_bytes: bytes) -> ChallengeResult:
"""Two-frame selfie: same person + measurable head turn + face/liveness gates."""
front, emb_a, yaw_a = _extract_face_features(front_bytes)
if not front.ok:
return ChallengeResult(ok=False, detail=front.detail or "正脸核验失败", front=front)
turn, emb_b, yaw_b = _extract_face_features(turn_bytes)
if not turn.ok:
return ChallengeResult(
ok=False,
detail=turn.detail or "转头照核验失败",
front=front,
turn=turn,
)
sim = None
if emb_a is not None and emb_b is not None:
sim = _cosine(emb_a, emb_b)
min_sim = 0.32
try:
min_sim = float(os.getenv("HUB_AVATAR_CHALLENGE_MIN_SIM") or "0.32")
except ValueError:
pass
if sim < min_sim:
return ChallengeResult(
ok=False,
detail="两张照片不是同一个人,请本人连续自拍完成核验",
similarity=sim,
front=front,
turn=turn,
)
yaw_delta = None
if yaw_a is not None and yaw_b is not None:
yaw_delta = abs(float(yaw_a) - float(yaw_b))
min_yaw = 0.06
try:
min_yaw = float(os.getenv("HUB_AVATAR_CHALLENGE_MIN_YAW") or "0.06")
except ValueError:
pass
if yaw_delta < min_yaw:
return ChallengeResult(
ok=False,
detail="转头幅度不够,请稍微左右转头后再拍第二张",
similarity=sim,
yaw_delta=yaw_delta,
front=front,
turn=turn,
)
return ChallengeResult(
ok=True,
detail="",
similarity=sim,
yaw_delta=yaw_delta,
front=front,
turn=turn,
)

View File

@ -0,0 +1,233 @@
"""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/hub/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,
},
]
# 国际城市(Hub 中文锁期间不进 SEED_CITIES)
SEED_CITIES_INTL: list[dict[str, Any]] = [
{
"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

View 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)

View File

@ -0,0 +1,330 @@
"""PocketBase `hub_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,
HUB_GEO_USE_PB,
HUB_TRIPS_COLLECTION,
)
log = logging.getLogger("hub_svc.geo_pb")
_token: str | None = None
_token_at = 0.0
_ensured = False
def pb_enabled() -> bool:
return bool(
HUB_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 `hub_trips` collection if missing."""
global _ensured
if _ensured:
return True
headers = _headers()
if not headers:
return False
base = PB_URL.rstrip("/")
name = HUB_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 hub_trips (guest_id)",
"CREATE INDEX idx_social_trips_city ON hub_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 = HUB_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 = HUB_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 = HUB_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

View 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]

View 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()),
}

View File

@ -0,0 +1,156 @@
"""游民社区原生音视频厅 — SRS RTMP 推流 + HTTP-FLV 拉流 + 房间信令。
微信小程序:LivePusher(pushUrl) + LivePlayer(playUrl)
门户 H5:仍可用 MiroTalk;本模块给 weapp 原生厅发流地址。
"""
from __future__ import annotations
import hashlib
import hmac
import os
import re
import threading
import time
from typing import Any
from hub_svc.config import (
LIVE_HTTP_PLAY_BASE,
LIVE_MAX_PEERS,
LIVE_PEER_TTL_SEC,
LIVE_RTMP_PUSH_BASE,
LIVE_STREAM_SECRET,
)
_lock = threading.RLock()
# room_id -> { peer_id: peer_dict }
_rooms: dict[str, dict[str, dict[str, Any]]] = {}
def _safe(s: str, n: int = 48) -> str:
t = re.sub(r"[^a-zA-Z0-9_-]+", "", (s or "").strip())[:n]
return t or "x"
def _sig(stream: str, exp: int) -> str:
raw = f"{stream}:{exp}".encode("utf-8")
return hmac.new(LIVE_STREAM_SECRET.encode("utf-8"), raw, hashlib.sha256).hexdigest()[:16]
def stream_name(room_id: str, peer_id: str) -> str:
return f"{_safe(room_id, 24)}_{_safe(peer_id, 24)}"
def build_urls(room_id: str, peer_id: str) -> dict[str, str]:
stream = stream_name(room_id, peer_id)
exp = int(time.time()) + 3600 * 6
token = _sig(stream, exp)
# 微信 LivePusher:RTMP url 勿带 query,否则真机常推流失败→本地黑屏
push = f"{LIVE_RTMP_PUSH_BASE.rstrip('/')}/{stream}"
# HTTP-FLV 拉流可带 token(nginx/SRS 忽略未知参数)
play = f"{LIVE_HTTP_PLAY_BASE.rstrip('/')}/{stream}.flv?e={exp}&k={token}"
return {"stream": stream, "pushUrl": push, "playUrl": play}
def _purge(room_id: str) -> None:
now = time.time()
room = _rooms.get(room_id) or {}
dead = [pid for pid, p in room.items() if now - float(p.get("seen", 0)) > LIVE_PEER_TTL_SEC]
for pid in dead:
room.pop(pid, None)
if not room:
_rooms.pop(room_id, None)
def list_peers(room_id: str) -> list[dict[str, Any]]:
with _lock:
_purge(room_id)
room = _rooms.get(room_id) or {}
return [
{
"peerId": p["peerId"],
"nick": p["nick"],
"playUrl": p["playUrl"],
"stream": p["stream"],
"seen": p["seen"],
}
for p in room.values()
]
def join_room(room_id: str, guest_id: str, nick: str) -> dict[str, Any]:
rid = _safe(room_id, 40)
gid = _safe(guest_id, 40)
name = (nick or "游民").strip()[:32] or "游民"
with _lock:
_purge(rid)
room = _rooms.setdefault(rid, {})
if gid not in room and len(room) >= LIVE_MAX_PEERS:
raise ValueError(f"厅已满(最多 {LIVE_MAX_PEERS} 人)")
urls = build_urls(rid, gid)
peer = {
"peerId": gid,
"nick": name,
"stream": urls["stream"],
"pushUrl": urls["pushUrl"],
"playUrl": urls["playUrl"],
"seen": time.time(),
"joinedAt": time.time(),
}
room[gid] = peer
peers = [
{
"peerId": p["peerId"],
"nick": p["nick"],
"playUrl": p["playUrl"],
"stream": p["stream"],
}
for pid, p in room.items()
if pid != gid
]
return {
"ok": True,
"roomId": rid,
"peerId": gid,
"nick": name,
"pushUrl": urls["pushUrl"],
"playUrl": urls["playUrl"],
"stream": urls["stream"],
"peers": peers,
"maxPeers": LIVE_MAX_PEERS,
"channelId": f"live-{rid}",
"engine": "srs-rtmp-flv",
}
def heartbeat(room_id: str, guest_id: str) -> dict[str, Any]:
rid = _safe(room_id, 40)
gid = _safe(guest_id, 40)
with _lock:
_purge(rid)
room = _rooms.get(rid) or {}
me = room.get(gid)
if not me:
raise ValueError("未在厅内,请重新进入")
me["seen"] = time.time()
peers = [
{
"peerId": p["peerId"],
"nick": p["nick"],
"playUrl": p["playUrl"],
"stream": p["stream"],
}
for pid, p in room.items()
if pid != gid
]
return {"ok": True, "roomId": rid, "peers": peers, "peerCount": len(peers) + 1}
def leave_room(room_id: str, guest_id: str) -> dict[str, Any]:
rid = _safe(room_id, 40)
gid = _safe(guest_id, 40)
with _lock:
room = _rooms.get(rid) or {}
room.pop(gid, None)
if not room:
_rooms.pop(rid, None)
return {"ok": True, "roomId": rid}

View File

@ -0,0 +1,201 @@
"""Fire Novu-domain notify_svc events from social (likes, coffee, board, city, rooms)."""
from __future__ import annotations
import json
import logging
import os
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
log = logging.getLogger("hub_svc.notify_bridge")
NOTIFY_INTERNAL_URL = os.getenv(
"NOTIFY_INTERNAL_URL",
os.getenv("NOTIFY_API_URL", "http://127.0.0.1:8023"),
).rstrip("/")
def _request(
method: str,
path: str,
body: dict[str, Any] | None = None,
timeout: float = 4.0,
) -> dict[str, Any] | None:
url = f"{NOTIFY_INTERNAL_URL}{path}"
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json"}
token = os.getenv('NOTIFY_INTERNAL_TOKEN')
if token: headers['X-Notify-Internal-Token'] = token
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
raw = res.read().decode("utf-8", errors="replace")
return json.loads(raw) if raw else {}
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc:
log.warning("notify %s %s failed: %s", method, path, exc)
return None
def ensure_subscriber(guest_id: str, name: str = "游民") -> None:
_request(
"POST",
"/api/notify/v1/subscribers",
{"subscriber_id": guest_id, "first_name": (name or "游民")[:40]},
)
def in_quiet_hours(channels: dict[str, Any] | None, *, dnd: bool = False) -> bool:
if dnd:
return True
if not channels:
return False
start = str(channels.get("quiet_start") or "").strip()
end = str(channels.get("quiet_end") or "").strip()
if not start or not end:
return False
tz_name = str(channels.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai"
try:
tz = ZoneInfo(tz_name)
except Exception:
tz = ZoneInfo("Asia/Shanghai")
now = datetime.now(tz)
try:
sh, sm = [int(x) for x in start.split(":")[:2]]
eh, em = [int(x) for x in end.split(":")[:2]]
except Exception:
return False
minutes = now.hour * 60 + now.minute
a = sh * 60 + sm
b = eh * 60 + em
if a == b:
return False
if a < b:
return a <= minutes < b
return minutes >= a or minutes < b
def _load_prefs(subscriber_id: str) -> tuple[dict[str, Any], bool]:
raw = _request(
"GET",
f"/api/notify/v1/subscribers/{urllib.parse.quote(subscriber_id)}/preferences",
)
if not raw:
return {}, False
prefs = raw.get("preferences") or raw
channels = prefs.get("channels") if isinstance(prefs.get("channels"), dict) else prefs
if not isinstance(channels, dict):
channels = {}
dnd = bool(prefs.get("dnd") or channels.get("dnd"))
return channels, dnd
def trigger(
workflow_id: str,
subscriber_id: str,
payload: dict[str, Any] | None = None,
*,
name: str = "游民",
respect_quiet: bool = True,
) -> dict[str, Any] | None:
ensure_subscriber(subscriber_id, name)
channels, dnd = _load_prefs(subscriber_id)
payload = dict(payload or {})
if respect_quiet and in_quiet_hours(channels, dnd=dnd):
payload["quietHours"] = True
return _request(
"POST",
"/api/notify/v1/events/trigger",
{
"workflow_id": workflow_id,
"subscriber_id": subscriber_id,
"payload": {**payload, "category": payload.get("category") or "social"},
},
)
def notify_like(to_guest: str, from_name: str) -> None:
trigger(
"social-like",
to_guest,
{"actor": from_name, "firstName": from_name, "ctaUrl": "/hub/people"},
name=from_name,
)
def notify_coffee_invite(to_guest: str, host_name: str, title: str) -> None:
trigger(
"coffee-invite",
to_guest,
{"firstName": host_name, "title": title, "ctaUrl": "/hub/coffeechat"},
name=host_name,
)
def notify_board_join(owner_guest: str, actor_name: str, board_title: str) -> None:
trigger(
"board-join",
owner_guest,
{
"firstName": actor_name,
"title": board_title,
"category": "project",
"ctaUrl": "/hub/work/boards",
},
name=actor_name,
)
def notify_city_online(to_guest: str, city: str, peer_name: str) -> None:
trigger(
"city-online",
to_guest,
{"firstName": peer_name, "city": city, "ctaUrl": "/hub/people"},
name=peer_name,
)
def notify_room_live(to_guest: str, room_title: str) -> None:
trigger(
"room-live",
to_guest,
{"title": room_title, "ctaUrl": "/hub/meetup"},
)
def notify_report_result(reporter_guest: str, note: str, status: str) -> None:
trigger(
"report-result",
reporter_guest,
{
"status": status,
"resultNote": note,
"category": "system",
"ctaUrl": "/hub/notifications",
},
respect_quiet=False,
)
def fire_city_digest(
subscriber_id: str,
city: str,
digest_text: str,
*,
weekly: bool = False,
) -> None:
trigger(
"city-digest-weekly" if weekly else "city-digest-daily",
subscriber_id,
{
"city": city,
"digestText": digest_text,
"firstName": "游民",
"ctaUrl": "/hub/people",
},
)

View File

@ -0,0 +1,132 @@
"""Cold-start: welcome + same-city recommendations via notify_svc (Novu-domain)."""
from __future__ import annotations
import logging
import os
from typing import Any
import urllib.error
import urllib.request
import json
log = logging.getLogger("hub_svc.onboarding")
NOTIFY_INTERNAL_URL = os.getenv(
"NOTIFY_INTERNAL_URL",
os.getenv("NOTIFY_API_URL", "http://127.0.0.1:8023"),
).rstrip("/")
NOTIFY_ONBOARDING_ENABLED = os.getenv("HUB_ONBOARDING_NOTIFY", "true").lower() in {
"1",
"true",
"yes",
"on",
}
def _post(path: str, body: dict[str, Any], timeout: float = 4.0) -> dict[str, Any] | None:
url = f"{NOTIFY_INTERNAL_URL}{path}"
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={"Content-Type": "application/json", "Accept": "application/json", "X-Notify-Internal-Token": os.getenv('NOTIFY_INTERNAL_TOKEN', '')},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
raw = res.read().decode("utf-8", errors="replace")
return json.loads(raw) if raw else {}
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc:
log.warning("notify call failed %s: %s", path, exc)
return None
def ensure_subscriber(guest_id: str, name: str) -> None:
first = (name or "游民").strip()[:40] or "游民"
_post(
"/api/notify/v1/subscribers",
{
"subscriber_id": guest_id,
"first_name": first,
"data": {"source": "social-join"},
},
)
def fire_join_onboarding(
*,
guest_id: str,
name: str,
city: str,
recs: list[dict[str, Any]],
) -> dict[str, Any]:
"""First-profile hooks: welcome + up to 3 same-city cards into in-app inbox."""
if not NOTIFY_ONBOARDING_ENABLED:
return {"ok": False, "skipped": "disabled"}
ensure_subscriber(guest_id, name)
first = (name or "游民").strip()[:40] or "游民"
city_label = (city or "").strip() or "同城"
welcome = _post(
"/api/notify/v1/events/trigger",
{
"workflow_id": "welcome-onboarding",
"subscriber_id": guest_id,
"payload": {
"firstName": first,
"city": city_label,
"category": "social",
},
},
)
lines: list[str] = []
for i, r in enumerate(recs[:3], start=1):
n = str(r.get("name") or "游民").strip()
c = str(r.get("city") or city_label).strip()
t = str(r.get("title") or r.get("lookingFor") or "").strip()
bit = f"{i}. {n} · {c}"
if t:
bit += f" · {t[:40]}"
lines.append(bit)
recs_text = "\n".join(lines) if lines else "暂时还没有同城推荐,先去「想见的人」逛逛。"
# Reuse welcome workflow shape by posting a direct social tip via a second trigger
# with city-recs-onboarding if present; otherwise welcome payload is enough + inbox CTA.
recs_result = _post(
"/api/notify/v1/events/trigger",
{
"workflow_id": "city-recs-onboarding",
"subscriber_id": guest_id,
"payload": {
"firstName": first,
"city": city_label,
"recsText": recs_text,
"category": "social",
"count": len(recs[:3]),
},
},
)
# Fallback: if city-recs workflow missing, inject via welcome-style trigger body in activity only
if recs_result is None and lines:
_post(
"/api/notify/v1/events/trigger",
{
"workflow_id": "welcome-onboarding",
"subscriber_id": guest_id,
"payload": {
"firstName": first,
"city": city_label,
"category": "social",
"recsText": recs_text,
},
},
)
return {
"ok": True,
"welcome": bool(welcome),
"recs": len(recs[:3]),
"recsText": recs_text,
}

File diff suppressed because it is too large Load Diff

View 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("hub_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

View File

@ -0,0 +1,108 @@
"""Centrifugo publish + connection JWT for 游民社区聊天."""
from __future__ import annotations
import logging
import time
from typing import Any
import httpx
import jwt
from hub_svc.config import (
CENTRIFUGO_API_KEY,
CENTRIFUGO_API_URL,
CENTRIFUGO_ENABLED,
CENTRIFUGO_TOKEN_SECRET,
CENTRIFUGO_WS_URL,
)
log = logging.getLogger("hub_svc.realtime")
_http: httpx.AsyncClient | None = None
def _client() -> httpx.AsyncClient:
global _http
if _http is None or _http.is_closed:
_http = httpx.AsyncClient(timeout=3.0)
return _http
def channel_name(channel_id: str) -> str:
"""Centrifugo channel — hub: 前缀与 social_svc 的 social: 隔离。"""
cid = (channel_id or "").strip() or "lobby"
if cid.startswith("hub:") or cid.startswith("social:"):
# 已带命名空间则原样(兼容旧客户端短暂双前缀)
if cid.startswith("social:"):
return "hub:" + cid[len("social:") :]
return cid
return f"hub:{cid}"
def issue_connection_token(guest_id: str, channel_id: str | None = None) -> dict[str, Any]:
"""Return client connection info. Disabled → ok=false (前端降级轮询)."""
if not CENTRIFUGO_ENABLED or not CENTRIFUGO_TOKEN_SECRET:
return {
"ok": False,
"enabled": False,
"wsUrl": CENTRIFUGO_WS_URL,
"token": "",
"channel": channel_name(channel_id or "lobby"),
}
now = int(time.time())
payload: dict[str, Any] = {
"sub": guest_id[:80],
"iat": now,
"exp": now + 60 * 60 * 12,
}
token = jwt.encode(payload, CENTRIFUGO_TOKEN_SECRET, algorithm="HS256")
if isinstance(token, bytes):
token = token.decode("utf-8")
return {
"ok": True,
"enabled": True,
"wsUrl": CENTRIFUGO_WS_URL,
"token": token,
"channel": channel_name(channel_id or "lobby"),
}
async def _publish(channel_id: str, data: dict[str, Any]) -> bool:
if not CENTRIFUGO_ENABLED or not CENTRIFUGO_API_KEY:
return False
url = CENTRIFUGO_API_URL.rstrip("/") + "/publish"
body = {"channel": channel_name(channel_id), "data": data}
try:
res = await _client().post(
url,
headers={"X-API-Key": CENTRIFUGO_API_KEY, "Content-Type": "application/json"},
json=body,
)
if res.status_code >= 400:
log.warning("centrifugo publish %s: %s", res.status_code, res.text[:200])
return False
return True
except Exception as e: # pragma: no cover
log.warning("centrifugo publish failed: %s", e)
return False
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 hub_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})

View File

@ -0,0 +1,112 @@
"""Read portal remote-config flags for hub_svc (avatar face gate, etc.)."""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Any
_CACHE: dict[str, Any] = {"ts": 0.0, "flags": {}, "copy": {}, "raw": {}}
_TTL_SEC = 2.0
DEFAULT_HUB_TRIAL = {
"enabled": True,
"chatMessages": 1,
"dateViews": 5,
"coffeeBookings": 0,
"mapOpens": 3,
}
def _candidate_paths() -> list[Path]:
env = (os.getenv("NOMADR_REMOTE_CONFIG") or os.getenv("REMOTE_CONFIG_PATH") or "").strip()
out: list[Path] = []
if env:
out.append(Path(env))
# .com primary first, then .cn mirror
out.append(Path("/var/www/nomadro.com/data/remote-config.json"))
out.append(Path("/var/www/nomadro.cn/data/remote-config.json"))
here = Path(__file__).resolve()
# apps/api/services/hub_svc → repo root
for up in (4, 5, 3):
try:
root = here.parents[up]
except IndexError:
continue
out.append(root / "data" / "remote-config.json")
seen: set[str] = set()
uniq: list[Path] = []
for p in out:
k = str(p)
if k not in seen:
seen.add(k)
uniq.append(p)
return uniq
def _load_remote() -> dict[str, Any]:
now = time.time()
if now - float(_CACHE.get("ts") or 0) < _TTL_SEC:
return {
"flags": dict(_CACHE.get("flags") or {}),
"copy": dict(_CACHE.get("copy") or {}),
}
for path in _candidate_paths():
try:
if not path.is_file():
continue
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
continue
flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
# Fallback: copy.hubFlags.features.avatarFaceCheck
if "hubAvatarFaceCheck" not in flags:
sf = copy.get("hubFlags") if isinstance(copy.get("hubFlags"), dict) else {}
feat = sf.get("features") if isinstance(sf.get("features"), dict) else {}
if "avatarFaceCheck" in feat:
flags = {**flags, "hubAvatarFaceCheck": bool(feat.get("avatarFaceCheck"))}
_CACHE["ts"] = now
_CACHE["flags"] = flags
_CACHE["copy"] = copy
_CACHE["raw"] = raw
return {"flags": dict(flags), "copy": dict(copy)}
except Exception:
continue
_CACHE["ts"] = now
_CACHE["flags"] = {}
_CACHE["copy"] = {}
return {"flags": {}, "copy": {}}
def _load_flags() -> dict[str, Any]:
return _load_remote()["flags"]
def hub_avatar_face_check_enabled() -> bool | None:
"""Return True/False from remote-config, or None if unset (caller uses env)."""
flags = _load_flags()
if "hubAvatarFaceCheck" not in flags:
return None
return bool(flags.get("hubAvatarFaceCheck"))
def hub_trial_limits() -> dict[str, Any]:
"""Chat/date/coffee/map trial caps for unpaid guests."""
packed = _load_remote()
flags = packed["flags"]
copy = packed["copy"]
raw = copy.get("hubTrial") if isinstance(copy.get("hubTrial"), dict) else {}
out = dict(DEFAULT_HUB_TRIAL)
if "enabled" in raw:
out["enabled"] = bool(raw["enabled"])
if "hubTrialEnabled" in flags:
out["enabled"] = bool(flags.get("hubTrialEnabled"))
for k in ("chatMessages", "dateViews", "coffeeBookings", "mapOpens"):
if k in raw and raw[k] is not None:
try:
out[k] = max(0, int(raw[k]))
except (TypeError, ValueError):
pass
return out

View File

@ -0,0 +1,10 @@
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"]

File diff suppressed because it is too large Load Diff

View 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 hub_svc import geo_store, photon
from hub_svc.config import HUB_ENABLED
from hub_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-Hub-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 HUB_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 HUB_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 HUB_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 HUB_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-Hub-Guest-Id"),
guest_id: str | None = Query(default=None),
):
if not HUB_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-Hub-Guest-Id"),
guest_id: str | None = Query(default=None),
):
if not HUB_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-Hub-Guest-Id"),
):
if not HUB_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-Hub-Guest-Id"),
):
if not HUB_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-Hub-Guest-Id"),
):
if not HUB_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}

View File

@ -0,0 +1,235 @@
"""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 hub_svc.config import HUB_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")
)
_boto = None
def _client():
global _boto
if _boto is not None:
return _boto
import boto3
from botocore.client import Config
_boto = 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"}),
)
return _boto
_RESUME_SUFFIX = {".pdf", ".doc", ".docx", ".txt", ".rtf", ".png", ".jpg", ".jpeg", ".webp"}
_RESUME_MIME = {
".pdf": "application/pdf",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".txt": "text/plain",
".rtf": "application/rtf",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
}
def _allow_resume(purpose: str) -> bool:
return (purpose or "").strip().lower() in {"resume", "cv", "gig-resume"}
def _object_key(filename: str, purpose: str, guest_id: str) -> str:
suffix = Path(filename or "upload.bin").suffix.lower() or ".jpg"
img_ok = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
vid_ok = {".webm", ".mp4", ".mov", ".m4v", ".mkv", ".ogg"}
allow_video = (purpose or "").startswith("liveness") or purpose in {
"liveness-video",
"audit-video",
"room-archive",
"meetup-archive",
}
allow_resume = _allow_resume(purpose)
if suffix in img_ok:
pass
elif allow_resume and suffix in _RESUME_SUFFIX:
pass
elif allow_video and suffix in vid_ok:
pass
elif allow_video:
suffix = ".webm"
elif allow_resume:
suffix = ".pdf"
else:
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)")
guessed = mimetypes.guess_type(filename or "")[0] or ""
ctype = (content_type or "").strip().lower() or guessed or "image/jpeg"
suffix = Path(filename or "").suffix.lower()
allow_video = (purpose or "").startswith("liveness") or purpose in {
"liveness-video",
"audit-video",
"room-archive",
"meetup-archive",
}
allow_resume = _allow_resume(purpose)
# Browser FormData Blob parts often arrive as application/octet-stream
if ctype.startswith("image/"):
pass
elif allow_resume and (
suffix in _RESUME_SUFFIX
or ctype in {
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/rtf",
"text/plain",
"application/octet-stream",
}
):
if suffix not in _RESUME_SUFFIX:
# octet-stream without extension → treat as pdf
suffix = ".pdf"
ctype = _RESUME_MIME.get(suffix) or guessed or "application/pdf"
elif allow_video and (
ctype.startswith("video/")
or suffix in {".webm", ".mp4", ".mov", ".mkv"}
or guessed.startswith("video/")
):
if not ctype.startswith("video/"):
ctype = guessed if guessed.startswith("video/") else (
"video/webm" if suffix in {".webm", ""} else f"video/{suffix[1:] or 'mp4'}"
)
elif not ctype.startswith("image/"):
if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"} or guessed.startswith(
"image/"
):
ctype = guessed if guessed.startswith("image/") else (
"image/jpeg" if suffix in {".jpg", ".jpeg", ""} else f"image/{suffix[1:]}"
)
else:
raise ValueError(
"only resume files allowed"
if allow_resume
else ("only images allowed" if not allow_video else "only images/videos allowed")
)
key = _object_key(filename, purpose, guest_id)
if s3_enabled():
bucket = _env("S3_BUCKET", default="nomadweb")
client = _client()
try:
# SeaweedFS often rejects canned ACL — skip ACL for lower latency
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)
# Live audit assets never land in avatars/
if (purpose or "") in {"room-archive", "meetup-archive"}:
sub = "room-archive"
elif allow_resume:
sub = "resumes"
elif (
allow_video
or ctype.startswith("video/")
or (purpose or "").startswith("liveness")
):
sub = "liveness"
else:
sub = "avatars"
path = HUB_UPLOAD_DIR / sub / Path(key).name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
if sub == "liveness":
route = "liveness"
elif sub == "resumes":
route = "resume"
else:
route = "avatar"
return UploadResult(
url=f"/api/hub/v1/files/{route}/{path.name}",
object_key=str(path),
size=len(data),
content_type=ctype,
storage="local",
)

View File

@ -0,0 +1,300 @@
# -*- coding: utf-8 -*-
"""Admin security denylist — email / guest / IP bans (PB hub_archives SoT).
Entity: hub_archives where entity="security_denylist"
entity_id: primary key (usually email lowercase)
payload: { email, qq, guestIds[], ips[], reason, active, at }
"""
from __future__ import annotations
import time
from typing import Any
from nomadro_pb.client import pb_quote
ENTITY = "security_denylist"
C_ARCHIVES = "hub_archives"
# Process cache — refresh every 30s (fail-open on PB outage after seed)
_CACHE: dict[str, Any] = {"at": 0.0, "emails": set(), "guests": set(), "ips": set(), "rows": []}
_TTL = 30.0
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _pb():
from hub_svc.pb_data import get_pb, init_pb
init_pb()
return get_pb()
def _norm_email(email: str) -> str:
return (email or "").strip().lower()[:160]
def _norm_ip(ip: str) -> str:
return (ip or "").strip().split("%")[0][:64]
def _seed_from_rows(rows: list[dict[str, Any]]) -> None:
emails: set[str] = set()
guests: set[str] = set()
ips: set[str] = set()
active_rows: list[dict[str, Any]] = []
for r in rows:
payload = r.get("payload") if isinstance(r.get("payload"), dict) else {}
if payload.get("active") is False:
continue
email = _norm_email(str(payload.get("email") or r.get("entity_id") or ""))
if email:
emails.add(email)
qq = str(payload.get("qq") or "").strip()
if qq and "@" not in qq:
emails.add(f"{qq}@qq.com")
for g in payload.get("guestIds") or []:
g = str(g or "").strip()
if g:
guests.add(g)
gid = str(r.get("guest_id") or "").strip()
if gid and gid.startswith("guest_"):
guests.add(gid)
for ip in payload.get("ips") or payload.get("ips_suspected") or []:
ip_n = _norm_ip(str(ip))
if ip_n:
ips.add(ip_n)
active_rows.append(r)
_CACHE["emails"] = emails
_CACHE["guests"] = guests
_CACHE["ips"] = ips
_CACHE["rows"] = active_rows
_CACHE["at"] = time.monotonic()
def refresh_denylist(*, force: bool = False) -> dict[str, Any]:
now = time.monotonic()
if not force and _CACHE["at"] and (now - float(_CACHE["at"])) < _TTL:
return {
"emails": set(_CACHE["emails"]),
"guests": set(_CACHE["guests"]),
"ips": set(_CACHE["ips"]),
"count": len(_CACHE["rows"]),
}
try:
rows = _pb().list_all(
C_ARCHIVES,
filter=f'entity="{ENTITY}"',
sort="-created_at",
hard_limit=2000,
)
_seed_from_rows(rows)
except Exception:
# Keep last good cache; empty only if never loaded
if not _CACHE["at"]:
_CACHE["at"] = now
return {
"emails": set(_CACHE["emails"]),
"guests": set(_CACHE["guests"]),
"ips": set(_CACHE["ips"]),
"count": len(_CACHE["rows"]),
}
def snapshot() -> dict[str, Any]:
return refresh_denylist(force=False)
def is_denied(
*,
email: str = "",
guest_id: str = "",
ip: str = "",
) -> dict[str, Any] | None:
"""Return hit detail if denied, else None."""
snap = snapshot()
email_n = _norm_email(email)
guest_n = (guest_id or "").strip()
ip_n = _norm_ip(ip)
reasons: list[str] = []
if email_n and email_n in snap["emails"]:
reasons.append(f"email:{email_n}")
# qq@x without full email — also match local-part@qq.com pattern already seeded
if email_n and "@" in email_n:
local = email_n.split("@", 1)[0]
if local.isdigit() and f"{local}@qq.com" in snap["emails"] and email_n != f"{local}@qq.com":
# only exact email match for non-qq aliases
pass
if guest_n and guest_n in snap["guests"]:
reasons.append(f"guest:{guest_n}")
if ip_n and ip_n in snap["ips"]:
reasons.append(f"ip:{ip_n}")
if not reasons:
return None
return {"denied": True, "reasons": reasons}
def assert_not_denied(*, email: str = "", guest_id: str = "", ip: str = "") -> None:
hit = is_denied(email=email, guest_id=guest_id, ip=ip)
if hit:
raise ValueError("账号已被封禁,无法继续操作")
def list_denylist(*, limit: int = 200) -> dict[str, Any]:
refresh_denylist(force=True)
items = []
for r in _CACHE["rows"][: max(1, min(int(limit or 200), 500))]:
payload = r.get("payload") if isinstance(r.get("payload"), dict) else {}
items.append(
{
"id": r.get("id"),
"email": payload.get("email") or r.get("entity_id") or "",
"qq": payload.get("qq") or "",
"guestIds": list(payload.get("guestIds") or []),
"ips": list(payload.get("ips") or payload.get("ips_suspected") or []),
"reason": payload.get("reason") or "",
"active": payload.get("active") is not False,
"at": payload.get("at") or r.get("created_at") or "",
}
)
return {"ok": True, "items": items, "total": len(items)}
def ban(
*,
email: str,
reason: str = "",
guest_ids: list[str] | None = None,
ips: list[str] | None = None,
qq: str = "",
) -> dict[str, Any]:
email_n = _norm_email(email)
if not email_n or "@" not in email_n:
raise ValueError("invalid email")
now = _now()
guests = [str(g).strip() for g in (guest_ids or []) if str(g).strip()]
ip_list = [_norm_ip(i) for i in (ips or []) if _norm_ip(i)]
qq_n = (qq or "").strip() or (email_n.split("@", 1)[0] if email_n.endswith("@qq.com") else "")
reason_n = (reason or f"admin ban {email_n}").strip()[:500]
payload = {
"email": email_n,
"qq": qq_n,
"guestIds": guests,
"ips": ip_list,
"ips_suspected": ip_list,
"reason": reason_n,
"active": True,
"at": now,
}
pb = _pb()
existing = pb.first(
C_ARCHIVES,
filter=f'entity="{ENTITY}" && entity_id={pb_quote(email_n)}',
)
if existing:
old = existing.get("payload") if isinstance(existing.get("payload"), dict) else {}
merged_guests = list({*list(old.get("guestIds") or []), *guests})
merged_ips = list(
{
*[_norm_ip(x) for x in (old.get("ips") or old.get("ips_suspected") or []) if x],
*ip_list,
}
)
payload["guestIds"] = merged_guests
payload["ips"] = merged_ips
payload["ips_suspected"] = merged_ips
if not payload.get("reason") and old.get("reason"):
payload["reason"] = old.get("reason")
primary_guest = qq_n or (guests[0] if guests else "")
rec = pb.update(
C_ARCHIVES,
str(existing["id"]),
{"action": "ban", "guest_id": primary_guest, "payload": payload},
)
else:
primary_guest = qq_n or (guests[0] if guests else "")
rec = pb.create(
C_ARCHIVES,
{
"entity": ENTITY,
"entity_id": email_n,
"action": "ban",
"guest_id": primary_guest,
"payload": payload,
"created_at": now,
},
)
# also mark join lead + hide roster guests
try:
from hub_svc import pb_data
lead = pb.first("hub_join_leads", filter=f"email={pb_quote(email_n)}")
if lead:
old_p = lead.get("payload") if isinstance(lead.get("payload"), dict) else {}
pb.update(
"hub_join_leads",
str(lead["id"]),
{
"stage": "blocked",
"payload": {**old_p, "blocked": True, "blockedReason": reason_n, "blockedAt": now},
"updated_at": now,
},
)
gid = str(lead.get("guest_id") or "").strip()
if gid and gid not in guests:
guests.append(gid)
for gid in guests:
row = pb_data.get_roster(gid)
if row and row.get("id"):
pb.update(
"hub_roster",
str(row["id"]),
{"status": "offline", "discoverable": False, "updated_at": now},
)
else:
# get_roster returns public shape without id — fetch raw
raw = pb.first("hub_roster", filter=f"guest_id={pb_quote(gid)}")
if raw:
pb.update(
"hub_roster",
str(raw["id"]),
{"status": "offline", "discoverable": False, "updated_at": now},
)
try:
pb.upsert(
"hub_blocks",
filter=f'guest_id="admin_system" && blocked_guest={pb_quote(gid)}',
payload={
"guest_id": "admin_system",
"blocked_guest": gid,
"reason": reason_n,
"created_at": now,
},
)
except Exception:
pass
except Exception:
pass
refresh_denylist(force=True)
return {"ok": True, "id": rec.get("id"), "email": email_n, "payload": payload}
def unban(*, email: str) -> dict[str, Any]:
email_n = _norm_email(email)
if not email_n:
raise ValueError("invalid email")
pb = _pb()
existing = pb.first(
C_ARCHIVES,
filter=f'entity="{ENTITY}" && entity_id={pb_quote(email_n)}',
)
if not existing:
return {"ok": True, "email": email_n, "active": False, "note": "not_found"}
payload = existing.get("payload") if isinstance(existing.get("payload"), dict) else {}
payload = dict(payload)
payload["active"] = False
payload["unbannedAt"] = _now()
pb.update(C_ARCHIVES, str(existing["id"]), {"action": "unban", "payload": payload})
refresh_denylist(force=True)
return {"ok": True, "email": email_n, "active": False}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
"""Server-side social trial gates — unpaid guests cannot bypass client caps."""
from __future__ import annotations
from hub_svc.remote_flags import hub_trial_limits
def _paid_ok(raw: object) -> bool:
return str(raw or "").strip().lower() in {"1", "true", "yes", "paid"}
def _guest_is_full_member(guest_id: str) -> bool:
"""Paid join + verified liveness + roster avatar → unlimited."""
gid = (guest_id or "").strip()
if not gid:
return False
try:
from hub_svc.pb_data import (
C_JOIN_LEADS,
get_pb,
get_roster,
init_pb,
pb_quote,
)
init_pb()
roster = get_roster(gid) or {}
avatar = str(roster.get("avatar") or "").strip()
live = str(
roster.get("livenessStatus") or roster.get("liveness_status") or ""
).strip()
if not avatar or live != "verified":
return False
rows = get_pb().list_all(
C_JOIN_LEADS,
filter=f"guest_id={pb_quote(gid)}",
hard_limit=40,
)
for row in rows or []:
if _paid_ok(row.get("paid")):
return True
return False
except Exception:
return False
def count_guest_messages(guest_id: str, *, hard_limit: int = 50) -> int:
gid = (guest_id or "").strip()
if not gid:
return 0
try:
from hub_svc.pb_data import C_MESSAGES, get_pb, init_pb, pb_quote
init_pb()
rows = get_pb().list_all(
C_MESSAGES,
filter=f"guest_id={pb_quote(gid)}",
hard_limit=hard_limit,
)
return len(rows or [])
except Exception:
return 0
def assert_chat_trial_ok(guest_id: str) -> None:
"""Raise ValueError if unpaid guest already used chat trial quota."""
limits = hub_trial_limits()
if not limits.get("enabled", True):
return
if _guest_is_full_member(guest_id):
return
cap = int(limits.get("chatMessages") or 0)
if cap <= 0:
raise ValueError("trial exhausted: chat requires membership")
used = count_guest_messages(guest_id, hard_limit=cap + 5)
if used >= cap:
raise ValueError("trial exhausted: chat message limit reached")

View File

@ -0,0 +1,67 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import BlogPostClient from "@hub/components/blog/BlogPostClient";
import { getBlogPost, listBlogPosts, listBlogSlugs } from "@hub/lib/blog/catalog";
import { resolveBlogAdSense } from "@hub/lib/blog/adsense";
import { blogPostingJsonLd } from "@hub/lib/blog/jsonld";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
type Props = { params: Promise<{ slug: string }> };
export async function generateStaticParams() {
return listBlogSlugs().map((slug) => ({ slug }));
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const post = getBlogPost(slug);
if (!post) return { title: "Not found" };
const url = `https://nomadro.com/hub/blog/${post.slug}`;
return {
title: `${post.title} | Nomadro Blog`,
description: post.description,
alternates: { canonical: url },
openGraph: {
title: post.title,
description: post.description,
url,
type: "article",
publishedTime: post.date,
modifiedTime: post.updated || post.date,
authors: [post.author || "Nomadro"],
tags: post.tags,
siteName: "Nomadro",
},
twitter: {
card: "summary_large_image",
title: post.title,
description: post.description,
},
robots: { index: true, follow: true },
};
}
export default async function HubBlogPostPage({ params }: Props) {
const { slug } = await params;
const post = getBlogPost(slug);
if (!post) notFound();
const related = listBlogPosts({ locale: post.locale })
.filter((p) => p.slug !== post.slug)
.filter((p) => p.tags.some((t) => post.tags.includes(t)))
.slice(0, 3);
const config = await readRemoteConfigFile().catch(() => null);
const adsense = resolveBlogAdSense(config);
const jsonLd = blogPostingJsonLd(post);
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<BlogPostClient post={post} related={related} adsense={adsense} />
</>
);
}

View File

@ -0,0 +1,58 @@
import type { Metadata } from "next";
import Link from "next/link";
import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath";
export const metadata: Metadata = {
title: "About the Nomad Blog | Nomadro",
description:
"Who publishes Nomadro’s nomad blog, what we write about, and how advertising may appear after approval.",
alternates: { canonical: "https://nomadro.com/hub/blog/about" },
robots: { index: true, follow: true },
};
export default function HubBlogAboutPage() {
return (
<SiteShell title="About" editorial>
<article className="sblog-page sblog-article">
<header className="sblog-hero">
<p className="sblog-eyebrow">Publisher</p>
<h1>About this blog</h1>
<p className="sblog-lead">
Nomadro publishes practical English guides for digital nomads on{" "}
<strong>nomadro.com</strong>. We also run community tools under{" "}
<Link href={hubPath("/")}>/hub</Link> so readers can meet people,
not only consume posts.
</p>
</header>
<div className="sblog-prose">
<h2>What we write</h2>
<p>
Field notes on housing, coworking, budgets, time zones, privacy, and
making friends in a new city. Articles are original, edited for clarity,
and meant to be useful offline as well as online.
</p>
<h2>Advertising</h2>
<p>
We may show Google AdSense units on long English articles after the
publisher account is approved. Until then, ads stay disabled via remote
configuration. Content always comes first; ads never replace the article.
</p>
<h2>Contact</h2>
<p>
Questions or corrections: use{" "}
<Link href={hubPath("/feedback")}>Feedback</Link>. Privacy details
live on the <Link href={hubPath("/privacy")}>Privacy</Link> page.
</p>
</div>
<nav className="sblog-policy-row">
<Link href={hubPath("/blog")}>Blog</Link>
<Link href={hubPath("/privacy")}>Privacy</Link>
<Link href={hubPath("/feedback")}>Contact</Link>
</nav>
<HubFooter />
</article>
</SiteShell>
);
}

View File

@ -0,0 +1,8 @@
/** Blog suspense — spinner only, no intermediate page. */
export default function BlogLoading() {
return (
<div className="social-loader" role="status" aria-busy="true" aria-label="Loading">
<span className="social-loader-ring" aria-hidden="true" />
</div>
);
}

35
src/app/hub/blog/page.tsx Normal file
View File

@ -0,0 +1,35 @@
import type { Metadata } from "next";
import BlogListClient from "@hub/components/blog/BlogListClient";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { blogListJsonLd } from "@hub/lib/blog/jsonld";
export const metadata: Metadata = {
title: "Nomad Blog | Nomadro",
description:
"English field notes for digital nomads: cities, cafés, remote work, budgets, and meeting people on the road.",
alternates: { canonical: "https://nomadro.com/hub/blog" },
openGraph: {
title: "Nomad Blog | Nomadro",
description:
"Practical guides for remote work and slow travel. Content-first — ads off until AdSense approval.",
url: "https://nomadro.com/hub/blog",
type: "website",
siteName: "Nomadro",
},
robots: { index: true, follow: true },
};
export default function HubBlogPage() {
const posts = listBlogPosts({ locale: "en", adsenseReadyOnly: false });
const jsonLd = blogListJsonLd(posts);
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<BlogListClient posts={posts} />
</>
);
}

View File

@ -0,0 +1,37 @@
import { listBlogPosts } from "@hub/lib/blog/catalog";
const SITE = "https://nomadro.com";
export async function GET() {
const posts = listBlogPosts({ locale: "en" });
const items = posts
.map(
(p) => `
<item>
<title><![CDATA[${p.title}]]></title>
<link>${SITE}/hub/blog/${p.slug}</link>
<guid>${SITE}/hub/blog/${p.slug}</guid>
<pubDate>${new Date(p.date).toUTCString()}</pubDate>
<description><![CDATA[${p.description}]]></description>
</item>`,
)
.join("");
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Nomadro Nomad Blog</title>
<link>${SITE}/hub/blog</link>
<description>English field notes for digital nomads</description>
<language>en-us</language>
${items}
</channel>
</rss>`;
return new Response(xml, {
headers: {
"Content-Type": "application/rss+xml; charset=utf-8",
"Cache-Control": "public, max-age=3600",
},
});
}

View File

@ -0,0 +1,24 @@
import { redirect } from "next/navigation";
/** 旧路径 /hub/chat/:id → /hub/chat?channel=id */
export default async function Page({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const { id } = await params;
const sp = await searchParams;
const next = new URLSearchParams();
const channel = String(id || "").trim();
if (channel && channel !== "general") next.set("channel", channel);
const introRaw = sp.intro;
const intro = Array.isArray(introRaw) ? introRaw[0] : introRaw;
if (intro) next.set("intro", intro);
const mRaw = sp.m;
const m = Array.isArray(mRaw) ? mRaw[0] : mRaw;
if (m) next.set("m", m);
const q = next.toString();
redirect(q ? `/hub/chat?${q}` : "/hub/chat");
}

View File

@ -0,0 +1,5 @@
import ChatListClient from "@hub/components/ChatListClient";
export default function Page() {
return <ChatListClient />;
}

View File

@ -0,0 +1,10 @@
import CoffeeBookPage from "@coffee/components/CoffeeBookPage";
export default async function Page({
params,
}: {
params: Promise<{ username: string; slug: string }>;
}) {
const { username, slug } = await params;
return <CoffeeBookPage username={username} slug={slug} />;
}

View File

@ -0,0 +1,10 @@
import CoffeeHostPage from "@coffee/components/CoffeeHostPage";
export default async function Page({
params,
}: {
params: Promise<{ username: string }>;
}) {
const { username } = await params;
return <CoffeeHostPage username={username} />;
}

View File

@ -0,0 +1,10 @@
import CoffeeBookingDetail from "@coffee/components/CoffeeBookingDetail";
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return <CoffeeBookingDetail id={id} />;
}

View File

@ -0,0 +1,5 @@
import CoffeeManagePage from "@coffee/components/CoffeeManagePage";
export default function Page() {
return <CoffeeManagePage />;
}

View File

@ -0,0 +1,5 @@
import CoffeeLanding from "@coffee/components/CoffeeLanding";
export default function Page() {
return <CoffeeLanding />;
}

View File

@ -0,0 +1,5 @@
import DateClient from "@hub/components/DateClient";
export default function Page() {
return <DateClient />;
}

View File

@ -0,0 +1,5 @@
import EbookClient from "@hub/components/EbookClient";
export default function Page() {
return <EbookClient />;
}

25
src/app/hub/error.tsx Normal file
View File

@ -0,0 +1,25 @@
"use client";
import Link from "next/link";
import { RefreshCw } from "lucide-react";
export default function HubError({ reset }: { reset: () => void }) {
return (
<main className="social-route-state">
<span className="social-route-state-mark" aria-hidden="true">
🧭
</span>
<h1>出了点小状况</h1>
<p role="alert">再试一次就好。</p>
<div className="social-actions">
<button type="button" className="social-btn primary" onClick={reset}>
<RefreshCw size={16} />
再试一次
</button>
<Link className="social-btn" href="/hub">
回首页
</Link>
</div>
</main>
);
}

View File

@ -0,0 +1,5 @@
import FeedbackClient from "@hub/components/FeedbackClient";
export default function Page() {
return <FeedbackClient />;
}

View File

@ -0,0 +1,6 @@
import TeamClient from "@hub/components/TeamClient";
/** 兼容旧路径 /hub/gigs → 远程团队 · 兼职 */
export default function Page() {
return <TeamClient initialKind="parttime" />;
}

View File

@ -0,0 +1,6 @@
import HomeClient from "@hub/components/HomeClient";
/** Hub 首页:/hub → /hub/home */
export default function HubHomeAliasPage() {
return <HomeClient />;
}

10
src/app/hub/join/page.tsx Normal file
View File

@ -0,0 +1,10 @@
import { Suspense } from "react";
import JoinClient from "@hub/components/JoinClient";
export default function Page() {
return (
<Suspense fallback={<div className="social-status">加载加入页…</div>}>
<JoinClient />
</Suspense>
);
}

45
src/app/hub/layout.tsx Normal file
View File

@ -0,0 +1,45 @@
import { ModuleBoundary } from "~/components/module-boundary";
/* 主题1=旅居社群(默认)· 主题2=琥珀信号 · 主题3/4=预留;后台 remote skin 可切换 */
import "@community/app/globals.css";
import "@hub/app/globals.css";
import "@hub/app/fx.css";
import "@hub/app/theme2.css";
import "@hub/app/theme3.css";
import "@hub/app/theme4.css";
import "@hub/app/home.css";
import "@hub/app/experience.css";
import "@hub/app/interaction.css";
import "@hub/app/studio.css";
import "@hub/app/motion.css";
import "@hub/app/depth.css";
import "@hub/app/vivid.css";
import "@hub/app/h5.css";
import "@hub/app/blog.css";
import "@hub/app/discovery.css";
import "@hub/app/live.css";
import HubExperience from "@hub/components/HubExperience";
export const metadata = {
title: "Nomadro Hub · 游民社区",
description: "游民社区:聊天群、约会、语音厅、同城见面、招聘共创",
};
export default function HubLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ModuleBoundary moduleKey="hub">
<div className="community-root hub-skin">
{/* 首屏防闪:优先缓存主题,否则主题1;远程配置拉取后由 SiteShell 覆盖 */}
<script
dangerouslySetInnerHTML={{
__html: `(function(){var k='nomadro-hub-skin',s='1';try{var v=localStorage.getItem(k);if(v==='1'||v==='2'||v==='3'||v==='4')s=v;}catch(e){}document.documentElement.setAttribute('data-hub-skin',s);})();`,
}}
/>
<HubExperience>{children}</HubExperience>
</div>
</ModuleBoundary>
);
}

8
src/app/hub/loading.tsx Normal file
View File

@ -0,0 +1,8 @@
/** Route suspense — spinner only, no intermediate page. */
export default function HubLoading() {
return (
<div className="social-loader" role="status" aria-busy="true" aria-label="Loading">
<span className="social-loader-ring" aria-hidden="true" />
</div>
);
}

5
src/app/hub/map/page.tsx Normal file
View File

@ -0,0 +1,5 @@
import MapClient from "@hub/components/MapClient";
export default function HubMapPage() {
return <MapClient />;
}

View File

@ -0,0 +1,6 @@
import MeetupLiveClient from "@hub/components/MeetupLiveClient";
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return <MeetupLiveClient meetupId={id} />;
}

View File

@ -0,0 +1,5 @@
import MeetupClient from "@hub/components/MeetupClient";
export default function Page() {
return <MeetupClient />;
}

View File

@ -0,0 +1,5 @@
import NotificationsClient from "@notify/components/NotificationsClient";
export default function Page() {
return <NotificationsClient />;
}

View File

@ -0,0 +1,5 @@
import NotificationSettingsClient from "@notify/components/NotificationSettingsClient";
export default function Page() {
return <NotificationSettingsClient />;
}

View File

@ -0,0 +1,5 @@
import ActivityClient from "@notify/components/ActivityClient";
export default function Page() {
return <ActivityClient />;
}

View File

@ -0,0 +1,5 @@
import InboxClient from "@notify/components/InboxClient";
export default function Page() {
return <InboxClient />;
}

View File

@ -0,0 +1,5 @@
import NotifyClient from "@notify/components/NotifyClient";
export default function Page() {
return <NotifyClient />;
}

View File

@ -0,0 +1,5 @@
import SubscribersClient from "@notify/components/SubscribersClient";
export default function Page() {
return <SubscribersClient />;
}

View File

@ -0,0 +1,5 @@
import TopicsClient from "@notify/components/TopicsClient";
export default function Page() {
return <TopicsClient />;
}

View File

@ -0,0 +1,10 @@
import WorkflowDetailClient from "@notify/components/WorkflowDetailClient";
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return <WorkflowDetailClient workflowId={id} />;
}

View File

@ -0,0 +1,5 @@
import WorkflowsClient from "@notify/components/WorkflowsClient";
export default function Page() {
return <WorkflowsClient />;
}

5
src/app/hub/page.tsx Normal file
View File

@ -0,0 +1,5 @@
import HomeClient from "@hub/components/HomeClient";
export default function HubHomePage() {
return <HomeClient />;
}

View File

@ -0,0 +1,15 @@
import { Suspense } from "react";
import PeopleProfileClient from "@hub/components/PeopleProfileClient";
export default async function PeopleProfilePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return (
<Suspense fallback={<div className="social-status">加载游民名片…</div>}>
<PeopleProfileClient id={id} />
</Suspense>
);
}

View File

@ -0,0 +1,6 @@
import { Suspense } from "react";
import PeopleClient from "@hub/components/PeopleClient";
export default function PeoplePage() {
return <Suspense fallback={<div className="social-status">正在发现同类…</div>}><PeopleClient /></Suspense>;
}

View File

@ -0,0 +1,10 @@
import PlaceDetailClient from "@hub/components/PlaceDetailClient";
export default async function HubPlaceDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return <PlaceDetailClient cityId={id} />;
}

View File

@ -0,0 +1,5 @@
import PlacesClient from "@hub/components/PlacesClient";
export default function HubPlacesPage() {
return <PlacesClient />;
}

View File

@ -0,0 +1,78 @@
import type { Metadata } from "next";
import Link from "next/link";
import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath";
export const metadata: Metadata = {
title: "Privacy | Nomadro Social",
description:
"How Nomadro handles data on /hub, cookies, analytics, and advertising (including Google AdSense when enabled).",
alternates: { canonical: "https://nomadro.com/hub/privacy" },
robots: { index: true, follow: true },
};
/** AdSense reviewers look for a clear Privacy Policy with ads/cookies disclosure */
export default function HubPrivacyPage() {
return (
<SiteShell title="Privacy" editorial>
<article className="sblog-page sblog-article">
<header className="sblog-hero">
<p className="sblog-eyebrow">Legal</p>
<h1>Privacy Policy</h1>
<p className="sblog-lead">
Last updated: 4 November 2026. This page covers nomadro.com social
surfaces including <code>/hub</code> and the Hub Blog.
</p>
</header>
<div className="sblog-prose">
<h2>Who we are</h2>
<p>
Nomadro operates nomadro.com. Contact us via{" "}
<Link href={hubPath("/feedback")}>Feedback</Link> for privacy
requests.
</p>
<h2>Data we process</h2>
<p>
Account or profile details you submit (for example display name, city,
or join flow fields), messages you post in community tools, technical
logs needed to keep the service running, and optional analytics events.
</p>
<h2>Cookies, analytics, and advertising</h2>
<p>
We may use cookies or similar technologies for session continuity,
preference storage, and traffic analytics. After Google AdSense
approval, advertising cookies may be used by Google and partners to
serve and measure ads on eligible pages. You can control cookies through
your browser settings. Where required by law, we will present a consent
mechanism before non‑essential advertising cookies.
</p>
<p>
Third‑party ad partners may collect data subject to their own policies
(for example Google’s advertising policies). See also our{" "}
<Link href={hubPath("/blog/about")}>About</Link> page for how ads
relate to editorial content.
</p>
<h2>Your choices</h2>
<p>
You may request access or deletion of account‑linked data via Feedback.
You may refuse non‑essential cookies where a banner is shown. Blocking
ads does not remove your ability to read blog articles.
</p>
<h2>International visitors</h2>
<p>
nomadro.com primarily serves an international audience. Data may be
processed on servers outside your country. We take reasonable measures
to protect information in transit (HTTPS) and at rest.
</p>
</div>
<nav className="sblog-policy-row">
<Link href={hubPath("/blog")}>Blog</Link>
<Link href={hubPath("/blog/about")}>About</Link>
<Link href={hubPath("/feedback")}>Contact</Link>
</nav>
<HubFooter />
</article>
</SiteShell>
);
}

View File

@ -0,0 +1,5 @@
import RosterClient from "@hub/components/RosterClient";
export default function Page() {
return <RosterClient />;
}

36
src/app/hub/sitemap.ts Normal file
View File

@ -0,0 +1,36 @@
import type { MetadataRoute } from "next";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { getPublicSiteUrl } from "~/lib/google/site";
const SITE = getPublicSiteUrl();
export default function sitemap(): MetadataRoute.Sitemap {
const posts = listBlogPosts({ locale: "all" });
const staticRoutes: MetadataRoute.Sitemap = [
{
url: `${SITE}/hub/blog`,
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.8,
},
{
url: `${SITE}/hub/blog/about`,
lastModified: new Date(),
changeFrequency: "monthly",
priority: 0.6,
},
{
url: `${SITE}/hub/privacy`,
lastModified: new Date(),
changeFrequency: "monthly",
priority: 0.7,
},
];
const postRoutes = posts.map((p) => ({
url: `${SITE}/hub/blog/${p.slug}`,
lastModified: new Date(p.updated || p.date),
changeFrequency: "monthly" as const,
priority: 0.7,
}));
return [...staticRoutes, ...postRoutes];
}

View File

@ -0,0 +1,5 @@
import SkillsBoardClient from "@hub/components/SkillsBoardClient";
export default function Page() {
return <SkillsBoardClient />;
}

View File

@ -0,0 +1,5 @@
import TeamClient from "@hub/components/TeamClient";
export default function Page() {
return <TeamClient />;
}

View File

@ -0,0 +1,5 @@
import VideosClient from "@hub/components/VideosClient";
export default function Page() {
return <VideosClient />;
}

6
src/app/hub/vip/page.tsx Normal file
View File

@ -0,0 +1,6 @@
import { redirect } from "next/navigation";
/** 会员入口已隐藏,直达统一加入社区。 */
export default function Page() {
redirect("/hub/join");
}

View File

@ -0,0 +1,6 @@
import { redirect } from "next/navigation";
/** Legacy Planka-vendor mount retired — native Next boards. */
export default function WorkAppRedirect() {
redirect("/hub/work/boards");
}

View File

@ -0,0 +1,8 @@
import BoardClient from "@work/components/BoardClient";
type Props = { params: Promise<{ id: string }> };
export default async function WorkBoardPage({ params }: Props) {
const { id } = await params;
return <BoardClient boardId={id} />;
}

View File

@ -0,0 +1,5 @@
import BoardsClient from "@work/components/BoardsClient";
export default function WorkBoardsPage() {
return <BoardsClient />;
}

View File

@ -0,0 +1,6 @@
import type { ReactNode } from "react";
import WorkAccessGate from "@work/components/WorkAccessGate";
export default function WorkLayout({ children }: { children: ReactNode }) {
return <WorkAccessGate>{children}</WorkAccessGate>;
}

View File

@ -0,0 +1,8 @@
import PadClient from "@work/components/PadClient";
type Props = { params: Promise<{ id: string }> };
export default async function WorkPadPage({ params }: Props) {
const { id } = await params;
return <PadClient padId={id} />;
}

View File

@ -0,0 +1,5 @@
import PadsClient from "@work/components/PadsClient";
export default function WorkPadsPage() {
return <PadsClient />;
}

View File

@ -0,0 +1,5 @@
import WorkClient from "@work/components/WorkClient";
export default function Page() {
return <WorkClient />;
}

View File

@ -0,0 +1,5 @@
import WrappedClient from "@hub/components/WrappedClient";
export default function Page() {
return <WrappedClient />;
}

View File

@ -181,6 +181,10 @@ export type NomadroRemoteConfig = {
social: ModuleToggle;
/** /social/blog — AdSense 友好英文长文;关则隐藏入口 */
socialBlog?: ModuleToggle;
/** /hub — social 独立副本,前后端/后台可独立演进 */
hub?: ModuleToggle;
/** /hub/blog */
hubBlog?: ModuleToggle;
vip: ModuleToggle;
meetups: ModuleToggle;
destinations: ModuleToggle;
@ -243,11 +247,15 @@ export type NomadroRemoteConfig = {
* false 则关闭限额(仍建议保留加入漏斗)。
*/
socialTrialEnabled?: boolean;
/** /hub 尝鲜开关;缺省跟随 socialTrialEnabled */
hubTrialEnabled?: boolean;
/**
* 游民社区实时 UX 超级兜底(谁在线 / 热更新 / 离线壳 / 埋点…)。
* 不限于下列键;后台 Switches「实时社区」可改。
*/
socialLive?: SocialLiveFlags;
/** /hub 实时 UX;缺省跟随 socialLive */
hubLive?: SocialLiveFlags;
};
/**
* 受众分轨(.com 国际优先;中文用户特殊对待)。
@ -369,6 +377,107 @@ export type NomadroRemoteConfig = {
};
featuredCityIds?: string[];
};
/**
* /hub 独立副本配置(fork of social*)。
* 未设置时客户端可用 social* 作离线种子;后台 /hub 写入走 hub* 键。
*/
hubTrial?: {
enabled?: boolean;
chatMessages?: number;
dateViews?: number;
coffeeBookings?: number;
mapOpens?: number;
};
hubEyebrow?: string;
hubHeroLine1?: string;
hubHeroAccent?: string;
hubHeroLead?: string;
hubJoinCta?: string;
hubInviteTitle?: string;
hubInviteLead?: string;
hubPromoUrl?: string;
hubOnlineTitle?: string;
hubOfflineTitle?: string;
hubTeamTitle?: string;
hubPages?: Record<
string,
{
eyebrow?: string;
title?: string;
accent?: string;
description?: string;
}
>;
hubVideoSources?: Record<string, string>;
hubHiddenSections?: string[];
hubCatalogs?: {
cafes?: Array<Record<string, unknown>>;
meetups?: Array<Record<string, unknown>>;
gigs?: Array<Record<string, unknown>>;
roster?: Array<Record<string, unknown>>;
videos?: Array<Record<string, unknown>>;
ebooks?: Array<Record<string, unknown>>;
};
hubWayGroup?: string;
hubWayChat?: string;
hubWayDate?: string;
hubWayCafe?: string;
hubWayTeam?: string;
hubPayJoinLabel?: string;
hubOaJoinLabel?: string;
hubLocale?: {
enabled?: string[];
mtEnabled?: boolean;
fallback?: string;
};
hubGeo?: {
enabledCountries?: string[];
featuredCityIds?: string[];
};
hubSkin?: "1" | "2" | "3" | "4";
hubExperience?: {
skin?: "1" | "2" | "3" | "4";
navigation?: Record<string, boolean>;
sections?: Record<string, boolean>;
pages?: Record<
string,
Record<
string,
{
eyebrow?: string;
title?: string;
accent?: string;
description?: string;
}
>
>;
announcement?: {
enabled?: boolean;
zh?: string;
en?: string;
href?: string;
};
featuredCityIds?: string[];
};
hubFlags?: {
pages?: Record<string, boolean>;
sections?: Record<string, boolean>;
features?: {
joinPay?: boolean;
cafeReviews?: boolean;
creationSheet?: boolean;
chatRealtime?: boolean;
livePusher?: boolean;
dateSwipe?: boolean;
rosterEdit?: boolean;
teamApply?: boolean;
dock?: boolean;
homeEntry?: boolean;
avatarFaceCheck?: boolean;
[key: string]: boolean | undefined;
};
buttons?: Record<string, boolean>;
};
/** AdSense 文案位兜底(优先 flags) */
adsenseClientId?: string;
adsensePublisherId?: string;
@ -559,16 +668,16 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
note: "ebook reader + pay",
},
community: {
enabled: true,
enabled: false,
title: "旅居社群",
tabLabel: "社群",
note: "nomadweb",
note: "默认隐藏;后台可开(中文公开三大=导航/小册/Hub)",
},
social: {
enabled: true,
title: "游民社区",
tabLabel: "社区",
note: "门户 /social · 可拆独立域",
note: "国际 /social · 勿与中文 Hub 混用",
},
socialBlog: {
enabled: true,
@ -576,8 +685,20 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
tabLabel: "Blog",
note: "/social/blog · EN long-form · AdSense",
},
destinations: { enabled: true, title: "目的地" },
meetups: { enabled: true, title: "活动" },
hub: {
enabled: true,
title: "游民社区",
tabLabel: "社区",
note: "中文门户 /portal → /hub/home · 独立于 /social",
},
hubBlog: {
enabled: false,
title: "Hub Blog",
tabLabel: "Hub Blog",
note: "/hub/blog · 默认关,后台可开",
},
destinations: { enabled: false, title: "目的地", note: "默认隐藏" },
meetups: { enabled: false, title: "活动", note: "默认隐藏" },
vip: { enabled: false, title: "会员中心", note: "deep link only" },
game: { enabled: false, title: "数字游民", note: "冻结隐藏 · 勿开入口" },
},
@ -593,6 +714,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
socialAvatarFaceCheck: false,
socialTrialEnabled: true,
socialLive: { ...DEFAULT_SOCIAL_LIVE },
hubLive: { ...DEFAULT_SOCIAL_LIVE },
/** Site ownership / ads.txt seed — units stay off until adsenseEnabled */
adsenseClientId: "ca-pub-8461145959530971",
adsensePublisherId: "pub-8461145959530971",
@ -662,13 +784,19 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
socialOfflineTitle: "同城,见一面",
socialTeamTitle: "一起,做点事",
socialLocale: {
enabled: [],
mtEnabled: true,
fallback: "en",
enabled: ["zh"],
mtEnabled: false,
fallback: "zh",
},
socialGeo: {
enabledCountries: [],
featuredCityIds: ["chiangmai", "bali", "dali", "lisbon", "chengdu"],
enabledCountries: ["CN"],
featuredCityIds: [
"chengdu",
"dali",
"shanghai",
"shenzhen",
"hangzhou",
],
},
socialSkin: "1",
socialExperience: {
@ -681,6 +809,27 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
socialWayTeam: "招聘 · 共创",
socialPayJoinLabel: "加入社区",
socialOaJoinLabel: "先看看公众号",
/** 首页默认只留 Hero + 连接方式卡片,其下模块全部隐藏 */
hubHiddenSections: ["belowWays"],
/** /hub 中文受众锁:屏蔽多语言 UI(features.hubCnOnly=false 可解除) */
hubLocale: {
enabled: ["zh"],
mtEnabled: false,
fallback: "zh",
},
hubFlags: {
features: {
hubCnOnly: true,
},
},
hubSkin: "1",
hubExperience: {
skin: "1",
navigation: {},
sections: {},
announcement: { enabled: false },
},
hubPages: {},
socialPages: {
people: {
eyebrow: "先逛逛大家",
@ -922,6 +1071,21 @@ export function resolveSocialLive(
}
}
/** /hub 优先 flags.hubLive,缺省回落 socialLive(离线种子兜底)。 */
export function resolveHubLive(
config: NomadroRemoteConfig | null | undefined,
): SocialLiveFlags {
try {
const base = mergeSocialLive(
DEFAULT_SOCIAL_LIVE,
config?.flags?.socialLive || undefined,
);
return mergeSocialLive(base, config?.flags?.hubLive || undefined);
} catch {
return { ...DEFAULT_SOCIAL_LIVE };
}
}
export function mergeRemoteConfig(
partial: Partial<NomadroRemoteConfig> | null | undefined,
): NomadroRemoteConfig {
@ -1020,6 +1184,15 @@ export function mergeRemoteConfig(
base.flags.socialLive || DEFAULT_SOCIAL_LIVE,
(pf.socialLive || undefined) as Partial<SocialLiveFlags> | undefined,
),
hubLive: mergeSocialLive(
mergeSocialLive(
base.flags.hubLive ||
base.flags.socialLive ||
DEFAULT_SOCIAL_LIVE,
(pf.socialLive || undefined) as Partial<SocialLiveFlags> | undefined,
),
(pf.hubLive || undefined) as Partial<SocialLiveFlags> | undefined,
),
},
audience: mergeAudienceConfig(base.audience, partial.audience),
copy: mergeCopy(base.copy, partial.copy),

View File

@ -2,12 +2,13 @@
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import SiteShell from "@social/components/SiteShell";
import { socialPath } from "@social/lib/socialPath";
import { socialTx } from "@social/lib/socialTx";
import { useSocialI18n } from "@social/lib/useSocialI18n";
import { SOCIAL_CITIES, type SocialCity } from "@social/lib/cities";
import { prefetchCityCopy, txCity, txCityField } from "@social/lib/localizeEntity";
import SiteShell from "@hub/components/SiteShell";
import { hubPath } from "@hub/lib/hubPath";
import { hubTx } from "@hub/lib/hubTx";
import { useHubI18n } from "@hub/lib/useHubI18n";
import { HUB_CITIES, type HubCity } from "@hub/lib/cities";
import { resolveSocialCities } from "@hub/geo";
import { prefetchCityCopy, txCity, txCityField } from "@hub/lib/localizeEntity";
import { coffeeApi } from "../lib/api";
import { LOCAL_COFFEE_HOSTS } from "../lib/localHosts";
import type { CoffeeHost } from "../lib/types";
@ -16,51 +17,69 @@ import "./coffee.css";
const FEATURED_CITY_IDS = [
"chengdu",
"dali",
"chiangmai",
"bali",
"lisbon",
"shanghai",
"shenzhen",
"hangzhou",
"penang",
"xiamen",
];
function cityMatch(hostCity: string, city: SocialCity) {
function cityMatch(hostCity: string, city: HubCity) {
const raw = (hostCity || "").toLowerCase();
if (!raw) return false;
return (
raw.includes(city.name.toLowerCase()) ||
raw.includes(city.id.toLowerCase()) ||
(city.name === "清迈" && raw.includes("chiang")) ||
(city.name === "巴厘岛" && (raw.includes("bali") || raw.includes("巴厘"))) ||
(city.name === "里斯本" && raw.includes("lisbon")) ||
(city.name === "槟城" && (raw.includes("penang") || raw.includes("槟"))) ||
(city.name === "大理" && raw.includes("dali")) ||
(city.name === "杭州" && raw.includes("hangzhou")) ||
(city.name === "厦门" && raw.includes("xiamen")) ||
(city.name === "成都" && raw.includes("chengdu"))
(city.name === "成都" && raw.includes("chengdu")) ||
(city.name === "上海" && raw.includes("shanghai")) ||
(city.name === "深圳" && (raw.includes("shenzhen") || raw.includes("sz"))) ||
(city.name === "昆明" && raw.includes("kunming")) ||
(city.name === "丽江" && raw.includes("lijiang"))
);
}
function isChinaHost(host: CoffeeHost): boolean {
const city = (host.city || "").trim();
if (!city) return true;
const hit = HUB_CITIES.find(
(c) =>
city === c.name ||
city.toLowerCase() === c.id ||
city.toLowerCase().includes(c.id) ||
c.name.includes(city) ||
city.includes(c.name),
);
if (hit) return hit.country === "中国";
// 英文别名兜底:只要能对上国内种子城
return HUB_CITIES.some((c) => cityMatch(city, c));
}
export default function CoffeeLanding() {
useSocialI18n();
const [hosts, setHosts] = useState<CoffeeHost[]>(LOCAL_COFFEE_HOSTS);
useHubI18n();
const [hosts, setHosts] = useState<CoffeeHost[]>(
LOCAL_COFFEE_HOSTS.filter(isChinaHost),
);
const [offline, setOffline] = useState(false);
const [loading, setLoading] = useState(true);
const [retry, setRetry] = useState(0);
const [cityId, setCityId] = useState<string>("all");
const cities = useMemo(() => {
const hot = SOCIAL_CITIES.filter((c) => FEATURED_CITY_IDS.includes(c.id));
const rest = SOCIAL_CITIES.filter((c) => !FEATURED_CITY_IDS.includes(c.id));
return [...hot, ...rest].slice(0, 12);
const pool = resolveSocialCities({ cnOnly: true });
const hot = pool.filter((c) => FEATURED_CITY_IDS.includes(c.id));
const rest = pool.filter((c) => !FEATURED_CITY_IDS.includes(c.id));
return [...hot, ...rest];
}, []);
const activeCity = cities.find((c) => c.id === cityId) || null;
const activeDisplay = activeCity ? txCity(activeCity) : null;
const filtered = useMemo(() => {
if (cityId === "all" || !activeCity) return hosts;
return hosts.filter((h) => cityMatch(h.city, activeCity));
const chinaHosts = hosts.filter(isChinaHost);
if (cityId === "all" || !activeCity) return chinaHosts;
return chinaHosts.filter((h) => cityMatch(h.city, activeCity));
}, [hosts, cityId, activeCity]);
useEffect(() => {
@ -74,13 +93,13 @@ export default function CoffeeLanding() {
.hosts()
.then((r) => {
if (!active) return;
// Online API is source of truth — never merge packaged seeds into a live response.
setHosts(r.hosts || []);
const live = (r.hosts || []).filter(isChinaHost);
setHosts(live.length ? live : LOCAL_COFFEE_HOSTS.filter(isChinaHost));
setOffline(false);
})
.catch(() => {
if (!active) return;
setHosts(LOCAL_COFFEE_HOSTS);
setHosts(LOCAL_COFFEE_HOSTS.filter(isChinaHost));
setOffline(true);
})
.finally(() => {
@ -92,39 +111,37 @@ export default function CoffeeLanding() {
}, [retry]);
return (
<SiteShell title={socialTx("线下咖啡聊")}>
<SiteShell title={hubTx("线下咖啡聊")}>
<div className="cf-root cf-offline">
<section className="cf-hero-offline" aria-labelledby="cf-offline-brand">
<div className="cf-hero-offline-bg" aria-hidden />
<div className="cf-hero-offline-copy">
<p className="cf-eyebrow">OFFLINE · CITY</p>
<p className="cf-eyebrow">{hubTx("同城 · 线下")}</p>
<h1 className="cf-brand" id="cf-offline-brand">
Nomadro <span>{socialTx("线下 Coffee")}</span>
{hubTx("同城")} <span>{hubTx("线下咖啡")}</span>
</h1>
<p className="cf-title">
{socialTx("挑一座城,约一杯线下咖啡")}
</p>
<p className="cf-title">{hubTx("挑一座城,约一杯线下咖啡")}</p>
<p className="cf-lead">
{socialTx(
"不是线上会议。同城咖啡馆见面,破冰、换签证经验、找搭子——城市就是你的会场。",
{hubTx(
"不是线上会议。同城咖啡馆见面,破冰、换旅居经验、找搭子——城市就是你的会场。",
)}
</p>
<div className="cf-cta">
<a className="cf-btn cf-btn-primary" href="#cf-hosts">
{socialTx("看谁在约")}
{hubTx("看谁在约")}
</a>
<Link
className="cf-btn cf-btn-ghost"
href={socialPath("/places?tab=cafes")}
href={hubPath("/places?city=")}
>
{socialTx("咖啡馆地图")}
{hubTx("咖啡馆")}
</Link>
<Link className="cf-btn cf-btn-ghost" href={socialPath("/places")}>
{socialTx("逛城市")}
<Link className="cf-btn cf-btn-ghost" href={hubPath("/places")}>
{hubTx("逛城市")}
</Link>
</div>
</div>
<ul className="cf-city-rail" aria-label={socialTx("热门城市")}>
<ul className="cf-city-rail" aria-label={hubTx("热门城市")}>
{cities.slice(0, 6).map((c) => {
const d = txCity(c);
return (
@ -144,12 +161,10 @@ export default function CoffeeLanding() {
</ul>
</section>
<section className="cf-city-board" aria-label={socialTx("按城见面")}>
<section className="cf-city-board" aria-label={hubTx("按城见面")}>
<div className="cf-section-head">
<h2>{socialTx("城市就是会场")}</h2>
<p>
{socialTx("先选城,再约人。线下咖啡聊绑定同城,不搞远程空聊。")}
</p>
<h2>{hubTx("城市就是会场")}</h2>
<p>{hubTx("先选城,再约人。线下咖啡聊绑定同城,不搞远程空聊。")}</p>
</div>
<div className="cf-city-filter" role="tablist">
<button
@ -159,7 +174,7 @@ export default function CoffeeLanding() {
className={`cf-filter-pill${cityId === "all" ? " is-on" : ""}`}
onClick={() => setCityId("all")}
>
{socialTx("全部城市")}
{hubTx("全部城市")}
</button>
{cities.map((c) => {
const d = txCity(c);
@ -198,27 +213,29 @@ export default function CoffeeLanding() {
</h3>
<p>
{activeDisplay.blurb ||
socialTx("同城咖啡馆约见,见面比聊天软件快。")}
hubTx("同城咖啡馆约见,见面比聊天软件快。")}
</p>
<div className="cf-cta">
<Link
className="cf-btn cf-btn-primary"
href={socialPath(`/places/${activeCity.id}`)}
href={hubPath(`/places/${activeCity.id}`)}
>
{socialTx("看这座城")}
{hubTx("看这座城")}
</Link>
<Link
className="cf-btn cf-btn-ghost"
href={socialPath(`/places?tab=cafes&city=${activeCity.id}`)}
href={hubPath(
`/places?city=${encodeURIComponent(activeCity.name)}`,
)}
>
{socialTx("同城咖啡馆")}
{hubTx("同城咖啡馆")}
</Link>
</div>
</div>
</article>
) : (
<div className="cf-city-mosaic">
{cities.slice(0, 8).map((c) => {
{cities.map((c) => {
const d = txCity(c);
return (
<button
@ -247,13 +264,11 @@ export default function CoffeeLanding() {
<div className="cf-section-head">
<h2 id="cf-hosts-title">
{activeDisplay
? `${activeDisplay.name} · ${socialTx("可约线下")}`
: socialTx("线下可约的人")}
? `${activeDisplay.name} · ${hubTx("可约线下")}`
: hubTx("线下可约的人")}
</h2>
<p>
{socialTx(
"约的是咖啡馆见面,不是视频会议。点进主页选时段即可。",
)}
{hubTx("约的是咖啡馆见面,不是视频会议。点进主页选时段即可。")}
</p>
</div>
@ -264,13 +279,13 @@ export default function CoffeeLanding() {
type="button"
onClick={() => setRetry((value) => value + 1)}
>
{socialTx("重新加载")}
{hubTx("重新加载")}
</button>
</p>
) : null}
{loading && (
<p className="cf-hint" role="status">
{socialTx("正在寻找可约的人…")}
{hubTx("正在寻找可约的人…")}
</p>
)}
@ -278,23 +293,23 @@ export default function CoffeeLanding() {
{filtered.map((h) => (
<Link
key={h.id}
href={socialPath(`/coffeechat/${h.username}`)}
href={hubPath(`/coffeechat/${h.username}`)}
className="cf-card cf-card-offline"
>
<div className="cf-meta">
<span className="cf-pill">
{h.city ? txCityField(h.city) : socialTx("同城待定")}
{h.city ? txCityField(h.city) : hubTx("同城待定")}
</span>
<span className="cf-pill ok">{socialTx("线下")}</span>
<span className="cf-pill ok">{hubTx("线下")}</span>
</div>
<h2>{h.name}</h2>
<p>
{h.bio
? socialTx(h.bio)
: socialTx("咖啡馆轻聊,帮你破冰同城。")}
? hubTx(h.bio)
: hubTx("咖啡馆轻聊,帮你破冰同城。")}
</p>
<span className="cf-meta">
@{h.username} · {h.event_count || 0} {socialTx("种见面")}
@{h.username} · {h.event_count || 0} {hubTx("种见面")}
</span>
</Link>
))}
@ -302,21 +317,19 @@ export default function CoffeeLanding() {
{!filtered.length && !loading ? (
<p className="cf-empty">
{socialTx(
"这城暂时没人开放预约,先逛咖啡馆地图,或换一座城。",
)}
{hubTx("这城暂时没人开放预约,先逛咖啡馆,或换一座城。")}
</p>
) : null}
<div className="cf-cta cf-cta-foot">
<Link
className="cf-btn cf-btn-ghost"
href={socialPath("/coffeechat/manage")}
href={hubPath("/coffeechat/manage")}
>
{socialTx("开放我的线下档期")}
{hubTx("开放我的线下档期")}
</Link>
<Link className="cf-btn cf-btn-ghost" href={socialPath("/people")}>
{socialTx("找同城的人")}
<Link className="cf-btn cf-btn-ghost" href={hubPath("/people")}>
{hubTx("找同城的人")}
</Link>
</div>
</section>

View File

@ -1,79 +1,61 @@
import type { CoffeeHost } from "./types";
/**
* Packaged offline seed for `/social/coffeechat` when coffee_svc is unreachable.
* Online PocketBase / API response always wins once connected.
* Packaged offline seed for coffeechat when coffee_svc is unreachable.
* Hub 中文锁:只国内主持人。
*/
export const LOCAL_COFFEE_HOSTS: CoffeeHost[] = [
{
id: "local_host_chengdu",
username: "alice",
name: "Alice Chen",
bio: "成都远程 · 爱咖啡闲聊产品与出海",
city: "Chengdu",
name: "小雨",
bio: "成都远程 · 爱咖啡闲聊产品与同城局",
city: "成都",
timezone: "Asia/Shanghai",
event_count: 1,
},
{
id: "local_host_dali",
username: "maya",
name: "Maya · 大理",
name: "小满 · 大理",
bio: "苍山脚下咖啡馆见面,聊慢节奏与远程工作",
city: "Dali",
city: "大理",
timezone: "Asia/Shanghai",
event_count: 1,
},
{
id: "local_host_cm",
username: "bob",
name: "Bob Rivera",
bio: "EN/ZH · Nimman 咖啡馆线下聊聊",
city: "Chiang Mai",
timezone: "Asia/Bangkok",
event_count: 1,
},
{
id: "local_host_bali",
username: "rina",
name: "Rina · Canggu",
bio: "冲浪后 cowork,咖啡馆见一面就好",
city: "Bali",
timezone: "Asia/Makassar",
event_count: 1,
},
{
id: "local_host_lisbon",
username: "leo",
name: "Leo Santos",
bio: "阳光海岸 · 欧洲时区线下 coffee",
city: "Lisbon",
timezone: "Europe/Lisbon",
event_count: 1,
},
{
id: "local_host_hz",
username: "qing",
name: "青禾 · 杭州",
bio: "西湖边咖啡馆,聊互联网与副业",
city: "Hangzhou",
city: "杭州",
timezone: "Asia/Shanghai",
event_count: 1,
},
{
id: "local_host_penang",
username: "mei",
name: "Mei · 槟城",
bio: "美食 + 海风开放工位,同城约一杯",
city: "Penang",
timezone: "Asia/Kuala_Lumpur",
event_count: 1,
},
{
id: "local_host_xiamen",
username: "kai",
name: "Kai · 厦门",
bio: "鼓浪屿附近咖啡馆轻聊,破冰同城",
city: "Xiamen",
city: "厦门",
timezone: "Asia/Shanghai",
event_count: 1,
},
{
id: "local_host_sh",
username: "lin",
name: "林悦 · 上海",
bio: "安福路咖啡馆见面,聊设计与远程",
city: "上海",
timezone: "Asia/Shanghai",
event_count: 1,
},
{
id: "local_host_sz",
username: "mia",
name: "Mia · 深圳",
bio: "南山咖啡馆,聊增长与创业",
city: "深圳",
timezone: "Asia/Shanghai",
event_count: 1,
},

91
src/modules/hub/README.md Normal file
View File

@ -0,0 +1,91 @@
# Nomadro Hub(/hub)
从 `/social` **只读复制**出的独立模块:门户 `src/modules/hub` + `src/app/hub` · API `/api/hub/v1` · 后台 **仅** `admin.nomadro.com` **`/cn/hub/*`**(国际轨走 `/intl/social/*`,互不混挂)。
中文门户「游民社区」→ `/hub/home`。**不要改 `src/modules/social` / `social_svc` 业务代码**;在本树演进。
## 中文受众锁(当前写死)
- `lib/hubCnLock.ts`:`isHubCnOnly()` **恒 true**(远程 `hubCnOnly=false` 暂不放开)。
- UI:强制中文、隐藏语言切换;聊天只要「游民大厅」。
- 地理:`geo/cnDefaults.ts` → `HUB_CN_GEO_CODES = ["CN"]`;`resolveSocialCities` 默认只中国;`HUB_CITIES` 不含清迈/巴厘岛/里斯本/槟城(国际种子在 `HUB_CITIES_INTL`)。
- 咖啡聊:`CoffeeLanding` 走 Hub 城市池 + `hubPath`;主持人离线种子仅国内。
- 后端镜像:`hub_svc/geo_cities.py` 默认 `SEED_CITIES` 仅中国。
## 隔离
- 后端:`apps/api/services/hub_svc` → `data/hub/hub.db` · PB collections `hub_*`
- 前缀:`/api/hub/v1`(不占用 `/api/v1` 或 `/api/social`)
- 挂载失败 / `HUB_ENABLED=false` → 不影响 ebook / community / pay / social
- 前端失败自动降级 localStorage
- 实时:Centrifugo(`/realtime/token` + publish);不可用则聊天室轮询
## 视觉
- **T1**(默认):社区对齐;`lib/skin.ts` · `HUB_SKIN_DEFAULT = "1"`
- **T2**:`app/theme2.css`(琥珀信号);切换器默认隐藏
- **首页视觉**:`ConnectionHero` 的 SVG 连接轨道、成员浮层、鼠标视差、柔光粒子;`home.css` 隔离首页样式,保留珊瑚红 / 薄荷绿 / 暖黄配色。
- **动效与可访问性**:区块滚动显现、卡片聚光、悬停声波、阅读进度;尊重 `prefers-reduced-motion`,视频按需加载,离开页面时清理监听。
- **交互**:粘性区块导航与当前位置、方向键筛选成员、关注本地保存;原生 `dialog` 管理视频与加群弹窗的焦点、Escape、背景锁定。
- **全站布局**:桌面为宽幅内容 + 顶部分组导航;移动端为顶部菜单 + 底部快捷入口。没有侧栏,聊天室频道也使用横向切换。
- **全站动效**:`HubExperience` / `experience.css` 提供星点连线、鼠标柔光、漂移光晕、卡片聚光和页面入场;`interaction.css` / `studio.css` 提供声波、会前雷达、名片透视与书封动效。动效可切为轻量,系统减少动态效果设置优先;离开页面或标签页隐藏时清理/暂停动画。
- **视觉终态层**:`depth.css` + `vivid.css` 统一玻璃导航、快捷轨、约会进度、聊天跳转最新、咖啡馆主从、Meetup 雷达、触控 ≥44px;子页 `HubQuickRail` 横向跳转。
- **H5(≤900px)**:`app/h5.css` **最后加载**;Ways 竖列表(群组聊天优先)、底栏「聊天」在「认识」左侧、滑卡/composer/加入 sheet 避开 dock + safe-area。
- **聊天性能**(不影响视觉):WS 连通后停 since 轮询;消息内存态 + 防抖写本地末 80 条;空 poll 不刷 read note。
## 子页面与交互边界
- `/people`:按城市 / 技能 / 兴趣搜索展示成员,收藏与名片弹窗;成员和在线状态为演示资料,可选显示本机已发布名片;交流入口通向真实公开频道,没有虚构私信或匹配结果。
- `/chat`、`/chat/[id]`:中文锁下 **仅游民大厅**(多国频道代码保留不露出);破冰话题、引用回复、表情、IME 友好 Enter、草稿、附件。Centrifugo 优先,失败降级轮询。**气泡双语**在中文锁下关闭机器翻译。`/chat/[id]` 重定向到公开厅。
- `/meetup`、`/meetup/[id]`:活动收藏表示本机参与计划,不是预约成功;导出日历按活动 IANA 时区转换为 UTC,种子默认 `Asia/Shanghai`。视频房间在明确点击进入后才加载,麦克风 / 摄像头默认关闭,支持布局切换、重连、新窗口和离开。音视频能力依赖现有 MiroTalk 服务及用户授权。
- `/coffeechat`:城市 / 关键词 / 网络 / 评分筛选,地点收藏、可分享选中地点、真实评价提交与离线重试。目录中的地点、带宽、评分仅作种子参考;邀约进入公开频道,不伪造订位或即时到场人数。
- `/roster`:编辑时实时预览名片与完成度,本机草稿优先;慢返回的服务端资料不会覆盖正在编辑的内容。保存调用现有资料 API,明确区别同步成功与尚未同步。
- `/team`、`/gigs`:搜索技能与角色、类型筛选、收藏、参与申请弹窗,校验必填项、保留本机草稿、失败重试和重复提交保护。目录机会是否开放需另行确认。
- `/videos`、`/date`、`/ebook`:统一搜索、收藏、内容详情和话题讨论入口。视频没有片源时明确展示目录预览,不显示假播放器;小册入口通向门户书库,不承诺目录主题已有对应完整正文。
- `/join`、`/vip`、`/feedback`:加群双路径(付费入群 + 关注公众号)、会员中心入口、反馈草稿与离线重试、「再提一条」;购买遵循 `payEnabled`,不承诺未实现的优先席位等权益。
- **支付 → 资料**:成功后进 `?step=profile`(`lib/joinFlow.ts`);PC 双栏 + 右侧实时名片,H5 全宽;开发本机可跳过支付。
- **头像**:`hubApi.uploadAvatar` → `POST /api/hub/v1/upload` → SeaweedFS(`s3.nomadro.com`,`S3_*` 与 community 对齐);无密钥 / 失败则本地 `GET /files/avatar/{name}`。草稿与昵称 **mount 后再读** localStorage,避免 hydration 错误。
- **子页面运营**:`/admin/config` 的 `copy.hubPages` 支持按路由键覆盖 `{ eyebrow, title, accent, description }`;`copy.hubVideoSources` 按目录 ID 配置片源;`copy.hubCatalogs` 可覆盖 cafes/meetups/gigs(空/非法回退包内 seed)。编辑器校验 JSON;空配置使用内置默认文案。
- **存储**:`useLocalState` 统一草稿、偏好和收藏,兼容服务端渲染和跨标签页更新。本机保存不会冒充服务器发布、真实关注关系或账号登录。
## 首页(数字游民社交)
- 右侧:同频引力轨道与演示成员;「看看社区故事」打开宣传片,首屏不加载视频。
- **后台文案**:`/admin/config` 可编辑 `copy.hubEyebrow` / `hubHeroLine1` / `hubHeroAccent` / `hubHeroLead` / `hubJoinCta` / `hubInviteTitle` / `hubInviteLead` / `hubOnlineTitle` / `hubOfflineTitle` / `hubTeamTitle`。空值或异常字段使用客户端默认值。
- **宣传片**:`copy.hubPromoUrl` 优先,其次兼容 `modules.social.promoVideoUrl`,最后使用默认源。
- CTA:仅「加群」→ 邮箱弹窗 → PC/H5 `zpay`、微信内 H5 `xpay`、小程序引导虚拟支付(`JoinPayModal` + `triggerPay`)
- 下方:三种连接入口 → 成员花名册 → Meetup → Coffeechat → **远程团队**(`/hub/team`:志愿者 / 兼职 / 全职)→ 加入邀请。
- 首页成员 / 活动预览沿用种子数据,演示在线状态明确标注,非实时成员统计。
## 本地验收
- TypeScript 全量检查与改动范围 ESLint。
- Chrome / Playwright 覆盖 17 个路由的 320 / 390 / 768 / 1440 宽度;首页补充 700 / 900 / 1024 宽度。
- 检查明暗主题、减少动态效果、菜单 / 原生弹窗、搜索收藏、公开话题草稿、聊天与表单提交成功 / 离线 / 重试、日历时区与视频会前确认。
- 自动化写接口使用拦截响应,不向实际社区发布消息、评价或申请,不触发真实支付。视频房间仅验证加载与控制流程,不代表外部音视频连通性已验收。
## 多语言(保底)
壳层字典支持中 / 英等(`lib/i18n.ts` + `useHubI18n` + `phrases`)。**中文锁开启时**:强制 `zh`、隐藏语言切换、关闭 Argos MT。锁关闭后顶栏语言写入 `nomadro-locale`。子页运营文案(`copy.hubPages`)仍以中文远程配置为主。
## 本地
```bash
pnpm dev:api
pnpm dev
# 浏览器打开 http://127.0.0.1:3000/hub
curl http://127.0.0.1:8080/api/hub/v1/health
```
部署说明见 [`deploy/hub/README.md`](../../../deploy/hub/README.md)。前端先本地验收,未经允许不上线。
## 社区发现体验(2026-11-04)
- 首页 `ConnectionWays`:群组聊天 / 认识一下 / 开视频聊聊 / 找个地方见面 / 找搭子·共创 五卡入口。
- `/hub/people` 使用独立城市与现有搜索、动态职业/兴趣/语言选项、可移除条件、排序和卡片直接关注。关注沿用本设备存储,与详情页及滑卡共用。
- 行程仅依据明确的 `status`:`here` 表示当前在此,`arriving` / `soon` 表示即将到达;不再通过在线状态推测行程。没有该字段的示例不参与行程匹配。
- 运营文案继续走 `copy.hubPages`:`discovery` 配置首页引导标题;`discovery-people`、`discovery-coffee`、`discovery-city`、`discovery-create` 配置对应说明;`peopleConnections` 配置找人页引导。使用已有 `eyebrow/title/description` 字段。
- `hubHiddenSections` 可隐藏首页区块:`discovery`、`jumpRail`、`livePulse`、`tonight`、`path`、`people`、`date`、`meetup`、`cities`、`coffee`、`team`、`skills`、`hire`、`ways`、`promo`、`invite`。体验台与 `hub_ops`/`hub_experience` 共用键;写 ops 时保留体验台专有隐藏键,避免互相覆盖。旧键 `discover`/`collaborate`/`faq` 自动映射。
- `flags.hubLive` 控制 /hub 实时 UX(cn 轨 Switches);缺省回落 `socialLive`。Centrifugo 频道前缀 `hub:`(与 social_svc `social:` 隔离)。
- `hubExperience.navigation` 控制顶栏 / 快捷栏 / 底栏 dock 入口;`announcement` 在壳层展示(可关闭)。
- **超级能力包(≥20)**:⌘K 跳转、快捷键 `?`、离线条、今日行动、意图测验、在线条、刚刚在线、语音厅收藏、快捷芯片、社区温度、本周城市、最近去过、回访连续天、标签云、邀请复制、摘要偏好、专注模式、提示音、本机静音模块、导航远程开关、`GET /api/hub/v1/features`、admin 首页编排预设。本机偏好存 `nomadro-hub:superPrefs`。
- 社区语言首次渲染与服务器保持一致,待受众识别完成后更新,避免英文浏览器水合失败。
- 验证:启动门户后运行 `python scripts/check-social-discovery.py`;覆盖关注持久化、组合筛选、真实行程语义、首页意图入口、中英文和 320/390/768/1440px 布局。截图与报告位于 `artifacts/social-discovery/`。

View File

@ -0,0 +1,603 @@
/* /hub/blog — editorial reading plane (AdSense: content first, clear hierarchy) */
.social-editorial {
--nav-height: 88px;
--sblog-index-max: 58rem;
--sblog-article-max: 42rem;
position: relative;
min-height: 100dvh;
}
.social-experience:has(.social-editorial) .social-fx-control {
display: none;
}
.social-editorial::before {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
background:
radial-gradient(ellipse 70% 45% at 50% -10%, rgba(78, 205, 196, 0.1), transparent 55%),
radial-gradient(ellipse 40% 30% at 90% 20%, rgba(255, 107, 107, 0.06), transparent 50%);
}
.social-editorial-frame {
position: relative;
z-index: 1;
width: 100%;
max-width: none;
margin: 0;
padding: calc(var(--nav-height) + 20px) clamp(1rem, 3vw, 2rem) 5.5rem;
box-sizing: border-box;
min-height: 100dvh;
}
.social-editorial .social-main--editorial {
width: 100%;
max-width: none;
margin: 0 auto;
padding: 0;
}
.sblog-page {
width: 100%;
max-width: var(--sblog-article-max);
margin: 0 auto;
padding: 0 0 1.5rem;
}
.sblog-page.sblog-index {
max-width: var(--sblog-index-max);
}
.sblog-hero {
margin-bottom: 1.35rem;
}
.sblog-eyebrow {
margin: 0 0 0.55rem;
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
color: color-mix(in srgb, var(--muted, #94a3b8) 92%, #fff);
}
.sblog-eyebrow a {
color: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
.sblog-hero h1 {
margin: 0 0 0.7rem;
font-size: clamp(1.85rem, 5vw, 2.45rem);
line-height: 1.15;
letter-spacing: -0.03em;
font-weight: 720;
}
.sblog-lead {
margin: 0;
font-size: 1.08rem;
line-height: 1.55;
color: var(--muted, #94a3b8);
max-width: 36rem;
}
.sblog-count {
margin: 0.85rem 0 0;
font-size: 0.82rem;
color: var(--muted, #64748b);
}
.sblog-meta {
margin: 0.85rem 0 0;
font-size: 0.88rem;
color: var(--muted, #94a3b8);
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.45rem;
align-items: center;
}
.sblog-inline-tag {
display: inline-block;
padding: 0.12rem 0.45rem;
border-radius: 999px;
font-size: 0.75rem;
background: color-mix(in srgb, currentColor 9%, transparent);
}
.sblog-tags {
display: flex;
flex-wrap: nowrap;
gap: 0.45rem;
margin: 0 0 1.35rem;
overflow-x: auto;
padding-bottom: 0.25rem;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
}
.sblog-tags::-webkit-scrollbar {
display: none;
}
.sblog-tag {
appearance: none;
flex: 0 0 auto;
border: 1px solid color-mix(in srgb, currentColor 16%, transparent);
background: transparent;
color: inherit;
font: inherit;
font-size: 0.78rem;
line-height: 1.2;
padding: 0.45rem 0.85rem;
border-radius: 999px;
min-height: 40px;
cursor: pointer;
white-space: nowrap;
}
.sblog-tag.is-on {
background: color-mix(in srgb, #2dd4bf 22%, transparent);
border-color: color-mix(in srgb, #2dd4bf 45%, transparent);
color: #ecfeff;
}
.sblog-featured {
display: flex;
flex-direction: column;
gap: 0.45rem;
margin: 0 0 1.75rem;
padding: 1.25rem 0 1.45rem;
border-bottom: 1px solid color-mix(in srgb, currentColor 14%, transparent);
text-decoration: none;
color: inherit;
transition: opacity 0.18s ease;
}
.sblog-featured:hover {
opacity: 0.92;
}
.sblog-featured-kicker {
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: #2dd4bf;
}
.sblog-featured time,
.sblog-featured em {
font-size: 0.82rem;
font-style: normal;
color: var(--muted, #94a3b8);
}
.sblog-featured strong {
font-size: clamp(1.25rem, 3.5vw, 1.55rem);
line-height: 1.3;
letter-spacing: -0.02em;
}
.sblog-featured-desc {
font-size: 1rem;
line-height: 1.5;
color: var(--muted, #94a3b8);
}
.sblog-featured:hover strong {
text-decoration: underline;
text-underline-offset: 3px;
}
.sblog-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.sblog-card-link {
display: flex;
flex-direction: column;
gap: 0.35rem;
height: 100%;
padding: 1.05rem 0;
border-bottom: 1px solid color-mix(in srgb, currentColor 10%, transparent);
text-decoration: none;
color: inherit;
}
.sblog-card-link time,
.sblog-card-link em {
font-size: 0.8rem;
font-style: normal;
color: var(--muted, #94a3b8);
}
.sblog-card-link strong {
font-size: 1.08rem;
line-height: 1.35;
letter-spacing: -0.01em;
}
.sblog-card-link span {
font-size: 0.94rem;
line-height: 1.45;
color: var(--muted, #94a3b8);
}
.sblog-card-link:hover strong {
text-decoration: underline;
text-underline-offset: 3px;
}
.sblog-article .sblog-hero {
padding-bottom: 1.15rem;
margin-bottom: 1.5rem;
border-bottom: 1px solid color-mix(in srgb, currentColor 12%, transparent);
}
.sblog-prose {
font-size: 1.08rem;
line-height: 1.75;
}
.sblog-prose h2 {
margin: 2rem 0 0.7rem;
font-size: 1.38rem;
line-height: 1.28;
letter-spacing: -0.02em;
}
.sblog-prose h3 {
margin: 1.45rem 0 0.5rem;
font-size: 1.12rem;
}
.sblog-prose p,
.sblog-prose ul,
.sblog-prose ol {
margin: 0 0 1.05rem;
}
.sblog-prose li {
margin: 0.28rem 0;
}
.sblog-prose a {
text-decoration: underline;
text-underline-offset: 2px;
color: #5eead4;
}
.sblog-prose code {
font-size: 0.9em;
padding: 0.1em 0.35em;
border-radius: 4px;
background: color-mix(in srgb, currentColor 8%, transparent);
}
.sblog-table-wrap {
overflow-x: auto;
margin: 0 0 1rem;
}
.sblog-table {
width: 100%;
border-collapse: collapse;
font-size: 0.92rem;
}
.sblog-table th,
.sblog-table td {
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
padding: 0.45rem 0.6rem;
text-align: left;
}
.sblog-ad {
margin: 1.85rem 0;
padding: 0.85rem 0.25rem;
border-top: 1px dashed color-mix(in srgb, currentColor 16%, transparent);
border-bottom: 1px dashed color-mix(in srgb, currentColor 16%, transparent);
min-height: 100px;
background: color-mix(in srgb, #fff 3%, transparent);
}
.sblog-ad-label {
margin: 0 0 0.45rem;
font-size: 0.68rem;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--muted, #94a3b8);
}
.sblog-related {
margin: 2.75rem 0 1rem;
padding-top: 1.35rem;
border-top: 1px solid color-mix(in srgb, currentColor 12%, transparent);
}
.sblog-related h2 {
margin: 0 0 0.75rem;
font-size: 1.05rem;
}
.sblog-related ul {
margin: 0;
padding-left: 1.1rem;
}
.sblog-related li {
margin: 0.4rem 0;
}
.sblog-policy-row {
display: flex;
flex-wrap: wrap;
gap: 0.85rem 1.15rem;
margin: 2.25rem 0 1rem;
padding-top: 1.15rem;
border-top: 1px solid color-mix(in srgb, currentColor 10%, transparent);
font-size: 0.9rem;
}
.sblog-policy-row a {
color: var(--muted, #94a3b8);
text-decoration: underline;
text-underline-offset: 2px;
}
.sblog-empty {
color: var(--muted, #94a3b8);
}
.social-editorial .social-workspace-footer {
max-width: none;
width: 100%;
margin: 0;
padding: 0 0 0.5rem;
}
@media (max-width: 900px) {
.social-editorial {
--nav-height: 80px;
}
.social-editorial-frame {
padding: calc(var(--nav-height) + 12px) 1rem calc(5.5rem + env(safe-area-inset-bottom, 0px));
}
.sblog-hero h1 {
font-size: clamp(1.65rem, 7vw, 2.1rem);
}
.sblog-lead {
font-size: 1rem;
}
}
@media (min-width: 901px) {
.social-editorial .social-mobile-dock {
display: none !important;
}
.social-editorial-frame {
padding-top: calc(var(--nav-height) + 28px);
padding-bottom: 4rem;
}
.sblog-featured {
padding: 1.5rem 1.35rem 1.65rem;
margin-inline: -1.35rem;
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
border-radius: 18px;
background: color-mix(in srgb, #fff 3.5%, transparent);
}
.sblog-featured strong {
font-size: clamp(1.4rem, 2.2vw, 1.75rem);
}
.sblog-featured:hover strong {
text-decoration: none;
}
.sblog-featured:hover {
border-color: color-mix(in srgb, #4ecdc4 28%, transparent);
}
.sblog-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 2rem;
row-gap: 0;
}
.sblog-list > li {
min-width: 0;
}
.sblog-card-link {
padding: 1.15rem 0 1.25rem;
}
.sblog-tag {
min-height: 40px;
}
.sblog-related-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.75rem 1.5rem;
}
.sblog-hero--index {
margin-bottom: 1.75rem;
}
.sblog-toolbar {
max-width: 28rem;
}
}
.sblog-progress {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 3px;
z-index: 1200;
pointer-events: none;
background: transparent;
}
.sblog-progress > span {
display: block;
height: 100%;
background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
transition: width 0.12s linear;
}
.sblog-toolbar { margin: 0 0 0.85rem; }
.sblog-search input {
width: 100%;
min-height: 44px;
border-radius: 12px;
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
background: color-mix(in srgb, #fff 4%, transparent);
color: inherit;
padding: 0.7rem 0.95rem;
font: inherit;
}
.sblog-search input:focus {
outline: 2px solid color-mix(in srgb, #4ecdc4 45%, transparent);
outline-offset: 1px;
}
.sblog-dot {
display: inline-block;
width: 3px;
height: 3px;
border-radius: 50%;
background: currentColor;
opacity: 0.45;
margin: 0 0.35rem;
vertical-align: middle;
}
.sblog-hero-glow {
position: absolute;
inset: -20% -10% auto;
height: 180px;
background: radial-gradient(ellipse at top, rgba(78, 205, 196, 0.14), transparent 70%);
pointer-events: none;
z-index: -1;
}
.sblog-hero--index, .sblog-hero--article { position: relative; }
.sblog-featured-top, .sblog-card-top, .sblog-featured-foot, .sblog-card-foot, .sblog-meta-row, .sblog-actions, .sblog-cta-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem 0.75rem;
}
.sblog-featured-foot, .sblog-card-foot, .sblog-meta-row { justify-content: space-between; }
.sblog-go {
font-size: 0.82rem;
font-weight: 650;
color: #4ecdc4;
}
.sblog-pill {
font-size: 0.72rem;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background: color-mix(in srgb, #4ecdc4 16%, transparent);
color: #99f6e4;
}
.sblog-empty-box {
padding: 1.5rem 0;
color: var(--muted, #94a3b8);
}
.sblog-text-btn, .sblog-ghost-btn {
appearance: none;
border: 1px solid color-mix(in srgb, currentColor 16%, transparent);
background: transparent;
color: inherit;
font: inherit;
font-size: 0.85rem;
min-height: 36px;
padding: 0.35rem 0.75rem;
border-radius: 999px;
cursor: pointer;
}
.sblog-toc {
margin: 0 0 1.5rem;
padding: 0.9rem 1rem;
border-radius: 14px;
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
background: color-mix(in srgb, #fff 3%, transparent);
}
.sblog-toc p {
margin: 0 0 0.45rem;
font-size: 0.75rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted, #94a3b8);
}
.sblog-toc ol {
margin: 0;
padding-left: 1.1rem;
}
.sblog-toc li { margin: 0.3rem 0; }
.sblog-cta {
margin: 2.5rem 0 1rem;
padding: 1.25rem 0 0;
border-top: 1px solid color-mix(in srgb, currentColor 12%, transparent);
}
.sblog-cta h2 { margin: 0 0 0.35rem; font-size: 1.15rem; }
.sblog-cta p { margin: 0 0 0.9rem; color: var(--muted, #94a3b8); }
.sblog-cta-primary, .sblog-cta-secondary {
display: inline-flex;
align-items: center;
min-height: 44px;
padding: 0 1rem;
border-radius: 999px;
text-decoration: none;
font-weight: 650;
}
.sblog-cta-primary {
background: #ff7b75;
color: #0a0e17;
}
.sblog-cta-secondary {
border: 1px solid color-mix(in srgb, currentColor 18%, transparent);
color: inherit;
}
.sblog-related-grid {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.75rem;
}
.sblog-related-grid a {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.85rem 0;
border-bottom: 1px solid color-mix(in srgb, currentColor 10%, transparent);
text-decoration: none;
color: inherit;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
border: 0;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,87 @@
/* Intent-led discovery and connection cards. Scoped to the social shell. */
.hub-skin .social-page-head .social-actions { min-width: 0; max-width: 100%; }
.hub-skin .social-page-head .social-demo-badge { white-space: normal; overflow-wrap: anywhere; line-height: 1.6; max-width: 100%; }
.hub-skin .social-intent-guide { margin-top: 26px; margin-bottom: 40px; }
.hub-skin .intent-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-bottom: 18px; }
.hub-skin .people-eyebrow { font-size: 10px; letter-spacing: .14em; font-weight: 700; color: var(--accent-3, #4ecdc4); }
.hub-skin .intent-heading h2 { margin: 0; font-size: clamp(19px, 2.4vw, 26px); letter-spacing: -.035em; }
.hub-skin .intent-options { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 12px; }
.hub-skin .intent-options button { display: flex; align-items: center; justify-content: center; gap: 10px; min-height: 52px; padding: 10px; border: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent); border-radius: 14px; background: var(--bg-glass); color: var(--text-secondary); font: inherit; font-size: 13px; cursor: pointer; transition: background .2s, border-color .2s; }
.hub-skin .intent-options button[aria-pressed="true"] { color: var(--text-primary); border-color: var(--accent-3, #4ecdc4); background: color-mix(in srgb, var(--accent-3, #4ecdc4) 12%, var(--bg-primary)); }
.hub-skin .intent-panel { position: relative; display: grid; grid-template-columns: 110px minmax(0, 1fr) auto; align-items: center; gap: 24px; padding: 30px; border: 1px solid color-mix(in srgb, var(--accent-3, #4ecdc4) 25%, transparent); border-radius: 22px; background: linear-gradient(115deg, color-mix(in srgb, var(--accent-3, #4ecdc4) 8%, transparent), transparent 65%), var(--bg-card); }
.hub-skin .intent-art { position: relative; display: grid; place-items: center; width: 100px; height: 100px; border: 1px dashed color-mix(in srgb, var(--accent-3, #4ecdc4) 40%, transparent); border-radius: 50%; color: var(--accent-3, #4ecdc4); }
.hub-skin .intent-art span { position: absolute; inset: 12px; border: 1px solid color-mix(in srgb, var(--accent-3, #4ecdc4) 20%, transparent); border-radius: 50%; }
.hub-skin .intent-art i { position: absolute; width: 9px; height: 9px; right: 7px; top: 13px; border-radius: 50%; background: var(--accent-3, #4ecdc4); box-shadow: 0 0 18px color-mix(in srgb, var(--accent-3, #4ecdc4) 45%, transparent); }
.hub-skin .intent-step { margin: 0 0 9px; color: var(--accent-3, #4ecdc4); font-size: 11px; }
.hub-skin .intent-panel-copy h3 { margin: 0 0 10px; font-size: clamp(18px, 2vw, 24px); letter-spacing: -.03em; line-height: 1.35; }
.hub-skin .intent-panel-copy > p:last-child { margin: 0; max-width: 540px; color: var(--text-secondary); font-size: 13px; line-height: 1.8; }
.hub-skin .intent-panel-actions { display: flex; flex-direction: column; align-items: center; gap: 12px; }
.hub-skin .intent-panel-actions > a:last-child { display: inline-flex; align-items: center; gap: 6px; color: var(--text-secondary); font-size: 12px; min-height: 44px; }
.hub-skin .people-discovery-banner { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin: 20px 0; padding: 28px; border: 1px solid color-mix(in srgb, var(--accent-3, #4ecdc4) 25%, transparent); border-radius: 20px; background: linear-gradient(110deg, color-mix(in srgb, var(--accent-3, #4ecdc4) 9%, transparent), transparent), var(--bg-card); }
.hub-skin .people-discovery-banner h2 { margin: 8px 0; font-size: clamp(20px, 2.4vw, 28px); line-height: 1.4; letter-spacing: -.035em; }
.hub-skin .people-discovery-banner p { margin: 0; font-size: 13px; color: var(--text-secondary); line-height: 1.8; }
.hub-skin .people-discovery-banner > a { flex-shrink: 0; }
.hub-skin .people-toolbar { display: flex; flex-direction: column; align-items: stretch; gap: 16px; padding: 20px; border-radius: 18px; }
.hub-skin .people-toolbar-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(130px, 200px) auto; align-items: end; gap: 12px; }
.hub-skin .people-toolbar .social-search { width: 100%; min-width: 0; min-height: 46px; margin: 0; }
.hub-skin .people-select { display: flex; flex-direction: column; gap: 6px; min-width: 0; color: var(--text-secondary); font-size: 11px; }
.hub-skin .people-select select { width: 100%; min-width: 0; min-height: 44px; padding: 9px 30px 9px 12px; color: var(--text-primary); border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent); border-radius: 10px; background: var(--bg-secondary); font: inherit; font-size: 12px; text-overflow: ellipsis; }
.hub-skin .people-refine { min-height: 46px; justify-content: center; }
.hub-skin .people-refinements { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; padding-top: 16px; border-top: 1px solid color-mix(in srgb, var(--text-primary) 10%, transparent); }
.hub-skin .people-refinements[hidden] { display: none; }
.hub-skin .people-refinements > p { grid-column: 1 / -1; margin: 0; font-size: 11px; color: var(--text-secondary); line-height: 1.6; }
.hub-skin .people-filter-chips { display: flex; gap: 8px; flex-wrap: wrap; }
.hub-skin .people-filter-chips button { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 6px 10px; color: var(--accent-3, #4ecdc4); background: color-mix(in srgb, var(--accent-3, #4ecdc4) 9%, transparent); border: 1px solid color-mix(in srgb, var(--accent-3, #4ecdc4) 25%, transparent); border-radius: 8px; font: inherit; font-size: 12px; cursor: pointer; }
.hub-skin .people-results-bar { display: flex; align-items: center; justify-content: space-between; gap: 14px; margin: 18px 0; }
.hub-skin .people-results-bar .social-result-summary { margin: 0; flex: 1; }
.hub-skin .people-live-notice { color: var(--accent-3, #4ecdc4); font-size: 12px; }
.hub-skin .people-live-notice:empty { margin: 0; }
.hub-skin .people-card-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; padding-bottom: 24px; }
.hub-skin .people-connection-card { display: flex; flex-direction: column; min-width: 0; padding: 22px; border: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent); border-radius: 20px; background: var(--bg-card); transition: transform .2s, border-color .2s; }
@media (hover: hover) { .hub-skin .people-connection-card:hover { transform: translateY(-3px); border-color: color-mix(in srgb, var(--accent-3, #4ecdc4) 50%, transparent); } }
.hub-skin .people-card-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 18px; }
.hub-skin .people-card-heading img { border-radius: 18px; object-fit: cover; flex-shrink: 0; }
.hub-skin .people-presence { font-size: 10px; color: var(--text-secondary); display: flex; gap: 6px; align-items: center; }
.hub-skin .people-presence.is-online { color: var(--accent-3, #4ecdc4); }
.hub-skin .people-presence.is-online::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
.hub-skin .people-profile-link { color: inherit; text-decoration: none; }
.hub-skin .people-profile-link h2 { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 21px; margin: 0 0 6px; overflow-wrap: anywhere; }
.hub-skin .people-profile-link h2 svg { color: var(--text-secondary); flex-shrink: 0; }
.hub-skin .people-card-role { font-size: 13px; color: var(--text-secondary); margin: 0 0 10px; }
.hub-skin .people-card-city { display: flex; align-items: center; gap: 5px; margin: 0 0 16px; font-size: 11px; color: var(--text-secondary); }
.hub-skin .people-card-tags { display: flex; flex-wrap: wrap; gap: 6px; }
.hub-skin .people-card-tags button { min-height: 36px; max-width: 100%; padding: 6px 9px; border-radius: 8px; border: 1px solid transparent; background: var(--bg-glass); color: var(--text-secondary); font: inherit; font-size: 11px; cursor: pointer; overflow-wrap: anywhere; }
.hub-skin .people-card-tags button[aria-pressed="true"] { border-color: var(--accent-3, #4ecdc4); color: var(--accent-3, #4ecdc4); }
.hub-skin .people-card-looking { flex: 1; margin: 16px 0 20px; font-size: 13px; line-height: 1.8; color: var(--text-primary); overflow-wrap: anywhere; }
.hub-skin .people-card-footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; border-top: 1px solid color-mix(in srgb, var(--text-primary) 10%, transparent); padding-top: 14px; }
.hub-skin .people-card-footer > a { display: inline-flex; align-items: center; gap: 4px; min-height: 44px; color: var(--text-secondary); font-size: 11px; }
.hub-skin .people-follow { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 9px 12px; border: 1px solid color-mix(in srgb, var(--text-primary) 16%, transparent); background: transparent; color: var(--text-primary); font: inherit; font-size: 12px; border-radius: 10px; cursor: pointer; }
.hub-skin .people-follow.is-following { color: var(--accent-1, #ff6b6b); border-color: color-mix(in srgb, var(--accent-1, #ff6b6b) 40%, transparent); background: color-mix(in srgb, var(--accent-1, #ff6b6b) 8%, transparent); }
.hub-skin :is(.intent-options, .intent-panel-actions, .people-toolbar, .people-card-grid, .people-results-bar) :is(a, button, select, input):focus-visible { outline: 2px solid var(--accent-3, #4ecdc4); outline-offset: 4px; }
@media (max-width: 1050px) {
.hub-skin .people-card-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.hub-skin .intent-panel { grid-template-columns: 80px minmax(0, 1fr); gap: 20px; }
.hub-skin .intent-art { width: 76px; height: 76px; }
.hub-skin .intent-panel-actions { grid-column: 2; flex-direction: row; justify-content: flex-start; flex-wrap: wrap; }
}
@media (max-width: 600px) {
.hub-skin .intent-heading { display: block; }
.hub-skin .intent-heading h2 { margin-top: 9px; }
.hub-skin .intent-options { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.hub-skin .intent-options button { min-height: 48px; font-size: 12px; }
.hub-skin .intent-panel { grid-template-columns: 1fr; padding: 22px; gap: 14px; }
.hub-skin .intent-art { display: none; }
.hub-skin .intent-panel-actions { grid-column: 1; align-items: flex-start; gap: 8px 16px; }
.hub-skin .people-discovery-banner { align-items: flex-start; flex-direction: column; padding: 22px; gap: 16px; }
.hub-skin .people-toolbar { padding: 16px; }
.hub-skin .people-toolbar-top { grid-template-columns: minmax(0, 1fr) auto; }
.hub-skin .people-toolbar-top .social-search { grid-column: 1 / -1; }
.hub-skin .people-refinements { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.hub-skin .people-card-grid { grid-template-columns: 1fr; gap: 12px; }
.hub-skin .people-connection-card { padding: 20px; }
.hub-skin .people-filter-chips button, .hub-skin .people-card-tags button { min-height: 44px; }
.hub-skin .people-results-bar { flex-wrap: wrap; }
}
@media (prefers-reduced-motion: reduce) {
.hub-skin :is(.people-connection-card, .intent-options button) { transition: none; transform: none; }
}

File diff suppressed because it is too large Load Diff

579
src/modules/hub/app/fx.css Normal file
View File

@ -0,0 +1,579 @@
/* —— 动效强化(玻璃面板风格;禁止大图卡) —— */
.social-fx {
position: relative;
isolation: isolate;
overflow-x: clip;
}
.social-fx #particle-canvas {
z-index: 0;
pointer-events: none;
opacity: 0.95;
}
.social-fx-orbs {
position: fixed;
inset: 0;
z-index: 0;
pointer-events: none;
overflow: hidden;
}
.social-fx-orb {
position: absolute;
border-radius: 50%;
filter: blur(70px);
opacity: 0.35;
animation: social-orb-drift 12s ease-in-out infinite;
}
.social-fx-orb.o1 {
width: 340px;
height: 340px;
left: -80px;
top: 18%;
background: #ff6b6b;
}
.social-fx-orb.o2 {
width: 280px;
height: 280px;
right: -60px;
top: 48%;
background: #4ecdc4;
animation-delay: -4s;
animation-duration: 14s;
}
.social-fx-orb.o3 {
width: 260px;
height: 260px;
left: 40%;
bottom: 8%;
background: #ffe66d;
animation-delay: -7s;
animation-duration: 16s;
}
@keyframes social-orb-drift {
0%,
100% {
transform: translate(0, 0) scale(1);
}
33% {
transform: translate(40px, -50px) scale(1.12);
}
66% {
transform: translate(-30px, 30px) scale(0.92);
}
}
/* Hero emoji rain */
.social-hero-fx {
position: relative;
}
.social-emoji-field {
position: absolute;
inset: 0;
pointer-events: none;
overflow: hidden;
z-index: 2;
}
.social-emoji-float {
position: absolute;
line-height: 1;
filter: none;
animation-name: social-emoji-fly;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
will-change: transform, opacity;
opacity: 0.22;
}
.social-emoji-field-soft {
z-index: 0;
opacity: 0.55;
}
@keyframes social-emoji-fly {
0%,
100% {
transform: translate3d(0, 4px, 0) rotate(-2deg) scale(1);
opacity: 0.14;
}
50% {
transform: translate3d(4px, -8px, 0) rotate(2deg) scale(1.04);
opacity: 0.28;
}
}
/* Emoji marquee belt — quiet divider */
.social-fx-belt {
overflow: hidden;
padding: 6px 0 10px;
opacity: 0.35;
mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
}
.social-fx-belt-track {
display: flex;
width: max-content;
gap: 0;
animation: social-belt-run 48s linear infinite;
}
.social-fx-belt-track span {
padding-right: 56px;
font-size: 0.95rem;
letter-spacing: 0.45em;
white-space: nowrap;
opacity: 0.4;
}
@keyframes social-belt-run {
from {
transform: translateX(0);
}
to {
transform: translateX(-33.333%);
}
}
/* Section spark */
.social-section-spark {
display: flex;
justify-content: center;
margin-bottom: 8px;
min-height: 28px;
}
.social-section-spark-svg {
width: min(240px, 72%);
height: 28px;
}
.social-spark-path {
stroke-dasharray: 280;
stroke-dashoffset: 280;
}
.reveal.visible .social-spark-path {
animation: social-spark-draw 1.1s ease forwards;
}
@keyframes social-spark-draw {
to {
stroke-dashoffset: 0;
}
}
.social-spark-dot {
animation: social-spark-blink 1.4s ease-in-out infinite;
}
@keyframes social-spark-blink {
0%,
100% {
opacity: 0.35;
r: 3;
}
50% {
opacity: 1;
r: 6;
}
}
.social-title-emoji {
display: inline-block;
margin-right: 0.28em;
opacity: 0.82;
animation: none;
transform: none;
}
@keyframes social-emoji-wiggle {
0%,
100% {
transform: rotate(0deg) scale(1);
}
50% {
transform: rotate(2deg) scale(1.02);
}
}
/* Path pills bounce in */
.social-path-track.reveal.visible .social-path-link {
animation: social-path-pop 0.55s cubic-bezier(0.2, 0.9, 0.2, 1.2) both;
}
.social-path-track.reveal.visible .social-path-link:nth-child(1) {
animation-delay: 0.05s;
}
.social-path-track.reveal.visible .social-path-link:nth-child(2) {
animation-delay: 0.12s;
}
.social-path-track.reveal.visible .social-path-link:nth-child(3) {
animation-delay: 0.19s;
}
.social-path-track.reveal.visible .social-path-link:nth-child(4) {
animation-delay: 0.26s;
}
@keyframes social-path-pop {
from {
opacity: 0;
transform: translateY(16px) scale(0.86);
}
to {
opacity: 1;
transform: none;
}
}
.social-path-link {
display: inline-flex;
align-items: center;
gap: 6px;
}
.social-path-emoji {
display: inline-block;
font-size: 1.05rem;
transition: transform 0.25s;
}
.social-path-link:hover .social-path-emoji {
animation: social-emoji-wiggle 0.55s ease;
}
/* CTA pulse */
.social-btn-pulse {
position: relative;
overflow: visible;
}
.social-btn-pulse::before,
.social-btn-pulse::after {
content: "";
position: absolute;
inset: -4px;
border-radius: inherit;
border: 2px solid rgba(78, 205, 196, 0.55);
pointer-events: none;
animation: social-btn-ring 1.6s ease-out infinite;
}
.social-btn-pulse::before {
animation-delay: 0.8s;
}
@keyframes social-btn-ring {
0% {
transform: scale(1);
opacity: 0.75;
}
100% {
transform: scale(1.28);
opacity: 0;
}
}
.social-promo-glow {
animation: social-promo-breathe 3.2s ease-in-out infinite;
}
@keyframes social-promo-breathe {
0%,
100% {
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 0 0 rgba(78, 205, 196, 0);
transform: translateY(0);
}
50% {
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.38), 0 0 48px 4px rgba(78, 205, 196, 0.28);
transform: translateY(-4px);
}
}
.social-promo-live {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 6px;
border-radius: 999px;
background: #22c55e;
vertical-align: middle;
animation: social-live-ping 1.2s ease-out infinite;
}
@keyframes social-live-ping {
0% {
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.65);
}
70% {
box-shadow: 0 0 0 10px rgba(34, 197, 94, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0);
}
}
/* Panels: animate when revealed */
.social-panel-fx {
--stagger: 0ms;
}
.reveal.visible .social-panel-fx,
.social-panel-fx.reveal.visible {
animation: social-panel-in 0.65s cubic-bezier(0.2, 0.8, 0.2, 1) both;
animation-delay: var(--stagger, 0ms);
}
@keyframes social-panel-in {
from {
opacity: 0;
transform: translateY(28px) scale(0.96) rotateX(6deg);
}
to {
opacity: 1;
transform: none;
}
}
.social-panel-fx:hover {
transform: translateY(-6px) scale(1.01);
box-shadow: var(--shadow-glow), 0 0 0 1px rgba(78, 205, 196, 0.28);
transition: transform 0.25s, box-shadow 0.25s;
}
.social-panel-ico {
width: 52px;
height: 52px;
display: grid;
place-items: center;
border-radius: 16px;
border: var(--border-glass);
background: color-mix(in srgb, var(--accent-3, #4ecdc4) 14%, transparent);
font-size: 1.45rem;
color: var(--accent-3, #4ecdc4);
animation: social-ico-bounce 2s ease-in-out infinite;
}
.social-panel-ico-bounce {
animation-duration: 1.6s;
}
@keyframes social-ico-bounce {
0%,
100% {
transform: translateY(0) rotate(0deg);
}
50% {
transform: translateY(-8px) rotate(-6deg);
}
}
.social-ring-spin {
transform-origin: 24px 24px;
animation: social-ring-spin 3.5s linear infinite;
}
@keyframes social-ring-spin {
to {
transform: rotate(360deg);
}
}
/* People chips */
.social-chip-pop {
animation: social-chip-in 0.5s cubic-bezier(0.2, 0.9, 0.2, 1.15) both;
animation-delay: var(--stagger, 0ms);
}
@keyframes social-chip-in {
from {
opacity: 0;
transform: scale(0.5) translateY(12px);
}
to {
opacity: 1;
transform: none;
}
}
.social-people-chip:hover {
transform: translateY(-6px) scale(1.05) !important;
}
.social-people-chip.is-online .social-people-chip-ava::before {
content: "";
position: absolute;
inset: -4px;
border-radius: 999px;
border: 2px solid rgba(78, 205, 196, 0.65);
animation: social-btn-ring 1.4s ease-out infinite;
}
.social-people-bar-avs img {
animation: social-ava-bob 2.4s ease-in-out infinite;
}
.social-people-bar-avs img:nth-child(2) {
animation-delay: 0.15s;
}
.social-people-bar-avs img:nth-child(3) {
animation-delay: 0.3s;
}
.social-people-bar-avs img:nth-child(4) {
animation-delay: 0.45s;
}
.social-people-bar-avs img:nth-child(5) {
animation-delay: 0.6s;
}
.social-people-bar-avs img:nth-child(6) {
animation-delay: 0.75s;
}
@keyframes social-ava-bob {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-5px);
}
}
.social-chip-heart {
position: absolute;
top: -4px;
right: -6px;
font-style: normal;
font-size: 0.8rem;
color: #ff6b6b;
animation: social-heart-pop 0.45s ease;
}
@keyframes social-heart-pop {
from {
transform: scale(0);
}
70% {
transform: scale(1.35);
}
to {
transform: scale(1);
}
}
.social-count-pulse {
display: inline-block;
color: var(--accent-3, #4ecdc4);
animation: social-count-glow 1.4s ease-in-out infinite;
}
@keyframes social-count-glow {
0%,
100% {
text-shadow: 0 0 0 transparent;
transform: scale(1);
}
50% {
text-shadow: 0 0 16px rgba(78, 205, 196, 0.9);
transform: scale(1.08);
}
}
.social-detail-in {
animation: social-detail-slide 0.4s cubic-bezier(0.2, 0.9, 0.2, 1);
position: relative;
overflow: hidden;
}
@keyframes social-detail-slide {
from {
opacity: 0;
transform: translateY(16px) scale(0.98);
}
to {
opacity: 1;
transform: none;
}
}
.social-burst {
position: absolute;
inset: 0;
display: grid;
place-items: center;
font-size: 1rem;
letter-spacing: 0.2em;
pointer-events: none;
opacity: 0.55;
animation: social-burst-up 0.55s ease forwards;
z-index: 2;
}
@keyframes social-burst-up {
from {
opacity: 0;
transform: translateY(6px) scale(0.9);
}
40% {
opacity: 0.55;
}
to {
opacity: 0;
transform: translateY(-18px) scale(1.05);
}
}
.social-logo-spin {
display: inline-block;
animation: social-logo-spin 6s linear infinite;
}
@keyframes social-logo-spin {
to {
transform: rotate(360deg);
}
}
.social-panel .btn-sm {
display: inline-flex;
align-items: center;
gap: 6px;
}
.social-hero-fx .shape {
animation-duration: 5.5s !important;
opacity: 0.55 !important;
}
@media (prefers-reduced-motion: reduce) {
.social-experience[data-immersive="false"] .social-emoji-float,
.social-experience[data-immersive="false"] .social-fx-orb,
.social-experience[data-immersive="false"] .social-fx-belt-track,
.social-experience[data-immersive="false"] .social-btn-pulse::before,
.social-experience[data-immersive="false"] .social-btn-pulse::after,
.social-experience[data-immersive="false"] .social-promo-glow,
.social-experience[data-immersive="false"] .social-promo-live,
.social-experience[data-immersive="false"] .social-panel-fx,
.social-experience[data-immersive="false"] .social-chip-pop,
.social-experience[data-immersive="false"] .social-title-emoji,
.social-experience[data-immersive="false"] .social-panel-ico,
.social-experience[data-immersive="false"] .social-ring-spin,
.social-experience[data-immersive="false"] .social-logo-spin,
.social-experience[data-immersive="false"]
.social-people-chip.is-online
.social-people-chip-ava::before,
.social-experience[data-immersive="false"] .social-people-bar-avs img,
.social-experience[data-immersive="false"] .social-count-pulse,
.social-experience[data-immersive="false"] .social-spark-path,
.social-experience[data-immersive="false"] .social-spark-dot,
.social-experience[data-immersive="false"] .social-hero-fx .shape {
animation: none !important;
}
}

File diff suppressed because it is too large Load Diff

3363
src/modules/hub/app/h5.css Normal file

File diff suppressed because it is too large Load Diff

3498
src/modules/hub/app/home.css Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,195 @@
/* Social Live — silent by default; float chip only when someone is online */
.social-live-shell {
z-index: 40;
display: flex;
flex-direction: column;
gap: 0;
pointer-events: none;
}
.social-live-shell > * {
pointer-events: auto;
}
/* Home: never steal sticky space under nav / hero brand */
.social-live-shell.is-home {
position: fixed;
left: 12px;
bottom: calc(76px + env(safe-area-inset-bottom, 0px));
right: auto;
top: auto;
width: auto;
max-width: min(72vw, 280px);
}
.social-live-shell:not(.is-home) {
position: sticky;
top: 0;
}
.social-live-offline {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: rgba(26, 18, 8, 0.92);
border: 1px solid rgba(245, 158, 11, 0.28);
border-radius: 12px;
color: #f8fafc;
margin: 8px 12px 0;
}
.social-live-shell.is-home .social-live-offline {
margin: 0 0 8px;
}
.social-live-offline strong {
display: block;
font-size: 0.8rem;
font-weight: 650;
}
.social-live-offline p {
margin: 1px 0 0;
font-size: 0.72rem;
color: #94a3b8;
line-height: 1.3;
}
.social-live-strip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 5px 10px 5px 8px;
background: rgba(12, 12, 15, 0.72);
backdrop-filter: blur(12px);
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: 999px;
color: #e2e8f0;
font-size: 0.75rem;
width: fit-content;
margin: 8px 12px 0;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
}
.social-live-strip.is-float,
.social-live-shell.is-home .social-live-strip {
margin: 0;
}
.social-live-strip strong {
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 3px;
letter-spacing: 0.01em;
}
.social-live-count {
font-style: normal;
font-variant-numeric: tabular-nums;
color: #34d399;
font-weight: 700;
min-width: 0.9em;
}
.social-live-dot {
width: 7px;
height: 7px;
border-radius: 999px;
background: #64748b;
flex-shrink: 0;
}
.social-live-dot.is-ok {
background: #22c55e;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.2);
animation: social-live-pulse 2.2s ease-in-out infinite;
}
.social-live-dot.is-warn {
background: #f59e0b;
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
}
@keyframes social-live-pulse {
0%,
100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.12);
opacity: 0.78;
}
}
.social-live-avs {
display: flex;
align-items: center;
margin-left: 2px;
}
.social-live-avs > * {
margin-left: -5px;
border-radius: 999px;
border: 1.5px solid #0c0c0f;
overflow: hidden;
}
.social-live-avs > *:first-child {
margin-left: 0;
}
.social-live-ver {
margin-left: 4px;
font-size: 0.65rem;
color: #64748b;
font-variant-numeric: tabular-nums;
}
.social-live-toast {
position: fixed;
left: 50%;
bottom: calc(72px + env(safe-area-inset-bottom, 0px));
transform: translateX(-50%);
z-index: 80;
max-width: min(92vw, 360px);
padding: 10px 16px;
border-radius: 12px;
background: #111827;
border: 1px solid rgba(52, 211, 153, 0.35);
color: #ecfdf5;
font-size: 0.85rem;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
animation: social-live-toast-in 0.28s ease-out;
}
@keyframes social-live-toast-in {
from {
opacity: 0;
transform: translateX(-50%) translateY(8px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@media (min-width: 901px) {
.social-live-shell.is-home {
bottom: 28px;
left: 24px;
}
.social-live-toast {
bottom: 28px;
}
}
@media (prefers-reduced-motion: reduce) {
.social-live-dot.is-ok,
.social-live-toast {
animation: none;
}
}

View File

@ -0,0 +1,542 @@
/* Immersive motion — beat Codex home.css mutes (loaded last). */
.social-experience[data-immersive="true"] .social-ambient i {
opacity: 0.22 !important;
filter: blur(80px);
animation: sx-aurora 18s ease-in-out infinite alternate !important;
}
.social-experience[data-immersive="true"] .social-ambient i:nth-child(2) {
opacity: 0.16 !important;
animation-duration: 22s !important;
animation-direction: alternate-reverse !important;
}
.social-experience[data-immersive="true"] .social-ambient i:nth-child(3) {
opacity: 0.12 !important;
animation-duration: 26s !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orbs {
opacity: 0.72 !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orb.o3 {
display: block !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orb {
animation: social-orb-drift 8s ease-in-out infinite !important;
filter: blur(48px) !important;
opacity: 0.62 !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orb.o2 {
animation-duration: 10s !important;
animation-delay: -3s !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orb.o3 {
animation-duration: 12s !important;
animation-delay: -6s !important;
}
.social-experience[data-immersive="true"] .social-constellation {
opacity: 1 !important;
}
.social-experience[data-immersive="true"] .social-pointer-glow {
background: radial-gradient(
480px circle at var(--pointer-x, -1000px) var(--pointer-y, -1000px),
rgba(78, 205, 196, 0.18),
rgba(255, 107, 107, 0.06) 42%,
transparent 72%
) !important;
}
/* Hero floating emoji */
.connection-hero {
position: relative;
overflow: clip;
}
.connection-hero .social-emoji-field {
z-index: 0;
opacity: 0.5;
}
.connection-hero-layout {
position: relative;
z-index: 2;
}
.social-experience[data-immersive="true"] .social-emoji-float {
opacity: 0.22 !important;
filter: none !important;
animation-name: social-emoji-fly !important;
animation-timing-function: ease-in-out !important;
animation-iteration-count: infinite !important;
will-change: transform, opacity;
}
.social-experience[data-immersive="false"] .social-emoji-field,
.social-experience[data-immersive="false"] .social-fx-belt {
display: none !important;
}
/* Signal bars */
.social-experience[data-immersive="true"] .connection-signal i {
animation: social-signal-bars 1s ease-in-out infinite !important;
transform-origin: bottom !important;
}
.social-experience[data-immersive="true"] .connection-signal i:nth-child(2) {
animation-delay: 0.1s !important;
}
.social-experience[data-immersive="true"] .connection-signal i:nth-child(3) {
animation-delay: 0.2s !important;
}
.social-experience[data-immersive="true"] .connection-signal i:nth-child(4) {
animation-delay: 0.3s !important;
}
@keyframes social-signal-bars {
0%,
100% {
transform: scaleY(0.4);
opacity: 0.4;
}
50% {
transform: scaleY(1);
opacity: 1;
}
}
.social-experience[data-immersive="true"] .connection-status-dot {
box-shadow: 0 0 0 0 rgba(78, 205, 196, 0.6) !important;
animation: social-live-ping 1.25s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-orbit-traveler {
animation-duration: 12s !important;
}
.social-experience[data-immersive="true"] .connection-orbit-traveler-second {
animation-duration: 16s !important;
}
.social-experience[data-immersive="true"] .connection-flight-path {
animation-duration: 10s !important;
opacity: 0.95 !important;
stroke-width: 2.2 !important;
}
.social-experience[data-immersive="true"] .connection-center-icon {
animation: social-center-glow 2.4s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-center-icon svg {
animation: connection-breathe 2s ease-in-out infinite !important;
}
@keyframes social-center-glow {
0%,
100% {
box-shadow:
0 0 36px rgba(78, 205, 196, 0.14),
inset 0 1px 0 rgba(255, 255, 255, 0.08);
}
50% {
box-shadow:
0 0 80px rgba(78, 205, 196, 0.42),
0 0 120px rgba(255, 107, 107, 0.12),
inset 0 1px 0 rgba(255, 255, 255, 0.16);
}
}
.social-experience[data-immersive="true"] .connection-person {
animation-duration: 4s !important;
}
.social-experience[data-immersive="true"] .connection-universe:hover .connection-person,
.social-experience[data-immersive="true"]
.connection-universe:focus-within
.connection-person {
animation-play-state: running !important;
}
.social-experience[data-immersive="true"] .connection-person-avatar > i {
animation: social-live-ping 1.35s ease-out infinite !important;
}
/* Title emoji: visible but calm (no infinite wiggle) */
.social-experience[data-immersive="true"] .social-home .social-title-emoji {
display: inline-block !important;
margin-right: 0.28em !important;
animation: none !important;
opacity: 0.85 !important;
}
.social-experience[data-immersive="true"] .social-home .social-btn-pulse {
position: relative !important;
overflow: visible !important;
}
.social-experience[data-immersive="true"] .social-home .social-btn-pulse::before,
.social-experience[data-immersive="true"] .social-home .social-btn-pulse::after {
content: "" !important;
display: block !important;
position: absolute !important;
inset: -5px !important;
border-radius: inherit !important;
border: 2px solid rgba(78, 205, 196, 0.55) !important;
pointer-events: none !important;
animation: social-btn-ring 1.4s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-btn-pulse::before {
animation-delay: 0.7s !important;
}
.social-experience[data-immersive="true"] .social-home .social-people-bar-avs img {
animation: social-ava-bob 1.8s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-people-bar-avs
img:nth-child(2) {
animation-delay: 0.1s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-people-bar-avs
img:nth-child(3) {
animation-delay: 0.2s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-people-bar-avs
img:nth-child(4) {
animation-delay: 0.3s !important;
}
.social-experience[data-immersive="true"] .social-home .social-count-pulse {
animation: social-count-glow 1.15s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .nav-logo .logo-icon {
animation: social-logo-spin 6s linear infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-path-track a,
.social-experience[data-immersive="true"]
.social-home
.social-path-track.reveal.visible
.social-path-link {
animation: social-path-pop 0.55s cubic-bezier(0.2, 0.9, 0.2, 1.15) both !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-path-track.reveal.visible
a:nth-child(1) {
animation-delay: 0.04s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-path-track.reveal.visible
a:nth-child(2) {
animation-delay: 0.1s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-path-track.reveal.visible
a:nth-child(3) {
animation-delay: 0.16s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-path-track.reveal.visible
a:nth-child(4) {
animation-delay: 0.22s !important;
}
.social-experience[data-immersive="true"] .social-home .social-path-emoji {
display: inline-block !important;
transition: transform 0.25s !important;
}
.social-experience[data-immersive="true"]
.social-home
.social-path-link:hover
.social-path-emoji {
animation: social-emoji-wiggle 0.5s ease !important;
}
/* Meetup equalizer always on in immersive */
.social-experience[data-immersive="true"] .connection-audio-bars i {
animation: connection-audio 1.05s ease-in-out infinite !important;
animation-play-state: running !important;
}
.social-experience[data-immersive="true"]
.social-home
.connection-cafe
.social-panel-ico {
animation: none !important;
}
.social-experience[data-immersive="true"]
.social-home
.connection-cafe:hover
.social-panel-ico {
animation: social-ico-bounce 1.55s ease-in-out 1 !important;
}
.social-experience[data-immersive="true"] .social-chip-pop {
animation: social-chip-in 0.5s cubic-bezier(0.2, 0.9, 0.2, 1.15) both !important;
animation-delay: var(--stagger, 0ms) !important;
}
.social-experience[data-immersive="true"]
.social-people-chip.is-online
.social-people-chip-ava {
position: relative;
}
.social-experience[data-immersive="true"]
.social-people-chip.is-online
.social-people-chip-ava::before {
content: "" !important;
position: absolute !important;
inset: -5px !important;
border-radius: 999px !important;
border: 2px solid rgba(78, 205, 196, 0.7) !important;
animation: social-btn-ring 1.25s ease-out infinite !important;
pointer-events: none !important;
}
/* Emoji belt */
.social-experience[data-immersive="true"] .social-fx-belt {
opacity: 1 !important;
padding: 14px 0 22px !important;
}
.social-experience[data-immersive="true"] .social-fx-belt-track {
animation: social-belt-run 14s linear infinite !important;
}
.social-experience[data-immersive="true"] .social-fx-belt-track span {
font-size: 1.65rem !important;
opacity: 0.82 !important;
letter-spacing: 0.45em !important;
}
/* Join CTA ring */
.social-experience[data-immersive="true"] .connection-join {
position: relative !important;
overflow: visible !important;
}
.social-experience[data-immersive="true"] .connection-join::after {
content: "" !important;
position: absolute !important;
inset: -6px !important;
border-radius: inherit !important;
border: 2px solid rgba(255, 107, 107, 0.5) !important;
animation: social-btn-ring 1.45s ease-out infinite !important;
pointer-events: none !important;
}
/* Section spark always draws when visible */
.social-experience[data-immersive="true"] .reveal.visible .social-spark-path {
animation: social-spark-draw 1s ease forwards !important;
}
.social-experience[data-immersive="true"] .social-spark-dot {
animation: social-spark-blink 1.2s ease-in-out infinite !important;
}
/* Panel lift */
.social-experience[data-immersive="true"] .reveal.visible .social-panel-fx,
.social-experience[data-immersive="true"] .social-panel-fx.reveal.visible {
animation: social-panel-in 0.65s cubic-bezier(0.2, 0.8, 0.2, 1) both !important;
animation-delay: var(--stagger, 0ms) !important;
}
/* Workspace subpages share immersive FX with home */
.social-experience[data-immersive="true"] .social-workspace .social-fx-orbs {
opacity: 0.58 !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-fx-orb {
animation: social-orb-drift 9s ease-in-out infinite !important;
filter: blur(52px) !important;
opacity: 0.55 !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-title-emoji {
display: inline-block !important;
margin-right: 0.28em;
animation: none !important;
opacity: 0.85 !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse {
position: relative !important;
overflow: visible !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse::before,
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse::after {
content: "" !important;
display: block !important;
position: absolute !important;
inset: -5px !important;
border-radius: inherit !important;
border: 2px solid rgba(78, 205, 196, 0.5) !important;
pointer-events: none !important;
animation: social-btn-ring 1.45s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse::before {
animation-delay: 0.7s !important;
}
.social-experience[data-immersive="true"] .social-room-hero-emoji i {
animation-name: social-emoji-fly !important;
animation-timing-function: ease-in-out !important;
animation-iteration-count: infinite !important;
opacity: 0.25 !important;
filter: none !important;
}
.social-experience[data-immersive="true"] .social-role-art > i {
animation: sx-orbit 18s linear infinite !important;
}
.social-experience[data-immersive="true"] .social-page-intro .social-emoji-float {
opacity: 0.2 !important;
}
/*
* Immersive is an explicit opt-in. It must beat OS prefers-reduced-motion
* (Windows “显示动画” off, automation browsers, etc.). Light mode still respects reduce.
*/
@media (prefers-reduced-motion: reduce) {
.social-experience[data-immersive="true"] .social-constellation,
.social-experience[data-immersive="true"] .social-pointer-glow {
display: block !important;
}
.social-experience[data-immersive="true"] .social-emoji-float {
animation-name: social-emoji-fly !important;
animation-timing-function: ease-in-out !important;
animation-iteration-count: infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-fx-orb,
.social-experience[data-immersive="true"] .social-workspace .social-fx-orb {
animation: social-orb-drift 8s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-title-emoji {
animation: none !important;
}
.social-experience[data-immersive="true"] .social-room-hero-emoji i {
animation-name: social-emoji-fly !important;
animation-iteration-count: infinite !important;
opacity: 0.22 !important;
}
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse::before,
.social-experience[data-immersive="true"] .social-workspace .social-btn-pulse::after {
animation: social-btn-ring 1.45s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .social-fx-belt-track {
animation: social-belt-run 48s linear infinite !important;
}
.social-experience[data-immersive="true"] .connection-signal i {
animation: social-signal-bars 1s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-status-dot,
.social-experience[data-immersive="true"] .connection-person-avatar > i {
animation: social-live-ping 1.25s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-orbit-traveler {
animation-duration: 12s !important;
animation-play-state: running !important;
}
.social-experience[data-immersive="true"] .connection-flight-path {
animation-play-state: running !important;
}
.social-experience[data-immersive="true"] .connection-center-icon {
animation: social-center-glow 2.4s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-center-icon svg {
animation: connection-breathe 2s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-title-emoji {
display: inline-block !important;
animation: none !important;
}
.social-experience[data-immersive="true"] .social-home .social-btn-pulse::before,
.social-experience[data-immersive="true"] .social-home .social-btn-pulse::after,
.social-experience[data-immersive="true"] .connection-join::after,
.social-experience[data-immersive="true"]
.social-people-chip.is-online
.social-people-chip-ava::before {
animation: social-btn-ring 1.4s ease-out infinite !important;
}
.social-experience[data-immersive="true"] .connection-audio-bars i {
animation: connection-audio 1.05s ease-in-out infinite !important;
animation-play-state: running !important;
}
.social-experience[data-immersive="true"] .social-home .connection-cafe .social-panel-ico {
animation: social-ico-bounce 1.55s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-people-bar-avs img {
animation: social-ava-bob 1.8s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .social-count-pulse {
animation: social-count-glow 1.15s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .social-home .nav-logo .logo-icon {
animation: social-logo-spin 6s linear infinite !important;
}
.social-experience[data-immersive="true"] .social-ambient i {
animation: sx-aurora 18s ease-in-out infinite alternate !important;
}
.social-experience[data-immersive="true"] .social-spark-dot {
animation: social-spark-blink 1.2s ease-in-out infinite !important;
}
.social-experience[data-immersive="true"] .reveal.visible .social-spark-path {
animation: social-spark-draw 1s ease forwards !important;
}
}

View File

@ -0,0 +1,166 @@
/* Slim shell tokens + nav base — replaces @community/app/globals.css on /hub */
:root {
--bg-primary: #0a0e17;
--bg-secondary: #111827;
--bg-card: rgba(17, 24, 39, 0.7);
--bg-glass: rgba(255, 255, 255, 0.05);
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--text-muted: #64748b;
--accent-1: #ff6b6b;
--accent-2: #ffe66d;
--accent-3: #4ecdc4;
--accent-4: #4ecdc4;
--gradient-main: linear-gradient(135deg, #ff6b6b, #ffe66d, #4ecdc4);
--gradient-text: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%);
--shadow-glow: 0 0 40px rgba(78, 205, 196, 0.15);
--shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3);
--border-glass: 1px solid rgba(255, 255, 255, 0.08);
--radius-sm: 8px;
--radius-md: 16px;
--radius-lg: 24px;
--radius-xl: 32px;
--font-display: var(--font-outfit), "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "Noto Sans SC", sans-serif;
--font-body: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",
"Noto Sans SC", var(--font-outfit), sans-serif;
--nav-height: 72px;
--transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
[data-theme="light"] {
--bg-primary: #f8fafc;
--bg-secondary: #ffffff;
--bg-card: rgba(255, 255, 255, 0.85);
--bg-glass: rgba(0, 0, 0, 0.03);
--text-primary: #0f172a;
--text-secondary: #475569;
--text-muted: #94a3b8;
--shadow-glow: 0 0 40px rgba(78, 205, 196, 0.1);
--shadow-card: 0 8px 32px rgba(0, 0, 0, 0.08);
--border-glass: 1px solid rgba(0, 0, 0, 0.06);
}
.community-root.hub-skin {
min-height: 100dvh;
background: var(--bg-primary);
color: var(--text-primary);
font-family: var(--font-body);
}
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--nav-height);
z-index: 1000;
transition: all var(--transition);
background: transparent;
}
.navbar.scrolled {
background: rgba(10, 14, 23, 0.85);
backdrop-filter: blur(20px);
border-bottom: var(--border-glass);
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);
}
[data-theme="light"] .navbar.scrolled {
background: rgba(248, 250, 252, 0.9);
}
.nav-container {
max-width: 1200px;
margin: 0 auto;
padding: 0 24px;
height: 100%;
display: flex;
align-items: center;
gap: 16px;
}
.nav-container > .logo {
flex-shrink: 0;
}
.nav-container > .nav-links {
flex: 1;
justify-content: center;
min-width: 0;
}
.logo {
display: flex;
align-items: center;
gap: 10px;
font-family: var(--font-display);
font-weight: 800;
font-size: 1.35rem;
letter-spacing: -0.02em;
}
.logo span {
background: linear-gradient(135deg, #ff6b6b, #ffe66d, #4ecdc4);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.logo-icon {
width: 36px;
height: 36px;
flex-shrink: 0;
}
.nav-links {
display: flex;
gap: 8px;
}
.nav-links a {
padding: 8px 16px;
border-radius: var(--radius-sm);
font-size: 0.9rem;
font-weight: 500;
color: var(--text-secondary);
transition: all var(--transition);
}
.nav-links a:hover {
color: var(--text-primary);
background: var(--bg-glass);
}
.mobile-menu-btn {
display: none;
flex-direction: column;
gap: 5px;
background: none;
border: none;
cursor: pointer;
padding: 8px;
}
.mobile-menu-btn span {
display: block;
width: 24px;
height: 2px;
background: var(--text-primary);
border-radius: 2px;
transition: all 0.3s ease;
transform-origin: center;
}
.mobile-menu-btn.open span:nth-child(1) {
transform: translateY(7px) rotate(45deg);
}
.mobile-menu-btn.open span:nth-child(2) {
opacity: 0;
transform: scaleX(0);
}
.mobile-menu-btn.open span:nth-child(3) {
transform: translateY(-7px) rotate(-45deg);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,494 @@
/**
* 游民社区 · 主题 2「琥珀信号」
* 与主题 1(旅居社群对齐)完全独立;html[data-hub-skin="2"] 启用。
*/
html[data-hub-skin="2"] .hub-skin {
--t2-ink: #07070a;
--t2-panel: #101016;
--t2-line: rgba(245, 158, 11, 0.22);
--t2-amber: #f59e0b;
--t2-amber-dim: rgba(245, 158, 11, 0.14);
--t2-cyan: #22d3ee;
--t2-text: #f4f1ea;
--t2-muted: #9a958c;
--t2-danger: #fb7185;
--t2-radius: 4px;
--t2-font-display: "Segoe UI Variable Display", "Bahnschrift", "DIN Alternate",
var(--font-outfit), system-ui, sans-serif;
--t2-font-body: var(--font-noto-sc), "Segoe UI", system-ui, sans-serif;
--sc-bg: var(--t2-ink);
--sc-bg-card: color-mix(in srgb, var(--t2-panel) 92%, transparent);
--sc-bg-glass: var(--t2-amber-dim);
--sc-text: var(--t2-text);
--sc-muted: var(--t2-muted);
--sc-accent-1: var(--t2-amber);
--sc-accent-2: #fbbf24;
--sc-accent-3: var(--t2-cyan);
--sc-gradient: linear-gradient(120deg, #f59e0b 0%, #fbbf24 45%, #22d3ee 100%);
--sc-border: 1px solid var(--t2-line);
--sc-radius: var(--t2-radius);
--sc-shadow: 0 0 0 1px rgba(245, 158, 11, 0.08), 0 24px 60px rgba(0, 0, 0, 0.45);
--sc-font-display: var(--t2-font-display);
--sc-font-body: var(--t2-font-body);
}
html.light[data-hub-skin="2"] .hub-skin,
html[data-theme="light"][data-hub-skin="2"] .hub-skin {
--t2-ink: #f6f3eb;
--t2-panel: #ffffff;
--t2-line: rgba(120, 80, 10, 0.18);
--t2-amber: #b45309;
--t2-amber-dim: rgba(180, 83, 9, 0.08);
--t2-cyan: #0e7490;
--t2-text: #1c1917;
--t2-muted: #78716c;
--sc-shadow: 0 0 0 1px rgba(180, 83, 9, 0.08), 0 18px 40px rgba(28, 25, 23, 0.08);
}
/* —— 壳 / 背景 —— */
html[data-hub-skin="2"] .social-flow,
html[data-hub-skin="2"] .social-root,
html[data-hub-skin="2"] .home-flow.social-flow {
background:
linear-gradient(180deg, rgba(245, 158, 11, 0.07), transparent 28%),
repeating-linear-gradient(
0deg,
transparent,
transparent 47px,
rgba(245, 158, 11, 0.035) 48px
),
radial-gradient(ellipse 80% 50% at 100% 0%, rgba(34, 211, 238, 0.08), transparent 55%),
var(--t2-ink, #07070a);
color: var(--t2-text, #f4f1ea);
font-family: var(--t2-font-body);
}
html[data-hub-skin="2"] .social-flow::before {
content: "";
pointer-events: none;
position: fixed;
inset: 0;
z-index: 0;
background: radial-gradient(circle at 12% 88%, rgba(245, 158, 11, 0.08), transparent 32%);
}
html[data-hub-skin="2"] .navbar {
border-bottom: 1px solid var(--t2-line);
background: color-mix(in srgb, var(--t2-ink) 78%, transparent);
backdrop-filter: blur(18px) saturate(1.2);
}
html[data-hub-skin="2"] .navbar.scrolled {
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
}
html[data-hub-skin="2"] .logo-icon {
border-radius: var(--t2-radius);
background: var(--t2-amber);
color: #111;
box-shadow: 0 0 24px rgba(245, 158, 11, 0.45);
}
html[data-hub-skin="2"] .logo-text {
font-family: var(--t2-font-display);
letter-spacing: 0.08em;
text-transform: uppercase;
font-size: 0.92rem;
}
html[data-hub-skin="2"] .btn-primary,
html[data-hub-skin="2"] .social-btn.primary,
html[data-hub-skin="2"] .social-compose button {
border-radius: var(--t2-radius);
background: var(--t2-amber) !important;
color: #111 !important;
border: none !important;
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.08), 0 8px 28px rgba(245, 158, 11, 0.35);
font-weight: 700;
letter-spacing: 0.02em;
}
html[data-hub-skin="2"] .btn-primary:hover,
html[data-hub-skin="2"] .social-btn.primary:hover {
filter: brightness(1.06);
transform: translateY(-1px);
}
html[data-hub-skin="2"] .btn-ghost,
html[data-hub-skin="2"] .social-btn,
html[data-hub-skin="2"] .social-nav-back {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: transparent;
}
html[data-hub-skin="2"] .nav-group-btn,
html[data-hub-skin="2"] .nav-dropdown-link,
html[data-hub-skin="2"] .nav-icon-btn {
border-radius: var(--t2-radius);
}
html[data-hub-skin="2"] .nav-dropdown {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: var(--t2-panel);
box-shadow: var(--sc-shadow);
}
/* 皮肤切换器 */
html[data-hub-skin="2"] .hub-skin-switch,
.hub-skin-switch {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 3px;
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(0, 0, 0, 0.25);
}
.hub-skin-switch button {
min-height: 36px;
min-width: 44px;
padding: 0 10px;
border: none;
border-radius: 4px;
background: transparent;
color: var(--sc-muted, #94a3b8);
font: inherit;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.04em;
cursor: pointer;
}
.hub-skin-switch button[aria-pressed="true"] {
background: var(--t2-amber, #f59e0b);
color: #111;
}
html[data-hub-skin="1"] .hub-skin-switch button[aria-pressed="true"] {
background: #4ecdc4;
color: #0a0e17;
}
/* —— Hero:品牌优先、少卡片 —— */
html[data-hub-skin="2"] .hero {
min-height: 100dvh;
display: flex;
align-items: stretch;
border-bottom: 1px solid var(--t2-line);
}
html[data-hub-skin="2"] .hero-bg-shapes .shape {
opacity: 0.28;
filter: saturate(0.55) hue-rotate(18deg);
}
html[data-hub-skin="2"] #particles-canvas,
html[data-hub-skin="2"] .particle-canvas {
opacity: 0.45;
mix-blend-mode: screen;
}
html[data-hub-skin="2"] .hero-badge {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: var(--t2-amber-dim);
color: var(--t2-amber);
letter-spacing: 0.14em;
text-transform: uppercase;
font-size: 0.72rem;
font-weight: 700;
}
html[data-hub-skin="2"] .hero-badge .badge-dot {
background: var(--t2-amber);
box-shadow: 0 0 12px var(--t2-amber);
}
html[data-hub-skin="2"] .hero-title {
font-family: var(--t2-font-display);
font-weight: 800;
letter-spacing: -0.04em;
text-transform: none;
}
html[data-hub-skin="2"] .gradient-text {
background: linear-gradient(100deg, #f59e0b, #fde68a 55%, #22d3ee) !important;
-webkit-background-clip: text !important;
background-clip: text !important;
color: transparent !important;
}
html[data-hub-skin="2"] .hero-subtitle {
color: var(--t2-muted);
font-size: 1.05rem;
max-width: 28rem;
border-left: 2px solid var(--t2-amber);
padding-left: 14px;
}
html[data-hub-skin="2"] .float-card {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: color-mix(in srgb, var(--t2-panel) 88%, transparent);
backdrop-filter: blur(10px);
font-family: var(--t2-font-display);
letter-spacing: 0.04em;
}
html[data-hub-skin="2"] .float-card small {
color: var(--t2-muted);
letter-spacing: 0;
}
html[data-hub-skin="2"] .globe-svg circle[fill="url(#hubGlobeGlow)"] {
opacity: 0.7;
}
/* PATH:竖轨信号条 */
html[data-hub-skin="2"] .journey-strip {
background: transparent;
}
html[data-hub-skin="2"] .section-tag {
color: var(--t2-amber);
letter-spacing: 0.2em;
border: 1px solid var(--t2-line);
border-radius: var(--t2-radius);
padding: 4px 8px;
background: var(--t2-amber-dim);
}
html[data-hub-skin="2"] .section-header h2,
html[data-hub-skin="2"] .social-hub-block-head h3,
html[data-hub-skin="2"] .social-hero h1,
html[data-hub-skin="2"] .social-section-head h2 {
font-family: var(--t2-font-display);
letter-spacing: -0.03em;
}
html[data-hub-skin="2"] .journey-card,
html[data-hub-skin="2"] .social-hub-card,
html[data-hub-skin="2"] .social-next-card,
html[data-hub-skin="2"] .social-card,
html[data-hub-skin="2"] .social-list-item,
html[data-hub-skin="2"] .social-panel {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background:
linear-gradient(135deg, var(--t2-amber-dim), transparent 42%),
var(--t2-panel);
box-shadow: none;
backdrop-filter: none;
}
html[data-hub-skin="2"] .social-hub-card:hover,
html[data-hub-skin="2"] .social-next-card:hover,
html[data-hub-skin="2"] .social-card:hover,
html[data-hub-skin="2"] .journey-card:hover {
transform: translateY(-2px);
border-color: rgba(245, 158, 11, 0.55);
box-shadow: 0 0 0 1px rgba(245, 158, 11, 0.2), 0 16px 40px rgba(0, 0, 0, 0.35);
}
html[data-hub-skin="2"] .social-hub-emoji,
html[data-hub-skin="2"] .social-card-ico {
border-radius: var(--t2-radius);
background: #000;
border: 1px solid var(--t2-line);
}
html[data-hub-skin="2"] .social-pill,
html[data-hub-skin="2"] .social-badge {
border-radius: var(--t2-radius);
letter-spacing: 0.08em;
text-transform: uppercase;
font-size: 0.68rem;
}
html[data-hub-skin="2"] .social-pill.live,
html[data-hub-skin="2"] .social-badge.live {
color: var(--t2-amber);
border-color: rgba(245, 158, 11, 0.45);
background: var(--t2-amber-dim);
}
html[data-hub-skin="2"] .social-hub-go,
html[data-hub-skin="2"] .social-next-card em,
html[data-hub-skin="2"] .social-list-item em {
color: var(--t2-amber);
font-style: normal;
}
html[data-hub-skin="2"] .journey-n {
color: var(--t2-amber);
font-family: var(--t2-font-display);
}
/* HUB:改成通栏带状,减弱「卡片堆」感 */
html[data-hub-skin="2"] .social-hub-grid {
grid-template-columns: 1fr;
gap: 10px;
}
html[data-hub-skin="2"] .social-hub-card {
min-height: 0;
display: grid;
grid-template-columns: auto 1fr auto;
grid-template-rows: auto auto;
gap: 6px 16px;
align-items: center;
padding: 16px 18px;
}
html[data-hub-skin="2"] .social-hub-card-top {
grid-column: 1;
grid-row: 1 / span 2;
}
html[data-hub-skin="2"] .social-hub-card h4 {
grid-column: 2;
grid-row: 1;
margin: 0;
}
html[data-hub-skin="2"] .social-hub-card p {
grid-column: 2;
grid-row: 2;
}
html[data-hub-skin="2"] .social-hub-card .social-pill {
display: none;
}
html[data-hub-skin="2"] .social-hub-go {
grid-column: 3;
grid-row: 1 / span 2;
align-self: center;
font-family: var(--t2-font-display);
letter-spacing: 0.06em;
}
html[data-hub-skin="2"] .social-next-grid {
grid-template-columns: 1fr;
gap: 10px;
}
@media (min-width: 900px) {
html[data-hub-skin="2"] .social-next-grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* Chat */
html[data-hub-skin="2"] .social-chat-thread {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background:
linear-gradient(180deg, rgba(245, 158, 11, 0.05), transparent 20%),
#0a0a0e;
max-height: min(62vh, 560px);
}
html[data-hub-skin="2"] .social-bubble {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: var(--t2-panel);
}
html[data-hub-skin="2"] .social-bubble.mine {
background: linear-gradient(160deg, rgba(245, 158, 11, 0.22), rgba(34, 211, 238, 0.08));
border-color: rgba(245, 158, 11, 0.4);
}
html[data-hub-skin="2"] .social-compose input,
html[data-hub-skin="2"] .social-form input,
html[data-hub-skin="2"] .social-form textarea,
html[data-hub-skin="2"] .social-chat-nick input {
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: #0a0a0e;
}
html[data-hub-skin="2"] .social-compose {
position: sticky;
bottom: 12px;
padding: 10px;
border-radius: var(--t2-radius);
border: 1px solid var(--t2-line);
background: color-mix(in srgb, var(--t2-panel) 90%, transparent);
backdrop-filter: blur(12px);
}
html[data-hub-skin="2"] .social-compose button {
border-radius: var(--t2-radius) !important;
min-width: 96px;
}
html[data-hub-skin="2"] .social-hero-tag {
border-radius: var(--t2-radius);
color: var(--t2-amber);
border-color: var(--t2-line);
background: var(--t2-amber-dim);
letter-spacing: 0.12em;
text-transform: uppercase;
font-size: 0.72rem;
font-weight: 700;
}
html[data-hub-skin="2"] .social-hero h1 span {
background: linear-gradient(100deg, #f59e0b, #22d3ee);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
html[data-hub-skin="2"] .footer {
border-top: 1px solid var(--t2-line);
background: #050508;
}
html[data-hub-skin="2"] .footer-cols h4 {
color: var(--t2-amber);
letter-spacing: 0.12em;
text-transform: uppercase;
font-size: 0.75rem;
}
html[data-hub-skin="2"] .social-live-tab.active {
background: var(--t2-amber) !important;
color: #111 !important;
}
html[data-hub-skin="2"] .social-live-iframe-mark {
background: var(--t2-amber) !important;
color: #111 !important;
border-radius: var(--t2-radius);
}
html[data-hub-skin="2"] .social-live-iframe-overlay h2 {
background: linear-gradient(100deg, #f59e0b, #22d3ee);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
@media (max-width: 640px) {
html[data-hub-skin="2"] .social-hub-card {
grid-template-columns: auto 1fr;
}
html[data-hub-skin="2"] .social-hub-go {
grid-column: 2;
grid-row: 3;
justify-self: start;
}
html[data-hub-skin="2"] .hub-skin-switch button {
min-width: 40px;
font-size: 0.72rem;
}
}

View File

@ -0,0 +1,8 @@
/**
* 游民社区 · 主题 3「预留」
* html[data-hub-skin="3"] 启用。当前继承主题1变量,后续可独立换肤。
*/
html[data-hub-skin="3"] .hub-skin {
/* 预留钩子:后续覆盖 --sc-* 即可 */
}

Some files were not shown because too many files have changed in this diff Show More