diff --git a/apps/admin/deploy/_vip_track_assets/server.py b/apps/admin/deploy/_vip_track_assets/server.py new file mode 100644 index 0000000..14328c8 --- /dev/null +++ b/apps/admin/deploy/_vip_track_assets/server.py @@ -0,0 +1,547 @@ +#!/usr/bin/env python3 +"""vip.hackrobot.cn track sidecar — SQLite + ntfy, isolated from VIP business.""" +from __future__ import annotations + +import json +import os +import sqlite3 +import threading +import time +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +PORT = int(os.environ.get("VIP_TRACK_PORT", "4011")) +BASE_DIR = Path(os.environ.get("VIP_TRACK_DIR", "/opt/vip-track")) +DB_PATH = Path(os.environ.get("VIP_TRACK_DB", str(BASE_DIR / "events.db"))) +ENV_FILE = BASE_DIR / "ntfy.env" + +def _load_env_file() -> None: + if not ENV_FILE.exists(): + return + try: + for line in ENV_FILE.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + k, v = line.split("=", 1) + k, v = k.strip(), v.strip().strip('"').strip("'") + if k and k not in os.environ: + os.environ[k] = v + except Exception: + pass + +_load_env_file() + +NTFY_BASE = os.environ.get("NTFY_BASE_URL", "https://ntfy.nomadro.cn").rstrip("/") +NTFY_TOPIC = (os.environ.get("NTFY_TOPIC") or "vip-hackrobot").strip().strip("/") +NTFY_TOKEN = (os.environ.get("NTFY_TOKEN") or "").strip() + +# health_down/up 只由 cron healthcheck.sh 推一次,避免 sidecar 再推「用户 ·」重复刷屏 +NTFY_EVENTS = { + "session_start", + "page_view", + "btn_click", + "pay_start", + "pay_success", + "pay_cancel", + "pay_fail", + "pay_pending", + "login_ok", + "login_fail", + "login_submit", + "error", + "web_vital_slow", +} +# 访问类:会话内去重,避免同人刷屏 +VISIT_EVENTS = {"session_start", "page_view"} +TITLE = { + "session_start": "用户访问", + "page_view": "浏览页面", + "btn_click": "点击", + "pay_start": "拉起支付", + "pay_success": "支付成功", + "pay_cancel": "取消支付", + "pay_fail": "支付失败", + "pay_pending": "支付确认中", + "login_ok": "登录成功", + "login_fail": "登录失败", + "login_submit": "提交登录", + "error": "前端异常", + "health_down": "站点异常", + "health_up": "站点恢复", + "web_vital_slow": "性能偏慢", +} +TAGS = { + "session_start": "eyes,globe_with_meridians", + "page_view": "eyes,globe_with_meridians", + "btn_click": "point_right,globe_with_meridians", + "pay_start": "credit_card,globe_with_meridians", + "pay_success": "moneybag,tada,globe_with_meridians", + "pay_cancel": "wave,globe_with_meridians", + "pay_fail": "warning,x,globe_with_meridians", + "pay_pending": "hourglass,globe_with_meridians", + "login_ok": "key,globe_with_meridians", + "login_fail": "key,warning,globe_with_meridians", + "login_submit": "key,globe_with_meridians", + "error": "rotating_light,globe_with_meridians", + "health_down": "rotating_light,skull", + "health_up": "white_check_mark,tada", + "web_vital_slow": "snail,chart_with_downwards_trend", +} +PRIORITY = { + "pay_success": "5", + "pay_fail": "5", + "health_down": "5", + "pay_start": "4", + "login_fail": "4", + "error": "4", + "session_start": "3", + "page_view": "2", + "btn_click": "2", + "health_up": "3", + "web_vital_slow": "3", +} + +_times: list[float] = [] +_visit_times: list[float] = [] +_seen_visit: dict[str, float] = {} +MAX_PER_MIN = 40 +MAX_VISIT_PER_MIN = 20 +VISIT_DEDUP_SEC = 600 # 同 session+事件+页 10 分钟内只推一次 +_db_lock = threading.Lock() +_stats = {"received": 0, "stored": 0, "notified": 0, "ntfy_fail": 0, "started": time.time(), "last_ntfy_err": ""} + + +def budget_ok(visit: bool = False) -> bool: + now = time.time() + while _times and _times[0] < now - 60: + _times.pop(0) + if len(_times) >= MAX_PER_MIN: + return False + if visit: + while _visit_times and _visit_times[0] < now - 60: + _visit_times.pop(0) + if len(_visit_times) >= MAX_VISIT_PER_MIN: + return False + _visit_times.append(now) + _times.append(now) + return True + + +def visit_dedup_ok(key: str) -> bool: + now = time.time() + # prune + dead = [k for k, t in _seen_visit.items() if now - t > VISIT_DEDUP_SEC] + for k in dead: + _seen_visit.pop(k, None) + if key in _seen_visit: + return False + _seen_visit[key] = now + return True + + +def short_uid(u: str) -> str: + u = (u or "").strip() + if not u: + return "-" + return ("…" + u[-8:]) if len(u) > 10 else u + + +def role_of(props: dict, identity: dict | None = None) -> tuple[str, str]: + """Return (role_key, role_cn). Prefer props from browser localStorage paidType.""" + identity = identity or {} + role = str(props.get("role") or identity.get("role") or "").strip().lower() + paid = str(props.get("paid_type") or identity.get("paid_type") or "").strip().lower() + role_cn = str(props.get("role_cn") or identity.get("role_cn") or "").strip() + if role == "vip" or paid == "vip": + return "vip", role_cn or "会员VIP" + return "guest", role_cn or "普通访客" + + +def fmt_secs(ms) -> str: + try: + v = int(ms or 0) + except Exception: + v = 0 + if v <= 0: + return "-" + s = v // 1000 + if s < 60: + return "%ds" % s + return "%dm%ds" % (s // 60, s % 60) + + +def _md_esc(v: object, limit: int = 160) -> str: + s = str(v if v is not None else "-").replace("|", "\\|").replace("\n", " ").strip() + return s[:limit] or "-" + + +def build_rich_message( + *, + ntfy_name: str, + openid: str, + session: str, + page: str, + label: str, + props: dict, + ip: str, + identity: dict | None, +) -> tuple[str, str, str, str, str]: + """title, markdown message, tags, priority, click_url — 详情尽量完整。""" + role, role_cn = role_of(props, identity) + crown = "👑会员" if role == "vip" else "👤访客" + action = TITLE.get(ntfy_name, ntfy_name) + who = "VIP" if role == "vip" else "访客" + title = "[WebVIP] / [%s] %s" % (who, action) + + email = str(props.get("email") or (identity or {}).get("email") or "").strip() + name = str(props.get("name") or (identity or {}).get("name") or "").strip() + user_id = str(props.get("user_id") or (identity or {}).get("user_id") or openid or "").strip() + device = str(props.get("device") or "-") + browser = str(props.get("browser") or "-") + screen = str(props.get("screen") or "-") + lang = str(props.get("lang") or "-") + tz = str(props.get("tz") or "-") + href = str(props.get("href") or "").strip() + ref = str(props.get("ref") or "").strip() + doc_title = str(props.get("title") or "").strip() + click_text = str(props.get("text") or label or "").strip() + el = str(props.get("el") or "").strip() + ua = str(props.get("ua") or "").strip() + alive = fmt_secs(props.get("alive_ms")) + paid = props.get("paid_type") or (identity or {}).get("paid_type") or "guest" + + lines = [ + "### %s · %s" % (crown, _md_esc(action, 80)), + "", + "- **站点** `vip.hackrobot.cn`", + "- **身份** `%s` · paidType=`%s`" % (_md_esc(role_cn, 40), _md_esc(paid, 40)), + "- **用户ID** `%s`" % _md_esc(user_id or "-"), + "- **昵称** `%s`" % _md_esc(name or "-"), + "- **邮箱** `%s`" % _md_esc(email or "-"), + "- **页面** `%s`" % _md_esc(page or "/"), + "- **标题** %s" % _md_esc(doc_title or "-"), + "- **动作** %s" % _md_esc(label or "-"), + "- **时间** `%s`" % time.strftime("%Y-%m-%d %H:%M:%S"), + "", + "| 字段 | 值 |", + "| --- | --- |", + "| 设备 | `%s / %s / %s` |" % (_md_esc(device, 40), _md_esc(browser, 40), _md_esc(screen, 40)), + "| 语言/时区 | `%s` / `%s` |" % (_md_esc(lang, 40), _md_esc(tz, 40)), + "| IP | `%s` |" % _md_esc(ip or "-", 64), + "| 会话 | `%s` |" % _md_esc(session or "-", 48), + "| 停留 | `%s` |" % _md_esc(alive, 24), + ] + if click_text and ntfy_name in ("btn_click", "pay_start", "login_submit"): + lines.append("| 点击文案 | %s |" % _md_esc(click_text, 120)) + if el: + lines.append("| 元素 | `<%s>` |" % _md_esc(el, 40)) + if href: + lines.append("| URL | %s |" % _md_esc(href, 160)) + lines.append("") + lines.append("[打开来源页](%s)" % href[:400]) + if ref: + lines.append("| 来源 | %s |" % _md_esc(ref, 140)) + if props.get("ms"): + lines.append("| 性能 | `%sms` |" % _md_esc(props.get("ms"), 24)) + if ua: + lines.append("| UA | `%s` |" % _md_esc(ua, 140)) + + tags = TAGS.get(ntfy_name, "bar_chart,globe_with_meridians") + if role == "vip": + tags = "crown," + tags + else: + tags = "bust_in_silhouette," + tags + pri = PRIORITY.get(ntfy_name, "3") + if role == "vip" and ntfy_name in ("pay_start", "pay_success", "session_start"): + try: + pri = str(max(int(pri), 4)) + except Exception: + pass + click = href if href.startswith("http") else "https://vip.hackrobot.cn/" + return title, "\n".join(lines), tags, pri, click + + +def init_db() -> None: + BASE_DIR.mkdir(parents=True, exist_ok=True) + with _db_lock: + con = sqlite3.connect(str(DB_PATH)) + try: + con.execute( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts REAL NOT NULL, + name TEXT NOT NULL, + page TEXT, + label TEXT, + openid TEXT, + session TEXT, + client TEXT, + props TEXT, + ip TEXT, + notified INTEGER DEFAULT 0 + ) + """ + ) + con.execute("CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts)") + con.execute("CREATE INDEX IF NOT EXISTS idx_events_name ON events(name)") + con.commit() + finally: + con.close() + + +def store_event( + *, + name: str, + page: str, + label: str, + openid: str, + session: str, + client: str, + props: dict, + ip: str, + notified: int, +) -> None: + with _db_lock: + con = sqlite3.connect(str(DB_PATH), timeout=2) + try: + con.execute( + "INSERT INTO events(ts,name,page,label,openid,session,client,props,ip,notified) VALUES(?,?,?,?,?,?,?,?,?,?)", + ( + time.time(), + name, + page, + label, + openid, + session, + client, + json.dumps(props, ensure_ascii=False)[:2000], + ip, + notified, + ), + ) + con.commit() + _stats["stored"] += 1 + except Exception: + pass + finally: + con.close() + + +def stats_summary() -> dict: + out = dict(_stats) + out["uptime_s"] = int(time.time() - _stats["started"]) + out["ntfy_base"] = NTFY_BASE + out["ntfy_topic"] = NTFY_TOPIC + out["ntfy_token_set"] = bool(NTFY_TOKEN) + with _db_lock: + con = sqlite3.connect(str(DB_PATH), timeout=2) + try: + row = con.execute("SELECT COUNT(*) FROM events").fetchone() + out["events_total"] = int(row[0] if row else 0) + recent = con.execute( + "SELECT name, COUNT(*) FROM events WHERE ts > ? GROUP BY name ORDER BY COUNT(*) DESC LIMIT 12", + (time.time() - 86400,), + ).fetchall() + out["last_24h"] = {k: v for k, v in recent} + except Exception as e: + out["db_error"] = str(e)[:120] + finally: + con.close() + return out + + +def publish( + title: str, + message: str, + tags: str, + priority: str, + click: str = "", +) -> bool: + if not NTFY_BASE or not NTFY_TOPIC: + return False + url = "%s/" % NTFY_BASE.rstrip("/") + try: + pri = max(1, min(5, int(priority or 3))) + except Exception: + pri = 3 + click_url = (click or "").strip()[:512] + payload = { + "topic": NTFY_TOPIC.strip().strip("/"), + "title": (title or "WebVIP")[:200], + "message": (message or "")[:3900], + "priority": pri, + "markdown": True, + "tags": [t.strip() for t in (tags or "").split(",") if t.strip()][:12], + "icon": "https://nomadro.com/icon-192.png", + } + if click_url: + payload["click"] = click_url + payload["actions"] = [ + {"action": "view", "label": "打开页面", "url": click_url, "clear": True}, + { + "action": "view", + "label": "VIP 首页", + "url": "https://vip.hackrobot.cn/", + "clear": True, + }, + ] + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + headers = {"Content-Type": "application/json"} + if NTFY_TOKEN: + headers["Authorization"] = "Bearer " + NTFY_TOKEN + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=6) as resp: + resp.read(64) + return True + except Exception as e: + _stats["ntfy_fail"] += 1 + _stats["last_ntfy_err"] = ("%s: %s" % (type(e).__name__, e))[:200] + return False + + +def maybe_ntfy_name(name: str, props: dict) -> str | None: + if name in NTFY_EVENTS: + return name + # promote slow vitals + if name == "web_vital" and (props.get("slow") in (1, "1", True) or int(props.get("ms") or 0) > 4000): + return "web_vital_slow" + return None + + +class H(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): + return + + def _cors(self): + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "Content-Type") + + def _json(self, code: int, obj: dict): + data = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self._cors() + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_OPTIONS(self): + self.send_response(204) + self._cors() + self.end_headers() + + def do_GET(self): + path = (self.path or "/").split("?", 1)[0] + if path in ("/stats", "/api/track/stats"): + # localhost-ish only + ip = self.client_address[0] if self.client_address else "" + if ip not in ("127.0.0.1", "::1"): + self._json(403, {"ok": False, "error": "local only"}) + return + self._json(200, {"ok": True, "stats": stats_summary()}) + return + if path in ("/health", "/api/track/health"): + self._json(200, {"ok": True, "service": "vip-track", "uptime_s": int(time.time() - _stats["started"])}) + return + self._json(200, {"ok": True, "service": "vip-track"}) + + def do_POST(self): + try: + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(max(0, min(n, 65536))) if n else b"{}" + body = json.loads(raw.decode("utf-8", "replace") or "{}") + except Exception: + body = {} + events = body.get("events") if isinstance(body, dict) else None + if not isinstance(events, list): + events = [] + openid = str((body or {}).get("openid") or "")[:64] if isinstance(body, dict) else "" + session = str((body or {}).get("session") or "")[:64] if isinstance(body, dict) else "" + client = str((body or {}).get("client") or "vip_web")[:32] if isinstance(body, dict) else "vip_web" + identity = (body or {}).get("identity") if isinstance(body, dict) else None + if not isinstance(identity, dict): + identity = {} + ip = self.headers.get("X-Real-IP") or self.headers.get("X-Forwarded-For") or ( + self.client_address[0] if self.client_address else "" + ) + ip = str(ip).split(",")[0].strip()[:64] + ua_hdr = (self.headers.get("User-Agent") or "")[:140] + notified = 0 + stored = 0 + for raw_ev in events[:20]: + if not isinstance(raw_ev, dict): + continue + name = str(raw_ev.get("name") or "").strip()[:64] + if not name: + continue + _stats["received"] += 1 + page = str(raw_ev.get("page") or "")[:64] + label = str(raw_ev.get("label") or "")[:160] + props = raw_ev.get("props") if isinstance(raw_ev.get("props"), dict) else {} + # merge identity defaults into props for storage/ntfy + for k in ("role", "role_cn", "paid_type", "email", "name", "user_id"): + if not props.get(k) and identity.get(k): + props[k] = identity.get(k) + if not props.get("ua") and ua_hdr: + props["ua"] = ua_hdr + ntfy_name = maybe_ntfy_name(name, props) + did_notify = 0 + if client in ("healthcheck", "probe", "deploy"): + ntfy_name = None + is_visit = ntfy_name in VISIT_EVENTS if ntfy_name else False + if ntfy_name and is_visit: + dedup_key = "%s|%s|%s|%s" % (ntfy_name, session or openid or ip, page, label[:40]) + if not visit_dedup_ok(dedup_key): + ntfy_name = None + # 同类点击短去重(30s),保留详情但不刷屏 + if ntfy_name == "btn_click": + ck = "btn|%s|%s|%s" % (session or openid or ip, page, label[:60]) + now = time.time() + last = _seen_visit.get(ck) + if last and now - last < 30: + ntfy_name = None + else: + _seen_visit[ck] = now + if ntfy_name and budget_ok(visit=is_visit): + title, message, tags, pri, click = build_rich_message( + ntfy_name=ntfy_name, + openid=openid, + session=session, + page=page, + label=label, + props=props, + ip=ip, + identity=identity, + ) + ok = publish(title, message, tags, pri, click=click) + if ok: + notified += 1 + did_notify = 1 + _stats["notified"] += 1 + # persist role into props for analytics + store_props = dict(props) + store_props["_role"] = role_of(props, identity)[0] + store_event( + name=name, + page=page, + label=label, + openid=openid, + session=session, + client=client, + props=store_props, + ip=ip, + notified=did_notify, + ) + stored += 1 + self._json(200, {"ok": True, "notified": notified, "stored": stored}) + + +if __name__ == "__main__": + init_db() + ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever() diff --git a/apps/admin/src/pages/SocialData.tsx b/apps/admin/src/pages/SocialData.tsx index a165cf4..fed360a 100644 --- a/apps/admin/src/pages/SocialData.tsx +++ b/apps/admin/src/pages/SocialData.tsx @@ -91,6 +91,35 @@ function cell(v: unknown, n = 80) { return s.length <= n ? s || '—' : `${s.slice(0, n)}…` } +/** 脏 PB:email_submit 不得显示已付/已过 */ +function joinPaidCell(it: Record): string { + const stage = String(it.stage || '') + const paid = String(it.paid ?? '') + const payload = + it.payload && typeof it.payload === 'object' && !Array.isArray(it.payload) + ? (it.payload as Record) + : {} + const price = Number(payload.priceFen) + const free = + paid === 'free' || + payload.intent === 'free' || + (Number.isFinite(price) && price <= 0) + if (stage === 'email_submit' || stage === 'pay_launched') { + return free ? '免费' : '未付' + } + if (free && stage !== 'pay_confirmed') return '免费' + if (paid === '1' || paid === 'true' || it.paid === true) return '已付' + return free ? '免费' : '未付' +} + +function joinLiveCell(it: Record): string { + const stage = String(it.stage || '') + if (stage === 'email_submit' || stage === 'pay_launched') return '未核验' + const live = String(it.livenessStatus || '') + if (live === 'verified' || stage === 'liveness_verified') return '已过' + return '未核验' +} + export default function SocialData() { const [tab, setTab] = useState('joins') const [overview, setOverview] = useState(null) @@ -346,8 +375,8 @@ export default function SocialData() { {it.stage || '—'} - {it.paid === '1' || it.paid === true ? '已付' : '未付'} - {it.livenessStatus || (it.faceOk ? 'ok' : '—')} + {joinPaidCell(it)} + {joinLiveCell(it)} {it.updatedAt || it.createdAt || '—'} ) diff --git a/apps/api/services/community_svc/services/ntfy_push.py b/apps/api/services/community_svc/services/ntfy_push.py index 93f3347..b004186 100644 --- a/apps/api/services/community_svc/services/ntfy_push.py +++ b/apps/api/services/community_svc/services/ntfy_push.py @@ -1,10 +1,14 @@ -"""ntfy push notifications (server: 127.0.0.1:2586).""" +"""ntfy push notifications — Markdown + icon + actions.""" from __future__ import annotations +from typing import Any + import httpx from community_svc.config import settings +DEFAULT_ICON = "https://nomadro.com/icon-192.png" + async def send_push( topic: str, @@ -13,19 +17,37 @@ async def send_push( *, tags: list[str] | None = None, click_url: str = "", + markdown: bool = True, + icon: str = DEFAULT_ICON, + actions: list[dict[str, Any]] | None = None, + attach: str = "", ) -> bool: if not settings.ntfy_enabled: return False base = settings.ntfy_url.rstrip("/") - url = f"{base}/{topic}" - headers: dict[str, str] = {"Title": title} - if click_url: - headers["Click"] = click_url + # Prefer JSON body so Markdown / Chinese titles work reliably. + payload: dict[str, Any] = { + "topic": topic.strip().strip("/"), + "title": (title or "Nomadro")[:200], + "message": (body or "")[:3900], + "markdown": bool(markdown), + "priority": 3, + } if tags: - headers["Tags"] = ",".join(tags) + payload["tags"] = [t for t in tags if t][:12] + if click_url: + payload["click"] = click_url[:512] + if icon: + payload["icon"] = icon[:512] + if attach: + payload["attach"] = attach[:512] + if actions: + payload["actions"] = actions[:3] + + headers: dict[str, str] = {"Content-Type": "application/json"} try: async with httpx.AsyncClient(timeout=8.0) as client: - r = await client.post(url, content=body, headers=headers) + r = await client.post(base, json=payload, headers=headers) return r.status_code < 300 except Exception: return False diff --git a/apps/api/services/ebook_svc/routers/ops_admin.py b/apps/api/services/ebook_svc/routers/ops_admin.py index 1a80c55..8252e3b 100644 --- a/apps/api/services/ebook_svc/routers/ops_admin.py +++ b/apps/api/services/ebook_svc/routers/ops_admin.py @@ -99,14 +99,46 @@ async def ntfy_status(_: str = Depends(require_admin)) -> dict: @router.post("/ntfy/test") async def ntfy_test(body: NtfyTestBody, _: str = Depends(require_admin)) -> dict: + from datetime import datetime, timezone, timedelta + + cst = timezone(timedelta(hours=8)) + now = datetime.now(cst).strftime("%Y-%m-%d %H:%M:%S") + rich = ntfy_svc.format_rich_message( + headline=f"📣 {body.title or '试推'}", + bullets=[ + ("正文", body.message or "admin 通知通路正常"), + ("时间", now), + ("来源", "admin.ops.ntfy/test"), + ], + table=[ + ("priority", str(body.priority)), + ("markdown", "on"), + ("icon", "nomadro icon-192"), + ], + links=[ + ("打开后台", "https://admin.nomadro.com/"), + ("订阅页", (settings.ntfy_base_url or "").rstrip("/") + "/" + (settings.ntfy_topic or "").strip().strip("/")), + ], + ) ok = await ntfy_svc.notify( - body.message, - title=body.title[:80], - tags=body.tags, + rich, + title=(body.title or "Nomadro 试推")[:80], + tags=body.tags or "loudspeaker,white_check_mark", priority=body.priority, + markdown=True, + click="https://admin.nomadro.com/", + actions=[ + { + "action": "view", + "label": "打开后台", + "url": "https://admin.nomadro.com/", + "clear": True, + } + ], ) return { "ok": ok, "enabled": bool(settings.ntfy_enabled), "topic": (settings.ntfy_topic or "").strip(), + "rich": True, } diff --git a/apps/api/services/ebook_svc/routers/social_ugc_admin.py b/apps/api/services/ebook_svc/routers/social_ugc_admin.py index 1d7ed92..e003e06 100644 --- a/apps/api/services/ebook_svc/routers/social_ugc_admin.py +++ b/apps/api/services/ebook_svc/routers/social_ugc_admin.py @@ -259,6 +259,20 @@ async def get_files( raise HTTPException(503, f"files unavailable: {e}") from e +@router.get("/room-archives") +async def get_room_archives( + q: str = "", + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), + _: str = Depends(require_admin), +) -> dict[str, Any]: + """语音厅静默录像列表(S3 / 本地兜底)。""" + try: + return ugc.list_room_archives(q=q, limit=limit, offset=offset) + except Exception as e: + raise HTTPException(503, f"room archives unavailable: {e}") from e + + @router.get("/coffee-bookings") async def get_coffee_bookings( q: str = "", diff --git a/apps/api/services/ebook_svc/services/config_live.py b/apps/api/services/ebook_svc/services/config_live.py index 9f15b02..02c8284 100644 --- a/apps/api/services/ebook_svc/services/config_live.py +++ b/apps/api/services/ebook_svc/services/config_live.py @@ -76,8 +76,45 @@ def notify_config_changed( return payload +def _ping_portal_notify(meta: dict[str, Any]) -> None: + """跨进程:FastAPI 写盘后立刻 ping Next /api/config/notify,门户 SSE 不等 watch。""" + import os + import urllib.error + import urllib.request + + base = ( + os.getenv("PORTAL_CONFIG_NOTIFY_URL") + or os.getenv("NEXT_CONFIG_NOTIFY_URL") + or "http://127.0.0.1:3000/api/config/notify" + ).strip() + if not base or base.lower() in ("0", "off", "false", "disabled"): + return + secret = (os.getenv("CONFIG_NOTIFY_SECRET") or "").strip() + body = json.dumps( + { + "version": meta.get("version"), + "updatedAt": meta.get("updatedAt") or "", + }, + ensure_ascii=False, + ).encode("utf-8") + headers = {"Content-Type": "application/json", "Accept": "application/json"} + if secret: + headers["X-Config-Notify-Secret"] = secret + + def _run() -> None: + try: + req = urllib.request.Request(base, data=body, headers=headers, method="POST") + with urllib.request.urlopen(req, timeout=1.5) as resp: + resp.read() + except (urllib.error.URLError, TimeoutError, OSError): + pass + + threading.Thread(target=_run, name="config-portal-ping", daemon=True).start() + + def notify_config_written(raw: dict[str, Any] | None = None) -> None: - notify_config_changed(_meta_from_raw(raw), source="write") + meta = notify_config_changed(_meta_from_raw(raw), source="write") + _ping_portal_notify(meta) def subscribe(listener: Listener) -> Callable[[], None]: diff --git a/apps/api/services/ebook_svc/services/ntfy.py b/apps/api/services/ebook_svc/services/ntfy.py index 635ea30..6972ecc 100644 --- a/apps/api/services/ebook_svc/services/ntfy.py +++ b/apps/api/services/ebook_svc/services/ntfy.py @@ -1,4 +1,4 @@ -"""把关键事件推到自建 ntfy(https://ntfy.nomadro.cn)。""" +"""把关键事件推到自建 ntfy(https://ntfy.nomadro.cn)— Markdown 富文本。""" from __future__ import annotations import logging @@ -10,6 +10,8 @@ from ebook_svc.config import settings logger = logging.getLogger(__name__) +DEFAULT_ICON = "https://nomadro.com/icon-192.png" + async def notify( message: str, @@ -17,6 +19,12 @@ async def notify( title: str = "Nomadmini", tags: str | None = None, priority: int = 3, + markdown: bool = True, + click: str | None = None, + icon: str | None = DEFAULT_ICON, + attach: str | None = None, + filename: str | None = None, + actions: list[dict[str, Any]] | None = None, ) -> bool: if not settings.ntfy_enabled: return False @@ -27,12 +35,23 @@ async def notify( payload: dict[str, Any] = { "topic": topic, - "message": message, - "title": title, + "message": (message or "")[:3900], + "title": (title or "Nomadro")[:200], "priority": max(1, min(5, int(priority))), + "markdown": bool(markdown), } if tags: - payload["tags"] = [t.strip() for t in tags.split(",") if t.strip()] + payload["tags"] = [t.strip() for t in tags.split(",") if t.strip()][:12] + if icon: + payload["icon"] = icon[:512] + if click: + payload["click"] = click[:512] + if attach: + payload["attach"] = attach[:512] + if filename: + payload["filename"] = filename[:120] + if actions: + payload["actions"] = actions[:3] headers: dict[str, str] = {"Content-Type": "application/json"} token = (settings.ntfy_token or "").strip() @@ -51,11 +70,44 @@ async def notify( return False +def _esc(value: Any, limit: int = 180) -> str: + s = str(value if value is not None else "").replace("|", "\\|").replace("\n", " ").strip() + return s[:limit] + + +def format_rich_message( + *, + headline: str, + bullets: list[tuple[str, str]] | None = None, + table: list[tuple[str, str]] | None = None, + footer: str | None = None, + links: list[tuple[str, str]] | None = None, +) -> str: + lines: list[str] = [f"### {_esc(headline)}", ""] + for k, v in bullets or []: + if not v: + continue + lines.append(f"- **{_esc(k)}** `{_esc(v)}`") + if table: + lines.extend(["", "| 字段 | 值 |", "| --- | --- |"]) + for k, v in table[:14]: + if v is None or v == "": + continue + lines.append(f"| {_esc(k)} | `{_esc(v)}` |") + if footer: + lines.extend(["", _esc(footer, 240)]) + for label, url in links or []: + if url: + lines.append(f"[{_esc(label, 40)}]({_esc(url, 400)})") + return "\n".join(lines)[:3900] + + def summarize_wx_event(root: dict[str, Any]) -> tuple[str, str, str]: """返回 (title, message, tags)。""" event = str(root.get("Event") or root.get("event") or "") msg_type = str(root.get("MsgType") or root.get("msg_type") or "").lower() - openid = str(root.get("OpenId") or root.get("FromUserName") or root.get("openid") or "")[-8:] + openid = str(root.get("OpenId") or root.get("FromUserName") or root.get("openid") or "") + openid_short = f"…{openid[-8:]}" if len(openid) > 8 else (openid or "—") if event == "xpay_goods_deliver_notify" or root.get("GoodsInfo") or root.get("OutTradeNo"): out_trade_no = root.get("OutTradeNo") or root.get("out_trade_no") or "-" @@ -64,28 +116,41 @@ def summarize_wx_event(root: dict[str, Any]) -> tuple[str, str, str]: if isinstance(gi, dict): product = str(gi.get("ProductId") or gi.get("product_id") or "") title = "支付发货" - msg = f"订单 {out_trade_no}" - if product: - msg += f" · 道具 {product}" - if openid: - msg += f" · …{openid}" + msg = format_rich_message( + headline="💰 支付发货", + bullets=[ + ("订单", str(out_trade_no)), + ("道具", product or "—"), + ("用户", openid_short), + ], + table=[(k, str(v)) for k, v in list(root.items())[:8] if k not in {"GoodsInfo"}], + ) return title, msg, "moneybag,white_check_mark" if msg_type in {"text", "image", "voice", "video", "miniprogrampage"}: content = str(root.get("Content") or root.get("Recognition") or "")[:180] title = "用户消息" - msg = content or f"收到 {msg_type}" - if openid: - msg = f"…{openid}: {msg}" + msg = format_rich_message( + headline="💬 用户消息", + bullets=[ + ("类型", msg_type), + ("用户", openid_short), + ("内容", content or f"收到 {msg_type}"), + ], + ) return title, msg, "speech_balloon" if event: title = "微信事件" - msg = event - if openid: - msg += f" · …{openid}" + msg = format_rich_message( + headline="🔔 微信事件", + bullets=[("事件", event), ("用户", openid_short)], + ) return title, msg, "bell" title = "微信推送" - msg = str(root)[:180] + msg = format_rich_message( + headline="📩 微信推送", + bullets=[("摘要", str(root)[:180])], + ) return title, msg, "incoming_envelope" diff --git a/apps/api/services/ebook_svc/services/social_ugc.py b/apps/api/services/ebook_svc/services/social_ugc.py index 913a193..6b4adc0 100644 --- a/apps/api/services/ebook_svc/services/social_ugc.py +++ b/apps/api/services/ebook_svc/services/social_ugc.py @@ -154,6 +154,10 @@ def list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, A return _pb().admin_list_files(q=q, limit=limit, offset=offset) +def list_room_archives(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: + return _pb().admin_list_room_archives(q=q, limit=limit, offset=offset) + + def list_coffee_bookings(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: return _pb().admin_list_coffee_bookings(q=q, limit=limit, offset=offset) diff --git a/apps/api/services/ebook_svc/services/track.py b/apps/api/services/ebook_svc/services/track.py index 91fa931..81df773 100644 --- a/apps/api/services/ebook_svc/services/track.py +++ b/apps/api/services/ebook_svc/services/track.py @@ -175,33 +175,129 @@ def _title(name: str, *, client: str | None = None) -> str: return f"[{ch}] {base}" +_PROP_LABEL = { + "audience": "受众", + "device": "设备", + "browser": "浏览器", + "screen": "屏幕", + "lang": "语言", + "tz": "时区", + "href": "链接", + "title": "页面标题", + "text": "文案", + "el": "元素", + "role": "角色", + "role_cn": "角色中文", + "paid_type": "付费类型", + "email": "邮箱", + "name": "昵称", + "user_id": "用户ID", + "channel": "渠道", + "popup": "弹窗", + "offline": "离线", + "amount": "金额", + "orderId": "订单", + "gateway": "网关", + "plan": "套餐", + "city": "城市", + "roomId": "房间", + "alive_ms": "停留", +} + + +def _prop_display(key: str, value: Any) -> str: + if key == "popup" and value == "douyin": + return "抖音群" + if key == "popup" and value == "wechat": + return "公众号" + if key == "offline" and value: + return "是" + if key == "channel": + return str(CLIENT_LABEL.get(str(value), value)) + if key == "alive_ms": + try: + return f"{round(float(value) / 1000)}s" + except Exception: + return str(value) + return str(value) + + def format_event_message(ev: dict[str, Any], *, openid: str | None, client: str | None) -> str: - parts = [f"用户 {_short_openid(openid)}"] + name = str(ev.get("name") or "event") + emoji = { + "pay_success": "💰", + "pay_fail": "⚠️", + "pay_start": "💳", + "pay_deliver": "📦", + "login_ok": "🔑", + "login_fail": "🔑", + "error": "🚨", + "page_view": "👀", + "app_launch": "🚀", + "join_group_show": "👥", + "join_group_open": "👥", + "wx_push": "📩", + }.get(name, "📡") + + bullets: list[tuple[str, str]] = [ + ("用户", _short_openid(openid)), + ("渠道", _channel_label(client)), + ] if ev.get("page"): - parts.append(f"页 {ev['page']}") + bullets.append(("页面", str(ev["page"]))) if ev.get("label"): - parts.append(str(ev["label"])) + bullets.append(("标签", str(ev["label"]))) + + table: list[tuple[str, str]] = [] props = ev.get("props") or {} - if isinstance(props, dict) and props: - bits = [] - for k, v in list(props.items())[:8]: - if v is None or v == "": + click = "" + if isinstance(props, dict): + for k, v in list(props.items())[:14]: + if v is None or v == "" or isinstance(v, (dict, list)): continue - if k == "popup" and v == "douyin": - bits.append("弹窗=抖音群") - elif k == "popup" and v == "wechat": - bits.append("弹窗=公众号") - elif k == "offline" and v: - bits.append("离线兜底") - elif k == "channel": - bits.append(f"渠道={CLIENT_LABEL.get(str(v), v)}") - else: - bits.append(f"{k}={v}") - if bits: - parts.append(" · ".join(bits)) - if client: - parts.append(f"[{client}]") - return " · ".join(parts)[:480] + if str(k).lower() in {"password", "token", "secret", "authorization"}: + continue + label = _PROP_LABEL.get(str(k), str(k)) + table.append((label, _prop_display(str(k), v))) + if k == "href" and str(v).startswith("http"): + click = str(v) + + links: list[tuple[str, str]] = [] + if click: + links.append(("打开来源页", click)) + links.append(("打开后台", "https://admin.nomadro.com/intl/events")) + + return ntfy_svc.format_rich_message( + headline=f"{emoji} {_title(name, client=client)}", + bullets=bullets, + table=table, + footer=None, + links=links, + ) + + +def _event_click(ev: dict[str, Any]) -> str | None: + props = ev.get("props") or {} + if isinstance(props, dict): + href = props.get("href") + if isinstance(href, str) and href.startswith("http"): + return href[:512] + return "https://admin.nomadro.com/intl/events" + + +def _event_actions(ev: dict[str, Any]) -> list[dict[str, Any]]: + click = _event_click(ev) + actions: list[dict[str, Any]] = [ + { + "action": "view", + "label": "后台事件", + "url": "https://admin.nomadro.com/intl/events", + "clear": True, + } + ] + if click and click != actions[0]["url"]: + actions.append({"action": "view", "label": "来源页", "url": click, "clear": True}) + return actions[:3] async def ingest_events( @@ -264,6 +360,9 @@ async def ingest_events( title=ntfy_title, tags=tags, priority=PRIORITY.get(name, 3), + markdown=True, + click=_event_click(ev), + actions=_event_actions(ev), ) if ok: notified += 1 diff --git a/apps/api/services/social_svc/pb_data.py b/apps/api/services/social_svc/pb_data.py index efaba06..e83dc9e 100644 --- a/apps/api/services/social_svc/pb_data.py +++ b/apps/api/services/social_svc/pb_data.py @@ -5,6 +5,7 @@ import time import uuid import hashlib import json +from pathlib import Path from typing import Any from nomadro_pb import ensure_once, get_pb, pb_quote @@ -166,6 +167,7 @@ def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, An tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8] item: dict[str, Any] = { "guestId": r.get("guest_id") or "", + "email": r.get("email") or "", "name": r.get("name") or "游民", "title": r.get("title") or "", "city": r.get("city") or "", @@ -240,8 +242,10 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: discoverable = str(discoverable).lower() not in {"0", "false", "no", "off"} onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") + email_n = str(payload.get("email") or "").strip().lower()[:160] body = { "guest_id": guest_id, + "email": email_n or str((existing or {}).get("email") or "").strip().lower()[:160], "name": str(payload.get("name") or "").strip()[:64] or "游民", "title": str(payload.get("title") or "").strip()[:80], "city": str(payload.get("city") or "").strip()[:64], @@ -283,7 +287,12 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: guest_id=guest_id, note="roster upsert before-write", ) - get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) + try: + get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) + except Exception: + # PB 尚无 email 字段时降级 + body.pop("email", None) + get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) row = get_roster(guest_id) or {} row["isFirstProfile"] = is_first archive_snapshot( @@ -346,13 +355,19 @@ def save_liveness_audit( similarity: float | None, yaw_delta: float | None, meta: dict[str, Any] | None = None, + email: str = "", ) -> dict[str, Any]: """Live capture audit only — never overwrites roster.avatar.""" init_pb() now = _now() + email_n = (email or "").strip().lower()[:160] + meta_body = dict(meta or {}) + if email_n: + meta_body["email"] = email_n item = { "id": _uid("live"), "guestId": guest_id, + "email": email_n, "frontUrl": front_url, "turnUrl": turn_url, "videoUrl": video_url, @@ -362,22 +377,26 @@ def save_liveness_audit( "status": "verified", "createdAt": now, } - rec = get_pb().create( - C_LIVENESS, - { - "guest_id": guest_id, - "avatar_url": "", # not an avatar - "front_url": front_url[:500], - "turn_url": turn_url[:500], - "video_url": (video_url or "")[:500], - "video_size": item["videoSize"], - "similarity": similarity, - "yaw_delta": yaw_delta, - "status": "verified", - "meta": meta or {}, - "created_at": now, - }, - ) + body = { + "guest_id": guest_id, + "avatar_url": "", # not an avatar + "front_url": front_url[:500], + "turn_url": turn_url[:500], + "video_url": (video_url or "")[:500], + "video_size": item["videoSize"], + "similarity": similarity, + "yaw_delta": yaw_delta, + "status": "verified", + "meta": meta_body, + "created_at": now, + } + if email_n: + body["email"] = email_n + try: + rec = get_pb().create(C_LIVENESS, body) + except Exception: + body.pop("email", None) + rec = get_pb().create(C_LIVENESS, body) item["id"] = rec.get("id") or item["id"] existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") @@ -390,22 +409,28 @@ def save_liveness_audit( "liveness_turn_url": turn_url[:500], "updated_at": now, } + if email_n: + patch["email"] = email_n if existing: get_pb().update(C_ROSTER, existing["id"], patch) else: # Placeholder only — not discoverable until profile + avatar submitted - get_pb().create( - C_ROSTER, - { - "guest_id": guest_id, - "name": "游民", - "avatar": "", - "discoverable": False, - "face_ok": False, - "status": "offline", - **patch, - }, - ) + create_body = { + "guest_id": guest_id, + "name": "游民", + "avatar": "", + "discoverable": False, + "face_ok": False, + "status": "offline", + **patch, + } + if email_n: + create_body["email"] = email_n + try: + get_pb().create(C_ROSTER, create_body) + except Exception: + create_body.pop("email", None) + get_pb().create(C_ROSTER, create_body) return item @@ -413,19 +438,24 @@ def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, init_pb() filt = f"status={pb_quote(status)}" if status else None rows = get_pb().list_all(C_LIVENESS, filter=filt, sort="-created_at", hard_limit=limit) - return [ - { - "id": r.get("id"), - "guestId": r.get("guest_id"), - "frontUrl": r.get("front_url") or "", - "turnUrl": r.get("turn_url") or "", - "videoUrl": r.get("video_url") or "", - "videoSize": r.get("video_size") or 0, - "status": r.get("status"), - "createdAt": r.get("created_at"), - } - for r in rows - ] + out: list[dict[str, Any]] = [] + for r in rows: + meta = r.get("meta") if isinstance(r.get("meta"), dict) else {} + out.append( + { + "id": r.get("id"), + "guestId": r.get("guest_id"), + "email": r.get("email") or meta.get("email") or "", + "frontUrl": r.get("front_url") or "", + "turnUrl": r.get("turn_url") or "", + "videoUrl": r.get("video_url") or "", + "videoSize": r.get("video_size") or 0, + "status": r.get("status"), + "meta": meta, + "createdAt": r.get("created_at"), + } + ) + return out def list_discovery_roster( @@ -1056,8 +1086,48 @@ def add_cafe_review( } +def _feedback_local_path() -> Path: + from social_svc.config import SOCIAL_DB_PATH + + return Path(SOCIAL_DB_PATH).resolve().parent / "feedback.json" + + +def _feedback_local_append(row: dict[str, Any]) -> None: + path = _feedback_local_path() + path.parent.mkdir(parents=True, exist_ok=True) + items: list[dict[str, Any]] = [] + if path.is_file(): + try: + raw = json.loads(path.read_text(encoding="utf-8")) + if isinstance(raw, dict) and isinstance(raw.get("items"), list): + items = list(raw["items"]) + elif isinstance(raw, list): + items = list(raw) + except Exception: + items = [] + items.insert(0, row) + path.write_text( + json.dumps({"items": items[:2000]}, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + + +def _feedback_local_list() -> list[dict[str, Any]]: + path = _feedback_local_path() + if not path.is_file(): + return [] + try: + raw = json.loads(path.read_text(encoding="utf-8")) + if isinstance(raw, dict) and isinstance(raw.get("items"), list): + return [x for x in raw["items"] if isinstance(x, dict)] + if isinstance(raw, list): + return [x for x in raw if isinstance(x, dict)] + except Exception: + return [] + return [] + + def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: - init_pb() now = _now() body = { "guest_id": guest_id, @@ -1066,15 +1136,141 @@ def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, "contact": (contact or "").strip()[:120], "created_at": now, } - rec = get_pb().create(C_FEEDBACK, body) - return { - "id": rec.get("id"), - "kind": body["kind"], - "text": body["text"], - "contact": body["contact"], - "guestId": guest_id, - "at": now, + if not body["text"]: + raise ValueError("请填写内容") + try: + init_pb() + rec = get_pb().create(C_FEEDBACK, body) + return { + "id": rec.get("id"), + "kind": body["kind"], + "text": body["text"], + "contact": body["contact"], + "guestId": guest_id, + "at": now, + "stored": "pocketbase", + } + except Exception: + # PB 挂了仍要接住反馈(本地 / 离线) + fid = f"fb_local_{uuid.uuid4().hex[:12]}" + row = { + "id": fid, + "kind": body["kind"], + "text": body["text"], + "contact": body["contact"], + "guestId": guest_id, + "at": now, + "source": "api-local", + } + _feedback_local_append(row) + return {**row, "stored": "local"} + + +_JOIN_FACE_STAGES = frozenset( + { + "profile_done", + "liveness_verified", + "liveness_failed", + "liveness_skipped", + "join_done", } +) +_JOIN_EARLY_STAGES = frozenset({"email_submit", "pay_launched"}) + + +def _sanitize_join_lead_item(item: dict[str, Any]) -> dict[str, Any]: + """Strip false 已付 / 已过 / 假「加入完成」from dirty leftovers.""" + stage = str(item.get("stage") or "") + payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} + stages: set[str] = set() + raw_stages = payload.get("stages") + if isinstance(raw_stages, list): + stages.update(str(s) for s in raw_stages if s) + hist = item.get("history") + if isinstance(hist, list): + for h in hist: + if isinstance(h, dict) and h.get("stage"): + stages.add(str(h["stage"])) + stages.add(stage) + has_face = bool(stages & _JOIN_FACE_STAGES) + paid = str(item.get("paid") or "") + price = payload.get("priceFen") + is_free_intent = ( + payload.get("intent") == "free" + or price == 0 + or (isinstance(price, (int, float)) and price <= 0) + ) + if paid == "1": + if is_free_intent and "pay_confirmed" not in stages: + paid = "free" + elif stage in _JOIN_EARLY_STAGES and "pay_confirmed" not in stages: + paid = "" + out = dict(item) + out["paid"] = paid + # 跳过自拍却写成 join_done → 纠正为 liveness_skipped(后台勿显示「加入完成」) + live = str(item.get("livenessStatus") or item.get("liveness_status") or "") + if stage == "join_done" and live != "verified" and payload.get("liveness") != "verified": + if "liveness_verified" not in stages: + out["stage"] = "liveness_skipped" + stage = "liveness_skipped" + # 当前停在只填邮箱 / 发起支付:绝不可能已核验(浏览器串号 faceOk 一律丢掉) + if stage in _JOIN_EARLY_STAGES: + out["faceOk"] = "" + out["livenessStatus"] = "none" + elif not has_face: + out["faceOk"] = "" + out["livenessStatus"] = "none" + return out + + +def _join_leads_local_path() -> Path: + from social_svc.config import SOCIAL_DB_PATH + + # Prefer portal data/join-leads.json next to repo root + root = Path(SOCIAL_DB_PATH).resolve().parents[1] + candidates = [ + root / "data" / "join-leads.json", + Path.cwd() / "data" / "join-leads.json", + ] + for p in candidates: + if p.is_file(): + return p + return candidates[0] + + +def _join_leads_local_list() -> list[dict[str, Any]]: + path = _join_leads_local_path() + if not path.is_file(): + return [] + try: + raw = json.loads(path.read_text(encoding="utf-8")) + items = raw.get("items") if isinstance(raw, dict) else raw + if not isinstance(items, list): + return [] + out: list[dict[str, Any]] = [] + for it in items: + if not isinstance(it, dict): + continue + out.append( + { + "id": it.get("id") or it.get("email") or "", + "email": it.get("email") or "", + "guestId": it.get("guestId") or it.get("guest_id") or "", + "stage": it.get("stage") or "", + "name": it.get("name") or "", + "paid": it.get("paid") or "", + "faceOk": it.get("faceOk") or it.get("face_ok") or "", + "livenessStatus": it.get("livenessStatus") or it.get("liveness_status") or "", + "ua": it.get("ua") or "", + "payload": it.get("payload") if isinstance(it.get("payload"), dict) else {}, + "createdAt": it.get("createdAt") or it.get("created_at") or "", + "updatedAt": it.get("updatedAt") or it.get("updated_at") or "", + "history": it.get("history") if isinstance(it.get("history"), list) else [], + } + ) + return out + except Exception: + return [] def upsert_join_lead( @@ -1098,52 +1294,89 @@ def upsert_join_lead( gid = (guest_id or "")[:120] stage_n = (stage or "email_submit")[:48] body_payload = payload if isinstance(payload, dict) else {} + allow_face = stage_n in _JOIN_FACE_STAGES + # email_submit 等禁止写入浏览器残留核验,避免串号 + face_in = (face_ok or "")[:8] if allow_face else "" + live_in = (liveness_status or "")[:24] if allow_face else "" + early = stage_n in {"email_submit", "pay_launched"} + paid_in = (paid or "")[:8] + intent = str(body_payload.get("intent") or "") + if early: + # 只填邮箱:最多记 free,绝不能记已付 + if paid_in == "free" or intent == "free" or body_payload.get("priceFen") == 0: + paid_in = "free" + else: + paid_in = "" snap = { "email": email_n, "guestId": gid, "stage": stage_n, "name": (name or "")[:64], - "paid": (paid or "")[:8], - "faceOk": (face_ok or "")[:8], - "livenessStatus": (liveness_status or "")[:24], + "paid": paid_in, + "faceOk": face_in, + "livenessStatus": live_in or ("none" if not allow_face else ""), "ua": (ua or "")[:240], "payload": body_payload, "at": now, } - archive_snapshot( - entity="join_leads", - entity_id=email_n, - action=stage_n, - payload=snap, - guest_id=gid, - note=f"join:{stage_n}", - ) + try: + archive_snapshot( + entity="join_leads", + entity_id=email_n, + action=stage_n, + payload=snap, + guest_id=gid, + note=f"join:{stage_n}", + ) + except Exception: + # PB 不可用时仍接受线索(门户 data/join-leads.json 已落盘) + pass lead_id = email_n try: pb = get_pb() existing = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}") + if existing and existing.get("id"): + face_val = face_in or (existing.get("face_ok") or "") if allow_face else (existing.get("face_ok") or "") + live_val = ( + live_in or (existing.get("liveness_status") or "none") + if allow_face + else (existing.get("liveness_status") or "none") + ) + else: + face_val = face_in + live_val = live_in or "none" + prev_paid = str((existing or {}).get("paid") or "") + if stage_n == "pay_confirmed" and (paid_in == "1" or not paid_in): + paid_val = "1" + elif paid_in == "free" or prev_paid == "free": + # 临时免费贯穿全程;除非真回调 pay_confirmed + paid_val = "free" + elif early: + # 只填邮箱 / 发起支付:禁止写成已付 + paid_val = "" + else: + paid_val = paid_in or prev_paid row = { "email": email_n, - "guest_id": gid, + "guest_id": gid or ((existing or {}).get("guest_id") or ""), "stage": stage_n, - "name": (name or "")[:64], + "name": (name or "")[:64] or ((existing or {}).get("name") or ""), "payload": body_payload, "ua": (ua or "")[:240], - "paid": (paid or "")[:8], - "face_ok": (face_ok or "")[:8], - "liveness_status": (liveness_status or "")[:24], + "paid": paid_val, + "face_ok": face_val, + "liveness_status": live_val, "updated_at": now, } if existing and existing.get("id"): - for k in ("paid", "face_ok", "liveness_status", "name", "guest_id"): - if not row.get(k) and existing.get(k): - row[k] = existing.get(k) old_p = existing.get("payload") if isinstance(existing.get("payload"), dict) else {} row["payload"] = { **old_p, **body_payload, "stages": list({*list(old_p.get("stages") or []), stage_n}), } + if not row.get("guest_id") and existing.get("guest_id"): + row["guest_id"] = existing.get("guest_id") rec = pb.update(C_JOIN_LEADS, str(existing["id"]), row) else: row["created_at"] = now @@ -1167,13 +1400,13 @@ def admin_list_join_leads( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Prefer live social_join_leads; fall back to social_archives entity=join_leads.""" - init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) needle = (q or "").strip().lower() items: list[dict[str, Any]] = [] try: + init_pb() rows = get_pb().list_all(C_JOIN_LEADS, sort="-updated_at", hard_limit=5000) for r in rows: items.append( @@ -1230,6 +1463,26 @@ def admin_list_join_leads( except Exception: items = [] + # Merge portal local file (dev / offline) — newer updatedAt wins per email + local_items = _join_leads_local_list() + if local_items: + by_email: dict[str, dict[str, Any]] = {} + for r in items: + em = str(r.get("email") or "").strip().lower() + if em: + by_email[em] = r + for r in local_items: + em = str(r.get("email") or "").strip().lower() + if not em: + continue + prev = by_email.get(em) + if not prev or str(r.get("updatedAt") or "") >= str(prev.get("updatedAt") or ""): + by_email[em] = r + items = list(by_email.values()) + + items = [_sanitize_join_lead_item(r) for r in items] + items.sort(key=lambda r: str(r.get("updatedAt") or ""), reverse=True) + if needle: items = [ r @@ -1557,16 +1810,13 @@ def admin_delete_gig_app(app_id: str) -> bool: def admin_list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: - init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) - rows = get_pb().list_all(C_FEEDBACK, sort="-created_at", hard_limit=5000) - total = len(rows) - page = rows[off : off + lim] - return { - "ok": True, - "total": total, - "items": [ + items: list[dict[str, Any]] = [] + try: + init_pb() + rows = get_pb().list_all(C_FEEDBACK, sort="-created_at", hard_limit=5000) + items = [ { "id": r.get("id"), "kind": r.get("kind"), @@ -1575,9 +1825,63 @@ def admin_list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: "guestId": r.get("guest_id"), "at": r.get("created_at"), } - for r in page - ], - } + for r in rows + ] + except Exception: + items = [] + # Merge API-local + portal-local offline files + seen = {str(x.get("id") or "") for x in items} + for src in (_feedback_local_list(),): + for r in src: + rid = str(r.get("id") or "") + if rid and rid in seen: + continue + if rid: + seen.add(rid) + items.append( + { + "id": r.get("id"), + "kind": r.get("kind"), + "text": r.get("text"), + "contact": r.get("contact") or "", + "guestId": r.get("guestId") or r.get("guest_id") or "", + "at": r.get("at") or r.get("created_at") or "", + } + ) + # Also portal data/feedback.json + try: + portal_fb = Path.cwd() / "data" / "feedback.json" + root_fb = Path(__file__).resolve().parents[4] / "data" / "feedback.json" + for p in (portal_fb, root_fb): + if not p.is_file(): + continue + raw = json.loads(p.read_text(encoding="utf-8")) + rows = raw.get("items") if isinstance(raw, dict) else raw + if not isinstance(rows, list): + continue + for r in rows: + if not isinstance(r, dict): + continue + rid = str(r.get("id") or "") + if rid and rid in seen: + continue + if rid: + seen.add(rid) + items.append( + { + "id": r.get("id"), + "kind": r.get("kind"), + "text": r.get("text"), + "contact": r.get("contact") or "", + "guestId": r.get("guestId") or "", + "at": r.get("at") or "", + } + ) + except Exception: + pass + items.sort(key=lambda r: str(r.get("at") or ""), reverse=True) + total = len(items) + return {"ok": True, "total": total, "items": items[off : off + lim]} def admin_delete_feedback(fid: str) -> bool: @@ -1794,6 +2098,302 @@ def admin_list_trips(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[ return _page_rows(items, limit=limit, offset=offset) +def _file_public_url(r: dict[str, Any]) -> str: + path = str(r.get("path") or "") + file_id = str(r.get("file_id") or r.get("id") or "") + if path.startswith("http://") or path.startswith("https://"): + return path + if path.startswith("/api/"): + return path + # 状态埋点占位 path(pending:// / uploading:// …)不是可播地址 + if "://" in path: + return "" + if path.startswith("/var/") or path.startswith("/www/"): + return f"/api/social/v1/files/{file_id}" if file_id else "" + return f"/api/social/v1/files/{file_id}" if file_id else "" + + +_ROOM_ARCHIVE_STATUSES = { + "pending", + "recording", + "uploading", + "uploaded", + "failed", + "denied", +} + + +def _room_archive_status_from_row(r: dict[str, Any]) -> str: + path = str(r.get("path") or "") + low = path.lower() + for st in ("pending", "recording", "uploading", "failed", "denied"): + if low.startswith(f"{st}://"): + return st + if path.startswith("http://") or path.startswith("https://") or path.startswith("/api/"): + return "uploaded" + if path.startswith("/var/") or path.startswith("/www/"): + return "uploaded" + if (r.get("size") or 0) and path: + return "uploaded" + return "pending" + + +def _room_archive_meta_path( + status: str, + session_id: str, + *, + room_id: str = "", + error: str = "", + path: str = "", + duration_sec: int = 0, + started_at: str = "", +) -> str: + st = (status or "pending").strip().lower() + if st == "uploaded" and path and ( + path.startswith("http://") + or path.startswith("https://") + or path.startswith("/api/") + or path.startswith("/var/") + or path.startswith("/www/") + ): + return path + q = [] + if room_id: + q.append(f"room={room_id[:80]}") + if error: + q.append(f"err={error[:120]}") + if duration_sec and int(duration_sec) > 0: + q.append(f"dur={int(duration_sec)}") + if started_at: + q.append(f"t0={started_at[:40]}") + tail = ("?" + "&".join(q)) if q else "" + return f"{st}://room-archive/{session_id}{tail}" + + +def _parse_meta_qs(path: str) -> dict[str, str]: + if "://" not in path or "?" not in path: + # uploaded S3 URL may embed nothing; try name later + return {} + try: + from urllib.parse import parse_qs, urlparse + + return {k: (v[0] if v else "") for k, v in parse_qs(urlparse(path).query).items()} + except Exception: + return {} + + +def _fmt_duration(sec: int) -> str: + s = max(0, int(sec or 0)) + if s < 60: + return f"{s}秒" + m, r = divmod(s, 60) + if m < 60: + return f"{m}分{r}秒" if r else f"{m}分钟" + h, m = divmod(m, 60) + return f"{h}小时{m}分" + + +def _duration_from_row(r: dict[str, Any]) -> int: + path = str(r.get("path") or "") + qs = _parse_meta_qs(path) + if qs.get("dur"): + try: + return max(0, int(qs["dur"])) + except Exception: + pass + name = str(r.get("name") or "") + # room-xxx__45s.webm + import re + + m = re.search(r"__(\d+)s(?:\.|$)", name) + if m: + try: + return max(0, int(m.group(1))) + except Exception: + pass + # live recording: estimate from t0 or created_at + t0 = qs.get("t0") or str(r.get("created_at") or "") + st = _room_archive_status_from_row(r) + if st in {"recording", "uploading", "pending"} and t0: + try: + from datetime import datetime, timezone + + raw = t0.replace("Z", "+00:00") + if raw.isdigit(): + start = datetime.fromtimestamp(int(raw) / (1000 if len(raw) > 10 else 1), tz=timezone.utc) + else: + start = datetime.fromisoformat(raw) + now = datetime.now(timezone.utc) + if start.tzinfo is None: + start = start.replace(tzinfo=timezone.utc) + return max(0, int((now - start).total_seconds())) + except Exception: + pass + return 0 + + +def _room_id_from_row(r: dict[str, Any]) -> str: + qs = _parse_meta_qs(str(r.get("path") or "")) + if qs.get("room"): + return qs["room"][:120] + name = str(r.get("name") or "") + if name.startswith("room-") and ".webm" in name: + core = name[5:].split(".webm")[0] + core = core.split("__")[0] + return core[:120] + return "" + + +def _is_room_archive_row(r: dict[str, Any]) -> bool: + name = str(r.get("name") or "").lower() + path = str(r.get("path") or "").lower() + kind = str(r.get("kind") or "").lower() + if kind in {"room-archive", "room-archive-session"}: + return True + if name.startswith("room-") or "room-archive" in name: + return True + if "room-archive" in path or "/room-archive/" in path: + return True + if kind == "video" and ("room-" in name or "meetup" in name): + return True + return False + + +def upsert_room_archive_event( + *, + session_id: str, + channel_id: str, + guest_id: str, + room_id: str = "", + status: str = "pending", + name: str = "", + mime: str = "video/webm", + size: int = 0, + path: str = "", + error: str = "", + seq: int = 0, + duration_sec: int = 0, + started_at: str = "", +) -> dict[str, Any]: + """进厅埋点 → 后台立刻可见;状态:pending/recording/uploading/uploaded/failed/denied。""" + init_pb() + now = _now() + sid = (session_id or "").strip()[:80] or _uid("arc") + st = (status or "pending").strip().lower() + if st not in _ROOM_ARCHIVE_STATUSES: + st = "pending" + gid = (guest_id or "")[:120] + ch = (channel_id or "meetup-live")[:80] + room = (room_id or "")[:120] + dur = max(0, int(duration_sec or 0)) + t0 = (started_at or "").strip()[:40] + fname = (name or "").strip()[:160] or f"room-{room or ch}-{sid}.webm" + if dur > 0 and "__" not in fname and fname.endswith(".webm"): + fname = fname[:-5] + f"__{dur}s.webm" + existing = get_pb().first(C_FILES, filter=f"file_id={pb_quote(sid)}") + prev_qs = _parse_meta_qs(str((existing or {}).get("path") or "")) + if not t0: + t0 = prev_qs.get("t0") or "" + if not dur: + try: + dur = max(0, int(prev_qs.get("dur") or 0)) + except Exception: + dur = 0 + if not t0 and st in {"pending", "recording"}: + t0 = now + final_path = _room_archive_meta_path( + st, + sid, + room_id=room, + error=error, + path=path, + duration_sec=dur, + started_at=t0, + ) + snap = { + "sessionId": sid, + "channelId": ch, + "guestId": gid, + "roomId": room, + "status": st, + "name": fname, + "size": int(size or 0), + "path": final_path, + "error": (error or "")[:240], + "seq": int(seq or 0), + "durationSec": dur, + "startedAt": t0, + "at": now, + } + try: + archive_snapshot( + entity="room_archives", + entity_id=sid, + action=st, + payload=snap, + guest_id=gid, + note=f"room-archive:{st}", + ) + except Exception: + pass + + body: dict[str, Any] = { + "file_id": sid, + "channel_id": ch, + "guest_id": gid or str((existing or {}).get("guest_id") or ""), + "kind": "room-archive", + "name": fname or str((existing or {}).get("name") or ""), + "mime": (mime or "video/webm")[:120], + "size": int(size or 0) or int((existing or {}).get("size") or 0), + "path": final_path, + } + if not existing: + body["created_at"] = now + else: + body["created_at"] = str((existing or {}).get("created_at") or now) + prev_st = _room_archive_status_from_row(existing or {}) + prev_path = str((existing or {}).get("path") or "") + if prev_st == "uploaded" and st != "uploaded": + body["path"] = prev_path + body["name"] = str((existing or {}).get("name") or body["name"]) + st = "uploaded" + final_path = prev_path + if st == "uploaded" and not ( + final_path.startswith("http") + or final_path.startswith("/api/") + or final_path.startswith("/var") + or final_path.startswith("/www") + ): + body["path"] = prev_path or final_path + # 已上传真文件时把时长烙进文件名,方便列表展示 + if st == "uploaded" and dur > 0: + nm = str(body.get("name") or "") + if nm.endswith(".webm") and "__" not in nm: + body["name"] = nm[:-5] + f"__{dur}s.webm" + + get_pb().upsert(C_FILES, filter=f"file_id={pb_quote(sid)}", payload=body) + play = "" + if st == "uploaded": + play = _file_public_url({**body, "file_id": sid}) + if "://" in play and not play.startswith("http") and not play.startswith("/api/"): + play = "" + return { + "ok": True, + "sessionId": sid, + "status": st, + "channelId": ch, + "guestId": gid, + "roomId": room, + "name": body.get("name") or fname, + "size": body["size"], + "durationSec": dur, + "durationLabel": _fmt_duration(dur) if dur else "", + "startedAt": t0, + "url": play, + "videoUrl": play, + "at": body.get("created_at") or now, + } + def admin_list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=5000) @@ -1808,7 +2408,8 @@ def admin_list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[ "name": r.get("name") or "", "mime": r.get("mime") or "", "size": r.get("size") or 0, - "url": f"/api/social/v1/files/{r.get('file_id') or r.get('id') or ''}", + "path": r.get("path") or "", + "url": _file_public_url(r), "at": r.get("created_at") or "", } for r in rows @@ -1825,6 +2426,94 @@ def admin_list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[ return _page_rows(items, limit=limit, offset=offset) +def admin_list_room_archives( + *, q: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + """语音厅静默录像:含待上传/上传中/已上传全状态。""" + init_pb() + rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=5000) + rows = [r for r in rows if _is_room_archive_row(r)] + gone = _soft_deleted_ids("files") | _soft_deleted_ids("room_archives") + needle = (q or "").strip().lower() + items = [] + for r in rows: + fid = str(r.get("file_id") or r.get("id") or "") + rid = str(r.get("id") or "") + if fid in gone or rid in gone: + continue + gid = str(r.get("guest_id") or "") + # 开发冒烟假数据不进运营列表 + if gid.startswith( + ("guest_debug", "guest_funnel", "guest_cdp", "guest_browserlike") + ) or fid.startswith(("arc_smoke_", "arc_cdp_", "arc_live_")): + continue + st = _room_archive_status_from_row(r) + dur = _duration_from_row(r) + # 空壳「上传中」超过 2 分钟视为失败(离厅未真正传完) + if st == "uploading" and int(r.get("size") or 0) <= 0: + try: + from datetime import datetime, timezone + + raw = str(r.get("created_at") or "").replace("Z", "+00:00") + start = datetime.fromisoformat(raw) + if start.tzinfo is None: + start = start.replace(tzinfo=timezone.utc) + age = (datetime.now(timezone.utc) - start).total_seconds() + if age > 120: + st = "failed" + except Exception: + pass + play = "" + if st == "uploaded": + play = _file_public_url(r) + if play.startswith("pending://") or ( + "://" in play and not play.startswith("http") and not play.startswith("/api/") + ): + play = "" + items.append( + { + "id": r.get("id"), + "fileId": r.get("file_id") or r.get("id") or "", + "sessionId": r.get("file_id") or r.get("id") or "", + "channelId": r.get("channel_id") or "", + "guestId": r.get("guest_id") or "", + "roomId": _room_id_from_row(r), + "kind": "room-archive", + "status": st, + "statusLabel": { + "pending": "待上传", + "recording": "录制中", + "uploading": "上传中", + "uploaded": "已上传", + "failed": "失败", + "denied": "未开摄像头", + }.get(st, st), + "name": r.get("name") or "", + "mime": r.get("mime") or "video/webm", + "size": r.get("size") or 0, + "durationSec": dur, + "durationLabel": _fmt_duration(dur) if dur else "", + "path": r.get("path") or "", + "url": play, + "videoUrl": play, + "at": r.get("created_at") or "", + } + ) + if needle: + items = [ + x + for x in items + if needle in str(x.get("name") or "").lower() + or needle in str(x.get("guestId") or "").lower() + or needle in str(x.get("channelId") or "").lower() + or needle in str(x.get("status") or "").lower() + or needle in str(x.get("statusLabel") or "").lower() + or needle in str(x.get("url") or "").lower() + or needle in str(x.get("roomId") or "").lower() + ] + return _page_rows(items, limit=limit, offset=offset) + + def admin_list_coffee_bookings( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: @@ -1908,20 +2597,22 @@ def admin_stats() -> dict[str, Any]: def _join_lead_public(r: dict[str, Any]) -> dict[str, Any]: - return { - "id": r.get("id"), - "email": r.get("email") or "", - "guestId": r.get("guest_id") or "", - "stage": r.get("stage") or "", - "name": r.get("name") or "", - "paid": r.get("paid") or "", - "faceOk": r.get("face_ok") or "", - "livenessStatus": r.get("liveness_status") or "", - "ua": r.get("ua") or "", - "payload": r.get("payload") or {}, - "createdAt": r.get("created_at") or "", - "updatedAt": r.get("updated_at") or "", - } + return _sanitize_join_lead_item( + { + "id": r.get("id"), + "email": r.get("email") or "", + "guestId": r.get("guest_id") or "", + "stage": r.get("stage") or "", + "name": r.get("name") or "", + "paid": r.get("paid") or "", + "faceOk": r.get("face_ok") or "", + "livenessStatus": r.get("liveness_status") or "", + "ua": r.get("ua") or "", + "payload": r.get("payload") or {}, + "createdAt": r.get("created_at") or "", + "updatedAt": r.get("updated_at") or "", + } + ) def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: @@ -1953,22 +2644,24 @@ def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: return None a0 = arch[0] payload = a0.get("payload") if isinstance(a0.get("payload"), dict) else {} - item = { - "id": a0.get("id") or key, - "email": payload.get("email") or a0.get("entity_id") or key, - "guestId": payload.get("guestId") or a0.get("guest_id") or "", - "stage": payload.get("stage") or a0.get("action") or "", - "name": payload.get("name") or "", - "paid": payload.get("paid") or "", - "faceOk": payload.get("faceOk") or "", - "livenessStatus": payload.get("livenessStatus") or "", - "ua": payload.get("ua") or "", - "payload": payload.get("payload") - if isinstance(payload.get("payload"), dict) - else payload, - "createdAt": a0.get("created_at") or "", - "updatedAt": a0.get("created_at") or "", - } + item = _sanitize_join_lead_item( + { + "id": a0.get("id") or key, + "email": payload.get("email") or a0.get("entity_id") or key, + "guestId": payload.get("guestId") or a0.get("guest_id") or "", + "stage": payload.get("stage") or a0.get("action") or "", + "name": payload.get("name") or "", + "paid": payload.get("paid") or "", + "faceOk": payload.get("faceOk") or "", + "livenessStatus": payload.get("livenessStatus") or "", + "ua": payload.get("ua") or "", + "payload": payload.get("payload") + if isinstance(payload.get("payload"), dict) + else payload, + "createdAt": a0.get("created_at") or "", + "updatedAt": a0.get("created_at") or "", + } + ) else: item = _join_lead_public(rec) @@ -1990,18 +2683,64 @@ def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: } for h in hist_rows ] + own_face_stages = { + "profile_done", + "liveness_verified", + "liveness_failed", + "liveness_skipped", + "join_done", + } + hist_actions = {str(h.get("action") or "") for h in history} + hist_actions.add(str(item.get("stage") or "")) + # 只有本线索历史里真的做过核验,才允许挂自拍/视频;join_done 可能是「稍后再说」 + own_liveness = "liveness_verified" in hist_actions + own_profile = bool(hist_actions & {"profile_done", "join_done"}) - roster = get_roster(gid) if gid else None - audits: list[dict[str, Any]] = [] - if gid: + # 花名册:优先按 email;guest 串号且 email 对不上 → 丢弃,禁止显示别人头像/自拍 + roster: dict[str, Any] | None = None + if email: try: - audits = [ - a - for a in list_liveness_audits(limit=40) - if str(a.get("guestId") or "") == gid - ][:8] + rec_by_email = pb.first(C_ROSTER, filter=f"email={pb_quote(email)}") + if rec_by_email: + roster = _roster_from_rec(rec_by_email, public=False) except Exception: - audits = [] + roster = None + if roster is None and gid: + cand = get_roster(gid) + if cand: + remail = str(cand.get("email") or "").strip().lower() + if remail and remail == email: + roster = cand + elif not remail and own_liveness: + roster = cand + else: + roster = None + + audits: list[dict[str, Any]] = [] + try: + for a in list_liveness_audits(limit=80): + meta = a.get("meta") if isinstance(a.get("meta"), dict) else {} + a_email = str(a.get("email") or meta.get("email") or "").strip().lower() + a_gid = str(a.get("guestId") or "") + if email and a_email and a_email == email: + audits.append(a) + elif own_liveness and gid and a_gid == gid and (not a_email or a_email == email): + audits.append(a) + if len(audits) >= 8: + break + except Exception: + audits = [] + + # 本线索从未核验:清空串来的 audit;roster 无本邮箱绑定也不挂媒体 + stage_now = str(item.get("stage") or "") + if not own_liveness and stage_now not in own_face_stages: + audits = [] + if roster and str(roster.get("email") or "").strip().lower() not in {"", email}: + roster = None + if roster and not own_liveness and stage_now in {"email_submit", "pay_launched"}: + # 只填邮箱阶段:绝不展示任何媒体 + roster = None + audits = [] def _abs_media(url: str) -> str: u = (url or "").strip() @@ -2021,38 +2760,49 @@ def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: return _abs_media(v.strip()) return "" - # Harvest media from lead payload + stage history (localhost dual-write often - # has relative /api/social/... URLs even when roster row is missing on US). - lead_payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} + # 只从「本邮箱」真正走过的资料/核验阶段收割媒体;email_submit 脏 payload 一律忽略 + _MEDIA_STAGES = frozenset( + {"profile_done", "liveness_verified", "join_done"} + ) harvested: dict[str, str] = { "avatar": "", "livenessFrontUrl": "", "livenessTurnUrl": "", "livenessVideoUrl": "", } - for blob in (lead_payload, *[h.get("payload") or {} for h in history]): - if not isinstance(blob, dict): - continue - nested = blob.get("payload") if isinstance(blob.get("payload"), dict) else {} - sources = (blob, nested) - if not harvested["avatar"]: - harvested["avatar"] = _pick_url( - *(s.get("avatarUrl") or s.get("avatar") for s in sources) - ) - if not harvested["livenessFrontUrl"]: - harvested["livenessFrontUrl"] = _pick_url( - *(s.get("frontUrl") or s.get("livenessFrontUrl") for s in sources) - ) - if not harvested["livenessTurnUrl"]: - harvested["livenessTurnUrl"] = _pick_url( - *(s.get("turnUrl") or s.get("livenessTurnUrl") for s in sources) - ) - if not harvested["livenessVideoUrl"]: - harvested["livenessVideoUrl"] = _pick_url( - *(s.get("videoUrl") or s.get("livenessVideoUrl") for s in sources) - ) + if own_profile or own_liveness: + harvest_blobs: list[dict[str, Any]] = [] + if str(item.get("stage") or "") in _MEDIA_STAGES: + lead_payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} + if lead_payload: + harvest_blobs.append(lead_payload) + for h in history: + if str(h.get("action") or "") not in _MEDIA_STAGES: + continue + blob = h.get("payload") + if isinstance(blob, dict): + harvest_blobs.append(blob) + for blob in harvest_blobs: + nested = blob.get("payload") if isinstance(blob.get("payload"), dict) else {} + sources = (blob, nested) + if not harvested["avatar"]: + harvested["avatar"] = _pick_url( + *(s.get("avatarUrl") or s.get("avatar") for s in sources) + ) + if own_liveness and not harvested["livenessFrontUrl"]: + harvested["livenessFrontUrl"] = _pick_url( + *(s.get("frontUrl") or s.get("livenessFrontUrl") for s in sources) + ) + if own_liveness and not harvested["livenessTurnUrl"]: + harvested["livenessTurnUrl"] = _pick_url( + *(s.get("turnUrl") or s.get("livenessTurnUrl") for s in sources) + ) + if own_liveness and not harvested["livenessVideoUrl"]: + harvested["livenessVideoUrl"] = _pick_url( + *(s.get("videoUrl") or s.get("livenessVideoUrl") for s in sources) + ) - if audits: + if own_liveness and audits: a0 = audits[0] if not harvested["livenessFrontUrl"]: harvested["livenessFrontUrl"] = _abs_media(str(a0.get("frontUrl") or "")) @@ -2061,32 +2811,108 @@ def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: if not harvested["livenessVideoUrl"]: harvested["livenessVideoUrl"] = _abs_media(str(a0.get("videoUrl") or "")) - media = { - "avatar": _abs_media((roster or {}).get("avatar") or "") or harvested["avatar"], - "livenessFrontUrl": _abs_media((roster or {}).get("livenessFrontUrl") or "") - or harvested["livenessFrontUrl"], - "livenessTurnUrl": _abs_media((roster or {}).get("livenessTurnUrl") or "") - or harvested["livenessTurnUrl"], - "livenessVideoUrl": _abs_media((roster or {}).get("livenessVideoUrl") or "") - or harvested["livenessVideoUrl"], - "audits": [ - { - **a, - "frontUrl": _abs_media(str(a.get("frontUrl") or "")), - "turnUrl": _abs_media(str(a.get("turnUrl") or "")), - "videoUrl": _abs_media(str(a.get("videoUrl") or "")), - } - for a in audits - ], - } + roster_email_ok = bool( + roster + and email + and str(roster.get("email") or "").strip().lower() == email + ) + # 只填邮箱 / 未填资料:媒体与 roster 全部清空,禁止串 Eric 等别人的脸 + early_only = stage_now in {"email_submit", "pay_launched"} or ( + not own_profile and not own_liveness + ) + if early_only: + roster = None + audits = [] + media = { + "avatar": "", + "livenessFrontUrl": "", + "livenessTurnUrl": "", + "livenessVideoUrl": "", + "audits": [], + } + else: + # 无本邮箱绑定的 roster:共用 guest 上的头像/自拍一律不信 + if not roster_email_ok: + avatar_url = "" + live_front = "" + live_turn = "" + live_video = "" + audits = [] + else: + avatar_url = harvested["avatar"] if own_profile else "" + if not avatar_url and own_profile: + avatar_url = _abs_media(str(roster.get("avatar") or "")) + live_front = harvested["livenessFrontUrl"] if own_liveness else "" + live_turn = harvested["livenessTurnUrl"] if own_liveness else "" + live_video = harvested["livenessVideoUrl"] if own_liveness else "" + if own_liveness: + live_front = live_front or _abs_media(str(roster.get("livenessFrontUrl") or "")) + live_turn = live_turn or _abs_media(str(roster.get("livenessTurnUrl") or "")) + live_video = live_video or _abs_media(str(roster.get("livenessVideoUrl") or "")) + media = { + "avatar": avatar_url, + "livenessFrontUrl": live_front, + "livenessTurnUrl": live_turn, + "livenessVideoUrl": live_video, + "audits": [ + { + **a, + "frontUrl": _abs_media(str(a.get("frontUrl") or "")), + "turnUrl": _abs_media(str(a.get("turnUrl") or "")), + "videoUrl": _abs_media(str(a.get("videoUrl") or "")), + } + for a in (audits if own_liveness and roster_email_ok else []) + ], + } + + # 时间线里早期阶段的脏 URL 也剥掉,避免详情页 timeline 再画出别人的脸 + _MEDIA_KEYS = ( + "avatar", + "avatarUrl", + "frontUrl", + "turnUrl", + "videoUrl", + "livenessFrontUrl", + "livenessTurnUrl", + "livenessVideoUrl", + ) + + def _strip_media_payload(payload: Any, *, keep: bool) -> Any: + if not isinstance(payload, dict): + return payload + out = dict(payload) + if not keep: + for k in _MEDIA_KEYS: + out.pop(k, None) + nested = out.get("payload") + if isinstance(nested, dict): + nest = dict(nested) + for k in _MEDIA_KEYS: + nest.pop(k, None) + out["payload"] = nest + return out + + clean_history = [] + for h in history: + act = str(h.get("action") or "") + keep = act in _MEDIA_STAGES and (own_profile or own_liveness) + if act in {"liveness_verified"} and not own_liveness: + keep = False + clean_history.append({**h, "payload": _strip_media_payload(h.get("payload"), keep=keep)}) + + clean_item = dict(item) + if early_only: + clean_item["payload"] = _strip_media_payload(clean_item.get("payload"), keep=False) + clean_item["faceOk"] = "" + clean_item["livenessStatus"] = "none" return { "ok": True, "entity": "joinLeads", "id": str(item.get("id") or email or key), - "item": {**item, "media": media, "roster": roster or {}}, + "item": {**clean_item, "media": media, "roster": roster or {}}, "softDeleted": False, - "history": history, + "history": clean_history, "media": media, "roster": roster or {}, } @@ -2113,6 +2939,18 @@ def admin_get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: rec = None if not rec: return None + # files / 语音厅录像:补可播 URL(S3 直链优先) + if entity == "files" and isinstance(rec, dict): + pub = _file_public_url(rec) + if pub: + rec = { + **rec, + "url": pub, + "videoUrl": pub if str(rec.get("mime") or "").startswith("video") + or str(rec.get("name") or "").lower().endswith((".webm", ".mp4", ".mov")) + or _is_room_archive_row(rec) + else rec.get("videoUrl") or "", + } hist = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote(entity)} && entity_id={pb_quote(entity_id)}", diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index b949df5..ccf294e 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -463,11 +463,14 @@ async def avatar_pose_challenge( front: UploadFile = File(...), turn: UploadFile = File(...), video: UploadFile | None = File(default=None), + email: str | None = Form(default=None), x_social_guest_id: str | None = Header(default=None), + x_social_email: str | None = Header(default=None), guest: str | None = Query(default=None), ): """Live selfie: front + turn frames + optional full camera recording for audit.""" peer = _guest(x_social_guest_id, guest) + email_n = (email or x_social_email or "").strip().lower()[:160] front_raw = await front.read() turn_raw = await turn.read() video_raw = await video.read() if video is not None else b"" @@ -527,10 +530,12 @@ async def avatar_pose_challenge( video_size=video_size, similarity=challenge.similarity, yaw_delta=challenge.yaw_delta, + email=email_n, meta={ "front_engine": challenge.front.engine if challenge.front else "", "turn_engine": challenge.turn.engine if challenge.turn else "", "has_video": bool(video_url), + "email": email_n, }, ) roster = store.get_roster(peer) or {} @@ -619,11 +624,62 @@ def liveness_audits( } +class RoomArchiveEventIn(BaseModel): + sessionId: str = Field(min_length=4, max_length=80) + channelId: str = Field(default="meetup-live", max_length=80) + roomId: str = Field(default="", max_length=120) + status: str = Field(default="pending", max_length=24) + name: str = Field(default="", max_length=160) + mime: str = Field(default="video/webm", max_length=120) + size: int = Field(default=0, ge=0) + path: str = Field(default="", max_length=800) + error: str = Field(default="", max_length=240) + seq: int = Field(default=0, ge=0) + durationSec: int = Field(default=0, ge=0) + startedAt: str = Field(default="", max_length=40) + + +@router.post("/room-archives/events") +async def room_archive_event( + body: RoomArchiveEventIn, + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + """语音厅埋点:进厅即落库,后台立刻出「待上传/上传中/已上传」。""" + peer = _guest(x_social_guest_id, guest) + + def persist(): + store.init_db() + return store.upsert_room_archive_event( + session_id=body.sessionId, + channel_id=body.channelId or "meetup-live", + guest_id=peer, + room_id=body.roomId, + status=body.status, + name=body.name, + mime=body.mime, + size=body.size, + path=body.path, + error=body.error, + seq=body.seq, + duration_sec=body.durationSec, + started_at=body.startedAt, + ) + + try: + return await run_in_threadpool(persist) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception as exc: + raise HTTPException(status_code=503, detail=f"room archive event failed: {exc}") from exc + + @router.post("/channels/{channel_id}/upload") async def upload_file( channel_id: str, file: UploadFile = File(...), kind: str = Form(default="file"), + session_id: str = Form(default=""), x_social_guest_id: str | None = Header(default=None), guest: str | None = Query(default=None), ): @@ -635,6 +691,8 @@ async def upload_file( raise HTTPException(status_code=413, detail="file too large") mime = file.content_type or "application/octet-stream" guessed = kind + if guessed in {"room-archive", "meetup-archive"}: + guessed = "video" if guessed == "file": if mime.startswith("image/"): guessed = "image" @@ -643,9 +701,80 @@ async def upload_file( elif mime.startswith("audio/"): guessed = "audio" + sid = (session_id or "").strip()[:80] + + # 语音/视频厅静默存档 → SeaweedFS S3;元数据 path 写公网 URL + if kind in {"room-archive", "meetup-archive"} or ( + guessed == "video" and (file.filename or "").startswith("room-") + ): + if sid: + try: + store.init_db() + store.upsert_room_archive_event( + session_id=sid, + channel_id=channel_id, + guest_id=peer, + status="uploading", + name=file.filename or "room-archive.webm", + mime=mime if mime.startswith("video/") else "video/webm", + size=len(raw), + ) + except Exception: + pass + + def persist_s3(): + from social_svc.s3_upload import upload_bytes + + up = upload_bytes( + raw, + filename=file.filename or f"room-{channel_id}.webm", + content_type=mime if mime.startswith("video/") else "video/webm", + purpose="room-archive", + guest_id=peer, + max_size=SOCIAL_UPLOAD_MAX_BYTES, + ) + store.init_db() + file_id = sid or f"file_{int(__import__('time').time() * 1000)}_{peer[:8]}" + return store.upsert_room_archive_event( + session_id=file_id, + channel_id=channel_id, + guest_id=peer, + status="uploaded", + name=file.filename or "room-archive.webm", + mime=up.content_type, + size=up.size, + path=up.url, + ) | { + "id": file_id, + "kind": "room-archive", + "mime": up.content_type, + "size": up.size, + "url": up.url, + "storage": up.storage, + "object_key": up.object_key, + } + + try: + return await run_in_threadpool(persist_s3) + except ValueError as exc: + if sid: + try: + store.upsert_room_archive_event( + session_id=sid, + channel_id=channel_id, + guest_id=peer, + status="failed", + error=str(exc)[:240], + ) + except Exception: + pass + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception: + pass # fall through to local persist + def persist(): store.init_db() - return store.save_upload( + saved = store.save_upload( channel_id, peer, kind=guessed, @@ -653,6 +782,22 @@ async def upload_file( mime=mime, data=raw, ) + if sid or kind in {"room-archive", "meetup-archive"} or ( + file.filename or "" + ).startswith("room-"): + file_id = sid or str(saved.get("id") or "") + if file_id: + return store.upsert_room_archive_event( + session_id=file_id, + channel_id=channel_id, + guest_id=peer, + status="uploaded", + name=file.filename or "room-archive.webm", + mime=mime, + size=len(raw), + path=str(saved.get("url") or saved.get("path") or ""), + ) | saved + return saved try: return await run_in_threadpool(persist) @@ -666,7 +811,12 @@ def get_file(file_id: str): meta = store.get_file(file_id) if not meta: raise HTTPException(status_code=404, detail="file not found") - path = Path(meta["path"]) + stored = str(meta.get("path") or "") + if stored.startswith("http://") or stored.startswith("https://"): + from fastapi.responses import RedirectResponse + + return RedirectResponse(stored, status_code=302) + path = Path(stored) if not path.is_file(): raise HTTPException(status_code=404, detail="file missing") return FileResponse( diff --git a/apps/api/services/social_svc/s3_upload.py b/apps/api/services/social_svc/s3_upload.py index 889352c..3642302 100644 --- a/apps/api/services/social_svc/s3_upload.py +++ b/apps/api/services/social_svc/s3_upload.py @@ -70,6 +70,8 @@ def _object_key(filename: str, purpose: str, guest_id: str) -> str: allow_video = (purpose or "").startswith("liveness") or purpose in { "liveness-video", "audit-video", + "room-archive", + "meetup-archive", } if suffix in img_ok: pass @@ -114,6 +116,8 @@ def upload_bytes( allow_video = (purpose or "").startswith("liveness") or purpose in { "liveness-video", "audit-video", + "room-archive", + "meetup-archive", } # Browser FormData Blob parts often arrive as application/octet-stream if ctype.startswith("image/"): @@ -159,11 +163,15 @@ def upload_bytes( # Local fallback (dev / S3 off / S3 error) # Live audit assets never land in avatars/ sub = ( - "liveness" - if allow_video - or ctype.startswith("video/") - or (purpose or "").startswith("liveness") - else "avatars" + "room-archive" + if (purpose or "") in {"room-archive", "meetup-archive"} + else ( + "liveness" + if allow_video + or ctype.startswith("video/") + or (purpose or "").startswith("liveness") + else "avatars" + ) ) path = SOCIAL_UPLOAD_DIR / sub / Path(key).name path.parent.mkdir(parents=True, exist_ok=True) diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 200a2c4..4af266a 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -812,6 +812,7 @@ def save_liveness_audit( similarity: float | None, yaw_delta: float | None, meta: dict[str, Any] | None = None, + email: str = "", ) -> dict[str, Any]: """Live capture audit only — never overwrites roster.avatar.""" from social_svc import pb_data @@ -825,6 +826,7 @@ def save_liveness_audit( similarity=similarity, yaw_delta=yaw_delta, meta=meta, + email=email, ) @@ -867,6 +869,41 @@ def upsert_join_lead( ) +def upsert_room_archive_event( + *, + session_id: str, + channel_id: str, + guest_id: str, + room_id: str = "", + status: str = "pending", + name: str = "", + mime: str = "video/webm", + size: int = 0, + path: str = "", + error: str = "", + seq: int = 0, + duration_sec: int = 0, + started_at: str = "", +) -> dict: + from social_svc import pb_data + + return pb_data.upsert_room_archive_event( + session_id=session_id, + channel_id=channel_id, + guest_id=guest_id, + room_id=room_id, + status=status, + name=name, + mime=mime, + size=size, + path=path, + error=error, + seq=seq, + duration_sec=duration_sec, + started_at=started_at, + ) + + def add_gig_app( gig_id: str, name: str, diff --git a/apps/com/admin/src/App.tsx b/apps/com/admin/src/App.tsx index b909608..91aaf3b 100644 --- a/apps/com/admin/src/App.tsx +++ b/apps/com/admin/src/App.tsx @@ -15,6 +15,7 @@ const Social = lazy(() => import('./pages/Social')) const SocialDetail = lazy(() => import('./pages/SocialDetail')) const Blog = lazy(() => import('./pages/Blog')) const Operations = lazy(() => import('./pages/Operations')) +const Pricing = lazy(() => import('./pages/Pricing')) import LaneHub, { type LaneKey } from './pages/LaneHub' /** @@ -78,6 +79,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -88,6 +90,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -105,6 +108,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> @@ -123,6 +127,7 @@ export default function App() { } /> + } /> } /> } /> } /> diff --git a/apps/com/admin/src/components/WebLayout.tsx b/apps/com/admin/src/components/WebLayout.tsx index fc332bd..20a277a 100644 --- a/apps/com/admin/src/components/WebLayout.tsx +++ b/apps/com/admin/src/components/WebLayout.tsx @@ -4,11 +4,18 @@ import { clearToken } from '../api/client' import { writeLane } from '../lib/lane' import type { LaneKey } from '../pages/LaneHub' -type NavLinkItem = { to: string; end?: boolean; label: string; hint?: string } +type NavLinkItem = { + to: string + end?: boolean + label: string + ico?: string + hint?: string + accent?: boolean +} type NavGroup = { id: string; label: string; items: NavLinkItem[] } const LANE_META: Record = { - cn: { title: '中文', mark: '中', sub: '微信 · zpay' }, + cn: { title: '中文', mark: '中', sub: '微信 · zpay / xpay' }, intl: { title: '国际', mark: 'EN', sub: 'English · Creem' }, } @@ -17,69 +24,73 @@ function buildNav(lane: LaneKey): NavGroup[] { const s = `${p}/social` return [ { - id: 'today', - label: '今日', + id: 'home', + label: '工作台', items: [ - { to: `${p}/operations`, label: '服务与资源', hint: '实时' }, - { to: `${s}/overview`, end: true, label: '指挥台', hint: '总览' }, - { to: `${s}/joins`, label: '加入线索' }, - { to: `${s}/liveness`, label: '自拍确认' }, - { to: `${s}/reports`, label: '举报' }, + { to: `${s}/overview`, end: true, label: '指挥台', ico: '◈', hint: '总览' }, + { to: `${p}/operations`, label: '服务健康', ico: '◎', hint: '实时' }, ], }, { - id: 'people', - label: '人', - items: [{ to: `${s}/roster`, label: '花名册' }], - }, - { - id: 'content', - label: '内容', + id: 'queue', + label: '审核队列', items: [ - { to: `${s}/messages`, label: '聊天' }, - { to: `${s}/reviews`, label: '咖啡馆评价' }, - { to: `${s}/meetupReviews`, label: '约聊评价' }, - { to: `${s}/gigs`, label: '接单' }, - { to: `${s}/skills`, label: '技能交换' }, - { to: `${s}/coffee`, label: '咖啡预约' }, - { to: `${s}/trips`, label: '行程' }, - { to: `${s}/feedback`, label: '反馈' }, + { to: `${s}/joins`, label: '加入线索', ico: '入' }, + { to: `${s}/liveness`, label: '自拍确认', ico: '拍' }, + { to: `${s}/roomArchives`, label: '语音厅录像', ico: '录', hint: 'S3' }, + { to: `${s}/reports`, label: '举报', ico: '报' }, ], }, { - id: 'safety', - label: '安全', + id: 'community', + label: '社区', items: [ - { to: `${s}/blocks`, label: '拉黑' }, - { to: `${s}/files`, label: '上传文件' }, - { to: `${s}/archives`, label: '存档' }, + { to: `${s}/roster`, label: '花名册', ico: '人' }, + { to: `${s}/messages`, label: '聊天', ico: '聊' }, + { to: `${s}/gigs`, label: '接单', ico: '单' }, + { to: `${s}/skills`, label: '技能交换', ico: '技' }, + { to: `${s}/coffee`, label: '咖啡预约', ico: '咖' }, + { to: `${s}/trips`, label: '行程', ico: '程' }, + { to: `${s}/reviews`, label: '咖啡馆评价', ico: '评' }, + { to: `${s}/meetupReviews`, label: '约聊评价', ico: '约' }, + { to: `${s}/feedback`, label: '反馈', ico: '馈' }, ], }, { - id: 'growth', - label: '增长', + id: 'monetize', + label: '变现', items: [ - { to: `${p}/switches`, label: '价格与开关' }, - { to: `${p}/blog`, label: 'Nomad Blog' }, - { to: `${s}/catalog`, label: '目录配置' }, - { to: `${p}/audience`, label: '受众设置' }, + { to: `${p}/pricing`, label: '动态价格', ico: '¥', hint: '主控', accent: true }, + { to: `${p}/switches`, label: '页面开关', ico: '开' }, + { to: `${p}/audience`, label: '受众设置', ico: '众' }, + { to: `${s}/catalog`, label: '目录配置', ico: '录' }, ], }, { id: 'biz', label: '经营', items: [ - { to: `${p}/orders`, label: '订单' }, - { to: `${p}/users`, label: '用户' }, + { to: `${p}/orders`, label: '订单', ico: '订' }, + { to: `${p}/users`, label: '用户', ico: '户' }, + { to: `${p}/blog`, label: 'Nomad Blog', ico: '文' }, + ], + }, + { + id: 'safety', + label: '风控', + items: [ + { to: `${s}/blocks`, label: '拉黑', ico: '黑' }, + { to: `${s}/files`, label: '上传文件', ico: '件' }, + { to: `${s}/archives`, label: '存档', ico: '档' }, ], }, { id: 'ops', - label: '运维', + label: '系统', items: [ - { to: `${p}/events`, label: '埋点' }, - { to: `${p}/ntfy`, label: '通知' }, - { to: `${p}/docs`, label: '部署' }, + { to: `${p}/events`, label: '埋点', ico: '点' }, + { to: `${p}/ntfy`, label: '通知', ico: '知' }, + { to: `${p}/docs`, label: '部署', ico: '署' }, ], }, ] @@ -93,7 +104,7 @@ function titleFromPath(lane: LaneKey, pathname: string) { return hit?.label || '指挥台' } -/** 社区优先运营壳:分组侧栏 + 顶栏受众切换 */ +/** 社区优先运营壳:变现独立 · 审核优先 · 分组侧栏 */ export default function WebLayout() { const nav = useNavigate() const { pathname } = useLocation() @@ -106,8 +117,15 @@ export default function WebLayout() { const searchRef = useRef(null) const [online, setOnline] = useState(navigator.onLine) const [theme, setTheme] = useState(() => document.documentElement.dataset.theme || 'dark') - const visibleGroups = groups.map(group => ({ ...group, items: group.items.filter(item => - `${group.label} ${item.label}`.toLowerCase().includes(query.trim().toLowerCase())) })).filter(group => group.items.length) + const q = query.trim().toLowerCase() + const visibleGroups = groups + .map((group) => ({ + ...group, + items: group.items.filter((item) => + `${group.label} ${item.label} ${item.hint || ''}`.toLowerCase().includes(q), + ), + })) + .filter((group) => group.items.length) const pageTitle = titleFromPath(lane, pathname) useEffect(() => { @@ -119,7 +137,9 @@ export default function WebLayout() { const keydown = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false) if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') { - event.preventDefault(); setOpen(window.matchMedia('(max-width: 860px)').matches); searchRef.current?.focus() + event.preventDefault() + setOpen(window.matchMedia('(max-width: 860px)').matches) + searchRef.current?.focus() } } window.addEventListener('online', update) @@ -155,10 +175,18 @@ export default function WebLayout() { else main?.removeAttribute('inert') const trap = (event: KeyboardEvent) => { if (event.key !== 'Tab' || !open) return - const elements = Array.from(document.querySelectorAll('.com-topbar-menu, .com-side button, .com-side a, .com-side input')).filter(el => !el.hasAttribute('disabled') && el.offsetParent !== null) - const first = elements[0], last = elements[elements.length - 1] - if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus() } - else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() } + const elements = Array.from( + document.querySelectorAll('.com-topbar-menu, .com-side button, .com-side a, .com-side input'), + ).filter((el) => !el.hasAttribute('disabled') && el.offsetParent !== null) + const first = elements[0] + const last = elements[elements.length - 1] + if (event.shiftKey && document.activeElement === first) { + event.preventDefault() + last?.focus() + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault() + first?.focus() + } } document.addEventListener('keydown', trap) return () => { @@ -176,14 +204,17 @@ export default function WebLayout() { function switchLane(next: LaneKey) { if (next === lane) return writeLane(next) - // Detail IDs are tied to their audience; enter the list when switching lanes. - const rest = pathname.replace(/^\/(cn|intl)/, '').replace(/(\/social\/[^/]+)\/[^/]+$/, '$1') || '/social/overview' + const rest = + pathname.replace(/^\/(cn|intl)/, '').replace(/(\/social\/[^/]+)\/[^/]+$/, '$1') || + '/social/overview' nav(`/${next}${rest.startsWith('/') ? rest : `/${rest}`}`) } return (
- @@ -260,20 +278,47 @@ export default function WebLayout() {

{meta.sub}

-
setQuery(e.target.value)} />
+ + + + ¥ + + + 动态价格 + 免费 / 付费一键切换 + + + +
+ setQuery(e.target.value)} + /> +
- - + {theme === 'dark' ? '浅色模式' : '深色模式'} + + 打开前台 ↗
diff --git a/apps/com/admin/src/lib/useConfigLive.ts b/apps/com/admin/src/lib/useConfigLive.ts index f0e8f49..e4cf488 100644 --- a/apps/com/admin/src/lib/useConfigLive.ts +++ b/apps/com/admin/src/lib/useConfigLive.ts @@ -30,7 +30,7 @@ export function useConfigLive() { }) } void poll() - const interval = window.setInterval(() => void poll(), 15000) + const interval = window.setInterval(() => void poll(), 2000) const refresh = () => void poll() window.addEventListener('online', refresh) document.addEventListener('visibilitychange', refresh) diff --git a/apps/com/admin/src/pages/Docs.tsx b/apps/com/admin/src/pages/Docs.tsx index ad89353..f417c8f 100644 --- a/apps/com/admin/src/pages/Docs.tsx +++ b/apps/com/admin/src/pages/Docs.tsx @@ -15,7 +15,10 @@ export default function Docs() { /cn · /intl — 受众模块总览与本轨开关
  • - …/switches — 页面 / flag / VIP / 文案(remote-config) + …/pricing — 动态价格(免费/付费 · 体验次数 · 支付开关) +
  • +
  • + …/switches — 页面 / flag / VIP 区块 / 文案(remote-config)
  • …/social — 游民社区 UGC(聊天 / 花名册 / 评价 / 接单 / 反馈) diff --git a/apps/com/admin/src/pages/LaneHub.tsx b/apps/com/admin/src/pages/LaneHub.tsx index e72088a..73aa606 100644 --- a/apps/com/admin/src/pages/LaneHub.tsx +++ b/apps/com/admin/src/pages/LaneHub.tsx @@ -144,9 +144,10 @@ export default function LaneHub({ lane }: { lane: LaneKey }) { const tools = [ { to: `/${lane}/social/overview`, ico: '◈', title: '指挥台', desc: '加入 / 自拍 / 举报优先' }, - { to: `/${lane}/switches`, ico: '⚡', title: '价格与开关', desc: '免费体验 · VIP 价格 · 页面' }, + { to: `/${lane}/pricing`, ico: '¥', title: '动态价格', desc: '免费 / 付费一键切换 · 体验次数' }, + { to: `/${lane}/switches`, ico: '开', title: '页面开关', desc: '模块显隐 · VIP 入口 · 文案' }, { to: `/${lane}/blog`, ico: '✎', title: 'Nomad Blog', desc: '文章显隐 / 置顶' }, - { to: `/${lane}/orders`, ico: '¥', title: '订单', desc: '支付与发货' }, + { to: `/${lane}/orders`, ico: '订', title: '订单', desc: '支付与发货' }, { to: `/${lane}/users`, ico: '◎', title: '用户', desc: '解锁与干预' }, { to: `/${lane}/events`, ico: '◉', title: '埋点', desc: '行为回放' }, { to: `/${lane}/ntfy`, ico: '♪', title: '通知', desc: 'ntfy 试推' }, diff --git a/apps/com/admin/src/pages/MediaValue.tsx b/apps/com/admin/src/pages/MediaValue.tsx index 22fb87a..3029667 100644 --- a/apps/com/admin/src/pages/MediaValue.tsx +++ b/apps/com/admin/src/pages/MediaValue.tsx @@ -25,8 +25,8 @@ export function looksLikeUrl(v: unknown): v is string { export function resolveMediaUrl(raw: string): string { const s = raw.trim() if (s.startsWith('data:') || s.startsWith('https://') || s.startsWith('http://')) return s - // social uploads / challenge files live on api.nomadro.com, not admin origin - if (s.startsWith('/api/social/')) return `https://api.nomadro.com${s}` + // social IM / 录像挂在门户同域,不在 api.nomadro.com + if (s.startsWith('/api/social/')) return `https://nomadro.com${s}` if (s.startsWith('/')) { const base = API_BASE || (typeof window !== 'undefined' ? window.location.origin : '') return `${base}${s}` diff --git a/apps/com/admin/src/pages/Ntfy.tsx b/apps/com/admin/src/pages/Ntfy.tsx index 553cbdd..fcc2a88 100644 --- a/apps/com/admin/src/pages/Ntfy.tsx +++ b/apps/com/admin/src/pages/Ntfy.tsx @@ -12,7 +12,9 @@ type NtfyStatus = { export default function Ntfy() { const [status, setStatus] = useState(null) const [title, setTitle] = useState('[WebAdmin] 试推') - const [message, setMessage] = useState('admin.nomadro.com 通知通路正常') + const [message, setMessage] = useState( + 'admin.nomadro.com 通知通路正常\n\n会以 Markdown 富文本推送(图标 / 表格 / 操作按钮)。', + ) const [loading, setLoading] = useState(true) const [busy, setBusy] = useState(false) const [err, setErr] = useState('') @@ -55,7 +57,7 @@ export default function Ntfy() {

    ntfy 通知

    - 查看通知通路状态;关键埋点和支付事件由服务端推送。 + 关键埋点 / 支付事件推 Markdown 富文本(图标、表格、点击跳转、操作按钮)。

    + + ) : null} + +
    +
    + 线上生效价 + {formatYuan(liveFen)} +

    + {isFree + ? '免费模式:不拉支付,前台临时放行;切回付费后未开通用户仍须付费。' + : `${liveFen} 分 · 门户 / VIP / 游民加入共用此价`} +

    +
    +
    +
    + 按钮预览 + {cfg.copy?.vipCta || (isFree ? '免费加入' : `立即加入 · ${formatYuan(liveFen)}`)} +
    +
    +
    + 支付总开关 +

    关闭后隐藏付费 CTA

    +
    + void patch({ flags: { payEnabled: v } }, v ? '支付已开启' : '支付已关闭')} + /> +
    +
    +
    + +
    +
    +
    +

    一键改价

    +

    点档位或手填金额,再点保存。前台实时吃新价。

    +
    +
    + +
    + {PRESETS.map((p) => { + const on = priceYuan === p.yuan + return ( + + ) + })} +
    + +
    + + + +
    + +
    + + +
    +
    + +
    +
    +
    +

    游民社区 · 免费体验

    +

    + 未加入可先试用;次数用完再引导付费。已付费且资料+自拍通过的用户不限次。 +

    +
    +
    +
    +
    + 开启体验次数限制 +

    关闭=未付费也可无限用(不推荐上线)

    +
    + setTrialDraft((d) => ({ ...d, enabled: v }))} + /> +
    +
    + {( + [ + ['chatMessages', '群聊可发句数'], + ['dateViews', '约会可看人数'], + ['coffeeBookings', '咖啡聊可约次数'], + ['mapOpens', '地图可打开次数'], + ] as const + ).map(([key, label]) => ( + + ))} +
    +
    + +
    +
    + + ) +} diff --git a/apps/com/admin/src/pages/Social.tsx b/apps/com/admin/src/pages/Social.tsx index 6144e25..23e65a5 100644 --- a/apps/com/admin/src/pages/Social.tsx +++ b/apps/com/admin/src/pages/Social.tsx @@ -13,6 +13,8 @@ import { SECTION_TITLE, type SectionKey, fmtTime, + joinLivenessLabel, + joinPaidLabel, joinStageLabel, joinStageTone, pickId, @@ -185,10 +187,13 @@ export default function Social() { } }, []) - const loadList = useCallback(async () => { + const loadList = useCallback(async (opts?: { silent?: boolean }) => { if (section === 'overview') return - setLoading(true) - setErr('') + const silent = Boolean(opts?.silent) + if (!silent) { + setLoading(true) + setErr('') + } try { if (section === 'catalog') { const data = await api<{ catalogs?: Record }>( @@ -214,11 +219,13 @@ export default function Social() { setItems(Array.isArray(data.items) ? data.items : []) setTotal(Number(data.total || 0)) } catch (e: unknown) { - setErr(e instanceof Error ? e.message : '加载失败') - setItems([]) - setTotal(0) + if (!silent) { + setErr(e instanceof Error ? e.message : '加载失败') + setItems([]) + setTotal(0) + } } finally { - setLoading(false) + if (!silent) setLoading(false) } }, [section, q, offset]) @@ -240,6 +247,15 @@ export default function Social() { void loadList() }, [loadList]) + // 语音厅录像:每 3s 静默刷新状态(录制中/上传中 → 已上传) + useEffect(() => { + if (section !== 'roomArchives') return + const tick = window.setInterval(() => { + void loadList({ silent: true }) + }, 3000) + return () => window.clearInterval(tick) + }, [section, loadList]) + const donutSegs = useMemo(() => { const c = stats?.counts || overview?.counts || {} const palette = [ @@ -417,7 +433,12 @@ export default function Social() {

    Today

    先处理这几件事

    -

    加入、自拍、举报优先;其余内容按需下钻。

    +

    + 加入、自拍、举报优先。改价走侧栏「动态价格」→{' '} + { e.preventDefault(); navigate(`/${lane}/pricing`) }}> + 打开定价 + +

    {( @@ -733,11 +754,13 @@ export default function Social() { 操作 ) : null} - {section === 'files' ? ( + {section === 'files' || section === 'roomArchives' ? ( - 文件名 + {section === 'roomArchives' ? '录像' : '文件名'} + {section === 'roomArchives' ? 状态 : null} + {section === 'roomArchives' ? 时长 : null} 类型 - 频道 + 频道 / 厅 访客 时间 操作 @@ -842,25 +865,24 @@ export default function Social() { - {joinStageLabel(row.stage)} + {joinStageLabel(row.stage, row)} - {row.paid === '1' || row.paid === true ? ( - 已付 - ) : ( - 未付 - )} + {(() => { + const label = joinPaidLabel(row) + if (label === '已付') + return 已付 + if (label === '免费') + return 免费 + return 未付 + })()} - {String(row.livenessStatus || '') === 'verified' || - row.faceOk === '1' || - row.faceOk === true ? ( + {joinLivenessLabel(row) === '已过' ? ( 已过 ) : ( - - {String(row.livenessStatus || '未核验')} - + 未核验 )} {fmtTime(row.updatedAt || row.updated_at || row.createdAt)} @@ -985,11 +1007,62 @@ export default function Social() { {fmtTime(row.at)} ) : null} - {section === 'files' ? ( + {section === 'files' || section === 'roomArchives' ? ( <> {short(row.name || row.fileId, 28)} + {section === 'roomArchives' && row.url ? ( +
    + S3 / 可播放 +
    + ) : null} + {section === 'roomArchives' && row.roomId ? ( +
    + 厅 {String(row.roomId)} +
    + ) : null} + {section === 'roomArchives' ? ( + + + {String( + row.statusLabel || + ({ + pending: '待上传', + recording: '录制中', + uploading: '上传中', + uploaded: '已上传', + failed: '失败', + denied: '未开摄像头', + } as Record)[String(row.status || '')] || + row.status || + '—', + )} + + + ) : null} + {section === 'roomArchives' ? ( + + + {String( + row.durationLabel || + (Number(row.durationSec) > 0 + ? `${row.durationSec}秒` + : '—'), + )} + + + ) : null} {String(row.kind || row.mime || '—')} {short(row.channelId, 12)} diff --git a/apps/com/admin/src/pages/SocialDetail.tsx b/apps/com/admin/src/pages/SocialDetail.tsx index 9528350..fbe54b4 100644 --- a/apps/com/admin/src/pages/SocialDetail.tsx +++ b/apps/com/admin/src/pages/SocialDetail.tsx @@ -13,6 +13,8 @@ import { } from './MediaValue' import { fmtTime, + joinLivenessLabel, + joinPaidLabel, joinStageLabel, joinStageTone, labelOf, @@ -35,6 +37,7 @@ const ENTITY_LABEL: Record = { reports: '举报', blocks: '拉黑', files: '上传文件', + roomArchives: '语音厅录像', archives: '存档快照', joinLeads: '加入线索', } @@ -131,61 +134,82 @@ function JoinPrimary({ string, unknown > - const audits = Array.isArray(m.audits) ? (m.audits as Array>) : [] - const gallery = [ - { key: 'avatar', label: '头像', value: String(m.avatar || r.avatar || '') }, - { - key: 'front', - label: '核验正面', - value: String(m.livenessFrontUrl || r.livenessFrontUrl || ''), - }, - { - key: 'turn', - label: '核验侧面', - value: String(m.livenessTurnUrl || r.livenessTurnUrl || ''), - }, - { - key: 'video', - label: '核验全程视频', - value: String(m.livenessVideoUrl || r.livenessVideoUrl || ''), - }, - ] + const stage = String(val(item, 'stage') || '') + const liveOk = joinLivenessLabel(item as Record) === '已过' + // 前端硬闸:未核验 / 只填邮箱 → 绝不渲染任何照片视频(防 API 旧副本串号) + const early = + stage === 'email_submit' || + stage === 'pay_launched' || + (!liveOk && stage !== 'profile_done' && stage !== 'liveness_verified') + const showAvatar = stage === 'profile_done' || stage === 'liveness_verified' || stage === 'join_done' + const showLive = liveOk + const audits = showLive && Array.isArray(m.audits) + ? (m.audits as Array>) + : [] + const gallery = early + ? [] + : [ + ...(showAvatar + ? [{ key: 'avatar', label: '头像', value: String(m.avatar || '') }] + : []), + ...(showLive + ? [ + { + key: 'front', + label: '核验正面', + value: String(m.livenessFrontUrl || ''), + }, + { + key: 'turn', + label: '核验侧面', + value: String(m.livenessTurnUrl || ''), + }, + { + key: 'video', + label: '核验全程视频', + value: String(m.livenessVideoUrl || ''), + }, + ] + : []), + ] + + // 未核验线索不展示串号花名册文案 + const showRosterBits = !early && showAvatar return (

    - {String(val(item, 'name') || val(r, 'name') || '未填名字')} + {String( + val(item, 'name') || + (showRosterBits ? val(r, 'name') : '') || + '未填名字', + )}

    - {joinStageLabel(val(item, 'stage'))} + {joinStageLabel(val(item, 'stage'), item as Record)}

    {String(val(item, 'email') ?? '—')}

    - 支付{' '} - {truthyFlag(val(item, 'paid')) ? '已付' : '未付'} + 支付 {joinPaidLabel(item as Record)} - 人脸{' '} - {truthyFlag(val(item, 'faceOk', 'face_ok')) ? '通过' : '未过'} + 人脸 {liveOk ? '通过' : '未过'} - 核验{' '} - - {String(val(item, 'livenessStatus', 'liveness_status') || 'none')} - + 核验 {liveOk ? 'verified' : '未核验'} 访客 {String(val(item, 'guestId', 'guest_id') ?? '—')} 更新 {fmtTime(val(item, 'updatedAt', 'updated_at', 'createdAt'))}
    - {String(val(r, 'bio') || '') ? ( + {showRosterBits && String(val(r, 'bio') || '') ? (

    {String(val(r, 'bio'))}

    ) : null} - {String(val(r, 'city') || val(r, 'title') || '') ? ( + {showRosterBits && String(val(r, 'city') || val(r, 'title') || '') ? (
    {val(r, 'city') ? {String(val(r, 'city'))} : null} {val(r, 'title') ? {String(val(r, 'title'))} : null} @@ -196,7 +220,7 @@ function JoinPrimary({ ) : null}

    照片与视频

    - + {gallery.some((g) => g.value) ? : null} {!gallery.some((g) => g.value) && !audits.length ? (

    还没有头像或核验媒体。

    ) : null} @@ -702,7 +726,15 @@ export default function SocialDetail() { const p = (h.payload || {}) as Record const nested = (p.payload as Record | undefined) || undefined - const media = pickMediaEntries({ ...p, ...(nested || {}) }) + // 只填邮箱 / 发起支付阶段禁止展示媒体(防串号脏 URL) + const act = String(h.action || '') + const allowMedia = + act === 'profile_done' || + act === 'liveness_verified' || + act === 'join_done' + const media = allowMedia + ? pickMediaEntries({ ...p, ...(nested || {}) }) + : [] return (
  • diff --git a/apps/com/admin/src/pages/Switches.tsx b/apps/com/admin/src/pages/Switches.tsx index 564d86b..a404151 100644 --- a/apps/com/admin/src/pages/Switches.tsx +++ b/apps/com/admin/src/pages/Switches.tsx @@ -1,8 +1,9 @@ /** * Web 动态开关 — 写入 remote-config;门户 / H5 约数秒热更新。 - * 不引入微信提审 / 抖音专属控件。 + * 价格改价请走 /pricing(动态价格)。 */ import { useCallback, useEffect, useMemo, useState } from 'react' +import { Link, useParams } from 'react-router-dom' import { api } from '../api/client' import { useConfigLive } from '../lib/useConfigLive' @@ -58,7 +59,7 @@ type TabKey = 'pages' | 'flags' | 'vip' | 'copy' const TABS: Array<{ key: TabKey; label: string }> = [ { key: 'pages', label: '页面' }, { key: 'flags', label: '功能' }, - { key: 'vip', label: 'VIP 入口' }, + { key: 'vip', label: 'VIP 区块' }, { key: 'copy', label: '文案' }, ] @@ -113,6 +114,8 @@ function Switch({ } export default function Switches() { + const { lane } = useParams() + const laneKey = lane === 'cn' ? 'cn' : 'intl' const live = useConfigLive() const [cfg, setCfg] = useState(null) const [busy, setBusy] = useState(false) @@ -126,14 +129,6 @@ export default function Switches() { vipCta: '', xHandle: '', }) - const [priceYuan, setPriceYuan] = useState('0.1') - const [trialDraft, setTrialDraft] = useState({ - enabled: true, - chatMessages: 1, - dateViews: 5, - coffeeBookings: 0, - mapOpens: 3, - }) const load = useCallback(async () => { setErr('') @@ -146,18 +141,6 @@ export default function Switches() { vipCta: data.copy?.vipCta || '', xHandle: data.copy?.xHandle || 'noamdcna', }) - const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0) - setPriceYuan( - fen % 100 === 0 ? String(fen / 100) : (fen / 100).toFixed(2).replace(/0+$/, '').replace(/\.$/, ''), - ) - const tr = data.copy?.socialTrial || {} - setTrialDraft({ - enabled: data.flags?.socialTrialEnabled !== false && tr.enabled !== false, - chatMessages: Math.max(0, Number(tr.chatMessages ?? 1) || 0), - dateViews: Math.max(0, Number(tr.dateViews ?? 5) || 0), - coffeeBookings: Math.max(0, Number(tr.coffeeBookings ?? 0) || 0), - mapOpens: Math.max(0, Number(tr.mapOpens ?? 3) || 0), - }) }, []) useEffect(() => { @@ -181,20 +164,6 @@ export default function Switches() { vipCta: data.copy?.vipCta || '', xHandle: data.copy?.xHandle || 'noamdcna', }) - const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0) - setPriceYuan( - fen % 100 === 0 - ? String(fen / 100) - : (fen / 100).toFixed(2).replace(/0+$/, '').replace(/\.$/, ''), - ) - const tr = data.copy?.socialTrial || {} - setTrialDraft({ - enabled: data.flags?.socialTrialEnabled !== false && tr.enabled !== false, - chatMessages: Math.max(0, Number(tr.chatMessages ?? 1) || 0), - dateViews: Math.max(0, Number(tr.dateViews ?? 5) || 0), - coffeeBookings: Math.max(0, Number(tr.coffeeBookings ?? 0) || 0), - mapOpens: Math.max(0, Number(tr.mapOpens ?? 3) || 0), - }) setMsg(okHint) } catch (e: unknown) { setErr(e instanceof Error ? e.message : '保存失败') @@ -223,15 +192,22 @@ export default function Switches() { return (
    -

    动态开关

    +

    页面开关

    - .com 全站共享配置:页面显隐、功能、VIP 入口与文案。保存后前台实时更新;受众专属文案请到「受众设置」。 + 页面显隐、功能 Flag、VIP 落地区块与门户文案。改价请走 + 动态价格 + ;受众专属文案在「受众设置」。

    版本 v{cfg.version ?? '—'} 页面开启 {onCount}/{PAGE_MODS.length} + + {(Number(cfg.copy?.vipPriceFen) || 0) <= 0 + ? '当前免费' + : `现价 ¥${((Number(cfg.copy?.vipPriceFen) || 0) / 100).toFixed((Number(cfg.copy?.vipPriceFen) || 0) % 100 === 0 ? 0 : 2)}`} + {cfg.updatedAt ? {cfg.updatedAt} : null}
    @@ -385,170 +361,24 @@ export default function Switches() { {tab === 'vip' ? ( <>
    -

    会员价格(免费 / 付费)

    -

    - 写入 remote-config.copy.vipPriceFen;0 元=免费加入。门户 / VIP / 游民加入支付跟此后台价。 -

    -
    - {[ - { label: '免费', yuan: '0' }, - { label: '¥0.1 测试', yuan: '0.1' }, - { label: '¥1', yuan: '1' }, - { label: '¥9.9', yuan: '9.9' }, - { label: '¥29', yuan: '29' }, - { label: '¥99', yuan: '99' }, - ].map((p) => ( - - ))} -
    -
    - - - -
    -
    - -
    -
    -
    -

    游民社区 · 免费体验次数

    -

    - 未加入用户可先逛;次数用完再引导加入。已付费并完成资料+自拍的用户不限次数。 -

    -
    +
    - 开启免费体验限制 -

    关闭后未付费也可无限使用(不推荐上线)

    +

    改价入口

    +

    + 会员价 / 免费体验已独立到「动态价格」。当前{' '} + {(Number(cfg.copy?.vipPriceFen) || 0) <= 0 + ? '免费' + : `¥${((Number(cfg.copy?.vipPriceFen) || 0) / 100).toFixed((Number(cfg.copy?.vipPriceFen) || 0) % 100 === 0 ? 0 : 2)}`} + 。 +

    - setTrialDraft((d) => ({ ...d, enabled: v }))} - /> -
    -
    - {( - [ - ['chatMessages', '群聊可发句数'], - ['dateViews', '约会可看人数'], - ['coffeeBookings', '咖啡聊可约次数'], - ['mapOpens', '地图可打开次数'], - ] as const - ).map(([key, label]) => ( - - ))} -
    -
    - + + 打开动态价格 → +
    -

    VIP 落地入口

    +

    VIP 落地区块

    {VIP_ENTRIES.map((f) => { const on = cfg.vipEntries?.[f.key] !== false diff --git a/apps/com/admin/src/pages/socialMeta.ts b/apps/com/admin/src/pages/socialMeta.ts index 68cd3a7..420de33 100644 --- a/apps/com/admin/src/pages/socialMeta.ts +++ b/apps/com/admin/src/pages/socialMeta.ts @@ -15,6 +15,7 @@ export type SectionKey = | 'blocks' | 'trips' | 'files' + | 'roomArchives' | 'coffee' | 'archives' | 'catalog' @@ -29,6 +30,7 @@ export const SECTIONS: SectionKey[] = [ 'gigs', 'skills', 'liveness', + 'roomArchives', 'coffee', 'trips', 'reports', @@ -49,6 +51,7 @@ export const SECTION_TITLE: Record = { gigs: '接单', skills: '技能交换', liveness: '自拍确认', + roomArchives: '语音厅录像', coffee: '咖啡预约', trips: '行程', reports: '举报', @@ -69,6 +72,7 @@ export const SECTION_DESC: Record = { gigs: '接单与共创申请。', skills: '技能交换(能提供 / 想换)。', liveness: '自拍确认:正面、侧面与录像。', + roomArchives: '进厅埋点立刻出记录:待上传 / 录制中 / 上传中 / 已上传;点行可播已上传视频。', coffee: '咖啡聊预约:谁约了、什么时段。', trips: '成员提交的旅居行程。', reports: '用户举报,优先处理。', @@ -89,6 +93,7 @@ export const SECTION_API: Partial> = { joins: 'join-leads', skills: 'skills', liveness: 'liveness', + roomArchives: 'room-archives', coffee: 'coffee-bookings', trips: 'trips', reports: 'reports', @@ -113,12 +118,57 @@ export const JOIN_STAGE_LABEL: Record = { liveness: '自拍确认', } -export function joinStageLabel(stage: unknown): string { +export function joinStageLabel(stage: unknown, row?: Record): string { const s = String(stage || '').trim() if (!s) return '未开始' + // 历史脏数据:跳过自拍却写成了 join_done → 仍显示「稍后再自拍」 + if (s === 'join_done' && row) { + const live = String(row.livenessStatus || row.liveness_status || '') + const payload = + row.payload && typeof row.payload === 'object' && !Array.isArray(row.payload) + ? (row.payload as Record) + : {} + if (live !== 'verified' && payload.liveness !== 'verified') { + return JOIN_STAGE_LABEL.liveness_skipped + } + } return JOIN_STAGE_LABEL[s] || s } +const JOIN_EARLY = new Set(['email_submit', 'pay_launched']) + +/** 支付列:脏数据 paid=1 / face 残留不得在「只填邮箱」阶段显示已付 */ +export function joinPaidLabel(row: Record): string { + const stage = String(row.stage || '') + const paid = String(row.paid ?? '') + const payload = + row.payload && typeof row.payload === 'object' && !Array.isArray(row.payload) + ? (row.payload as Record) + : {} + const price = Number(payload.priceFen) + const free = + paid === 'free' || + payload.intent === 'free' || + (Number.isFinite(price) && price <= 0) + if (JOIN_EARLY.has(stage)) { + if (free) return '免费' + return '未付' + } + if (free) return '免费' + if (paid === '1' || paid === 'true' || row.paid === true) return '已付' + return '未付' +} + +/** 核验列:只有真做过 liveness_verified 才算已过;join_done 可能是「稍后再说」 */ +export function joinLivenessLabel(row: Record): string { + const stage = String(row.stage || '') + if (JOIN_EARLY.has(stage)) return '未核验' + const live = String(row.livenessStatus || row.liveness_status || '') + if (live === 'verified' || stage === 'liveness_verified') return '已过' + // faceOk 浏览器残留 / join_done 跳过自拍 → 一律未核验 + return '未核验' +} + export function joinStageTone(stage: unknown): 'ok' | 'warn' | 'bad' | 'info' | 'muted' { const s = String(stage || '').toLowerCase() if (s.includes('fail') || s.includes('skip')) return 'bad' @@ -135,6 +185,8 @@ export function toEntity(kind: string): string { if (kind === 'coffee' || kind === 'coffee-bookings' || kind === 'coffeeBookings') return 'coffeeBookings' if (kind === 'meetup-reviews' || kind === 'meetupReviews') return 'meetupReviews' + // 语音厅录像落在 social_files,详情走 files 实体 + if (kind === 'roomArchives' || kind === 'room-archives') return 'files' return kind } @@ -144,6 +196,7 @@ export function toListSegment(kind: string): string { if (kind === 'joinLeads' || kind === 'join-leads') return 'joins' if (kind === 'coffeeBookings' || kind === 'coffee-bookings') return 'coffee' if (kind === 'meetupReviews' || kind === 'meetup-reviews') return 'meetupReviews' + if (kind === 'room-archives') return 'roomArchives' return kind } @@ -270,7 +323,8 @@ export function short(v: unknown, n = 48) { export function pickId(row: Record, section: SectionKey): string { if (section === 'roster') return String(row.guestId || row.guest_id || '') if (section === 'joins') return String(row.id || row.email || '') - if (section === 'files') return String(row.id || row.fileId || '') + if (section === 'files' || section === 'roomArchives') + return String(row.id || row.fileId || '') return String(row.id || row.messageId || row.entityId || '') } @@ -284,6 +338,7 @@ export const OVERVIEW_STATS: Array<[string, string, SectionKey]> = [ ['接单', 'gigApps', 'gigs'], ['技能交换', 'skills', 'skills'], ['自拍确认', 'liveness', 'liveness'], + ['语音厅录像', 'roomArchives', 'roomArchives'], ['咖啡预约', 'coffeeBookings', 'coffee'], ['行程', 'trips', 'trips'], ['举报', 'reports', 'reports'], diff --git a/apps/com/admin/src/upgrade.css b/apps/com/admin/src/upgrade.css index 2337b9d..98c34c8 100644 --- a/apps/com/admin/src/upgrade.css +++ b/apps/com/admin/src/upgrade.css @@ -8,7 +8,7 @@ --muted: #9daec5; --accent: #f6b44b; --accent-2: #64c9ed; - --side-w: 252px; + --side-w: 268px; --radius: 14px; --shadow: 0 8px 28px #00000020; } @@ -45,10 +45,43 @@ button:disabled { cursor: not-allowed; opacity: .55; } .com-nav { scrollbar-width: thin; scrollbar-color: var(--line) transparent; padding-right: 3px; } .com-nav-group { margin-bottom: 12px; } .com-nav-group-label { color: var(--muted); font-size: 10px; letter-spacing: .12em; margin: 10px 10px 4px; } -.com-nav a { border-radius: 8px; min-height: 38px; padding: 9px 12px; font-size: 13px; border: 1px solid transparent; color: var(--muted); } +.com-nav a { border-radius: 8px; min-height: 38px; padding: 9px 10px; font-size: 13px; border: 1px solid transparent; color: var(--muted); display: flex; align-items: center; gap: 8px; justify-content: flex-start; } .com-nav a:hover { background: var(--panel-2); color: var(--text); } .com-nav a.active { background: var(--panel-2); border-color: var(--line); color: var(--text); box-shadow: inset 3px 0 var(--accent); } -.com-nav-hint { color: var(--accent); font-size: 10px; } +.com-nav a.is-accent { color: var(--accent); } +.com-nav a.is-accent.active { background: color-mix(in srgb, var(--accent) 14%, var(--panel-2)); border-color: color-mix(in srgb, var(--accent) 40%, var(--line)); } +.com-nav-ico { width: 22px; height: 22px; border-radius: 6px; display: grid; place-items: center; font-size: 11px; font-weight: 700; background: var(--bg); color: var(--muted); flex-shrink: 0; } +.com-nav a.active .com-nav-ico, .com-nav a.is-accent .com-nav-ico { background: color-mix(in srgb, var(--accent) 18%, var(--bg)); color: var(--accent); } +.com-nav-label { flex: 1; min-width: 0; } +.com-nav-hint { color: var(--accent); font-size: 10px; margin-left: auto; } +.com-nav-group.is-money .com-nav-group-label { color: var(--accent); } +.com-nav-price-jump { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--line)); background: color-mix(in srgb, var(--accent) 12%, var(--panel)); color: var(--text); text-decoration: none; margin: 2px 0 4px; } +.com-nav-price-jump:hover { border-color: var(--accent); } +.com-nav-price-jump strong { display: block; font-size: 13px; } +.com-nav-price-jump em { display: block; font-style: normal; font-size: 11px; color: var(--muted); margin-top: 2px; } +.com-nav-price-mark { width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center; font-weight: 800; background: var(--accent); color: #1c1408; flex-shrink: 0; } +.com-panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; flex-wrap: wrap; } +.com-pricing-eyebrow { font-size: 10px; letter-spacing: .16em; color: var(--accent); font-weight: 700; margin-bottom: 6px; } +.com-pricing-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; margin-bottom: 18px; } +.com-pricing-hero-main, .com-pricing-hero-side { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); padding: 22px; } +.com-pricing-hero-main { border-top: 3px solid var(--accent); } +.com-pricing-kicker { display: block; font-size: 11px; letter-spacing: .08em; color: var(--muted); margin-bottom: 8px; } +.com-pricing-hero-main strong { display: block; font-size: clamp(40px, 6vw, 64px); letter-spacing: -.05em; line-height: 1; font-variant-numeric: tabular-nums; } +.com-pricing-hero-main strong.is-free { color: var(--ok, #34d399); } +.com-pricing-hero-main p { margin: 12px 0 0; color: var(--muted); font-size: 13px; line-height: 1.55; max-width: 42ch; } +.com-pricing-preview { padding: 14px 16px; border-radius: 10px; background: var(--bg); border: 1px solid var(--line); margin-bottom: 14px; } +.com-pricing-preview span { display: block; font-size: 11px; color: var(--muted); margin-bottom: 6px; } +.com-pricing-preview em { font-style: normal; font-size: 18px; font-weight: 700; letter-spacing: -.02em; } +.com-pricing-pay-row { margin: 0; padding-top: 4px; } +.com-pricing-presets { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin-bottom: 18px; } +.com-pricing-preset { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; padding: 14px 14px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); color: var(--text); cursor: pointer; text-align: left; min-height: 72px; } +.com-pricing-preset strong { font-size: 16px; letter-spacing: -.02em; } +.com-pricing-preset span { font-size: 11px; color: var(--muted); } +.com-pricing-preset:hover { border-color: var(--accent-2); } +.com-pricing-preset.is-on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--bg)); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 35%, transparent); } +.com-pricing-preset.is-free.is-on { border-color: var(--ok, #34d399); background: color-mix(in srgb, #34d399 12%, var(--bg)); } +.com-pricing-form { margin-bottom: 8px; } +.com-page-head a { color: var(--accent-2); } .com-side-foot { border-color: var(--line); display: grid; grid-template-columns: 1fr 1fr; gap: 7px; } .com-side-foot > :first-child { grid-column: 1 / -1; } .com-side-link, .com-logout { min-height: 38px; font-size: 12px; border-radius: 8px; border-color: var(--line); } @@ -126,7 +159,12 @@ button:disabled { cursor: not-allowed; opacity: .55; } :root[data-theme='light'] .com-switch-card, :root[data-theme='light'] .com-hub-card, :root[data-theme='light'] .modsel-card { background: var(--panel); border-color: var(--line); } :root[data-theme='light'] .com-flag-row { border-color: var(--line); } .com-switch input:focus-visible + .com-switch-track { outline: 2px solid var(--accent-2); outline-offset: 4px; } -@media (max-width: 1100px) { .com-main { padding-inline: 22px; } .com-health-grid { gap: 12px; } } +@media (max-width: 1100px) { + .com-main { padding-inline: 22px; } + .com-health-grid { gap: 12px; } + .com-pricing-hero { grid-template-columns: 1fr; } + .com-pricing-presets { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} @media (max-width: 860px) { .com-main { padding: 0 16px 40px; } .com-topbar { background: var(--panel); border-color: var(--line); } @@ -140,6 +178,7 @@ button:disabled { cursor: not-allowed; opacity: .55; } .com-page-head-row { align-items: flex-start; gap: 14px; } .com-cmd-hero { padding: 20px; } .com-table td { padding: 12px; } + .com-nav-price-jump { min-height: 52px; } } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } diff --git a/apps/com/admin/vite.config.ts b/apps/com/admin/vite.config.ts index c9c6100..e884ffa 100644 --- a/apps/com/admin/vite.config.ts +++ b/apps/com/admin/vite.config.ts @@ -3,10 +3,10 @@ import react from '@vitejs/plugin-react' /** * admin.nomadro.com — Web only; isolated from apps/admin (.cn) - * 本地调试默认反代美国 VPS API(后端在服务器,前端本机)。 - * 若要打本地 API:设 VITE_DEV_API=http://127.0.0.1:8080 + * 本地默认打本机 API(与门户共用 data/remote-config.json),改价即时生效。 + * 连美国机:VITE_DEV_API=https://api.nomadro.com */ -const DEV_API = process.env.VITE_DEV_API || 'https://api.nomadro.com' +const DEV_API = process.env.VITE_DEV_API || 'http://127.0.0.1:8080' export default defineConfig({ plugins: [react()], diff --git a/deploy/observability/notify-ntfy.sh b/deploy/observability/notify-ntfy.sh index 643ecd4..60c02b2 100644 --- a/deploy/observability/notify-ntfy.sh +++ b/deploy/observability/notify-ntfy.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Publish a notification to local ntfy (https://ntfy.nomadro.com). -# Usage: notify-ntfy.sh "title" "message" [priority] [tags] [topic] +# Publish a rich notification to ntfy (https://ntfy.nomadro.cn). +# Usage: notify-ntfy.sh "title" "message" [priority] [tags] [topic] [click] set -euo pipefail CONF="${NOMADRO_NTFY_CONF:-/etc/nomadro/ntfy.env}" @@ -12,18 +12,63 @@ MESSAGE="${2:-}" PRIORITY="${3:-default}" TAGS="${4:-warning}" TOPIC="${5:-${NTFY_TOPIC:-nomadro}}" +CLICK="${6:-}" BASE_URL="${NTFY_BASE_URL:-https://ntfy.nomadro.cn}" TOKEN="${NTFY_TOKEN:-}" +ICON="${NTFY_ICON_URL:-https://nomadro.com/icon-192.png}" if [[ -z "$TOKEN" ]]; then echo "notify-ntfy: NTFY_TOKEN missing in $CONF" >&2 exit 1 fi -curl -fsS \ - -H "Authorization: Bearer ${TOKEN}" \ - -H "Title: ${TITLE}" \ - -H "Priority: ${PRIORITY}" \ - -H "Tags: ${TAGS}" \ - -d "$MESSAGE" \ - "${BASE_URL%/}/${TOPIC}" >/dev/null +# Map named priorities to ntfy ints +case "$PRIORITY" in + min) P=1 ;; + low) P=2 ;; + default) P=3 ;; + high) P=4 ;; + urgent|max) P=5 ;; + *) P="$PRIORITY" ;; +esac + +NOW="$(TZ=Asia/Shanghai date '+%Y-%m-%d %H:%M:%S')" +RICH=$(cat </dev/null || echo unknown)\` +EOF +) + +# Build JSON without requiring jq +python3 - "$BASE_URL" "$TOKEN" "$TOPIC" "$TITLE" "$RICH" "$P" "$TAGS" "$ICON" "$CLICK" <<'PY' +import json, sys, urllib.request +base, token, topic, title, message, priority, tags, icon, click = sys.argv[1:10] +payload = { + "topic": topic.strip("/"), + "title": title[:200], + "message": message[:3900], + "priority": int(priority), + "markdown": True, + "tags": [t.strip() for t in tags.split(",") if t.strip()], + "icon": icon, +} +if click: + payload["click"] = click + payload["actions"] = [{"action": "view", "label": "打开", "url": click, "clear": True}] +req = urllib.request.Request( + base.rstrip("/") + "/", + data=json.dumps(payload).encode("utf-8"), + headers={ + "Content-Type": "application/json", + "Authorization": f"Bearer {token}", + }, + method="POST", +) +with urllib.request.urlopen(req, timeout=12) as resp: + resp.read() +print("ok") +PY diff --git a/scripts/deploy_platform_upgrade_com.py b/scripts/deploy_platform_upgrade_com.py index d8ebbf6..3734e14 100644 --- a/scripts/deploy_platform_upgrade_com.py +++ b/scripts/deploy_platform_upgrade_com.py @@ -19,13 +19,14 @@ PORTAL = '/var/www/nomadro.cn' ADMIN = '/www/wwwroot/admin.nomadro.com' API_FILES = [ 'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py', - 'services/weapp_switches.py', + 'services/weapp_switches.py', 'services/config_live.py', ] SOCIAL_FILES = ['pb_data.py', 'store.py', 'routers/api.py'] SOURCE_FILES = [ 'next.config.ts', 'src/middleware.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts', 'src/lib/remote-config-live.ts', 'src/lib/remote-config-store.ts', 'src/lib/use-remote-config.ts', - 'src/app/api/config/stream/route.ts', 'src/app/api/pay/confirm/route.ts', + 'src/app/api/config/stream/route.ts', 'src/app/api/config/meta/route.ts', + 'src/app/api/config/notify/route.ts', 'src/app/api/pay/confirm/route.ts', 'src/app/api/auth/sync-session/route.ts', 'src/app/api/portal/join-leads/route.ts', 'src/app/api/admin/social/ugc/join-leads/route.ts', 'src/app/api/work/v1/[[...path]]/route.ts', 'src/app/api/notify/v1/[[...path]]/route.ts', diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.ts index 280767a..40f82a6 100644 --- a/src/app/api/admin/config/route.ts +++ b/src/app/api/admin/config/route.ts @@ -45,9 +45,28 @@ export async function PUT(request: Request) { const saved = await writeRemoteConfigFile(merged); void publishNtfy({ title: "远程配置已更新", - message: `v${saved.version} · ${saved.updatedAt || "now"} · ${saved.copy?.homeBrand || "nomadro"}`, + message: [ + "### ⚙️ 远程配置已更新", + "", + `- **版本** \`v${saved.version}\``, + `- **时间** \`${saved.updatedAt || "now"}\``, + `- **品牌** \`${saved.copy?.homeBrand || "nomadro"}\``, + "", + "[打开后台配置](https://admin.nomadro.com/intl)", + ].join("\n"), tags: "gear,nomadro", priority: "default", + markdown: true, + click: "https://admin.nomadro.com/intl", + icon: "https://nomadro.com/icon-192.png", + actions: [ + { + action: "view", + label: "打开后台", + url: "https://admin.nomadro.com/intl", + clear: true, + }, + ], }); return NextResponse.json({ ok: true, config: saved }); } catch (e) { diff --git a/src/app/api/admin/notify/route.ts b/src/app/api/admin/notify/route.ts index e1671fe..a74aff4 100644 --- a/src/app/api/admin/notify/route.ts +++ b/src/app/api/admin/notify/route.ts @@ -32,12 +32,34 @@ export async function POST(request: Request) { if (!title || !message) { return NextResponse.json({ ok: false, error: "missing title/message" }, { status: 400 }); } + const richMessage = [ + "### 📣 手动试推", + "", + message, + "", + `- **来源** \`admin.nomadro\``, + `- **时间** ${new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })}`, + "", + "[打开后台](https://admin.nomadro.com/)", + ].join("\n"); + const result = await publishNtfy({ title, - message, + message: richMessage, priority: body.priority as never, tags: body.tags || "loudspeaker,nomadro", topic: body.topic, + markdown: true, + click: "https://admin.nomadro.com/", + icon: "https://nomadro.com/icon-192.png", + actions: [ + { + action: "view", + label: "打开后台", + url: "https://admin.nomadro.com/", + clear: true, + }, + ], }); return NextResponse.json(result, { status: result.ok ? 200 : 502 }); } diff --git a/src/app/api/config/notify/route.ts b/src/app/api/config/notify/route.ts new file mode 100644 index 0000000..77abab4 --- /dev/null +++ b/src/app/api/config/notify/route.ts @@ -0,0 +1,66 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + ensureConfigFileWatcher, + notifyConfigChanged, + refreshConfigMeta, +} from "~/lib/remote-config-live"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * FastAPI / 后台写 remote-config 后跨进程 ping:立刻推 SSE,不等文件 watch。 + * 仅本机 / 内网;无鉴权密钥时只接受 loopback。 + */ +function allowNotify(req: NextRequest): boolean { + const secret = (process.env.CONFIG_NOTIFY_SECRET || "").trim(); + if (secret) { + const got = + req.headers.get("x-config-notify-secret") || + req.headers.get("authorization")?.replace(/^Bearer\s+/i, "") || + ""; + return got === secret; + } + const fwd = (req.headers.get("x-forwarded-for") || "").split(",")[0]?.trim(); + const real = req.headers.get("x-real-ip") || ""; + const host = req.headers.get("host") || ""; + const ip = fwd || real || ""; + if ( + !ip || + ip === "127.0.0.1" || + ip === "::1" || + ip === "::ffff:127.0.0.1" || + ip.startsWith("127.") + ) { + return true; + } + // Next 同机调用时常无 localhost host + if (/^(localhost|127\.0\.0\.1)(:\d+)?$/i.test(host)) return true; + return false; +} + +export async function POST(req: NextRequest) { + if (!allowNotify(req)) { + return NextResponse.json({ ok: false, error: "forbidden" }, { status: 403 }); + } + ensureConfigFileWatcher(); + let body: { version?: number; updatedAt?: string } = {}; + try { + body = (await req.json()) as typeof body; + } catch { + /* empty body → read disk */ + } + const disk = await refreshConfigMeta(); + const meta = { + version: Number(body.version) || disk.version, + updatedAt: String(body.updatedAt || disk.updatedAt || ""), + }; + notifyConfigChanged(meta, "write"); + return NextResponse.json({ ok: true, ...meta }); +} + +export async function GET() { + ensureConfigFileWatcher(); + const meta = await refreshConfigMeta(); + return NextResponse.json({ ok: true, ...meta }); +} diff --git a/src/app/api/portal/feedback/route.ts b/src/app/api/portal/feedback/route.ts new file mode 100644 index 0000000..8559654 --- /dev/null +++ b/src/app/api/portal/feedback/route.ts @@ -0,0 +1,156 @@ +import { NextRequest, NextResponse } from "next/server"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { requireAdminSession } from "~/lib/admin-auth"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +const FILE = path.join(process.cwd(), "data", "feedback.json"); + +type Item = { + id: string; + kind: string; + text: string; + contact: string; + guestId: string; + at: string; + source: string; +}; + +type Store = { items: Item[] }; + +function withCors(res: NextResponse): NextResponse { + res.headers.set("Access-Control-Allow-Origin", "*"); + res.headers.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS"); + res.headers.set( + "Access-Control-Allow-Headers", + "Content-Type, Authorization, X-Social-Guest-Id", + ); + return res; +} + +export async function OPTIONS() { + return withCors(new NextResponse(null, { status: 204 })); +} + +async function readStore(): Promise { + try { + const raw = await fs.readFile(FILE, "utf8"); + const parsed = JSON.parse(raw) as Store; + if (parsed && Array.isArray(parsed.items)) return parsed; + } catch { + /* missing */ + } + return { items: [] }; +} + +async function writeStore(store: Store): Promise { + await fs.mkdir(path.dirname(FILE), { recursive: true }); + await fs.writeFile(FILE, JSON.stringify(store, null, 2) + "\n", "utf8"); +} + +function uid(): string { + return `fb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; +} + +/** Admin / debug list — local offline seed. */ +export async function GET(req: NextRequest) { + if (!(await requireAdminSession())) { + return NextResponse.json( + { ok: false, error: "unauthorized" }, + { status: 401, headers: { "Cache-Control": "no-store" } }, + ); + } + const limit = Math.min( + 500, + Math.max(1, Number(req.nextUrl.searchParams.get("limit") || 100) || 100), + ); + const offset = Math.max( + 0, + Number(req.nextUrl.searchParams.get("offset") || 0) || 0, + ); + const store = await readStore(); + const rows = [...store.items].sort((a, b) => + (b.at || "").localeCompare(a.at || ""), + ); + return NextResponse.json( + { + ok: true, + total: rows.length, + items: rows.slice(offset, offset + limit), + }, + { headers: { "Cache-Control": "no-store" } }, + ); +} + +/** Always persist locally so PB 挂了也不会假称「没网」。 */ +export async function POST(req: NextRequest) { + let body: Record = {}; + try { + body = (await req.json()) as Record; + } catch { + return withCors( + NextResponse.json({ detail: "invalid json" }, { status: 400 }), + ); + } + const text = String(body.text || "").trim().slice(0, 4000); + if (!text) { + return withCors( + NextResponse.json({ detail: "请填写内容" }, { status: 400 }), + ); + } + const kindRaw = String(body.kind || "建议"); + const kind = kindRaw === "反馈" ? "反馈" : "建议"; + const contact = String(body.contact || "").trim().slice(0, 120); + const guestId = String( + body.guestId || req.headers.get("x-social-guest-id") || "", + ).slice(0, 120); + const now = new Date().toISOString(); + const item: Item = { + id: uid(), + kind, + text, + contact, + guestId, + at: now, + source: "portal-local", + }; + const store = await readStore(); + store.items.unshift(item); + store.items = store.items.slice(0, 2000); + await writeStore(store); + + // Best-effort forward to social_svc (PB) — failure does not fail the request + const payload = JSON.stringify({ kind, text, contact }); + const headers = { + "Content-Type": "application/json", + "X-Social-Guest-Id": guestId || "portal", + }; + for (const raw of [ + process.env.SOCIAL_API_URL, + process.env.API_URL, + "http://127.0.0.1:8080", + ]) { + const base = (raw || "").replace(/\/$/, ""); + if (!base) continue; + void fetch(`${base}/api/social/v1/feedback`, { + method: "POST", + headers, + body: payload, + }).catch(() => undefined); + } + + return withCors( + NextResponse.json({ + ok: true, + id: item.id, + kind: item.kind, + text: item.text, + contact: item.contact, + guestId: item.guestId, + at: item.at, + stored: "local", + }), + ); +} diff --git a/src/app/api/portal/join-leads/route.ts b/src/app/api/portal/join-leads/route.ts index e8c2a52..96af9b4 100644 --- a/src/app/api/portal/join-leads/route.ts +++ b/src/app/api/portal/join-leads/route.ts @@ -8,6 +8,68 @@ export const dynamic = "force-dynamic"; const FILE = path.join(process.cwd(), "data", "join-leads.json"); +/** Only these stages may attach / update face + liveness on a lead. */ +const FACE_LIVENESS_STAGES = new Set([ + "profile_done", + "liveness_verified", + "liveness_failed", + "liveness_skipped", + "join_done", +]); + +/** email_submit / pay_launched 不得写成已付(1) */ +const EARLY_STAGES = new Set(["email_submit", "pay_launched"]); + +function normalizePaid( + stage: string, + paidIn: string, + payload: Record, + prevPaid: string, +): string { + const intent = String(payload.intent || ""); + const priceFen = Number(payload.priceFen); + const free = + paidIn === "free" || + intent === "free" || + (Number.isFinite(priceFen) && priceFen <= 0) || + prevPaid === "free"; + if (stage === "pay_confirmed") return paidIn === "1" || paidIn === "" ? "1" : paidIn; + // 临时免费贯穿全程;脏数据「已付」不得盖过 free + if (free) return "free"; + if (EARLY_STAGES.has(stage)) { + // 只填邮箱 / 点了支付但未回调:禁止写成已付 + if (paidIn === "1") return prevPaid === "1" ? "1" : ""; + return paidIn || prevPaid || ""; + } + return paidIn || prevPaid || ""; +} + +function sanitizeLead(lead: Lead): Lead { + const histStages = new Set( + (lead.history || []).map((h) => String(h.stage || "")).filter(Boolean), + ); + histStages.add(lead.stage); + const hasFaceStage = [...FACE_LIVENESS_STAGES].some((s) => histStages.has(s)); + let paid = lead.paid || ""; + const payload = lead.payload || {}; + if ( + paid === "1" && + EARLY_STAGES.has(lead.stage) && + !histStages.has("pay_confirmed") && + !histStages.has("profile_done") && + !histStages.has("join_done") + ) { + paid = + payload.intent === "free" || Number(payload.priceFen) === 0 ? "free" : ""; + } + return { + ...lead, + paid, + faceOk: hasFaceStage ? lead.faceOk || "" : "", + livenessStatus: hasFaceStage ? lead.livenessStatus || "none" : "none", + }; +} + function withCors(res: NextResponse): NextResponse { res.headers.set("Access-Control-Allow-Origin", "*"); res.headers.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS"); @@ -72,7 +134,7 @@ export async function GET(req: NextRequest) { Number(req.nextUrl.searchParams.get("offset") || 0) || 0, ); const store = await readStore(); - let rows = [...store.items].sort((a, b) => + let rows = store.items.map(sanitizeLead).sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || ""), ); if (q) { @@ -112,9 +174,10 @@ export async function POST(req: NextRequest) { "", ).slice(0, 120); const name = String(body.name || "").slice(0, 64); - const paid = String(body.paid || "").slice(0, 8); - const faceOk = String(body.faceOk || "").slice(0, 8); - const livenessStatus = String(body.livenessStatus || "").slice(0, 24); + const paidIn = String(body.paid || "").slice(0, 8); + const allowFace = FACE_LIVENESS_STAGES.has(stage); + const faceOkIn = String(body.faceOk || "").slice(0, 8); + const livenessIn = String(body.livenessStatus || "").slice(0, 24); const ua = String( body.ua || req.headers.get("user-agent") || "", ).slice(0, 240); @@ -128,14 +191,19 @@ export async function POST(req: NextRequest) { let lead: Lead; if (idx >= 0) { const prev = store.items[idx]; - lead = { + const faceOk = allowFace ? faceOkIn || prev.faceOk : prev.faceOk || ""; + const livenessStatus = allowFace + ? livenessIn || prev.livenessStatus || "none" + : prev.livenessStatus || "none"; + const paid = normalizePaid(stage, paidIn, payload, prev.paid || ""); + lead = sanitizeLead({ ...prev, guestId: guestId || prev.guestId, stage, name: name || prev.name, - paid: paid || prev.paid, - faceOk: faceOk || prev.faceOk, - livenessStatus: livenessStatus || prev.livenessStatus, + paid, + faceOk, + livenessStatus, ua: ua || prev.ua, payload: { ...prev.payload, ...payload }, updatedAt: now, @@ -143,24 +211,25 @@ export async function POST(req: NextRequest) { ...(prev.history || []), { stage, at: now, payload }, ].slice(-40), - }; + }); store.items[idx] = lead; } else { - lead = { + const paid = normalizePaid(stage, paidIn, payload, ""); + lead = sanitizeLead({ id: uid(), email, guestId, stage, name, paid, - faceOk, - livenessStatus, + faceOk: allowFace ? faceOkIn : "", + livenessStatus: allowFace ? livenessIn || "none" : "none", ua, payload, createdAt: now, updatedAt: now, history: [{ stage, at: now, payload }], - }; + }); store.items.unshift(lead); } await writeStore(store); @@ -170,9 +239,9 @@ export async function POST(req: NextRequest) { email, stage, name, - paid, - faceOk, - livenessStatus, + paid: lead.paid, + faceOk: lead.faceOk, + livenessStatus: lead.livenessStatus, ua, payload, guestId, diff --git a/src/lib/ntfy-rich.ts b/src/lib/ntfy-rich.ts new file mode 100644 index 0000000..4af9ebd --- /dev/null +++ b/src/lib/ntfy-rich.ts @@ -0,0 +1,247 @@ +/** + * Build detailed Markdown bodies + actions for ntfy clients. + */ + +import type { NtfyAction, NtfyPublishInput } from "~/lib/ntfy"; + +export type TrackLikeEvent = { + name?: string; + page?: string; + label?: string; + props?: Record; + ts?: number; +}; + +const PROP_LABEL: Record = { + audience: "受众", + device: "设备", + browser: "浏览器", + screen: "屏幕", + lang: "语言", + tz: "时区", + href: "链接", + title: "页面标题", + text: "文案", + el: "元素", + role: "角色", + role_cn: "角色中文", + paid_type: "付费类型", + email: "邮箱", + name: "昵称", + user_id: "用户ID", + channel: "渠道", + popup: "弹窗", + offline: "离线", + amount: "金额", + orderId: "订单", + out_trade_no: "商户单号", + gateway: "网关", + plan: "套餐", + city: "城市", + roomId: "房间", + alive_ms: "停留(ms)", +}; + +const SKIP_PROPS = new Set(["password", "token", "secret", "authorization"]); + +function esc(value: unknown): string { + return String(value ?? "") + .replace(/\|/g, "\\|") + .replace(/\n/g, " ") + .trim() + .slice(0, 180); +} + +function shortUid(uid: string | undefined): string { + const u = (uid || "").trim(); + if (!u) return "—"; + return u.length > 12 ? `…${u.slice(-10)}` : u; +} + +function fmtTime(ts?: number): string { + const d = ts && Number.isFinite(ts) ? new Date(ts) : new Date(); + try { + return new Intl.DateTimeFormat("zh-CN", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false, + }).format(d); + } catch { + return d.toISOString(); + } +} + +function propRows(props: Record | undefined): string[] { + if (!props) return []; + const rows: string[] = []; + for (const [k, v] of Object.entries(props)) { + if (SKIP_PROPS.has(k.toLowerCase())) continue; + if (v == null || v === "") continue; + if (typeof v === "object") continue; + const label = PROP_LABEL[k] || k; + let display = esc(v); + if (k === "popup" && v === "douyin") display = "抖音群"; + if (k === "popup" && v === "wechat") display = "公众号"; + if (k === "offline" && v) display = "是"; + if (k === "alive_ms" && typeof v === "number") { + display = `${Math.round(v / 1000)}s`; + } + rows.push(`| ${label} | \`${display}\` |`); + } + return rows.slice(0, 14); +} + +function eventEmoji(name: string): string { + if (name.startsWith("pay_")) return "💰"; + if (name.startsWith("login_")) return "🔑"; + if (name.startsWith("join_")) return "👥"; + if (name.startsWith("follow_")) return "❤️"; + if (name === "error") return "🚨"; + if (name === "session_start") return "🌊"; + if (name === "page_view") return "👀"; + if (name === "book_complete") return "📚"; + if (name === "feedback_submit") return "✉️"; + if (name === "share_x") return "🐦"; + return "📡"; +} + +export function adminEventsUrl(site: string): string { + if (site.includes("nomadro.com") || site === "web_intl") { + return "https://admin.nomadro.com/intl/events"; + } + return "https://admin.nomadro.cn/"; +} + +export function buildTrackNtfyPayload(input: { + name: string; + title: string; + site: string; + openid?: string; + client?: string; + event: TrackLikeEvent; + tags?: string; + priority?: NtfyPublishInput["priority"]; + topic?: string; +}): NtfyPublishInput { + const { name, title, site, openid, client, event } = input; + const props = (event.props || {}) as Record; + const href = + typeof props.href === "string" && props.href.startsWith("http") + ? props.href + : ""; + const page = String(event.page || "").slice(0, 80); + const label = String(event.label || "").slice(0, 160); + const email = + typeof props.email === "string" ? String(props.email).slice(0, 80) : ""; + const nick = + typeof props.name === "string" + ? String(props.name).slice(0, 40) + : typeof props.role_cn === "string" + ? String(props.role_cn).slice(0, 40) + : ""; + + const lines: string[] = [ + `### ${eventEmoji(name)} ${esc(title)}`, + "", + `- **站点** \`${esc(site)}\``, + `- **客户端** \`${esc(client || "web")}\``, + `- **用户** \`${shortUid(openid)}\`${nick ? ` · **${esc(nick)}**` : ""}`, + ]; + if (email) lines.push(`- **邮箱** \`${esc(email)}\``); + if (page) lines.push(`- **页面** \`${esc(page)}\``); + if (label) lines.push(`- **标签** ${esc(label)}`); + lines.push(`- **时间** ${fmtTime(event.ts)}`); + + const rows = propRows(props); + if (rows.length) { + lines.push("", "| 字段 | 值 |", "| --- | --- |", ...rows); + } + + if (href) { + lines.push("", `[打开来源页](${href})`); + } + + const adminUrl = adminEventsUrl(site); + lines.push("", `[打开后台事件](${adminUrl})`); + + const actions: NtfyAction[] = [ + { + action: "view", + label: "后台事件", + url: adminUrl, + clear: true, + }, + ]; + if (href) { + actions.push({ action: "view", label: "来源页", url: href, clear: true }); + } + if (site.includes("nomadro.com")) { + actions.push({ + action: "view", + label: "门户", + url: "https://nomadro.com/", + clear: true, + }); + } + + return { + title: title.slice(0, 80), + message: lines.join("\n").slice(0, 3900), + tags: input.tags, + priority: input.priority, + topic: input.topic, + markdown: true, + click: href || adminUrl, + icon: "https://nomadro.com/icon-192.png", + actions: actions.slice(0, 3), + }; +} + +export function buildPlainRichNtfy(input: { + title: string; + headline?: string; + bullets?: Array<[string, string]>; + table?: Array<[string, string]>; + footer?: string; + click?: string; + tags?: string; + priority?: NtfyPublishInput["priority"]; + actions?: NtfyAction[]; + attach?: string; +}): NtfyPublishInput { + const lines: string[] = [ + `### ${esc(input.headline || input.title)}`, + "", + ]; + for (const [k, v] of input.bullets || []) { + lines.push(`- **${esc(k)}** ${esc(v)}`); + } + if (input.table?.length) { + lines.push("", "| 字段 | 值 |", "| --- | --- |"); + for (const [k, v] of input.table) { + lines.push(`| ${esc(k)} | \`${esc(v)}\` |`); + } + } + if (input.footer) { + lines.push("", esc(input.footer)); + } + if (input.click) { + lines.push("", `[打开链接](${input.click})`); + } + return { + title: input.title.slice(0, 80), + message: lines.join("\n").slice(0, 3900), + markdown: true, + tags: input.tags, + priority: input.priority, + click: input.click, + icon: "https://nomadro.com/icon-192.png", + attach: input.attach, + actions: input.actions?.slice(0, 3), + }; +} diff --git a/src/lib/ntfy.ts b/src/lib/ntfy.ts index a8f0fb3..2078d55 100644 --- a/src/lib/ntfy.ts +++ b/src/lib/ntfy.ts @@ -1,29 +1,86 @@ /** * Publish to self-hosted ntfy (https://ntfy.nomadro.cn). * Env: NTFY_BASE_URL, NTFY_TOPIC, NTFY_TOKEN (optional Bearer). + * Rich payload: markdown / icon / click / attach / actions. + * @see https://docs.ntfy.sh/publish/ */ + +export type NtfyPriority = + | "min" + | "low" + | "default" + | "high" + | "urgent" + | number; + +export type NtfyAction = { + action: "view" | "http" | "broadcast"; + label: string; + url: string; + clear?: boolean; + method?: string; + headers?: Record; + body?: string; +}; + export type NtfyPublishInput = { title: string; message: string; - priority?: "min" | "low" | "default" | "high" | "urgent" | number; - tags?: string; + priority?: NtfyPriority; + tags?: string | string[]; topic?: string; + /** Render message as Markdown (lists, bold, links, images). */ + markdown?: boolean; + /** URL opened when the notification is tapped. */ + click?: string; + /** JPEG/PNG icon URL shown beside the notification. */ + icon?: string; + /** External attachment URL (image preview when image). */ + attach?: string; + filename?: string; + /** Up to 3 action buttons. */ + actions?: NtfyAction[]; }; +const DEFAULT_ICON = + process.env.NTFY_ICON_URL?.trim() || + "https://nomadro.com/icon-192.png"; + export function ntfyConfigured(): boolean { const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").trim(); const topic = (process.env.NTFY_TOPIC || "nomadro").trim(); return Boolean(base && topic); } +function resolvePriority(raw: NtfyPriority | undefined): number { + if (typeof raw === "number") return Math.max(1, Math.min(5, Math.round(raw))); + return ( + ({ min: 1, low: 2, default: 3, high: 4, urgent: 5 } as const)[ + raw || "default" + ] ?? 3 + ); +} + +function resolveTags(tags: string | string[] | undefined): string[] { + if (!tags) return []; + const list = Array.isArray(tags) ? tags : tags.split(","); + return list.map((t) => t.trim()).filter(Boolean).slice(0, 12); +} + export async function publishNtfy(input: NtfyPublishInput): Promise<{ ok: boolean; skipped?: boolean; status?: number; error?: string; }> { - const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").replace(/\/$/, ""); - const topic = (input.topic || process.env.NTFY_TOPIC || "nomadro").replace(/^\/+|\/+$/g, ""); + const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").replace( + /\/$/, + "", + ); + const topic = (input.topic || process.env.NTFY_TOPIC || "nomadro").replace( + /^\/+|\/+$/g, + "", + ); if (!base || !topic) { return { ok: false, skipped: true, error: "ntfy not configured" }; } @@ -35,24 +92,29 @@ export async function publishNtfy(input: NtfyPublishInput): Promise<{ const token = (process.env.NTFY_TOKEN || "").trim(); if (token) headers.Authorization = `Bearer ${token}`; - const priorityRaw = input.priority ?? "default"; - const priority = - typeof priorityRaw === "number" - ? priorityRaw - : ({ min: 1, low: 2, default: 3, high: 4, urgent: 5 } as const)[ - priorityRaw - ] ?? 3; - const tags = (input.tags || "") - .split(",") - .map((t) => t.trim()) - .filter(Boolean); + const tags = resolveTags(input.tags); + const actions = (input.actions || []).slice(0, 3); + const markdown = input.markdown !== false; + const icon = (input.icon || DEFAULT_ICON).trim(); const body = JSON.stringify({ topic, title: input.title.slice(0, 200), - message: input.message.slice(0, 4000), - priority, + message: input.message.slice(0, 3900), + priority: resolvePriority(input.priority), + markdown, ...(tags.length ? { tags } : {}), + ...(icon ? { icon } : {}), + ...(input.click ? { click: input.click.slice(0, 512) } : {}), + ...(input.attach + ? { + attach: input.attach.slice(0, 512), + ...(input.filename + ? { filename: input.filename.slice(0, 120) } + : {}), + } + : {}), + ...(actions.length ? { actions } : {}), }); try { @@ -63,7 +125,11 @@ export async function publishNtfy(input: NtfyPublishInput): Promise<{ cache: "no-store", }); if (!res.ok) { - return { ok: false, status: res.status, error: await res.text().then((t) => t.slice(0, 200)) }; + return { + ok: false, + status: res.status, + error: await res.text().then((t) => t.slice(0, 200)), + }; } return { ok: true, status: res.status }; } catch (e) { diff --git a/src/lib/remote-config-live.ts b/src/lib/remote-config-live.ts index 93d7826..732c84c 100644 --- a/src/lib/remote-config-live.ts +++ b/src/lib/remote-config-live.ts @@ -88,9 +88,9 @@ export function ensureConfigFileWatcher(): void { /* watch 不可用时靠 SSE 内轮询 */ } - // 兜底轮询(跨进程 / 某些 FS 不触发 watch,例如 FastAPI 另进程写入) + // 兜底轮询(跨进程 / Windows FS watch 偶发漏事件;FastAPI 另进程写入) const poll = setInterval(() => { void emitFromDisk("poll"); - }, 4000); + }, 1000); poll.unref(); } diff --git a/src/lib/remote-config.ts b/src/lib/remote-config.ts index 3abba39..9aedd42 100644 --- a/src/lib/remote-config.ts +++ b/src/lib/remote-config.ts @@ -479,7 +479,8 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { homeBrand: "nomadro", homeTagline: "", homeLead: "", - vipPriceFen: 10, + // 离线种子默认免费;线上以 remote-config / 后台动态价格覆盖 + vipPriceFen: 0, vipProductId: "tiktok", vipCta: "立即加入 · ¥0.1", socialTrial: { @@ -498,7 +499,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { socialHeroAccent: "同类", socialHeroLead: "换一座城市,不必重新孤独。\n从一句你好、一杯咖啡开始,找到一起生活、\n一起探索、一起做点什么的人。", - socialJoinCta: "找到我的同频", + socialJoinCta: "加入社区", socialInviteTitle: "下一站,和同类一起。", socialInviteLead: "无论你正在出发,还是已经在路上,这里都有一个属于你的位置。", @@ -506,9 +507,9 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { socialOnlineTitle: "随时,聊得来", socialOfflineTitle: "同城,见一面", socialTeamTitle: "一起,做点事", - socialWayGroup: "群组聊天", - socialWayChat: "开视频聊聊", - socialWayDate: "认识一下", + socialWayGroup: "聊天群", + socialWayChat: "语音厅", + socialWayDate: "约会", socialWayCafe: "找个地方见面", socialWayTeam: "找搭子 · 共创", socialPayJoinLabel: "加入社区", @@ -519,28 +520,28 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { title: "想见的人", accent: "认识新朋友", description: - "点开卡片,看看对方在做什么。现在是示例介绍,方便你先熟悉;想打招呼,去大家聊天的地方说一句就好。", + "点开卡片,看看对方在做什么。想打招呼,去聊天群说一句就好。", }, date: { eyebrow: "慢慢认识", - title: "认识一下", + title: "约会", accent: "想认识的人", description: "右滑表示想认识,会先记在你这边。接下来可以去聊天室打个招呼——不是一对一私信,而是大家一起聊。", }, chat: { eyebrow: "大家在这儿聊", - title: "聊天室", + title: "聊天群", accent: "打个招呼", description: "进来跟大家说说话。网络不好时,刚才的话可能先留在你这边,联网后再试一次就行。", }, meetup: { eyebrow: "面对面更近", - title: "随时,聊得来", - accent: "开视频", + title: "语音厅", + accent: "开麦聊聊", description: - "几个人一起开摄像头见面聊天。点「想参加」只是先记在你这边,还不等于已经约好。", + "几个人一起开麦见面聊天。", }, coffeechat: { eyebrow: "约出来喝一杯", diff --git a/src/lib/use-remote-config.ts b/src/lib/use-remote-config.ts index 533b81b..90e9918 100644 --- a/src/lib/use-remote-config.ts +++ b/src/lib/use-remote-config.ts @@ -7,11 +7,17 @@ import { type NomadroRemoteConfig, } from "~/lib/remote-config"; import { + remoteConfigMetaUrl, remoteConfigStreamUrl, remoteConfigUrl, } from "~/lib/remote-config-client"; -const CACHE_KEY = "nomadro_web_remote_config_v1"; +/** v2:作废旧缓存(曾把免费 0 分卡成付费默认 10 分) */ +const CACHE_KEY = "nomadro_web_remote_config_v2"; +const BC_NAME = "nomadro-remote-config"; +/** 可见时 meta 探针;版本变了才拉全量 */ +const META_POLL_MS = 1200; +const SSE_RECONNECT_MS = 1500; type Result = { config: NomadroRemoteConfig; @@ -30,10 +36,12 @@ let snapshot: Snapshot = { const listeners = new Set<() => void>(); let bootstrapped = false; let knownVersion = 0; +let knownUpdatedAt = ""; let es: EventSource | null = null; let reconnectTimer: ReturnType | null = null; let pollTimer: ReturnType | null = null; let inFlight: Promise | null = null; +let bc: BroadcastChannel | null = null; function emit() { for (const cb of listeners) cb(); @@ -62,8 +70,9 @@ function writeCache(config: NomadroRemoteConfig) { } } -function apply(config: NomadroRemoteConfig, fromOffline: boolean) { +function apply(config: NomadroRemoteConfig, fromOffline: boolean, broadcast = true) { knownVersion = Number(config.version) || knownVersion; + knownUpdatedAt = String(config.updatedAt || knownUpdatedAt); writeCache(config); snapshot = { config, @@ -72,6 +81,18 @@ function apply(config: NomadroRemoteConfig, fromOffline: boolean) { version: snapshot.version + 1, }; emit(); + if (broadcast && typeof BroadcastChannel !== "undefined") { + try { + bc ??= new BroadcastChannel(BC_NAME); + bc.postMessage({ + type: "config", + version: knownVersion, + updatedAt: knownUpdatedAt, + }); + } catch { + /* ignore */ + } + } } async function fetchFullConfig(): Promise { @@ -90,6 +111,33 @@ async function fetchFullConfig(): Promise { return null; } +async function fetchMeta(): Promise<{ version: number; updatedAt: string } | null> { + try { + const res = await fetch(remoteConfigMetaUrl(), { + cache: "no-store", + mode: "cors", + credentials: "omit", + signal: AbortSignal.timeout(5000), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) return null; + return { + version: Number(data.version) || 0, + updatedAt: String(data.updatedAt || ""), + }; + } catch { + return null; + } +} + +function metaChanged(meta: { version: number; updatedAt: string }) { + if (!meta.version && !meta.updatedAt) return false; + return ( + meta.version !== knownVersion || + (Boolean(meta.updatedAt) && meta.updatedAt !== knownUpdatedAt) + ); +} + async function pull(force = false) { if (inFlight) { await inFlight; @@ -116,16 +164,21 @@ async function pull(force = false) { } } +async function pollMeta() { + if (typeof document !== "undefined" && document.visibilityState === "hidden") { + return; + } + if (typeof navigator !== "undefined" && navigator.onLine === false) return; + const meta = await fetchMeta(); + if (meta && metaChanged(meta)) void pull(true); +} + function connectSse() { if (typeof EventSource === "undefined") return; const streamUrl = remoteConfigStreamUrl(); const crossOrigin = streamUrl.startsWith("http"); - if (crossOrigin) { - if (!pollTimer) { - pollTimer = setInterval(() => void pull(false), 30_000); - } - return; - } + // 跨域 EventSource 常被拦;靠 meta 秒级轮询 + if (crossOrigin) return; try { es?.close(); es = new EventSource(streamUrl); @@ -135,7 +188,12 @@ function connectSse() { String((ev as MessageEvent).data || "{}"), ) as { version?: number; updatedAt?: string }; const v = Number(data.version) || 0; - if (v && (v !== knownVersion || data.updatedAt !== snapshot.config.updatedAt)) void pull(true); + if ( + v && + (v !== knownVersion || data.updatedAt !== snapshot.config.updatedAt) + ) { + void pull(true); + } } catch { void pull(true); } @@ -144,10 +202,10 @@ function connectSse() { es?.close(); es = null; if (reconnectTimer) clearTimeout(reconnectTimer); - reconnectTimer = setTimeout(connectSse, 8000); + reconnectTimer = setTimeout(connectSse, SSE_RECONNECT_MS); }; } catch { - /* SSE unavailable — visibility pull only */ + /* SSE unavailable — meta poll only */ } } @@ -162,6 +220,7 @@ function ensureBootstrapped() { const cached = readCache(); if (cached) { knownVersion = Number(cached.version) || 0; + knownUpdatedAt = String(cached.updatedAt || ""); snapshot = { config: cached, fromOffline: true, @@ -185,13 +244,36 @@ function ensureBootstrapped() { })(); connectSse(); - // SSE can be blocked by intermediaries; retain a bounded fallback in every mode. - if (!pollTimer) pollTimer = setInterval(() => { - if (document.visibilityState === 'visible' && navigator.onLine) void pull(false); - }, 30000); + if (!pollTimer) { + pollTimer = setInterval(() => void pollMeta(), META_POLL_MS); + } + + if (typeof BroadcastChannel !== "undefined") { + try { + bc ??= new BroadcastChannel(BC_NAME); + bc.onmessage = (ev) => { + const msg = ev.data as { + type?: string; + version?: number; + updatedAt?: string; + }; + if (msg?.type !== "config") return; + const v = Number(msg.version) || 0; + if (v && (v !== knownVersion || msg.updatedAt !== knownUpdatedAt)) { + void pull(true); + } + }; + } catch { + /* ignore */ + } + } + window.addEventListener("online", onVisible); window.addEventListener("focus", onVisible); document.addEventListener("visibilitychange", onVisible); + window.addEventListener("storage", (e) => { + if (e.key === CACHE_KEY && e.newValue) void pull(true); + }); } function subscribe(cb: () => void) { @@ -219,8 +301,22 @@ function getServerSnapshot(): Result { /** * 门户远程配置(全局单例): - * 多组件共用一次 fetch + 一条 SSE,避免 /api/config 刷屏。 + * SSE 即时推 + meta 探针 + BroadcastChannel 多标签同步。 + * 多组件共用一次 fetch,避免 /api/config 刷屏。 */ export function useRemoteConfig(): Result { return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } + +/** 加群弹窗 / 支付前强制拉最新价,避免 localStorage 脏缓存 */ +export async function refreshRemoteConfig( + force = true, +): Promise { + if (typeof window !== "undefined") ensureBootstrapped(); + await pull(force); + return snapshot.config; +} + +export function getRemoteConfigSnapshot(): Result { + return snapshot; +} diff --git a/src/modules/coffee/components/CoffeeLanding.tsx b/src/modules/coffee/components/CoffeeLanding.tsx index 6fb55b8..554839d 100644 --- a/src/modules/coffee/components/CoffeeLanding.tsx +++ b/src/modules/coffee/components/CoffeeLanding.tsx @@ -1,21 +1,59 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import Link from "next/link"; import SiteShell from "@social/components/SiteShell"; -import HomeCoffeeEntry from "@social/components/HomeCoffeeEntry"; import { socialPath } from "@social/lib/socialPath"; import { socialTx } from "@social/lib/socialTx"; import { useSocialI18n } from "@social/lib/useSocialI18n"; +import { SOCIAL_CITIES, type SocialCity } from "@social/lib/cities"; import { coffeeApi } from "../lib/api"; import type { CoffeeHost } from "../lib/types"; import "./coffee.css"; +const FEATURED_CITY_IDS = [ + "chengdu", + "dali", + "chiangmai", + "bali", + "lisbon", + "hangzhou", + "penang", + "xiamen", +]; + +function cityMatch(hostCity: string, city: SocialCity) { + const raw = (hostCity || "").toLowerCase(); + if (!raw) return false; + return ( + raw.includes(city.name.toLowerCase()) || + raw.includes(city.id.toLowerCase()) || + (city.name === "清迈" && raw.includes("chiang")) || + (city.name === "巴厘岛" && (raw.includes("bali") || raw.includes("巴厘"))) || + (city.name === "里斯本" && raw.includes("lisbon")) + ); +} + export default function CoffeeLanding() { const { locale } = useSocialI18n(); const zh = locale === "zh"; const [hosts, setHosts] = useState([]); const [err, setErr] = useState(null); + const [cityId, setCityId] = useState("all"); + + const cities = useMemo(() => { + const hot = SOCIAL_CITIES.filter((c) => FEATURED_CITY_IDS.includes(c.id)); + const rest = SOCIAL_CITIES.filter((c) => !FEATURED_CITY_IDS.includes(c.id)); + return [...hot, ...rest].slice(0, 12); + }, []); + + const activeCity = cities.find((c) => c.id === cityId) || null; + + const filtered = useMemo(() => { + if (cityId === "all" || !activeCity) return hosts; + const hit = hosts.filter((h) => cityMatch(h.city, activeCity)); + return hit.length ? hit : hosts; + }, [hosts, cityId, activeCity]); useEffect(() => { void coffeeApi @@ -25,58 +63,212 @@ export default function CoffeeLanding() { }, []); return ( - - -
    -
    -
    -

    - Nomadro Coffee -

    -

    - {zh ? "预约一次同城咖啡聊" : "Book a coffee chat"} + +
    +
    +
    +
    +

    {zh ? "OFFLINE · CITY" : "OFFLINE · CITY"}

    +

    + Nomadro {zh ? "线下 Coffee" : "Offline Coffee"}

    +

    + {zh + ? "挑一座城,约一杯线下咖啡" + : "Pick a city. Book an offline coffee."} +

    {zh - ? "读 Cal.com 域模型后自研:日程 · 事件类型 · 可约时段 · 预约确认。同域原生页,挂在游民社区咖啡聊。" - : "Cal.com-domain secondary-dev: schedules, event types, slots, bookings — native on social coffeechat."} + ? "不是线上会议。同城咖啡馆见面,破冰、换签证经验、找搭子——城市就是你的会场。" + : "Not a Zoom. Meet IRL at a café — city is the venue."}

    - - {zh ? "约演示主持人" : "Book demo host"} - - - {zh ? "管理我的日程" : "Manage schedule"} - - + + {zh ? "看谁在约" : "Who’s free"} + + {zh ? "咖啡馆地图" : "Café map"} + + {zh ? "逛城市" : "Browse cities"} +
    -
    +
      + {cities.slice(0, 6).map((c) => ( +
    • + +
    • + ))} +
    - {err &&

    {err}

    } -
    - {hosts.map((h) => ( - +
    +

    {zh ? "城市就是会场" : "Cities as venues"}

    +

    + {zh + ? "先选城,再约人。线下咖啡聊绑定同城,不搞远程空聊。" + : "Choose the city first. Offline coffee stays local."} +

    +
    +
    + + {cities.map((c) => ( + + ))} +
    + + {activeCity ? ( +
    +
    +
    +

    + {activeCity.emoji} {activeCity.country} +

    +

    + {activeCity.name} + {activeCity.vibe} +

    +

    + {activeCity.blurb || + (zh + ? "同城咖啡馆约见,见面比聊天软件快。" + : "Meet at a local café — faster than DMs.")} +

    +
    + + {zh ? `去看${activeCity.name}` : `Explore ${activeCity.name}`} + + + {zh ? "同城咖啡馆" : "Cafés nearby"} + +
    -

    {h.name}

    -

    {h.bio}

    - - @{h.username} · {h.event_count || 0}{" "} - {zh ? "种聊聊" : "event types"} - +
    + ) : ( +
    + {cities.slice(0, 8).map((c) => ( + + ))} +
    + )} +

    + +
    +
    +

    + {activeCity + ? zh + ? `${activeCity.name} · 可约线下` + : `${activeCity.name} · offline` + : zh + ? "线下可约的人" + : "People for offline coffee"} +

    +

    + {zh + ? "约的是咖啡馆见面,不是视频会议。点进主页选时段即可。" + : "Café meetups, not video calls. Pick a slot on their page."} +

    +
    + + {err &&

    {err}

    } + +
    + {filtered.map((h) => ( + +
    + {h.city || (zh ? "同城待定" : "City TBD")} + {zh ? "线下" : "IRL"} +
    +

    {h.name}

    +

    {h.bio || (zh ? "咖啡馆轻聊,帮你破冰同城。" : "Café chat to break the ice.")}

    + + @{h.username} · {h.event_count || 0}{" "} + {zh ? "种见面" : "meet types"} + + + ))} +
    + + {!filtered.length && !err ? ( +

    + {zh + ? "这城暂时没人开放预约,先逛咖啡馆地图,或换一座城。" + : "No hosts here yet — try the café map or another city."} +

    + ) : null} + +
    + + {zh ? "开放我的线下档期" : "Open my offline slots"} - ))} -
    + + {zh ? "找同城的人" : "Find locals"} + +
    +
    ); diff --git a/src/modules/coffee/components/coffee.css b/src/modules/coffee/components/coffee.css index acd7c16..a231ffc 100644 --- a/src/modules/coffee/components/coffee.css +++ b/src/modules/coffee/components/coffee.css @@ -332,3 +332,208 @@ min-width: 1.2rem; text-align: right; } + +/* —— Offline coffee · city-first —— */ +.cf-offline { max-width: 1040px; } +.cf-eyebrow { + margin: 0 0 0.45rem; + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--cf-amber); +} +.cf-hero-offline { + position: relative; + overflow: hidden; + isolation: isolate; + display: grid; + gap: 1.35rem; + margin: 0 -0.35rem 1.75rem; + padding: 1.75rem 1.2rem 1.35rem; + border-radius: 28px; + border: 1px solid var(--cf-line); + background: #0c0c0f; + min-height: min(62dvh, 520px); +} +.cf-hero-offline-bg { + position: absolute; + inset: 0; + z-index: 0; + background: + linear-gradient(115deg, rgba(12, 12, 15, 0.92) 18%, rgba(12, 12, 15, 0.55) 55%, rgba(12, 12, 15, 0.82) 100%), + radial-gradient(600px 280px at 18% -10%, rgba(245, 158, 11, 0.28), transparent 55%), + url("https://images.unsplash.com/photo-1495474472287-4d71bcdd2085?auto=format&fit=crop&w=1600&q=80") + center / cover no-repeat; + animation: cf-glow 6s ease-in-out infinite alternate; +} +.cf-hero-offline-copy, +.cf-city-rail { + position: relative; + z-index: 1; +} +.cf-hero-offline .cf-title { + font-size: clamp(1.35rem, 3.4vw, 1.85rem); + max-width: 18ch; +} +.cf-city-rail { + display: grid; + grid-auto-flow: column; + grid-auto-columns: minmax(132px, 1fr); + gap: 0.55rem; + overflow-x: auto; + padding-bottom: 0.2rem; + list-style: none; + margin: 0; + scrollbar-width: thin; +} +.cf-city-chip { + display: grid; + gap: 0.15rem; + min-height: 72px; + padding: 0.7rem 0.75rem; + border-radius: 16px; + border: 1px solid rgba(255, 255, 255, 0.12); + background: rgba(0, 0, 0, 0.38); + backdrop-filter: blur(8px); + color: var(--cf-ink); + text-align: left; + cursor: pointer; + font: inherit; + transition: border-color 0.15s ease, transform 0.15s ease; +} +.cf-city-chip strong { font-family: Syne, sans-serif; font-size: 0.95rem; } +.cf-city-chip em { + font-style: normal; + font-size: 0.7rem; + color: var(--cf-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.cf-city-chip.is-on, +.cf-city-chip:hover { + border-color: rgba(245, 158, 11, 0.55); + transform: translateY(-2px); +} + +.cf-section-head { margin: 0 0 1rem; } +.cf-section-head h2 { + margin: 0 0 0.35rem; + font-family: Syne, sans-serif; + font-size: clamp(1.2rem, 2.8vw, 1.55rem); + font-weight: 800; + letter-spacing: -0.03em; +} +.cf-section-head p { + margin: 0; + color: var(--cf-muted); + max-width: 36rem; + line-height: 1.5; +} + +.cf-city-filter { + display: flex; + flex-wrap: wrap; + gap: 0.45rem; + margin-bottom: 1rem; +} +.cf-filter-pill { + min-height: 40px; + padding: 0.35rem 0.85rem; + border-radius: 999px; + border: 1px solid var(--cf-line); + background: transparent; + color: var(--cf-muted); + font: inherit; + font-size: 0.84rem; + font-weight: 600; + cursor: pointer; +} +.cf-filter-pill.is-on { + color: #0c0c0f; + background: var(--cf-amber); + border-color: var(--cf-amber); +} + +.cf-city-spotlight { + display: grid; + gap: 0; + margin-bottom: 1.5rem; + border-radius: 22px; + overflow: hidden; + border: 1px solid var(--cf-line); + background: #111114; +} +@media (min-width: 800px) { + .cf-city-spotlight { grid-template-columns: 1.05fr 0.95fr; min-height: 280px; } +} +.cf-city-spotlight-media { + min-height: 180px; + background: + linear-gradient(180deg, transparent 30%, rgba(12, 12, 15, 0.55)), + #1a1510 center / cover no-repeat; +} +.cf-city-spotlight-body { + display: grid; + gap: 0.55rem; + align-content: center; + padding: 1.25rem 1.2rem 1.35rem; +} +.cf-city-spotlight-body h3 { + margin: 0; + font-family: Syne, sans-serif; + font-size: 1.45rem; + display: grid; + gap: 0.2rem; +} +.cf-city-spotlight-body h3 span { + font-size: 0.88rem; + font-weight: 600; + color: var(--cf-muted); +} +.cf-city-spotlight-body > p { margin: 0; color: var(--cf-muted); line-height: 1.5; } + +.cf-city-mosaic { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.55rem; + margin-bottom: 1.5rem; +} +@media (min-width: 720px) { + .cf-city-mosaic { grid-template-columns: repeat(4, minmax(0, 1fr)); } +} +.cf-city-tile { + position: relative; + min-height: 110px; + padding: 0.85rem; + border: 0; + border-radius: 16px; + overflow: hidden; + cursor: pointer; + color: #fff; + text-align: left; + font: inherit; + background: + linear-gradient(180deg, transparent 20%, rgba(0, 0, 0, 0.72)), + #1c1814 center / cover no-repeat; + display: flex; + flex-direction: column; + justify-content: flex-end; + gap: 0.15rem; +} +.cf-city-tile span { font-family: Syne, sans-serif; font-weight: 700; } +.cf-city-tile em { + font-style: normal; + font-size: 0.72rem; + color: rgba(255, 255, 255, 0.72); +} + +.cf-hosts { margin-top: 0.5rem; } +.cf-card-offline { min-height: 148px; } +.cf-cta-foot { margin-top: 1.25rem; } + +@media (prefers-reduced-motion: reduce) { + .cf-hero-offline-bg, + .cf-steam { animation: none; } +} diff --git a/src/modules/social/app/experience.css b/src/modules/social/app/experience.css index d00b3d8..9811eb3 100644 --- a/src/modules/social/app/experience.css +++ b/src/modules/social/app/experience.css @@ -745,6 +745,24 @@ font-size: 0.98rem; letter-spacing: -0.02em; } +.social-selfie-rec { + margin-left: auto; + margin-right: 6px; + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.02em; + color: #f87171; + animation: social-selfie-rec-pulse 1.2s ease-in-out infinite; +} +@keyframes social-selfie-rec-pulse { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.45; + } +} .social-selfie-close { display: grid; place-items: center; diff --git a/src/modules/social/app/h5.css b/src/modules/social/app/h5.css index 800b379..03386d3 100644 --- a/src/modules/social/app/h5.css +++ b/src/modules/social/app/h5.css @@ -2363,6 +2363,749 @@ html[data-theme="light"] .social-mobile-dock a[aria-current="page"] { background: linear-gradient(120deg, rgba(245,158,11,0.95), rgba(56,189,248,0.85)); color: #0b1020; } + +/* Places hub — simple city-first */ +.sp-hub { + --sp-amber: #f59e0b; + --sp-ink: #f4f4f5; + --sp-muted: rgba(244, 244, 245, 0.65); + --sp-line: rgba(255, 255, 255, 0.1); + max-width: 960px; + margin: 0 auto; + padding: 0.5rem 1rem 3rem; + color: var(--sp-ink); +} +.sp-hub .sr-only, +.sp-cafes .sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} +.sp-hero { + margin: 0 0 1.25rem; + padding: 1.5rem 1.15rem 1.35rem; + border-radius: 22px; + border: 1px solid var(--sp-line); + background: + radial-gradient(520px 220px at 12% -30%, rgba(245, 158, 11, 0.22), transparent 55%), + linear-gradient(165deg, #16120e 0%, #0c0c0f 70%); +} +.sp-eyebrow { + margin: 0 0 0.4rem; + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--sp-amber); +} +.sp-hero h1 { + margin: 0 0 0.45rem; + font-size: clamp(1.55rem, 4vw, 2rem); + font-weight: 800; + letter-spacing: -0.03em; + line-height: 1.1; +} +.sp-hero h1 span { color: var(--sp-amber); } +.sp-lead { + margin: 0 0 1rem; + max-width: 28rem; + color: var(--sp-muted); + line-height: 1.5; + font-size: 0.95rem; +} +.sp-hero-acts { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} +.sp-btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 44px; + padding: 0.5rem 1rem; + border-radius: 999px; + border: 1px solid var(--sp-line); + background: transparent; + color: inherit; + font: inherit; + font-weight: 600; + font-size: 0.9rem; + text-decoration: none; + cursor: pointer; +} +.sp-btn-primary { + background: var(--sp-amber); + border-color: var(--sp-amber); + color: #0c0c0f; +} +.sp-seg { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.35rem; + margin: 0 0 1rem; + padding: 0.3rem; + border-radius: 14px; + border: 1px solid var(--sp-line); + background: rgba(255, 255, 255, 0.03); +} +.sp-seg button { + min-height: 44px; + border: 0; + border-radius: 10px; + background: transparent; + color: var(--sp-muted); + font: inherit; + font-weight: 700; + cursor: pointer; +} +.sp-seg button.is-on { + background: var(--sp-amber); + color: #0c0c0f; +} +.sp-toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.55rem; + margin: 0 0 0.75rem; + align-items: center; +} +.sp-search { + flex: 1 1 200px; +} +.sp-search input { + width: 100%; + min-height: 44px; + padding: 0.5rem 0.9rem; + border-radius: 12px; + border: 1px solid var(--sp-line); + background: rgba(0, 0, 0, 0.28); + color: var(--sp-ink); + font: inherit; +} +.sp-hot { + min-height: 44px; + padding: 0 0.95rem; + border-radius: 999px; + border: 1px solid var(--sp-line); + background: transparent; + color: var(--sp-muted); + font: inherit; + font-weight: 600; + cursor: pointer; +} +.sp-hot.is-on { + border-color: rgba(245, 158, 11, 0.55); + color: var(--sp-amber); + background: rgba(245, 158, 11, 0.1); +} +.sp-count { + margin: 0 0 0.75rem; + font-size: 0.82rem; + color: var(--sp-muted); +} +.sp-muted { + color: var(--sp-muted); + font-size: 0.9rem; +} +.sp-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.65rem; +} +@media (min-width: 720px) { + .sp-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } +} +@media (min-width: 980px) { + .sp-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } +} +.sp-card { + position: relative; + display: block; + min-height: 150px; + border-radius: 16px; + overflow: hidden; + text-decoration: none; + color: #fff; + background: #1a1612 center / cover no-repeat; + border: 1px solid var(--sp-line); + transition: transform 0.15s ease, border-color 0.15s ease; +} +.sp-card:hover { + transform: translateY(-2px); + border-color: rgba(245, 158, 11, 0.45); +} +.sp-card-veil { + position: absolute; + inset: 0; + background: linear-gradient(180deg, transparent 15%, rgba(0, 0, 0, 0.78)); +} +.sp-card-body { + position: relative; + z-index: 1; + display: grid; + gap: 0.2rem; + align-content: end; + min-height: 150px; + padding: 0.85rem 0.9rem; +} +.sp-card-body em { + font-style: normal; + font-size: 0.7rem; + color: rgba(255, 255, 255, 0.7); +} +.sp-card-body strong { + font-size: 1.1rem; + letter-spacing: -0.02em; +} +.sp-card-body p { + margin: 0; + font-size: 0.78rem; + color: rgba(255, 255, 255, 0.72); + line-height: 1.35; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +/* Cafes tab — city-first list + expand sheet */ +.sp-cafe-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 0.75rem; + margin: 0 0 0.85rem; + padding: 0.25rem 0 0.15rem; +} +.sp-cafe-head h1 { + margin: 0; + font-size: clamp(1.35rem, 3.6vw, 1.7rem); + font-weight: 800; + letter-spacing: -0.03em; + line-height: 1.15; +} +.sp-cafe-head h1 span { color: var(--sp-amber, #f59e0b); } +.sp-cafe-head .sp-btn { + flex-shrink: 0; + min-height: 40px; + padding: 0 0.9rem; + font-size: 0.84rem; +} +.sp-lead--tight { + margin: -0.35rem 0 0.9rem; + font-size: 0.9rem; +} +.sp-card { + width: 100%; + cursor: pointer; + font: inherit; + text-align: left; + appearance: none; +} +.sp-places-cafes { + margin-top: 1.35rem; + padding-top: 1.1rem; + border-top: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); +} +.sp-places-cafes-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + margin: 0 0 0.85rem; +} +.sp-places-cafes-head h2 { + margin: 0; + font-size: 1.05rem; + font-weight: 800; + letter-spacing: -0.02em; +} +.sp-link { + color: var(--sp-amber, #f59e0b); + font-size: 0.82rem; + font-weight: 600; + text-decoration: none; +} +.sp-cafe-city-banner-acts { + display: flex; + flex-wrap: wrap; + gap: 0.45rem; + margin-top: 0.45rem; +} +.sp-cafe-city-banner-acts .sp-btn { + min-height: 36px; + padding: 0 0.85rem; + font-size: 0.82rem; +} +.sp-cafes { + display: grid; + gap: 0.85rem; +} +.sp-cafe-sheet-acts .social-save { + min-height: 44px; + padding: 0 0.85rem; + border-radius: 999px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: transparent; + color: inherit; + font: inherit; + font-size: 0.86rem; + font-weight: 600; + cursor: pointer; +} +.sp-cafe-page-head { + margin: 0 0 0.25rem; +} +.sp-cafe-page-head h1 { + margin: 0 0 0.4rem; + font-size: clamp(1.45rem, 4vw, 1.85rem); + font-weight: 800; + letter-spacing: -0.03em; +} +.sp-cafe-page-head h1 span { color: var(--sp-amber, #f59e0b); } +.sp-cafe-city-rail { + display: flex; + gap: 0.45rem; + overflow-x: auto; + padding: 0.15rem 0 0.25rem; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; +} +.sp-cafe-city-rail::-webkit-scrollbar { display: none; } +.sp-cafe-city-rail button { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + gap: 0.35rem; + min-height: 40px; + padding: 0 0.9rem; + border-radius: 999px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: transparent; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); + font: inherit; + font-size: 0.86rem; + font-weight: 600; + cursor: pointer; + white-space: nowrap; +} +.sp-cafe-city-rail button.is-on { + color: #0c0c0f; + background: var(--sp-amber, #f59e0b); + border-color: var(--sp-amber, #f59e0b); +} +.sp-cafe-city-banner { + position: relative; + overflow: hidden; + min-height: 112px; + border-radius: 16px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: #16120e center / cover no-repeat; +} +.sp-cafe-city-banner-veil { + position: absolute; + inset: 0; + background: linear-gradient( + 105deg, + rgba(12, 12, 15, 0.9) 8%, + rgba(12, 12, 15, 0.35) 70%, + rgba(12, 12, 15, 0.55) + ); +} +.sp-cafe-city-banner-copy { + position: relative; + z-index: 1; + display: grid; + gap: 0.2rem; + padding: 1rem 1.05rem; + color: #f4f4f5; +} +.sp-cafe-city-banner-copy p { + margin: 0; + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-size: 0.72rem; + color: rgba(244, 244, 245, 0.7); +} +.sp-cafe-city-banner-copy strong { + font-size: 1.2rem; + letter-spacing: -0.02em; +} +.sp-cafe-city-banner-copy em { + font-style: normal; + font-size: 0.8rem; + color: var(--sp-amber, #f59e0b); +} +.sp-cafe-toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.55rem; + align-items: center; +} +.sp-cafe-sort-select { + min-height: 44px; + padding: 0 0.85rem; + border-radius: 12px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: rgba(0, 0, 0, 0.28); + color: var(--sp-ink, #f4f4f5); + font: inherit; + font-size: 0.86rem; +} +.sp-cafe-search { + flex: 1 1 180px; + display: flex; + align-items: center; + gap: 0.5rem; + min-height: 44px; + padding: 0 0.85rem; + border-radius: 12px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: rgba(0, 0, 0, 0.28); + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); +} +.sp-cafe-search input { + flex: 1; + min-width: 0; + border: 0; + background: transparent; + color: var(--sp-ink, #f4f4f5); + font: inherit; + outline: none; +} +.sp-cafe-sort { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; +} +.sp-cafe-sort button { + min-height: 34px; + padding: 0 0.75rem; + border-radius: 999px; + border: 1px solid transparent; + background: rgba(255, 255, 255, 0.04); + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); + font: inherit; + font-size: 0.78rem; + font-weight: 600; + cursor: pointer; +} +.sp-cafe-sort button.is-on { + border-color: rgba(245, 158, 11, 0.45); + color: var(--sp-amber, #f59e0b); + background: rgba(245, 158, 11, 0.1); +} +.sp-cafe-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 0.55rem; +} +.sp-cafe-row { + width: 100%; + display: grid; + grid-template-columns: auto 1fr auto; + gap: 0.75rem; + align-items: center; + min-height: 72px; + padding: 0.85rem 0.9rem; + border-radius: 16px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: rgba(255, 255, 255, 0.03); + color: inherit; + text-align: left; + font: inherit; + cursor: pointer; + transition: border-color 0.15s ease, background 0.15s ease; +} +.sp-cafe-row:hover, +.sp-cafe-row.is-open { + border-color: rgba(245, 158, 11, 0.45); + background: rgba(245, 158, 11, 0.06); +} +.sp-cafe-row.is-partner .sp-cafe-row-mark { + background: rgba(245, 158, 11, 0.16); + color: var(--sp-amber, #f59e0b); +} +.sp-cafe-row-mark { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.06); + color: rgba(244, 244, 245, 0.75); +} +.sp-cafe-row-main { + display: grid; + gap: 0.18rem; + min-width: 0; +} +.sp-cafe-row-main strong { + font-size: 1rem; + letter-spacing: -0.02em; + line-height: 1.25; +} +.sp-cafe-row-main em { + display: inline-flex; + align-items: center; + gap: 0.25rem; + font-style: normal; + font-size: 0.78rem; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.sp-cafe-row-meta { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + margin-top: 0.1rem; +} +.sp-cafe-row-meta > span { + font-size: 0.7rem; + padding: 0.12rem 0.45rem; + border-radius: 999px; + background: rgba(255, 255, 255, 0.06); + color: rgba(244, 244, 245, 0.72); +} +.sp-cafe-row-meta .is-tag { + color: var(--sp-amber, #f59e0b); + background: rgba(245, 158, 11, 0.12); +} +.sp-cafe-row-go { + color: rgba(244, 244, 245, 0.45); + flex-shrink: 0; +} +.sp-cafe-row.is-open .sp-cafe-row-go { + color: var(--sp-amber, #f59e0b); + transform: rotate(90deg); +} +.sp-cafe-sheet { + margin-top: 0.45rem; + border-radius: 18px; + border: 1px solid rgba(245, 158, 11, 0.28); + overflow: hidden; + background: #0f0e0c; + animation: sp-cafe-in 0.22s ease; +} +@keyframes sp-cafe-in { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} +@media (prefers-reduced-motion: reduce) { + .sp-cafe-sheet { animation: none; } +} +.sp-cafe-sheet-hero { + position: relative; + min-height: 132px; + background: #1a1612 center / cover no-repeat; +} +.sp-cafe-sheet-veil { + position: absolute; + inset: 0; + background: linear-gradient(180deg, rgba(0, 0, 0, 0.15), rgba(12, 12, 15, 0.92)); +} +.sp-cafe-sheet-close { + position: absolute; + top: 0.65rem; + right: 0.65rem; + z-index: 2; + display: grid; + place-items: center; + width: 36px; + height: 36px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.18); + background: rgba(0, 0, 0, 0.45); + color: #fff; + cursor: pointer; +} +.sp-cafe-sheet-hero-copy { + position: relative; + z-index: 1; + display: grid; + gap: 0.25rem; + padding: 1.35rem 1.05rem 1rem; + color: #f4f4f5; +} +.sp-cafe-sheet-hero-copy p { + margin: 0; + font-size: 0.75rem; + color: rgba(244, 244, 245, 0.75); +} +.sp-cafe-sheet-hero-copy h2 { + margin: 0; + font-size: 1.35rem; + letter-spacing: -0.03em; + line-height: 1.15; +} +.sp-cafe-sheet-hero-copy em { + font-style: normal; + font-size: 0.86rem; + color: var(--sp-amber, #f59e0b); +} +.sp-cafe-sheet-body { + display: grid; + gap: 0.85rem; + padding: 0.95rem 1.05rem 1.15rem; +} +.sp-cafe-facts { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} +.sp-cafe-facts li { + display: inline-flex; + align-items: center; + gap: 0.35rem; + min-height: 34px; + padding: 0 0.7rem; + border-radius: 999px; + background: rgba(255, 255, 255, 0.05); + font-size: 0.78rem; + color: rgba(244, 244, 245, 0.82); +} +.sp-cafe-sheet-acts { + display: grid; + gap: 0.5rem; +} +.sp-cafe-sheet-cta { + width: 100%; + gap: 0.4rem; +} +.sp-cafe-sheet-sec { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + align-items: center; +} +.sp-cafe-sheet-sec .sp-btn { + flex: 1 1 auto; + min-width: 8.5rem; +} +.sp-cafe-soft { + margin: 0; + font-size: 0.82rem; + line-height: 1.45; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); +} +.sp-cafe-reviews { + border-top: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + padding-top: 0.35rem; +} +.sp-cafe-reviews-toggle { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + min-height: 44px; + padding: 0 0.15rem; + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-weight: 700; + cursor: pointer; +} +.sp-cafe-reviews-toggle svg { + transition: transform 0.15s ease; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); +} +.sp-cafe-reviews-toggle.is-open svg { + transform: rotate(180deg); +} +.sp-cafe-reviews-body { + display: grid; + gap: 0.75rem; + padding-bottom: 0.35rem; +} +.sp-cafe-review-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 0.55rem; +} +.sp-cafe-review-list li { + padding: 0.7rem 0.8rem; + border-radius: 12px; + background: rgba(255, 255, 255, 0.04); +} +.sp-cafe-review-list header { + display: flex; + justify-content: space-between; + gap: 0.5rem; + margin-bottom: 0.25rem; + font-size: 0.82rem; +} +.sp-cafe-review-list p { + margin: 0; + font-size: 0.86rem; + line-height: 1.45; + color: rgba(244, 244, 245, 0.85); +} +.sp-cafe-review-form { + display: grid; + gap: 0.55rem; +} +.sp-cafe-review-form label { + display: grid; + gap: 0.3rem; + font-size: 0.78rem; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); +} +.sp-cafe-review-form input, +.sp-cafe-review-form textarea { + min-height: 42px; + padding: 0.55rem 0.75rem; + border-radius: 10px; + border: 1px solid var(--sp-line, rgba(255, 255, 255, 0.1)); + background: rgba(0, 0, 0, 0.28); + color: var(--sp-ink, #f4f4f5); + font: inherit; +} +.sp-cafe-review-form textarea { min-height: 84px; resize: vertical; } +.sp-cafe-stars { + margin: 0; + padding: 0; + border: 0; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.25rem; +} +.sp-cafe-stars legend { + width: 100%; + margin-bottom: 0.25rem; + font-size: 0.78rem; + color: var(--sp-muted, rgba(244, 244, 245, 0.65)); +} +.sp-cafe-stars button { + display: grid; + place-items: center; + width: 36px; + height: 36px; + border: 0; + border-radius: 8px; + background: transparent; + color: rgba(244, 244, 245, 0.35); + cursor: pointer; +} +.sp-cafe-stars button.is-on { color: var(--sp-amber, #f59e0b); } + .social-places-remote { margin: 0 0 1.25rem; } .social-places-remote h2 { font-size: 1rem; margin: 0 0 0.6rem; } .social-places-remote-list { diff --git a/src/modules/social/app/home.css b/src/modules/social/app/home.css index 16d6edb..bda751d 100644 --- a/src/modules/social/app/home.css +++ b/src/modules/social/app/home.css @@ -2443,6 +2443,98 @@ padding-top: 28px; padding-bottom: 4px; } +.home-coffee-city-rail { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + margin: 0 0 14px; +} +.home-coffee-city-chip { + min-height: 40px; + padding: 0 14px; + border-radius: 999px; + border: 1px solid var(--connection-border); + background: transparent; + color: var(--text-secondary); + font: inherit; + font-size: 13px; + font-weight: 600; + cursor: pointer; +} +.home-coffee-city-chip.is-on { + color: #0c0c0f; + background: #f59e0b; + border-color: #f59e0b; +} +.home-coffee-city-more { + display: inline-flex; + align-items: center; + gap: 4px; + min-height: 40px; + padding: 0 8px; + color: #f59e0b; + font-size: 13px; + font-weight: 600; + text-decoration: none; +} +.home-coffee-city-stage { + position: relative; + overflow: hidden; + min-height: 180px; + margin-bottom: 14px; + border-radius: 18px; + border: 1px solid var(--connection-border); + background: #121214 center / cover no-repeat; +} +.home-coffee-city-stage-veil { + position: absolute; + inset: 0; + background: linear-gradient( + 100deg, + rgba(12, 12, 15, 0.88) 12%, + rgba(12, 12, 15, 0.35) 70%, + rgba(12, 12, 15, 0.55) + ); +} +.home-coffee-city-stage-copy { + position: relative; + z-index: 1; + display: grid; + gap: 6px; + padding: 18px 16px; + color: #f4f4f5; + max-width: 28rem; +} +.home-coffee-city-stage-copy p { + margin: 0; + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: rgba(244, 244, 245, 0.7); +} +.home-coffee-city-stage-copy strong { + font-family: inherit; + font-size: clamp(1.25rem, 3vw, 1.6rem); + letter-spacing: -0.03em; +} +.home-coffee-city-stage-copy em { + font-style: normal; + font-size: 13px; + color: #f59e0b; +} +.home-coffee-city-blurb { + font-size: 14px !important; + line-height: 1.45; + color: rgba(244, 244, 245, 0.78) !important; +} +.home-coffee-city-acts { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 6px; +} .home-coffee-card { display: flex; align-items: center; diff --git a/src/modules/social/app/interaction.css b/src/modules/social/app/interaction.css index cf1e439..e1d9435 100644 --- a/src/modules/social/app/interaction.css +++ b/src/modules/social/app/interaction.css @@ -722,11 +722,7 @@ background: var(--bg-glass); } .social-nick-label { - display: flex; - align-items: center; - gap: 7px; - font-size: 10px; - color: var(--text-muted); + display: none; /* 未注册随机昵称,不再露出游客输入框 */ } .social-workspace .social-nick-label input { width: 90px; @@ -1769,11 +1765,20 @@ transform: rotate(-12deg); } .social-date-stamp.pass { - right: 18px; - color: #ff8f8f; - border-color: #ff6b6b; - background: rgba(255, 107, 107, 0.12); - transform: rotate(12deg); + display: none; /* 去掉卡片右上「划走」水印 */ +} +.social-date-gender { + display: inline-block; + margin-right: 0.15em; + font-size: 0.92em; + vertical-align: -0.05em; +} +.social-chat-join-hint { + width: 100%; + text-align: left; + cursor: pointer; + border: 0; + appearance: none; } .social-date-photo-dots { position: absolute; diff --git a/src/modules/social/components/AttractiveRoster.tsx b/src/modules/social/components/AttractiveRoster.tsx index 7e4971e..c21e81c 100644 --- a/src/modules/social/components/AttractiveRoster.tsx +++ b/src/modules/social/components/AttractiveRoster.tsx @@ -146,7 +146,6 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {

    {socialTx("点开卡片,看看对方在做什么、想认识谁。")} - {socialTx("现在是示例介绍,方便你先逛逛")} {roster.some((m) => m.id === SELF_MEMBER_ID) ? socialTx("(也包含你写好的介绍)") : ""} @@ -162,7 +161,6 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {

    {online.length}{" "} {socialTx("位现在在线")} - · {socialTx("示例数据")}

    + {open ? ( +
    + {!reviews.length ? ( +

    {socialTx("还没有评价")} · {socialTx("写一条帮后来的人。")}

    + ) : ( +
      + {reviews.map((review) => ( +
    • +
      + {review.author} + {"★".repeat(Math.max(1, Math.min(5, review.score)))} +
      +

      {review.text}

      + {review.local ? ( + + ) : null} +
    • + ))} +
    + )} + void submit(e)}> -
    +
    {socialTx("评分")} {[1, 2, 3, 4, 5].map((value) => ( @@ -229,12 +230,11 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {