chore: apply codex repair updates (tracked files only)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-29 21:51:04 +08:00
parent f40774ddd3
commit 42f0f41bf1
148 changed files with 5393 additions and 4784 deletions

View File

@ -65,6 +65,12 @@ WX_PAY_ENV=0
# PHOTON_BASE_URL=https://photon.komoot.io # PHOTON_BASE_URL=https://photon.komoot.io
# SOCIAL_GEO_USE_PB=true # SOCIAL_GEO_USE_PB=true
# SOCIAL_TRIPS_COLLECTION=social_trips # SOCIAL_TRIPS_COLLECTION=social_trips
# Hub fork of social (independent process :8025 locally)
# HUB_API_URL=https://nomadro.com
# HUB_ENABLED=true
# HUB_DB_PATH=
# HUB_GEO_USE_PB=true
# HUB_TRIPS_COLLECTION=hub_trips
# PB_URL=http://127.0.0.1:8090 # PB_URL=http://127.0.0.1:8090
# PB_ADMIN_EMAIL= # PB_ADMIN_EMAIL=
# PB_ADMIN_PASSWORD= # PB_ADMIN_PASSWORD=

1
.gitignore vendored
View File

@ -18,6 +18,7 @@ node_modules/
# next.js / builds # next.js / builds
/.next/ /.next/
/.next-*/
/out/ /out/
/apps/**/.next/ /apps/**/.next/
/apps/**/out/ /apps/**/out/

View File

