From ae6dba026e6eaf1fe924de60dc6fe711d019f620 Mon Sep 17 00:00:00 2001 From: Eric Date: Thu, 5 Nov 2026 12:48:49 +0800 Subject: [PATCH] Ship social live UX gates, hide no-face roster avatars, and slim join profile. Co-authored-by: Cursor --- .../ebook_svc/routers/weapp_switches_admin.py | 23 +++ .../ebook_svc/services/weapp_switches.py | 49 +++++ apps/api/services/social_svc/pb_data.py | 31 ++- apps/api/services/social_svc/routers/api.py | 50 ++++- apps/api/services/social_svc/store.py | 148 +++++++++++-- apps/com/admin/src/pages/Switches.tsx | 150 +++++++++++++- src/app/admin/config/page.tsx | 5 + src/app/social/layout.tsx | 1 + src/lib/remote-config.ts | 141 +++++++++++++ src/modules/social/app/live.css | 195 ++++++++++++++++++ .../social/components/AttractiveRoster.tsx | 18 +- .../social/components/ChatWorkspace.tsx | 17 +- .../social/components/CommunityWelcome.tsx | 147 +++---------- .../social/components/ConnectionHero.tsx | 13 +- src/modules/social/components/DateClient.tsx | 16 +- .../social/components/EventDirectory.tsx | 15 +- src/modules/social/components/HomeClient.tsx | 15 +- .../social/components/HomeStatusStrip.tsx | 2 +- .../social/components/JoinPayModal.tsx | 40 ++-- src/modules/social/components/MapClient.tsx | 31 ++- .../social/components/PeopleClient.tsx | 7 +- .../social/components/PeopleProfileClient.tsx | 18 +- .../social/components/PlaceDetailClient.tsx | 7 +- src/modules/social/components/SiteShell.tsx | 4 + .../social/components/SocialAvatar.tsx | 16 +- .../social/components/SocialLiveShell.tsx | 172 +++++++++++++++ src/modules/social/lib/api.ts | 58 ++++++ src/modules/social/lib/discoveryRoster.ts | 64 ++++-- src/modules/social/lib/mapPins.ts | 5 +- src/modules/social/lib/phrases.ts | 13 ++ src/modules/social/lib/rankDiscovery.ts | 6 +- src/modules/social/lib/socialLive.ts | 32 +++ src/modules/social/lib/socialTrack.ts | 32 +++ src/modules/social/lib/socialTrial.ts | 15 +- src/modules/social/lib/useSocialPresence.ts | 176 ++++++++++++++++ 35 files changed, 1511 insertions(+), 221 deletions(-) create mode 100644 src/modules/social/app/live.css create mode 100644 src/modules/social/components/SocialLiveShell.tsx create mode 100644 src/modules/social/lib/socialLive.ts create mode 100644 src/modules/social/lib/socialTrack.ts create mode 100644 src/modules/social/lib/useSocialPresence.ts diff --git a/apps/api/services/ebook_svc/routers/weapp_switches_admin.py b/apps/api/services/ebook_svc/routers/weapp_switches_admin.py index 438773a..97944f3 100644 --- a/apps/api/services/ebook_svc/routers/weapp_switches_admin.py +++ b/apps/api/services/ebook_svc/routers/weapp_switches_admin.py @@ -20,6 +20,28 @@ class ModuleIn(BaseModel): note: str | None = Field(default=None, max_length=1000) +class SocialLiveIn(BaseModel): + """游民社区实时 UX 超级兜底 — 不限于下列键,可继续扩展。""" + presenceEnabled: bool | None = None + presenceStrip: bool | None = None + presenceCityScope: bool | None = None + discoveryAutoRefresh: bool | None = None + discoveryRefreshSec: int | None = Field(default=None, ge=15, le=300) + configHotReloadToast: bool | None = None + offlineFallbackShell: bool | None = None + hideNoFaceAvatar: bool | None = None + livenessGate: bool | None = None + trackLiveEvents: bool | None = None + chatPresencePill: bool | None = None + mapLivePins: bool | None = None + joinPriceLive: bool | None = None + onlineCountBadge: bool | None = None + softStatusSync: bool | None = None + configVersionChip: bool | None = None + trialLive: bool | None = None + presenceHeartbeatSec: int | None = Field(default=None, ge=10, le=120) + + class FlagsIn(BaseModel): payEnabled: bool | None = None socialFollow: bool | None = None @@ -29,6 +51,7 @@ class FlagsIn(BaseModel): joinGroupWechat: bool | None = None socialTrialEnabled: bool | None = None socialAvatarFaceCheck: bool | None = None + socialLive: SocialLiveIn | None = None adsenseEnabled: bool | None = None adsenseClientId: str | None = Field(default=None, max_length=64, pattern=r"^(ca-pub-[0-9]+)?$") adsensePublisherId: str | None = Field(default=None, max_length=64, pattern=r"^(pub-[0-9]+)?$") diff --git a/apps/api/services/ebook_svc/services/weapp_switches.py b/apps/api/services/ebook_svc/services/weapp_switches.py index d89d21a..631e700 100644 --- a/apps/api/services/ebook_svc/services/weapp_switches.py +++ b/apps/api/services/ebook_svc/services/weapp_switches.py @@ -95,6 +95,50 @@ def _social_trial(raw: Any) -> dict[str, Any]: return base +DEFAULT_SOCIAL_LIVE: dict[str, Any] = { + "presenceEnabled": True, + "presenceStrip": True, + "presenceCityScope": True, + "discoveryAutoRefresh": True, + "discoveryRefreshSec": 45, + "configHotReloadToast": True, + "offlineFallbackShell": True, + "hideNoFaceAvatar": True, + "livenessGate": True, + "trackLiveEvents": True, + "chatPresencePill": True, + "mapLivePins": True, + "joinPriceLive": True, + "onlineCountBadge": True, + "softStatusSync": True, + "configVersionChip": False, + "trialLive": True, + "presenceHeartbeatSec": 25, +} + + +def _social_live(raw: Any) -> dict[str, Any]: + base = dict(DEFAULT_SOCIAL_LIVE) + if not isinstance(raw, dict): + return base + for k, default in DEFAULT_SOCIAL_LIVE.items(): + if k not in raw or raw[k] is None: + continue + if isinstance(default, bool): + base[k] = bool(raw[k]) + elif isinstance(default, int): + try: + n = int(raw[k]) + except (TypeError, ValueError): + continue + if k.endswith("Sec"): + lo, hi = (15, 300) if k == "discoveryRefreshSec" else (10, 120) + base[k] = max(lo, min(hi, n)) + else: + base[k] = max(0, n) + return base + + def _vip_price_fen(raw: Any, fallback: int = 10) -> int: try: return max(0, int(raw)) @@ -216,6 +260,7 @@ def read_weapp_switches() -> dict[str, Any]: "adsenseSlotBlogEnd": str(flags_raw.get("adsenseSlotBlogEnd") or ""), "socialAvatarFaceCheck": bool(flags_raw.get("socialAvatarFaceCheck")), "socialTrialEnabled": flags_raw.get("socialTrialEnabled", True) is not False, + "socialLive": _social_live(flags_raw.get("socialLive")), }, "copy": { "homeBrand": str(copy_raw.get("homeBrand") or "nomadro"), @@ -291,6 +336,10 @@ def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]: flags["socialAvatarFaceCheck"] = bool(fp["socialAvatarFaceCheck"]) if "socialTrialEnabled" in fp: flags["socialTrialEnabled"] = bool(fp["socialTrialEnabled"]) + if "socialLive" in fp and fp["socialLive"] is not None: + prev = flags.get("socialLive") if isinstance(flags.get("socialLive"), dict) else {} + incoming = fp["socialLive"] if isinstance(fp["socialLive"], dict) else {} + flags["socialLive"] = _social_live({**prev, **incoming}) for ak in ( "adsenseClientId", "adsensePublisherId", diff --git a/apps/api/services/social_svc/pb_data.py b/apps/api/services/social_svc/pb_data.py index e83dc9e..412abab 100644 --- a/apps/api/services/social_svc/pb_data.py +++ b/apps/api/services/social_svc/pb_data.py @@ -160,11 +160,20 @@ def health() -> dict[str, Any]: # —— roster —— +def _face_ok_raw(raw: Any) -> bool: + return raw is True or raw == 1 or str(raw).lower() in {"1", "true", "yes"} + + def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, Any]: status = (r.get("status") or "online").strip() or "online" skills = r.get("skills") or "" intents = r.get("intents") or "" tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8] + face_ok = _face_ok_raw(r.get("face_ok")) + avatar = str(r.get("avatar") or "").strip() + # Public surfaces never leak no-face album photos — placeholder only. + if public and not face_ok: + avatar = "" item: dict[str, Any] = { "guestId": r.get("guest_id") or "", "email": r.get("email") or "", @@ -173,7 +182,7 @@ def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, An "city": r.get("city") or "", "skills": skills, "bio": r.get("bio") or "", - "avatar": r.get("avatar") or "", + "avatar": avatar, "gender": r.get("gender") or "", "intents": intents, "availability": r.get("availability") or "", @@ -182,7 +191,7 @@ def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, An "updatedAt": r.get("updated_at") or "", "online": status in {"online", "here", "available"}, "tags": tags, - "faceOk": bool(r.get("face_ok")), + "faceOk": face_ok, "livenessStatus": r.get("liveness_status") or "none", "livenessAt": r.get("liveness_at") or "", "livenessVideoUrl": r.get("liveness_video_url") or "", @@ -478,14 +487,9 @@ def list_discovery_roster( continue if not (r.get("name") or "").strip(): continue - # Dating / 约会: no face in avatar → never show + # Dating / 约会: no face in avatar → never show the person if require_face: - face_raw = r.get("face_ok") - face_ok = face_raw is True or face_raw == 1 or str(face_raw).lower() in { - "1", - "true", - "yes", - } + face_ok = _face_ok_raw(r.get("face_ok")) avatar = str(r.get("avatar") or "").strip() if not face_ok: continue @@ -585,7 +589,10 @@ def channel_seq(channel_id: str) -> int: def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]: - """Batch roster.avatar for chat bubbles (guest_id → url).""" + """Batch roster.avatar for chat bubbles (guest_id → url). + + No-face album photos are blanked — chat never paints them. + """ ids = sorted({str(g or "").strip() for g in guest_ids if str(g or "").strip()}) if not ids: return {} @@ -601,8 +608,10 @@ def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]: rows = [] for r in rows: gid = str(r.get("guest_id") or "").strip() + if not gid or not _face_ok_raw(r.get("face_ok")): + continue av = str(r.get("avatar") or "").strip()[:500] - if gid and av: + if av: out[gid] = av return out diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index ccf294e..033de44 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -74,6 +74,17 @@ class ReportIn(BaseModel): class PresenceIn(BaseModel): nick: str = Field(default="游民", max_length=48) + city: str = Field(default="", max_length=64) + avatar: str = Field(default="", max_length=500) + softStatusSync: bool = False + + +class SocialPresenceIn(BaseModel): + """Global / city who's-online heartbeat (not tied to a chat channel).""" + nick: str = Field(default="游民", max_length=48) + city: str = Field(default="", max_length=64) + avatar: str = Field(default="", max_length=500) + softStatusSync: bool = True class NoteIn(BaseModel): @@ -363,7 +374,44 @@ async def post_presence( guest: str | None = Query(default=None), ): peer = _guest(x_social_guest_id, guest) - return store.touch_presence(channel_id, peer, body.nick) + return store.touch_presence( + channel_id, + peer, + body.nick, + city=body.city, + avatar=body.avatar, + soft_status_sync=bool(body.softStatusSync), + ) + + +@router.post("/roster/presence") +async def post_roster_presence( + body: SocialPresenceIn, + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + """Global social presence heartbeat — powers「谁在线」strip + city count.""" + peer = _guest(x_social_guest_id, guest) + return store.touch_presence( + store.SOCIAL_GLOBAL_ROOM, + peer, + body.nick, + city=body.city, + avatar=body.avatar, + soft_status_sync=bool(body.softStatusSync), + ) + + +@router.get("/roster/online") +def get_roster_online( + city: str = Query(default=""), + limit: int = Query(default=48, ge=1, le=64), + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + """Who's online now (TTL presence). Offline clients get empty + UI fallback.""" + _ = _guest(x_social_guest_id, guest) + return store.list_social_online(city=(city or "").strip(), limit=limit) @router.post("/upload") diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 4af266a..9906d6a 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -550,37 +550,112 @@ def get_file(file_id: str) -> dict[str, Any] | None: # Element-like soft presence (TTL heartbeat; UI-agnostic) +# Rooms: chat channel ids + global "social:global" + optional "social:city:" _PRESENCE: dict[str, dict[str, dict[str, Any]]] = {} _PRESENCE_TTL_SEC = 45 +SOCIAL_GLOBAL_ROOM = "social:global" + + +def _city_room(city: str) -> str: + slug = "".join((city or "").strip().lower().split())[:48] + return f"social:city:{slug}" if slug else SOCIAL_GLOBAL_ROOM def touch_presence( - channel_id: str, guest_id: str, nick: str = "" + channel_id: str, + guest_id: str, + nick: str = "", + *, + city: str = "", + avatar: str = "", + soft_status_sync: bool = False, ) -> dict[str, Any]: """Soft presence: process-local TTL map (fast path). PB ch_meta.presence is best-effort mirror.""" now = time.time() - room = _PRESENCE.setdefault(channel_id, {}) - room[guest_id] = { - "guestId": guest_id, - "nick": (nick or "游民").strip()[:48] or "游民", - "at": now, - } - # prune - dead = [gid for gid, meta in room.items() if now - float(meta["at"]) > _PRESENCE_TTL_SEC] - for gid in dead: - room.pop(gid, None) - peers = online_peers(channel_id) + rooms = [channel_id or SOCIAL_GLOBAL_ROOM] + if channel_id != SOCIAL_GLOBAL_ROOM: + rooms.append(SOCIAL_GLOBAL_ROOM) + city_slug = "".join((city or "").strip().lower().split()) + if city_slug: + rooms.append(_city_room(city)) + + for room_id in rooms: + room = _PRESENCE.setdefault(room_id, {}) + room[guest_id] = { + "guestId": guest_id, + "nick": (nick or "游民").strip()[:48] or "游民", + "city": (city or "").strip()[:64], + "avatar": (avatar or "").strip()[:500], + "at": now, + } + dead = [ + gid + for gid, meta in room.items() + if now - float(meta["at"]) > _PRESENCE_TTL_SEC + ] + for gid in dead: + room.pop(gid, None) + + peers = online_peers(channel_id or SOCIAL_GLOBAL_ROOM) + city_peers = online_peers(_city_room(city)) if city_slug else peers + + if soft_status_sync: + try: + from social_svc import pb_data + + row = pb_data.get_roster(guest_id) + cur = str((row or {}).get("status") or "") + if row and cur in {"", "offline", "away"}: + # Full merge — upsert_roster replaces fields; never send a partial stub. + pb_data.upsert_roster( + guest_id, + { + **{ + k: row.get(k) + for k in ( + "name", + "title", + "city", + "phone", + "linktree", + "skills", + "bio", + "avatar", + "gender", + "intents", + "availability", + "lookingFor", + "relationship", + "education", + "graduation", + "wechat", + "email", + "discoverable", + ) + if row.get(k) is not None + }, + "status": "online", + "city": city or row.get("city") or "", + "avatar": avatar or row.get("avatar") or "", + "name": row.get("name") or nick or "游民", + }, + ) + except Exception: + pass + try: from social_svc import pb_data from nomadro_pb import get_pb, pb_quote pb_data.init_pb() meta = get_pb().first( - pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}" + pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id or SOCIAL_GLOBAL_ROOM)}" ) presence = { - p["guestId"]: {"nick": p["nick"], "at": now} for p in peers + p["guestId"]: {"nick": p["nick"], "at": now, "city": p.get("city") or ""} + for p in peers } + cid = channel_id or SOCIAL_GLOBAL_ROOM if meta: get_pb().update( pb_data.C_CHMETA, meta["id"], {"presence": presence, "updated_at": _now()} @@ -589,7 +664,7 @@ def touch_presence( get_pb().create( pb_data.C_CHMETA, { - "channel_id": channel_id, + "channel_id": cid, "seq": 0, "pins": [], "presence": presence, @@ -598,7 +673,13 @@ def touch_presence( ) except Exception: pass - return {"channelId": channel_id, "online": len(peers), "peers": peers} + return { + "channelId": channel_id or SOCIAL_GLOBAL_ROOM, + "online": len(peers), + "peers": peers, + "cityOnline": len(city_peers), + "cityPeers": city_peers[:24], + } def online_peers(channel_id: str) -> list[dict[str, Any]]: @@ -609,11 +690,34 @@ def online_peers(channel_id: str) -> list[dict[str, Any]]: if now - float(meta["at"]) > _PRESENCE_TTL_SEC: room.pop(gid, None) continue - out.append({"guestId": gid, "nick": meta.get("nick") or "游民"}) + out.append( + { + "guestId": gid, + "nick": meta.get("nick") or "游民", + "city": meta.get("city") or "", + "avatar": meta.get("avatar") or "", + } + ) out.sort(key=lambda p: p["nick"]) return out[:64] +def list_social_online(*, city: str = "", limit: int = 48) -> dict[str, Any]: + """Public who's-online for social shell (global + optional city).""" + city_slug = "".join((city or "").strip().lower().split()) + global_peers = online_peers(SOCIAL_GLOBAL_ROOM) + city_peers = online_peers(_city_room(city)) if city_slug else [] + lim = max(1, min(int(limit or 48), 64)) + return { + "ok": True, + "online": len(global_peers), + "peers": global_peers[:lim], + "city": (city or "").strip()[:64], + "cityOnline": len(city_peers), + "cityPeers": city_peers[:lim], + } + + def report_message( channel_id: str, msg_id: str, guest_id: str, reason: str = "" ) -> dict[str, Any]: @@ -667,6 +771,10 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: intents = (r["intents"] if "intents" in keys else "") or "" skills = r["skills"] or "" status = ((r["status"] if "status" in keys else "") or "online").strip() or "online" + face_ok = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)) + avatar = (r["avatar"] if "avatar" in keys else "") or "" + if public and not face_ok: + avatar = "" item: dict[str, Any] = { "guestId": r["guest_id"], "name": r["name"], @@ -674,7 +782,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: "city": r["city"] or "", "skills": skills, "bio": r["bio"] or "", - "avatar": (r["avatar"] if "avatar" in keys else "") or "", + "avatar": avatar, "gender": (r["gender"] if "gender" in keys else "") or "", "intents": intents, "availability": (r["availability"] if "availability" in keys else "") or "", @@ -695,7 +803,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: "wechat": (r["wechat"] if "wechat" in keys else "") or "", "discoverable": int(r["discoverable"] if "discoverable" in keys and r["discoverable"] is not None else 1), "onboardedAt": (r["onboarded_at"] if "onboarded_at" in keys else "") or "", - "faceOk": bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)), + "faceOk": face_ok, "livenessStatus": (r["liveness_status"] if "liveness_status" in keys else "") or "none", "livenessAt": (r["liveness_at"] if "liveness_at" in keys else "") or "", "livenessVideoUrl": (r["liveness_video_url"] if "liveness_video_url" in keys else "") or "", @@ -703,7 +811,7 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: ) else: item["linktree"] = r["linktree"] or "" - item["faceOk"] = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)) + item["faceOk"] = face_ok item["livenessStatus"] = (r["liveness_status"] if "liveness_status" in keys else "") or "none" return item diff --git a/apps/com/admin/src/pages/Switches.tsx b/apps/com/admin/src/pages/Switches.tsx index a404151..6f3aeab 100644 --- a/apps/com/admin/src/pages/Switches.tsx +++ b/apps/com/admin/src/pages/Switches.tsx @@ -24,6 +24,8 @@ type SwitchesCfg = { adsenseSlotBlogMid?: string adsenseSlotBlogEnd?: string socialTrialEnabled?: boolean + socialAvatarFaceCheck?: boolean + socialLive?: SocialLiveCfg } copy: { homeBrand: string @@ -54,15 +56,60 @@ type SwitchesCfg = { updatedAt?: string } -type TabKey = 'pages' | 'flags' | 'vip' | 'copy' +type SocialLiveCfg = { + presenceEnabled?: boolean + presenceStrip?: boolean + presenceCityScope?: boolean + discoveryAutoRefresh?: boolean + discoveryRefreshSec?: number + configHotReloadToast?: boolean + offlineFallbackShell?: boolean + hideNoFaceAvatar?: boolean + livenessGate?: boolean + trackLiveEvents?: boolean + chatPresencePill?: boolean + mapLivePins?: boolean + joinPriceLive?: boolean + onlineCountBadge?: boolean + softStatusSync?: boolean + configVersionChip?: boolean + trialLive?: boolean + presenceHeartbeatSec?: number +} + +type TabKey = 'pages' | 'flags' | 'live' | 'vip' | 'copy' const TABS: Array<{ key: TabKey; label: string }> = [ { key: 'pages', label: '页面' }, { key: 'flags', label: '功能' }, + { key: 'live', label: '实时社区' }, { key: 'vip', label: 'VIP 区块' }, { key: 'copy', label: '文案' }, ] +const SOCIAL_LIVE_FLAGS: Array<{ + key: keyof SocialLiveCfg + label: string + desc: string +}> = [ + { key: 'presenceEnabled', label: '谁在线心跳', desc: '全局 presence 心跳;关则不报在线' }, + { key: 'presenceStrip', label: '在线条', desc: '壳层展示谁在线 / 人数' }, + { key: 'presenceCityScope', label: '同城在线', desc: '优先展示同城在线人数' }, + { key: 'discoveryAutoRefresh', label: '发现自动刷新', desc: '大厅 / 约会列表定时拉新' }, + { key: 'configHotReloadToast', label: '配置热更新 Toast', desc: '后台改开关后前端提示' }, + { key: 'offlineFallbackShell', label: '离线超级兜底壳', desc: '断网不白屏,展示本地兜底' }, + { key: 'hideNoFaceAvatar', label: '无人脸头像隐藏', desc: '无 faceOk 的头像不展示' }, + { key: 'livenessGate', label: '真人自拍闸', desc: '约会 / 畅聊要求自拍核验' }, + { key: 'trackLiveEvents', label: '实时埋点', desc: '在线心跳 / 配置热更 / 刷新上报' }, + { key: 'chatPresencePill', label: '聊天在线 pill', desc: '群聊顶栏显示在线人数' }, + { key: 'mapLivePins', label: '地图人钉实时', desc: '地图 pins 跟发现列表热刷新' }, + { key: 'joinPriceLive', label: '加入价实时', desc: '弹窗打开时强制拉最新价' }, + { key: 'onlineCountBadge', label: '在线人数角标', desc: '在线条显示数字' }, + { key: 'softStatusSync', label: '心跳同步在线状态', desc: '心跳把 roster 标为 online' }, + { key: 'configVersionChip', label: '配置版本 chip', desc: '弱提示当前 remote-config 版本' }, + { key: 'trialLive', label: '尝鲜限额实时', desc: '跟随后台 trial 配置;关则用离线种子' }, +] + const PAGE_MODS = [ { key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' }, { key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' }, @@ -285,6 +332,16 @@ export default function Switches() { { key: 'payEnabled', label: '支付总开关', desc: '关闭后隐藏付费 CTA' }, { key: 'socialFollow', label: '关注引导', desc: '公众号 / X 关注弹窗' }, { key: 'offlineBadge', label: '离线角标', desc: '展示「本地数据」提示' }, + { + key: 'socialAvatarFaceCheck', + label: '头像人脸检测', + desc: '关=静默检测不提示;开=强制正面照文案', + }, + { + key: 'socialTrialEnabled', + label: '尝鲜限额', + desc: '未完整加入时的聊天/约会配额', + }, { key: 'adsenseEnabled', label: 'AdSense 展示', @@ -358,6 +415,97 @@ export default function Switches() { ) : null} + {tab === 'live' ? ( +
+

实时社区 · UX 超级兜底

+

+ 谁在线、热更新、离线壳、埋点、发现刷新等。门户 SSE 热推;不限于下列开关,可持续扩展。 +

+
+ {SOCIAL_LIVE_FLAGS.map((f) => { + const defaults: Record = { + presenceEnabled: true, + presenceStrip: true, + presenceCityScope: true, + discoveryAutoRefresh: true, + configHotReloadToast: true, + offlineFallbackShell: true, + hideNoFaceAvatar: true, + livenessGate: true, + trackLiveEvents: true, + chatPresencePill: true, + mapLivePins: true, + joinPriceLive: true, + onlineCountBadge: true, + softStatusSync: true, + configVersionChip: false, + trialLive: true, + } + const raw = cfg.flags.socialLive?.[f.key] + const on = + typeof raw === 'boolean' ? raw : Boolean(defaults[f.key as string]) + return ( +
+
+ {f.label} +

{f.desc}

+
+ + void patch( + { flags: { socialLive: { [f.key]: v } } }, + `${f.label}已${v ? '开启' : '关闭'}`, + ) + } + /> +
+ ) + })} +
+ + +
+
+
+ ) : null} + {tab === 'vip' ? ( <>
diff --git a/src/app/admin/config/page.tsx b/src/app/admin/config/page.tsx index d258390..e605f7d 100644 --- a/src/app/admin/config/page.tsx +++ b/src/app/admin/config/page.tsx @@ -259,6 +259,11 @@ export default function AdminConfigPage() { label: "头像人脸检测", hint: "游民社区上传头像是否强制正脸检测;关=任意图可传。SSE/WS 热更新前端与 social 上传闸。默认关。", }, + { + key: "socialTrialEnabled" as const, + label: "尝鲜限额", + hint: "未完整加入时的聊天/约会配额。细项与实时 UX 见 admin.nomadro.com → 动态开关 → 实时社区。", + }, ] as const ).map(({ key, label, hint }) => (
@@ -310,7 +322,7 @@ function PersonMini({ m }: { m: SocialRosterMember }) { className={`social-people-chip social-chip-pop${m.online ? " is-online" : ""}`} > - + {m.online ? : null} {m.name} diff --git a/src/modules/social/components/PlaceDetailClient.tsx b/src/modules/social/components/PlaceDetailClient.tsx index 023a95e..e5bcde2 100644 --- a/src/modules/social/components/PlaceDetailClient.tsx +++ b/src/modules/social/components/PlaceDetailClient.tsx @@ -386,7 +386,12 @@ export default function PlaceDetailClient({ cityId }: Props) { href={socialPath(`/people/${p.id}`)} className="spd-person" > - + {p.name} {p.title || p.city} diff --git a/src/modules/social/components/SiteShell.tsx b/src/modules/social/components/SiteShell.tsx index 064a53d..0d7f834 100644 --- a/src/modules/social/components/SiteShell.tsx +++ b/src/modules/social/components/SiteShell.tsx @@ -28,6 +28,7 @@ import SocialBrandLogo from "./SocialBrandLogo"; import JoinPayModal from "./JoinPayModal"; import NavAccountMenu from "./NavAccountMenu"; import TrialNudgeBanner from "./TrialNudgeBanner"; +import SocialLiveShell from "./SocialLiveShell"; import { consumeOpenJoinModalFlag, subscribeSocialJoinModal, @@ -309,6 +310,7 @@ export default function SiteShell({ {t.skipToMain} {nav} + {children} {authModal} @@ -323,6 +325,7 @@ export default function SiteShell({ {t.skipToMain} {nav} +
{children} @@ -361,6 +364,7 @@ export default function SiteShell({ {t.skipToMain} {nav} +
diff --git a/src/modules/social/components/SocialAvatar.tsx b/src/modules/social/components/SocialAvatar.tsx index dda2183..85eb546 100644 --- a/src/modules/social/components/SocialAvatar.tsx +++ b/src/modules/social/components/SocialAvatar.tsx @@ -2,17 +2,23 @@ import Image from "next/image"; +const PLACEHOLDER = "/icons/nomadro.webp"; + /** Unoptimized keeps external/profile/API avatar URLs working offline & cross-host. */ export default function SocialAvatar({ src, size, lazy = false, + faceOk, }: { src: string; size: number; lazy?: boolean; + /** When false, never paint the raw album URL (no-face photos stay hidden). */ + faceOk?: boolean; }) { - const url = (src || "").trim(); + const raw = (src || "").trim(); + const url = faceOk === false ? "" : raw; // Relative social API / blob: use plain — next/image remotePatterns skip these. if ( !url || @@ -23,7 +29,7 @@ export default function SocialAvatar({ return ( // eslint-disable-next-line @next/next/no-img-element { const img = event.currentTarget; - if (!img.src.endsWith("/icons/nomadro.webp")) - img.src = "/icons/nomadro.webp"; + if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER; }} /> ); @@ -48,8 +53,7 @@ export default function SocialAvatar({ loading={lazy ? "lazy" : "eager"} onError={(event) => { const img = event.currentTarget; - if (!img.src.endsWith("/icons/nomadro.webp")) - img.src = "/icons/nomadro.webp"; + if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER; }} /> ); diff --git a/src/modules/social/components/SocialLiveShell.tsx b/src/modules/social/components/SocialLiveShell.tsx new file mode 100644 index 0000000..a27e084 --- /dev/null +++ b/src/modules/social/components/SocialLiveShell.tsx @@ -0,0 +1,172 @@ +"use client"; + +/** + * Social Live UX — heartbeat always; chrome only when it earns the pixel. + * Never paste landing copy into presence. Never sticky-bar the home hero. + */ +import { useEffect, useRef, useState } from "react"; +import { usePathname } from "next/navigation"; +import { useRemoteConfig } from "~/lib/use-remote-config"; +import { socialPath } from "@social/lib/socialPath"; +import { socialTx } from "@social/lib/socialTx"; +import { + getSocialLive, + type SocialLiveFlags, +} from "@social/lib/socialLive"; +import { socialTrack } from "@social/lib/socialTrack"; +import { useSocialPresence } from "@social/lib/useSocialPresence"; +import SocialAvatar from "./SocialAvatar"; + +function LiveToast({ + text, + onDone, +}: { + text: string; + onDone: () => void; +}) { + useEffect(() => { + const t = setTimeout(onDone, 3200); + return () => clearTimeout(t); + }, [onDone, text]); + return ( +
+ {text} +
+ ); +} + +export default function SocialLiveShell({ + /** Home hero: never sticky-strip under nav */ + home = false, +}: { + home?: boolean; +}) { + const pathname = usePathname(); + const { config } = useRemoteConfig(); + const live = getSocialLive(config); + const presence = useSocialPresence(config); + const [toast, setToast] = useState(""); + const [navOffline, setNavOffline] = useState(false); + const lastVersion = useRef(Number(config.version) || 0); + const booted = useRef(false); + + const isHome = + home || + pathname === socialPath("/") || + pathname === socialPath("") || + pathname === "/social" || + pathname === "/social/"; + + useEffect(() => { + const sync = () => + setNavOffline(typeof navigator !== "undefined" && !navigator.onLine); + sync(); + window.addEventListener("online", sync); + window.addEventListener("offline", sync); + return () => { + window.removeEventListener("online", sync); + window.removeEventListener("offline", sync); + }; + }, []); + + useEffect(() => { + const v = Number(config.version) || 0; + if (!booted.current) { + booted.current = true; + lastVersion.current = v; + return; + } + if (v && v !== lastVersion.current) { + lastVersion.current = v; + socialTrack(live, "social_config_hot", { version: v }); + if (live.configHotReloadToast) { + setToast( + socialTx("社区配置已更新") + + (live.configVersionChip ? ` · v${v}` : ""), + ); + } + } + }, [config.version, live]); + + // Only real browser offline — never flash on first-paint config seed. + const showOffline = live.offlineFallbackShell && navOffline; + + const peers = + live.presenceCityScope && presence.cityPeers.length + ? presence.cityPeers + : presence.peers; + const count = + live.presenceCityScope && presence.cityOnline > 0 + ? presence.cityOnline + : presence.online; + + // Home: never float / never strip — heartbeat still runs, zero chrome. + const showStrip = + !isHome && + live.presenceStrip && + live.presenceEnabled && + count > 0 && + !presence.fromOffline; + + if (!showStrip && !showOffline && !toast) { + return null; + } + + return ( +
+ {showOffline ? ( +
+ +
+ {socialTx("网络已断开")} +

{socialTx("仍可浏览本地数据,连上后自动刷新。")}

+
+
+ ) : null} + + {showStrip ? ( +
+ + + {live.onlineCountBadge ? ( + {count} + ) : null} + {socialTx("人在线")} + + {peers.length ? ( +
+ {peers.slice(0, 6).map((p) => ( + + ))} +
+ ) : null} + {live.configVersionChip ? ( + v{config.version || "—"} + ) : null} +
+ ) : null} + + {toast ? setToast("")} /> : null} +
+ ); +} + +export function readLiveFlags( + config: { flags?: { socialLive?: Partial } } | null, +): SocialLiveFlags { + return getSocialLive(config as never); +} diff --git a/src/modules/social/lib/api.ts b/src/modules/social/lib/api.ts index 94d160d..8d83b3c 100644 --- a/src/modules/social/lib/api.ts +++ b/src/modules/social/lib/api.ts @@ -125,6 +125,64 @@ export const socialApi = { json: { nick: nick || "游民" }, }), + /** Global who's-online heartbeat (social shell). */ + rosterPresence: (opts?: { + nick?: string; + city?: string; + avatar?: string; + softStatusSync?: boolean; + }) => + req<{ + channelId: string; + online: number; + peers: Array<{ + guestId: string; + nick: string; + city?: string; + avatar?: string; + }>; + cityOnline?: number; + cityPeers?: Array<{ + guestId: string; + nick: string; + city?: string; + avatar?: string; + }>; + }>("/roster/presence", { + method: "POST", + json: { + nick: opts?.nick || "游民", + city: opts?.city || "", + avatar: opts?.avatar || "", + softStatusSync: opts?.softStatusSync !== false, + }, + }), + + rosterOnline: (opts?: { city?: string; limit?: number }) => { + const q = new URLSearchParams(); + if (opts?.city) q.set("city", opts.city); + if (opts?.limit) q.set("limit", String(opts.limit)); + const qs = q.toString(); + return req<{ + ok: boolean; + online: number; + peers: Array<{ + guestId: string; + nick: string; + city?: string; + avatar?: string; + }>; + city?: string; + cityOnline?: number; + cityPeers?: Array<{ + guestId: string; + nick: string; + city?: string; + avatar?: string; + }>; + }>(`/roster/online${qs ? `?${qs}` : ""}`, { ttlMs: 0 }); + }, + listMessages: ( channelId: string, opts?: { limit?: number; since?: number; before?: number; q?: string }, diff --git a/src/modules/social/lib/discoveryRoster.ts b/src/modules/social/lib/discoveryRoster.ts index 606a26d..65fec5c 100644 --- a/src/modules/social/lib/discoveryRoster.ts +++ b/src/modules/social/lib/discoveryRoster.ts @@ -2,6 +2,7 @@ import { useEffect, useMemo, useState, useSyncExternalStore } from "react"; import { useAudienceModule } from "~/modules/audience"; +import { useRemoteConfig } from "~/lib/use-remote-config"; import { socialApi } from "./api"; import { MOCK_ROSTER, type SocialRosterMember } from "./rosterMock"; import { cnAvatarForSeed, mapRosterAvatarPack } from "./rosterAvatars"; @@ -11,6 +12,11 @@ import { } from "./rankDiscovery"; import { isFaceOk } from "./livenessGate"; import { loadJson, saveJson } from "./storage"; +import { + getSocialLive, + socialLiveDiscoveryMs, +} from "./socialLive"; +import { socialTrack } from "./socialTrack"; import type { SocialRosterProfile } from "./types"; export const ROSTER_PUBLISH_KEY = "roster-publish"; @@ -119,6 +125,8 @@ export function useDiscoveryRoster(opts?: { }): SocialRosterMember[] { const requireFace = Boolean(opts?.requireFace); const { bundle } = useAudienceModule(); + const { config } = useRemoteConfig(); + const live = getSocialLive(config); const pack = bundle.module.social.rosterAvatarPack; const published = useSyncExternalStore( subscribeSocialStorage, @@ -144,22 +152,52 @@ export function useDiscoveryRoster(opts?: { useEffect(() => { let cancelled = false; - void socialApi - .discoveryRoster({ limit: 48, requireFace }) - .then((res) => { - if (cancelled || !res?.items?.length) { - if (!cancelled) setRemote([]); - return; - } - setRemote(res.items.map(discoveryItemToMember)); - }) - .catch(() => { - /* offline → keep mock */ - }); + let timer: ReturnType | null = null; + + const pull = () => { + void socialApi + .discoveryRoster({ limit: 48, requireFace }) + .then((res) => { + if (cancelled) return; + if (!res?.items?.length) { + setRemote([]); + return; + } + setRemote(res.items.map(discoveryItemToMember)); + socialTrack(live, "social_discovery_refresh", { + count: res.items.length, + requireFace: requireFace ? 1 : 0, + }); + }) + .catch(() => { + /* offline → keep mock / last good */ + }); + }; + + pull(); + if (live.discoveryAutoRefresh) { + timer = setInterval(pull, socialLiveDiscoveryMs(live)); + } + const onVis = () => { + if (!document.hidden) pull(); + }; + const onOnline = () => pull(); + document.addEventListener("visibilitychange", onVis); + window.addEventListener("online", onOnline); return () => { cancelled = true; + if (timer) clearInterval(timer); + document.removeEventListener("visibilitychange", onVis); + window.removeEventListener("online", onOnline); }; - }, [profile.city, profile.skills, profile.intents, requireFace]); + }, [ + profile.city, + profile.skills, + profile.intents, + requireFace, + live.discoveryAutoRefresh, + live.discoveryRefreshSec, + ]); const seed = useMemo( () => mapRosterAvatarPack(MOCK_ROSTER, pack), diff --git a/src/modules/social/lib/mapPins.ts b/src/modules/social/lib/mapPins.ts index 4bb357b..3726b77 100644 --- a/src/modules/social/lib/mapPins.ts +++ b/src/modules/social/lib/mapPins.ts @@ -48,6 +48,7 @@ export type MapPersonPin = { id: string; name: string; avatar: string; + faceOk?: boolean; gender: "f" | "m"; title: string; cityId: string; @@ -142,10 +143,12 @@ export function buildMapPersonPins( ? codeForCountry(loc.country) : fromPool[index % fromPool.length]; const destCode = loc.nextName ? toCode : codeForCountry(loc.country); + const faceOk = m.faceOk !== false; pins.push({ id: m.id, name: m.name, - avatar: m.avatar, + avatar: faceOk ? m.avatar : "", + faceOk, gender: m.gender, title: m.title, cityId: loc.cityId, diff --git a/src/modules/social/lib/phrases.ts b/src/modules/social/lib/phrases.ts index cef0922..3a16be1 100644 --- a/src/modules/social/lib/phrases.ts +++ b/src/modules/social/lib/phrases.ts @@ -724,4 +724,17 @@ export const SOCIAL_PHRASES_EN: Record = { "关注": "Follow", "👆 点卡片看看详情,也可以先点爱心关注": "👆 Tap a card for details, or ♥ to follow", + "社区配置已更新": "Community settings updated", + "离线模式 · 本地兜底": "Offline · local fallback", + "网络已断开": "You’re offline", + "仍可浏览本地数据,连上后自动刷新。": + "Local data still works — refreshes when you’re back online.", + "网络不稳时仍可浏览本地数据;恢复后自动刷新谁在线与配置。": + "You can still browse local data offline; presence and config refresh when you’re back.", + "重试": "Retry", + "人在线": " online", + "等待同频游民上线": "Waiting for fellow nomads", + "下一步:上传头像": "Next: upload a photo", + "上传中…": "Uploading…", + "准备中…": "Getting ready…", }; diff --git a/src/modules/social/lib/rankDiscovery.ts b/src/modules/social/lib/rankDiscovery.ts index a767acf..059d871 100644 --- a/src/modules/social/lib/rankDiscovery.ts +++ b/src/modules/social/lib/rankDiscovery.ts @@ -80,13 +80,15 @@ export function discoveryItemToMember(item: { .map((t) => t.trim()) .filter(Boolean) .slice(0, 8); + const faceOk = Boolean(item.faceOk); return { id: item.guestId, name: item.name, title: item.title || "游民", city: item.city || "探索中", tags: tags.length ? tags : ["新朋友"], - avatar: item.avatar || "", + // Never paint album photos without a detected face. + avatar: faceOk ? item.avatar || "" : "", bio: item.bio || "", vibe: item.status === "here" ? "同城想出来" : item.online ? "在线" : "刚出现", online: Boolean(item.online), @@ -94,6 +96,6 @@ export function discoveryItemToMember(item: { lookingFor: item.lookingFor || "想认识同频游民", gender: (item.gender as SocialRosterMember["gender"]) || "f", availability: item.availability || "", - faceOk: Boolean(item.faceOk), + faceOk, }; } diff --git a/src/modules/social/lib/socialLive.ts b/src/modules/social/lib/socialLive.ts new file mode 100644 index 0000000..308bbb8 --- /dev/null +++ b/src/modules/social/lib/socialLive.ts @@ -0,0 +1,32 @@ +/** + * Social live UX flags — offline-first resolve from remote-config. + * UI/UX is the super-fallback: never throw, always return seed defaults. + */ +import { + DEFAULT_SOCIAL_LIVE, + resolveSocialLive, + type NomadroRemoteConfig, + type SocialLiveFlags, +} from "~/lib/remote-config"; + +export type { SocialLiveFlags }; + +export function getSocialLive( + config: NomadroRemoteConfig | null | undefined, +): SocialLiveFlags { + try { + return resolveSocialLive(config); + } catch { + return { ...DEFAULT_SOCIAL_LIVE }; + } +} + +export function socialLiveHeartbeatMs(live: SocialLiveFlags): number { + const sec = Number(live.presenceHeartbeatSec) || 25; + return Math.min(120_000, Math.max(10_000, sec * 1000)); +} + +export function socialLiveDiscoveryMs(live: SocialLiveFlags): number { + const sec = Number(live.discoveryRefreshSec) || 45; + return Math.min(300_000, Math.max(15_000, sec * 1000)); +} diff --git a/src/modules/social/lib/socialTrack.ts b/src/modules/social/lib/socialTrack.ts new file mode 100644 index 0000000..b60ef77 --- /dev/null +++ b/src/modules/social/lib/socialTrack.ts @@ -0,0 +1,32 @@ +/** + * Social live tracking — silent, never throws. + * Gated by flags.socialLive.trackLiveEvents (UI/UX still works when off). + */ +import { track } from "~/lib/analytics/track"; +import type { SocialLiveFlags } from "./socialLive"; + +export function socialTrack( + live: SocialLiveFlags | null | undefined, + name: string, + props?: Record, +): void { + try { + if (!live?.trackLiveEvents) return; + const clean: Record = { + surface: "social_live", + }; + if (props) { + for (const [k, v] of Object.entries(props)) { + if (v === undefined) continue; + clean[k] = v; + } + } + track(name, { + page: "social", + label: name, + props: clean, + }); + } catch { + /* ignore */ + } +} diff --git a/src/modules/social/lib/socialTrial.ts b/src/modules/social/lib/socialTrial.ts index 86a79f9..226a477 100644 --- a/src/modules/social/lib/socialTrial.ts +++ b/src/modules/social/lib/socialTrial.ts @@ -43,13 +43,16 @@ export function resolveTrialLimits( const raw = (config?.copy as { socialTrial?: Partial } | undefined) ?.socialTrial; const flagsOn = config?.flags?.socialTrialEnabled; + // trialLive=false → freeze to offline seed (UI still works; no remote trial thrash) + const liveOn = config?.flags?.socialLive?.trialLive !== false; + const enabledBase = + typeof flagsOn === "boolean" + ? flagsOn + : typeof raw?.enabled === "boolean" + ? raw.enabled + : DEFAULT_TRIAL_LIMITS.enabled; return { - enabled: - typeof flagsOn === "boolean" - ? flagsOn - : typeof raw?.enabled === "boolean" - ? raw.enabled - : DEFAULT_TRIAL_LIMITS.enabled, + enabled: liveOn ? enabledBase : DEFAULT_TRIAL_LIMITS.enabled, chatMessages: Math.max( 0, Number(raw?.chatMessages ?? DEFAULT_TRIAL_LIMITS.chatMessages) || 0, diff --git a/src/modules/social/lib/useSocialPresence.ts b/src/modules/social/lib/useSocialPresence.ts new file mode 100644 index 0000000..767eb8d --- /dev/null +++ b/src/modules/social/lib/useSocialPresence.ts @@ -0,0 +1,176 @@ +"use client"; + +import { useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { socialApi } from "./api"; +import { ensureGuestNick } from "./guestNick"; +import { loadJson } from "./storage"; +import { + getSocialLive, + socialLiveHeartbeatMs, + type SocialLiveFlags, +} from "./socialLive"; +import { socialTrack } from "./socialTrack"; +import type { NomadroRemoteConfig } from "~/lib/remote-config"; +import type { SocialRosterProfile } from "./types"; + +export type SocialPresencePeer = { + guestId: string; + nick: string; + city?: string; + avatar?: string; +}; + +export type SocialPresenceState = { + online: number; + peers: SocialPresencePeer[]; + cityOnline: number; + cityPeers: SocialPresencePeer[]; + fromOffline: boolean; + lastBeatAt: number; +}; + +const EMPTY: SocialPresenceState = { + online: 0, + peers: [], + cityOnline: 0, + cityPeers: [], + fromOffline: true, + lastBeatAt: 0, +}; + +const STORAGE_CHANGE = "nomadro-social-storage"; + +function subscribeProfile(cb: () => void) { + window.addEventListener(STORAGE_CHANGE, cb); + window.addEventListener("storage", cb); + return () => { + window.removeEventListener(STORAGE_CHANGE, cb); + window.removeEventListener("storage", cb); + }; +} + +function readProfile(): Pick { + const raw = loadJson>("roster", { + name: "", + title: "", + city: "", + phone: "", + linktree: "", + skills: "", + bio: "", + avatar: "", + }); + return { + name: typeof raw.name === "string" ? raw.name : "", + city: typeof raw.city === "string" ? raw.city : "", + avatar: typeof raw.avatar === "string" ? raw.avatar : "", + }; +} + +/** + * Global social presence heartbeat + who's-online snapshot. + * UI/UX fallback: never throws; offline → empty peers + fromOffline. + */ +export function useSocialPresence( + config: NomadroRemoteConfig | null | undefined, +): SocialPresenceState { + const live = getSocialLive(config); + const [state, setState] = useState(EMPTY); + const liveRef = useRef(live); + liveRef.current = live; + + const profileSnap = useSyncExternalStore( + subscribeProfile, + () => JSON.stringify(readProfile()), + () => "{}", + ); + + useEffect(() => { + if (!live.presenceEnabled) { + setState(EMPTY); + return; + } + let cancelled = false; + let timer: ReturnType | null = null; + + const beat = async () => { + if (cancelled || document.hidden) return; + const profile = readProfile(); + const nick = + (profile.name || "").trim() || ensureGuestNick() || "游民"; + const city = liveRef.current.presenceCityScope + ? (profile.city || "").trim() + : ""; + try { + const res = await socialApi.rosterPresence({ + nick, + city, + avatar: (profile.avatar || "").trim(), + softStatusSync: liveRef.current.softStatusSync, + }); + if (cancelled) return; + const next: SocialPresenceState = { + online: Number(res.online) || 0, + peers: Array.isArray(res.peers) ? res.peers : [], + cityOnline: Number(res.cityOnline) || 0, + cityPeers: Array.isArray(res.cityPeers) ? res.cityPeers : [], + fromOffline: false, + lastBeatAt: Date.now(), + }; + setState(next); + socialTrack(liveRef.current, "social_presence_beat", { + online: next.online, + cityOnline: next.cityOnline, + }); + } catch { + if (cancelled) return; + // Soft fallback: keep last good peers; mark offline for UX shell + setState((prev) => ({ + ...prev, + fromOffline: true, + lastBeatAt: Date.now(), + })); + try { + const snap = await socialApi.rosterOnline({ city, limit: 32 }); + if (cancelled) return; + setState({ + online: Number(snap.online) || 0, + peers: Array.isArray(snap.peers) ? snap.peers : [], + cityOnline: Number(snap.cityOnline) || 0, + cityPeers: Array.isArray(snap.cityPeers) ? snap.cityPeers : [], + fromOffline: true, + lastBeatAt: Date.now(), + }); + } catch { + /* keep previous */ + } + } + }; + + void beat(); + timer = setInterval( + () => void beat(), + socialLiveHeartbeatMs(liveRef.current), + ); + const onVis = () => { + if (!document.hidden) void beat(); + }; + const onOnline = () => void beat(); + document.addEventListener("visibilitychange", onVis); + window.addEventListener("online", onOnline); + return () => { + cancelled = true; + if (timer) clearInterval(timer); + document.removeEventListener("visibilitychange", onVis); + window.removeEventListener("online", onOnline); + }; + }, [live.presenceEnabled, live.presenceCityScope, live.softStatusSync, profileSnap]); + + return state; +} + +export function useSocialLiveFlags( + config: NomadroRemoteConfig | null | undefined, +): SocialLiveFlags { + return getSocialLive(config); +}