Wire Hub API aliases, Next proxy, and .com admin cn lane for /hub.

Include hub Next API routes and admin module select so the China-only Hub ship can build and mount on nomadro.com.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-29 00:03:33 +08:00
parent d971a1f3e6
commit 1058eca8af
31 changed files with 1328 additions and 110 deletions

View File

@ -155,12 +155,18 @@ from ebook_svc.routers import ( # noqa: E402
social_ugc_admin,
social_locale_geo_admin,
social_blog_admin,
hub_ugc_admin,
hub_locale_geo_admin,
hub_blog_admin,
community_admin,
)
app.include_router(social_ugc_admin.router)
app.include_router(social_locale_geo_admin.router)
app.include_router(social_blog_admin.router)
app.include_router(hub_ugc_admin.router)
app.include_router(hub_locale_geo_admin.router)
app.include_router(hub_blog_admin.router)
app.include_router(community_admin.router)
app.include_router(shop_admin.router)
app.include_router(memo_admin.router)

View File

@ -1,31 +1,39 @@
# admin.nomadro.com(Web 运营台)
包名:`@nomadro/admin-com`。源码在 `apps/com/admin`,与 `apps/admin`(`.cn` 微信/抖音)隔离。
包名:`@nomadro/admin-com`。源码在 `apps/com/admin`,与 `apps/admin`(`.cn` 微信/抖音)及 `apps/hackrobot`(VIP)隔离。
**生产**:前后端都在美国机(`admin.nomadro.com` + `api.nomadro.com`)。
**生产**:美国机 `admin.nomadro.com` + `api.nomadro.com` / `nomadro.com`。
## 能力
## 受众真分轨(强制)
2026-11 升级:响应式深浅主题、可搜索导航、移动菜单键盘操作、路由错误恢复;新增 `/:lane/operations` 服务资源监控。配置页显示实时版本并阻止过期版本覆盖;订单分页、状态识别与安全 CSV 导出已加强。线上验收与回滚见 [平台升级记录](../../../docs/platform-upgrade-2026-11.md)。
登录 → **全屏选轨** → 进入该轨壳。两轨 **互不混挂** 对方社区后台;误入路径自动改写。
流程:登录 → **全屏选模块** → 进入该模块壳。
| 轨 | 路径前缀 | 默认指挥台 | 社区产品 | 门户对照 |
|---|---|---|---|---|
| **中文 cn** | `/cn/*` | `/cn/hub/overview` | **Hub** `/hub` | `/portal` · 三大模块(导航/小册/Hub) |
| **国际 intl** | `/intl/*` | `/intl/social/overview` | **Social** `/social` | `/social/home` |
- 侧栏 SoT:`src/lib/adminNav.ts`(cn 只挂 Hub 树;intl 只挂 Social 树)
- 默认首页:`src/lib/laneHome.ts`
- 切轨(顶栏 / Alt+1/2):`social` ↔ `hub` 路径互映射(`WebLayout.switchLane`)
- 路由门禁:`RequireCommunity`(cn 进 `/social/*` → `/hub/*`;intl 进 `/hub/*` → `/social/*`)
- 页面开关:cn 优先展示 Hub 模块键;intl 优先 Social
## 其它能力
响应式深浅主题、可搜索导航、移动菜单、路由错误恢复、`/:lane/operations` 服务监控;配置页版本防覆盖;订单分页与 CSV 导出。
| 页 | 路径 | 说明 |
|---|---|---|
| 选模块 | `/` | 登录后中间页(无侧栏) |
| 中文用户 | `/cn/*` | 特殊线运营壳 |
| 国际用户 | `/intl/*` | 默认线运营壳 |
| 子页 | `…/switches|events|orders|users|ntfy|docs` | 模块内工具 |
| 选轨 | `/modules` | 登录后中间页(无侧栏) |
| 中文 | `/cn/hub/*` · `/cn/switches` … | Hub 运营 + 门户开关 / 价格 / 增长 |
| 国际 | `/intl/social/*` · `/intl/switches` … | Social 运营 + 同上 |
## 部署
```bash
pnpm build:admin-com
python apps/admin/deploy/_deploy_admin_com_us.py
# ntfy 试推 API(增量)
python apps/admin/deploy/_deploy_ops_admin_us.py
```
登录:`hackrobot` / `Xiao4669805@`
本地一般不启本包;门户调试见 [`apps/com/README.md`](../README.md)。
本地:`pnpm dev:admin-com`。门户联调见 [`apps/com/README.md`](../README.md)。

View File