@ -15,6 +15,7 @@ Follow `.cursor/rules/*.mdc`。
| Layer | Path | | Layer | Path |
|---|---| |---|---|
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` | | Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
| **Hub(social 独立副本)** | `/hub` · `src/modules/hub` + `src/app/hub` · `hub_svc` `/api/hub/v1` · `hub_main :8025` · 后台 `/{lane}/hub/*`。**勿改** `/social` 业务代码 |
| Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 | | Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 |
| Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 | | Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 |
| Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 | | Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 |
@ -33,6 +34,8 @@ Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline default
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。 **全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
**受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。后台登录后选 `/cn`|`/intl`。见 `audience-cn-intl.mdc`。 **受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。见 `audience-cn-intl.mdc`。
**admin.nomadro.com 真分轨**:登录选轨后 **cn → `/cn/hub/*`(中文 Hub)** · **intl → `/intl/social/*`(国际 Social)**;侧栏互不混挂;误入对方社区路径自动改写。中文门户三大公开模块 = 导航 `/nav` · 小册 `/book` · Hub `/hub`(不是 `/social`)。
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。 H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。

View File

@ -1,5 +1,7 @@
# Nomadro # Nomadro
> 2026-11-29 本地跨项目检查与修复:[审计记录、验证结果和剩余问题](docs/code-audit-2026-11-29.md)。日常检查:`pnpm typecheck:all`、`pnpm test:local`。本次修复未部署。
> **Hub `.com` 已发布**:`20261128T165939Z`(本地 2026-11-29),门户 [nomadro.com/hub](https://nomadro.com/hub) + Hub API + [admin.nomadro.com](https://admin.nomadro.com/) 中文轨。构建 `OfO3HMXd-HIAPfsB7UgKC`;[检查、发布与回滚记录](docs/hub-audit-2026-11-29.md)。未同步 `.cn`、VIP hackrobot 或小程序。 > **Hub `.com` 已发布**:`20261128T165939Z`(本地 2026-11-29),门户 [nomadro.com/hub](https://nomadro.com/hub) + Hub API + [admin.nomadro.com](https://admin.nomadro.com/) 中文轨。构建 `OfO3HMXd-HIAPfsB7UgKC`;[检查、发布与回滚记录](docs/hub-audit-2026-11-29.md)。未同步 `.cn`、VIP hackrobot 或小程序。
> **管理后台域名铁律(永远禁止混淆)** > **管理后台域名铁律(永远禁止混淆)**

View File

@ -42,6 +42,10 @@ apps/api/.venv/Scripts/python.exe -m unittest discover -s apps/api/tests -v
| `services/community_svc` | 原 community-api | `/api/v1/*` | | `services/community_svc` | 原 community-api | `/api/v1/*` |
| `services/pay_svc` | 原 payjsapi | `/nomadvip` `/digital` `/api/meetup` … | | `services/pay_svc` | 原 payjsapi | `/nomadvip` `/digital` `/api/meetup` … |
## Hub API(`hub_svc` · `:8025`)
中文游民社区独立进程:`hub_main.py` → `http://127.0.0.1:8025`,路由前缀 `/api/hub/v1`(presence / chat / roster / geo)。Centrifugo 频道用 `hub:` 前缀,与 `social_svc` 的 `social:` 隔离。体验台与 UGC 管理仍走 ebook 管理接口 `/api/admin/hub/ugc/*`(写 remote-config)。本地:`pnpm dev:hub-api` / `scripts/dev-hub.ps1`。
## 本地 ## 本地
```bash ```bash

View File

@ -24,12 +24,14 @@ def available_times(day: str, schedule: dict, event: dict, bookings: list[dict],
for window in schedule.get('availability') or []: for window in schedule.get('availability') or []:
if local_date.strftime('%A') not in window.get('days', []): continue if local_date.strftime('%A') not in window.get('days', []): continue
first, last = int(window['startTime']), int(window['endTime']) first, last = int(window['startTime']), int(window['endTime'])
window_end = (midnight + timedelta(minutes=last)).astimezone(timezone.utc)
for minute in range(first, last - length + 1, interval): for minute in range(first, last - length + 1, interval):
start_local = midnight + timedelta(minutes=minute) start_local = midnight + timedelta(minutes=minute)
start = start_local.astimezone(timezone.utc) start = start_local.astimezone(timezone.utc)
# Skip nonexistent wall-clock times during a daylight-saving jump. # Skip nonexistent wall-clock times during a daylight-saving jump.
if start.astimezone(tz).replace(tzinfo=None) != start_local.replace(tzinfo=None): continue if start.astimezone(tz).replace(tzinfo=None) != start_local.replace(tzinfo=None): continue
end = start + timedelta(minutes=length) end = start + timedelta(minutes=length)
if end > window_end: continue
if start <= now: continue if start <= now: continue
if any(start - before < busy_end and end + after > busy_start for busy_start, busy_end in occupied): continue if any(start - before < busy_end and end + after > busy_start for busy_start, busy_end in occupied): continue
key = start.strftime('%Y-%m-%dT%H:%M:%SZ') key = start.strftime('%Y-%m-%dT%H:%M:%SZ')

View File

@ -88,6 +88,9 @@ from ebook_svc.routers import social_ops_admin # noqa: E402
from ebook_svc.routers import social_ugc_admin # noqa: E402 from ebook_svc.routers import social_ugc_admin # noqa: E402
from ebook_svc.routers import social_locale_geo_admin # noqa: E402 from ebook_svc.routers import social_locale_geo_admin # noqa: E402
from ebook_svc.routers import social_blog_admin # noqa: E402 from ebook_svc.routers import social_blog_admin # noqa: E402
from ebook_svc.routers import hub_ugc_admin # noqa: E402
from ebook_svc.routers import hub_locale_geo_admin # noqa: E402
from ebook_svc.routers import hub_blog_admin # noqa: E402
from ebook_svc.routers import community_admin # noqa: E402 from ebook_svc.routers import community_admin # noqa: E402
app.include_router(weapp_switches_admin.router) app.include_router(weapp_switches_admin.router)
@ -96,6 +99,9 @@ app.include_router(social_ops_admin.router)
app.include_router(social_ugc_admin.router) app.include_router(social_ugc_admin.router)
app.include_router(social_locale_geo_admin.router) app.include_router(social_locale_geo_admin.router)
app.include_router(social_blog_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(community_admin.router)
# 运营:ntfy 状态 / 试推(admin.nomadro.com) # 运营:ntfy 状态 / 试推(admin.nomadro.com)
from ebook_svc.routers import ops_admin # noqa: E402 from ebook_svc.routers import ops_admin # noqa: E402

View File

@ -30,6 +30,8 @@ MODULE_KEYS = (
"community", "community",
"social", "social",
"socialBlog", "socialBlog",
"hub",
"hubBlog",
"vip", "vip",
"destinations", "destinations",
"meetups", "meetups",
@ -39,13 +41,18 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"}, "home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"}, "nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"}, "book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"}, # 中文公开三大=导航/小册/Hub;旅居等默认关,后台可开
# 对齐线上 remote-config:游民社区 / pages/social/index;缺省开启,写入只改 enabled "community": {
"enabled": False,
"title": "旅居社群",
"tabLabel": "社群",
"note": "默认隐藏;后台可开",
},
"social": { "social": {
"enabled": True, "enabled": True,
"title": "游民社区", "title": "游民社区",
"tabLabel": "社区", "tabLabel": "社区",
"note": "Taro 原生 pages/social · 开关不碰业务库", "note": "国际 /social · 勿与中文 Hub 混用",
}, },
"socialBlog": { "socialBlog": {
"enabled": True, "enabled": True,
@ -53,9 +60,21 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
"tabLabel": "Blog", "tabLabel": "Blog",
"note": "/social/blog · EN long-form · AdSense", "note": "/social/blog · EN long-form · AdSense",
}, },
"hub": {
"enabled": True,
"title": "游民社区",
"tabLabel": "社区",
"note": "中文门户 /portal → /hub/home · 独立于 /social",
},
"hubBlog": {
"enabled": False,
"title": "Hub Blog",
"tabLabel": "Hub Blog",
"note": "/hub/blog",
},
"vip": {"enabled": False, "title": "会员中心"}, "vip": {"enabled": False, "title": "会员中心"},
"destinations": {"enabled": True, "title": "目的地"}, "destinations": {"enabled": False, "title": "目的地", "note": "默认隐藏"},
"meetups": {"enabled": True, "title": "活动"}, "meetups": {"enabled": False, "title": "活动", "note": "默认隐藏"},
"game": {"enabled": False, "title": "数字游民", "note": "冻结隐藏 · 勿开入口"}, "game": {"enabled": False, "title": "数字游民", "note": "冻结隐藏 · 勿开入口"},
} }

View File

@ -22,17 +22,17 @@ CENTRIFUGO_TOKEN_SECRET = os.getenv("CENTRIFUGO_TOKEN_SECRET", "")
# 浏览器 WebSocket(经 nginx 反代,与门户同域) # 浏览器 WebSocket(经 nginx 反代,与门户同域)
CENTRIFUGO_WS_URL = os.getenv( CENTRIFUGO_WS_URL = os.getenv(
"CENTRIFUGO_WS_URL", "CENTRIFUGO_WS_URL",
"wss://nomadro.cn/rt/connection/websocket", "wss://nomadro.com/rt/connection/websocket",
) )
# 原生音视频厅(SRS RTMP 推 / HTTP-FLV 拉)— 微信 LivePusher/LivePlayer # 原生音视频厅(SRS RTMP 推 / HTTP-FLV 拉)— 微信 LivePusher/LivePlayer
LIVE_RTMP_PUSH_BASE = os.getenv( LIVE_RTMP_PUSH_BASE = os.getenv(
"LIVE_RTMP_PUSH_BASE", "LIVE_RTMP_PUSH_BASE",
"rtmp://82.157.112.245/live", "rtmp://nomadro.com/live",
) )
LIVE_HTTP_PLAY_BASE = os.getenv( LIVE_HTTP_PLAY_BASE = os.getenv(
"LIVE_HTTP_PLAY_BASE", "LIVE_HTTP_PLAY_BASE",
"https://nomadro.cn/live", "https://nomadro.com/live",
) )
LIVE_STREAM_SECRET = os.getenv( LIVE_STREAM_SECRET = os.getenv(
"LIVE_STREAM_SECRET", "LIVE_STREAM_SECRET",

View File

@ -6,6 +6,7 @@ import time
from typing import Any from typing import Any
import httpx import httpx
from nomadro_pb import pb_quote
from .config import ( from .config import (
PB_ADMIN_EMAIL, PB_ADMIN_EMAIL,
@ -91,11 +92,11 @@ def ensure_collection() -> bool:
body = { body = {
"name": name, "name": name,
"type": "base", "type": "base",
"listRule": "", "listRule": None,
"viewRule": "", "viewRule": None,
"createRule": "", "createRule": None,
"updateRule": "", "updateRule": None,
"deleteRule": "", "deleteRule": None,
"fields": [ "fields": [
{"name": "guest_id", "type": "text", "required": True}, {"name": "guest_id", "type": "text", "required": True},
{"name": "city_id", "type": "text", "required": False}, {"name": "city_id", "type": "text", "required": False},
@ -215,13 +216,13 @@ def list_trips(
ensure_collection() ensure_collection()
filters: list[str] = [] filters: list[str] = []
if guest_id: if guest_id:
filters.append(f'guest_id="{guest_id}"') filters.append(f'guest_id={pb_quote(guest_id)}')
if city_id: if city_id:
filters.append(f'city_id="{city_id}"') filters.append(f'city_id={pb_quote(city_id)}')
if visibility: if visibility:
filters.append(f'visibility="{visibility}"') filters.append(f'visibility={pb_quote(visibility)}')
if status: if status:
filters.append(f'status="{status}"') filters.append(f'status={pb_quote(status)}')
params: dict[str, Any] = { params: dict[str, Any] = {
"page": 1, "page": 1,
"perPage": max(1, min(limit, 500)), "perPage": max(1, min(limit, 500)),
@ -271,19 +272,12 @@ def upsert_trip(trip: dict[str, Any]) -> dict[str, Any] | None:
tid = trip.get("id") or "" tid = trip.get("id") or ""
try: try:
with httpx.Client(timeout=10.0) as client: with httpx.Client(timeout=10.0) as client:
if tid: if tid and not tid.startswith("trip_"):
r = client.patch( r = client.patch(
f"{base}/api/collections/{col}/records/{tid}", f"{base}/api/collections/{col}/records/{tid}",
headers=headers, headers=headers,
json=payload, json=payload,
) )
if r.status_code >= 400:
# maybe id is sqlite-local; create new
r = client.post(
f"{base}/api/collections/{col}/records",
headers=headers,
json=payload,
)
else: else:
r = client.post( r = client.post(
f"{base}/api/collections/{col}/records", f"{base}/api/collections/{col}/records",

View File

@ -1,10 +1,11 @@
"""Trips store: SQLite always; PocketBase preferred SoT when reachable.""" """Hub trips use PocketBase; legacy SQLite helpers remain inactive."""
from __future__ import annotations from __future__ import annotations
import time import time
import uuid import uuid
from datetime import date from datetime import date
from typing import Any from typing import Any
from fastapi import HTTPException
from . import geo_pb from . import geo_pb
from .geo_cities import ( from .geo_cities import (
@ -104,7 +105,10 @@ def list_trips(**kwargs: Any) -> list[dict[str, Any]]:
pb = geo_pb.list_trips(**kwargs) pb = geo_pb.list_trips(**kwargs)
if pb is not None: if pb is not None:
return pb return pb
return list_trips_sqlite(**kwargs) # Public city catalogs remain available without inventing live arrivals.
if kwargs.get("visibility") == "public" and not kwargs.get("guest_id"):
return []
raise HTTPException(status_code=503, detail="行程服务暂不可用,请稍后重试")
def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]: def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]:
@ -184,11 +188,9 @@ def create_trip(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
if trip["status"] not in {"here", "planned", "past"}: if trip["status"] not in {"here", "planned", "past"}:
trip["status"] = "planned" trip["status"] = "planned"
pb = geo_pb.upsert_trip(trip) pb = geo_pb.upsert_trip(trip)
if pb: if pb is None:
# keep local mirror with PB id raise HTTPException(status_code=503, detail="行程未保存,请稍后重试")
trip = pb return pb
save_trip_sqlite(trip)
return trip
def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None: def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None:
@ -197,10 +199,6 @@ def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[st
if t["id"] == trip_id: if t["id"] == trip_id:
existing = t existing = t
break break
if not existing:
# try sqlite only
rows = list_trips_sqlite(guest_id=guest_id, visibility=None, limit=500)
existing = next((t for t in rows if t["id"] == trip_id), None)
if not existing: if not existing:
return None return None
city = (payload.get("city") or existing["city"]).strip() city = (payload.get("city") or existing["city"]).strip()
@ -247,26 +245,16 @@ def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[st
if trip["lat"] is not None and trip["lng"] is not None: if trip["lat"] is not None and trip["lng"] is not None:
trip["h3_cell"] = latlng_to_cell(float(trip["lat"]), float(trip["lng"])) trip["h3_cell"] = latlng_to_cell(float(trip["lat"]), float(trip["lng"]))
pb = geo_pb.upsert_trip(trip) pb = geo_pb.upsert_trip(trip)
if pb: if pb is None:
trip = pb raise HTTPException(status_code=503, detail="行程未保存,请稍后重试")
save_trip_sqlite(trip) return pb
return trip
def delete_trip(guest_id: str, trip_id: str) -> bool: def delete_trip(guest_id: str, trip_id: str) -> bool:
pb = geo_pb.delete_trip(trip_id, guest_id) pb = geo_pb.delete_trip(trip_id, guest_id)
ensure_trips_schema() if pb is None:
with db() as conn: raise HTTPException(status_code=503, detail="行程未删除,请稍后重试")
cur = conn.execute( return pb
"DELETE FROM trips WHERE id = ? AND guest_id = ?",
(trip_id, guest_id),
)
local = cur.rowcount > 0
if pb is True:
return True
if pb is False and not local:
return False
return local or pb is not False
def map_cities() -> list[dict[str, Any]]: def map_cities() -> list[dict[str, Any]]:

View File

@ -13,6 +13,9 @@ log = logging.getLogger("hub_svc.photon")
def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None: def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None:
props = f.get("properties") or {} props = f.get("properties") or {}
# Hub's current city scope is CN. Retain global normalization below.
if str(props.get("countrycode") or "").upper() != "CN":
return None
geom = f.get("geometry") or {} geom = f.get("geometry") or {}
coords = geom.get("coordinates") or [] coords = geom.get("coordinates") or []
if len(coords) < 2: if len(coords) < 2:

View File

@ -18,7 +18,7 @@ from hub_svc.realtime import (
publish_live_event, publish_live_event,
) )
router = APIRouter(tags=["social"]) router = APIRouter(tags=["hub"])
def _guest( def _guest(
@ -631,7 +631,7 @@ async def avatar_pose_challenge(
video: UploadFile | None = File(default=None), video: UploadFile | None = File(default=None),
email: str | None = Form(default=None), email: str | None = Form(default=None),
x_hub_guest_id: str | None = Header(default=None), x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None), x_social_email: str | None = Header(default=None, alias="X-Hub-Email"),
guest: str | None = Query(default=None), guest: str | None = Query(default=None),
): ):
"""Live selfie: front + turn frames + optional full camera recording for audit.""" """Live selfie: front + turn frames + optional full camera recording for audit."""
@ -795,7 +795,9 @@ def liveness_audits(
limit: int = Query(default=40, ge=1, le=200), limit: int = Query(default=40, ge=1, le=200),
x_hub_guest_id: str | None = Header(default=None), x_hub_guest_id: str | None = Header(default=None),
): ):
"""Admin-oriented list of liveness recordings (guest header still required).""" """Recordings are available through authenticated admin UGC routes only."""
raise HTTPException(status_code=403, detail="自拍核验记录仅对管理后台开放")
_guest(x_hub_guest_id) _guest(x_hub_guest_id)
store.init_db() store.init_db()
return { return {
@ -1165,7 +1167,7 @@ def put_my_roster(
def post_feedback( def post_feedback(
body: FeedbackIn, body: FeedbackIn,
x_hub_guest_id: str | None = Header(default=None), x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None), x_social_email: str | None = Header(default=None, alias="X-Hub-Email"),
user_agent: str | None = Header(default=None, alias="User-Agent"), user_agent: str | None = Header(default=None, alias="User-Agent"),
): ):
guest = _guest(x_hub_guest_id) guest = _guest(x_hub_guest_id)
@ -1534,6 +1536,10 @@ def resolve_report(
body: ReportResolveIn, body: ReportResolveIn,
x_hub_guest_id: str | None = Header(default=None), x_hub_guest_id: str | None = Header(default=None),
): ):
# Moderation is available only through the authenticated admin UGC API.
# A client-supplied guest ID is not an administrator credential.
raise HTTPException(status_code=403, detail="请通过管理后台处理举报")
from hub_svc import community_board as board from hub_svc import community_board as board
from hub_svc.notify_bridge import notify_report_result from hub_svc.notify_bridge import notify_report_result
@ -1562,6 +1568,8 @@ def get_reports(
limit: int = Query(default=40, ge=1, le=100), limit: int = Query(default=40, ge=1, le=100),
x_hub_guest_id: str | None = Header(default=None), x_hub_guest_id: str | None = Header(default=None),
): ):
raise HTTPException(status_code=403, detail="举报列表仅对管理后台开放")
from hub_svc import community_board as board from hub_svc import community_board as board
_guest(x_hub_guest_id) _guest(x_hub_guest_id)

View File

@ -14,7 +14,9 @@ log = logging.getLogger("nomadro_pb")
class PocketBaseError(RuntimeError): class PocketBaseError(RuntimeError):
pass def __init__(self, message: str, *, status_code: int | None = None) -> None:
super().__init__(message)
self.status_code = status_code
def pb_quote(value: str) -> str: def pb_quote(value: str) -> str:
@ -72,7 +74,7 @@ class PocketBaseClient:
detail = res.json() detail = res.json()
except Exception: except Exception:
detail = res.text detail = res.text
raise PocketBaseError(f"PocketBase {res.status_code}: {detail}") raise PocketBaseError(f"PocketBase {res.status_code}: {detail}", status_code=res.status_code)
if not res.content: if not res.content:
return None return None
return res.json() return res.json()
@ -111,8 +113,10 @@ class PocketBaseClient:
def get_collection(self, name: str) -> dict[str, Any] | None: def get_collection(self, name: str) -> dict[str, Any] | None:
try: try:
return self.request("GET", f"/api/collections/{name}", admin=True) return self.request("GET", f"/api/collections/{name}", admin=True)
except PocketBaseError: except PocketBaseError as exc:
return None if exc.status_code == 404:
return None
raise
def create_collection(self, body: dict[str, Any]) -> dict[str, Any]: def create_collection(self, body: dict[str, Any]) -> dict[str, Any]:
return self.request("POST", "/api/collections", admin=True, json=body) return self.request("POST", "/api/collections", admin=True, json=body)

View File

@ -335,6 +335,40 @@ SOCIAL_ARCHIVES = _base(
], ],
) )
def _hub_clone(social_spec: dict[str, Any]) -> dict[str, Any]:
"""Clone a social_* collection schema to hub_* (independent /hub fork)."""
name = str(social_spec["name"])
if not name.startswith("social_"):
raise ValueError(f"expected social_* collection, got {name}")
hub_name = "hub_" + name[len("social_") :]
indexes = []
for raw in social_spec.get("indexes") or []:
indexes.append(
str(raw)
.replace(f"idx_social_", "idx_hub_")
.replace(f" ON {name} ", f" ON {hub_name} ")
.replace(f" ON {name}(", f" ON {hub_name}(")
)
return _base(hub_name, list(social_spec["fields"]), indexes or None)
HUB_ROSTER = _hub_clone(SOCIAL_ROSTER)
HUB_LIVENESS = _hub_clone(SOCIAL_LIVENESS)
HUB_SKILLS = _hub_clone(SOCIAL_SKILLS)
HUB_REVIEWS = _hub_clone(SOCIAL_REVIEWS)
HUB_BLOCKS = _hub_clone(SOCIAL_BLOCKS)
HUB_REPORTS = _hub_clone(SOCIAL_REPORTS)
HUB_MESSAGES = _hub_clone(SOCIAL_MESSAGES)
HUB_CHANNEL_META = _hub_clone(SOCIAL_CHANNEL_META)
HUB_CHANNEL_READS = _hub_clone(SOCIAL_CHANNEL_READS)
HUB_FILES = _hub_clone(SOCIAL_FILES)
HUB_TRIPS = _hub_clone(SOCIAL_TRIPS)
HUB_CAFE_REVIEWS = _hub_clone(SOCIAL_CAFE_REVIEWS)
HUB_FEEDBACK = _hub_clone(SOCIAL_FEEDBACK)
HUB_JOIN_LEADS = _hub_clone(SOCIAL_JOIN_LEADS)
HUB_GIG_APPS = _hub_clone(SOCIAL_GIG_APPS)
HUB_ARCHIVES = _hub_clone(SOCIAL_ARCHIVES)
# —— Coffee —— # —— Coffee ——
COFFEE_HOSTS = _base( COFFEE_HOSTS = _base(
"coffee_hosts", "coffee_hosts",
@ -559,6 +593,22 @@ ALL_COLLECTIONS: list[dict[str, Any]] = [
SOCIAL_JOIN_LEADS, SOCIAL_JOIN_LEADS,
SOCIAL_GIG_APPS, SOCIAL_GIG_APPS,
SOCIAL_ARCHIVES, SOCIAL_ARCHIVES,
HUB_ROSTER,
HUB_LIVENESS,
HUB_SKILLS,
HUB_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,
COFFEE_HOSTS, COFFEE_HOSTS,
COFFEE_SCHEDULES, COFFEE_SCHEDULES,
COFFEE_EVENT_TYPES, COFFEE_EVENT_TYPES,

View File

@ -45,6 +45,13 @@ class CoffeeSchedulingTests(unittest.TestCase):
result = available_times('2026-11-09', schedule, self.event, [], datetime(2026, 1, 1, tzinfo=timezone.utc)) result = available_times('2026-11-09', schedule, self.event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
self.assertEqual(len(result), len({row['start'] for row in result})) self.assertEqual(len(result), len({row['start'] for row in result}))
def test_dst_spring_forward_meeting_must_finish_within_window(self):
schedule = {'timezone': 'America/New_York', 'availability': [
{'days': ['Sunday'], 'startTime': 60, 'endTime': 180}]}
event = {'active': True, 'length_minutes': 60, 'slot_interval': 30}
result = available_times('2026-03-08', schedule, event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
self.assertEqual([row['local'] for row in result], ['01:00'])
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -89,3 +89,18 @@ class PocketBaseClientTests(unittest.TestCase):
return httpx.Response(200, json={'token': 'legacy'}) return httpx.Response(200, json={'token': 'legacy'})
self.assertEqual(self.client(handler).admin_token(), 'legacy') self.assertEqual(self.client(handler).admin_token(), 'legacy')
def test_collection_lookup_only_treats_404_as_missing(self):
for status in [404, 403, 500, 503]:
with self.subTest(status=status):
def handler(request):
if request.url.path.endswith('auth-with-password'):
return httpx.Response(200, json={'token': 'valid'})
return httpx.Response(status, json={'message': 'lookup failed'})
client = self.client(handler)
if status == 404:
self.assertIsNone(client.get_collection('records'))
else:
with self.assertRaises(PocketBaseError) as raised:
client.get_collection('records')
self.assertEqual(raised.exception.status_code, status)

View File

@ -3,6 +3,7 @@
* 内容 SoT 仍是仓库 Markdown;本页管线上运营与广告展示。 * 内容 SoT 仍是仓库 Markdown;本页管线上运营与广告展示。
*/ */
import { useCallback, useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { api } from '../api/client' import { api } from '../api/client'
import { useConfigLive } from '../lib/useConfigLive' import { useConfigLive } from '../lib/useConfigLive'
import { useDraft } from '../lib/useDraft' import { useDraft } from '../lib/useDraft'
@ -64,6 +65,9 @@ function draftFrom(overview: Overview) {
} }
export default function Blog() { export default function Blog() {
const { lane } = useParams()
const community = lane === 'cn' ? 'hub' : 'social'
const endpoint = `/api/admin/${community}/blog`
const live = useConfigLive() const live = useConfigLive()
const [tab, setTab] = useState<TabKey>('posts') const [tab, setTab] = useState<TabKey>('posts')
const [ov, setOv] = useState<Overview | null>(null) const [ov, setOv] = useState<Overview | null>(null)
@ -89,8 +93,8 @@ export default function Blog() {
setErr('') setErr('')
try { try {
const [overview, list] = await Promise.all([ const [overview, list] = await Promise.all([
api<Overview>('/api/admin/social/blog/overview'), api<Overview>(`${endpoint}/overview`),
api<{ items?: Post[] }>('/api/admin/social/blog/posts'), api<{ items?: Post[] }>(`${endpoint}/posts`),
]) ])
setOv(overview) setOv(overview)
setPosts(Array.isArray(list.items) ? list.items : []) setPosts(Array.isArray(list.items) ? list.items : [])
@ -99,13 +103,13 @@ export default function Blog() {
const msg = e instanceof Error ? e.message : '加载失败' const msg = e instanceof Error ? e.message : '加载失败'
setErr( setErr(
/not found/i.test(msg) /not found/i.test(msg)
? 'Blog 管理接口未部署(/api/admin/social/blog)。请联系运维推送 social_blog_admin。' ? `Blog 管理接口未部署(${endpoint})。请联系运维检查 ${community}_blog_admin。`
: msg, : msg,
) )
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, []) }, [endpoint, community])
useEffect(() => { useEffect(() => {
void load() void load()
@ -130,7 +134,7 @@ export default function Blog() {
setMsg('') setMsg('')
setErr('') setErr('')
try { try {
const next = await api<Overview>('/api/admin/social/blog/ops', { const next = await api<Overview>(`${endpoint}/ops`, {
method: 'PATCH', method: 'PATCH',
body: JSON.stringify({ ...body, expectedVersion: ov.version }), body: JSON.stringify({ ...body, expectedVersion: ov.version }),
}) })
@ -138,7 +142,7 @@ export default function Blog() {
editor.accept(draftFrom(next), Object.keys(body) as Array<keyof typeof draft>) editor.accept(draftFrom(next), Object.keys(body) as Array<keyof typeof draft>)
setMsg(okHint) setMsg(okHint)
try { try {
const list = await api<{ items?: Post[] }>('/api/admin/social/blog/posts') const list = await api<{ items?: Post[] }>(`${endpoint}/posts`)
setPosts(Array.isArray(list.items) ? list.items : []) setPosts(Array.isArray(list.items) ? list.items : [])
} catch { setErr('修改已保存,文章列表刷新失败,请点刷新重试') } } catch { setErr('修改已保存,文章列表刷新失败,请点刷新重试') }
} catch (e: unknown) { } catch (e: unknown) {
@ -164,18 +168,17 @@ export default function Blog() {
<div className="com-page com-blog-admin"> <div className="com-page com-blog-admin">
<header className="com-page-head com-page-head-row"> <header className="com-page-head com-page-head-row">
<div> <div>
<h1>Nomad Blog</h1> <h1>{community === 'hub' ? 'Hub 游民手记' : 'Nomad Blog'}</h1>
<p> <p>
管理 <code>/social/blog</code>:文章显隐、置顶、AdSense 与模块开关。正文仍在仓库 Markdown(Tina 管理 <code>/{community}/blog</code>:文章显隐、置顶与模块开关。正文在本轨独立内容目录维护。
式 Git SoT)。
</p> </p>
<div className="com-chip-row"> <div className="com-chip-row">
<span className={`com-chip${ov?.moduleEnabled ? ' com-chip-ok' : ''}`}> <span className={`com-chip${ov?.moduleEnabled ? ' com-chip-ok' : ''}`}>
模块 {ov?.moduleEnabled ? '开' : '关'} 模块 {ov?.moduleEnabled ? '开' : '关'}
</span> </span>
<span className={`com-chip${ov?.adsenseEnabled ? ' com-chip-ok' : ''}`}> {community !== 'hub' ? <span className={`com-chip${ov?.adsenseEnabled ? ' com-chip-ok' : ''}`}>
AdSense {ov?.adsenseEnabled ? '展示中' : '关闭'} AdSense {ov?.adsenseEnabled ? '展示中' : '关闭'}
</span> </span> : null}
{ov?.version != null ? <span className="com-chip">v{ov.version}</span> : null} {ov?.version != null ? <span className="com-chip">v{ov.version}</span> : null}
</div> </div>
</div> </div>
@ -210,9 +213,9 @@ export default function Blog() {
<strong>{ov?.counts?.hidden ?? '—'}</strong> <strong>{ov?.counts?.hidden ?? '—'}</strong>
</article> </article>
<article className="com-stat"> <article className="com-stat">
<span className="com-stat-label">广告就绪</span> <span className="com-stat-label">{community === 'hub' ? '内容受众' : '广告就绪'}</span>
<strong>{adsReady ? '是' : '否'}</strong> <strong>{community === 'hub' ? '中文' : adsReady ? '是' : '否'}</strong>
<span className="com-stat-note">{adsReady ? 'client + slot' : '先填 clientId / slot'}</span> <span className="com-stat-note">{community === 'hub' ? 'Hub 独立内容' : adsReady ? 'client + slot' : '先填 clientId / slot'}</span>
</article> </article>
</div> </div>
@ -236,7 +239,7 @@ export default function Blog() {
</div> </div>
<nav className="com-tabs" aria-label="博客运营"> <nav className="com-tabs" aria-label="博客运营">
{TABS.map((t) => ( {TABS.filter((t) => community !== 'hub' || t.key !== 'adsense').map((t) => (
<button <button
key={t.key} key={t.key}
type="button" type="button"
@ -409,9 +412,9 @@ export default function Blog() {
<div className="com-panel-head"> <div className="com-panel-head">
<div> <div>
<h2>模块与运营文案</h2> <h2>模块与运营文案</h2>
<p>关闭 modules.socialBlog 可隐藏入口(需门户读配置)。</p> <p>关闭 modules.{community}Blog 可隐藏本轨博客入口及文章。</p>
</div> </div>
<label className="com-switch" title="socialBlog"> <label className="com-switch" title={`${community}Blog`}>
<input <input
type="checkbox" type="checkbox"
aria-label="博客模块开关" aria-label="博客模块开关"

View File

@ -10,16 +10,11 @@ if (!process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY) {
} }
} }
/** 低配服务器构建:限制并行与 Turbopack 目标内存,避免 pnpm build 把机器拖死 / OOM */ /** 低配服务器构建限制并行;Node 堆上限由 package.json 的 build 命令控制。 */
const buildCpuCount = Math.max( const buildCpuCount = Math.max(
1, 1,
Number.parseInt(process.env.NEXT_BUILD_CPUS ?? "1", 10) || 1, Number.parseInt(process.env.NEXT_BUILD_CPUS ?? "1", 10) || 1,
); );
const turbopackMemoryMb = Math.max(
256,
Number.parseInt(process.env.NEXT_BUILD_TURBOPACK_MEMORY_MB ?? "1536", 10) ||
1536,
);
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// 不暴露 X-Powered-By: Next.js // 不暴露 X-Powered-By: Next.js
@ -63,7 +58,6 @@ const nextConfig: NextConfig = {
experimental: { experimental: {
cpus: buildCpuCount, cpus: buildCpuCount,
memoryBasedWorkersCount: true, memoryBasedWorkersCount: true,
turbopackMemoryLimit: turbopackMemoryMb * 1024 * 1024,
// 仅 next dev(NODE_ENV=development)建议开启,避免栈帧过滤读到 null source map 控制台报错 // 仅 next dev(NODE_ENV=development)建议开启,避免栈帧过滤读到 null source map 控制台报错
// 生产 build 默认关闭以省内存;需要 Sentry 等可设 NEXT_BUILD_TURBOPACK_SOURCE_MAPS=1 // 生产 build 默认关闭以省内存;需要 Sentry 等可设 NEXT_BUILD_TURBOPACK_SOURCE_MAPS=1
turbopackSourceMaps: turbopackSourceMaps:

View File

@ -13,10 +13,10 @@
"geist": "^1.7.0", "geist": "^1.7.0",
"github-markdown-css": "^5.9.0", "github-markdown-css": "^5.9.0",
"marked": "^17.0.4", "marked": "^17.0.4",
"next": "16.1.6", "next": "16.4.6",
"pocketbase": "^0.26.8", "pocketbase": "^0.26.8",
"react": "19.2.3", "react": "19.2.9",
"react-dom": "19.2.3", "react-dom": "19.2.9",
"three": "^0.183.2" "three": "^0.183.2"
}, },
"devDependencies": { "devDependencies": {
@ -26,7 +26,7 @@
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/three": "^0.183.1", "@types/three": "^0.183.1",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.1.6", "eslint-config-next": "16.4.6",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5" "typescript": "^5"
}, },

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ const h5ViteProxy = {
} }
export default defineConfig(async (merge) => { export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = { const baseConfig: UserConfigExport<'vite'> = {
projectName: 'nomadro-h5', projectName: 'nomadro-h5',
date: '2026-3-30', date: '2026-3-30',
designWidth: 750, designWidth: 750,

View File

@ -2,7 +2,7 @@ const tabBar = {
color: '#8b93a7', color: '#8b93a7',
selectedColor: '#4ecdc4', selectedColor: '#4ecdc4',
backgroundColor: '#0c0c0f', backgroundColor: '#0c0c0f',
borderStyle: 'black', borderStyle: 'black' as const,
list: [ list: [
{ {
pagePath: 'pages/home/index', pagePath: 'pages/home/index',

View File

@ -1,6 +1,7 @@
import { Component, Fragment, useEffect } from 'react' import { Component, Fragment, useEffect } from 'react'
import type { PropsWithChildren, ReactNode } from 'react' import type { PropsWithChildren, ReactNode } from 'react'
import Taro, { useDidHide, useDidShow, useLaunch } from '@tarojs/taro' import Taro, { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import { flush, trackAppLaunch } from './utils/track' import { flush, trackAppLaunch } from './utils/track'
import { import {
loadRemoteConfig, loadRemoteConfig,
@ -63,7 +64,7 @@ function App({ children }: PropsWithChildren) {
applyH5Theme('dark') applyH5Theme('dark')
// 公众号私信卡片:pages/...?userid=OA_openid // 公众号私信卡片:pages/...?userid=OA_openid
const oa = captureOaUseridFromOptions( const oa = captureOaUseridFromOptions(
(options || {}) as Record<string, unknown>, (options || {}) as unknown as Record<string, unknown>,
) )
if (oa) { if (oa) {
void syncOaProfileBind(true).catch(() => undefined) void syncOaProfileBind(true).catch(() => undefined)

View File

@ -9,6 +9,7 @@ type BoxProps = {
id?: string id?: string
children?: ReactNode children?: ReactNode
onClick?: () => void onClick?: () => void
onLongPress?: () => void
html?: string html?: string
style?: CSSProperties style?: CSSProperties
'aria-hidden'?: boolean 'aria-hidden'?: boolean
@ -32,6 +33,7 @@ export function H5Box({
id, id,
children, children,
onClick, onClick,
onLongPress,
html, html,
style, style,
'aria-hidden': ariaHidden, 'aria-hidden': ariaHidden,
@ -87,6 +89,7 @@ export function H5Box({
className={className} className={className}
style={style} style={style}
onClick={handleClick} onClick={handleClick}
onLongPress={onLongPress}
onTouchStart={onTouchStart || onPointerDown} onTouchStart={onTouchStart || onPointerDown}
onTouchMove={onTouchMove || onPointerMove} onTouchMove={onTouchMove || onPointerMove}
onTouchEnd={onTouchEnd || onPointerUp} onTouchEnd={onTouchEnd || onPointerUp}
@ -102,14 +105,16 @@ export function H5Txt({
className, className,
id, id,
children, children,
style,
}: { }: {
className?: string className?: string
id?: string id?: string
children?: ReactNode children?: ReactNode
style?: CSSProperties
}) { }) {
if (isH5) return <span id={id} className={className}>{children}</span> if (isH5) return <span id={id} className={className} style={style}>{children}</span>
return ( return (
<Text id={id} className={className}> <Text id={id} className={className} style={style}>
{children} {children}
</Text> </Text>
) )

View File

@ -30,7 +30,7 @@
"id": "nomadcna", "id": "nomadcna",
"title": "nomadcna", "title": "nomadcna",
"subtitle": "国内数字游民社区", "subtitle": "国内数字游民社区",
"href": "https://nomadro.com/social", "href": "https://nomadro.com/hub",
"icon": "/icons/nomadcna.webp" "icon": "/icons/nomadcna.webp"
} }
] ]

View File

@ -793,6 +793,12 @@ export function nomadCodeReadPayload(): ReadPayload {
} }
], ],
progress: { chapter_id: "00-前言", percent: 0 }, progress: { chapter_id: "00-前言", percent: 0 },
access: { unlocked: false, is_free: false }, unlocked: false,
unlock_percent: 30,
preview_ratio: 0.3,
access: {
book_id: "default", unlocked: false, is_free: false, unlock_percent: 30,
product_id: "nomad_lite", price_fen: 2900, updated_at: 0,
},
} as ReadPayload } as ReadPayload
} }

View File

@ -418,7 +418,7 @@ export default function BookCoverPage() {
void loadRemoteConfig(true) void loadRemoteConfig(true)
// 预下载阅读壳,避免提审点开黑屏 // 预下载阅读壳,避免提审点开黑屏
try { try {
void Taro.loadSubPackage?.({ name: 'vip-ebook' }) void Taro.loadSubPackage?.({ name: 'vip-ebook' } as Parameters<typeof Taro.loadSubPackage>[0])
} catch { } catch {
/* ignore */ /* ignore */
} }

View File

@ -214,7 +214,7 @@ function SocialHome() {
<H5El as='nav' className='social-path' aria-label='本页导航'> <H5El as='nav' className='social-path' aria-label='本页导航'>
<H5El className='container'> <H5El className='container'>
<H5El className='social-path-track reveal visible'> <H5El className='social-path-track reveal visible'>
{PATH_CHIPS.filter((p) => !hiddenSections.includes(p.href.slice(1))).map((p) => ( {PATH_CHIPS.filter((p) => !hiddenSections.some(section => section === p.href.slice(1))).map((p) => (
<H5El <H5El
as='a' as='a'
key={p.href} key={p.href}

View File

@ -26,6 +26,8 @@ export type Destination = {
climate?: string climate?: string
nomads_count?: string nomads_count?: string
highlights?: string[] highlights?: string[]
map_x?: number
map_y?: number
} }
export type Meetup = { export type Meetup = {

View File

@ -7,6 +7,8 @@ export type ChapterMeta = {
id: string id: string
title: string title: string
order: number order: number
emoji?: string
unlocked?: boolean
} }
export type BookDetail = { export type BookDetail = {
@ -42,6 +44,7 @@ export type ReadPayload = {
price_label?: string price_label?: string
offer_name?: string offer_name?: string
updated_at?: number updated_at?: number
progress?: { chapter_id: string; percent: number }
access?: AccessSnapshot access?: AccessSnapshot
} }

View File

@ -26,7 +26,6 @@ let pollTimer: ReturnType<typeof setInterval> | null = null
let knownVersion = 0 let knownVersion = 0
let knownFp = '' let knownFp = ''
let configInFlight: Promise<LoadResult> | null = null let configInFlight: Promise<LoadResult> | null = null
let forceQueued = false
let appVisible = true let appVisible = true
let socketTask: Taro.SocketTask | null = null let socketTask: Taro.SocketTask | null = null
let socketReconnect: ReturnType<typeof setTimeout> | null = null let socketReconnect: ReturnType<typeof setTimeout> | null = null
@ -35,23 +34,8 @@ let stoppedFlag = false
function configFingerprint(cfg: NomadroRemoteConfig): string { function configFingerprint(cfg: NomadroRemoteConfig): string {
try { try {
// 必须含 copy:VIP 价/道具/CTA、小册 live bump,否则后台改档 UI 不刷新 // Every configurable field matters, including nav content and page switches.
return JSON.stringify({ return JSON.stringify(cfg)
v: cfg.version,
at: cfg.updatedAt,
modules: cfg.modules,
flags: cfg.flags,
copy: {
vipPriceFen: cfg.copy?.vipPriceFen,
vipProductId: cfg.copy?.vipProductId,
vipCta: cfg.copy?.vipCta,
vipOfferKey: cfg.copy?.vipOfferKey,
booksOfferRev: (cfg.copy as { booksOfferRev?: number } | undefined)?.booksOfferRev,
booksOfferBookId: (cfg.copy as { booksOfferBookId?: string } | undefined)
?.booksOfferBookId,
},
bookAudit: cfg.platforms?.weapp?.bookAudit,
})
} catch { } catch {
return String(cfg.version || 0) return String(cfg.version || 0)
} }
@ -156,7 +140,6 @@ export function loadRemoteConfig(force = false): Promise<LoadResult> {
if (!force && memory) return Promise.resolve(memory) if (!force && memory) return Promise.resolve(memory)
if (configInFlight) { if (configInFlight) {
if (force) forceQueued = true
return configInFlight return configInFlight
} }
@ -200,10 +183,6 @@ export function loadRemoteConfig(force = false): Promise<LoadResult> {
configInFlight = pending configInFlight = pending
void pending.finally(() => { void pending.finally(() => {
if (configInFlight === pending) configInFlight = null if (configInFlight === pending) configInFlight = null
if (forceQueued) {
forceQueued = false
void loadRemoteConfig(true)
}
}) })
return pending return pending
} }
@ -358,7 +337,10 @@ export function startRemoteConfigLiveSync(): () => void {
if (visible) void loadRemoteConfig(true) if (visible) void loadRemoteConfig(true)
}, FULL_POLL_MS) }, FULL_POLL_MS)
void loadRemoteConfig(true) // Coalesce startup with onAppShow and let an immediate hide suppress the pull.
void Promise.resolve().then(() => {
if (!stoppedFlag && appVisible) return loadRemoteConfig(true)
})
const stop = () => { const stop = () => {
stoppedFlag = true stoppedFlag = true

View File

@ -242,12 +242,15 @@ export const socialApi = {
channelId: string, channelId: string,
opts?: { limit?: number; since?: number; before?: number; q?: string }, opts?: { limit?: number; since?: number; before?: number; q?: string },
) => { ) => {
const q = new URLSearchParams() // Mini-program engines do not consistently provide URLSearchParams.
if (opts?.limit) q.set('limit', String(opts.limit)) const query: string[] = []
if (opts?.since != null) q.set('since', String(opts.since)) const add = (key: string, value: string | number) =>
if (opts?.before != null) q.set('before', String(opts.before)) query.push(`${key}=${encodeURIComponent(String(value))}`)
if (opts?.q) q.set('q', opts.q) if (opts?.limit) add('limit', opts.limit)
const qs = q.toString() if (opts?.since != null) add('since', opts.since)
if (opts?.before != null) add('before', opts.before)
if (opts?.q) add('q', opts.q)
const qs = query.join('&')
return req<{ items: SocialChatMessage[]; seq?: number }>( return req<{ items: SocialChatMessage[]; seq?: number }>(
`/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ''}`, `/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ''}`,
) )

View File

@ -1,10 +1,10 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2017",
"module": "commonjs", "module": "esnext",
"jsx": "react-jsx", "jsx": "react-jsx",
"strict": true, "strict": true,
"moduleResolution": "node", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true, "esModuleInterop": true,
"skipLibCheck": true, "skipLibCheck": true,

View File

@ -31,7 +31,7 @@ export default defineConfig(async (merge) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const { vitePostCopySizePlugin } = require('../scripts/post-copy-size-plugin') const { vitePostCopySizePlugin } = require('../scripts/post-copy-size-plugin')
const baseConfig: UserConfigExport = { const baseConfig: UserConfigExport<'vite' | 'webpack5'> = {
projectName: 'nomadro-tt', projectName: 'nomadro-tt',
date: '2026-3-30', date: '2026-3-30',
designWidth: 750, designWidth: 750,
@ -79,7 +79,7 @@ export default defineConfig(async (merge) => {
alias: { alias: {
'@': path.resolve(__dirname, '..', 'src'), '@': path.resolve(__dirname, '..', 'src'),
}, },
modifyWebpackChain(chain) { modifyWebpackChain(chain: { plugin(name: string): { use(plugin: unknown, args?: unknown[]): unknown } }) {
if (useVite) return if (useVite) return
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const CopyWebpackPlugin = require('copy-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin')

View File

@ -25,7 +25,7 @@ export default defineAppConfig({
}, },
}, },
/** 抖音官方:app.json usePrivacyCheck(见隐私协议开发指南) */ /** 抖音官方:app.json usePrivacyCheck(见隐私协议开发指南) */
usePrivacyCheck: true, ...{ usePrivacyCheck: true },
/** 兼容旧字段 */ /** 兼容旧字段 */
__usePrivacyCheck__: true, __usePrivacyCheck__: true,
window: { window: {

View File

@ -74,14 +74,16 @@ export function H5Txt({
className, className,
id, id,
children, children,
style,
}: { }: {
className?: string className?: string
id?: string id?: string
children?: ReactNode children?: ReactNode
style?: CSSProperties
}) { }) {
if (isH5) return <span id={id} className={className}>{children}</span> if (isH5) return <span id={id} className={className} style={style}>{children}</span>
return ( return (
<Text id={id} className={className}> <Text id={id} className={className} style={style}>
{children} {children}
</Text> </Text>
) )

View File

@ -30,7 +30,7 @@
"id": "nomadcna", "id": "nomadcna",
"title": "nomadcna", "title": "nomadcna",
"subtitle": "国内数字游民社区", "subtitle": "国内数字游民社区",
"href": "https://nomadro.com/social", "href": "https://nomadro.com/hub",
"icon": "/icons/nomadcna.webp" "icon": "/icons/nomadcna.webp"
} }
] ]

File diff suppressed because one or more lines are too long

View File

@ -26,6 +26,8 @@ export type Destination = {
climate?: string climate?: string
nomads_count?: string nomads_count?: string
highlights?: string[] highlights?: string[]
map_x?: number
map_y?: number
} }
export type Meetup = { export type Meetup = {

View File

@ -12,6 +12,8 @@ export type ChapterMeta = {
id: string id: string
title: string title: string
order: number order: number
emoji?: string
unlocked?: boolean
} }
export type BookDetail = { export type BookDetail = {
@ -47,6 +49,7 @@ export type ReadPayload = {
price_label?: string price_label?: string
offer_name?: string offer_name?: string
updated_at?: number updated_at?: number
progress?: { chapter_id: string; percent: number }
access?: AccessSnapshot access?: AccessSnapshot
} }

View File

@ -94,7 +94,13 @@ export default defineConfig(async (merge) => {
alias: { alias: {
'@': h5Src, '@': h5Src,
}, },
modifyWebpackChain(chain) { modifyWebpackChain(chain: {
resolve: {
modules: { prepend(path: string): unknown }
alias: { set(key: string, value: string): unknown }
}
plugin(name: string): { use(plugin: unknown, args?: unknown[]): unknown }
}) {
const weappNm = path.resolve(__dirname, '..', 'node_modules') const weappNm = path.resolve(__dirname, '..', 'node_modules')
const webpack = require('webpack') const webpack = require('webpack')
chain.resolve.modules.prepend(weappNm) chain.resolve.modules.prepend(weappNm)

View File

@ -7,7 +7,7 @@
"xhs_imgs": 120, "xhs_imgs": 120,
"xhs_budget_kb": 2867, "xhs_budget_kb": 2867,
"xhs_used_kb": 1012, "xhs_used_kb": 1012,
"seconds": 3.4, "seconds": 1.2,
"limits": { "limits": {
"douyin": "main≤4MB sub≤2MB total≤16MB", "douyin": "main≤4MB sub≤2MB total≤16MB",
"xhs": "offline pack ≤10MB & ≤200 files; no CDN" "xhs": "offline pack ≤10MB & ≤200 files; no CDN"

View File

@ -460,6 +460,8 @@ def write_xhs(chapters: list[dict], title: str) -> None:
"author": "异度世界", "author": "异度世界",
"coverEmoji": "🚀", "coverEmoji": "🚀",
"description": "配图按小红书小工具包体积上限精选固化(禁 CDN)。", "description": "配图按小红书小工具包体积上限精选固化(禁 CDN)。",
# 小红书小工具试读章数;赞赏解锁全书(§3.18 rewardAuthor)
"free_chapters": 3,
"tags": soft_sanitize_audit_deep(["数字游民", "云手机", "无人直播", "自动化"]), "tags": soft_sanitize_audit_deep(["数字游民", "云手机", "无人直播", "自动化"]),
"chapters": [ "chapters": [
{ {

View File

@ -177,6 +177,24 @@ test('configuration polling pauses in background and never overlaps slow meta re
stop() stop()
}) })
test('copy and page configuration updates notify subscribers without a version bump', async () => {
let config = { ...seed, copy: { navContent: 'old' }, pages: { book: true } }
const { api } = harness('services/remoteConfig.ts', {
request: async () => ({ statusCode: 200, data: { config } }),
}, seedImport)
const updates = []
const unsubscribe = api.subscribeRemoteConfig(result => updates.push(result.config))
await api.loadRemoteConfig(true)
config = { ...config, copy: { navContent: 'new' } }
await api.loadRemoteConfig(true)
config = { ...config, pages: { book: false } }
await api.loadRemoteConfig(true)
unsubscribe()
assert.equal(updates.length, 3)
assert.equal(updates[1].copy.navContent, 'new')
assert.equal(updates[2].pages.book, false)
})
test('rapid taps open one page; home resets the stack', async () => { test('rapid taps open one page; home resets the stack', async () => {
const gate = deferred() const gate = deferred()
let navigations = 0 let navigations = 0

View File

@ -21,7 +21,7 @@ test('reads fail over and subsequent writes use the successful origin', async ()
await api.socialApi.listMessages('general') await api.socialApi.listMessages('general')
await api.socialApi.sendMessage('general', 'Name', 'Hello', 'key') await api.socialApi.sendMessage('general', 'Name', 'Hello', 'key')
assert.equal(urls.length, 3) assert.equal(urls.length, 3)
assert.ok(urls[2].startsWith('https://api.nomadro.cn/')) assert.equal(new URL(urls[2]).origin, new URL(urls[1]).origin)
}) })
test('uncertain message writes never replay across origins', async () => { test('uncertain message writes never replay across origins', async () => {
let count = 0 let count = 0

View File

@ -1,16 +1,17 @@
{ {
"extends": "../h5/tsconfig.json",
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2017",
"module": "commonjs", "module": "esnext",
"jsx": "react-jsx", "jsx": "react-jsx",
"strict": true, "strict": true,
"moduleResolution": "node", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true, "esModuleInterop": true,
"skipLibCheck": true, "skipLibCheck": true,
"baseUrl": ".", "baseUrl": ".",
"paths": { "@/*": ["src/*"] }, "paths": { "@/*": ["../h5/src/*"] },
"types": ["@tarojs/taro"] "types": ["@tarojs/taro"]
}, },
"include": ["src", "types", "config"] "include": ["../h5/src", "types", "config"]
} }

File diff suppressed because one or more lines are too long

View File

@ -39,6 +39,7 @@
<button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button> <button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button>
<button type="button" class="home-xhs-btn" id="home-journal">写日记</button> <button type="button" class="home-xhs-btn" id="home-journal">写日记</button>
<button type="button" class="home-xhs-btn" id="home-works">我的作品</button> <button type="button" class="home-xhs-btn" id="home-works">我的作品</button>
<button type="button" class="home-xhs-btn home-xhs-reward is-hidden" id="home-reward">赞赏解锁</button>
</div> </div>
<p class="home-time" id="home-time"></p> <p class="home-time" id="home-time"></p>
</div> </div>
@ -125,6 +126,7 @@
<p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p> <p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p>
<p class="rs-section">小红书</p> <p class="rs-section">小红书</p>
<div class="rs-actions"> <div class="rs-actions">
<button type="button" class="rs-action is-hidden" id="btn-reward">赞赏解锁全书</button>
<button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button> <button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button>
<button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button> <button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button>
<button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button> <button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button>

View File

@ -736,6 +736,61 @@ button {
color: var(--r-text); color: var(--r-text);
} }
.paywall {
margin: 28px 0 40px;
padding: 22px 14px 18px;
text-align: center;
border-top: 1px dashed var(--r-border);
background: linear-gradient(180deg, transparent, rgba(245, 158, 11, 0.08));
border-radius: 0 0 16px 16px;
}
.paywall-emoji {
display: block;
font-size: 30px;
line-height: 1;
}
.paywall-title {
display: block;
margin-top: 8px;
font-size: 20px;
font-weight: 700;
color: var(--r-text);
}
.paywall-desc {
display: block;
margin: 6px auto 0;
max-width: 16em;
font-size: 13px;
line-height: 1.45;
color: var(--r-muted);
}
.paywall-btn {
margin-top: 16px;
min-height: 44px;
min-width: 160px;
background: linear-gradient(135deg, #f59e0b, #d97706);
}
.paywall-hint {
display: block;
margin-top: 10px;
font-size: 12px;
color: var(--r-muted);
}
.drawer-item.locked .drawer-name {
opacity: 0.72;
}
.home-xhs-reward {
border-color: rgba(245, 158, 11, 0.45);
color: #f59e0b;
}
.md-body { .md-body {
font-size: 16px; font-size: 16px;
line-height: 1.7; line-height: 1.7;

View File

@ -11,16 +11,25 @@ ROOT = Path(__file__).resolve().parents[1]
MINI = ROOT.parent MINI = ROOT.parent
SRC = ROOT / "tool" SRC = ROOT / "tool"
OUT = ROOT / "release-book" OUT = ROOT / "release-book"
PACK = MINI / "scripts" / "pack-hackrobot-book.py" PACK_CANDIDATES = (
MINI / "weapp" / "scripts" / "pack-hackrobot-book.py",
MINI / "scripts" / "pack-hackrobot-book.py",
)
def main() -> int: def main() -> int:
check_call([sys.executable, str(ROOT / "scripts" / "sync_data.py")]) sync = ROOT / "scripts" / "sync_data.py"
if sync.is_file():
try:
check_call([sys.executable, str(sync)])
except Exception as e:
print(f"WARN sync_data failed, continue with local book seed: {e}", file=sys.stderr)
# export 会写回旧册;必须再用 hackrobot 覆盖 book-data + portal.book # export 会写回旧册;必须再用 hackrobot 覆盖 book-data + portal.book
if PACK.is_file(): pack = next((p for p in PACK_CANDIDATES if p.is_file()), None)
check_call([sys.executable, str(PACK)]) if pack:
check_call([sys.executable, str(pack)])
else: else:
print(f"WARN missing {PACK}", file=sys.stderr) print(f"WARN missing pack-hackrobot-book.py under {PACK_CANDIDATES}", file=sys.stderr)
if OUT.exists(): if OUT.exists():
shutil.rmtree(OUT, ignore_errors=True) shutil.rmtree(OUT, ignore_errors=True)
@ -70,6 +79,14 @@ def main() -> int:
if "低成本工作室" not in app_js or "数字游民:自动化杠杆副业" not in app_js: if "低成本工作室" not in app_js or "数字游民:自动化杠杆副业" not in app_js:
print("FATAL release-book missing hackrobot chapters", file=sys.stderr) print("FATAL release-book missing hackrobot chapters", file=sys.stderr)
return 1 return 1
if "rewardAuthor" not in app_js or "free_chapters" not in app_js:
print("FATAL release-book missing tip/trial unlock hooks", file=sys.stderr)
return 1
css = (OUT / "styles.css").read_text(encoding="utf-8", errors="ignore")
html = (OUT / "index.html").read_text(encoding="utf-8", errors="ignore")
if ".paywall" not in css or 'id="btn-reward"' not in html:
print("FATAL release-book missing paywall UI", file=sys.stderr)
return 1
print(f"assembled {OUT}") print(f"assembled {OUT}")
for p in sorted(OUT.iterdir()): for p in sorted(OUT.iterdir()):

View File

@ -8,14 +8,19 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
MINI = ROOT.parent MINI = ROOT.parent
SCRIPT = MINI / "scripts" / "export-xhs-offline.mjs" # SoT 在 xhs/scripts;兼容旧路径 miniprogram/scripts
CANDIDATES = (
ROOT / "scripts" / "export-xhs-offline.mjs",
MINI / "scripts" / "export-xhs-offline.mjs",
)
def main() -> int: def main() -> int:
if not SCRIPT.is_file(): script = next((p for p in CANDIDATES if p.is_file()), None)
print(f"missing {SCRIPT}", file=sys.stderr) if not script:
print(f"missing export-xhs-offline.mjs under {CANDIDATES}", file=sys.stderr)
return 1 return 1
return subprocess.call(["node", str(SCRIPT)], cwd=str(MINI)) return subprocess.call(["node", str(script)], cwd=str(MINI))
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,601 +1,4 @@
/* book-app runtime — BOOK_DATA from book/book-data.js */ /* book-app runtime — BOOK_DATA from book/book-data.js */
(function () {
return 0;
});
}
function setLocalData(key, data, encrypt) {
var serialized;
try {
serialized = JSON.stringify(data);
} catch (e) {
return Promise.resolve(false);
}
if (typeof serialized !== "string") return Promise.resolve(false);
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.setStorage === "function"
) {
var payload = { key: key, data: serialized };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload))
.then(function () {
return true;
})
.catch(function () {
return writeBrowser(key, serialized);
});
}
return writeBrowser(key, serialized);
});
}
function writeBrowser(key, serialized) {
try {
global.localStorage.setItem(key, serialized);
return true;
} catch (e) {
return false;
}
}
function getLocalData(key, fallback, encrypt) {
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.getStorage === "function"
) {
var payload = { key: key };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.getStorage(payload))
.then(function (res) {
var raw = res && res.data;
if (raw != null && raw !== "") {
try {
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
// Retry without encrypt (migration), then browser
if (useEncrypt) {
return Promise.resolve(mt.getStorage({ key: key }))
.then(function (res2) {
var raw2 = res2 && res2.data;
if (raw2 != null && raw2 !== "") {
try {
var parsed = JSON.parse(raw2);
return setLocalData(key, parsed, true).then(function () {
return parsed;
});
} catch (e2) {
return readBrowser(key, fallback);
}
}
return readBrowser(key, fallback);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
var fromBrowser = readBrowser(key, null);
if (fromBrowser == null) return fallback;
return writeNative(mt, key, JSON.stringify(fromBrowser), false).then(
function () {
return fromBrowser;
},
function () {
return fromBrowser;
}
);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
return readBrowser(key, fallback);
});
}
function writeNative(mt, key, serialized, encrypt) {
if (!mt || typeof mt.setStorage !== "function") {
return Promise.resolve(false);
}
var payload = { key: key, data: serialized };
if (encrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload)).then(
function () {
return true;
},
function () {
return false;
}
);
}
function readBrowser(key, fallback) {
try {
var raw = global.localStorage.getItem(key);
if (raw == null || raw === "") return fallback;
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
function removeLocalData(key) {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.removeStorage === "function"
) {
return Promise.resolve(mt.removeStorage({ key: key }))
.then(function () {
removeBrowser(key);
return true;
})
.catch(function () {
return removeBrowser(key);
});
}
return removeBrowser(key);
});
}
function clearLocalData() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.clearStorage === "function"
) {
return Promise.resolve(mt.clearStorage())
.then(function () {
clearBrowser();
return true;
})
.catch(function () {
return clearBrowser();
});
}
return clearBrowser();
});
}
function removeBrowser(key) {
try {
global.localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
}
function clearBrowser() {
try {
global.localStorage.clear();
return true;
} catch (e) {
return false;
}
}
function getLaunchOptions() {
var xhs = global.xhs;
if (xhs && xhs.launchOptions) {
return Promise.resolve(xhs.launchOptions);
}
var mt = getMiniTool();
if (!mt || typeof mt.getLaunchOptions !== "function") {
return Promise.resolve(null);
}
return Promise.resolve(mt.getLaunchOptions()).catch(function () {
return null;
});
}
/** Read miniToolSnapshotInfo from launch options (comment re-entry, §3.9). */
function readSnapshotInfo(launchOptions) {
if (!launchOptions) return null;
var raw =
launchOptions.miniToolSnapshotInfo ||
(launchOptions.query && launchOptions.query.miniToolSnapshotInfo) ||
(launchOptions.referrerInfo &&
launchOptions.referrerInfo.miniToolSnapshotInfo) ||
(launchOptions.extraData && launchOptions.extraData.miniToolSnapshotInfo);
if (!raw) return null;
if (typeof raw === "object") return raw;
try {
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function callApi(name, options) {
var mt = getMiniTool();
if (!mt || typeof mt[name] !== "function") {
return Promise.reject({ errMsg: name + ":fail not available" });
}
return Promise.resolve(mt[name](options || {}));
}
function writeTempFile(dataUrl) {
return callApi("writeTempFile", { data: dataUrl }).then(function (res) {
return (res && res.filePath) || dataUrl;
});
}
function saveImageToPhotosAlbum(filePath) {
return callApi("saveImageToPhotosAlbum", { filePath: filePath });
}
function postNote(opts) {
return callApi("postNote", opts);
}
function canPostComment(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, COMMENT_MIN) &&
mt &&
typeof mt.interactionOpenApi === "function"
);
}
function postComment(payload, saveToAlbum) {
return callApi("interactionOpenApi", {
payload: payload,
saveToAlbum: saveToAlbum !== false
});
}
function getStorageInfo() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(buildVersion, STORAGE_MIN) ||
!mt ||
typeof mt.getStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getStorageInfo()).catch(function () {
return null;
});
});
}
function canUseFileSystem(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, FILE_MIN) &&
mt &&
typeof mt.writeFile === "function" &&
typeof mt.readFile === "function"
);
}
function getUserDataPath() {
return getLaunchOptions().then(function (opts) {
var env = opts && opts.miniToolEnv;
return (env && env.userDataPath) || "";
});
}
function ensureDir(dirPath) {
var mt = getMiniTool();
if (!mt || typeof mt.mkdir !== "function") {
return Promise.resolve(false);
}
return Promise.resolve(mt.mkdir({ dirPath: dirPath, recursive: true }))
.then(function () {
return true;
})
.catch(function () {
return false;
});
}
function writeUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "writeFile:fail version" });
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "writeFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("writeFile", {
filePath: filePath,
data: typeof data === "string" ? data : JSON.stringify(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function appendUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "appendFile:fail version" });
}
var mt = getMiniTool();
if (!mt || typeof mt.appendFile !== "function") {
// Fallback: read + write
return readUtf8File(relativePath).then(function (prev) {
return writeUtf8File(
relativePath,
(prev || "") + (typeof data === "string" ? data : String(data))
);
});
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "appendFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("appendFile", {
filePath: filePath,
data: typeof data === "string" ? data : String(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function postVideoNote(opts) {
var videoRes = { video_url: opts.videoPath };
if (opts.coverPath) videoRes.cover_url = opts.coverPath;
return callApi("postNote", {
title: opts.title,
content: opts.content,
pageType: "video_publish",
mediaInfo: {
video_resources: videoRes
}
});
}
function readUtf8File(relativePath) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.resolve(null);
}
return getUserDataPath().then(function (root) {
if (!root) return null;
var filePath = root + "/" + String(relativePath || "").replace(/^\/+/, "");
return callApi("readFile", { filePath: filePath, encoding: "utf8" })
.then(function (res) {
return res && res.data != null ? res.data : null;
})
.catch(function () {
return null;
});
});
});
}
/** Write dataURL to temp, then optionally persist via saveFile (9.49+). */
function persistImage(dataUrl, relativePath) {
return writeTempFile(dataUrl).then(function (tempPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!relativePath ||
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.saveFile !== "function"
) {
return tempPath;
}
return getUserDataPath().then(function (root) {
if (!root) return tempPath;
var dest = root + "/" + String(relativePath).replace(/^\/+/, "");
var dir = dest.replace(/\/[^/]+$/, "");
return ensureDir(dir).then(function () {
return callApi("saveFile", {
tempFilePath: tempPath,
filePath: dest
})
.then(function (res) {
return (res && res.savedFilePath) || dest || tempPath;
})
.catch(function () {
return tempPath;
});
});
});
});
});
}
function getFileStorageInfo() {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.getFileStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getFileStorageInfo()).catch(function () {
return null;
});
});
}
function unlinkFile(relativeOrAbsPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.unlink !== "function"
) {
return false;
}
var path = String(relativeOrAbsPath || "");
if (!path) return false;
var p = Promise.resolve(path);
if (path.indexOf("/") !== 0 && path.indexOf("usr") !== 0) {
p = getUserDataPath().then(function (root) {
return root ? root + "/" + path.replace(/^\/+/, "") : path;
});
}
return p.then(function (filePath) {
return callApi("unlink", { filePath: filePath })
.then(function () {
return true;
})
.catch(function () {
return false;
});
});
});
}
function readDirList(relativeDir) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.readDir !== "function"
) {
return [];
}
return getUserDataPath().then(function (root) {
if (!root) return [];
var dirPath =
root +
(relativeDir
? "/" + String(relativeDir).replace(/^\/+|\/+$/g, "")
: "");
return callApi("readDir", { dirPath: dirPath })
.then(function (res) {
var files = (res && res.files) || [];
return files.map(function (f) {
if (typeof f === "string") {
return { name: f, path: dirPath + "/" + f };
}
var name = f.name || f.fileName || String(f);
return {
name: name,
path: f.path || f.filePath || dirPath + "/" + name,
isDir: !!(f.isDir || f.isDirectory)
};
});
})
.catch(function () {
return [];
});
});
});
}
function cleanupShareDir() {
return readDirList("share").then(function (files) {
var chain = Promise.resolve(0);
for (var i = 0; i < files.length; i++) {
(function (file) {
if (file.isDir) return;
chain = chain.then(function (n) {
return callApi("unlink", { filePath: file.path })
.then(function () {
return n + 1;
})
.catch(function () {
return n;
});
});
})(files[i]);
}
return chain;
});
}
/** Convert <input type=file> File / Blob to data URL (offline, no network). */
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
if (!blob) {
reject({ errMsg: "blobToDataUrl:fail empty" });
return;
}
try {
var reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject({ errMsg: "blobToDataUrl:fail read" });
};
reader.readAsDataURL(blob);
} catch (e) {
reject({ errMsg: "blobToDataUrl:fail " + (e && e.message) });
}
});
}
global.XhsBridge = {
getBuildVersion: getBuildVersion,
getClientVersion: getClientVersion,
isClientVersionAtLeast: isClientVersionAtLeast,
setLocalData: setLocalData,
getLocalData: getLocalData,
removeLocalData: removeLocalData,
clearLocalData: clearLocalData,
getStorageInfo: getStorageInfo,
getFileStorageInfo: getFileStorageInfo,
getLaunchOptions: getLaunchOptions,
readSnapshotInfo: readSnapshotInfo,
writeTempFile: writeTempFile,
saveImageToPhotosAlbum: saveImageToPhotosAlbum,
postNote: postNote,
canPostComment: canPostComment,
postComment: postComment,
canUseFileSystem: canUseFileSystem,
getUserDataPath: getUserDataPath,
writeUtf8File: writeUtf8File,
appendUtf8File: appendUtf8File,
readUtf8File: readUtf8File,
persistImage: persistImage,
unlinkFile: unlinkFile,
readDirList: readDirList,
cleanupShareDir: cleanupShareDir,
blobToDataUrl: blobToDataUrl,
postVideoNote: postVideoNote,
getMiniTool: getMiniTool,
STORAGE_MIN: STORAGE_MIN,
COMMENT_MIN: COMMENT_MIN,
FILE_MIN: FILE_MIN
};
})(window);
(function () { (function () {
"use strict"; "use strict";
@ -608,8 +11,11 @@
var JOURNAL_KEY = "yidu_journal"; var JOURNAL_KEY = "yidu_journal";
var TIME_KEY = "yidu_read_time"; var TIME_KEY = "yidu_read_time";
var WORKS_KEY = "yidu_works"; var WORKS_KEY = "yidu_works";
var UNLOCK_KEY = "yidu_book_unlock";
var NOTES_FILE = "notes/clips.json"; var NOTES_FILE = "notes/clips.json";
var JOURNAL_FILE = "notes/journal.json"; var JOURNAL_FILE = "notes/journal.json";
/** 试读章数兜底;BOOK_DATA.free_chapters / unlock_percent 可覆盖 */
var DEFAULT_FREE_CHAPTERS = 3;
var Bridge = window.XhsBridge; var Bridge = window.XhsBridge;
var FONT_SIZES = [ var FONT_SIZES = [
{ label: "小", value: 15 }, { label: "小", value: 15 },
@ -660,7 +66,10 @@
jumpLockUntil: 0, jumpLockUntil: 0,
chromeHidden: false, chromeHidden: false,
camStream: null, camStream: null,
camShot: null camShot: null,
unlocked: false,
rewarding: false,
closeRetentionOn: false
}; };
var el = {}; var el = {};
@ -1143,6 +552,128 @@
return null; return null;
} }
function freeChapterCount() {
var book = state.book || {};
var chapters = book.chapters || [];
var total = chapters.length || 1;
var n = Number(book.free_chapters);
if (isFinite(n) && n >= 1) {
return Math.min(total, Math.max(1, Math.floor(n)));
}
var pct = Number(book.unlock_percent);
if (isFinite(pct) && pct > 0 && pct < 100) {
return Math.min(total, Math.max(1, Math.floor((total * pct) / 100)));
}
return Math.min(total, DEFAULT_FREE_CHAPTERS);
}
/** 赞赏可用才门控;旧客户端 / 浏览器保证全书可读 */
function canGateByReward() {
return !!(Bridge && typeof Bridge.canRewardAuthor === "function" && Bridge.canRewardAuthor(state.buildVersion));
}
function hasFullAccess() {
if (!canGateByReward()) return true;
return !!state.unlocked;
}
function isChapterLocked(idx) {
if (hasFullAccess()) return false;
return idx >= freeChapterCount();
}
function loadUnlock() {
var bookId = state.book && state.book.id;
return Bridge.getLocalData(UNLOCK_KEY, null, true).then(function (raw) {
if (!raw || typeof raw !== "object") return false;
if (raw.bookId && bookId && raw.bookId !== bookId) return false;
return !!raw.unlocked;
});
}
function saveUnlock(unlocked) {
state.unlocked = !!unlocked;
return Bridge.setLocalData(
UNLOCK_KEY,
{
bookId: state.book && state.book.id,
unlocked: !!unlocked,
at: Date.now()
},
true
);
}
function syncCloseRetention() {
var want = canGateByReward() && !state.unlocked;
if (want === state.closeRetentionOn) {
return Promise.resolve(want);
}
state.closeRetentionOn = want;
if (!Bridge || typeof Bridge.setCloseRetentionEnabled !== "function") {
return Promise.resolve(false);
}
return Bridge.setCloseRetentionEnabled(want).catch(function () {
return false;
});
}
function buildPaywallHtml() {
var freeN = freeChapterCount();
var total = ((state.book && state.book.chapters) || []).length;
var lockedN = Math.max(0, total - freeN);
var tipOk = canGateByReward();
return (
'<div class="paywall" id="book-paywall">' +
'<span class="paywall-emoji">☕</span>' +
'<span class="paywall-title">试读结束</span>' +
'<span class="paywall-desc">已开放前 ' +
freeN +
" 章 · 余下 " +
lockedN +
" 章需赞赏解锁</span>" +
(tipOk
? '<button type="button" class="fin-btn paywall-btn" data-unlock="reward">赞赏解锁全书</button>' +
'<span class="paywall-hint">任意金额即可 · 关闭时也可顺手支持作者</span>'
: '<span class="paywall-hint">请升级小红书至 9.53.3+ 后赞赏解锁</span>') +
"</div>"
);
}
function requestUnlock() {
if (state.rewarding) return;
if (!canGateByReward()) {
alert("当前环境暂不支持赞赏,请升级小红书后重试");
return;
}
var already = !!state.unlocked;
state.rewarding = true;
Bridge.rewardAuthor()
.then(function () {
if (already) {
state.rewarding = false;
alert("感谢再次支持");
return null;
}
return saveUnlock(true).then(function () {
state.rewarding = false;
return syncCloseRetention();
});
})
.then(function (didUnlock) {
if (already || didUnlock === null) return;
alert("感谢支持,全书已解锁");
renderReader(true);
syncActionLabels();
})
.catch(function (err) {
state.rewarding = false;
var msg = String((err && err.errMsg) || "");
if (/cancel|取消|fail user/i.test(msg)) return;
alert("赞赏未完成,可稍后再试");
});
}
function escapeText(s) { function escapeText(s) {
return String(s) return String(s)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
@ -1205,7 +736,14 @@
} }
} else { } else {
if (el.btnStart) el.btnStart.textContent = "开始阅读"; if (el.btnStart) el.btnStart.textContent = "开始阅读";
if (el.homeHint) el.homeHint.textContent = "点一下,直接进入正文"; if (el.homeHint) {
if (canGateByReward() && !state.unlocked) {
el.homeHint.textContent =
"免费试读前 " + freeChapterCount() + " 章 · 赞赏解锁全书";
} else {
el.homeHint.textContent = "点一下,直接进入正文";
}
}
} }
updateHomeTimeLabel(); updateHomeTimeLabel();
showView("home"); showView("home");
@ -1371,20 +909,26 @@
var active = i === state.activeChapter ? " active" : ""; var active = i === state.activeChapter ? " active" : "";
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length]; var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var starred = isBookmarked(ch.id) ? " ★" : ""; var starred = isBookmarked(ch.id) ? " ★" : "";
var locked = isChapterLocked(i);
var lockMark = locked ? " 🔒" : "";
html.push( html.push(
'<button type="button" class="drawer-item' + '<button type="button" class="drawer-item' +
active + active +
(locked ? " locked" : "") +
'" data-ch="' + '" data-ch="' +
ch.id + ch.id +
'" data-idx="' + '" data-idx="' +
i + i +
'"><span class="drawer-idx">' + '"' +
(locked ? ' data-locked="1"' : "") +
'><span class="drawer-idx">' +
pad2(i + 1) + pad2(i + 1) +
'</span><span class="drawer-body"><span class="drawer-name">' + '</span><span class="drawer-body"><span class="drawer-name">' +
emoji + emoji +
" " + " " +
escapeText(ch.title) + escapeText(ch.title) +
starred + starred +
lockMark +
"</span></span></button>" "</span></span></button>"
); );
} }
@ -1570,6 +1114,27 @@
opts = opts || {}; opts = opts || {};
var chapters = (state.book && state.book.chapters) || []; var chapters = (state.book && state.book.chapters) || [];
if (idx < 0 || idx >= chapters.length) return; if (idx < 0 || idx >= chapters.length) return;
if (isChapterLocked(idx)) {
var wall = $("book-paywall");
if (wall) {
state.jumpLockUntil = Date.now() + (opts.lockMs || 520);
state.activeChapter = Math.max(0, freeChapterCount() - 1);
var wr = wall.getBoundingClientRect();
var wy =
(window.pageYOffset || document.documentElement.scrollTop || 0) +
wr.top -
topbarOffset();
scrollToY(Math.max(0, wy));
if (opts.update !== false) {
setTimeout(function () {
updateProgressUI();
}, 60);
}
} else if (!opts.silent) {
requestUnlock();
}
return;
}
var ch = chapters[idx]; var ch = chapters[idx];
var target = $("ch-" + ch.id); var target = $("ch-" + ch.id);
if (!target) return; if (!target) return;
@ -1708,15 +1273,20 @@
remainingMinutes() + remainingMinutes() +
'</span><span class="stat-l">余下</span></div>' + '</span><span class="stat-l">余下</span></div>' +
"</div>" + "</div>" +
'<span class="hero-tip">点左右翻页 · 点中间显隐顶栏</span>' + '<span class="hero-tip">' +
(canGateByReward() && !state.unlocked
? "试读前 " + freeChapterCount() + " 章 · 点左右翻页"
: "点左右翻页 · 点中间显隐顶栏") +
"</span>" +
"</div>" "</div>"
); );
for (var i = 0; i < chapters.length; i++) { var visibleEnd = hasFullAccess() ? chapters.length : freeChapterCount();
for (var i = 0; i < visibleEnd; i++) {
var ch = chapters[i]; var ch = chapters[i];
var mins = chapterMinutes(ch.content); var mins = chapterMinutes(ch.content);
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length]; var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var next = chapters[i + 1]; var next = i + 1 < visibleEnd ? chapters[i + 1] : null;
var nextEmoji = CHAPTER_EMOJIS[(i + 1) % CHAPTER_EMOJIS.length]; var nextEmoji = CHAPTER_EMOJIS[(i + 1) % CHAPTER_EMOJIS.length];
html.push('<section class="chapter-block" id="ch-' + ch.id + '" data-idx="' + i + '">'); html.push('<section class="chapter-block" id="ch-' + ch.id + '" data-idx="' + i + '">');
if (i > 0) { if (i > 0) {
@ -1768,17 +1338,21 @@
html.push("</section>"); html.push("</section>");
} }
html.push( if (!hasFullAccess()) {
'<div class="fin" id="book-fin">' + html.push(buildPaywallHtml());
'<span class="fin-emoji">✨</span>' + } else {
'<span class="fin-title">全书读完</span>' + html.push(
'<span class="fin-desc">数字游民 · 一人公司 · 慢慢翻完也很棒</span>' + '<div class="fin" id="book-fin">' +
'<div class="fin-actions">' + '<span class="fin-emoji">✨</span>' +
'<button type="button" class="fin-btn" data-fin="share">发读完证书</button>' + '<span class="fin-title">全书读完</span>' +
'<button type="button" class="fin-btn ghost" data-fin="restart">从头再读</button>' + '<span class="fin-desc">数字游民 · 一人公司 · 慢慢翻完也很棒</span>' +
'<button type="button" class="fin-btn ghost" data-fin="home">返回封面</button>' + '<div class="fin-actions">' +
"</div></div>" '<button type="button" class="fin-btn" data-fin="share">发读完证书</button>' +
); '<button type="button" class="fin-btn ghost" data-fin="restart">从头再读</button>' +
'<button type="button" class="fin-btn ghost" data-fin="home">返回封面</button>' +
"</div></div>"
);
}
if (el.paper) el.paper.innerHTML = html.join(""); if (el.paper) el.paper.innerHTML = html.join("");
renderToc(""); renderToc("");
@ -1790,6 +1364,11 @@
idx = state.progress.chapterIndex; idx = state.progress.chapterIndex;
} }
if (idx < 0) idx = 0; if (idx < 0) idx = 0;
if (isChapterLocked(idx)) {
idx = Math.max(0, freeChapterCount() - 1);
jumpToChapter(idx, { lockMs: 600 });
return;
}
state.activeChapter = idx; state.activeChapter = idx;
var pct = Number(state.progress.scrollPercent) || 0; var pct = Number(state.progress.scrollPercent) || 0;
if (pct > 2) { if (pct > 2) {
@ -1813,11 +1392,15 @@
typeof progress.chapterIndex === "number" typeof progress.chapterIndex === "number"
? progress.chapterIndex ? progress.chapterIndex
: findChapterIndex(progress.chapterId); : findChapterIndex(progress.chapterId);
if (idx >= 0) state.activeChapter = idx; if (idx >= 0) {
if (isChapterLocked(idx)) idx = Math.max(0, freeChapterCount() - 1);
state.activeChapter = idx;
}
} }
renderReader(true); renderReader(true);
refreshPrefSegs(); refreshPrefSegs();
syncActionLabels(); syncActionLabels();
syncCloseRetention();
startReadTimer(); startReadTimer();
}); });
} }
@ -1841,6 +1424,14 @@
var showComment = Bridge.canPostComment(state.buildVersion); var showComment = Bridge.canPostComment(state.buildVersion);
if (el.btnComment) setHidden(el.btnComment, !showComment); if (el.btnComment) setHidden(el.btnComment, !showComment);
if (el.btnCommentText) setHidden(el.btnCommentText, !showComment); if (el.btnCommentText) setHidden(el.btnCommentText, !showComment);
var showReward = canGateByReward();
if (el.btnReward) {
setHidden(el.btnReward, !showReward);
el.btnReward.textContent = state.unlocked ? "已解锁 · 再赞赏" : "赞赏解锁全书";
}
if (el.btnRewardHome) {
setHidden(el.btnRewardHome, !showReward || state.unlocked);
}
} }
function chapterExcerpt(ch, maxLen) { function chapterExcerpt(ch, maxLen) {
@ -2953,7 +2544,9 @@
el.homeCheckin = $("home-checkin"); el.homeCheckin = $("home-checkin");
el.homeJournal = $("home-journal"); el.homeJournal = $("home-journal");
el.homeWorks = $("home-works"); el.homeWorks = $("home-works");
el.btnRewardHome = $("home-reward");
el.btnStart = $("btn-start"); el.btnStart = $("btn-start");
el.btnReward = $("btn-reward");
el.btnToc = $("btn-toc"); el.btnToc = $("btn-toc");
el.btnTocTitle = $("btn-toc-title"); el.btnTocTitle = $("btn-toc-title");
el.btnSettings = $("btn-settings"); el.btnSettings = $("btn-settings");
@ -3106,6 +2699,10 @@
}); });
on(el.btnClearData, "click", clearLocalData); on(el.btnClearData, "click", clearLocalData);
on(el.btnBackHome, "click", goHome); on(el.btnBackHome, "click", goHome);
on(el.btnReward, "click", requestUnlock);
on(el.btnRewardHome, "click", function () {
requestUnlock();
});
on(el.tabChapters, "click", function () { on(el.tabChapters, "click", function () {
setDrawerTab("chapters"); setDrawerTab("chapters");
}); });
@ -3177,6 +2774,10 @@
goHome(); goHome();
return; return;
} }
if (node.getAttribute && node.getAttribute("data-unlock") === "reward") {
requestUnlock();
return;
}
if (node.classList && node.classList.contains("next-peek")) { if (node.classList && node.classList.contains("next-peek")) {
var idx = Number(node.getAttribute("data-next-idx") || 0); var idx = Number(node.getAttribute("data-next-idx") || 0);
jumpToChapter(idx); jumpToChapter(idx);
@ -3237,7 +2838,9 @@
node.tagName === "BUTTON" || node.tagName === "BUTTON" ||
node.tagName === "A" || node.tagName === "A" ||
(node.classList && (node.classList &&
(node.classList.contains("next-peek") || node.classList.contains("fin-btn"))) (node.classList.contains("next-peek") ||
node.classList.contains("fin-btn") ||
node.classList.contains("paywall-btn")))
) { ) {
return; return;
} }
@ -3274,6 +2877,7 @@
? snap.chapterIndex ? snap.chapterIndex
: findChapterIndex(snap.chapterId); : findChapterIndex(snap.chapterId);
if (idx < 0) idx = 0; if (idx < 0) idx = 0;
if (isChapterLocked(idx)) idx = Math.max(0, freeChapterCount() - 1);
state.activeChapter = idx; state.activeChapter = idx;
var pct = Number(snap.scrollPercent) || 0; var pct = Number(snap.scrollPercent) || 0;
getProgress(state.book.id).then(function (progress) { getProgress(state.book.id).then(function (progress) {
@ -3331,19 +2935,23 @@
loadStreak(), loadStreak(),
loadReadTime(), loadReadTime(),
loadWorks(), loadWorks(),
loadUnlock(),
Bridge.getLaunchOptions() Bridge.getLaunchOptions()
]); ]);
}) })
.then(function (tuple) { .then(function (tuple) {
state.prefs = tuple[0] || copyObj(DEFAULT_PREFS); state.prefs = tuple[0] || copyObj(DEFAULT_PREFS);
state.unlocked = !!tuple[7];
bind(); bind();
refreshStorageCap(); refreshStorageCap();
var snap = Bridge.readSnapshotInfo(tuple[7]); syncCloseRetention();
var snap = Bridge.readSnapshotInfo(tuple[8]);
if (snap && applySnapshot(snap)) { if (snap && applySnapshot(snap)) {
startReadTimer(); startReadTimer();
return; return;
} }
renderHome(); renderHome();
syncActionLabels();
}) })
.catch(function (err) { .catch(function (err) {
showBootError("启动错误: " + (err && err.message ? err.message : String(err))); showBootError("启动错误: " + (err && err.message ? err.message : String(err)));

View File

@ -736,6 +736,61 @@ button {
color: var(--r-text); color: var(--r-text);
} }
.paywall {
margin: 28px 0 40px;
padding: 22px 14px 18px;
text-align: center;
border-top: 1px dashed var(--r-border);
background: linear-gradient(180deg, transparent, rgba(245, 158, 11, 0.08));
border-radius: 0 0 16px 16px;
}
.paywall-emoji {
display: block;
font-size: 30px;
line-height: 1;
}
.paywall-title {
display: block;
margin-top: 8px;
font-size: 20px;
font-weight: 700;
color: var(--r-text);
}
.paywall-desc {
display: block;
margin: 6px auto 0;
max-width: 16em;
font-size: 13px;
line-height: 1.45;
color: var(--r-muted);
}
.paywall-btn {
margin-top: 16px;
min-height: 44px;
min-width: 160px;
background: linear-gradient(135deg, #f59e0b, #d97706);
}
.paywall-hint {
display: block;
margin-top: 10px;
font-size: 12px;
color: var(--r-muted);
}
.drawer-item.locked .drawer-name {
opacity: 0.72;
}
.home-xhs-reward {
border-color: rgba(245, 158, 11, 0.45);
color: #f59e0b;
}
.md-body { .md-body {
font-size: 16px; font-size: 16px;
line-height: 1.7; line-height: 1.7;

View File

@ -39,6 +39,7 @@
<button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button> <button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button>
<button type="button" class="home-xhs-btn" id="home-journal">写日记</button> <button type="button" class="home-xhs-btn" id="home-journal">写日记</button>
<button type="button" class="home-xhs-btn" id="home-works">我的作品</button> <button type="button" class="home-xhs-btn" id="home-works">我的作品</button>
<button type="button" class="home-xhs-btn home-xhs-reward is-hidden" id="home-reward">赞赏解锁</button>
</div> </div>
<p class="home-time" id="home-time"></p> <p class="home-time" id="home-time"></p>
</div> </div>
@ -125,6 +126,7 @@
<p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p> <p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p>
<p class="rs-section">小红书</p> <p class="rs-section">小红书</p>
<div class="rs-actions"> <div class="rs-actions">
<button type="button" class="rs-action is-hidden" id="btn-reward">赞赏解锁全书</button>
<button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button> <button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button>
<button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button> <button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button>
<button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button> <button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button>

File diff suppressed because one or more lines are too long

View File

@ -8,6 +8,8 @@
var STORAGE_MIN = 9460; var STORAGE_MIN = 9460;
var COMMENT_MIN = 9490; var COMMENT_MIN = 9490;
var FILE_MIN = 9490; var FILE_MIN = 9490;
/** §3.18 / §3.19 赞赏 & 挽留:客户端 9.53.3+ → 9533 */
var REWARD_MIN = 9533;
function readBuildVersion(launchOptions) { function readBuildVersion(launchOptions) {
var env = launchOptions && launchOptions.miniToolEnv; var env = launchOptions && launchOptions.miniToolEnv;
@ -302,6 +304,50 @@
}); });
} }
function canRewardAuthor(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, REWARD_MIN) &&
mt &&
typeof mt.rewardAuthor === "function"
);
}
/** §3.18 — 成功仅表示赞赏流程结束,不含金额;取消/失败走 reject */
function rewardAuthor() {
return getBuildVersion().then(function (bv) {
if (!canRewardAuthor(bv)) {
return Promise.reject({ errMsg: "rewardAuthor:fail not available" });
}
return callApi("rewardAuthor");
});
}
/**
* §3.19 — 关闭容器时是否拉起赞赏挽留;默认 false,仅当前容器有效。
* 低于 9.53.3 时静默跳过,保证核心可读。
*/
function setCloseRetentionEnabled(enabled) {
var on = !!enabled;
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, REWARD_MIN) ||
!mt ||
typeof mt.setCloseRetentionEnabled !== "function"
) {
return false;
}
return callApi("setCloseRetentionEnabled", { enabled: on })
.then(function () {
return true;
})
.catch(function () {
return false;
});
});
}
function getStorageInfo() { function getStorageInfo() {
return getBuildVersion().then(function (buildVersion) { return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool(); var mt = getMiniTool();
@ -620,6 +666,9 @@
postNote: postNote, postNote: postNote,
canPostComment: canPostComment, canPostComment: canPostComment,
postComment: postComment, postComment: postComment,
canRewardAuthor: canRewardAuthor,
rewardAuthor: rewardAuthor,
setCloseRetentionEnabled: setCloseRetentionEnabled,
canUseFileSystem: canUseFileSystem, canUseFileSystem: canUseFileSystem,
getUserDataPath: getUserDataPath, getUserDataPath: getUserDataPath,
writeUtf8File: writeUtf8File, writeUtf8File: writeUtf8File,
@ -634,6 +683,7 @@
getMiniTool: getMiniTool, getMiniTool: getMiniTool,
STORAGE_MIN: STORAGE_MIN, STORAGE_MIN: STORAGE_MIN,
COMMENT_MIN: COMMENT_MIN, COMMENT_MIN: COMMENT_MIN,
FILE_MIN: FILE_MIN FILE_MIN: FILE_MIN,
REWARD_MIN: REWARD_MIN
}; };
})(window); })(window);

