diff --git a/apps/api/README.md b/apps/api/README.md index e331a7b..e7c90a2 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -1,5 +1,27 @@ # Nomadro 统一 API +## 2026-11-02:社区消息与报名兼容修复(未部署) + +仅修改 `social_svc/store.py` 与 `social_svc/routers/api.py`:聊天改为读取最近一批、按时间正序返回,同秒消息以 rowid 保持稳定顺序;消息可带 `clientId`、报名可带 `requestId`,由设备身份和频道/岗位限定作用域,重复请求复用同一记录与时间,不同载荷返回 409。旧客户端不传标识继续兼容。纯 SQLite 接口移入线程池,消息发布失败不影响已提交记录。 + +没有 schema 迁移、删除、历史重写或业务库同步;使用已有主键实现幂等。社区 SQLite 与会员/订单库隔离。`test_social_store.py` 7 项与 `test_social_api.py` 4 项均使用临时数据库并 mock 实时发布,验证最近 100 条消息、同秒排序、重试与冲突、旧请求兼容、资料隐私字段和设备隔离、旧表和记录保留。连同配置测试,18 项全部通过。 + +线上只读检查显示 `nomadro-social` 监听 8020、单进程运行且不支持热重载;`live.py` 的视频房间状态保存在进程内。为满足不影响现有业务的约束,本轮未执行直接重启、数据库同步或线上测试写入。发布须先处理活动视频房间的状态连续性,并保留旧版本与回滚路径;客户端可先构建验收,后端可选字段兼容现有请求。 + +## 2026-11-02:公开配置读取优化(未部署) + +`public_config_snapshot.py` 按文件修改时间、大小及 inode 复用 JSON 解析结果;文件变化立即重新读取。文件短暂缺失、写入未完成或 JSON 损坏时,保留同一路径最近一次有效快照;首次读取失败仍返回原有默认配置。路径变化不会复用旧路径数据。返回深拷贝防止调用方污染缓存,meta 遇到非法 version 返回 0,避免 500。 + +保持 `/api/config`、`/api/ebook/config` 及对应 `/meta` 的路由、响应结构、CORS 和 no-store 头兼容。此次改动只有文件读取和进程内缓存,没有数据库访问、迁移、配置写回或支付/订单/会员修改,尚未更新线上服务。 + +隔离验证(仅临时 JSON 文件,不启动业务应用、不连接生产): + +```bash +apps/api/.venv/Scripts/python.exe -m unittest discover -s apps/api/tests -v +``` + +七项回归覆盖缓存复用、文件替换即时生效、损坏/缺失兜底、路径隔离、读取过程中文件变化、接口兼容性与非法版本。 + 合并原三套后端为一个入口(路径兼容): | 模块 | 来源 | 路径前缀 | diff --git a/apps/api/services/ebook_svc/routers/public_config.py b/apps/api/services/ebook_svc/routers/public_config.py index 05e26c8..49ea878 100644 --- a/apps/api/services/ebook_svc/routers/public_config.py +++ b/apps/api/services/ebook_svc/routers/public_config.py @@ -6,40 +6,20 @@ """ from __future__ import annotations -import json from typing import Any from fastapi import APIRouter from fastapi.responses import JSONResponse from ebook_svc.services.tt_platform_config import resolve_config_file +from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot router = APIRouter(tags=["public-config"]) +_snapshot = PublicConfigSnapshot() def _read_full_config() -> dict[str, Any]: - path = resolve_config_file() - if not path.is_file(): - return { - "version": 1, - "updatedAt": "", - "modules": {}, - "flags": {}, - "copy": {}, - "platforms": {}, - } - try: - raw = json.loads(path.read_text(encoding="utf-8")) - return raw if isinstance(raw, dict) else {} - except Exception: - return { - "version": 1, - "updatedAt": "", - "modules": {}, - "flags": {}, - "copy": {}, - "platforms": {}, - } + return _snapshot.read(resolve_config_file()) @router.get("/api/config") @@ -60,10 +40,14 @@ async def public_remote_config() -> JSONResponse: @router.get("/api/ebook/config/meta") async def public_remote_config_meta() -> JSONResponse: config = _read_full_config() + try: + version = int(config.get("version") or 0) + except (TypeError, ValueError, OverflowError): + version = 0 return JSONResponse( content={ "ok": True, - "version": int(config.get("version") or 0), + "version": version, "updatedAt": str(config.get("updatedAt") or ""), }, headers={ diff --git a/apps/api/services/ebook_svc/services/public_config_snapshot.py b/apps/api/services/ebook_svc/services/public_config_snapshot.py new file mode 100644 index 0000000..38eccc4 --- /dev/null +++ b/apps/api/services/ebook_svc/services/public_config_snapshot.py @@ -0,0 +1,53 @@ +"""Read-only configuration snapshots. Never writes configuration or business data.""" +from __future__ import annotations + +import json +from copy import deepcopy +from pathlib import Path +from threading import RLock +from typing import Any + + +class PublicConfigSnapshot: + """Reuse parsed JSON until the file changes; retain a valid snapshot during writes.""" + + def __init__(self) -> None: + self._lock = RLock() + self._path: Path | None = None + self._signature: tuple[int, int, int] | None = None + self._config: dict[str, Any] | None = None + + @staticmethod + def _stat(path: Path) -> tuple[int, int, int]: + stat = path.stat() + return stat.st_mtime_ns, stat.st_size, stat.st_ino + + def read(self, path: Path) -> dict[str, Any]: + with self._lock: + if path != self._path: + self._path = path + self._signature = None + self._config = None + try: + signature = self._stat(path) + if signature != self._signature: + raw = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(raw, dict): + raise ValueError("Configuration must be an object") + # Do not cache an intermediate read while the file is changing. + if self._stat(path) != signature: + raise ValueError("Configuration changed during read") + self._config = raw + self._signature = signature + except (OSError, ValueError, UnicodeError): + pass + if self._config is not None: + return deepcopy(self._config) + return { + "version": 1, + "updatedAt": "", + "modules": {}, + "flags": {}, + "copy": {}, + "platforms": {}, + } diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index 0221ff9..9c499d3 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -3,6 +3,7 @@ from __future__ import annotations from fastapi import APIRouter, Header, HTTPException, Query from pydantic import BaseModel, Field +from starlette.concurrency import run_in_threadpool from social_svc import live, store from social_svc.config import SOCIAL_ENABLED @@ -28,6 +29,7 @@ def _guest( class MessageIn(BaseModel): author: str = Field(default="游民", max_length=48) text: str = Field(min_length=1, max_length=2000) + clientId: str | None = Field(default=None, min_length=1, max_length=80) class ReviewIn(BaseModel): @@ -57,6 +59,7 @@ class GigAppIn(BaseModel): name: str = Field(min_length=1, max_length=64) contact: str = Field(min_length=1, max_length=120) note: str = Field(default="", max_length=2000) + requestId: str | None = Field(default=None, min_length=1, max_length=80) @router.get("/health") @@ -81,7 +84,7 @@ async def realtime_token( @router.get("/channels/{channel_id}/messages") -async def get_messages(channel_id: str, limit: int = 100): +def get_messages(channel_id: str, limit: int = 100): store.init_db() return {"items": store.list_messages(channel_id, limit)} @@ -94,10 +97,15 @@ async def post_message( guest: str | None = Query(default=None), ): peer = _guest(x_social_guest_id, guest) - store.init_db() if not body.text.strip(): raise HTTPException(status_code=400, detail="empty text") - saved = store.add_message(channel_id, body.author, body.text, peer) + def persist(): + store.init_db() + return store.add_message(channel_id, body.author, body.text, peer, body.clientId) + try: + saved = await run_in_threadpool(persist) + except ValueError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc # 实时推送失败不影响落库成功 try: await publish_chat_message(channel_id, saved) @@ -107,13 +115,13 @@ async def post_message( @router.get("/cafes/{cafe_id}/reviews") -async def get_reviews(cafe_id: str, limit: int = 50): +def get_reviews(cafe_id: str, limit: int = 50): store.init_db() return {"items": store.list_reviews(cafe_id, limit)} @router.post("/cafes/{cafe_id}/reviews") -async def post_review( +def post_review( cafe_id: str, body: ReviewIn, x_social_guest_id: str | None = Header(default=None), @@ -131,14 +139,14 @@ async def post_review( @router.get("/roster/me") -async def get_my_roster(x_social_guest_id: str | None = Header(default=None)): +def get_my_roster(x_social_guest_id: str | None = Header(default=None)): guest = _guest(x_social_guest_id) store.init_db() return {"item": store.get_roster(guest)} @router.put("/roster/me") -async def put_my_roster( +def put_my_roster( body: RosterIn, x_social_guest_id: str | None = Header(default=None), ): @@ -148,7 +156,7 @@ async def put_my_roster( @router.post("/feedback") -async def post_feedback( +def post_feedback( body: FeedbackIn, x_social_guest_id: str | None = Header(default=None), ): @@ -158,14 +166,19 @@ async def post_feedback( @router.post("/gigs/{gig_id}/apply") -async def post_gig_apply( +def post_gig_apply( gig_id: str, body: GigAppIn, x_social_guest_id: str | None = Header(default=None), ): guest = _guest(x_social_guest_id) + if not body.name.strip() or not body.contact.strip(): + raise HTTPException(status_code=400, detail="请填写称呼和联系方式") store.init_db() - return store.add_gig_app(gig_id, body.name, body.contact, body.note, guest) + try: + return store.add_gig_app(gig_id, body.name, body.contact, body.note, guest, body.requestId) + except ValueError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc class LiveJoinIn(BaseModel): diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 728a015..b5597f3 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +import hashlib import sqlite3 import time import uuid @@ -112,7 +113,7 @@ def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]: SELECT id, channel_id, author, text, guest_id, created_at FROM messages WHERE channel_id = ? - ORDER BY created_at ASC + ORDER BY created_at DESC, rowid DESC LIMIT ? """, (channel_id, max(1, min(limit, 500))), @@ -126,13 +127,13 @@ def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]: "guestId": r["guest_id"], "at": r["created_at"], } - for r in rows + for r in reversed(rows) ] -def add_message(channel_id: str, author: str, text: str, guest_id: str) -> dict[str, Any]: +def add_message(channel_id: str, author: str, text: str, guest_id: str, client_id: str | None = None) -> dict[str, Any]: item = { - "id": _uid("msg"), + "id": ("msg_" + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]) if client_id else _uid("msg"), "channelId": channel_id, "author": (author or "游民").strip()[:48] or "游民", "text": text.strip()[:2000], @@ -142,11 +143,17 @@ def add_message(channel_id: str, author: str, text: str, guest_id: str) -> dict[ with db() as conn: conn.execute( """ - INSERT INTO messages(id, channel_id, author, text, guest_id, created_at) + INSERT OR IGNORE INTO messages(id, channel_id, author, text, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?) """, (item["id"], item["channelId"], item["author"], item["text"], guest_id, item["at"]), ) + row = conn.execute("SELECT * FROM messages WHERE id = ?", (item["id"],)).fetchone() + if row["text"] != item["text"] or row["author"] != item["author"]: + raise ValueError("同一请求标识不能用于不同消息") + item["at"] = row["created_at"] + if client_id: + item["clientId"] = client_id return item @@ -296,9 +303,9 @@ def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, return item -def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str) -> dict[str, Any]: +def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str, request_id: str | None = None) -> dict[str, Any]: item = { - "id": _uid("app"), + "id": ("app_" + hashlib.sha256(json.dumps([guest_id, gig_id, request_id]).encode()).hexdigest()[:32]) if request_id else _uid("app"), "gigId": gig_id, "name": name.strip()[:64], "contact": contact.strip()[:120], @@ -309,11 +316,15 @@ def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str) with db() as conn: conn.execute( """ - INSERT INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at) + INSERT OR IGNORE INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) """, (item["id"], item["gigId"], item["name"], item["contact"], item["note"], guest_id, item["at"]), ) + row = conn.execute("SELECT * FROM gig_apps WHERE id = ?", (item["id"],)).fetchone() + if (row["name"], row["contact"], row["note"]) != (item["name"], item["contact"], item["note"]): + raise ValueError("同一请求标识不能用于不同申请") + item["at"] = row["created_at"] return item diff --git a/apps/api/tests/test_public_config_snapshot.py b/apps/api/tests/test_public_config_snapshot.py new file mode 100644 index 0000000..3d78ce4 --- /dev/null +++ b/apps/api/tests/test_public_config_snapshot.py @@ -0,0 +1,99 @@ +"""Isolated tests: temporary JSON only, no app startup or database connections.""" +import json +import asyncio +import importlib.util +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch +from types import SimpleNamespace + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "services")) + +from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot + + +class PublicConfigSnapshotTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.path = Path(self.directory.name) / "config.json" + self.reader = PublicConfigSnapshot() + + def write(self, value): + self.path.write_text(json.dumps(value), encoding="utf-8") + + def test_unchanged_file_is_not_parsed_again(self): + self.write({"version": 10, "flags": {"payEnabled": False}}) + first = self.reader.read(self.path) + first["flags"]["payEnabled"] = True + with patch.object(Path, "read_text", side_effect=AssertionError("read again")): + self.assertFalse(self.reader.read(self.path)["flags"]["payEnabled"]) + + def test_update_visible_immediately(self): + self.write({"version": 1}) + self.assertEqual(self.reader.read(self.path)["version"], 1) + replacement = self.path.with_suffix(".new") + replacement.write_text('{"version": 222}', encoding="utf-8") + replacement.replace(self.path) + self.assertEqual(self.reader.read(self.path)["version"], 222) + + def test_partial_write_and_missing_file_keep_last_good_config(self): + self.write({"version": 9, "modules": {"vip": {"enabled": False}}}) + expected = self.reader.read(self.path) + for text in ('{"version":', '[]', '\ufffd'): + self.path.write_text(text, encoding="utf-8") + self.assertEqual(self.reader.read(self.path), expected) + self.path.unlink() + self.assertEqual(self.reader.read(self.path), expected) + self.write({"version": 123}) + self.assertEqual(self.reader.read(self.path)["version"], 123) + + def test_new_path_does_not_reuse_old_config(self): + self.write({"version": 99}) + self.reader.read(self.path) + empty = self.reader.read(self.path.with_name("missing.json")) + self.assertEqual(empty["version"], 1) + self.assertEqual(empty["modules"], {}) + + def test_changing_file_during_read_does_not_replace_snapshot(self): + self.write({"version": 9}) + self.reader.read(self.path) + self.write({"version": 100}) + with patch.object(self.reader, "_stat", side_effect=[(1, 2, 3), (4, 5, 6)]): + self.assertEqual(self.reader.read(self.path)["version"], 9) + + def load_router(self): + # Avoid importing settings/app startup: neither real databases nor live APIs. + target = Path(__file__).resolve().parents[1] / "services/ebook_svc/routers/public_config.py" + spec = importlib.util.spec_from_file_location("public_config_under_test", target) + module = importlib.util.module_from_spec(spec) + with patch.dict(sys.modules, { + "ebook_svc.services.tt_platform_config": SimpleNamespace(resolve_config_file=lambda: self.path), + }): + spec.loader.exec_module(module) + return module + + def test_public_response_preserves_envelope_headers_and_aliases(self): + config = {"version": 7, "updatedAt": "now", "flags": {"payEnabled": False}} + self.write(config) + router = self.load_router() + response = asyncio.run(router.public_remote_config()) + self.assertEqual(json.loads(response.body), {"ok": True, "source": "file", "config": config}) + self.assertIn("no-store", response.headers["cache-control"]) + self.assertEqual(response.headers["access-control-allow-origin"], "*") + self.assertEqual({route.path for route in router.router.routes}, { + "/api/config", "/api/ebook/config", "/api/config/meta", "/api/ebook/config/meta", + }) + + def test_meta_handles_malformed_version_without_server_error(self): + self.write({"version": {"unexpected": True}}) + router = self.load_router() + response = asyncio.run(router.public_remote_config_meta()) + self.assertEqual(response.status_code, 200) + self.assertEqual(json.loads(response.body)["version"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/api/tests/test_social_api.py b/apps/api/tests/test_social_api.py new file mode 100644 index 0000000..626e3bd --- /dev/null +++ b/apps/api/tests/test_social_api.py @@ -0,0 +1,64 @@ +"""HTTP compatibility tests against a temporary database and mocked realtime.""" +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import AsyncMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services')) +from fastapi import FastAPI +from fastapi.testclient import TestClient +from social_svc import store +from social_svc.routers.api import router + + +class SocialApiTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db') + override.start() + self.addCleanup(override.stop) + publish = patch('social_svc.routers.api.publish_chat_message', new_callable=AsyncMock) + publish.start() + self.addCleanup(publish.stop) + app = FastAPI() + app.include_router(router, prefix='/api/social/v1') + self.client = TestClient(app) + self.addCleanup(self.client.close) + self.headers = {'X-Social-Guest-Id': 'isolated-test'} + + def test_message_retry_conflict_and_legacy_payload(self): + url = '/api/social/v1/channels/general/messages' + body = {'author': 'Name', 'text': 'Hello', 'clientId': 'same'} + first = self.client.post(url, json=body, headers=self.headers) + self.assertEqual(first.status_code, 200) + self.assertEqual(self.client.post(url, json=body, headers=self.headers).json(), first.json()) + self.assertEqual(self.client.post(url, json={**body, 'text': 'Changed'}, headers=self.headers).status_code, 409) + self.assertEqual(self.client.post(url, json={'text': 'Legacy'}, headers=self.headers).status_code, 200) + self.assertEqual(len(self.client.get(url).json()['items']), 2) + + def test_whitespace_and_missing_identity_do_not_write_messages(self): + url = '/api/social/v1/channels/general/messages' + self.assertEqual(self.client.post(url, json={'text': ' '}, headers=self.headers).status_code, 400) + self.assertEqual(self.client.post(url, json={'text': 'Hello'}).status_code, 400) + + def test_application_retry_and_whitespace_validation(self): + url = '/api/social/v1/gigs/project/apply' + body = {'name': 'Name', 'contact': 'Contact', 'requestId': 'same'} + first = self.client.post(url, json=body, headers=self.headers) + self.assertEqual(first.status_code, 200) + self.assertEqual(self.client.post(url, json=body, headers=self.headers).json(), first.json()) + self.assertEqual(self.client.post(url, json={**body, 'contact': 'Changed'}, headers=self.headers).status_code, 409) + self.assertEqual(self.client.post(url, json={**body, 'name': ' '}, headers=self.headers).status_code, 400) + + def test_roster_round_trip_keeps_private_fields_and_guest_isolation(self): + url = '/api/social/v1/roster/me' + body = {'name': 'Name', 'phone': 'private-contact', 'linktree': 'https://example.invalid'} + self.assertEqual(self.client.put(url, json=body, headers=self.headers).status_code, 200) + self.assertEqual(self.client.get(url, headers=self.headers).json()['item']['phone'], 'private-contact') + self.assertIsNone(self.client.get(url, headers={'X-Social-Guest-Id': 'another-test'}).json()['item']) + + +if __name__ == '__main__': + unittest.main() diff --git a/apps/api/tests/test_social_store.py b/apps/api/tests/test_social_store.py new file mode 100644 index 0000000..4016d92 --- /dev/null +++ b/apps/api/tests/test_social_store.py @@ -0,0 +1,82 @@ +"""Social regressions use a temporary SQLite database; no production app startup.""" +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services')) +from social_svc import store + + +class SocialStoreTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db') + override.start() + self.addCleanup(override.stop) + store.init_db() + + def test_recent_history_is_chronological_even_with_equal_timestamps(self): + with patch.object(store, '_now', return_value='2026-11-02T00:00:00.000Z'): + for i in range(125): + store.add_message('lobby', 'Guest', str(i), 'guest') + self.assertEqual([m['text'] for m in store.list_messages('lobby')], [str(i) for i in range(25, 125)]) + self.assertEqual(store.list_messages('other'), []) + + def test_message_replay_is_idempotent_and_preserves_time(self): + with patch.object(store, '_now', return_value='first'): + first = store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1') + self.assertEqual(store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1'), first) + self.assertEqual(len(store.list_messages('lobby')), 1) + with self.assertRaises(ValueError): + store.add_message('lobby', 'Guest', 'different', 'guest', 'request1') + self.assertEqual(store.list_messages('lobby')[0]['text'], 'hello') + + def test_message_keys_are_scoped_to_guest_and_channel(self): + items = [store.add_message(channel, 'Guest', 'hello', guest, 'same') + for channel, guest in [('a', 'one'), ('a', 'two'), ('b', 'one')]] + self.assertEqual(len({item['id'] for item in items}), 3) + + def test_old_clients_without_keys_keep_working(self): + one = store.add_message('lobby', 'Guest', 'hello', 'guest') + two = store.add_message('lobby', 'Guest', 'hello', 'guest') + self.assertNotEqual(one['id'], two['id']) + self.assertNotIn('clientId', one) + + def test_gig_replay_and_payload_conflict(self): + first = store.add_gig_app('gig', 'Name', 'Contact', 'Note', 'guest', 'key') + self.assertEqual(store.add_gig_app('gig', 'Name', 'Contact', 'Note', 'guest', 'key'), first) + with self.assertRaises(ValueError): + store.add_gig_app('gig', 'Name', 'Changed', 'Note', 'guest', 'key') + second = store.add_gig_app('other', 'Name', 'Contact', 'Note', 'guest', 'key') + self.assertNotEqual(first['id'], second['id']) + with store.db() as conn: + self.assertEqual(conn.execute('SELECT COUNT(*) FROM gig_apps').fetchone()[0], 2) + + def test_roster_round_trip_isolated_by_guest(self): + profile = dict(name='Name', title='Designer', city='Dali', phone='private', + linktree='https://example.invalid', skills='Design', bio='Hello') + saved = store.upsert_roster('one', profile) + self.assertEqual(store.get_roster('one'), saved) + self.assertIsNone(store.get_roster('two')) + store.init_db() + self.assertEqual(store.get_roster('one'), saved) + + def test_existing_tables_and_rows_survive_reinitialization(self): + message = store.add_message('lobby', 'Guest', 'existing', 'guest') + review = store.add_review('cafe', 'Guest', 4, 'Good', '', 'guest') + with store.db() as conn: + before = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name")) + store.init_db() + store.add_message('lobby', 'Guest', 'new', 'guest', 'key') + with store.db() as conn: + after = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name")) + self.assertEqual([tuple(row) for row in before], [tuple(row) for row in after]) + self.assertEqual(store.list_messages('lobby')[0]['id'], message['id']) + self.assertEqual(store.list_reviews('cafe')[0]['id'], review['id']) + + +if __name__ == '__main__': + unittest.main() diff --git a/apps/miniprogram/h5/scripts/check-account-ux.py b/apps/miniprogram/h5/scripts/check-account-ux.py new file mode 100644 index 0000000..89b87f7 --- /dev/null +++ b/apps/miniprogram/h5/scripts/check-account-ux.py @@ -0,0 +1,97 @@ +"""Check built shared pages using mocked APIs only; no production network access. + +Serve h5/dist on localhost:10086 first. Requires Python Playwright + Chromium. +""" +from pathlib import Path +import json + +from playwright.sync_api import sync_playwright + +BASE = "http://127.0.0.1:10086" +OUT = Path(__file__).resolve().parents[1] / "tmp" / "account-ux" +OUT.mkdir(parents=True, exist_ok=True) + + +def run(): + results = [] + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + for width in (320, 390, 430): + context = browser.new_context(viewport={"width": width, "height": 844}, is_mobile=True) + errors = [] + state = {"offline": False, "favorites_error": True} + + def route_request(route): + url = route.request.url + if not url.startswith(BASE + "/"): + return route.abort() + if not any(prefix in url for prefix in ("/api/", "/ebook-api", "/community-api")): + return route.continue_() + payload = {} + status = 200 + if url.endswith("/api/config"): + payload = {"config": {"version": 99, "flags": {"offlineBadge": True}}} + elif url.endswith("/api/config/meta"): + payload = {"version": 99} + elif url.endswith("/auth/presence"): + payload = {"openid": "ux-test", "isVip": True} + status = 503 if state["offline"] else 200 + elif url.endswith("/auth/profile/stats"): + payload = {"favorites_count": 0, "destinations_explored": 3, "member_since": "2026-01", "nomad_level": "探索者"} + elif url.endswith("/auth/favorites/detail"): + payload = [] + status = 503 if state["favorites_error"] else 200 + elif "/config/stream" in url: + status = 503 + route.fulfill(status=status, content_type="application/json", body=json.dumps(payload)) + + context.route("**/*", route_request) + page = context.new_page() + page.on("pageerror", lambda error: errors.append(str(error))) + page.goto(BASE + "/#/pages/home/index") + toggle = page.locator(".hub-theme-toggle") + toggle.wait_for() + assert toggle.bounding_box()["height"] >= 44 + assert page.locator(".hub-portal-card").count() > 0 + toggle.click() + assert page.locator(".hub-root").get_attribute("data-theme") == "light" + page.wait_for_function("getComputedStyle(document.querySelector('.hub-root')).backgroundColor === 'rgb(248, 250, 252)'") + page.screenshot(path=str(OUT / f"home-light-{width}.png"), full_page=True) + + page.goto(BASE + "/#/pages/mine/index") + page.get_by_text("未登录", exact=True).wait_for() + assert page.locator(".profile-header .btn").bounding_box()["height"] >= 44 + page.evaluate("""() => { + localStorage.setItem('nomadro_token', JSON.stringify({data:'mock-token'})); + localStorage.setItem('nomadro_openid', JSON.stringify({data:'ux-test'})); + }""") + page.reload() + page.get_by_text("收藏暂未同步,请刷新重试", exact=True).wait_for() + assert page.get_by_text("探索目的地", exact=True).count() == 0 + page.screenshot(path=str(OUT / f"account-partial-{width}.png"), full_page=True) + + state["offline"] = True + page.get_by_text("刷新", exact=True).click() + page.get_by_text("同步失败,请检查网络后重试", exact=True).wait_for() + assert page.get_by_text("退出登录", exact=True).count() == 1 + assert page.evaluate("localStorage.getItem('nomadro_token')") is not None + + state["offline"] = False + state["favorites_error"] = False + page.get_by_text("重试同步", exact=True).click() + page.get_by_text("探索目的地", exact=True).wait_for() + assert page.locator(".profile-stats").evaluate("el => el.scrollWidth <= el.clientWidth") + assert page.evaluate("document.documentElement.scrollWidth <= innerWidth") + page.screenshot(path=str(OUT / f"account-restored-{width}.png"), full_page=True) + page.get_by_text("退出登录", exact=True).click() + page.get_by_text("未登录", exact=True).wait_for() + assert page.evaluate("localStorage.getItem('nomadro_token')") is None + assert not errors, errors + results.append({"width": width, "ok": True}) + context.close() + browser.close() + print(json.dumps(results)) + + +if __name__ == "__main__": + run() diff --git a/apps/miniprogram/h5/scripts/check-social-ux.py b/apps/miniprogram/h5/scripts/check-social-ux.py new file mode 100644 index 0000000..4539102 --- /dev/null +++ b/apps/miniprogram/h5/scripts/check-social-ux.py @@ -0,0 +1,157 @@ +"""Community browser regressions; external requests are mocked or blocked.""" +import json +from pathlib import Path +from playwright.sync_api import sync_playwright +BASE = 'http://127.0.0.1:10086' +OUT = Path(__file__).resolve().parents[1] / 'tmp' / 'social-ux' +OUT.mkdir(parents=True, exist_ok=True) + +def run(): + results = [] + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + for width in (320, 390, 430): + context = browser.new_context(viewport={'width': width, 'height': 844}, is_mobile=True) + errors, writes = [], [] + state = {'roster': None, 'fail_save': False, 'fail_send': True, 'messages': [], 'fail_apply': True, 'reviews': []} + def route_request(route): + request = route.request + url = request.url + if '/api/social/v1/' in url: + payload, status = {}, 200 + if '/realtime/token' in url: + payload = {'ok': True, 'enabled': False} + elif '/roster/me' in url: + if request.method == 'PUT': + writes.append(('roster', request.post_data_json)) + if state['fail_save']: status = 503 + else: state['roster'] = request.post_data_json + payload = state['roster'] or {} + else: payload = {'item': state['roster']} + elif '/messages' in url: + if request.method == 'POST': + body = request.post_data_json + writes.append(('message', body)) + if state['fail_send']: status = 503 + payload = {**body, 'id': 'msg_saved', 'channelId': 'general', 'guestId': request.headers.get('x-social-guest-id'), 'at': '2026-11-02T00:00:00.000Z'} + if status == 200: state['messages'] = [payload] + else: payload = {'items': state['messages']} + elif '/reviews' in url: + if request.method == 'POST': + payload = {**request.post_data_json, 'id': 'review_saved', 'at': '2026-11-02T00:00:00.000Z'} + state['reviews'] = [payload] + else: payload = {'items': state['reviews']} + elif '/apply' in url: + writes.append(('apply', request.post_data_json)) + payload = {'id': 'application_saved'} + if state['fail_apply']: status = 503 + return route.fulfill(status=status, content_type='application/json', body=json.dumps(payload)) + if not url.startswith(BASE + '/'): + return route.abort() + if '/api/' in url or '/ebook-api' in url: + payload = {} + if '/api/config' in url: + payload = {'config': {'version': 99, 'modules': {'social': {'enabled': True}}, 'flags': {'socialFollow': False}}} + elif '/social-join-status' in url: + payload = {'ok': True, 'isMember': False, 'enabled': False, 'priceFen': 4900} + return route.fulfill(status=200, content_type='application/json', body=json.dumps(payload)) + return route.continue_() + context.route('**/*', route_request) + page = context.new_page() + page.on('pageerror', lambda error: errors.append(str(error))) + routes = ['index', 'people/index', 'people/index?mode=cafe', 'people/profile/index?id=m01', 'date/index', 'team/index', 'roster/index', 'chat/index', 'meetup/index', 'meetup-live/index'] + for index, route in enumerate(routes): + page.goto(BASE + '/#/pages/social/' + route) + page.locator('.soc-taro-root').wait_for() + page.wait_for_timeout(250) + assert page.locator('.soc-taro-root').inner_text().strip(), route + assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), (width, route, 'overflow') + page.screenshot(path=str(OUT / f'{width}-{index}.png'), full_page=True) + if page.locator('.social-theme-control').count(): + page.locator('.social-theme-control').click() + page.wait_for_function("document.querySelector('.soc-taro-root').dataset.theme === 'light'") + page.wait_for_timeout(500) + if index == 1: + assert page.locator('.social-people-chip').first.evaluate("el => getComputedStyle(el).backgroundColor === 'rgb(255, 255, 255)'") + page.screenshot(path=str(OUT / f'{width}-{index}-light.png'), full_page=True) + page.locator('.social-theme-control').click() + page.goto(BASE + '/#/pages/social/people/index') + page.get_by_role('button', name='关注', exact=True).first.click() + page.reload() + page.get_by_role('button', name='取消关注', exact=True).first.wait_for() + page.locator('.social-search-row input').fill('no-such-person') + assert page.locator('.social-people-chip').count() == 0 + page.get_by_role('button', name='清空筛选', exact=True).click() + assert page.locator('.social-people-chip').count() > 0 + page.goto(BASE + '/#/pages/social/date/index') + page.locator('.social-date-act.like').click() + page.wait_for_timeout(350) + page.locator('.social-date-act.undo').click() + page.goto(BASE + '/#/pages/social/team/index') + page.get_by_role('button', name='我想参与 ↗', exact=True).first.click() + page.locator('.social-apply-sheet input').nth(0).fill('Applicant') + page.locator('.social-apply-sheet input').nth(1).fill('contact@example.invalid') + page.get_by_role('button', name='发送参与申请', exact=True).click() + page.get_by_role('button', name='重试提交', exact=True).wait_for() + state['fail_apply'] = False + page.get_by_role('button', name='重试提交', exact=True).click() + page.get_by_text('已表达兴趣', exact=True).wait_for() + apply_writes = [body for kind, body in writes if kind == 'apply'] + assert apply_writes[0]['requestId'] == apply_writes[1]['requestId'] + page.goto(BASE + '/#/pages/social/people/index?mode=cafe') + page.get_by_role('button', name='查看与分享评价', exact=True).first.click() + page.locator('.social-sheet-panel textarea').fill('Useful workspace') + page.get_by_role('button', name='发表评价', exact=True).click() + page.get_by_text('Useful workspace', exact=True).wait_for() + page.get_by_role('button', name='关闭评价', exact=True).click() + page.goto(BASE + '/#/pages/social/index') + page.get_by_role('tab', name='共创', exact=True).click() + page.locator('.social-ugc-card').first.click() + page.get_by_role('dialog').wait_for() + page.get_by_role('button', name='关闭介绍', exact=True).click() + page.get_by_role('button', name='社区故事', exact=False).click() + page.get_by_role('dialog', name='社区故事').wait_for() + page.locator('.connection-video-content header').click() + assert page.get_by_role('dialog', name='社区故事').is_visible() + page.get_by_role('dialog', name='社区故事').get_by_role('button', name='关闭', exact=True).click() + page.locator('.social-join-btn').count() # Joining must never send a mock payment order. + page.get_by_role('button', name='加入社区', exact=True).first.click() + page.get_by_role('dialog', name='加入社区').wait_for() + page.locator('.social-join-sheet-submit').wait_for() + assert page.locator('.social-join-sheet-submit').is_disabled() + page.get_by_role('dialog', name='加入社区').get_by_role('button', name='关闭', exact=True).click() + page.goto(BASE + '/#/pages/social/roster/index') + page.locator('#profile_name input').wait_for() + page.locator('#profile_name input').fill('Test Nomad') + page.locator('#profile_city input').fill('Dali') + state['fail_save'] = True + page.get_by_role('button', name='保存到社区', exact=True).click() + page.get_by_text('同步未完成,草稿已保留,可以稍后重试', exact=True).wait_for() + page.reload() + page.wait_for_timeout(400) + assert page.locator('#profile_name input').input_value() == 'Test Nomad' + state['fail_save'] = False + page.get_by_role('button', name='保存到社区', exact=True).click() + page.get_by_text('已同步到社区', exact=True).wait_for() + assert state['roster']['city'] == 'Dali' + page.goto(BASE + '/#/pages/social/chat/index') + page.locator('.im-composer input').fill('Hello from test') + page.get_by_role('button', name='发送消息', exact=True).click() + page.get_by_text('未送达 · 点重试', exact=True).wait_for() + state['fail_send'] = False + page.get_by_text('未送达 · 点重试', exact=True).click() + page.get_by_text('已送达', exact=True).wait_for() + message_writes = [body for kind, body in writes if kind == 'message'] + assert len(message_writes) == 2 + assert message_writes[0]['clientId'] == message_writes[1]['clientId'] + assert not errors, errors + results.append({'width': width, 'routes': len(routes), 'writes': len(writes), 'ok': True}) + context.close() + browser.close() + print(json.dumps(results)) + +if __name__ == '__main__': + run() + + + diff --git a/apps/miniprogram/h5/src/app.tsx b/apps/miniprogram/h5/src/app.tsx index 44ec1b1..4d534d2 100644 --- a/apps/miniprogram/h5/src/app.tsx +++ b/apps/miniprogram/h5/src/app.tsx @@ -20,8 +20,6 @@ function App({ children }: PropsWithChildren) { useLaunch(() => { trackAppLaunch() void loadRemoteConfig(true) - startRemoteConfigLiveSync() - startVipAccessLiveSync() if (process.env.TARO_ENV === 'h5') { applyH5Theme(getStoredH5Theme()) } diff --git a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts index 9016b33..acbfcb3 100644 --- a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts +++ b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts @@ -86,9 +86,26 @@ export type NomadroRemoteConfig = { joinGroupDouyinQr?: string /** 知识社群解锁文案 */ memoUnlockCta?: string + socialPages?: Record + socialVideoSources?: Record + socialCatalogs?: Partial> + socialHiddenSections?: string[] + [key: `social${string}`]: unknown } /** 导航分类/链接(后台 CRUD);离线用 links.json */ navContent?: NavContent + /** 社区运营内容;缺省使用包内目录。空数组可用于下架某类内容。 */ + socialContent?: { + copy?: Record + promoUrl?: string + hiddenSections?: string[] + roster?: unknown[] + gigs?: unknown[] + meetups?: unknown[] + cafes?: unknown[] + videos?: unknown[] + ebooks?: unknown[] + } /** 分端配置:weapp.vipContent 仅微信 VIP 落地页;tt 由抖音端读,此处透传不解析 */ platforms?: { weapp?: { diff --git a/apps/miniprogram/h5/src/data/socialSeed.ts b/apps/miniprogram/h5/src/data/socialSeed.ts index 0cad4e4..75052b7 100644 --- a/apps/miniprogram/h5/src/data/socialSeed.ts +++ b/apps/miniprogram/h5/src/data/socialSeed.ts @@ -34,7 +34,7 @@ export const SOCIAL_COPY = { socialWayTeam: '找搭子 · 共创', } as const -export type SocialLandingCopy = typeof SOCIAL_COPY +export type SocialLandingCopy = { -readonly [K in keyof typeof SOCIAL_COPY]: string } export const SOCIAL_DOCK = [ { path: '/pages/social/index', label: '首页', short: '首页', emoji: '🏠', match: 'exact' as const }, diff --git a/apps/miniprogram/h5/src/data/socialTypes.ts b/apps/miniprogram/h5/src/data/socialTypes.ts index 42ba058..782a6f4 100644 --- a/apps/miniprogram/h5/src/data/socialTypes.ts +++ b/apps/miniprogram/h5/src/data/socialTypes.ts @@ -51,6 +51,7 @@ export type SocialMeetup = { }; export type SocialVideo = { + url?: string; id: string; title: string; city: string; diff --git a/apps/miniprogram/h5/src/hooks/useSocialChat.ts b/apps/miniprogram/h5/src/hooks/useSocialChat.ts index a0e4cfe..9fd3556 100644 --- a/apps/miniprogram/h5/src/hooks/useSocialChat.ts +++ b/apps/miniprogram/h5/src/hooks/useSocialChat.ts @@ -1,209 +1,154 @@ -/** - * 群组聊天:HTTP 拉历史/发消息 + Centrifugo WebSocket 实时。 - * 无假消息;离线时本地队列可重试,UI 标明状态。 - */ +/** Community chat: persistent outbox, explicit retries, HTTP + WebSocket. */ import { useCallback, useEffect, useRef, useState } from 'react' -import Taro from '@tarojs/taro' -import { - getSocialGuestId, - socialApi, - type SocialChatMessage, -} from '@/services/socialApi' +import Taro, { useDidHide, useDidShow } from '@tarojs/taro' +import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatMessage } from '@/services/socialApi' import { connectChatRealtime } from '@/services/socialRealtime' +import { mergeChatMessages } from '@/services/socialChatState' +import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal' export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline' -const NICK_KEY = 'nick' - export function useSocialChat(channelId: string) { + const guest = getSocialGuestId() + const outboxKey = `outbox_${guest}_${channelId}` + const draftKey = `chat_draft_${channelId}` const [messages, setMessages] = useState([]) - const [draft, setDraft] = useState('') + const [draft, setDraft] = useState(() => readSocialLocal(draftKey, '')) const [nick, setNick] = useState(() => { - try { - return String(Taro.getStorageSync(NICK_KEY) || '游民') - } catch { - return '游民' - } + try { return String(Taro.getStorageSync('nick') || '游民') } catch { return '游民' } }) const [status, setStatus] = useState('connecting') const [sending, setSending] = useState(false) const lock = useRef(false) - const mounted = useRef(true) - const guest = getSocialGuestId() + const active = useRef(channelId) + const mounted = useRef(false) + const initializedKey = useRef('') + const visible = useRef(true) + const refreshRef = useRef<() => Promise>(async () => {}) + active.current = channelId - const mergeRemote = useCallback((items: SocialChatMessage[]) => { - setMessages((current) => { - const pendingMine = current.filter( - (m) => m.mine && (m.delivery === 'local' || m.delivery === 'pending'), - ) - const remote = items.map((item) => ({ - ...item, - mine: item.guestId === guest, - delivery: 'sent' as const, - })) - const ids = new Set(remote.map((m) => m.id)) - return [ - ...remote, - ...pendingMine.filter((m) => !ids.has(m.id)), - ].slice(-300) - }) - }, [guest]) + useDidHide(() => { visible.current = false }) + useDidShow(() => { visible.current = true; void refreshRef.current() }) + + useEffect(() => { + const timer = setTimeout(() => writeSocialLocal(draftKey, draft), 250) + return () => clearTimeout(timer) + }, [draft, draftKey]) + + useEffect(() => { + if (!mounted.current || initializedKey.current !== outboxKey) return + const pending = messages.filter((m) => m.mine && m.delivery !== 'sent').slice(-50) + .map((m) => ({ ...m, delivery: 'local' as const })) + writeSocialLocal(outboxKey, pending) + }, [messages, outboxKey]) useEffect(() => { mounted.current = true let cancelled = false - let stopWs: (() => void) | null = null + let stopWs: (() => void) | undefined let refreshing = false - + let realtime = false + let failures = 0 + let nextRefresh = 0 const refresh = async () => { - if (cancelled || refreshing) return + if (cancelled || refreshing || !visible.current) return refreshing = true try { - const res = await socialApi.listMessages(channelId) + const response = await socialApi.listMessages(channelId) if (cancelled) return - mergeRemote(res.items || []) - setStatus((s) => (s === 'live' ? 'live' : 'polling')) + if (!Array.isArray(response.items)) throw new Error('消息格式异常') + setMessages((current) => mergeChatMessages(current, response.items, guest)) + failures = 0 + nextRefresh = 0 + setStatus(realtime ? 'live' : 'polling') } catch { - if (!cancelled) setStatus((s) => (s === 'live' ? 'live' : 'offline')) - } finally { - refreshing = false - } + failures++ + nextRefresh = Date.now() + Math.min(60000, 8000 * 2 ** Math.min(failures, 3)) + if (!cancelled) setStatus(realtime ? 'live' : 'offline') + } finally { refreshing = false } } - - setMessages([]) + refreshRef.current = refresh + const local = readSocialLocal(outboxKey, []) + initializedKey.current = outboxKey + setMessages(Array.isArray(local) ? local.filter((m) => m.channelId === channelId && m.guestId === guest).map((m) => ({ ...m, delivery: 'local' as const })) : []) + setDraft(readSocialLocal(draftKey, '')) + setSending(false) + lock.current = false setStatus('connecting') void refresh() - - const poll = setInterval(() => void refresh(), 8000) - + const timer = setInterval(() => { + if (Date.now() >= nextRefresh) void refresh() + }, 8000) void connectChatRealtime(channelId, (item) => { if (cancelled) return - setMessages((current) => { - if (current.some((m) => m.id === item.id)) return current - return [ - ...current, - { - ...item, - mine: item.guestId === guest, - delivery: 'sent', - }, - ].slice(-300) - }) - setStatus('live') - }).then((conn) => { - if (cancelled) { - conn?.disconnect() - return - } - if (conn) { - stopWs = conn.disconnect - setStatus('live') - } else { - setStatus((s) => (s === 'offline' ? 'offline' : 'polling')) - } - }) - + setMessages((current) => mergeChatMessages(current, [item], guest)) + }, (connected) => { + realtime = connected + if (!cancelled) setStatus(connected ? 'live' : 'polling') + }).then((connection) => { + if (cancelled) connection?.disconnect() + else stopWs = connection?.disconnect + }).catch(() => { if (!cancelled) setStatus('polling') }) return () => { cancelled = true mounted.current = false - clearInterval(poll) + clearInterval(timer) stopWs?.() } - }, [channelId, guest, mergeRemote]) + }, [channelId, guest, outboxKey, draftKey]) + + const deliver = useCallback(async (item: SocialChatMessage) => { + if (lock.current) return false + lock.current = true + setSending(true) + setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'pending' as const } : m)) + try { + const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId) + if (!saved?.id) throw new Error('发送结果异常') + const pending = readSocialLocal(outboxKey, []) + if (Array.isArray(pending)) writeSocialLocal(outboxKey, pending.filter((message) => message.id !== item.id && (!item.clientId || message.clientId !== item.clientId))) + if (!mounted.current || active.current !== channelId) return true + setMessages((current) => mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest)) + return true + } catch { + if (!mounted.current || active.current !== channelId) return false + setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'local' as const } : m)) + setStatus('offline') + void Taro.showToast({ title: '消息已保留,点击重试发送', icon: 'none' }) + return false + } finally { + if (active.current === channelId) { + lock.current = false + if (mounted.current) setSending(false) + } + } + }, [channelId, guest, outboxKey]) const send = useCallback(async () => { const text = draft.trim() if (!text || text.length > 2000 || lock.current) return false - lock.current = true - setSending(true) - const author = nick.trim() || '游民' - const tempId = `local_${Date.now()}` - setMessages((current) => - [ - ...current, - { - id: tempId, - channelId, - author, - text, - at: new Date().toISOString(), - guestId: guest, - mine: true, - delivery: 'pending', - }, - ].slice(-300), - ) - setDraft('') - try { - Taro.setStorageSync(NICK_KEY, author) - const saved = await socialApi.sendMessage(channelId, author, text) - if (!mounted.current) return true - setMessages((current) => - [ - ...current.filter((m) => m.id !== tempId && m.id !== saved.id), - { - ...saved, - mine: true, - guestId: guest, - delivery: 'sent', - }, - ].slice(-300), - ) - return true - } catch { - if (!mounted.current) return false - setMessages((current) => - current.map((m) => - m.id === tempId ? { ...m, delivery: 'local' as const } : m, - ), - ) - setStatus('offline') - Taro.showToast({ title: '发送失败,已留在本地', icon: 'none' }) - return false - } finally { - lock.current = false - if (mounted.current) setSending(false) + const clientId = createSocialRequestId() + const item: SocialChatMessage = { + id: `local_${clientId}`, clientId, channelId, author: nick.trim().slice(0, 24) || '游民', + text, at: new Date().toISOString(), guestId: guest, mine: true, delivery: 'pending', } - }, [channelId, draft, guest, nick]) + // Save before clearing the input so navigating away cannot lose unsent text. + const existing = readSocialLocal(outboxKey, []) + if (!writeSocialLocal(outboxKey, [...(Array.isArray(existing) ? existing : []), { ...item, delivery: 'local' }].slice(-50))) { + void Taro.showToast({ title: '本地保存失败,请保留输入后重试', icon: 'none' }) + return false + } + setMessages((current) => [...current, item].slice(-300)) + setDraft('') + writeSocialLocal(draftKey, '') + try { Taro.setStorageSync('nick', item.author) } catch { /* optional */ } + return deliver(item) + }, [channelId, draft, draftKey, deliver, guest, nick, outboxKey]) - const retryLocal = useCallback( - async (id: string) => { - const item = messages.find((m) => m.id === id && m.delivery === 'local') - if (!item || lock.current) return - lock.current = true - setSending(true) - try { - const saved = await socialApi.sendMessage( - channelId, - item.author, - item.text, - ) - setMessages((current) => - [ - ...current.filter((m) => m.id !== id && m.id !== saved.id), - { ...saved, mine: true, guestId: guest, delivery: 'sent' }, - ].slice(-300), - ) - setStatus((s) => (s === 'offline' ? 'polling' : s)) - } catch { - Taro.showToast({ title: '仍失败,稍后重试', icon: 'none' }) - } finally { - lock.current = false - setSending(false) - } - }, - [channelId, guest, messages], - ) + const retryLocal = useCallback(async (id: string) => { + const item = messages.find((m) => m.id === id && m.delivery === 'local') + if (item) await deliver(item) + }, [deliver, messages]) - return { - messages, - draft, - setDraft, - nick, - setNick, - status, - sending, - send, - retryLocal, - } + return { messages, draft, setDraft, nick, setNick, status, sending, send, retryLocal, refresh: () => refreshRef.current() } } diff --git a/apps/miniprogram/h5/src/hooks/useSocialContent.ts b/apps/miniprogram/h5/src/hooks/useSocialContent.ts new file mode 100644 index 0000000..37db3c3 --- /dev/null +++ b/apps/miniprogram/h5/src/hooks/useSocialContent.ts @@ -0,0 +1,41 @@ +import { useEffect, useMemo, useState } from 'react' +import { getCachedRemoteConfig, subscribeRemoteConfig } from '@/services/remoteConfig' +import { DEFAULT_PROMO, MOCK_ROSTER, SEED_CAFES, SEED_EBOOKS, SEED_GIGS, SEED_MEETUPS, SEED_VIDEOS, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed' + +function catalog(value: unknown, fallback: T[], valid: (row: any) => boolean): T[] { + if (!Array.isArray(value)) return fallback + const seen = new Set() + const rows = value.filter((row) => { + if (!row || typeof row.id !== 'string' || !row.id || seen.has(row.id) || !valid(row)) return false + seen.add(row.id) + return true + }) + return value.length && !rows.length ? fallback : rows as T[] +} +const text = (row: any, keys: string[]) => keys.every((key) => typeof row[key] === 'string') +const tags = (row: any) => Array.isArray(row.tags) && row.tags.every((tag: unknown) => typeof tag === 'string') + +export function useSocialContent() { + const [config, setConfig] = useState(getCachedRemoteConfig) + useEffect(() => subscribeRemoteConfig((result) => setConfig(result.config)), []) + return useMemo(() => { + const source = { ...config.socialContent, ...config.copy.socialCatalogs } + const copy = { ...SOCIAL_COPY } as SocialLandingCopy + for (const key of Object.keys(copy) as (keyof SocialLandingCopy)[]) { + const value = config.copy[key] ?? source.copy?.[key] + if (typeof value === 'string') copy[key] = value + } + return { + copy, + pages: config.copy.socialPages || {}, + promoUrl: typeof config.copy.socialPromoUrl === 'string' ? config.copy.socialPromoUrl : typeof source.promoUrl === 'string' ? source.promoUrl : DEFAULT_PROMO, + hiddenSections: Array.isArray(config.copy.socialHiddenSections) ? config.copy.socialHiddenSections.filter((key) => typeof key === 'string') : (Array.isArray(source.hiddenSections) ? source.hiddenSections : []), + roster: catalog(source.roster, MOCK_ROSTER, (r) => text(r, ['name', 'title', 'city', 'bio', 'lookingFor', 'avatar']) && tags(r) && (!r.gallery || (Array.isArray(r.gallery) && r.gallery.every((url: unknown) => typeof url === 'string'))) && (!r.languages || (Array.isArray(r.languages) && r.languages.every((value: unknown) => typeof value === 'string')))), + gigs: catalog(source.gigs, SEED_GIGS, (r) => text(r, ['title', 'role', 'pay']) && tags(r)), + meetups: catalog(source.meetups, SEED_MEETUPS, (r) => text(r, ['title', 'city', 'date', 'time', 'mirotalkRoom', 'channelId'])), + cafes: catalog(source.cafes, SEED_CAFES, (r) => text(r, ['name', 'city', 'vibe']) && Number.isFinite(r.wifiMbps)), + videos: catalog(source.videos, SEED_VIDEOS, (r) => text(r, ['title', 'city', 'summary', 'coverEmoji']) && Number.isFinite(r.minutes)).map((video) => ({ ...video, url: config.copy.socialVideoSources?.[video.id] || video.url })), + ebooks: catalog(source.ebooks, SEED_EBOOKS, (r) => text(r, ['title', 'blurb']) && Number.isFinite(r.chapters)), + } + }, [config]) +} diff --git a/apps/miniprogram/h5/src/hooks/useSocialPage.ts b/apps/miniprogram/h5/src/hooks/useSocialPage.ts new file mode 100644 index 0000000..b53e27b --- /dev/null +++ b/apps/miniprogram/h5/src/hooks/useSocialPage.ts @@ -0,0 +1,16 @@ +import { useMemo, type CSSProperties } from 'react' +import { useNomadroTheme } from '@/utils/h5Theme' +import { safePx, useSafeAreaMetrics } from '@/utils/safeArea' +import '@/styles/social-next/ux.scss' + +export function useSocialPage() { + const theme = useNomadroTheme() + const safe = useSafeAreaMetrics() + const pageStyle = useMemo(() => ({ + '--safe-status-bar': safePx(safe.statusBarHeight), + '--safe-nav-bar': safePx(safe.navBarHeight), + '--safe-menu-pad': safePx(safe.menuRightPad), + '--safe-header': safePx(safe.headerHeight), + }) as CSSProperties, [safe.statusBarHeight, safe.navBarHeight, safe.menuRightPad, safe.headerHeight]) + return { theme, pageStyle } +} diff --git a/apps/miniprogram/h5/src/pages/home/index.scss b/apps/miniprogram/h5/src/pages/home/index.scss index baf76f5..09095c0 100644 --- a/apps/miniprogram/h5/src/pages/home/index.scss +++ b/apps/miniprogram/h5/src/pages/home/index.scss @@ -1,2 +1,64 @@ @use '../../styles/hub.scss'; @import '../../styles/weapp-parity.scss'; + +.hub-root .hub-theme-toggle, +.hub-root .hub-status-retry { + display: flex; + align-items: center; + justify-content: center; + min-width: 2.75rem; + min-height: 2.75rem; + margin: 0; + padding: 0 0.75rem; + border: var(--hub-border); + border-radius: 0.875rem; + background: var(--hub-bg-glass); + color: var(--hub-text); + font-size: 0.8125rem; + line-height: 1.4; + &::after { border: 0; } + &:active { opacity: 0.7; } +} + +.hub-root .hub-theme-toggle { font-size: 1.375rem; } + +.hub-home-lead, +.hub-offline-status, +.hub-empty-status { + order: 3; + width: 100%; + box-sizing: border-box; + color: var(--hub-muted); + font-size: 0.875rem; + text-align: center; + margin-top: 1rem; +} + +.hub-offline-status, +.hub-empty-status { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0.75rem; +} + +.hub-root .hub-portal-card:active { opacity: 0.75; } + +.hub-root[data-theme='light'] .hub-gradient-text { + color: #b45309 !important; + -webkit-text-fill-color: #b45309 !important; +} + +.hub-root[data-theme='light'] .hub-portal-card--main .hub-portal-name { + color: #0f766e; + background: none; + -webkit-text-fill-color: #0f766e; +} + +@media (prefers-reduced-motion: reduce) { + .hub-root .hub-shape, + .hub-root .hub-float-card, + .hub-root .hub-globe-css-dot, + .hub-root .hub-globe-css-path { animation: none !important; } +} diff --git a/apps/miniprogram/h5/src/pages/home/index.tsx b/apps/miniprogram/h5/src/pages/home/index.tsx index c3421c9..beccba1 100644 --- a/apps/miniprogram/h5/src/pages/home/index.tsx +++ b/apps/miniprogram/h5/src/pages/home/index.tsx @@ -3,7 +3,7 @@ * H5 真布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。 */ import { useEffect, useState, type CSSProperties, type ReactNode } from 'react' -import { View, Text } from '@tarojs/components' +import { View, Text, Button } from '@tarojs/components' import Taro, { useDidShow, usePageScroll } from '@tarojs/taro' import { getCachedRemoteConfig, @@ -12,7 +12,7 @@ import { subscribeRemoteConfig, } from '@/services/remoteConfig' import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults' -import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme' +import { applyH5Theme, toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme' import { goPage } from '@/utils/nav' import { usePageShare, markPageShare } from '@/utils/pageShare' import { safePx, useSafeAreaMetrics } from '@/utils/safeArea' @@ -167,10 +167,26 @@ function IndexPage() { const [config, setConfig] = useState(() => getCachedRemoteConfig()) const theme = useNomadroTheme() const [navScrolled, setNavScrolled] = useState(false) + const [offline, setOffline] = useState(false) + const [refreshing, setRefreshing] = useState(false) + + async function refreshConfig() { + if (refreshing) return + setRefreshing(true) + try { + const result = await loadRemoteConfig(true) + setConfig(result.config) + setOffline(result.fromOffline) + } finally { + setRefreshing(false) + } + } useEffect(() => { - const unsub = subscribeRemoteConfig((r) => setConfig(r.config)) - void loadRemoteConfig(true).then((r) => setConfig(r.config)) + const unsub = subscribeRemoteConfig((r) => { + setConfig(r.config) + setOffline(r.fromOffline) + }) applyH5Theme(theme) return unsub }, []) @@ -342,6 +358,13 @@ function IndexPage() { {brand} + {showQuickNav && isH5 && isDev ? ( openDevLink('admin')}> @@ -408,6 +431,17 @@ function IndexPage() { 自由生活 + {cfg.copy.homeLead ? {cfg.copy.homeLead} : null} + + {offline && cfg.flags.offlineBadge ? ( + + 当前显示本地内容 + + + ) : null} + {portals.map((portal) => ( ))} + {!portals.length ? ( + + 内容正在准备中 + + + ) : null} diff --git a/apps/miniprogram/h5/src/pages/mine/index.scss b/apps/miniprogram/h5/src/pages/mine/index.scss index d70267a..377e68b 100644 --- a/apps/miniprogram/h5/src/pages/mine/index.scss +++ b/apps/miniprogram/h5/src/pages/mine/index.scss @@ -1 +1,69 @@ -/* mine — shared theme */ +.mine-page { + --mine-bg: #0a0e17; + --mine-card: #111827; + --mine-text: #f1f5f9; + --mine-muted: #94a3b8; + --mine-border: rgba(148, 163, 184, 0.18); + min-height: 100vh; + background: var(--mine-bg); + color: var(--mine-text); +} + +.mine-page[data-theme='light'] { + --mine-bg: #f8fafc; + --mine-card: #fff; + --mine-text: #0f172a; + --mine-muted: #64748b; + --mine-border: rgba(15, 23, 42, 0.12); +} + +.mine-page .mine-container { + padding: 1.25rem 1rem calc(2rem + env(safe-area-inset-bottom)); + box-sizing: border-box; +} + +.mine-page .profile-header, +.mine-page .profile-stats, +.mine-page .mine-empty { + padding: 1.5rem; + margin-bottom: 1.25rem; + background: var(--mine-card); + border: 1rpx solid var(--mine-border); + border-radius: 1.25rem; + color: var(--mine-text); +} + +.mine-page .profile-header { align-items: center; gap: 0.5rem; text-align: center; } +.mine-page .profile-avatar { width: 4.5rem; height: 4.5rem; font-size: 2rem; margin-bottom: 0.75rem; } +.mine-page .profile-name { display: block; font-size: 1.25rem; font-weight: 600; } +.mine-page .profile-email, +.mine-page .profile-level { display: block; margin-top: 0.5rem; color: var(--mine-muted); font-size: 0.875rem; } +.mine-page .profile-stats { display: flex; flex-wrap: nowrap; justify-content: space-around; gap: 0.75rem; padding: 1.25rem 0.75rem; } +.mine-page .profile-stat { display: flex; flex: 1; min-width: 0; padding: 0; border: 0; background: transparent; flex-direction: column; align-items: center; gap: 0.375rem; font-size: 0.875rem; overflow-wrap: anywhere; } +.mine-page .profile-stat-n { font-size: 1.125rem; font-weight: 600; } +.mine-page .profile-stat-l { color: var(--mine-muted); } + +.mine-page .btn { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + min-height: 2.75rem; + padding: 0.625rem 1rem; + margin-top: 1rem; + border-radius: 0.875rem; + box-sizing: border-box; + font-size: 0.9375rem; + line-height: 1.5; + &::after { border: 0; } + &:active { opacity: 0.75; } + &[disabled] { opacity: 0.65; } +} + +.mine-page .btn-primary { background: #4ecdc4; color: #0a0e17; font-weight: 600; } +.mine-page .btn-ghost { background: transparent; border: 1rpx solid var(--mine-border); color: var(--mine-text); } +.mine-page .mine-sync-row { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; color: var(--mine-muted); font-size: 0.8125rem; margin: 1.25rem 0; } +.mine-page .mine-sync-row .btn { width: auto; margin: 0; flex-shrink: 0; } +.mine-page .mine-favorites-title { display: block; font-size: 1.125rem; margin-bottom: 1rem; color: var(--mine-text); } +.mine-page .mine-empty { text-align: center; color: var(--mine-muted); font-size: 0.875rem; line-height: 1.75; } +.mine-page .mine-inline-error { display: block; margin: 0.75rem 0; color: var(--mine-muted); font-size: 0.875rem; } diff --git a/apps/miniprogram/h5/src/pages/mine/index.tsx b/apps/miniprogram/h5/src/pages/mine/index.tsx index aade112..496b620 100644 --- a/apps/miniprogram/h5/src/pages/mine/index.tsx +++ b/apps/miniprogram/h5/src/pages/mine/index.tsx @@ -1,6 +1,6 @@ import { View, Text, Button, ScrollView } from '@tarojs/components' -import Taro from '@tarojs/taro' -import { useEffect, useState } from 'react' +import Taro, { useDidShow } from '@tarojs/taro' +import { useEffect, useRef, useState } from 'react' import { BrandNav, SiteFooter } from '../../components/Chrome' import { DestCard } from '../../components/DestCard' import { STORAGE_OPENID, STORAGE_TOKEN } from '../../utils/config' @@ -12,6 +12,10 @@ import { type ProfileStats, } from '../../services/api' import { usePageShare, markPageShare } from '@/utils/pageShare' +import { useNomadroTheme } from '@/utils/h5Theme' +import { goPage } from '@/utils/nav' +import { isAccountBlockedError } from '@/utils/accountBlocked' +import { safePx, useSafeAreaMetrics } from '@/utils/safeArea' import './index.scss' type MineUser = { @@ -28,8 +32,17 @@ function MinePage() { const [stats, setStats] = useState(null) const [favs, setFavs] = useState([]) const [loading, setLoading] = useState(false) + const [refreshing, setRefreshing] = useState(false) + const [refreshError, setRefreshError] = useState('') + const [favoritesError, setFavoritesError] = useState(false) + const refreshId = useRef(0) + const refreshInFlight = useRef(false) + const theme = useNomadroTheme() + const safe = useSafeAreaMetrics() async function refresh() { + if (refreshInFlight.current) return + const id = ++refreshId.current const token = Taro.getStorageSync(STORAGE_TOKEN) const openid = Taro.getStorageSync(STORAGE_OPENID) if (!token || !openid) { @@ -38,6 +51,12 @@ function MinePage() { setFavs([]) return } + // 已有会话先显示账户壳;弱网不把用户退回登录页。 + setUser((current) => current || { id: String(openid), name: 'Nomadro 用户', email: '', avatar: '🟢' }) + refreshInFlight.current = true + setRefreshing(true) + setRefreshError('') + setFavoritesError(false) try { // 主会话:ebook Bearer(与支付 / VIP 一致) const presence = await requestEbook<{ @@ -45,6 +64,7 @@ function MinePage() { openid?: string isVip?: boolean }>({ url: '/api/ebook/auth/presence', method: 'POST' }) + if (id !== refreshId.current) return setUser({ id: String(presence.openid || openid), name: 'Nomadro 用户', @@ -53,22 +73,34 @@ function MinePage() { isVip: Boolean(presence.isVip), }) // 社群收藏为增强项,失败不踢主登录 - const [s, f] = await Promise.all([ - fetchProfileStats().catch(() => null), - fetchFavoriteDetails().catch(() => [] as Destination[]), + const [s, f] = await Promise.allSettled([ + fetchProfileStats(), + fetchFavoriteDetails(), ]) - setStats(s) - setFavs(f) - } catch { - clearLogin() - setUser(null) - setStats(null) - setFavs([]) + if (id !== refreshId.current) return + if (s.status === 'fulfilled') setStats(s.value) + if (f.status === 'fulfilled') setFavs(f.value) + else setFavoritesError(true) + } catch (error) { + if (id !== refreshId.current) return + if (isAccountBlockedError(error) || !Taro.getStorageSync(STORAGE_TOKEN)) { + setUser(null) + setStats(null) + setFavs([]) + } + setRefreshError(isAccountBlockedError(error) ? '账号不可用' : '同步失败,请检查网络后重试') + } finally { + if (id === refreshId.current) { + refreshInFlight.current = false + setRefreshing(false) + } } } + useDidShow(() => { void refresh() }) + useEffect(() => { - void refresh() + return () => { refreshId.current += 1 } }, []) async function onWechatLogin() { @@ -97,6 +129,11 @@ function MinePage() { } function onLogout() { + refreshId.current += 1 + refreshInFlight.current = false + setRefreshing(false) + setRefreshError('') + setFavoritesError(false) clearLogin() setUser(null) setStats(null) @@ -104,9 +141,10 @@ function MinePage() { } return ( - + - + 👤 MINE 我的 @@ -117,8 +155,8 @@ function MinePage() { 未登录 微信一键登录,同步会员与收藏 - ) : ( @@ -129,7 +167,7 @@ function MinePage() { {user.name} - {user.isVip ? '👑 VIP 会员' : '普通用户 · 可开通 VIP'} + {user.isVip === undefined ? '会员信息待同步' : user.isVip ? '👑 VIP 会员' : '普通用户 · 可开通 VIP'} {stats ? {stats.nomad_level} : null} + + ❤️ 收藏的城市 + {favoritesError ? 收藏暂未同步,请刷新重试 : null} {favs.length ? ( favs.map((d) => ) ) : ( - 还没有收藏 · 去目的地逛逛 + + {refreshing ? '正在加载收藏…' : favoritesError || refreshError ? '连接恢复后即可查看收藏' : '收藏喜欢的城市,留给下一次出发'} + {!refreshing && !favoritesError && !refreshError ? ( + + ) : null} + )} )} + {!user && refreshError ? {refreshError} : null} +