@ -1,11 +1,16 @@
import { Navigate, Route, Routes, useParams } from 'react-router-dom'
import { Navigate, Route, Routes, useLocation, useParams } from 'react-router-dom'
import { getToken } from './api/client'
import { readLane } from './lib/lane'
import { laneHomeRelative } from './lib/laneHome'
import {
Blog,
Denylist,
Docs,
Events,
HubDenylist,
HubDetail,
HubExperience,
HubLocaleGeo,
Ntfy,
Orders,
SocialDetail,
@ -19,15 +24,44 @@ import ModuleSelect from './pages/ModuleSelect'
import WebLayout from './components/WebLayout'
/** Hot paths — no Suspense flash on first entry after login. */
import Social from './pages/Social'
import Hub from './pages/Hub'
import Pricing from './pages/Pricing'
import Google from './pages/Google'
import Operations from './pages/Operations'
import LaneHub, { type LaneKey } from './pages/LaneHub'
/**
* admin.nomadro.com — 游民社区运营台
* 登录 → /{lane}/social/overview(社区优先)
* admin.nomadro.com — 受众分轨运营台
* cn → /cn/hub/overview · intl → /intl/social/overview
*/
function LaneIndexRedirect() {
const { lane } = useParams()
return <Navigate to={laneHomeRelative(lane)} replace />
}
/** cn 只运营 Hub;intl 只运营 Social — 误入对方路径自动改写 */
function RequireCommunity({
kind,
children,
}: {
kind: 'social' | 'hub'
children: React.ReactNode
}) {
const { lane } = useParams()
const { pathname } = useLocation()
if (kind === 'social' && lane === 'cn') {
return <Navigate to={pathname.replace(/\/social(\/|$)/, '/hub$1')} replace />
}
if (kind === 'hub' && lane === 'intl') {
return <Navigate to={pathname.replace(/\/hub(\/|$)/, '/social$1')} replace />
}
return <>{children}</>
}
function withCommunity(kind: 'social' | 'hub', node: React.ReactNode) {
return <RequireCommunity kind={kind}>{node}</RequireCommunity>
}
function Private({ children }: { children: React.ReactNode }) {
if (!getToken()) return <Navigate to="/login" replace />
return <>{children}</>
@ -83,52 +117,92 @@ export default function App() {
</Private>
}
>
<Route index element={<Navigate to="social/overview" replace />} />
<Route index element={<LaneIndexRedirect />} />
<Route path="audience" element={<LaneHome />} />
<Route path="operations" element={<Operations />} />
<Route path="pricing" element={<Pricing />} />
<Route path="switches" element={<Switches />} />
<Route path="google" element={<Google />} />
<Route path="social" element={<Navigate to="overview" replace />} />
<Route path="social/overview" element={<Social />} />
<Route path="social/roster" element={<Social />} />
<Route path="social/messages" element={<Social />} />
<Route path="social/reviews" element={<Social />} />
<Route path="social/meetupReviews" element={<Social />} />
<Route path="social/gigs" element={<Social />} />
<Route path="social/skills" element={<Social />} />
<Route path="social/liveness" element={<Social />} />
<Route path="social/roomArchives" element={<Social />} />
<Route path="social/coffee" element={<Social />} />
<Route path="social/trips" element={<Social />} />
<Route path="social/reports" element={<Social />} />
<Route path="social/blocks" element={<Social />} />
<Route path="social/denylist" element={<Denylist />} />
<Route path="social/files" element={<Social />} />
<Route path="social/feedback" element={<Social />} />
<Route path="social/archives" element={<Social />} />
<Route path="social/joins" element={<Social />} />
<Route path="social/catalog" element={<Social />} />
<Route path="social/locale-geo" element={<SocialLocaleGeo />} />
<Route path="social/experience" element={<SocialExperience />} />
<Route path="social/roster/:id" element={<SocialDetail />} />
<Route path="social/messages/:id" element={<SocialDetail />} />
<Route path="social/reviews/:id" element={<SocialDetail />} />
<Route path="social/meetupReviews/:id" element={<SocialDetail />} />
<Route path="social/gigs/:id" element={<SocialDetail />} />
<Route path="social/gigApps/:id" element={<SocialDetail />} />
<Route path="social/skills/:id" element={<SocialDetail />} />
<Route path="social/liveness/:id" element={<SocialDetail />} />
<Route path="social/roomArchives/:id" element={<SocialDetail />} />
<Route path="social/coffee/:id" element={<SocialDetail />} />
<Route path="social/trips/:id" element={<SocialDetail />} />
<Route path="social/reports/:id" element={<SocialDetail />} />
<Route path="social/blocks/:id" element={<SocialDetail />} />
<Route path="social/files/:id" element={<SocialDetail />} />
<Route path="social/feedback/:id" element={<SocialDetail />} />
<Route path="social/joins/:id" element={<SocialDetail />} />
<Route path="social/archives/:id" element={<SocialDetail />} />
<Route path="social/:section" element={<Social />} />
<Route path="social/overview" element={withCommunity('social', <Social />)} />
<Route path="social/roster" element={withCommunity('social', <Social />)} />
<Route path="social/messages" element={withCommunity('social', <Social />)} />
<Route path="social/reviews" element={withCommunity('social', <Social />)} />
<Route path="social/meetupReviews" element={withCommunity('social', <Social />)} />
<Route path="social/gigs" element={withCommunity('social', <Social />)} />
<Route path="social/skills" element={withCommunity('social', <Social />)} />
<Route path="social/liveness" element={withCommunity('social', <Social />)} />
<Route path="social/roomArchives" element={withCommunity('social', <Social />)} />
<Route path="social/coffee" element={withCommunity('social', <Social />)} />
<Route path="social/trips" element={withCommunity('social', <Social />)} />
<Route path="social/reports" element={withCommunity('social', <Social />)} />
<Route path="social/blocks" element={withCommunity('social', <Social />)} />
<Route path="social/denylist" element={withCommunity('social', <Denylist />)} />
<Route path="social/files" element={withCommunity('social', <Social />)} />
<Route path="social/feedback" element={withCommunity('social', <Social />)} />
<Route path="social/archives" element={withCommunity('social', <Social />)} />
<Route path="social/joins" element={withCommunity('social', <Social />)} />
<Route path="social/catalog" element={withCommunity('social', <Social />)} />
<Route path="social/locale-geo" element={withCommunity('social', <SocialLocaleGeo />)} />
<Route path="social/experience" element={withCommunity('social', <SocialExperience />)} />
<Route path="social/roster/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/messages/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/reviews/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/meetupReviews/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/gigs/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/gigApps/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/skills/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/liveness/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/roomArchives/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/coffee/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/trips/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/reports/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/blocks/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/files/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/feedback/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/joins/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/archives/:id" element={withCommunity('social', <SocialDetail />)} />
<Route path="social/:section" element={withCommunity('social', <Social />)} />
<Route path="hub" element={<Navigate to="overview" replace />} />
<Route path="hub/overview" element={withCommunity('hub', <Hub />)} />
<Route path="hub/roster" element={withCommunity('hub', <Hub />)} />
<Route path="hub/messages" element={withCommunity('hub', <Hub />)} />
<Route path="hub/reviews" element={withCommunity('hub', <Hub />)} />
<Route path="hub/meetupReviews" element={withCommunity('hub', <Hub />)} />
<Route path="hub/gigs" element={withCommunity('hub', <Hub />)} />
<Route path="hub/skills" element={withCommunity('hub', <Hub />)} />
<Route path="hub/liveness" element={withCommunity('hub', <Hub />)} />
<Route path="hub/roomArchives" element={withCommunity('hub', <Hub />)} />
<Route path="hub/coffee" element={withCommunity('hub', <Hub />)} />
<Route path="hub/trips" element={withCommunity('hub', <Hub />)} />
<Route path="hub/reports" element={withCommunity('hub', <Hub />)} />
<Route path="hub/blocks" element={withCommunity('hub', <Hub />)} />
<Route path="hub/denylist" element={withCommunity('hub', <HubDenylist />)} />
<Route path="hub/files" element={withCommunity('hub', <Hub />)} />
<Route path="hub/feedback" element={withCommunity('hub', <Hub />)} />
<Route path="hub/archives" element={withCommunity('hub', <Hub />)} />
<Route path="hub/joins" element={withCommunity('hub', <Hub />)} />
<Route path="hub/catalog" element={withCommunity('hub', <Hub />)} />
<Route path="hub/locale-geo" element={withCommunity('hub', <HubLocaleGeo />)} />
<Route path="hub/experience" element={withCommunity('hub', <HubExperience />)} />
<Route path="hub/roster/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/messages/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/reviews/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/meetupReviews/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/gigs/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/gigApps/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/skills/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/liveness/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/roomArchives/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/coffee/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/trips/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/reports/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/blocks/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/files/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/feedback/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/joins/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/archives/:id" element={withCommunity('hub', <HubDetail />)} />
<Route path="hub/:section" element={withCommunity('hub', <Hub />)} />
<Route path="blog" element={<Blog />} />
<Route path="events" element={<Events />} />
<Route path="orders" element={<Orders />} />

View File

@ -140,9 +140,18 @@ export default function WebLayout() {
function switchLane(next: LaneKey) {
if (next === lane) return
const rest =
pathname.replace(/^\/(cn|intl)/, '').replace(/(\/social\/[^/]+)\/[^/]+$/, '$1') ||
'/social/overview'
let rest = pathname.replace(/^\/(cn|intl)/, '')
// 详情页收拢到列表段
rest = rest.replace(/(\/(?:social|hub)\/[^/]+)\/[^/]+$/, '$1')
// cn 只运营 Hub;intl 只运营 Social — 切轨时互映射路径
if (next === 'cn') {
rest = rest.replace(/^\/social(\/|$)/, '/hub$1')
} else {
rest = rest.replace(/^\/hub(\/|$)/, '/social$1')
}
if (!rest || rest === '/') {
rest = next === 'cn' ? '/hub/overview' : '/social/overview'
}
nav(`/${next}${rest.startsWith('/') ? rest : `/${rest}`}`)
}

View File

@ -25,6 +25,10 @@ export const Ntfy = lz(() => import('../pages/Ntfy'))
export const SocialDetail = lz(() => import('../pages/SocialDetail'))
export const SocialLocaleGeo = lz(() => import('../pages/SocialLocaleGeo'))
export const SocialExperience = lz(() => import('../pages/SocialExperience'))
export const HubDetail = lz(() => import('../pages/HubDetail'))
export const HubLocaleGeo = lz(() => import('../pages/HubLocaleGeo'))
export const HubExperience = lz(() => import('../pages/HubExperience'))
export const HubDenylist = lz(() => import('../pages/HubDenylist'))
export const Blog = lz(() => import('../pages/Blog'))
export const Denylist = lz(() => import('../pages/Denylist'))
@ -35,6 +39,7 @@ export function warmSecondaryChunks() {
void Switches.preload()
void Events.preload()
void SocialExperience.preload()
void HubExperience.preload()
void Denylist.preload()
}
if (typeof requestIdleCallback === 'function') {
@ -49,6 +54,10 @@ export function preloadForPath(to: string) {
if (to.includes('/social/experience')) return void SocialExperience.preload()
if (to.includes('/social/locale-geo')) return void SocialLocaleGeo.preload()
if (/\/social\/[^/]+\/[^/]+/.test(to)) return void SocialDetail.preload()
if (to.includes('/hub/experience')) return void HubExperience.preload()
if (to.includes('/hub/locale-geo')) return void HubLocaleGeo.preload()
if (/\/hub\/[^/]+\/[^/]+/.test(to)) return void HubDetail.preload()
if (to.includes('/hub/denylist')) return void HubDenylist.preload()
if (to.includes('/blog')) return void Blog.preload()
if (to.includes('/switches')) return void Switches.preload()
if (to.includes('/events')) return void Events.preload()

View File

@ -1,9 +1,11 @@
/**
* Poll social who's-online for admin chrome.
* Poll who's-online for admin chrome (cn→Hub · intl→Social).
* Emits toast when someone newly appears.
*/
import { useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import { api } from '../api/client'
import { laneCommunitySegment } from './laneHome'
export type PresencePeer = {
guestId: string
@ -33,6 +35,8 @@ const EMPTY: PresenceSnap = {
const POLL_MS = 8000
export function useSocialPresenceLive(): PresenceSnap {
const { lane } = useParams()
const community = laneCommunitySegment(lane)
const [snap, setSnap] = useState<PresenceSnap>(EMPTY)
const seen = useRef<Set<string>>(new Set())
const booted = useRef(false)
@ -40,6 +44,9 @@ export function useSocialPresenceLive(): PresenceSnap {
useEffect(() => {
let cancelled = false
let timer: ReturnType<typeof setInterval> | null = null
seen.current = new Set()
booted.current = false
setSnap(EMPTY)
const pull = async () => {
if (cancelled || document.hidden) return
@ -49,7 +56,7 @@ export function useSocialPresenceLive(): PresenceSnap {
online?: number
peers?: PresencePeer[]
cityOnline?: number
}>('/api/admin/social/ugc/presence?limit=48')
}>(`/api/admin/${community}/ugc/presence?limit=48`)
if (cancelled) return
const peers = Array.isArray(data.peers) ? data.peers : []
const online = Number(data.online) || peers.length
@ -91,7 +98,7 @@ export function useSocialPresenceLive(): PresenceSnap {
if (timer) clearInterval(timer)
document.removeEventListener('visibilitychange', onVis)
}
}, [])
}, [community])
return snap
}

View File

@ -142,16 +142,45 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
.catch(() => setSocialCounts(null))
}, [lane])
const community = lane === 'cn' ? 'hub' : 'social'
const tools = [
{ to: `/${lane}/social/overview`, ico: '01', title: '指挥台', desc: '加入 / 自拍 / 举报优先' },
{
to: `/${lane}/${community}/overview`,
ico: '01',
title: lane === 'cn' ? 'Hub 指挥台' : 'Social 指挥台',
desc:
lane === 'cn'
? '中文游民社区 /hub · 加入 / 自拍 / 举报'
: 'International /social · joins / liveness / reports',
},
{ to: `/${lane}/pricing`, ico: lane === 'cn' ? '¥' : '$', title: '动态价格', desc: '免费 / 付费一键切换 · 体验次数' },
{ to: `/${lane}/switches`, ico: '02', title: '页面开关', desc: '模块显隐 · VIP 入口 · 文案' },
{ to: `/${lane}/social/experience`, ico: '03', title: '体验主题', desc: '主题1/2/3/4 · 首页编排 · 文案' },
{ to: `/${lane}/social/locale-geo`, ico: '04', title: '语言国家', desc: '多语言开关 · 国家目录 · 优先城市' },
{
to: `/${lane}/switches`,
ico: '02',
title: '页面开关',
desc: lane === 'cn' ? '导航·小册·Hub 显隐' : 'Nav·Book·Social·VIP',
},
{
to: `/${lane}/${community}/experience`,
ico: '03',
title: '体验主题',
desc: '主题1/2/3/4 · 首页编排 · 文案',
},
{
to: `/${lane}/${community}/locale-geo`,
ico: '04',
title: '语言国家',
desc: '多语言开关 · 国家目录 · 优先城市',
},
{ to: `/${lane}/blog`, ico: '05', title: 'Nomad Blog', desc: '文章显隐 / 置顶' },
{ to: `/${lane}/orders`, ico: '06', title: '订单', desc: '支付与发货' },
{ to: `/${lane}/users`, ico: '07', title: '用户', desc: '解锁与干预' },
{ to: `/${lane}/social/denylist`, ico: '🛡', title: '封禁名单', desc: '手动拉黑 / 解封' },
{
to: `/${lane}/${community}/denylist`,
ico: '🛡',
title: '封禁名单',
desc: '手动拉黑 / 解封',
},
{ to: `/${lane}/events`, ico: '08', title: '用户分析', desc: '访客 · DAU · 漏斗 · 事件流' },
{ to: `/${lane}/ntfy`, ico: '09', title: '通知', desc: 'ntfy 试推' },
]

View File

@ -1,6 +1,7 @@
import { FormEvent, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api, clearToken, setToken } from '../api/client'
import { sanitizeLaneReturnPath } from '../lib/laneHome'
export default function Login() {
const nav = useNavigate()
@ -24,10 +25,7 @@ export default function Login() {
setToken(data.token)
const saved = sessionStorage.getItem('nomadro_admin_return') || ''
sessionStorage.removeItem('nomadro_admin_return')
nav(
/^\/(cn|intl)(\/|$)/.test(saved) ? saved : '/modules',
{ replace: true },
)
nav(saved ? sanitizeLaneReturnPath(saved) : '/modules', { replace: true })
} catch (ex: unknown) {
setErr(ex instanceof Error ? ex.message : '登录失败')
} finally {
@ -44,11 +42,11 @@ export default function Login() {
<img src="/apple-touch-icon.png" width={56} height={56} alt="" />
<div>
<h1>Nomadro Ops</h1>
<p>admin.nomadro.com · 社区运营台</p>
<p>admin.nomadro.com · Hub / Social 分轨</p>
</div>
</div>
<p className="login-hint" style={{ marginTop: 0 }}>
🚀 中文轨 / 国际轨分治 · 支付与关注互不覆盖
中文 → Hub(/hub)· 国际 → Social(/social)· 支付与关注互不覆盖
</p>
<label>
用户名
@ -79,7 +77,7 @@ export default function Login() {
<button type="submit" disabled={loading}>
{loading ? '进入中…' : '✨ 进入运营台'}
</button>
<p className="login-hint">登录后选择 CN / INTL 受众轨。</p>
<p className="login-hint">登录后选择 CN(Hub)/ INTL(Social)。</p>
</form>
</div>
)

View File

@ -1,9 +1,10 @@
import { useNavigate } from 'react-router-dom'
import { clearToken } from '../api/client'
import { writeLane } from '../lib/lane'
import { laneHomePath } from '../lib/laneHome'
import { LANE_THEMES } from '../lib/laneTheme'
/** 登录后全屏选轨:中文 / 国际彻底分治 */
/** 登录后全屏选轨:中文 Hub / 国际 Social 彻底分治 */
export default function ModuleSelect() {
const nav = useNavigate()
@ -14,7 +15,7 @@ export default function ModuleSelect() {
function go(lane: 'cn' | 'intl') {
writeLane(lane)
nav(`/${lane}/social/overview`)
nav(laneHomePath(lane))
}
const cn = LANE_THEMES.cn
@ -31,9 +32,9 @@ export default function ModuleSelect() {
<div>
<h1>选择受众轨</h1>
<p>
中文与国际用户的支付、关注、文案完全分轨。
中文轨运营 Hub(/hub)· 国际轨运营 Social(/social);支付 / 关注 / 文案分轨。
<br />
<span className="modsel-note">Choose lane · CN or International</span>
<span className="modsel-note">CN → Hub · INTL → Social</span>
</p>
</div>
<button type="button" className="modsel-logout" onClick={logout}>
@ -57,11 +58,12 @@ export default function ModuleSelect() {
<span className="modsel-en">{cn.titleEn}</span>
<span className="modsel-desc">{cn.taglineZh}</span>
<ul className="modsel-facts">
<li>产品 {cn.productHint}</li>
<li>支付 {cn.payHint}</li>
<li>关注 {cn.followHint}</li>
<li>识别 {cn.detectHint}</li>
</ul>
<span className="modsel-cta">进入中文指挥台 →</span>
<span className="modsel-cta">进入中文 Hub 指挥台 →</span>
</button>
<button
@ -79,11 +81,12 @@ export default function ModuleSelect() {
<span className="modsel-en">{intl.titleZh}</span>
<span className="modsel-desc">{intl.taglineEn}</span>
<ul className="modsel-facts">
<li>Product {intl.productHint}</li>
<li>Pay {intl.payHint}</li>
<li>Follow {intl.followHint}</li>
<li>Detect {intl.detectHint}</li>
</ul>
<span className="modsel-cta">Enter international console →</span>
<span className="modsel-cta">Enter Social console →</span>
</button>
</div>
</div>

View File

@ -34,6 +34,7 @@ type SwitchesCfg = {
socialTrialEnabled?: boolean
socialAvatarFaceCheck?: boolean
socialLive?: SocialLiveCfg
hubLive?: SocialLiveCfg
}
copy: {
homeBrand: string
@ -118,17 +119,40 @@ const SOCIAL_LIVE_FLAGS: Array<{
{ key: 'trialLive', label: '尝鲜限额实时', desc: '跟随后台 trial 配置;关则用离线种子' },
]
const PAGE_MODS = [
{ key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' },
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' },
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册阅读' },
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
{ key: 'social', label: '游民社区', ico: '💕', desc: '社交大厅;关则拦截入口' },
{ key: 'socialBlog', label: 'Nomad Blog', ico: '📝', desc: '/social/blog 英文长文 · AdSense' },
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地;关则加群改弹引导' },
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
] as const
type PageMod = { key: string; label: string; ico: string; desc: string }
/** cn:门户三大公开模块(导航/小册/Hub)优先;intl:Social 优先 */
function pageModsForLane(lane: 'cn' | 'intl'): PageMod[] {
const sharedHead: PageMod[] = [
{ key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' },
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' },
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册阅读' },
]
const sharedTail: PageMod[] = [
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '后台可隐藏;公开默认关' },
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地;关则加群改弹引导' },
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
]
if (lane === 'cn') {
return [
...sharedHead,
{ key: 'hub', label: '游民社区 Hub', ico: '🧩', desc: '中文独立 /hub;关则拦截入口' },
{ key: 'hubBlog', label: 'Hub Blog', ico: '📝', desc: '/hub/blog' },
...sharedTail,
{ key: 'social', label: 'Social(国际)', ico: '💕', desc: '勿与 Hub 混用;国际轨产品' },
{ key: 'socialBlog', label: 'Social Blog', ico: '📰', desc: '/social/blog · 国际' },
]
}
return [
...sharedHead,
{ key: 'social', label: '游民社区 Social', ico: '💕', desc: '国际 /social;关则拦截入口' },
{ key: 'socialBlog', label: 'Nomad Blog', ico: '📝', desc: '/social/blog 英文长文 · AdSense' },
...sharedTail,
{ key: 'hub', label: 'Hub(中文)', ico: '🧩', desc: '中文轨产品;本轨一般不运营' },
{ key: 'hubBlog', label: 'Hub Blog', ico: '📰', desc: '/hub/blog · 中文' },
]
}
const VIP_ENTRIES = [
{ key: 'showStats', label: '数据条', desc: '落地页统计数字' },
@ -230,10 +254,12 @@ export default function Switches() {
}
}
const pageMods = useMemo(() => pageModsForLane(laneKey), [laneKey])
const onCount = useMemo(() => {
if (!cfg) return 0
return PAGE_MODS.filter((m) => cfg.modules[m.key]?.enabled !== false).length
}, [cfg])
return pageMods.filter((m) => cfg.modules[m.key]?.enabled !== false).length
}, [cfg, pageMods])
if (!cfg) {
return (
@ -259,7 +285,7 @@ export default function Switches() {
<div className="com-chip-row">
<span className="com-chip">版本 v{cfg.version ?? '—'}</span>
<span className="com-chip com-chip-ok">
页面开启 {onCount}/{PAGE_MODS.length}
页面开启 {onCount}/{pageMods.length}
</span>
<span className="com-chip">
{(Number(cfg.copy?.vipPriceFen) || 0) <= 0
@ -299,7 +325,7 @@ export default function Switches() {
<h2>页面模块</h2>
<p className="com-panel-desc">关闭后对应入口隐藏或拦截</p>
<div className="com-switch-grid">
{PAGE_MODS.map((m) => {
{pageMods.map((m) => {
const on = cfg.modules[m.key]?.enabled !== false
return (
<article key={m.key} className={`com-switch-card${on ? ' is-on' : ' is-off'}`}>
@ -442,9 +468,14 @@ export default function Switches() {
{tab === 'live' ? (
<section className="com-panel">
<h2>实时社区 · UX 超级兜底</h2>
<h2>
{laneKey === 'cn' ? '实时 Hub' : '实时 Social'} · UX 超级兜底
</h2>
<p className="com-panel-desc">
谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推;不限于下列开关,可持续扩展。
{laneKey === 'cn'
? '写入 flags.hubLive(/hub);缺省时门户仍可读 socialLive 兜底。'
: '写入 flags.socialLive(/social)。'}{' '}
谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推。
</p>
<div className="com-flag-list">
{SOCIAL_LIVE_FLAGS.map((f) => {
@ -466,7 +497,11 @@ export default function Switches() {
configVersionChip: false,
trialLive: true,
}
const raw = cfg.flags.socialLive?.[f.key]
const liveBag =
laneKey === 'cn'
? cfg.flags.hubLive || cfg.flags.socialLive
: cfg.flags.socialLive
const raw = liveBag?.[f.key]
const on =
typeof raw === 'boolean' ? raw : Boolean(defaults[f.key as string])
return (
@ -481,7 +516,12 @@ export default function Switches() {
label={f.label}
onChange={(v) =>
void patch(
{ flags: { socialLive: { [f.key]: v } } },
{
flags:
laneKey === 'cn'
? { hubLive: { [f.key]: v } }
: { socialLive: { [f.key]: v } },
},
`${f.label}已${v ? '开启' : '关闭'}`,
)
}
@ -497,12 +537,28 @@ export default function Switches() {
min={15}
max={300}
disabled={busy}
defaultValue={Number(cfg.flags.socialLive?.discoveryRefreshSec) || 45}
defaultValue={
Number(
(laneKey === 'cn'
? cfg.flags.hubLive || cfg.flags.socialLive
: cfg.flags.socialLive
)?.discoveryRefreshSec,
) || 45
}
onBlur={(e) => {
const liveBag =
laneKey === 'cn'
? cfg.flags.hubLive || cfg.flags.socialLive
: cfg.flags.socialLive
const n = Math.max(15, Math.min(300, Number(e.target.value) || 45))
if (n === Number(cfg.flags.socialLive?.discoveryRefreshSec)) return
if (n === Number(liveBag?.discoveryRefreshSec)) return
void patch(
{ flags: { socialLive: { discoveryRefreshSec: n } } },
{
flags:
laneKey === 'cn'
? { hubLive: { discoveryRefreshSec: n } }
: { socialLive: { discoveryRefreshSec: n } },
},
`发现刷新 → ${n}s`,
)
}}
@ -515,12 +571,28 @@ export default function Switches() {
min={10}
max={120}
disabled={busy}
defaultValue={Number(cfg.flags.socialLive?.presenceHeartbeatSec) || 25}
defaultValue={
Number(
(laneKey === 'cn'
? cfg.flags.hubLive || cfg.flags.socialLive
: cfg.flags.socialLive
)?.presenceHeartbeatSec,
) || 25
}
onBlur={(e) => {
const liveBag =
laneKey === 'cn'
? cfg.flags.hubLive || cfg.flags.socialLive
: cfg.flags.socialLive
const n = Math.max(10, Math.min(120, Number(e.target.value) || 25))
if (n === Number(cfg.flags.socialLive?.presenceHeartbeatSec)) return
if (n === Number(liveBag?.presenceHeartbeatSec)) return
void patch(
{ flags: { socialLive: { presenceHeartbeatSec: n } } },
{
flags:
laneKey === 'cn'
? { hubLive: { presenceHeartbeatSec: n } }
: { socialLive: { presenceHeartbeatSec: n } },
},
`心跳周期 → ${n}s`,
)
}}

View File

@ -10,6 +10,11 @@ const SOCIAL_API_URL = (
? API_URL.replace(/\bapi\.(nomadro\.(?:com|cn))\b/i, "$1")
: API_URL)
).replace(/\/$/, "");
/** Hub fork of social — independent process; defaults to same host until HUB_API_URL set. */
const HUB_API_URL = (process.env.HUB_API_URL || SOCIAL_API_URL).replace(
/\/$/,
"",
);
/**
* Micro-frontend upstreams (Planka / Etherpad).
@ -32,6 +37,7 @@ const aliases = {
"@ebook": path.resolve(__dirname, "src/modules/ebook"),
"@community": path.resolve(__dirname, "src/modules/community"),
"@social": path.resolve(__dirname, "src/modules/social"),
"@hub": path.resolve(__dirname, "src/modules/hub"),
"@navmini": path.resolve(__dirname, "src/modules/nav"),
"@vip": path.resolve(__dirname, "src/modules/vip"),
"@work": path.resolve(__dirname, "src/modules/work"),
@ -68,6 +74,7 @@ const nextConfig: NextConfig = {
"@ebook": "./src/modules/ebook",
"@community": "./src/modules/community",
"@social": "./src/modules/social",
"@hub": "./src/modules/hub",
"@navmini": "./src/modules/nav",
"@vip": "./src/modules/vip",
"@work": "./src/modules/work",
@ -121,6 +128,10 @@ const nextConfig: NextConfig = {
source: "/api/social/:path*",
destination: `${SOCIAL_API_URL}/api/social/:path*`,
},
{
source: "/api/hub/:path*",
destination: `${HUB_API_URL}/api/hub/:path*`,
},
// Local Centrifugo (scripts/dev-centrifugo.ps1). Prod uses nginx /rt/ on the portal host.
{
source: "/rt",

View File

@ -16,6 +16,7 @@
"dev:admin-com": "pnpm --filter @nomadro/admin-com dev",
"dev:api": "node scripts/dev-api.mjs",
"dev:social-api": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/dev-social.ps1",
"dev:hub-api": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/dev-hub.ps1",
"dev:centrifugo": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/dev-centrifugo.ps1",
"dev:work-api": "python -m uvicorn work_main:app --reload --port 8021 --app-dir apps/api",
"dev:notify-api": "python -m uvicorn notify_main:app --reload --port 8023 --app-dir apps/api",

View File

@ -0,0 +1,246 @@
"""Deploy Nomadro Hub API backend to US VPS only (no frontend)."""
from __future__ import annotations
import os
import tarfile
import tempfile
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
HOST, USER, PASSWORD = "108.174.50.68", "root", "Xiao4669805"
REMOTE_API = "/var/www/nomadro.cn/apps/api"
VENV_PY = f"{REMOTE_API}/.venv-social/bin/python"
INCLUDE = [
"hub_main.py",
"services/hub_svc",
"services/nomadro_pb/schemas.py",
"services/ebook_svc/services/hub_experience.py",
"services/ebook_svc/services/hub_ugc.py",
"services/ebook_svc/services/hub_locale_geo.py",
"services/ebook_svc/services/hub_blog_ops.py",
"services/ebook_svc/services/hub_ops.py",
"services/ebook_svc/services/hub_join_config.py",
"services/ebook_svc/routers/hub_ugc_admin.py",
"services/ebook_svc/routers/hub_locale_geo_admin.py",
"services/ebook_svc/routers/hub_blog_admin.py",
]
SERVICE = r"""[Unit]
Description=Nomadro Hub API (independent fork of social)
After=network.target
[Service]
EnvironmentFile=-/etc/nomadro/centrifugo.env
EnvironmentFile=-/etc/nomadro/portal.env
Type=simple
WorkingDirectory=/var/www/nomadro.cn/apps/api
Environment=HOST=127.0.0.1
Environment=PORT=8025
Environment=HUB_ENABLED=true
Environment=HUB_DB_PATH=/var/www/nomadro-data/hub/hub.db
Environment=PYTHONPATH=/var/www/nomadro.cn/apps/api:/var/www/nomadro.cn/apps/api/services
Environment=PB_URL=http://127.0.0.1:8090
Environment=POCKETBASE_URL=http://127.0.0.1:8090
Environment=PB_ADMIN_EMAIL=xiaoshuang.eric@gmail.com
Environment=PB_ADMIN_PASSWORD=Xiao4669805@
Environment=POCKETBASE_EMAIL=xiaoshuang.eric@gmail.com
Environment=POCKETBASE_PASSWORD=Xiao4669805@
Environment=S3_ENABLED=true
Environment=S3_PUBLIC_URL=https://s3.nomadro.com
Environment=S3_ENDPOINT=http://127.0.0.1:8333
Environment=S3_BUCKET=nomadweb
Environment=S3_ACCESS_KEY=nomadweb
Environment=S3_SECRET_KEY=Xiao4669805@
ExecStart=/var/www/nomadro.cn/apps/api/.venv-social/bin/python -m uvicorn hub_main:app --host 127.0.0.1 --port 8025
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
NGINX_SNIPPET = r"""
# Nomadro Hub API (independent)
location /api/hub/ {
proxy_pass http://127.0.0.1:8025;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 120s;
}
"""
def pack() -> Path:
api = ROOT / "apps" / "api"
tmp = Path(tempfile.mkdtemp(prefix="hub-be-"))
tar_path = tmp / "hub-backend.tgz"
with tarfile.open(tar_path, "w:gz") as tar:
for rel in INCLUDE:
src = api / rel
if not src.exists():
raise FileNotFoundError(src)
tar.add(src, arcname=rel)
return tar_path
def main() -> int:
tar_path = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
remote_tar = "/tmp/hub-backend.tgz"
sftp.put(str(tar_path), remote_tar)
print("uploaded", tar_path.name)
def run(cmd: str, timeout: int = 120) -> str:
print(">>", cmd[:160])
_, stdout, stderr = c.exec_command(cmd, timeout=timeout)
code = stdout.channel.recv_exit_status()
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
if out.strip():
print(out[-3000:])
if err.strip():
print("ERR", err[-1500:])
if code != 0:
raise RuntimeError(f"cmd failed ({code}): {cmd}")
return out
run(f"mkdir -p {REMOTE_API}/services /var/www/nomadro-data/hub/uploads")
run(f"tar -xzf {remote_tar} -C {REMOTE_API}")
# Patch ebook_svc main + app main on server if hub routers not included
run(
r"""python3 - <<'PY'
from pathlib import Path
paths = [
Path('/var/www/nomadro.cn/apps/api/services/ebook_svc/main.py'),
Path('/var/www/nomadro.cn/apps/api/app/main.py'),
]
needle_import = 'from ebook_svc.routers import hub_ugc_admin'
for p in paths:
if not p.exists():
print('skip missing', p); continue
t = p.read_text(encoding='utf-8')
if needle_import in t:
print('already wired', p); continue
# insert after social_blog_admin include if present
if 'social_blog_admin' in t and 'hub_ugc_admin' not in t:
t = t.replace(
'from ebook_svc.routers import social_blog_admin',
'from ebook_svc.routers import social_blog_admin\nfrom ebook_svc.routers import hub_ugc_admin\nfrom ebook_svc.routers import hub_locale_geo_admin\nfrom ebook_svc.routers import hub_blog_admin',
)
t = t.replace(
'app.include_router(social_blog_admin.router)',
'app.include_router(social_blog_admin.router)\napp.include_router(hub_ugc_admin.router)\napp.include_router(hub_locale_geo_admin.router)\napp.include_router(hub_blog_admin.router)',
)
# app/main.py style bundle import
if 'social_ugc_admin,' in t and 'hub_ugc_admin,' not in t:
t = t.replace(
'social_blog_admin,\n community_admin,',
'social_blog_admin,\n hub_ugc_admin,\n hub_locale_geo_admin,\n hub_blog_admin,\n community_admin,',
)
p.write_text(t, encoding='utf-8')
print('patched', p)
else:
print('manual check', p)
PY"""
)
# systemd unit
sftp.file("/etc/systemd/system/nomadro-hub.service", "w").write(SERVICE)
run("systemctl daemon-reload && systemctl enable --now nomadro-hub.service")
run("systemctl restart nomadro-hub.service; sleep 2; systemctl is-active nomadro-hub.service")
# ensure hub collections via social venv
run(
f"""{VENV_PY} - <<'PY'
import os, sys
sys.path[:0] = ['{REMOTE_API}', '{REMOTE_API}/services']
os.environ['PB_URL']='http://127.0.0.1:8090'
os.environ['POCKETBASE_URL']='http://127.0.0.1:8090'
os.environ['PB_ADMIN_EMAIL']='xiaoshuang.eric@gmail.com'
os.environ['PB_ADMIN_PASSWORD']='Xiao4669805@'
from nomadro_pb.ensure import ensure_selected
names={{
'hub_roster','hub_liveness_audits','hub_skill_posts','hub_meetup_reviews',
'hub_blocks','hub_reports','hub_messages','hub_channel_meta','hub_channel_reads',
'hub_files','hub_trips','hub_cafe_reviews','hub_feedback','hub_join_leads',
'hub_gig_apps','hub_archives',
}}
print('ensure', ensure_selected(names))
PY""",
timeout=180,
)
# nginx: inject snippet if missing
run(
r"""python3 - <<'PY'
from pathlib import Path
roots = list(Path('/etc/nginx').rglob('*.conf'))
hit = None
for p in roots:
try:
t = p.read_text(encoding='utf-8', errors='ignore')
except Exception:
continue
if 'nomadro.com' in t and 'server_name' in t and 'ssl' in t.lower():
if '/api/social/' in t or 'proxy_pass http://127.0.0.1:8020' in t:
hit = p
break
print('candidate', hit)
if not hit:
raise SystemExit('nginx conf not found')
t = hit.read_text(encoding='utf-8')
if '/api/hub/' in t:
print('nginx hub already present')
else:
needle = 'location /api/social/'
snip = '''
location /api/hub/ {
proxy_pass http://127.0.0.1:8025;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 120s;
}
'''
if needle in t:
t = t.replace(needle, snip + '\n ' + needle, 1)
else:
# insert before last closing brace of server
idx = t.rfind('}')
t = t[:idx] + snip + '\n' + t[idx:]
bak = hit.with_suffix(hit.suffix + '.bak-hub')
bak.write_text(hit.read_text(encoding='utf-8'), encoding='utf-8')
hit.write_text(t, encoding='utf-8')
print('wrote', hit)
PY"""
)
run("nginx -t && systemctl reload nginx")
# restart main API if present (admin hub routes)
run(
"systemctl restart nomadmini-api.service 2>/dev/null || systemctl restart nomadro-api.service 2>/dev/null || true; "
"sleep 1; curl -sS http://127.0.0.1:8025/health; echo; "
"curl -sS http://127.0.0.1:8025/api/hub/v1/health; echo; "
"curl -sk https://nomadro.com/api/hub/v1/health; echo"
)
sftp.close()
c.close()
print("HUB BACKEND DEPLOYED")
return 0
if __name__ == "__main__":
raise SystemExit(main())

16
scripts/dev-hub.ps1 Normal file
View File

@ -0,0 +1,16 @@
# Local nomadro-hub (:8025) — independent fork of social_main (:8020).
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Api = Join-Path $Root "apps\api"
Set-Location $Api
$env:HOST = "127.0.0.1"
$env:HUB_ENABLED = "true"
$env:CENTRIFUGO_ENABLED = "true"
$env:CENTRIFUGO_API_URL = "http://127.0.0.1:8008/api"
$env:CENTRIFUGO_API_KEY = "nomadro-local-centrifugo-api-key-dev-only"
$env:CENTRIFUGO_TOKEN_SECRET = "nomadro-local-centrifugo-token-hmac-dev-only"
$env:CENTRIFUGO_WS_URL = "ws://127.0.0.1:8008/connection/websocket"
Write-Host "[hub] http://127.0.0.1:8025/health centrifugo=$($env:CENTRIFUGO_ENABLED)"
python -m uvicorn hub_main:app --host 127.0.0.1 --port 8025 --reload

View File

@ -0,0 +1,51 @@
"""Ensure PocketBase hub_* collections exist (idempotent)."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
API = ROOT / "apps" / "api"
sys.path.insert(0, str(API))
sys.path.insert(0, str(API / "services"))
try:
from dotenv import load_dotenv
load_dotenv(ROOT / ".env")
load_dotenv(ROOT / ".env.local", override=True)
load_dotenv(API / ".env")
load_dotenv(API / ".env.local", override=True)
except Exception:
pass
from nomadro_pb.ensure import ensure_selected # noqa: E402
HUB_NAMES = {
"hub_roster",
"hub_liveness_audits",
"hub_skill_posts",
"hub_meetup_reviews",
"hub_blocks",
"hub_reports",
"hub_messages",
"hub_channel_meta",
"hub_channel_reads",
"hub_files",
"hub_trips",
"hub_cafe_reviews",
"hub_feedback",
"hub_join_leads",
"hub_gig_apps",
"hub_archives",
}
def main() -> int:
ok = ensure_selected(HUB_NAMES)
print("hub_collections_ok" if ok else "hub_collections_failed", sorted(HUB_NAMES))
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,96 @@
"""SSH to US VPS: ensure hub_* PB collections on same-box :8090."""
from __future__ import annotations
import sys
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
HOST, USER, PASSWORD = "108.174.50.68", "root", "Xiao4669805"
# Upload schemas + ensure script pieces and run against local PB on US.
REMOTE_PY = r'''
import sys
sys.path.insert(0, "/var/www/nomadro.cn/apps/api")
sys.path.insert(0, "/var/www/nomadro.cn/apps/api/services")
import os
os.environ.setdefault("PB_URL", "http://127.0.0.1:8090")
os.environ.setdefault("POCKETBASE_URL", "http://127.0.0.1:8090")
# admin from existing env files if present
for p in ("/var/www/nomadro.cn/apps/api/.env", "/var/www/nomadro.cn/apps/api/.env.local"):
try:
from dotenv import load_dotenv
load_dotenv(p, override=False)
except Exception:
pass
# Prefer inline credentials from service env
import subprocess, re
try:
out = subprocess.check_output(
"systemctl show nomadro-social -p Environment --value",
shell=True, text=True, stderr=subprocess.DEVNULL,
)
for part in out.replace("\n", " ").split():
if "=" in part:
k, _, v = part.partition("=")
if k.startswith("PB_") or k.startswith("POCKETBASE_"):
os.environ.setdefault(k, v)
except Exception:
pass
from nomadro_pb.ensure import ensure_selected
NAMES = {
"hub_roster","hub_liveness_audits","hub_skill_posts","hub_meetup_reviews",
"hub_blocks","hub_reports","hub_messages","hub_channel_meta","hub_channel_reads",
"hub_files","hub_trips","hub_cafe_reviews","hub_feedback","hub_join_leads",
"hub_gig_apps","hub_archives",
}
# Schemas may not include hub_* on server yet — inject from local upload
ok = False
try:
ok = ensure_selected(NAMES)
except ValueError as e:
print("schema_missing_on_server", e)
raise
print("RESULT", ok)
'''
def main() -> int:
# First upload updated schemas.py so server knows hub_* specs
local_schemas = ROOT / "apps/api/services/nomadro_pb/schemas.py"
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=25, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
remote_schemas = "/var/www/nomadro.cn/apps/api/services/nomadro_pb/schemas.py"
# backup
try:
sftp.stat(remote_schemas)
stdin, stdout, stderr = c.exec_command(
f"cp -a {remote_schemas} {remote_schemas}.bak-hub-$(date +%Y%m%d%H%M%S)"
)
stdout.channel.recv_exit_status()
except IOError:
print("remote schemas missing — portal path may differ")
sftp.put(str(local_schemas), remote_schemas)
print("uploaded schemas.py")
# Also need ensure.py if older — skip; ensure_selected already there
sftp.close()
stdin, stdout, stderr = c.exec_command("python3 - <<'PY'\n" + REMOTE_PY + "\nPY")
code = stdout.channel.recv_exit_status()
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
print(out)
if err:
print("STDERR", err[-2000:])
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Admin list of join leads — prefer local portal store (works without hub_svc deploy).
* Falls through to upstream admin API when local empty and upstream available.
*/
export async function GET(req: NextRequest) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
}
const qs = req.nextUrl.searchParams.toString();
const origin = req.nextUrl.origin;
try {
const local = await fetch(
`${origin}/api/portal/join-leads${qs ? `?${qs}` : ""}`,
{ headers: { cookie: req.headers.get('cookie') || '' }, cache: "no-store", signal: AbortSignal.timeout(5000) },
);
if (local.ok) {
const data = (await local.json()) as {
ok?: boolean;
total?: number;
items?: unknown[];
};
if (Array.isArray(data.items) && (data.items.length > 0 || data.total === 0)) {
return NextResponse.json(data);
}
}
} catch {
/* try upstream */
}
const upstream = (
process.env.ADMIN_API_URL ||
process.env.API_URL ||
""
).replace(/\/$/, "");
if (upstream) {
try {
const cookie = req.headers.get("cookie") || "";
const auth = req.headers.get("authorization") || "";
const res = await fetch(
`${upstream}/api/admin/hub/ugc/join-leads${qs ? `?${qs}` : ""}`,
{
headers: {
...(cookie ? { cookie } : {}),
...(auth ? { authorization: auth } : {}),
},
cache: "no-store",
signal: AbortSignal.timeout(8000),
},
);
const text = await res.text();
return new NextResponse(text, {
status: res.status,
headers: {
"Content-Type": res.headers.get("content-type") || "application/json",
},
});
} catch (e) {
return NextResponse.json(
{
ok: false,
total: 0,
items: [],
error: e instanceof Error ? e.message : "upstream fail",
},
{ status: 200 },
);
}
}
return NextResponse.json({ ok: true, total: 0, items: [] });
}

View File

@ -0,0 +1,127 @@
import { NextRequest, NextResponse } from "next/server";
import { HUB_PHRASES_EN } from "@hub/lib/phrases";
import { LOCALE_SET } from "~/lib/locales";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
type Body = {
q?: string | string[];
source?: string;
target?: string;
};
function phraseHit(zh: string): string | null {
return HUB_PHRASES_EN[zh] || HUB_PHRASES_EN[zh.trim()] || null;
}
async function translateViaArgos(
texts: string[],
source: string,
target: string,
): Promise<string[] | null> {
const base = (
process.env.HUB_TX_URL ||
process.env.LIBRETRANSLATE_URL ||
"http://127.0.0.1:5055"
).replace(/\/$/, "");
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 120_000);
try {
const res = await fetch(`${base}/translate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ q: texts, source, target, format: "text" }),
signal: controller.signal,
});
if (!res.ok) return null;
const data = (await res.json()) as {
translations?: string[];
translatedText?: string;
};
if (Array.isArray(data.translations)) return data.translations;
if (typeof data.translatedText === "string" && texts.length === 1) {
return [data.translatedText];
}
return null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
export async function POST(req: NextRequest) {
let body: Body;
try {
body = (await req.json()) as Body;
} catch {
return NextResponse.json({ ok: false, error: "invalid json" }, { status: 400 });
}
const source = (body.source || "zh").slice(0, 8);
const target = (body.target || "en").slice(0, 8);
if (!LOCALE_SET.has(source) || !LOCALE_SET.has(target)) {
return NextResponse.json({ ok: false, error: "unsupported lang" }, { status: 400 });
}
const list = Array.isArray(body.q)
? body.q.map(String)
: typeof body.q === "string"
? [body.q]
: [];
if (!list.length) {
return NextResponse.json({ ok: false, error: "q required" }, { status: 400 });
}
if (list.length > 60) {
return NextResponse.json({ ok: false, error: "batch too large" }, { status: 400 });
}
if (source === target) {
return NextResponse.json({ ok: true, translations: list, engine: "identity" });
}
const out: string[] = list.map(() => "");
// Curated zh→en phrases first
if (source === "zh" && target === "en") {
list.forEach((t, i) => {
out[i] = phraseHit(t) || "";
});
}
const needIdx: number[] = [];
const needTexts: string[] = [];
list.forEach((t, i) => {
if (!out[i]) {
needIdx.push(i);
needTexts.push(t);
}
});
if (needTexts.length) {
const mt = await translateViaArgos(needTexts, source, target);
if (mt) {
needIdx.forEach((idx, j) => {
const hit = (mt[j] || "").trim();
out[idx] = hit || list[idx];
});
} else if (source === "zh" && target === "en") {
needIdx.forEach((idx) => {
out[idx] = phraseHit(list[idx]) || list[idx];
});
} else {
needIdx.forEach((idx) => {
out[idx] = list[idx];
});
}
}
list.forEach((t, i) => {
if (!out[i]) out[i] = t;
});
return NextResponse.json({
ok: true,
translations: out,
engine: "argos+phrases",
});
}

View File

@ -0,0 +1,38 @@
import { NextRequest } from "next/server";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import {
assertPublicKey,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
/** Public blog catalog — admin + SEO tools; AdSense-friendly indexable metadata */
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const locale = (req.nextUrl.searchParams.get("locale") || "en").trim();
const items = listBlogPosts({
locale: locale === "all" ? "all" : locale === "zh" ? "zh" : "en",
}).map((p) => ({
slug: p.slug,
title: p.title,
description: p.description,
date: p.date,
tags: p.tags,
wordCount: p.wordCount,
readingMinutes: p.readingMinutes,
locale: p.locale,
author: p.author,
url: `https://nomadro.com/hub/blog/${p.slug}`,
}));
return jsonOk(req, {
ok: true,
total: items.length,
items,
pagePath: "/hub/blog",
});
}

View File

@ -0,0 +1,55 @@
import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities";
import {
assertPublicKey,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const sp = req.nextUrl.searchParams;
const qs = sp.toString();
const remote = await proxySocial(`/map/cities${qs ? `?${qs}` : ""}`);
if (remote.ok) {
return jsonOk(req, { ok: true, source: "hub_api", ...(remote.data as object) });
}
let items = HUB_CITIES.map((c) => ({
id: c.id,
name: c.name,
country: c.country,
emoji: c.emoji,
vibe: c.vibe,
lat: c.lat,
lng: c.lng,
memberCount: c.members,
meetupCount: c.meetupCount,
tags: c.tags,
hot: c.hot,
}));
const west = sp.get("west");
const south = sp.get("south");
const east = sp.get("east");
const north = sp.get("north");
if (west && south && east && north) {
const w = Number(west);
const s = Number(south);
const e = Number(east);
const n = Number(north);
items = items.filter(
(c) => c.lng >= w && c.lng <= e && c.lat >= s && c.lat <= n,
);
}
return jsonOk(req, {
ok: true,
source: "local_seed",
items,
fallback: true,
});
}

View File

@ -0,0 +1,44 @@
import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities";
import {
assertPublicKey,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const sp = req.nextUrl.searchParams;
const q = (sp.get("q") || "").trim();
const limit = Math.min(20, Math.max(1, Number(sp.get("limit") || 8)));
const lang = sp.get("lang") || "zh";
if (!q) {
return jsonOk(req, { ok: true, items: [], source: "empty_q" });
}
const remote = await proxySocial(
`/cities/search?q=${encodeURIComponent(q)}&limit=${limit}&lang=${encodeURIComponent(lang)}`,
);
if (remote.ok) {
return jsonOk(req, { ok: true, source: "hub_api", ...(remote.data as object) });
}
const ql = q.toLowerCase();
const items = HUB_CITIES.filter(
(c) =>
c.name.toLowerCase().includes(ql) ||
c.id.includes(ql) ||
(c.country || "").toLowerCase().includes(ql) ||
(c.tags || []).some((t) => t.toLowerCase().includes(ql)),
).slice(0, limit);
return jsonOk(req, {
ok: true,
source: "local_seed",
items,
fallback: true,
});
}

View File

@ -0,0 +1,70 @@
import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog";
import {
assertPublicKey,
jsonErr,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function POST(
req: NextRequest,
ctx: { params: Promise<{ gigId: string }> },
) {
const denied = assertPublicKey(req);
if (denied) return denied;
const { gigId } = await ctx.params;
const gig = PUBLIC_GIGS.find((g) => g.id === gigId);
if (!gig) return jsonErr(req, 404, "gig not found");
const body = (await req.json().catch(() => ({}))) as {
name?: string;
contact?: string;
note?: string;
};
const name = (body.name || "").trim();
const contact = (body.contact || "").trim();
if (!name || !contact) {
return jsonErr(req, 400, "name and contact required", {
pagePath: "/hub/team",
linkText: "去申请页补全",
});
}
const guest =
req.headers.get("x-social-hub-hub-guest-id") ||
`public-${Buffer.from(contact).toString("base64url").slice(0, 24)}`;
const remote = await proxySocial(`/gigs/${encodeURIComponent(gigId)}/apply`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Hub-Guest-Id": guest,
},
body: JSON.stringify({ name, contact, note: body.note || "" }),
});
if (remote.ok) {
return jsonOk(req, {
ok: true,
status: "submitted",
source: "hub_api",
...(remote.data as object),
pagePath: "/hub/team",
linkText: "查看招聘",
});
}
return jsonOk(req, {
ok: true,
status: "queued_local",
source: "fallback",
gigId,
name,
contact,
note: body.note || "",
pagePath: "/hub/team",
linkText: "打开申请页重试",
detail: "upstream apply unavailable; return handoff",
});
}

View File

@ -0,0 +1,38 @@
import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog";
import {
assertPublicKey,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const kind = req.nextUrl.searchParams.get("kind") || "all";
const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim()
.toLowerCase();
let gigs = [...PUBLIC_GIGS];
if (kind && kind !== "all") {
gigs = gigs.filter((g) => g.kind === kind);
}
if (keyword) {
gigs = gigs.filter(
(g) =>
g.title.toLowerCase().includes(keyword) ||
g.role.toLowerCase().includes(keyword) ||
g.tags.some((t) => t.toLowerCase().includes(keyword)),
);
}
return jsonOk(req, {
ok: true,
gigs,
pagePath: "/hub/team",
linkText: "打开招聘",
});
}

View File

@ -0,0 +1,24 @@
import { NextRequest } from "next/server";
import { PUBLIC_JOIN } from "~/lib/public-api/catalog";
import {
assertPublicKey,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const email = req.nextUrl.searchParams.get("email") || "";
return jsonOk(req, {
ok: true,
...PUBLIC_JOIN,
email: email || null,
isMember: false,
note: "Paid social join is isolated from VIP (__vip__). Prefer handoff to pagePath.",
});
}

View File

@ -0,0 +1,33 @@
import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog";
import {
assertPublicKey,
jsonErr,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(
req: NextRequest,
ctx: { params: Promise<{ meetupId: string }> },
) {
const denied = assertPublicKey(req);
if (denied) return denied;
const { meetupId } = await ctx.params;
const room = PUBLIC_MEETUPS.find((r) => r.id === meetupId);
if (!room) return jsonErr(req, 404, "meetup not found");
const nick = req.nextUrl.searchParams.get("nick") || "游民";
return jsonOk(req, {
ok: true,
title: room.title,
meetupId: room.id,
nick,
pagePath: `/hub/meetup/${encodeURIComponent(room.id)}`,
linkText: "进入语音视频厅",
mirotalkRoom: room.mirotalkRoom,
});
}

View File

@ -0,0 +1,34 @@
import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog";
import {
assertPublicKey,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim()
.toLowerCase();
let rooms = [...PUBLIC_MEETUPS];
if (keyword) {
rooms = rooms.filter(
(r) =>
r.title.toLowerCase().includes(keyword) ||
r.id.includes(keyword) ||
r.mirotalkRoom.includes(keyword),
);
}
return jsonOk(req, {
ok: true,
rooms,
pagePath: "/hub/meetup",
linkText: "打开见面列表",
});
}

View File

@ -0,0 +1,21 @@
import { NextRequest } from "next/server";
import { HUB_SECTIONS } from "@hub/lib/catalog";
import {
assertPublicKey,
jsonOk,
optionsOk,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
return optionsOk(req);
}
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
return jsonOk(req, {
ok: true,
base: "/hub",
sections: HUB_SECTIONS,
});
}

View File

@ -1,7 +1,7 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { hardNavigate } from "~/lib/hard-nav";
import {
effectiveHomeVariant,
useAudienceModule,
@ -11,16 +11,16 @@ import {
* 根路径按受众分轨跳转:
* - cn → /portal(Hero 枢纽;出海导航 / 小册默认开)
* - intl → /social(游民社区)
* 用 location.assign,避免 router.replace 与软导航叠加重崩。
*/
export default function HomePage() {
const router = useRouter();
const { bundle } = useAudienceModule();
const variant = effectiveHomeVariant(bundle);
const href = variant === "portal" ? "/portal" : "/social/home";
useEffect(() => {
router.replace(href);
}, [href, router]);
hardNavigate(href);
}, [href]);
return (
<div

12
src/lib/hard-nav.ts Normal file
View File

@ -0,0 +1,12 @@
/** 同域硬跳:避开 App Router 软导航(layout CSS 残留会搞崩门户)。 */
export function hardNavigate(href: string) {
if (typeof window === "undefined") return;
window.location.assign(href);
}
export function hardNavClick(href: string) {
return (event: { preventDefault: () => void }) => {
event.preventDefault();
hardNavigate(href);
};
}

View File

@ -66,6 +66,14 @@ export function proxy(request: NextRequest) {
return NextResponse.redirect(url, 302);
}
// Independent hub fork (copy of social) — bare /hub → /hub/home
if (pathname === "/hub" || pathname === "/hub/") {
const url = request.nextUrl.clone();
url.pathname = "/hub/home";
url.search = search;
return NextResponse.redirect(url, 302);
}
// Alias: /ebook → /book (product mount path)
if (pathname === "/ebook" || pathname.startsWith("/ebook/")) {
const url = request.nextUrl.clone();

View File

@ -21,6 +21,7 @@
"@ebook/*": ["./src/modules/ebook/*"],
"@community/*": ["./src/modules/community/*"],
"@social/*": ["./src/modules/social/*"],
"@hub/*": ["./src/modules/hub/*"],
"@navmini/*": ["./src/modules/nav/*"],
"@vip/*": ["./src/modules/vip/*"],
"@work/*": ["./src/modules/work/*"],