File diff suppressed because one or more lines are too long

View File

@ -18,27 +18,43 @@
"tabLabel": "小册" "tabLabel": "小册"
}, },
"community": { "community": {
"enabled": true, "enabled": false,
"title": "旅居社群", "title": "旅居社群",
"tabLabel": "社群" "tabLabel": "社群",
"note": "默认隐藏;后台可开"
}, },
"social": { "social": {
"enabled": true, "enabled": true,
"title": "游民社区", "title": "游民社区",
"tabLabel": "社区", "tabLabel": "社区",
"note": "门户 /social · 可拆独立域" "note": "国际 /social · 勿与中文 Hub 混用"
},
"hub": {
"enabled": true,
"title": "游民社区",
"tabLabel": "社区",
"note": "中文门户 /portal → /hub/home"
},
"hubBlog": {
"enabled": false,
"title": "Hub Blog",
"tabLabel": "Hub Blog",
"note": "/hub/blog"
}, },
"destinations": { "destinations": {
"enabled": true, "enabled": false,
"title": "目的地" "title": "目的地",
"note": "默认隐藏"
}, },
"meetups": { "meetups": {
"enabled": true, "enabled": false,
"title": "活动" "title": "活动",
"note": "默认隐藏"
}, },
"vip": { "vip": {
"enabled": true, "enabled": false,
"title": "会员中心" "title": "会员中心",
"note": "deep link only"
}, },
"game": { "game": {
"enabled": false, "enabled": false,

View File

@ -52,3 +52,12 @@ packages/sdk/tools.json
| GET | `/api/public/v1/nav/links` | listNavLinks | | GET | `/api/public/v1/nav/links` | listNavLinks |
Social 读接口优先反代 `SOCIAL_API_URL`,失败回落本地种子(离线兜底)。 Social 读接口优先反代 `SOCIAL_API_URL`,失败回落本地种子(离线兜底)。
## SDK / MCP 请求行为
SDK 默认请求超时为 15 秒,可通过 `createNomadroClient({ timeoutMs })` 调整;MCP 同为 15 秒。
网络失败、超时和 HTTP 错误均不自动重放写请求。成功响应必须是 JSON 对象,HTML、`null`、数组等异常响应会抛出错误。
SDK HTTP 错误保留 `status` 和 `data`,便于调用方区分权限、参数和上游故障。
`callTool` 直接读取 `packages/sdk/tools.json`,支持解构后调用。
本地回归:`pnpm test:platform`。测试使用模拟请求,不连接生产服务。

View File

@ -47,6 +47,8 @@ const aliases = {
}; };
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// Allow an isolated local audit without replacing another dev/build output.
distDir: process.env.NOMADRO_NEXT_DIST_DIR || ".next",
poweredByHeader: false, poweredByHeader: false,
compress: true, compress: true,
experimental: { experimental: {

View File

@ -32,6 +32,9 @@
"start": "next start", "start": "next start",
"lint": "eslint", "lint": "eslint",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test:platform": "node --test tests/platform.test.cjs",
"typecheck:all": "pnpm typecheck && pnpm --filter @nomadro/admin exec tsc --noEmit && pnpm --filter @nomadro/admin-com exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-h5 exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-weapp exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-tt exec tsc --noEmit && pnpm --dir apps/hackrobot/vip exec tsc --noEmit",
"test:local": "pnpm test:platform && pnpm --filter @nomadro/miniprogram-weapp test:runtime && pnpm --filter @nomadro/miniprogram-weapp test:social && python -m pytest apps/api/tests -q && python scripts/test_hub_boundaries.py && node scripts/test-hub-config.cjs && python scripts/lane_guard.py",
"guard:lanes": "python scripts/lane_guard.py", "guard:lanes": "python scripts/lane_guard.py",
"guard:lanes:update": "python scripts/lane_guard.py --update-baseline", "guard:lanes:update": "python scripts/lane_guard.py --update-baseline",
"clean": "node scripts/clean-artifacts.mjs", "clean": "node scripts/clean-artifacts.mjs",
@ -88,17 +91,17 @@
"markdown-it": "^15.0.3", "markdown-it": "^15.0.3",
"marked": "^17.0.4", "marked": "^17.0.4",
"nanoid": "^6.0.2", "nanoid": "^6.0.2",
"next": "16.1.6", "next": "16.4.6",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"photoswipe": "^5.4.4", "photoswipe": "^5.4.4",
"pocketbase": "^0.26.8", "pocketbase": "^0.26.8",
"posthog-js": "^1.447.3", "posthog-js": "^1.447.3",
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"qrcode.react": "^4.2.0", "qrcode.react": "^4.2.0",
"react": "19.2.3", "react": "19.2.9",
"react-beautiful-dnd": "^13.1.1", "react-beautiful-dnd": "^13.1.1",
"react-datepicker": "^9.1.0", "react-datepicker": "^9.1.0",
"react-dom": "19.2.3", "react-dom": "19.2.9",
"react-dropzone": "^20.1.4", "react-dropzone": "^20.1.4",
"react-hot-keys": "^3.0.0", "react-hot-keys": "^3.0.0",
"react-hot-toast": "^2.6.1", "react-hot-toast": "^2.6.1",
@ -135,15 +138,21 @@
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/three": "^0.183.1", "@types/three": "^0.183.1",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.1.6", "eslint-config-next": "16.4.6",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5" "typescript": "^5"
}, },
"packageManager": "pnpm@10.25.0+sha1.2cfb3ab644446565c127f58165cc76368c9c920b", "packageManager": "pnpm@10.25.0+sha1.2cfb3ab644446565c127f58165cc76368c9c920b",
"engines": { "engines": {
"node": ">=18" "node": ">=20.9.0"
}, },
"pnpm": { "pnpm": {
"overrides": {
"seroval@<1.6.10": "1.6.10",
"@remix-run/router@<1.23.3": "1.23.3",
"markdown-it@>=14.0.0 <14.3.3": "14.3.3",
"linkify-it@>=5.0.0 <5.0.2": "5.0.2"
},
"onlyBuiltDependencies": [ "onlyBuiltDependencies": [
"@parcel/watcher", "@parcel/watcher",
"@swc/core", "@swc/core",

View File

@ -38,7 +38,7 @@ function fillPath(template, args) {
}); });
} }
async function callTool(name, args = {}) { export async function callTool(name, args = {}, doFetch = fetch) {
const tool = TOOLS.find((t) => t.name === name); const tool = TOOLS.find((t) => t.name === name);
if (!tool) throw new Error(`unknown tool ${name}`); if (!tool) throw new Error(`unknown tool ${name}`);
const pathParams = [...tool.path.matchAll(/\{(\w+)\}/g)].map((m) => m[1]); const pathParams = [...tool.path.matchAll(/\{(\w+)\}/g)].map((m) => m[1]);
@ -63,11 +63,16 @@ async function callTool(name, args = {}) {
for (const p of pathParams) delete payload[p]; for (const p of pathParams) delete payload[p];
body = JSON.stringify(payload); body = JSON.stringify(payload);
} }
const res = await fetch(url, { method: tool.method, headers, body }); const res = await doFetch(url, {
const data = await res.json().catch(() => ({})); method: tool.method, headers, body, signal: AbortSignal.timeout(15_000),
});
const payload = await res.json().catch(() => undefined);
const data = payload && typeof payload === "object" && !Array.isArray(payload)
? payload : undefined;
if (!res.ok) { if (!res.ok) {
throw new Error(data.detail || data.error || `HTTP ${res.status}`); throw new Error(data?.detail || data?.error || `HTTP ${res.status}`);
} }
if (!data) throw new Error(`Invalid JSON object response (HTTP ${res.status})`);
return data; return data;
} }

