- 谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推;不限于下列开关,可持续扩展。
+ {laneKey === 'cn'
+ ? '写入 flags.hubLive(/hub);缺省时门户仍可读 socialLive 兜底。'
+ : '写入 flags.socialLive(/social)。'}{' '}
+ 谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推。
{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`,
)
}}
diff --git a/next.config.ts b/next.config.ts
index 746f5b7..faf6878 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -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",
diff --git a/package.json b/package.json
index c2172a9..33d83a4 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/scripts/deploy_hub_backend_us.py b/scripts/deploy_hub_backend_us.py
new file mode 100644
index 0000000..22286fd
--- /dev/null
+++ b/scripts/deploy_hub_backend_us.py
@@ -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())
diff --git a/scripts/dev-hub.ps1 b/scripts/dev-hub.ps1
new file mode 100644
index 0000000..8966c9c
--- /dev/null
+++ b/scripts/dev-hub.ps1
@@ -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
diff --git a/scripts/ensure_hub_collections.py b/scripts/ensure_hub_collections.py
new file mode 100644
index 0000000..e3feb1e
--- /dev/null
+++ b/scripts/ensure_hub_collections.py
@@ -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())
diff --git a/scripts/ensure_hub_collections_us.py b/scripts/ensure_hub_collections_us.py
new file mode 100644
index 0000000..ec804f4
--- /dev/null
+++ b/scripts/ensure_hub_collections_us.py
@@ -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())
diff --git a/src/app/api/admin/hub/ugc/join-leads/route.ts b/src/app/api/admin/hub/ugc/join-leads/route.ts
new file mode 100644
index 0000000..7e817cd
--- /dev/null
+++ b/src/app/api/admin/hub/ugc/join-leads/route.ts
@@ -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: [] });
+}
diff --git a/src/app/api/hub/translate/route.ts b/src/app/api/hub/translate/route.ts
new file mode 100644
index 0000000..c34426e
--- /dev/null
+++ b/src/app/api/hub/translate/route.ts
@@ -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
{
+ 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",
+ });
+}
diff --git a/src/app/api/public/v1/hub/blog/route.ts b/src/app/api/public/v1/hub/blog/route.ts
new file mode 100644
index 0000000..b6bb1ec
--- /dev/null
+++ b/src/app/api/public/v1/hub/blog/route.ts
@@ -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",
+ });
+}
diff --git a/src/app/api/public/v1/hub/cities/route.ts b/src/app/api/public/v1/hub/cities/route.ts
new file mode 100644
index 0000000..1461b36
--- /dev/null
+++ b/src/app/api/public/v1/hub/cities/route.ts
@@ -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,
+ });
+}
diff --git a/src/app/api/public/v1/hub/cities/search/route.ts b/src/app/api/public/v1/hub/cities/search/route.ts
new file mode 100644
index 0000000..603f44c
--- /dev/null
+++ b/src/app/api/public/v1/hub/cities/search/route.ts
@@ -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,
+ });
+}
diff --git a/src/app/api/public/v1/hub/gigs/[gigId]/apply/route.ts b/src/app/api/public/v1/hub/gigs/[gigId]/apply/route.ts
new file mode 100644
index 0000000..efe99de
--- /dev/null
+++ b/src/app/api/public/v1/hub/gigs/[gigId]/apply/route.ts
@@ -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",
+ });
+}
diff --git a/src/app/api/public/v1/hub/gigs/route.ts b/src/app/api/public/v1/hub/gigs/route.ts
new file mode 100644
index 0000000..120925e
--- /dev/null
+++ b/src/app/api/public/v1/hub/gigs/route.ts
@@ -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: "打开招聘",
+ });
+}
diff --git a/src/app/api/public/v1/hub/join/route.ts b/src/app/api/public/v1/hub/join/route.ts
new file mode 100644
index 0000000..66c1eaf
--- /dev/null
+++ b/src/app/api/public/v1/hub/join/route.ts
@@ -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.",
+ });
+}
diff --git a/src/app/api/public/v1/hub/meetups/[meetupId]/route.ts b/src/app/api/public/v1/hub/meetups/[meetupId]/route.ts
new file mode 100644
index 0000000..d13b3a5
--- /dev/null
+++ b/src/app/api/public/v1/hub/meetups/[meetupId]/route.ts
@@ -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,
+ });
+}
diff --git a/src/app/api/public/v1/hub/meetups/route.ts b/src/app/api/public/v1/hub/meetups/route.ts
new file mode 100644
index 0000000..2192ff8
--- /dev/null
+++ b/src/app/api/public/v1/hub/meetups/route.ts
@@ -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: "打开见面列表",
+ });
+}
diff --git a/src/app/api/public/v1/hub/routes/route.ts b/src/app/api/public/v1/hub/routes/route.ts
new file mode 100644
index 0000000..17674e7
--- /dev/null
+++ b/src/app/api/public/v1/hub/routes/route.ts
@@ -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,
+ });
+}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 1b577ac..6c120ee 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -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 (
void }) => {
+ event.preventDefault();
+ hardNavigate(href);
+ };
+}
diff --git a/src/proxy.ts b/src/proxy.ts
index a9d85b0..ba502b7 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -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();
diff --git a/tsconfig.json b/tsconfig.json
index 4b671b3..040ae0e 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -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/*"],