View File

@ -68,7 +68,7 @@ export function resolvePayProvider(input: ResolvePayInput = {}): {
const region: PayRegion = const region: PayRegion =
input.region && input.region !== "auto" input.region && input.region !== "auto"
? input.region ? input.region
: input.audience === "intl" || input.isChinaUser === false : (input.audience ? input.audience === "intl" : input.isChinaUser === false)
? "overseas" ? "overseas"
: "cn"; : "cn";

View File

@ -14,6 +14,8 @@ export type NomadroClientOptions = {
/** Social guest id for write endpoints */ /** Social guest id for write endpoints */
guestId?: string; guestId?: string;
fetch?: typeof fetch; fetch?: typeof fetch;
/** Maximum duration of a request in milliseconds (default 15 seconds). */
timeoutMs?: number;
}; };
export type JsonMap = Record<string, unknown>; export type JsonMap = Record<string, unknown>;
@ -42,6 +44,10 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
"https://nomadro.com" "https://nomadro.com"
).replace(/\/$/, ""); ).replace(/\/$/, "");
const doFetch = opts.fetch || fetch; const doFetch = opts.fetch || fetch;
const timeoutMs = opts.timeoutMs ?? 15_000;
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new Error("timeoutMs must be a positive finite number");
}
async function request( async function request(
method: "GET" | "POST", method: "GET" | "POST",
@ -67,16 +73,20 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
headers, headers,
body: body ? JSON.stringify(body) : undefined, body: body ? JSON.stringify(body) : undefined,
cache: "no-store", cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
}); });
const data = (await res.json().catch(() => ({}))) as JsonMap; const payload: unknown = await res.json().catch(() => undefined);
const data = payload && typeof payload === "object" && !Array.isArray(payload)
? payload as JsonMap : undefined;
if (!res.ok) { if (!res.ok) {
const err = new Error( const err = new Error(
String(data.detail || data.error || `HTTP ${res.status}`), String(data?.detail || data?.error || `HTTP ${res.status}`),
) as Error & { status?: number; data?: JsonMap }; ) as Error & { status?: number; data?: JsonMap };
err.status = res.status; err.status = res.status;
err.data = data; err.data = data;
throw err; throw err;
} }
if (!data) throw new Error(`Invalid JSON object response (HTTP ${res.status})`);
return data; return data;
} }
@ -129,36 +139,14 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
/** Invoke any tool by name (MCP-friendly). */ /** Invoke any tool by name (MCP-friendly). */
async callTool(name: NomadroToolName, args: JsonMap = {}) { async callTool(name: NomadroToolName, args: JsonMap = {}) {
switch (name) { const tool = NOMADRO_TOOLS.find((item) => item.name === name);
case "health": if (!tool) throw new Error(`unknown tool ${name}`);
return this.health(); const path = fillPath(tool.path, args);
case "getMeta": const payload = { ...args };
return this.getMeta(); for (const match of tool.path.matchAll(/\{(\w+)\}/g)) delete payload[match[1]];
case "getConfig": return tool.method === "GET"
return this.getConfig(); ? request("GET", path, payload)
case "listMapCities": : request("POST", path, undefined, payload);
return this.listMapCities(args as never);
case "searchCities":
return this.searchCities(args as never);
case "listMeetups":
return this.listMeetups(args as never);
case "openMeetup":
return this.openMeetup(args as never);
case "listGigs":
return this.listGigs(args as never);
case "applyGig":
return this.applyGig(args as never);
case "joinSocial":
return this.joinSocial(args as never);
case "checkVip":
return this.checkVip(args as never);
case "listNavLinks":
return this.listNavLinks(args as never);
case "listSocialRoutes":
return this.listSocialRoutes();
default:
throw new Error(`unknown tool ${name}`);
}
}, },
}; };
} }

3180
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 775 B

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -20,11 +20,22 @@ ADMIN = '/www/wwwroot/admin.nomadro.com'
API_FILES = [ API_FILES = [
'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py', 'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py',
'routers/social_ugc_admin.py', 'routers/google_admin.py', 'routers/social_blog_admin.py', 'routers/social_ugc_admin.py', 'routers/google_admin.py', 'routers/social_blog_admin.py',
'routers/hub_ugc_admin.py', 'routers/hub_locale_geo_admin.py', 'routers/hub_blog_admin.py',
'services/weapp_switches.py', 'services/config_live.py', 'services/google_link.py', 'services/weapp_switches.py', 'services/config_live.py', 'services/google_link.py',
'services/google_oauth.py', 'services/social_blog_ops.py', 'services/google_oauth.py', 'services/social_blog_ops.py',
'services/hub_ugc.py', 'services/hub_experience.py', 'services/hub_locale_geo.py',
'services/hub_blog_ops.py', 'services/hub_ops.py', 'services/hub_join_config.py',
'services/ntfy.py', 'services/track.py', 'services/social_ugc.py', 'services/ntfy.py', 'services/track.py', 'services/social_ugc.py',
] ]
SOCIAL_FILES = ['pb_data.py', 'store.py', 'face_check.py', 'routers/api.py', 's3_upload.py'] SOCIAL_FILES = ['pb_data.py', 'store.py', 'face_check.py', 'routers/api.py', 's3_upload.py']
# Full hub_svc tree for nomadro-hub + nomadmini-api (/api/admin/hub needs config/security_denylist/…)
HUB_FILES = [
'pb_data.py', 'store.py', 'face_check.py', 'config.py', 's3_upload.py', 'community_board.py',
'security_denylist.py', 'realtime.py', 'live.py', 'remote_flags.py', 'trial_gate.py',
'onboarding.py', 'notify_bridge.py', 'im.py', 'contract.py',
'geo_pb.py', 'geo_cities.py', 'geo_store.py', 'geo_h3.py', 'photon.py',
'__init__.py', 'routers/__init__.py', 'routers/api.py', 'routers/geo.py',
]
SOURCE_FILES = [ SOURCE_FILES = [
'next.config.ts', 'src/proxy.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts', 'next.config.ts', 'src/proxy.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts',
'src/lib/ntfy.ts', 'src/lib/ntfy-rich.ts', 'src/lib/feedback-identity.ts', 'src/lib/ntfy.ts', 'src/lib/ntfy-rich.ts', 'src/lib/feedback-identity.ts',
@ -104,6 +115,16 @@ def main():
archive.addfile(entry, io.BytesIO(blob)) archive.addfile(entry, io.BytesIO(blob))
for relative in SOCIAL_FILES: for relative in SOCIAL_FILES:
archive.add(ROOT / 'apps/api/services/social_svc' / relative, arcname='social/' + relative) archive.add(ROOT / 'apps/api/services/social_svc' / relative, arcname='social/' + relative)
for relative in HUB_FILES:
path = ROOT / 'apps/api/services/hub_svc' / relative
if path.is_file():
archive.add(path, arcname='hub/' + relative)
hub_main = ROOT / 'apps/api/hub_main.py'
if hub_main.is_file():
archive.add(hub_main, arcname='hub_main.py')
schemas = ROOT / 'apps/api/services/nomadro_pb/schemas.py'
if schemas.is_file():
archive.add(schemas, arcname='nomadro_pb/schemas.py')
digest = hashlib.sha256(package.read_bytes()).hexdigest() digest = hashlib.sha256(package.read_bytes()).hexdigest()
print('release', RELEASE, 'build', build_id, 'packageMB', round(package.stat().st_size / 1024**2, 1)) print('release', RELEASE, 'build', build_id, 'packageMB', round(package.stat().st_size / 1024**2, 1))
sftp = client.open_sftp() sftp = client.open_sftp()
@ -114,6 +135,7 @@ def main():
[f'/opt/nomadmini/backend/app/{name}' for name in API_FILES] [f'/opt/nomadmini/backend/app/{name}' for name in API_FILES]
+ [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES] + [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES]
+ [f'/opt/nomadmini/backend/social_svc/{name}' for name in SOCIAL_FILES] + [f'/opt/nomadmini/backend/social_svc/{name}' for name in SOCIAL_FILES]
+ [f'{PORTAL}/apps/api/services/hub_svc/{name}' for name in HUB_FILES]
) )
target_args = ' '.join(targets) target_args = ' '.join(targets)
try: try:
@ -121,7 +143,11 @@ def main():
echo '{digest} /tmp/nomadro-upgrade-{RELEASE}.tgz' | sha256sum -c - echo '{digest} /tmp/nomadro-upgrade-{RELEASE}.tgz' | sha256sum -c -
mkdir -p {STAGE} {BACKUP} mkdir -p {STAGE} {BACKUP}
tar -xzf /tmp/nomadro-upgrade-{RELEASE}.tgz -C {STAGE} tar -xzf /tmp/nomadro-upgrade-{RELEASE}.tgz -C {STAGE}
tar -czf {BACKUP}/backend.tgz {target_args} EXISTING=""
for f in {target_args}; do
if [ -e "$f" ]; then EXISTING="$EXISTING $f"; fi
done
if [ -n "$EXISTING" ]; then tar -czf {BACKUP}/backend.tgz $EXISTING; else tar -czf {BACKUP}/backend.tgz --files-from /dev/null; fi
cp -a {ADMIN} {BACKUP}/admin cp -a {ADMIN} {BACKUP}/admin
cp /etc/nginx/sites-available/admin.nomadro.com.conf {BACKUP}/admin-nginx.conf cp /etc/nginx/sites-available/admin.nomadro.com.conf {BACKUP}/admin-nginx.conf
cp {PORTAL}/data/remote-config.json {BACKUP}/remote-config.json cp {PORTAL}/data/remote-config.json {BACKUP}/remote-config.json
@ -135,17 +161,67 @@ test -f {STAGE}/portal/.next/BUILD_ID
run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}') run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}')
# admin.nomadro.com → :8010 imports /opt/nomadmini/backend/social_svc (not portal tree) # admin.nomadro.com → :8010 imports /opt/nomadmini/backend/social_svc (not portal tree)
run(client, f'mkdir -p /opt/nomadmini/backend/social_svc/$(dirname {relative}) && cp {STAGE}/social/{relative} /opt/nomadmini/backend/social_svc/{relative}') run(client, f'mkdir -p /opt/nomadmini/backend/social_svc/$(dirname {relative}) && cp {STAGE}/social/{relative} /opt/nomadmini/backend/social_svc/{relative}')
for relative in HUB_FILES:
run(client, f'mkdir -p {PORTAL}/apps/api/services/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} {PORTAL}/apps/api/services/hub_svc/{relative}')
# admin.nomadro.com → :8010 also needs hub_svc for /api/admin/hub/*
run(client, f'mkdir -p /opt/nomadmini/backend/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} /opt/nomadmini/backend/hub_svc/{relative}')
run(client, f'test -f {STAGE}/hub_main.py && cp {STAGE}/hub_main.py {PORTAL}/apps/api/hub_main.py || true')
run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && cp {STAGE}/nomadro_pb/schemas.py {PORTAL}/apps/api/services/nomadro_pb/schemas.py || true')
run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && mkdir -p /opt/nomadmini/backend/nomadro_pb && cp {STAGE}/nomadro_pb/schemas.py /opt/nomadmini/backend/nomadro_pb/schemas.py || true')
# Source parity for the legacy API tree and repository service tree. # Source parity for the legacy API tree and repository service tree.
for relative in API_FILES: for relative in API_FILES:
source = ROOT / 'apps/api/services/ebook_svc' / relative source = ROOT / 'apps/api/services/ebook_svc' / relative
if not source.is_file():
print('skip missing api source', relative)
continue
destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}' destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}'
sftp = client.open_sftp() sftp = client.open_sftp()
try: sftp.put(str(source), destination) try: sftp.put(str(source), destination)
finally: sftp.close() finally: sftp.close()
# Ensure production main.py mounts hub admin routers (file-level API copy alone is not enough)
run(client, r'''set -eu
python3 - <<'PY'
from pathlib import Path
p = Path('/opt/nomadmini/backend/app/main.py')
text = p.read_text(encoding='utf-8')
if 'include_router(hub_ugc_admin.router)' in text:
print('main.py hub routers ok')
else:
needle = 'app.include_router(social_ugc_admin.router)\n'
if needle not in text:
raise SystemExit('main.py missing social_ugc anchor')
imports = (
'from app.routers import hub_ugc_admin # noqa: E402\n'
'from app.routers import hub_locale_geo_admin # noqa: E402\n'
'from app.routers import hub_blog_admin # noqa: E402\n'
)
includes = (
'app.include_router(hub_ugc_admin.router)\n'
'app.include_router(hub_locale_geo_admin.router)\n'
'app.include_router(hub_blog_admin.router)\n'
)
if 'hub_ugc_admin' not in text:
text = text.replace(
'from app.routers import social_ugc_admin # noqa: E402\n',
'from app.routers import social_ugc_admin # noqa: E402\n' + imports,
1,
)
text = text.replace(needle, needle + includes, 1)
p.write_text(text, encoding='utf-8')
print('main.py hub routers patched')
PY
mkdir -p /etc/systemd/system/nomadmini-api.service.d
cat >/etc/systemd/system/nomadmini-api.service.d/hub-path.conf <<'EOF'
[Service]
Environment=PYTHONPATH=/opt/nomadmini/backend
Environment=HUB_INTERNAL_URL=http://127.0.0.1:8025
EOF
systemctl daemon-reload
''')
run(client, '''set -eu run(client, '''set -eu
cd /opt/nomadmini/backend cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin; print("API imports OK")' .venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin,hub_ugc_admin; print("API imports OK", hub_ugc_admin.router.prefix)'
systemctl restart nomadmini-api nomadro-social systemctl restart nomadmini-api nomadro-social nomadro-hub
''') ''')
run(client, f'''set -eu run(client, f'''set -eu
cd {PORTAL} cd {PORTAL}
@ -162,13 +238,15 @@ done
curl --fail --silent --max-time 10 http://127.0.0.1:4003/api/health >/dev/null curl --fail --silent --max-time 10 http://127.0.0.1:4003/api/health >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/ >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/ >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/social/chat >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/social/chat >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/hub/home >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/notifications/settings >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/notifications/settings >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8010/health >/dev/null curl --fail --silent --max-time 10 http://127.0.0.1:8010/health >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8020/health >/dev/null curl --fail --silent --max-time 10 http://127.0.0.1:8020/health >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8025/health >/dev/null
cp -a {STAGE}/admin/assets/. {ADMIN}/assets/ cp -a {STAGE}/admin/assets/. {ADMIN}/assets/
cp {STAGE}/admin/index.html {ADMIN}/index.html.next cp {STAGE}/admin/index.html {ADMIN}/index.html.next
mv {ADMIN}/index.html.next {ADMIN}/index.html mv {ADMIN}/index.html.next {ADMIN}/index.html
systemctl is-active nomadro nomadmini-api nomadro-social nginx systemctl is-active nomadro nomadmini-api nomadro-social nomadro-hub nginx
''') ''')
report = {'release': RELEASE, 'buildId': build_id, 'backup': BACKUP, 'stage': STAGE, 'sha256': digest, 'deployed': True} report = {'release': RELEASE, 'buildId': build_id, 'backup': BACKUP, 'stage': STAGE, 'sha256': digest, 'deployed': True}
(ROOT / 'artifacts/platform-upgrade/deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8') (ROOT / 'artifacts/platform-upgrade/deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8')

View File

@ -5,41 +5,25 @@ export const runtime = "nodejs";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
/** /**
* Admin list of join leads — prefer local portal store (works without hub_svc deploy). * Read Hub leads from the authenticated Hub API; never use the Social portal file.
* Falls through to upstream admin API when local empty and upstream available.
*/ */
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
if (!(await requireAdminSession())) { const auth = req.headers.get("authorization") || "";
if (!auth.startsWith("Bearer ") && !(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } }); return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
} }
const qs = req.nextUrl.searchParams.toString(); 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 = ( const upstream = (
process.env.ADMIN_API_URL || process.env.ADMIN_API_URL ||
process.env.API_URL || process.env.API_URL ||
"" "https://api.nomadro.com"
).replace(/\/$/, ""); ).replace(/\/$/, "");
if (upstream) { if (upstream) {
try { try {
if (new URL(upstream).origin === req.nextUrl.origin) {
return NextResponse.json({ ok: false, error: "Hub 管理 API 上游不能指向门户自身" }, { status: 503 });
}
const cookie = req.headers.get("cookie") || ""; const cookie = req.headers.get("cookie") || "";
const auth = req.headers.get("authorization") || ""; const auth = req.headers.get("authorization") || "";
const res = await fetch( const res = await fetch(
@ -68,10 +52,10 @@ export async function GET(req: NextRequest) {
items: [], items: [],
error: e instanceof Error ? e.message : "upstream fail", error: e instanceof Error ? e.message : "upstream fail",
}, },
{ status: 200 }, { status: 503 },
); );
} }
} }
return NextResponse.json({ ok: true, total: 0, items: [] }); return NextResponse.json({ ok: false, error: "Hub 管理 API 未配置" }, { status: 503 });
} }

View File

@ -458,7 +458,13 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
successWrap.classList.add("show"); successWrap.classList.add("show");
var dest=returnUrl||"/"; var dest=returnUrl||"/";
var joinDest=/[?&]join=1(?:&|$)/.test(dest)||(function(){try{return localStorage.getItem("social-join-pending-profile")==="1"||sessionStorage.getItem("social-join-pending-profile")==="1"||document.cookie.indexOf("nomadro_social_join=1")>=0;}catch(e){return false;}})(); var joinDest=/[?&]join=1(?:&|$)/.test(dest)||(function(){try{return localStorage.getItem("social-join-pending-profile")==="1"||sessionStorage.getItem("social-join-pending-profile")==="1"||document.cookie.indexOf("nomadro_social_join=1")>=0;}catch(e){return false;}})();
if(joinDest){ var hubDest=false;
try{hubDest=new URL(dest,window.location.origin).pathname==="/hub/paid";}catch(e){}
if(hubDest){
var hubReturn=new URL(dest,window.location.origin);
hubReturn.searchParams.set("order_id",orderId);
dest=hubReturn.toString();
}else if(joinDest){
try{localStorage.setItem("social-join-pending-profile","1");sessionStorage.setItem("social-join-pending-profile","1");localStorage.setItem("social-join-paid","1");}catch(e){} try{localStorage.setItem("social-join-pending-profile","1");sessionStorage.setItem("social-join-pending-profile","1");localStorage.setItem("social-join-paid","1");}catch(e){}
dest="/paid?join=1&paid=1"; dest="/paid?join=1&paid=1";
} }

View File

@ -1,5 +1,7 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { listBlogPosts } from "@hub/lib/blog/catalog"; import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
@ -14,10 +16,8 @@ export async function OPTIONS(req: NextRequest) {
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const denied = assertPublicKey(req); const denied = assertPublicKey(req);
if (denied) return denied; if (denied) return denied;
const locale = (req.nextUrl.searchParams.get("locale") || "en").trim(); const { posts, enabled } = await publishedHubBlog();
const items = listBlogPosts({ const items = posts.map((p) => ({
locale: locale === "all" ? "all" : locale === "zh" ? "zh" : "en",
}).map((p) => ({
slug: p.slug, slug: p.slug,
title: p.title, title: p.title,
description: p.description, description: p.description,
@ -31,6 +31,7 @@ export async function GET(req: NextRequest) {
})); }));
return jsonOk(req, { return jsonOk(req, {
ok: true, ok: true,
enabled,
total: items.length, total: items.length,
items, items,
pagePath: "/hub/blog", pagePath: "/hub/blog",

View File

@ -1,10 +1,10 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities"; import { HUB_CITIES } from "@hub/lib/cities";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
optionsOk, optionsOk,
proxySocial,
} from "~/lib/public-api/http"; } from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) { export async function OPTIONS(req: NextRequest) {
@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
if (denied) return denied; if (denied) return denied;
const sp = req.nextUrl.searchParams; const sp = req.nextUrl.searchParams;
const qs = sp.toString(); const qs = sp.toString();
const remote = await proxySocial(`/map/cities${qs ? `?${qs}` : ""}`); const remote = await proxyHub(`/map/cities${qs ? `?${qs}` : ""}`);
if (remote.ok) { if (remote.ok) {
return jsonOk(req, { ok: true, source: "hub_api", ...(remote.data as object) }); return jsonOk(req, { ok: true, source: "hub_api", ...(remote.data as object) });
} }

View File

@ -1,10 +1,10 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities"; import { HUB_CITIES } from "@hub/lib/cities";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
optionsOk, optionsOk,
proxySocial,
} from "~/lib/public-api/http"; } from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) { export async function OPTIONS(req: NextRequest) {
@ -21,7 +21,7 @@ export async function GET(req: NextRequest) {
if (!q) { if (!q) {
return jsonOk(req, { ok: true, items: [], source: "empty_q" }); return jsonOk(req, { ok: true, items: [], source: "empty_q" });
} }
const remote = await proxySocial( const remote = await proxyHub(
`/cities/search?q=${encodeURIComponent(q)}&limit=${limit}&lang=${encodeURIComponent(lang)}`, `/cities/search?q=${encodeURIComponent(q)}&limit=${limit}&lang=${encodeURIComponent(lang)}`,
); );
if (remote.ok) { if (remote.ok) {

View File

@ -1,11 +1,11 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog"; import { hubPublicCatalog } from "@hub/lib/publicApi";
import { import {
assertPublicKey, assertPublicKey,
jsonErr, jsonErr,
jsonOk, jsonOk,
optionsOk, optionsOk,
proxySocial,
} from "~/lib/public-api/http"; } from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) { export async function OPTIONS(req: NextRequest) {
@ -19,15 +19,16 @@ export async function POST(
const denied = assertPublicKey(req); const denied = assertPublicKey(req);
if (denied) return denied; if (denied) return denied;
const { gigId } = await ctx.params; const { gigId } = await ctx.params;
const gig = PUBLIC_GIGS.find((g) => g.id === gigId); const { gigs } = await hubPublicCatalog();
const gig = gigs.find((g) => g.id === gigId);
if (!gig) return jsonErr(req, 404, "gig not found"); if (!gig) return jsonErr(req, 404, "gig not found");
const body = (await req.json().catch(() => ({}))) as { const body = (await req.json().catch(() => ({}))) as {
name?: string; name?: string;
contact?: string; contact?: string;
note?: string; note?: string;
}; };
const name = (body.name || "").trim(); const name = typeof body?.name === "string" ? body.name.trim() : "";
const contact = (body.contact || "").trim(); const contact = typeof body?.contact === "string" ? body.contact.trim() : "";
if (!name || !contact) { if (!name || !contact) {
return jsonErr(req, 400, "name and contact required", { return jsonErr(req, 400, "name and contact required", {
pagePath: "/hub/team", pagePath: "/hub/team",
@ -35,15 +36,15 @@ export async function POST(
}); });
} }
const guest = const guest =
req.headers.get("x-social-hub-hub-guest-id") || req.headers.get("x-hub-guest-id") ||
`public-${Buffer.from(contact).toString("base64url").slice(0, 24)}`; `public-${Buffer.from(contact).toString("base64url").slice(0, 24)}`;
const remote = await proxySocial(`/gigs/${encodeURIComponent(gigId)}/apply`, { const remote = await proxyHub(`/gigs/${encodeURIComponent(gigId)}/apply`, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"X-Hub-Guest-Id": guest, "X-Hub-Guest-Id": guest,
}, },
body: JSON.stringify({ name, contact, note: body.note || "" }), body: JSON.stringify({ name, contact, note: typeof body.note === "string" ? body.note : "" }),
}); });
if (remote.ok) { if (remote.ok) {
return jsonOk(req, { return jsonOk(req, {
@ -55,16 +56,7 @@ export async function POST(
linkText: "查看招聘", linkText: "查看招聘",
}); });
} }
return jsonOk(req, { return jsonErr(req, remote.status || 503, "申请尚未提交,请稍后重试", {
ok: true, pagePath: "/hub/team", linkText: "返回申请页", status: "not_submitted",
status: "queued_local",
source: "fallback",
gigId,
name,
contact,
note: body.note || "",
pagePath: "/hub/team",
linkText: "打开申请页重试",
detail: "upstream apply unavailable; return handoff",
}); });
} }

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog"; import { hubPublicCatalog } from "@hub/lib/publicApi";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
@ -17,7 +17,7 @@ export async function GET(req: NextRequest) {
const keyword = (req.nextUrl.searchParams.get("keyword") || "") const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim() .trim()
.toLowerCase(); .toLowerCase();
let gigs = [...PUBLIC_GIGS]; let { gigs } = await hubPublicCatalog();
if (kind && kind !== "all") { if (kind && kind !== "all") {
gigs = gigs.filter((g) => g.kind === kind); gigs = gigs.filter((g) => g.kind === kind);
} }

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { PUBLIC_JOIN } from "~/lib/public-api/catalog"; import { PUBLIC_HUB_JOIN } from "@hub/lib/publicApi";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
@ -16,9 +16,9 @@ export async function GET(req: NextRequest) {
const email = req.nextUrl.searchParams.get("email") || ""; const email = req.nextUrl.searchParams.get("email") || "";
return jsonOk(req, { return jsonOk(req, {
ok: true, ok: true,
...PUBLIC_JOIN, ...PUBLIC_HUB_JOIN,
email: email || null, email: email || null,
isMember: false, isMember: false,
note: "Paid social join is isolated from VIP (__vip__). Prefer handoff to pagePath.", note: "Hub 中文社区独立加入流程,请前往 pagePath 完成。",
}); });
} }

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog"; import { hubPublicCatalog } from "@hub/lib/publicApi";
import { import {
assertPublicKey, assertPublicKey,
jsonErr, jsonErr,
@ -18,7 +18,8 @@ export async function GET(
const denied = assertPublicKey(req); const denied = assertPublicKey(req);
if (denied) return denied; if (denied) return denied;
const { meetupId } = await ctx.params; const { meetupId } = await ctx.params;
const room = PUBLIC_MEETUPS.find((r) => r.id === meetupId); const { meetups } = await hubPublicCatalog();
const room = meetups.find((r) => r.id === meetupId);
if (!room) return jsonErr(req, 404, "meetup not found"); if (!room) return jsonErr(req, 404, "meetup not found");
const nick = req.nextUrl.searchParams.get("nick") || "游民"; const nick = req.nextUrl.searchParams.get("nick") || "游民";
return jsonOk(req, { return jsonOk(req, {

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog"; import { hubPublicCatalog } from "@hub/lib/publicApi";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
const keyword = (req.nextUrl.searchParams.get("keyword") || "") const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim() .trim()
.toLowerCase(); .toLowerCase();
let rooms = [...PUBLIC_MEETUPS]; let { meetups: rooms } = await hubPublicCatalog();
if (keyword) { if (keyword) {
rooms = rooms.filter( rooms = rooms.filter(
(r) => (r) =>

View File

@ -1,5 +1,8 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { HUB_SECTIONS } from "@hub/lib/catalog"; import { HUB_SECTIONS } from "@hub/lib/catalog";
import { hubPath } from "@hub/lib/hubPath";
import { isHubNavEnabled } from "@hub/lib/navFlags";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
import { import {
assertPublicKey, assertPublicKey,
jsonOk, jsonOk,
@ -13,9 +16,15 @@ export async function OPTIONS(req: NextRequest) {
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const denied = assertPublicKey(req); const denied = assertPublicKey(req);
if (denied) return denied; if (denied) return denied;
const config = await readRemoteConfigFile();
return jsonOk(req, { return jsonOk(req, {
ok: true, ok: true,
base: "/hub", base: "/hub",
sections: HUB_SECTIONS, sections: HUB_SECTIONS.map(section => ({
...section,
features: section.features
.filter(feature => isHubNavEnabled(config.copy.hubExperience?.navigation, feature.href))
.map(feature => ({ ...feature, href: hubPath(feature.href) })),
})).filter(section => section.features.length),
}); });
} }

View File

@ -6,6 +6,7 @@ import { getLocale } from "@ebook/lib/i18n/server";
import { BookRoutesProvider } from "@ebook/components/BookRoutes"; import { BookRoutesProvider } from "@ebook/components/BookRoutes";
import { ModuleBoundary } from "~/components/module-boundary"; import { ModuleBoundary } from "~/components/module-boundary";
import "@ebook/app/globals.css"; import "@ebook/app/globals.css";
import "@ebook/app/cover-hero.css";
export default async function BookLayout({ export default async function BookLayout({
children, children,

View File

@ -1,7 +1,11 @@
@import "tailwindcss"; /* Scan portal sources only; build outputs and audit artifacts are not classes. */
@import "tailwindcss" source("../");
@source "../../packages";
:root, :root,
.dark { .dark {
/* Chinese text remains readable offline without a Google Fonts download. */
--font-noto-sc: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
--background: #0a0e17; --background: #0a0e17;
--foreground: #f1f5f9; --foreground: #f1f5f9;
--hub-accent-1: #ff6b6b; --hub-accent-1: #ff6b6b;

View File

@ -634,6 +634,7 @@ html.light .hub-navbar.scrolled,
min-height: 100svh; min-height: 100svh;
gap: 0.65rem; gap: 0.65rem;
padding-top: calc(var(--hub-nav-height) + 0.65rem); padding-top: calc(var(--hub-nav-height) + 0.65rem);
padding-inline: max(1rem, env(safe-area-inset-left), env(safe-area-inset-right));
} }
.hub-hero-title { .hub-hero-title {
@ -648,26 +649,36 @@ html.light .hub-navbar.scrolled,
animation-duration: 7s; animation-duration: 7s;
} }
.hub-portal-grid { /* 三大模块:H5 恢复横向三卡(与原版一致) */
.hub-portal-grid,
.hub-portal-grid--row,
.hub-portal-grid--2x2 {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px; gap: 8px;
max-width: none;
} }
.hub-portal-card { .hub-portal-card {
padding: 14px 10px; flex-direction: column;
gap: 10px;
align-items: center; align-items: center;
justify-content: center;
gap: 8px;
min-height: 88px;
padding: 10px 8px;
text-align: center; text-align: center;
} }
.hub-portal-ico { .hub-portal-ico {
width: 32px; width: 34px;
height: 32px; height: 34px;
font-size: 0.95rem; font-size: 1.05rem;
border-radius: 10px;
} }
.hub-portal-name { .hub-portal-name {
font-size: 0.78rem; font-size: 0.86rem;
letter-spacing: -0.03em; letter-spacing: -0.02em;
white-space: nowrap;
} }
.hub-fc-1 { .hub-fc-1 {
@ -687,16 +698,13 @@ html.light .hub-navbar.scrolled,
} }
@media (max-width: 380px) { @media (max-width: 380px) {
.hub-portal-grid {
gap: 6px;
}
.hub-portal-card { .hub-portal-card {
padding: 12px 6px; padding: 12px 14px;
min-height: 48px;
} }
.hub-portal-name { .hub-portal-name {
font-size: 0.7rem; font-size: 0.92rem;
} }
} }

View File

@ -1,10 +1,12 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import BlogPostClient from "@hub/components/blog/BlogPostClient"; import BlogPostClient from "@hub/components/blog/BlogPostClient";
import { getBlogPost, listBlogPosts, listBlogSlugs } from "@hub/lib/blog/catalog"; import { getBlogPost, listBlogSlugs } from "@hub/lib/blog/catalog";
import { resolveBlogAdSense } from "@hub/lib/blog/adsense"; import { resolveBlogAdSense } from "@hub/lib/blog/adsense";
import { blogPostingJsonLd } from "@hub/lib/blog/jsonld"; import { blogPostingJsonLd } from "@hub/lib/blog/jsonld";
import { readRemoteConfigFile } from "~/lib/remote-config-store"; import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
type Props = { params: Promise<{ slug: string }> }; type Props = { params: Promise<{ slug: string }> };
@ -14,7 +16,8 @@ export async function generateStaticParams() {
export async function generateMetadata({ params }: Props): Promise<Metadata> { export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params; const { slug } = await params;
const post = getBlogPost(slug); const publication = await publishedHubBlog();
const post = publication.posts.some((p) => p.slug === slug) ? getBlogPost(slug) : null;
if (!post) return { title: "Not found" }; if (!post) return { title: "Not found" };
const url = `https://nomadro.com/hub/blog/${post.slug}`; const url = `https://nomadro.com/hub/blog/${post.slug}`;
return { return {
@ -43,15 +46,16 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
export default async function HubBlogPostPage({ params }: Props) { export default async function HubBlogPostPage({ params }: Props) {
const { slug } = await params; const { slug } = await params;
const post = getBlogPost(slug); const publication = await publishedHubBlog();
const post = publication.posts.some((p) => p.slug === slug) ? getBlogPost(slug) : null;
if (!post) notFound(); if (!post) notFound();
const related = listBlogPosts({ locale: post.locale }) const related = publication.posts
.filter((p) => p.slug !== post.slug) .filter((p) => p.slug !== post.slug)
.filter((p) => p.tags.some((t) => post.tags.includes(t))) .filter((p) => p.tags.some((t) => post.tags.includes(t)))
.slice(0, 3); .slice(0, 3);
const config = await readRemoteConfigFile().catch(() => null); const config = publication.config;
const adsense = resolveBlogAdSense(config); const adsense = resolveBlogAdSense(config);
const jsonLd = blogPostingJsonLd(post); const jsonLd = blogPostingJsonLd(post);
@ -59,7 +63,7 @@ export default async function HubBlogPostPage({ params }: Props) {
<> <>
<script <script
type="application/ld+json" type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
/> />
<BlogPostClient post={post} related={related} adsense={adsense} /> <BlogPostClient post={post} related={related} adsense={adsense} />
</> </>

View File

@ -3,16 +3,19 @@ import Link from "next/link";
import SiteShell from "@hub/components/SiteShell"; import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation"; import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath"; import { hubPath } from "@hub/lib/hubPath";
import HubInformationPage from "@hub/components/HubInformationPage";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "About the Nomad Blog | Nomadro", title: "关于游民社区 | Nomadro Hub",
description: description:
"Who publishes Nomadro’s nomad blog, what we write about, and how advertising may appear after approval.", "面向中文用户的独立游民社区,认识伙伴、远程工作、同城见面与共创。",
alternates: { canonical: "https://nomadro.com/hub/blog/about" }, alternates: { canonical: "https://nomadro.com/hub/blog/about" },
robots: { index: true, follow: true }, robots: { index: true, follow: true },
}; };
export default function HubBlogAboutPage() { export default function HubBlogAboutPage() {
if (isHubCnOnly()) return <HubInformationPage />;
return ( return (
<SiteShell title="About" editorial> <SiteShell title="About" editorial>
<article className="sblog-page sblog-article"> <article className="sblog-page sblog-article">

View File

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

View File

@ -1,17 +1,20 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import BlogListClient from "@hub/components/blog/BlogListClient"; import BlogListClient from "@hub/components/blog/BlogListClient";
import { listBlogPosts } from "@hub/lib/blog/catalog"; import { publishedHubBlog } from "@hub/lib/blog/published";
import { notFound } from "next/navigation";
export const dynamic = "force-dynamic";
import { blogListJsonLd } from "@hub/lib/blog/jsonld"; import { blogListJsonLd } from "@hub/lib/blog/jsonld";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Nomad Blog | Nomadro", title: "游民手记 | Nomadro Hub",
description: description:
"English field notes for digital nomads: cities, cafés, remote work, budgets, and meeting people on the road.", "面向中文游民的城市生活、远程办公与社区见面手记。",
alternates: { canonical: "https://nomadro.com/hub/blog" }, alternates: { canonical: "https://nomadro.com/hub/blog" },
openGraph: { openGraph: {
title: "Nomad Blog | Nomadro", title: "游民手记 | Nomadro Hub",
description: description:
"Practical guides for remote work and slow travel. Content-first — ads off until AdSense approval.", "从远程办公到同城见面,分享实用的游民生活经验。",
url: "https://nomadro.com/hub/blog", url: "https://nomadro.com/hub/blog",
type: "website", type: "website",
siteName: "Nomadro", siteName: "Nomadro",
@ -19,17 +22,18 @@ export const metadata: Metadata = {
robots: { index: true, follow: true }, robots: { index: true, follow: true },
}; };
export default function HubBlogPage() { export default async function HubBlogPage() {
const posts = listBlogPosts({ locale: "en", adsenseReadyOnly: false }); const { posts, enabled, heroLead } = await publishedHubBlog();
if (!enabled) notFound();
const jsonLd = blogListJsonLd(posts); const jsonLd = blogListJsonLd(posts);
return ( return (
<> <>
<script <script
type="application/ld+json" type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
/> />
<BlogListClient posts={posts} /> <BlogListClient posts={posts} heroLead={heroLead} />
</> </>
); );
} }

View File

@ -1,18 +1,22 @@
import { listBlogPosts } from "@hub/lib/blog/catalog"; import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
const cdata = (s: string) => s.replace(/\]\]>/g, "]]]]><![CDATA[>");
const SITE = "https://nomadro.com"; const SITE = "https://nomadro.com";
export async function GET() { export async function GET() {
const posts = listBlogPosts({ locale: "en" }); const { posts, enabled } = await publishedHubBlog();
if (!enabled) return new Response(null, { status: 404 });
const items = posts const items = posts
.map( .map(
(p) => ` (p) => `
<item> <item>
<title><![CDATA[${p.title}]]></title> <title><![CDATA[${cdata(p.title)}]]></title>
<link>${SITE}/hub/blog/${p.slug}</link> <link>${SITE}/hub/blog/${p.slug}</link>
<guid>${SITE}/hub/blog/${p.slug}</guid> <guid>${SITE}/hub/blog/${p.slug}</guid>
<pubDate>${new Date(p.date).toUTCString()}</pubDate> <pubDate>${new Date(p.date).toUTCString()}</pubDate>
<description><![CDATA[${p.description}]]></description> <description><![CDATA[${cdata(p.description)}]]></description>
</item>`, </item>`,
) )
.join(""); .join("");
@ -20,10 +24,10 @@ export async function GET() {
const xml = `<?xml version="1.0" encoding="UTF-8"?> const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"> <rss version="2.0">
<channel> <channel>
<title>Nomadro Nomad Blog</title> <title>Nomadro Hub 游民手记</title>
<link>${SITE}/hub/blog</link> <link>${SITE}/hub/blog</link>
<description>English field notes for digital nomads</description> <description>面向中文游民的远程办公与社区生活手记</description>
<language>en-us</language> <language>zh-CN</language>
${items} ${items}
</channel> </channel>
</rss>`; </rss>`;
@ -31,7 +35,7 @@ export async function GET() {
return new Response(xml, { return new Response(xml, {
headers: { headers: {
"Content-Type": "application/rss+xml; charset=utf-8", "Content-Type": "application/rss+xml; charset=utf-8",
"Cache-Control": "public, max-age=3600", "Cache-Control": "no-store",
}, },
}); });
} }

View File

@ -1,4 +1,4 @@
import CoffeeBookPage from "@coffee/components/CoffeeBookPage"; import CoffeeBookPage from "@hub/coffee/components/CoffeeBookPage";
export default async function Page({ export default async function Page({
params, params,
@ -6,5 +6,5 @@ export default async function Page({
params: Promise<{ username: string; slug: string }>; params: Promise<{ username: string; slug: string }>;
}) { }) {
const { username, slug } = await params; const { username, slug } = await params;
return <CoffeeBookPage username={username} slug={slug} />; return <CoffeeBookPage key={`${username}/${slug}`} username={username} slug={slug} />;
} }

View File

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

View File

@ -1,4 +1,4 @@
import CoffeeBookingDetail from "@coffee/components/CoffeeBookingDetail"; import CoffeeBookingDetail from "@hub/coffee/components/CoffeeBookingDetail";
export default async function Page({ export default async function Page({
params, params,

View File

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

View File

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

View File

@ -7,6 +7,7 @@ import "@hub/app/theme2.css";
import "@hub/app/theme3.css"; import "@hub/app/theme3.css";
import "@hub/app/theme4.css"; import "@hub/app/theme4.css";
import "@hub/app/home.css"; import "@hub/app/home.css";
import "@hub/app/cn-join.css";
import "@hub/app/experience.css"; import "@hub/app/experience.css";
import "@hub/app/interaction.css"; import "@hub/app/interaction.css";
import "@hub/app/studio.css"; import "@hub/app/studio.css";
@ -21,7 +22,7 @@ import HubExperience from "@hub/components/HubExperience";
export const metadata = { export const metadata = {
title: "Nomadro Hub · 游民社区", title: "Nomadro Hub · 游民社区",
description: "游民社区:聊天群、约会、语音厅、同城见面、招聘共创", description: "换一座城市,不必重新孤独。加群,找到同频的人。",
}; };
export default function HubLayout({ export default function HubLayout({

View File

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

View File

@ -3,17 +3,20 @@ import Link from "next/link";
import SiteShell from "@hub/components/SiteShell"; import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation"; import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath"; import { hubPath } from "@hub/lib/hubPath";
import HubInformationPage from "@hub/components/HubInformationPage";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Privacy | Nomadro Social", title: "隐私说明 | Nomadro Hub",
description: description:
"How Nomadro handles data on /hub, cookies, analytics, and advertising (including Google AdSense when enabled).", "了解 Nomadro Hub 中文社区的数据处理、本机存储与隐私选择。",
alternates: { canonical: "https://nomadro.com/hub/privacy" }, alternates: { canonical: "https://nomadro.com/hub/privacy" },
robots: { index: true, follow: true }, robots: { index: true, follow: true },
}; };
/** AdSense reviewers look for a clear Privacy Policy with ads/cookies disclosure */ /** AdSense reviewers look for a clear Privacy Policy with ads/cookies disclosure */
export default function HubPrivacyPage() { export default function HubPrivacyPage() {
if (isHubCnOnly()) return <HubInformationPage privacy />;
return ( return (
<SiteShell title="Privacy" editorial> <SiteShell title="Privacy" editorial>
<article className="sblog-page sblog-article"> <article className="sblog-page sblog-article">

View File

@ -1,11 +1,13 @@
import type { MetadataRoute } from "next"; import type { MetadataRoute } from "next";
import { listBlogPosts } from "@hub/lib/blog/catalog"; import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
import { getPublicSiteUrl } from "~/lib/google/site"; import { getPublicSiteUrl } from "~/lib/google/site";
const SITE = getPublicSiteUrl(); const SITE = getPublicSiteUrl();
export default function sitemap(): MetadataRoute.Sitemap { export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = listBlogPosts({ locale: "all" }); const { posts, enabled } = await publishedHubBlog();
const staticRoutes: MetadataRoute.Sitemap = [ const staticRoutes: MetadataRoute.Sitemap = [
{ {
url: `${SITE}/hub/blog`, url: `${SITE}/hub/blog`,
@ -32,5 +34,5 @@ export default function sitemap(): MetadataRoute.Sitemap {
changeFrequency: "monthly" as const, changeFrequency: "monthly" as const,
priority: 0.7, priority: 0.7,
})); }));
return [...staticRoutes, ...postRoutes]; return [...staticRoutes.filter((route) => enabled || !route.url.includes("/blog")), ...postRoutes];
} }

View File

@ -1,6 +1,9 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import WorkAccessGate from "@work/components/WorkAccessGate"; import WorkAccessGate from "@work/components/WorkAccessGate";
import HubReservedModule from "@hub/components/HubReservedModule";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export default function WorkLayout({ children }: { children: ReactNode }) { export default function WorkLayout({ children }: { children: ReactNode }) {
if (isHubCnOnly()) return <HubReservedModule kind="work" />;
return <WorkAccessGate>{children}</WorkAccessGate>; return <WorkAccessGate>{children}</WorkAccessGate>;
} }

View File

@ -3,7 +3,6 @@ import "./hub.css";
import { type Metadata, type Viewport } from "next"; import { type Metadata, type Viewport } from "next";
import { Suspense } from "react"; import { Suspense } from "react";
import { Noto_Sans_SC } from "next/font/google";
import { outfit } from "~/lib/fonts"; import { outfit } from "~/lib/fonts";
import { LocaleProvider } from "~/components/locale-provider"; import { LocaleProvider } from "~/components/locale-provider";
import { import {
@ -118,20 +117,13 @@ export const metadata: Metadata = {
}, },
}; };
const notoSansSC = Noto_Sans_SC({
subsets: ["latin"],
weight: ["300", "400", "500", "700"],
variable: "--font-noto-sc",
display: "swap",
});
export default function RootLayout({ export default function RootLayout({
children, children,
}: Readonly<{ children: React.ReactNode }>) { }: Readonly<{ children: React.ReactNode }>) {
return ( return (
<html <html
lang="zh-CN" lang="zh-CN"
className={`${outfit.variable} ${notoSansSC.variable} dark`} className={`${outfit.variable} dark`}
suppressHydrationWarning suppressHydrationWarning
> >
<head> <head>

View File

@ -1,5 +1,10 @@
import "@navmini/styles/global.css"; import "@navmini/styles/global.css";
export default function NavLayout({ children }: { children: React.ReactNode }) { export default function NavLayout({ children }: { children: React.ReactNode }) {
return <div className="navmini-root">{children}</div>; /* 默认日间;客户端 App 按 navmini-theme 覆盖。勿写 html — 门户强制 dark */
return (
<div className="navmini-root" data-theme="light">
{children}
</div>
);
} }

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import Link from "next/link";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { hardNavClick } from "~/lib/hard-nav";
import { useRemoteConfig } from "~/lib/use-remote-config"; import { useRemoteConfig } from "~/lib/use-remote-config";
import type { NomadroRemoteConfig } from "~/lib/remote-config"; import type { NomadroRemoteConfig } from "~/lib/remote-config";
@ -46,8 +46,9 @@ export function ModuleGate({
<p style={{ margin: 0, color: "#94a3b8", maxWidth: 320, lineHeight: 1.5 }}> <p style={{ margin: 0, color: "#94a3b8", maxWidth: 320, lineHeight: 1.5 }}>
该内容暂未开放,稍后再来看看吧。 该内容暂未开放,稍后再来看看吧。
</p> </p>
<Link <a
href="/" href="/portal"
onClick={hardNavClick("/portal")}
style={{ style={{
marginTop: 8, marginTop: 8,
color: "#0a0e17", color: "#0a0e17",
@ -62,7 +63,7 @@ export function ModuleGate({
}} }}
> >
返回首页 返回首页
</Link> </a>
</div> </div>
); );
} }

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