Ship social places/join UX, room-archive ops, and rich Markdown ntfy alerts.
Unify city+cafe into one places page, gate join with on-page modal, and enrich ntfy with icons, tables, and action buttons across portal/API/admin. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
308974bf5e
commit
3e60ba1a1b
547
apps/admin/deploy/_vip_track_assets/server.py
Normal file
547
apps/admin/deploy/_vip_track_assets/server.py
Normal file
@ -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()
|
||||
@ -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, unknown>): 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<string, unknown>)
|
||||
: {}
|
||||
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, unknown>): 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<Tab>('joins')
|
||||
const [overview, setOverview] = useState<Overview | null>(null)
|
||||
@ -346,8 +375,8 @@ export default function SocialData() {
|
||||
</div>
|
||||
</td>
|
||||
<td>{it.stage || '—'}</td>
|
||||
<td>{it.paid === '1' || it.paid === true ? '已付' : '未付'}</td>
|
||||
<td>{it.livenessStatus || (it.faceOk ? 'ok' : '—')}</td>
|
||||
<td>{joinPaidCell(it)}</td>
|
||||
<td>{joinLiveCell(it)}</td>
|
||||
<td>{it.updatedAt || it.createdAt || '—'}</td>
|
||||
</tr>
|
||||
)
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
}
|
||||
|
||||
@ -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 = "",
|
||||
|
||||
@ -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]:
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -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(
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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() {
|
||||
<Route index element={<Navigate to="social/overview" replace />} />
|
||||
<Route path="audience" element={<LaneHome />} />
|
||||
<Route path="operations" element={<Operations />} />
|
||||
<Route path="pricing" element={<Pricing />} />
|
||||
<Route path="switches" element={<Switches />} />
|
||||
<Route path="social" element={<Navigate to="overview" replace />} />
|
||||
<Route path="social/overview" element={<Social />} />
|
||||
@ -88,6 +90,7 @@ export default function App() {
|
||||
<Route path="social/gigs" element={<Social />} />
|
||||
<Route path="social/skills" element={<Social />} />
|
||||
<Route path="social/liveness" element={<Social />} />
|
||||
<Route path="social/roomArchives" element={<Social />} />
|
||||
<Route path="social/coffee" element={<Social />} />
|
||||
<Route path="social/trips" element={<Social />} />
|
||||
<Route path="social/reports" element={<Social />} />
|
||||
@ -105,6 +108,7 @@ export default function App() {
|
||||
<Route path="social/gigApps/:id" element={<SocialDetail />} />
|
||||
<Route path="social/skills/:id" element={<SocialDetail />} />
|
||||
<Route path="social/liveness/:id" element={<SocialDetail />} />
|
||||
<Route path="social/roomArchives/:id" element={<SocialDetail />} />
|
||||
<Route path="social/coffee/:id" element={<SocialDetail />} />
|
||||
<Route path="social/trips/:id" element={<SocialDetail />} />
|
||||
<Route path="social/reports/:id" element={<SocialDetail />} />
|
||||
@ -123,6 +127,7 @@ export default function App() {
|
||||
</Route>
|
||||
|
||||
<Route path="/audience" element={<Navigate to="/" replace />} />
|
||||
<Route path="/pricing" element={<Navigate to="/" replace />} />
|
||||
<Route path="/switches" element={<Navigate to="/" replace />} />
|
||||
<Route path="/events" element={<Navigate to="/" replace />} />
|
||||
<Route path="/orders" element={<Navigate to="/" replace />} />
|
||||
|
||||
@ -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<LaneKey, { title: string; mark: string; sub: string }> = {
|
||||
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<HTMLInputElement>(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<HTMLElement>('.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<HTMLElement>('.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 (
|
||||
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
|
||||
<a className="com-skip" href="#main-content">跳至主要内容</a>
|
||||
<a className="com-skip" href="#main-content">
|
||||
跳至主要内容
|
||||
</a>
|
||||
<header className="com-topbar">
|
||||
<button
|
||||
type="button"
|
||||
@ -206,11 +237,7 @@ export default function WebLayout() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="com-lane-switch" role="group" aria-label="受众">
|
||||
<button
|
||||
type="button"
|
||||
className={lane === 'cn' ? 'is-on' : ''}
|
||||
onClick={() => switchLane('cn')}
|
||||
>
|
||||
<button type="button" className={lane === 'cn' ? 'is-on' : ''} onClick={() => switchLane('cn')}>
|
||||
中文
|
||||
</button>
|
||||
<button
|
||||
@ -223,14 +250,9 @@ export default function WebLayout() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{open && (
|
||||
<button
|
||||
type="button"
|
||||
className="com-nav-scrim"
|
||||
aria-label="关闭菜单"
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{open ? (
|
||||
<button type="button" className="com-nav-scrim" aria-label="关闭菜单" onClick={() => setOpen(false)} />
|
||||
) : null}
|
||||
|
||||
<aside className="com-side">
|
||||
<div className="com-logo">
|
||||
@ -242,11 +264,7 @@ export default function WebLayout() {
|
||||
</div>
|
||||
|
||||
<div className="com-lane-switch com-lane-switch--side" role="group" aria-label="受众">
|
||||
<button
|
||||
type="button"
|
||||
className={lane === 'cn' ? 'is-on' : ''}
|
||||
onClick={() => switchLane('cn')}
|
||||
>
|
||||
<button type="button" className={lane === 'cn' ? 'is-on' : ''} onClick={() => switchLane('cn')}>
|
||||
<em>{LANE_META.cn.mark}</em>
|
||||
中文
|
||||
</button>
|
||||
@ -260,20 +278,47 @@ export default function WebLayout() {
|
||||
</button>
|
||||
</div>
|
||||
<p className="com-lane-hint">{meta.sub}</p>
|
||||
<div className="com-nav-search"><input ref={searchRef} type="search" aria-label="搜索后台功能" placeholder="搜索功能… Ctrl K" value={query} onChange={e => setQuery(e.target.value)} /></div>
|
||||
|
||||
<NavLink to={`/${lane}/pricing`} className="com-nav-price-jump">
|
||||
<span className="com-nav-price-mark" aria-hidden>
|
||||
¥
|
||||
</span>
|
||||
<span>
|
||||
<strong>动态价格</strong>
|
||||
<em>免费 / 付费一键切换</em>
|
||||
</span>
|
||||
</NavLink>
|
||||
|
||||
<div className="com-nav-search">
|
||||
<input
|
||||
ref={searchRef}
|
||||
type="search"
|
||||
aria-label="搜索后台功能"
|
||||
placeholder="搜索功能… Ctrl K"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<nav className="com-nav" aria-label="后台导航">
|
||||
{visibleGroups.length === 0 && <p className="com-muted">没有匹配的功能</p>}
|
||||
{visibleGroups.length === 0 ? <p className="com-muted">没有匹配的功能</p> : null}
|
||||
{visibleGroups.map((group) => (
|
||||
<div key={group.id} className="com-nav-group">
|
||||
<div key={group.id} className={`com-nav-group${group.id === 'monetize' ? ' is-money' : ''}`}>
|
||||
<div className="com-nav-group-label">{group.label}</div>
|
||||
{group.items.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.end}
|
||||
className={({ isActive }) => (isActive ? 'active' : '')}
|
||||
className={({ isActive }) =>
|
||||
`${isActive ? 'active' : ''}${item.accent ? ' is-accent' : ''}`.trim()
|
||||
}
|
||||
>
|
||||
{item.ico ? (
|
||||
<span className="com-nav-ico" aria-hidden>
|
||||
{item.ico}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="com-nav-label">{item.label}</span>
|
||||
{item.hint ? <span className="com-nav-hint">{item.hint}</span> : null}
|
||||
</NavLink>
|
||||
@ -283,13 +328,15 @@ export default function WebLayout() {
|
||||
</nav>
|
||||
|
||||
<div className="com-side-foot">
|
||||
<button className="com-logout" type="button" onClick={toggleTheme} aria-label={theme === 'dark' ? '切换浅色主题' : '切换深色主题'}>{theme === 'dark' ? '☀ 浅色模式' : '◐ 深色模式'}</button>
|
||||
<a
|
||||
className="com-side-link"
|
||||
href="https://nomadro.com/social"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
<button
|
||||
className="com-logout"
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
aria-label={theme === 'dark' ? '切换浅色主题' : '切换深色主题'}
|
||||
>
|
||||
{theme === 'dark' ? '浅色模式' : '深色模式'}
|
||||
</button>
|
||||
<a className="com-side-link" href="https://nomadro.com/social" target="_blank" rel="noreferrer">
|
||||
打开前台 ↗
|
||||
</a>
|
||||
<button type="button" className="com-logout" onClick={logout}>
|
||||
@ -299,8 +346,23 @@ export default function WebLayout() {
|
||||
</aside>
|
||||
|
||||
<main className="com-main" id="main-content" tabIndex={-1}>
|
||||
<div className="com-workspace-bar"><div><span className="com-workspace-label">NOMADRO / WORKSPACE</span><p>{meta.title}受众 <span>/</span> {pageTitle}</p></div><span className={`com-connection${online ? '' : ' is-offline'}`} role="status"><i />{online ? '网络已连接' : '网络已断开'}</span></div>
|
||||
{!online && <div className="com-toast com-toast-err" role="alert">网络已断开,请恢复连接后继续保存操作。</div>}
|
||||
<div className="com-workspace-bar">
|
||||
<div>
|
||||
<span className="com-workspace-label">NOMADRO / WORKSPACE</span>
|
||||
<p>
|
||||
{meta.title}受众 <span>/</span> {pageTitle}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`com-connection${online ? '' : ' is-offline'}`} role="status">
|
||||
<i />
|
||||
{online ? '网络已连接' : '网络已断开'}
|
||||
</span>
|
||||
</div>
|
||||
{!online ? (
|
||||
<div className="com-toast com-toast-err" role="alert">
|
||||
网络已断开,请恢复连接后继续保存操作。
|
||||
</div>
|
||||
) : null}
|
||||
<Outlet key={lane} />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -15,7 +15,10 @@ export default function Docs() {
|
||||
<code>/cn</code> · <code>/intl</code> — 受众模块总览与本轨开关
|
||||
</li>
|
||||
<li>
|
||||
<code>…/switches</code> — 页面 / flag / VIP / 文案(remote-config)
|
||||
<code>…/pricing</code> — 动态价格(免费/付费 · 体验次数 · 支付开关)
|
||||
</li>
|
||||
<li>
|
||||
<code>…/switches</code> — 页面 / flag / VIP 区块 / 文案(remote-config)
|
||||
</li>
|
||||
<li>
|
||||
<code>…/social</code> — 游民社区 UGC(聊天 / 花名册 / 评价 / 接单 / 反馈)
|
||||
|
||||
@ -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 试推' },
|
||||
|
||||
@ -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}`
|
||||
|
||||
@ -12,7 +12,9 @@ type NtfyStatus = {
|
||||
export default function Ntfy() {
|
||||
const [status, setStatus] = useState<NtfyStatus | null>(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() {
|
||||
<div>
|
||||
<h1>ntfy 通知</h1>
|
||||
<p>
|
||||
查看通知通路状态;关键埋点和支付事件由服务端推送。
|
||||
关键埋点 / 支付事件推 Markdown 富文本(图标、表格、点击跳转、操作按钮)。
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={load} disabled={loading}>
|
||||
|
||||
423
apps/com/admin/src/pages/Pricing.tsx
Normal file
423
apps/com/admin/src/pages/Pricing.tsx
Normal file
@ -0,0 +1,423 @@
|
||||
/**
|
||||
* 动态价格 — VIP / 游民加入价 + 免费体验次数
|
||||
* 写入 remote-config.copy.vipPriceFen;门户 / VIP / 支付实时跟随。
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
import { useConfigLive } from '../lib/useConfigLive'
|
||||
|
||||
type PricingCfg = {
|
||||
flags: {
|
||||
payEnabled?: boolean
|
||||
socialTrialEnabled?: boolean
|
||||
}
|
||||
copy: {
|
||||
vipCta?: string
|
||||
vipPriceFen?: number
|
||||
socialTrial?: {
|
||||
enabled?: boolean
|
||||
chatMessages?: number
|
||||
dateViews?: number
|
||||
coffeeBookings?: number
|
||||
mapOpens?: number
|
||||
}
|
||||
}
|
||||
version?: number
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
const PRESETS = [
|
||||
{ label: '免费', yuan: '0', hint: '临时放行' },
|
||||
{ label: '¥0.1', yuan: '0.1', hint: '支付冒烟' },
|
||||
{ label: '¥1', yuan: '1', hint: '低价测试' },
|
||||
{ label: '¥9.9', yuan: '9.9', hint: '入门' },
|
||||
{ label: '¥29', yuan: '29', hint: '常用' },
|
||||
{ label: '¥88', yuan: '88', hint: '现网档' },
|
||||
{ label: '¥99', yuan: '99', hint: '标准' },
|
||||
{ label: '¥298', yuan: '298', hint: '高档' },
|
||||
] as const
|
||||
|
||||
function fenToYuanInput(fen: number) {
|
||||
if (fen % 100 === 0) return String(fen / 100)
|
||||
return (fen / 100).toFixed(2).replace(/0+$/, '').replace(/\.$/, '')
|
||||
}
|
||||
|
||||
function formatYuan(fen: number) {
|
||||
if (fen <= 0) return '免费'
|
||||
return fen % 100 === 0 ? `¥${fen / 100}` : `¥${(fen / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
label: string
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<label className="com-switch" title={label}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
aria-label={label}
|
||||
/>
|
||||
<span className="com-switch-track">
|
||||
<span className="com-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Pricing() {
|
||||
const { lane } = useParams()
|
||||
const laneKey = lane === 'cn' ? 'cn' : 'intl'
|
||||
const live = useConfigLive()
|
||||
const [cfg, setCfg] = useState<PricingCfg | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [priceYuan, setPriceYuan] = useState('88')
|
||||
const [vipCta, setVipCta] = useState('')
|
||||
const [trialDraft, setTrialDraft] = useState({
|
||||
enabled: true,
|
||||
chatMessages: 1,
|
||||
dateViews: 5,
|
||||
coffeeBookings: 0,
|
||||
mapOpens: 3,
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<PricingCfg>('/api/admin/weapp/switches')
|
||||
setCfg(data)
|
||||
const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0)
|
||||
setPriceYuan(fenToYuanInput(fen))
|
||||
setVipCta(data.copy?.vipCta || '')
|
||||
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(() => {
|
||||
load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<PricingCfg>('/api/admin/weapp/switches', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...body, expectedVersion: cfg?.version }),
|
||||
})
|
||||
setCfg(data)
|
||||
const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0)
|
||||
setPriceYuan(fenToYuanInput(fen))
|
||||
setVipCta(data.copy?.vipCta || '')
|
||||
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 : '保存失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const liveFen = Math.max(0, Number(cfg?.copy?.vipPriceFen) || 0)
|
||||
const isFree = liveFen <= 0
|
||||
const draftFen = useMemo(() => {
|
||||
const yuan = Number(priceYuan)
|
||||
if (!Number.isFinite(yuan) || yuan < 0) return null
|
||||
return Math.round(yuan * 100)
|
||||
}, [priceYuan])
|
||||
const dirty =
|
||||
draftFen != null &&
|
||||
(draftFen !== liveFen || (vipCta || '').trim() !== (cfg?.copy?.vipCta || '').trim())
|
||||
|
||||
// 其他页面 / 进程改了配置 → 本页跟价,避免脏 expectedVersion 覆盖
|
||||
useEffect(() => {
|
||||
if (!live.meta?.version || cfg?.version == null) return
|
||||
if (live.meta.version === cfg.version) return
|
||||
if (dirty || busy) return
|
||||
void load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [live.meta?.version, cfg?.version, dirty, busy, load])
|
||||
|
||||
function savePrice() {
|
||||
const yuan = Number(priceYuan)
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(priceYuan.trim()) || !Number.isFinite(yuan) || yuan < 0 || yuan > 1000000) {
|
||||
setErr('请填写 0–1,000,000 元,最多两位小数;免费填 0')
|
||||
return
|
||||
}
|
||||
const fen = Math.round(yuan * 100)
|
||||
const autoCta =
|
||||
fen <= 0 ? '免费加入' : `立即加入 · ¥${fen % 100 === 0 ? fen / 100 : (fen / 100).toFixed(2)}`
|
||||
const typed = vipCta.trim()
|
||||
const nextCta = !typed || typed.includes('¥') || typed.includes('¥') ? autoCta : typed
|
||||
void patch(
|
||||
{ copy: { vipCta: nextCta, vipPriceFen: fen } },
|
||||
fen <= 0 ? '已设为免费加入(0 分)' : `动态价格已更新为 ${formatYuan(fen)}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (!cfg) {
|
||||
return (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head">
|
||||
<h1>动态价格</h1>
|
||||
<p>加载远程配置…</p>
|
||||
</header>
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="com-page com-pricing">
|
||||
<header className="com-page-head">
|
||||
<div className="com-pricing-eyebrow">REMOTE · LIVE · {laneKey.toUpperCase()}</div>
|
||||
<h1>动态价格</h1>
|
||||
<p>
|
||||
改这里,门户 VIP / 游民加入支付立刻跟价。0 元=免费加入;保存后约数秒热更新。页面显隐请去
|
||||
<Link to={`/${laneKey}/switches`}> 页面开关</Link>。
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className={`com-chip${isFree ? ' com-chip-ok' : ' is-on'}`}>
|
||||
{isFree ? '当前免费' : `当前 ${formatYuan(liveFen)}`}
|
||||
</span>
|
||||
<span className={`com-chip${cfg.flags?.payEnabled !== false ? ' com-chip-ok' : ''}`}>
|
||||
{cfg.flags?.payEnabled !== false ? '支付开' : '支付关'}
|
||||
</span>
|
||||
<span className="com-chip">v{cfg.version ?? '—'}</span>
|
||||
{cfg.updatedAt ? <span className="com-chip">{cfg.updatedAt}</span> : null}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
|
||||
<div className="com-config-live" role="status">
|
||||
<span className={`com-status-dot${live.connected ? '' : ' is-polling'}`} />
|
||||
{live.connected ? '实时配置通道已连接' : '配置轮询兜底中'}
|
||||
<span>
|
||||
服务端 v{live.meta?.version ?? '—'} · 当前编辑 v{cfg.version ?? '—'}
|
||||
</span>
|
||||
</div>
|
||||
{live.meta && cfg.version != null && live.meta.version !== cfg.version ? (
|
||||
<div className="com-toast">
|
||||
配置已在其他页面更新。请刷新后再保存,避免覆盖。
|
||||
<button
|
||||
className="com-btn"
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (window.confirm('刷新将放弃未保存修改,继续?')) {
|
||||
void load().catch((e) => setErr(String(e)))
|
||||
}
|
||||
}}
|
||||
>
|
||||
加载最新
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<section className="com-pricing-hero">
|
||||
<div className="com-pricing-hero-main">
|
||||
<span className="com-pricing-kicker">线上生效价</span>
|
||||
<strong className={isFree ? 'is-free' : ''}>{formatYuan(liveFen)}</strong>
|
||||
<p>
|
||||
{isFree
|
||||
? '免费模式:不拉支付,前台临时放行;切回付费后未开通用户仍须付费。'
|
||||
: `${liveFen} 分 · 门户 / VIP / 游民加入共用此价`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="com-pricing-hero-side">
|
||||
<div className="com-pricing-preview">
|
||||
<span>按钮预览</span>
|
||||
<em>{cfg.copy?.vipCta || (isFree ? '免费加入' : `立即加入 · ${formatYuan(liveFen)}`)}</em>
|
||||
</div>
|
||||
<div className="com-flag-row com-pricing-pay-row">
|
||||
<div>
|
||||
<strong>支付总开关</strong>
|
||||
<p>关闭后隐藏付费 CTA</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={cfg.flags?.payEnabled !== false}
|
||||
disabled={busy}
|
||||
label="支付总开关"
|
||||
onChange={(v) => void patch({ flags: { payEnabled: v } }, v ? '支付已开启' : '支付已关闭')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>一键改价</h2>
|
||||
<p className="com-panel-desc">点档位或手填金额,再点保存。前台实时吃新价。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="com-pricing-presets" role="group" aria-label="价格档位">
|
||||
{PRESETS.map((p) => {
|
||||
const on = priceYuan === p.yuan
|
||||
return (
|
||||
<button
|
||||
key={p.yuan}
|
||||
type="button"
|
||||
className={`com-pricing-preset${on ? ' is-on' : ''}${p.yuan === '0' ? ' is-free' : ''}`}
|
||||
disabled={busy}
|
||||
onClick={() => setPriceYuan(p.yuan)}
|
||||
>
|
||||
<strong>{p.label}</strong>
|
||||
<span>{p.hint}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="com-form-grid com-pricing-form">
|
||||
<label className="com-field">
|
||||
<span>价格(元)· 0 = 免费</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
value={priceYuan}
|
||||
disabled={busy}
|
||||
onChange={(e) => setPriceYuan(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="com-field">
|
||||
<span>折合分(fen)</span>
|
||||
<input value={draftFen == null ? '—' : String(draftFen)} disabled readOnly />
|
||||
</label>
|
||||
<label className="com-field">
|
||||
<span>VIP CTA(可改)</span>
|
||||
<input
|
||||
value={vipCta}
|
||||
disabled={busy}
|
||||
onChange={(e) => setVipCta(e.target.value)}
|
||||
placeholder="立即加入 · ¥88"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="com-actions">
|
||||
<button type="button" className="com-btn" disabled={busy || !dirty} onClick={savePrice}>
|
||||
{busy ? '保存中…' : dirty ? '保存动态价格' : '已是当前价'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn-ghost"
|
||||
disabled={busy || priceYuan === fenToYuanInput(liveFen)}
|
||||
onClick={() => {
|
||||
setPriceYuan(fenToYuanInput(liveFen))
|
||||
setVipCta(cfg.copy?.vipCta || '')
|
||||
}}
|
||||
>
|
||||
重置草稿
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="com-panel">
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<h2>游民社区 · 免费体验</h2>
|
||||
<p className="com-panel-desc">
|
||||
未加入可先试用;次数用完再引导付费。已付费且资料+自拍通过的用户不限次。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="com-flag-row" style={{ marginBottom: 12 }}>
|
||||
<div>
|
||||
<strong>开启体验次数限制</strong>
|
||||
<p>关闭=未付费也可无限用(不推荐上线)</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={trialDraft.enabled}
|
||||
disabled={busy}
|
||||
label="体验限制"
|
||||
onChange={(v) => setTrialDraft((d) => ({ ...d, enabled: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="com-form-grid">
|
||||
{(
|
||||
[
|
||||
['chatMessages', '群聊可发句数'],
|
||||
['dateViews', '约会可看人数'],
|
||||
['coffeeBookings', '咖啡聊可约次数'],
|
||||
['mapOpens', '地图可打开次数'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
disabled={busy || !trialDraft.enabled}
|
||||
value={trialDraft[key]}
|
||||
onChange={(e) =>
|
||||
setTrialDraft((d) => ({
|
||||
...d,
|
||||
[key]: Math.max(0, Math.floor(Number(e.target.value) || 0)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void patch(
|
||||
{
|
||||
flags: { socialTrialEnabled: trialDraft.enabled },
|
||||
copy: {
|
||||
socialTrial: {
|
||||
enabled: trialDraft.enabled,
|
||||
chatMessages: trialDraft.chatMessages,
|
||||
dateViews: trialDraft.dateViews,
|
||||
coffeeBookings: trialDraft.coffeeBookings,
|
||||
mapOpens: trialDraft.mapOpens,
|
||||
},
|
||||
},
|
||||
},
|
||||
trialDraft.enabled
|
||||
? `体验已保存:聊${trialDraft.chatMessages}·约${trialDraft.dateViews}·咖${trialDraft.coffeeBookings}·图${trialDraft.mapOpens}`
|
||||
: '已关闭体验限制',
|
||||
)
|
||||
}
|
||||
>
|
||||
保存体验次数
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -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<string, unknown> }>(
|
||||
@ -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() {
|
||||
<div className="com-cmd-hero-copy">
|
||||
<p className="com-cmd-kicker">Today</p>
|
||||
<h2>先处理这几件事</h2>
|
||||
<p>加入、自拍、举报优先;其余内容按需下钻。</p>
|
||||
<p>
|
||||
加入、自拍、举报优先。改价走侧栏「动态价格」→{' '}
|
||||
<a href={`/${lane}/pricing`} onClick={(e) => { e.preventDefault(); navigate(`/${lane}/pricing`) }}>
|
||||
打开定价
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<div className="com-cmd-priority">
|
||||
{(
|
||||
@ -733,11 +754,13 @@ export default function Social() {
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
) : null}
|
||||
{section === 'files' ? (
|
||||
{section === 'files' || section === 'roomArchives' ? (
|
||||
<tr>
|
||||
<th>文件名</th>
|
||||
<th>{section === 'roomArchives' ? '录像' : '文件名'}</th>
|
||||
{section === 'roomArchives' ? <th>状态</th> : null}
|
||||
{section === 'roomArchives' ? <th>时长</th> : null}
|
||||
<th>类型</th>
|
||||
<th>频道</th>
|
||||
<th>频道 / 厅</th>
|
||||
<th>访客</th>
|
||||
<th>时间</th>
|
||||
<th>操作</th>
|
||||
@ -842,25 +865,24 @@ export default function Social() {
|
||||
<span
|
||||
className={`com-badge tone-${joinStageTone(row.stage)}`}
|
||||
>
|
||||
{joinStageLabel(row.stage)}
|
||||
{joinStageLabel(row.stage, row)}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{row.paid === '1' || row.paid === true ? (
|
||||
<span className="com-badge tone-ok">已付</span>
|
||||
) : (
|
||||
<span className="com-muted">未付</span>
|
||||
)}
|
||||
{(() => {
|
||||
const label = joinPaidLabel(row)
|
||||
if (label === '已付')
|
||||
return <span className="com-badge tone-ok">已付</span>
|
||||
if (label === '免费')
|
||||
return <span className="com-badge">免费</span>
|
||||
return <span className="com-muted">未付</span>
|
||||
})()}
|
||||
</td>
|
||||
<td>
|
||||
{String(row.livenessStatus || '') === 'verified' ||
|
||||
row.faceOk === '1' ||
|
||||
row.faceOk === true ? (
|
||||
{joinLivenessLabel(row) === '已过' ? (
|
||||
<span className="com-badge tone-ok">已过</span>
|
||||
) : (
|
||||
<span className="com-muted">
|
||||
{String(row.livenessStatus || '未核验')}
|
||||
</span>
|
||||
<span className="com-muted">未核验</span>
|
||||
)}
|
||||
</td>
|
||||
<td>{fmtTime(row.updatedAt || row.updated_at || row.createdAt)}</td>
|
||||
@ -985,11 +1007,62 @@ export default function Social() {
|
||||
<td>{fmtTime(row.at)}</td>
|
||||
</>
|
||||
) : null}
|
||||
{section === 'files' ? (
|
||||
{section === 'files' || section === 'roomArchives' ? (
|
||||
<>
|
||||
<td>
|
||||
<strong>{short(row.name || row.fileId, 28)}</strong>
|
||||
{section === 'roomArchives' && row.url ? (
|
||||
<div className="com-muted" style={{ fontSize: 12, marginTop: 4 }}>
|
||||
S3 / 可播放
|
||||
</div>
|
||||
) : null}
|
||||
{section === 'roomArchives' && row.roomId ? (
|
||||
<div className="com-muted" style={{ fontSize: 11, marginTop: 2 }}>
|
||||
厅 {String(row.roomId)}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
{section === 'roomArchives' ? (
|
||||
<td>
|
||||
<span
|
||||
className={`com-badge tone-${
|
||||
row.status === 'uploaded'
|
||||
? 'ok'
|
||||
: row.status === 'uploading' || row.status === 'recording'
|
||||
? 'warn'
|
||||
: row.status === 'failed' || row.status === 'denied'
|
||||
? 'danger'
|
||||
: 'muted'
|
||||
}`}
|
||||
>
|
||||
{String(
|
||||
row.statusLabel ||
|
||||
({
|
||||
pending: '待上传',
|
||||
recording: '录制中',
|
||||
uploading: '上传中',
|
||||
uploaded: '已上传',
|
||||
failed: '失败',
|
||||
denied: '未开摄像头',
|
||||
} as Record<string, string>)[String(row.status || '')] ||
|
||||
row.status ||
|
||||
'—',
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
) : null}
|
||||
{section === 'roomArchives' ? (
|
||||
<td>
|
||||
<strong>
|
||||
{String(
|
||||
row.durationLabel ||
|
||||
(Number(row.durationSec) > 0
|
||||
? `${row.durationSec}秒`
|
||||
: '—'),
|
||||
)}
|
||||
</strong>
|
||||
</td>
|
||||
) : null}
|
||||
<td>{String(row.kind || row.mime || '—')}</td>
|
||||
<td>
|
||||
<code>{short(row.channelId, 12)}</code>
|
||||
|
||||
@ -13,6 +13,8 @@ import {
|
||||
} from './MediaValue'
|
||||
import {
|
||||
fmtTime,
|
||||
joinLivenessLabel,
|
||||
joinPaidLabel,
|
||||
joinStageLabel,
|
||||
joinStageTone,
|
||||
labelOf,
|
||||
@ -35,6 +37,7 @@ const ENTITY_LABEL: Record<string, string> = {
|
||||
reports: '举报',
|
||||
blocks: '拉黑',
|
||||
files: '上传文件',
|
||||
roomArchives: '语音厅录像',
|
||||
archives: '存档快照',
|
||||
joinLeads: '加入线索',
|
||||
}
|
||||
@ -131,61 +134,82 @@ function JoinPrimary({
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
const audits = Array.isArray(m.audits) ? (m.audits as Array<Record<string, unknown>>) : []
|
||||
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<string, unknown>) === '已过'
|
||||
// 前端硬闸:未核验 / 只填邮箱 → 绝不渲染任何照片视频(防 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<Record<string, unknown>>)
|
||||
: []
|
||||
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 (
|
||||
<div className="com-detail-hero com-join-hero">
|
||||
<div className="com-detail-name-row">
|
||||
<h2 className="com-detail-name">
|
||||
{String(val(item, 'name') || val(r, 'name') || '未填名字')}
|
||||
{String(
|
||||
val(item, 'name') ||
|
||||
(showRosterBits ? val(r, 'name') : '') ||
|
||||
'未填名字',
|
||||
)}
|
||||
</h2>
|
||||
<span className={`com-badge tone-${joinStageTone(val(item, 'stage'))}`}>
|
||||
{joinStageLabel(val(item, 'stage'))}
|
||||
{joinStageLabel(val(item, 'stage'), item as Record<string, unknown>)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="com-detail-title">{String(val(item, 'email') ?? '—')}</p>
|
||||
<div className="com-detail-meta">
|
||||
<span>
|
||||
支付{' '}
|
||||
<strong>{truthyFlag(val(item, 'paid')) ? '已付' : '未付'}</strong>
|
||||
支付 <strong>{joinPaidLabel(item as Record<string, unknown>)}</strong>
|
||||
</span>
|
||||
<span>
|
||||
人脸{' '}
|
||||
<strong>{truthyFlag(val(item, 'faceOk', 'face_ok')) ? '通过' : '未过'}</strong>
|
||||
人脸 <strong>{liveOk ? '通过' : '未过'}</strong>
|
||||
</span>
|
||||
<span>
|
||||
核验{' '}
|
||||
<strong>
|
||||
{String(val(item, 'livenessStatus', 'liveness_status') || 'none')}
|
||||
</strong>
|
||||
核验 <strong>{liveOk ? 'verified' : '未核验'}</strong>
|
||||
</span>
|
||||
<span>
|
||||
访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code>
|
||||
</span>
|
||||
<span>更新 {fmtTime(val(item, 'updatedAt', 'updated_at', 'createdAt'))}</span>
|
||||
</div>
|
||||
{String(val(r, 'bio') || '') ? (
|
||||
{showRosterBits && String(val(r, 'bio') || '') ? (
|
||||
<p className="com-detail-bio">{String(val(r, 'bio'))}</p>
|
||||
) : null}
|
||||
{String(val(r, 'city') || val(r, 'title') || '') ? (
|
||||
{showRosterBits && String(val(r, 'city') || val(r, 'title') || '') ? (
|
||||
<div className="com-chip-row">
|
||||
{val(r, 'city') ? <span className="com-chip">{String(val(r, 'city'))}</span> : null}
|
||||
{val(r, 'title') ? <span className="com-chip">{String(val(r, 'title'))}</span> : null}
|
||||
@ -196,7 +220,7 @@ function JoinPrimary({
|
||||
) : null}
|
||||
|
||||
<h3 className="com-media-heading">照片与视频</h3>
|
||||
<MediaGallery items={gallery} />
|
||||
{gallery.some((g) => g.value) ? <MediaGallery items={gallery} /> : null}
|
||||
{!gallery.some((g) => g.value) && !audits.length ? (
|
||||
<p className="com-muted">还没有头像或核验媒体。</p>
|
||||
) : null}
|
||||
@ -702,7 +726,15 @@ export default function SocialDetail() {
|
||||
const p = (h.payload || {}) as Record<string, unknown>
|
||||
const nested =
|
||||
(p.payload as Record<string, unknown> | 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 (
|
||||
<li key={h.id || `${h.action}-${h.at}`}>
|
||||
<div className="com-timeline-head">
|
||||
|
||||
@ -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<SwitchesCfg | null>(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 (
|
||||
<div className="com-page">
|
||||
<header className="com-page-head">
|
||||
<h1>动态开关</h1>
|
||||
<h1>页面开关</h1>
|
||||
<p>
|
||||
.com 全站共享配置:页面显隐、功能、VIP 入口与文案。保存后前台实时更新;受众专属文案请到「受众设置」。
|
||||
页面显隐、功能 Flag、VIP 落地区块与门户文案。改价请走
|
||||
<Link to={`/${laneKey}/pricing`}> 动态价格</Link>
|
||||
;受众专属文案在「受众设置」。
|
||||
</p>
|
||||
<div className="com-chip-row">
|
||||
<span className="com-chip">版本 v{cfg.version ?? '—'}</span>
|
||||
<span className="com-chip com-chip-ok">
|
||||
页面开启 {onCount}/{PAGE_MODS.length}
|
||||
</span>
|
||||
<span className="com-chip">
|
||||
{(Number(cfg.copy?.vipPriceFen) || 0) <= 0
|
||||
? '当前免费'
|
||||
: `现价 ¥${((Number(cfg.copy?.vipPriceFen) || 0) / 100).toFixed((Number(cfg.copy?.vipPriceFen) || 0) % 100 === 0 ? 0 : 2)}`}
|
||||
</span>
|
||||
{cfg.updatedAt ? <span className="com-chip">{cfg.updatedAt}</span> : null}
|
||||
</div>
|
||||
</header>
|
||||
@ -385,170 +361,24 @@ export default function Switches() {
|
||||
{tab === 'vip' ? (
|
||||
<>
|
||||
<section className="com-panel">
|
||||
<h2>会员价格(免费 / 付费)</h2>
|
||||
<p className="com-muted" style={{ marginTop: 0 }}>
|
||||
写入 remote-config.copy.vipPriceFen;0 元=免费加入。门户 / VIP / 游民加入支付跟此后台价。
|
||||
</p>
|
||||
<div className="com-chip-row" style={{ marginBottom: 12 }}>
|
||||
{[
|
||||
{ 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) => (
|
||||
<button
|
||||
key={p.yuan}
|
||||
type="button"
|
||||
className={`com-chip${priceYuan === p.yuan ? ' com-chip-ok' : ''}`}
|
||||
disabled={busy}
|
||||
onClick={() => setPriceYuan(p.yuan)}
|
||||
>
|
||||
{p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="com-form-grid">
|
||||
<label className="com-field">
|
||||
<span>价格(元)· 0=免费</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
value={priceYuan}
|
||||
disabled={busy}
|
||||
onChange={(e) => setPriceYuan(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="com-field">
|
||||
<span>当前分(fen)</span>
|
||||
<input
|
||||
value={String(Math.max(0, Number(cfg.copy?.vipPriceFen) || 0))}
|
||||
disabled
|
||||
readOnly
|
||||
/>
|
||||
</label>
|
||||
<label className="com-field">
|
||||
<span>VIP CTA(可改)</span>
|
||||
<input
|
||||
value={draftCopy.vipCta}
|
||||
disabled={busy}
|
||||
onChange={(e) => setDraftCopy((d) => ({ ...d, vipCta: e.target.value }))}
|
||||
placeholder="立即加入 · ¥0.1"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
const yuan = Number(priceYuan)
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(priceYuan.trim()) || !Number.isFinite(yuan) || yuan < 0 || yuan > 1000000) {
|
||||
setErr('请填写 0–1,000,000 元之间的价格,最多两位小数;免费请明确填写 0')
|
||||
return
|
||||
}
|
||||
const fen = Math.round(yuan * 100)
|
||||
const autoCta =
|
||||
fen <= 0
|
||||
? '免费加入'
|
||||
: `立即加入 · ¥${fen % 100 === 0 ? fen / 100 : (fen / 100).toFixed(2)}`
|
||||
const cta = (draftCopy.vipCta || '').trim() || autoCta
|
||||
void patch(
|
||||
{
|
||||
copy: {
|
||||
...draftCopy,
|
||||
vipCta: cta.includes('¥') || cta.includes('¥') || !draftCopy.vipCta.trim()
|
||||
? autoCta
|
||||
: cta,
|
||||
vipPriceFen: fen,
|
||||
},
|
||||
},
|
||||
fen <= 0 ? '已设为免费(0 分)' : `会员价已更新为 ¥${(fen / 100).toFixed(fen % 100 === 0 ? 0 : 2)}`,
|
||||
)
|
||||
}}
|
||||
>
|
||||
保存价格
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
<section className="com-panel">
|
||||
<h2>游民社区 · 免费体验次数</h2>
|
||||
<p className="com-muted" style={{ marginTop: 0 }}>
|
||||
未加入用户可先逛;次数用完再引导加入。已付费并完成资料+自拍的用户不限次数。
|
||||
</p>
|
||||
<div className="com-flag-row" style={{ marginBottom: 12 }}>
|
||||
<div className="com-panel-head">
|
||||
<div>
|
||||
<strong>开启免费体验限制</strong>
|
||||
<p>关闭后未付费也可无限使用(不推荐上线)</p>
|
||||
<h2>改价入口</h2>
|
||||
<p className="com-panel-desc">
|
||||
会员价 / 免费体验已独立到「动态价格」。当前{' '}
|
||||
{(Number(cfg.copy?.vipPriceFen) || 0) <= 0
|
||||
? '免费'
|
||||
: `¥${((Number(cfg.copy?.vipPriceFen) || 0) / 100).toFixed((Number(cfg.copy?.vipPriceFen) || 0) % 100 === 0 ? 0 : 2)}`}
|
||||
。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={trialDraft.enabled}
|
||||
disabled={busy}
|
||||
label="体验限制"
|
||||
onChange={(v) => setTrialDraft((d) => ({ ...d, enabled: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="com-form-grid">
|
||||
{(
|
||||
[
|
||||
['chatMessages', '群聊可发句数'],
|
||||
['dateViews', '约会可看人数'],
|
||||
['coffeeBookings', '咖啡聊可约次数'],
|
||||
['mapOpens', '地图可打开次数'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<label key={key} className="com-field">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
disabled={busy || !trialDraft.enabled}
|
||||
value={trialDraft[key]}
|
||||
onChange={(e) =>
|
||||
setTrialDraft((d) => ({
|
||||
...d,
|
||||
[key]: Math.max(0, Math.floor(Number(e.target.value) || 0)),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="com-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void patch(
|
||||
{
|
||||
flags: { socialTrialEnabled: trialDraft.enabled },
|
||||
copy: {
|
||||
socialTrial: {
|
||||
enabled: trialDraft.enabled,
|
||||
chatMessages: trialDraft.chatMessages,
|
||||
dateViews: trialDraft.dateViews,
|
||||
coffeeBookings: trialDraft.coffeeBookings,
|
||||
mapOpens: trialDraft.mapOpens,
|
||||
},
|
||||
},
|
||||
},
|
||||
trialDraft.enabled
|
||||
? `已保存:聊${trialDraft.chatMessages}·约${trialDraft.dateViews}·咖${trialDraft.coffeeBookings}·图${trialDraft.mapOpens}`
|
||||
: '已关闭体验限制',
|
||||
)
|
||||
}
|
||||
>
|
||||
保存体验次数
|
||||
</button>
|
||||
<Link className="com-btn" to={`/${laneKey}/pricing`}>
|
||||
打开动态价格 →
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
<section className="com-panel">
|
||||
<h2>VIP 落地入口</h2>
|
||||
<h2>VIP 落地区块</h2>
|
||||
<div className="com-flag-list">
|
||||
{VIP_ENTRIES.map((f) => {
|
||||
const on = cfg.vipEntries?.[f.key] !== false
|
||||
|
||||
@ -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<SectionKey, string> = {
|
||||
gigs: '接单',
|
||||
skills: '技能交换',
|
||||
liveness: '自拍确认',
|
||||
roomArchives: '语音厅录像',
|
||||
coffee: '咖啡预约',
|
||||
trips: '行程',
|
||||
reports: '举报',
|
||||
@ -69,6 +72,7 @@ export const SECTION_DESC: Record<SectionKey, string> = {
|
||||
gigs: '接单与共创申请。',
|
||||
skills: '技能交换(能提供 / 想换)。',
|
||||
liveness: '自拍确认:正面、侧面与录像。',
|
||||
roomArchives: '进厅埋点立刻出记录:待上传 / 录制中 / 上传中 / 已上传;点行可播已上传视频。',
|
||||
coffee: '咖啡聊预约:谁约了、什么时段。',
|
||||
trips: '成员提交的旅居行程。',
|
||||
reports: '用户举报,优先处理。',
|
||||
@ -89,6 +93,7 @@ export const SECTION_API: Partial<Record<SectionKey, string>> = {
|
||||
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<string, string> = {
|
||||
liveness: '自拍确认',
|
||||
}
|
||||
|
||||
export function joinStageLabel(stage: unknown): string {
|
||||
export function joinStageLabel(stage: unknown, row?: Record<string, unknown>): 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<string, unknown>)
|
||||
: {}
|
||||
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, unknown>): 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<string, unknown>)
|
||||
: {}
|
||||
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, unknown>): 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<string, unknown>, 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'],
|
||||
|
||||
@ -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; }
|
||||
|
||||
@ -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()],
|
||||
|
||||
@ -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 <<EOF
|
||||
### ${TITLE}
|
||||
|
||||
${MESSAGE}
|
||||
|
||||
- **时间** \`${NOW}\`
|
||||
- **主机** \`$(hostname 2>/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
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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 });
|
||||
}
|
||||
|
||||
66
src/app/api/config/notify/route.ts
Normal file
66
src/app/api/config/notify/route.ts
Normal file
@ -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 });
|
||||
}
|
||||
156
src/app/api/portal/feedback/route.ts
Normal file
156
src/app/api/portal/feedback/route.ts
Normal file
@ -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<Store> {
|
||||
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<void> {
|
||||
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<string, unknown> = {};
|
||||
try {
|
||||
body = (await req.json()) as Record<string, unknown>;
|
||||
} 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",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@ -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<string, unknown>,
|
||||
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,
|
||||
|
||||
247
src/lib/ntfy-rich.ts
Normal file
247
src/lib/ntfy-rich.ts
Normal file
@ -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<string, unknown>;
|
||||
ts?: number;
|
||||
};
|
||||
|
||||
const PROP_LABEL: Record<string, string> = {
|
||||
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<string, unknown> | 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<string, unknown>;
|
||||
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),
|
||||
};
|
||||
}
|
||||
102
src/lib/ntfy.ts
102
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<string, string>;
|
||||
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) {
|
||||
|
||||
@ -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();
|
||||
}
|
||||
|
||||
@ -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: "约出来喝一杯",
|
||||
|
||||
@ -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<typeof setTimeout> | null = null;
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let inFlight: Promise<void> | 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<NomadroRemoteConfig | null> {
|
||||
@ -90,6 +111,33 @@ async function fetchFullConfig(): Promise<NomadroRemoteConfig | null> {
|
||||
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<NomadroRemoteConfig> {
|
||||
if (typeof window !== "undefined") ensureBootstrapped();
|
||||
await pull(force);
|
||||
return snapshot.config;
|
||||
}
|
||||
|
||||
export function getRemoteConfigSnapshot(): Result {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@ -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<CoffeeHost[]>([]);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [cityId, setCityId] = useState<string>("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 (
|
||||
<SiteShell title={socialTx("咖啡聊预约")}>
|
||||
<HomeCoffeeEntry inPage />
|
||||
<div className="cf-root">
|
||||
<section className="cf-hero" aria-labelledby="cf-brand">
|
||||
<div>
|
||||
<p className="cf-brand" id="cf-brand">
|
||||
Nomadro <span>Coffee</span>
|
||||
</p>
|
||||
<h1 className="cf-title">
|
||||
{zh ? "预约一次同城咖啡聊" : "Book a coffee chat"}
|
||||
<SiteShell title={socialTx("线下咖啡聊")}>
|
||||
<div className="cf-root cf-offline">
|
||||
<section className="cf-hero-offline" aria-labelledby="cf-offline-brand">
|
||||
<div className="cf-hero-offline-bg" aria-hidden />
|
||||
<div className="cf-hero-offline-copy">
|
||||
<p className="cf-eyebrow">{zh ? "OFFLINE · CITY" : "OFFLINE · CITY"}</p>
|
||||
<h1 className="cf-brand" id="cf-offline-brand">
|
||||
Nomadro <span>{zh ? "线下 Coffee" : "Offline Coffee"}</span>
|
||||
</h1>
|
||||
<p className="cf-title">
|
||||
{zh
|
||||
? "挑一座城,约一杯线下咖啡"
|
||||
: "Pick a city. Book an offline coffee."}
|
||||
</p>
|
||||
<p className="cf-lead">
|
||||
{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."}
|
||||
</p>
|
||||
<div className="cf-cta">
|
||||
<Link className="cf-btn cf-btn-primary" href={socialPath("/coffeechat/guest")}>
|
||||
{zh ? "约演示主持人" : "Book demo host"}
|
||||
</Link>
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath("/coffeechat/manage")}>
|
||||
{zh ? "管理我的日程" : "Manage schedule"}
|
||||
</Link>
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath("/places?tab=cafes")}>
|
||||
<a className="cf-btn cf-btn-primary" href="#cf-hosts">
|
||||
{zh ? "看谁在约" : "Who’s free"}
|
||||
</a>
|
||||
<Link
|
||||
className="cf-btn cf-btn-ghost"
|
||||
href={socialPath("/places?tab=cafes")}
|
||||
>
|
||||
{zh ? "咖啡馆地图" : "Café map"}
|
||||
</Link>
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath("/places")}>
|
||||
{zh ? "逛城市" : "Browse cities"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="cf-steam" aria-hidden />
|
||||
<ul className="cf-city-rail" aria-label={zh ? "热门城市" : "Cities"}>
|
||||
{cities.slice(0, 6).map((c) => (
|
||||
<li key={c.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={`cf-city-chip${cityId === c.id ? " is-on" : ""}`}
|
||||
onClick={() => setCityId(c.id)}
|
||||
>
|
||||
<span aria-hidden>{c.emoji}</span>
|
||||
<strong>{c.name}</strong>
|
||||
<em>{c.vibe.split("·")[0].trim()}</em>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
<div className="cf-grid">
|
||||
{hosts.map((h) => (
|
||||
<Link
|
||||
key={h.id}
|
||||
href={socialPath(`/coffeechat/${h.username}`)}
|
||||
className="cf-card"
|
||||
<section className="cf-city-board" aria-label={zh ? "按城见面" : "By city"}>
|
||||
<div className="cf-section-head">
|
||||
<h2>{zh ? "城市就是会场" : "Cities as venues"}</h2>
|
||||
<p>
|
||||
{zh
|
||||
? "先选城,再约人。线下咖啡聊绑定同城,不搞远程空聊。"
|
||||
: "Choose the city first. Offline coffee stays local."}
|
||||
</p>
|
||||
</div>
|
||||
<div className="cf-city-filter" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={cityId === "all"}
|
||||
className={`cf-filter-pill${cityId === "all" ? " is-on" : ""}`}
|
||||
onClick={() => setCityId("all")}
|
||||
>
|
||||
<div className="cf-meta">
|
||||
<span className="cf-pill">{h.city || "Remote"}</span>
|
||||
<span>{h.timezone}</span>
|
||||
{zh ? "全部城市" : "All cities"}
|
||||
</button>
|
||||
{cities.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={cityId === c.id}
|
||||
className={`cf-filter-pill${cityId === c.id ? " is-on" : ""}`}
|
||||
onClick={() => setCityId(c.id)}
|
||||
>
|
||||
{c.emoji} {c.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeCity ? (
|
||||
<article className="cf-city-spotlight">
|
||||
<div
|
||||
className="cf-city-spotlight-media"
|
||||
style={
|
||||
activeCity.cover
|
||||
? { backgroundImage: `url(${activeCity.cover})` }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<div className="cf-city-spotlight-body">
|
||||
<p className="cf-eyebrow">
|
||||
{activeCity.emoji} {activeCity.country}
|
||||
</p>
|
||||
<h3>
|
||||
{activeCity.name}
|
||||
<span>{activeCity.vibe}</span>
|
||||
</h3>
|
||||
<p>
|
||||
{activeCity.blurb ||
|
||||
(zh
|
||||
? "同城咖啡馆约见,见面比聊天软件快。"
|
||||
: "Meet at a local café — faster than DMs.")}
|
||||
</p>
|
||||
<div className="cf-cta">
|
||||
<Link
|
||||
className="cf-btn cf-btn-primary"
|
||||
href={socialPath(`/places/${activeCity.id}`)}
|
||||
>
|
||||
{zh ? `去看${activeCity.name}` : `Explore ${activeCity.name}`}
|
||||
</Link>
|
||||
<Link
|
||||
className="cf-btn cf-btn-ghost"
|
||||
href={socialPath(`/places?tab=cafes&city=${activeCity.id}`)}
|
||||
>
|
||||
{zh ? "同城咖啡馆" : "Cafés nearby"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<h2>{h.name}</h2>
|
||||
<p>{h.bio}</p>
|
||||
<span className="cf-meta">
|
||||
@{h.username} · {h.event_count || 0}{" "}
|
||||
{zh ? "种聊聊" : "event types"}
|
||||
</span>
|
||||
</article>
|
||||
) : (
|
||||
<div className="cf-city-mosaic">
|
||||
{cities.slice(0, 8).map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="cf-city-tile"
|
||||
onClick={() => setCityId(c.id)}
|
||||
style={
|
||||
c.cover
|
||||
? { backgroundImage: `url(${c.cover})` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span>
|
||||
{c.emoji} {c.name}
|
||||
</span>
|
||||
<em>{c.vibe}</em>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section id="cf-hosts" className="cf-hosts" aria-labelledby="cf-hosts-title">
|
||||
<div className="cf-section-head">
|
||||
<h2 id="cf-hosts-title">
|
||||
{activeCity
|
||||
? zh
|
||||
? `${activeCity.name} · 可约线下`
|
||||
: `${activeCity.name} · offline`
|
||||
: zh
|
||||
? "线下可约的人"
|
||||
: "People for offline coffee"}
|
||||
</h2>
|
||||
<p>
|
||||
{zh
|
||||
? "约的是咖啡馆见面,不是视频会议。点进主页选时段即可。"
|
||||
: "Café meetups, not video calls. Pick a slot on their page."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
|
||||
<div className="cf-grid">
|
||||
{filtered.map((h) => (
|
||||
<Link
|
||||
key={h.id}
|
||||
href={socialPath(`/coffeechat/${h.username}`)}
|
||||
className="cf-card cf-card-offline"
|
||||
>
|
||||
<div className="cf-meta">
|
||||
<span className="cf-pill">{h.city || (zh ? "同城待定" : "City TBD")}</span>
|
||||
<span className="cf-pill ok">{zh ? "线下" : "IRL"}</span>
|
||||
</div>
|
||||
<h2>{h.name}</h2>
|
||||
<p>{h.bio || (zh ? "咖啡馆轻聊,帮你破冰同城。" : "Café chat to break the ice.")}</p>
|
||||
<span className="cf-meta">
|
||||
@{h.username} · {h.event_count || 0}{" "}
|
||||
{zh ? "种见面" : "meet types"}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!filtered.length && !err ? (
|
||||
<p className="cf-empty">
|
||||
{zh
|
||||
? "这城暂时没人开放预约,先逛咖啡馆地图,或换一座城。"
|
||||
: "No hosts here yet — try the café map or another city."}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="cf-cta cf-cta-foot">
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath("/coffeechat/manage")}>
|
||||
{zh ? "开放我的线下档期" : "Open my offline slots"}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath("/people")}>
|
||||
{zh ? "找同城的人" : "Find locals"}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</SiteShell>
|
||||
);
|
||||
|
||||
@ -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; }
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -146,7 +146,6 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx("点开卡片,看看对方在做什么、想认识谁。")}
|
||||
{socialTx("现在是示例介绍,方便你先逛逛")}
|
||||
{roster.some((m) => m.id === SELF_MEMBER_ID)
|
||||
? socialTx("(也包含你写好的介绍)")
|
||||
: ""}
|
||||
@ -162,7 +161,6 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
||||
<p>
|
||||
<strong className="social-count-pulse">{online.length}</strong>{" "}
|
||||
{socialTx("位现在在线")}
|
||||
<span> · {socialTx("示例数据")}</span>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@ -54,6 +54,7 @@ export default function AvatarSelfieModal({
|
||||
const [countdown, setCountdown] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [previewReady, setPreviewReady] = useState(false);
|
||||
const [recording, setRecording] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
@ -67,33 +68,51 @@ export default function AvatarSelfieModal({
|
||||
setCountdown(null);
|
||||
setBusy(false);
|
||||
setPreviewReady(false);
|
||||
setRecording(false);
|
||||
autoStartedRef.current = false;
|
||||
frontBlobRef.current = null;
|
||||
chunksRef.current = [];
|
||||
recorderRef.current = null;
|
||||
|
||||
const startRecorder = (stream: MediaStream) => {
|
||||
/** 拿到流立刻开录——不要等倒计时 / 预览,后台要全程存档 */
|
||||
const startRecorder = (stream: MediaStream): boolean => {
|
||||
const mime = pickRecorderMime();
|
||||
if (!mime || typeof MediaRecorder === "undefined") return;
|
||||
if (!mime || typeof MediaRecorder === "undefined") {
|
||||
setRecording(false);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (recorderRef.current && recorderRef.current.state !== "inactive") {
|
||||
try {
|
||||
recorderRef.current.stop();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
const rec = new MediaRecorder(stream, {
|
||||
mimeType: mime,
|
||||
videoBitsPerSecond: 2_000_000,
|
||||
videoBitsPerSecond: 2_500_000,
|
||||
});
|
||||
chunksRef.current = [];
|
||||
rec.ondataavailable = (ev) => {
|
||||
if (ev.data && ev.data.size > 0) chunksRef.current.push(ev.data);
|
||||
};
|
||||
// Short timeslice → keep all frames for admin audit archive
|
||||
rec.start(250);
|
||||
rec.onerror = () => {
|
||||
if (!cancelled) setRecording(false);
|
||||
};
|
||||
// 100ms 切片,开摄像头起的每一帧都进存档
|
||||
rec.start(100);
|
||||
recorderRef.current = rec;
|
||||
if (!cancelled) setRecording(true);
|
||||
return true;
|
||||
} catch {
|
||||
recorderRef.current = null;
|
||||
if (!cancelled) setRecording(false);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const attach = async (stream: MediaStream) => {
|
||||
streamRef.current = stream;
|
||||
const attachPreview = async (stream: MediaStream) => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
video.srcObject = stream;
|
||||
@ -110,7 +129,6 @@ export default function AvatarSelfieModal({
|
||||
} catch {
|
||||
/* autoplay may need metadata first */
|
||||
}
|
||||
startRecorder(stream);
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
@ -135,14 +153,23 @@ export default function AvatarSelfieModal({
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
return;
|
||||
}
|
||||
await new Promise((r) => requestAnimationFrame(() => r(undefined)));
|
||||
if (cancelled) {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
return;
|
||||
streamRef.current = stream;
|
||||
// 先录再贴预览:保证「进入摄像头」即开始存档
|
||||
if (!startRecorder(stream)) {
|
||||
// 再试一次(部分浏览器要等 track live)
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
if (!cancelled) startRecorder(stream);
|
||||
}
|
||||
await attach(stream);
|
||||
await attachPreview(stream);
|
||||
if (!cancelled && videoRef.current && videoRef.current.srcObject !== stream) {
|
||||
await attach(stream);
|
||||
await attachPreview(stream);
|
||||
}
|
||||
// 若仍未录上,预览就绪后再补开一次
|
||||
if (
|
||||
!cancelled &&
|
||||
(!recorderRef.current || recorderRef.current.state === "inactive")
|
||||
) {
|
||||
startRecorder(stream);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
@ -166,6 +193,7 @@ export default function AvatarSelfieModal({
|
||||
if (video) video.srcObject = null;
|
||||
streamRef.current?.getTracks().forEach((t) => t.stop());
|
||||
streamRef.current = null;
|
||||
setRecording(false);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
@ -191,22 +219,35 @@ export default function AvatarSelfieModal({
|
||||
return new Promise((resolve) => {
|
||||
const rec = recorderRef.current;
|
||||
if (!rec || rec.state === "inactive") {
|
||||
resolve({ blob: null, mime: "" });
|
||||
const mime = pickRecorderMime() || "video/webm";
|
||||
const parts = chunksRef.current;
|
||||
resolve({
|
||||
blob: parts.length > 0 ? new Blob(parts, { type: mime }) : null,
|
||||
mime,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const mime = rec.mimeType || pickRecorderMime() || "video/webm";
|
||||
rec.onstop = () => {
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
setRecording(false);
|
||||
const parts = chunksRef.current;
|
||||
const blob = parts.length > 0 ? new Blob(parts, { type: mime }) : null;
|
||||
recorderRef.current = null;
|
||||
resolve({ blob, mime });
|
||||
};
|
||||
rec.onstop = finish;
|
||||
try {
|
||||
rec.requestData?.();
|
||||
rec.stop();
|
||||
} catch {
|
||||
resolve({ blob: null, mime: "" });
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
// 兜底:部分环境 onstop 不触发
|
||||
window.setTimeout(finish, 800);
|
||||
});
|
||||
}
|
||||
|
||||
@ -237,6 +278,11 @@ export default function AvatarSelfieModal({
|
||||
setBusy(true);
|
||||
try {
|
||||
const { blob: videoBlob, mime } = await stopRecorder();
|
||||
if (!videoBlob || videoBlob.size < 1024) {
|
||||
throw new Error(
|
||||
socialTx("录屏失败,请重开摄像头再试一次") || "录屏失败,请重开摄像头再试一次",
|
||||
);
|
||||
}
|
||||
await onCaptured({
|
||||
front,
|
||||
turn: turnBlob,
|
||||
@ -253,16 +299,58 @@ export default function AvatarSelfieModal({
|
||||
? socialTx(e.message) || e.message
|
||||
: socialTx("自拍没通过,请再试一次"),
|
||||
);
|
||||
// 失败后尽量重新开录,方便立刻重试
|
||||
if (streamRef.current) {
|
||||
try {
|
||||
const mime = pickRecorderMime();
|
||||
if (mime && typeof MediaRecorder !== "undefined") {
|
||||
const rec = new MediaRecorder(streamRef.current, {
|
||||
mimeType: mime,
|
||||
videoBitsPerSecond: 2_500_000,
|
||||
});
|
||||
chunksRef.current = [];
|
||||
rec.ondataavailable = (ev) => {
|
||||
if (ev.data && ev.data.size > 0) chunksRef.current.push(ev.data);
|
||||
};
|
||||
rec.start(100);
|
||||
recorderRef.current = rec;
|
||||
setRecording(true);
|
||||
}
|
||||
} catch {
|
||||
setRecording(false);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Silent reference frame (no UI step) → prompt turn → second countdown → turn shot. */
|
||||
/** Silent reference frame → turn prompt → turn shot. */
|
||||
async function beginChallenge() {
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
try {
|
||||
if (!recording && streamRef.current) {
|
||||
// 挑战开始前再兜底开录一次
|
||||
const mime = pickRecorderMime();
|
||||
if (mime && typeof MediaRecorder !== "undefined") {
|
||||
try {
|
||||
const rec = new MediaRecorder(streamRef.current, {
|
||||
mimeType: mime,
|
||||
videoBitsPerSecond: 2_500_000,
|
||||
});
|
||||
chunksRef.current = [];
|
||||
rec.ondataavailable = (ev) => {
|
||||
if (ev.data && ev.data.size > 0) chunksRef.current.push(ev.data);
|
||||
};
|
||||
rec.start(100);
|
||||
recorderRef.current = rec;
|
||||
setRecording(true);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
const front = await snap();
|
||||
if (!front) {
|
||||
setErr(socialTx("拍照失败,请重试"));
|
||||
@ -271,7 +359,6 @@ export default function AvatarSelfieModal({
|
||||
}
|
||||
frontBlobRef.current = front;
|
||||
setStep("turn");
|
||||
// Brief pause so user can start turning, then countdown for the turn frame
|
||||
await new Promise((r) => window.setTimeout(r, 900));
|
||||
runCountdown(3, () => {
|
||||
void (async () => {
|
||||
@ -291,7 +378,7 @@ export default function AvatarSelfieModal({
|
||||
}
|
||||
}
|
||||
|
||||
// Camera ready → auto countdown → turn (no separate front-photo step)
|
||||
// Camera ready → auto countdown → turn
|
||||
useEffect(() => {
|
||||
if (!open || !previewReady || err || autoStartedRef.current) return;
|
||||
if (step !== "arm" || countdown !== null || busy) return;
|
||||
@ -318,6 +405,7 @@ export default function AvatarSelfieModal({
|
||||
aria-modal="true"
|
||||
aria-label={socialTx("现场自拍")}
|
||||
data-preview-ready={previewReady ? "true" : "false"}
|
||||
data-recording={recording ? "true" : "false"}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@ -328,6 +416,11 @@ export default function AvatarSelfieModal({
|
||||
<div className="social-selfie-card">
|
||||
<header className="social-selfie-head">
|
||||
<strong>{socialTx("现场自拍")}</strong>
|
||||
{recording ? (
|
||||
<span className="social-selfie-rec" role="status">
|
||||
● {socialTx("录制中 · 全程存档")}
|
||||
</span>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="social-selfie-close"
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
import {
|
||||
useEffect,
|
||||
useId,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@ -13,30 +12,25 @@ import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import {
|
||||
ArrowUpRight,
|
||||
ChevronDown,
|
||||
Coffee,
|
||||
MapPin,
|
||||
MessageCircle,
|
||||
Plug,
|
||||
Search,
|
||||
Star,
|
||||
Wifi,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import SiteShell from "./SiteShell";
|
||||
import CityDirectory from "./CityDirectory";
|
||||
import {
|
||||
BookmarkButton,
|
||||
DemoBadge,
|
||||
EmptyState,
|
||||
PageIntro,
|
||||
SearchField,
|
||||
ResultSummary,
|
||||
ShareButton,
|
||||
} from "./SocialUI";
|
||||
import { BookmarkButton, EmptyState, ShareButton } from "./SocialUI";
|
||||
import { socialApi } from "@social/lib/api";
|
||||
import { useLocalState } from "@social/lib/useLocalState";
|
||||
import { uid } from "@social/lib/storage";
|
||||
import { resolveSocialCatalog } from "@social/lib/resolveCatalog";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import type { SocialCafe, SocialCafeReview } from "@social/lib/types";
|
||||
import { SOCIAL_CITIES } from "@social/lib/cities";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
@ -51,7 +45,22 @@ function subscribeHash(callback: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
function cityCover(cityName: string): string | undefined {
|
||||
return SOCIAL_CITIES.find(
|
||||
(c) => c.name === cityName || cityName.includes(c.name) || c.name.includes(cityName),
|
||||
)?.cover;
|
||||
}
|
||||
|
||||
function cityEmoji(cityName: string): string {
|
||||
return (
|
||||
SOCIAL_CITIES.find(
|
||||
(c) =>
|
||||
c.name === cityName || cityName.includes(c.name) || c.name.includes(cityName),
|
||||
)?.emoji || "☕"
|
||||
);
|
||||
}
|
||||
|
||||
function CafeReviewForm({ cafe }: { cafe: SocialCafe }) {
|
||||
const [reviews, setReviews] = useLocalState<Review[]>(
|
||||
`cafe-reviews:${cafe.id}`,
|
||||
[],
|
||||
@ -59,12 +68,17 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
const [author, setAuthor] = useLocalState("nick", "游民");
|
||||
const [score, setScore] = useState(5);
|
||||
const [text, setText] = useLocalState(`cafe-review-draft:${cafe.id}`, "");
|
||||
const [photoNote, setPhotoNote] = useLocalState(`cafe-review-note:${cafe.id}`, "");
|
||||
const [photoNote, setPhotoNote] = useLocalState(
|
||||
`cafe-review-note:${cafe.id}`,
|
||||
"",
|
||||
);
|
||||
const [status, setStatus] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const lock = useRef(false);
|
||||
const textRef = useRef(text);
|
||||
textRef.current = text;
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void socialApi
|
||||
@ -75,16 +89,15 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
...(response.items || []),
|
||||
...current.filter((review) => review.local),
|
||||
]);
|
||||
setStatus("评价已连接社区。");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active)
|
||||
setStatus("网络不太好:评价先留在你这边了,有网后再点「再发一次」。");
|
||||
/* offline seed ok */
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [cafe.id, setReviews]);
|
||||
|
||||
const submit = async (event?: FormEvent, retry?: Review) => {
|
||||
event?.preventDefault();
|
||||
const payload = retry
|
||||
@ -117,10 +130,8 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
...current.filter((review) => review.local),
|
||||
]);
|
||||
})
|
||||
.catch(() =>
|
||||
setStatus("评价已发布;列表暂未刷新,请稍后重新打开查看。"),
|
||||
);
|
||||
setStatus("评价已发布");
|
||||
.catch(() => undefined);
|
||||
setStatus(socialTx("评价已发布"));
|
||||
if (!retry && textRef.current.trim() === payload.text) {
|
||||
setText("");
|
||||
setPhotoNote("");
|
||||
@ -137,7 +148,7 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
},
|
||||
...current,
|
||||
]);
|
||||
setStatus("先留在你这边了。有网后点评价下面的「再发一次」就行。");
|
||||
setStatus(socialTx("先留在你这边了。有网后点评价下面的「再发一次」就行。"));
|
||||
if (!retry && textRef.current.trim() === payload.text) {
|
||||
setText("");
|
||||
setPhotoNote("");
|
||||
@ -147,80 +158,70 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const invitation = `有人约在 ${cafe.city} · ${cafe.name} 喝咖啡,一起聊聊远程生活?`;
|
||||
|
||||
return (
|
||||
<section className="social-panel social-cafe-detail" id={id}>
|
||||
<div className="social-cafe-detail-hero" aria-hidden>
|
||||
<Coffee size={42} strokeWidth={1.2} />
|
||||
<span>{cafe.city}</span>
|
||||
</div>
|
||||
<div className="social-section-label">
|
||||
<span>{socialTx("详情")}</span>
|
||||
<ShareButton
|
||||
path={socialPath(`/places?tab=cafes#${cafe.id}`)}
|
||||
title={`${cafe.city} · ${cafe.name}`}
|
||||
/>
|
||||
</div>
|
||||
<h2>{cafe.name}</h2>
|
||||
<p className="social-muted">
|
||||
{cafe.city} · {cafe.vibe}
|
||||
</p>
|
||||
<div className="social-cafe-facts">
|
||||
<span>
|
||||
<Wifi size={15} />
|
||||
{cafe.wifiMbps} Mbps
|
||||
</span>
|
||||
<span>
|
||||
<Plug size={15} />
|
||||
{cafe.power}
|
||||
</span>
|
||||
<span>
|
||||
<Star size={15} />
|
||||
{cafe.rating}
|
||||
</span>
|
||||
<span>{cafe.partners ? "推荐见面点" : "社区收录"}</span>
|
||||
</div>
|
||||
<Link
|
||||
className="social-btn coral"
|
||||
href={socialPath(
|
||||
`/chat?intro=${encodeURIComponent(invitation)}`,
|
||||
)}
|
||||
<div className="sp-cafe-reviews">
|
||||
<button
|
||||
type="button"
|
||||
className={`sp-cafe-reviews-toggle${open ? " is-open" : ""}`}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
<MessageCircle size={15} />
|
||||
{socialTx("去聊天室约人")} <ArrowUpRight size={15} />
|
||||
</Link>
|
||||
<p className="social-muted social-cafe-invite-note">
|
||||
{socialTx("先在聊天室约好时间,再出来见面。评分供参考,你也可以留下自己的体验。")}
|
||||
</p>
|
||||
<div className="social-review-layout">
|
||||
<div>
|
||||
<h3>{socialTx("写评价")}</h3>
|
||||
<form
|
||||
className="social-form"
|
||||
onSubmit={(event) => void submit(event)}
|
||||
>
|
||||
<span>
|
||||
{socialTx("评价")}
|
||||
{reviews.length ? ` · ${reviews.length}` : ""}
|
||||
</span>
|
||||
<ChevronDown size={16} aria-hidden />
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="sp-cafe-reviews-body">
|
||||
{!reviews.length ? (
|
||||
<p className="sp-cafe-soft">{socialTx("还没有评价")} · {socialTx("写一条帮后来的人。")}</p>
|
||||
) : (
|
||||
<ul className="sp-cafe-review-list">
|
||||
{reviews.map((review) => (
|
||||
<li key={review.id}>
|
||||
<header>
|
||||
<strong>{review.author}</strong>
|
||||
<span>{"★".repeat(Math.max(1, Math.min(5, review.score)))}</span>
|
||||
</header>
|
||||
<p>{review.text}</p>
|
||||
{review.local ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void submit(undefined, review)}
|
||||
>
|
||||
{socialTx("还没发出 · 再发一次")}
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<form className="sp-cafe-review-form" onSubmit={(e) => void submit(e)}>
|
||||
<label>
|
||||
{socialTx("名字")}
|
||||
<input
|
||||
value={author}
|
||||
onChange={(event) => setAuthor(event.target.value)}
|
||||
onChange={(e) => setAuthor(e.target.value)}
|
||||
maxLength={40}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<fieldset className="social-star-rating">
|
||||
<fieldset className="sp-cafe-stars">
|
||||
<legend>{socialTx("评分")}</legend>
|
||||
{[1, 2, 3, 4, 5].map((value) => (
|
||||
<button
|
||||
type="button"
|
||||
key={value}
|
||||
aria-label={`评分 ${value} 星`}
|
||||
aria-label={`${socialTx("评分")} ${value}`}
|
||||
aria-pressed={score === value}
|
||||
onClick={() => setScore(value)}
|
||||
className={value <= score ? "selected" : ""}
|
||||
className={value <= score ? "is-on" : ""}
|
||||
>
|
||||
<Star
|
||||
size={23}
|
||||
size={20}
|
||||
fill={value <= score ? "currentColor" : "none"}
|
||||
/>
|
||||
</button>
|
||||
@ -229,12 +230,11 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
<label>
|
||||
{socialTx("体验")}
|
||||
<textarea
|
||||
aria-label={socialTx("体验")}
|
||||
required
|
||||
rows={4}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={socialTx("网速 / 插座 / 适合工作还是聊天")}
|
||||
/>
|
||||
</label>
|
||||
@ -243,76 +243,127 @@ function CafeDetail({ cafe, id }: { cafe: SocialCafe; id: string }) {
|
||||
<input
|
||||
maxLength={200}
|
||||
value={photoNote}
|
||||
onChange={(event) => setPhotoNote(event.target.value)}
|
||||
onChange={(e) => setPhotoNote(e.target.value)}
|
||||
placeholder={socialTx("例如:二楼靠窗合影位很好拍")}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="submit"
|
||||
className="social-btn"
|
||||
className="sp-btn sp-btn-primary"
|
||||
disabled={busy || !text.trim()}
|
||||
>
|
||||
{busy ? "提交中…" : "发布"}
|
||||
{busy ? socialTx("提交中…") : socialTx("发布")}
|
||||
</button>
|
||||
</form>
|
||||
{status ? (
|
||||
<p className="sp-cafe-soft" role="status">
|
||||
{status}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<div className="social-section-label">
|
||||
{socialTx("评价")} <span>{reviews.length}</span>
|
||||
</div>
|
||||
{!reviews.length ? (
|
||||
<EmptyState title={socialTx("还没有评价")} description="写一条帮后来的人。">
|
||||
<span className="social-muted">{socialTx("也可以先写在你这边")}</span>
|
||||
</EmptyState>
|
||||
) : (
|
||||
<div className="social-review-list">
|
||||
{reviews.map((review) => (
|
||||
<article key={review.id}>
|
||||
<header>
|
||||
<strong>{review.author}</strong>
|
||||
<span>
|
||||
{"★".repeat(Math.max(1, Math.min(5, review.score)))}
|
||||
</span>
|
||||
</header>
|
||||
<p>{review.text}</p>
|
||||
{review.photoNote ? (
|
||||
<p className="social-muted">合照:{review.photoNote}</p>
|
||||
) : null}
|
||||
<small suppressHydrationWarning>
|
||||
{new Date(review.at).toLocaleDateString()}
|
||||
</small>
|
||||
{review.local && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void submit(undefined, review)}
|
||||
>
|
||||
{socialTx("还没发出 · 再发一次")}
|
||||
</button>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CafeSheet({
|
||||
cafe,
|
||||
onClose,
|
||||
}: {
|
||||
cafe: SocialCafe;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const invitation = `有人约在 ${cafe.city} · ${cafe.name} 喝咖啡,一起聊聊远程生活?`;
|
||||
const cover = cityCover(cafe.city);
|
||||
|
||||
return (
|
||||
<section className="sp-cafe-sheet" aria-labelledby={`cafe-sheet-${cafe.id}`}>
|
||||
<div
|
||||
className="sp-cafe-sheet-hero"
|
||||
style={cover ? { backgroundImage: `url(${cover})` } : undefined}
|
||||
>
|
||||
<div className="sp-cafe-sheet-veil" aria-hidden />
|
||||
<button
|
||||
type="button"
|
||||
className="sp-cafe-sheet-close"
|
||||
aria-label={socialTx("关闭")}
|
||||
onClick={onClose}
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
<div className="sp-cafe-sheet-hero-copy">
|
||||
<p>
|
||||
<span aria-hidden>{cityEmoji(cafe.city)}</span> {cafe.city}
|
||||
{cafe.partners ? ` · ${socialTx("推荐见面点")}` : ""}
|
||||
</p>
|
||||
<h2 id={`cafe-sheet-${cafe.id}`}>{cafe.name}</h2>
|
||||
<em>{cafe.vibe}</em>
|
||||
</div>
|
||||
</div>
|
||||
{status && (
|
||||
<p
|
||||
className={`social-status${status.includes("你这边") || status.includes("网络不太好") ? " warn" : ""}`}
|
||||
role="status"
|
||||
>
|
||||
{status}
|
||||
|
||||
<div className="sp-cafe-sheet-body">
|
||||
<ul className="sp-cafe-facts" aria-label={socialTx("详情")}>
|
||||
<li>
|
||||
<Wifi size={15} aria-hidden /> {cafe.wifiMbps} Mbps
|
||||
</li>
|
||||
<li>
|
||||
<Plug size={15} aria-hidden /> {cafe.power}
|
||||
</li>
|
||||
<li>
|
||||
<Star size={15} aria-hidden /> {cafe.rating}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div className="sp-cafe-sheet-acts">
|
||||
<Link
|
||||
className="sp-btn sp-btn-primary sp-cafe-sheet-cta"
|
||||
href={socialPath(
|
||||
`/coffeechat?city=${encodeURIComponent(cafe.city)}`,
|
||||
)}
|
||||
>
|
||||
<Coffee size={15} aria-hidden />
|
||||
{socialTx("线下咖啡聊")}
|
||||
</Link>
|
||||
<div className="sp-cafe-sheet-sec">
|
||||
<Link
|
||||
className="sp-btn"
|
||||
href={socialPath(
|
||||
`/chat?intro=${encodeURIComponent(invitation)}`,
|
||||
)}
|
||||
>
|
||||
<MessageCircle size={15} aria-hidden />
|
||||
{socialTx("去聊天室约人")}
|
||||
</Link>
|
||||
<ShareButton
|
||||
path={socialPath(
|
||||
`/places?city=${encodeURIComponent(cafe.city)}#${cafe.id}`,
|
||||
)}
|
||||
title={`${cafe.city} · ${cafe.name}`}
|
||||
/>
|
||||
<BookmarkButton id={cafe.id} collection="saved-cafes" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="sp-cafe-soft">
|
||||
{socialTx(
|
||||
"先在聊天室约好时间,再出来见面。评分供参考,你也可以留下自己的体验。",
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<CafeReviewForm key={cafe.id} cafe={cafe} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default function CafeDirectory({
|
||||
embedded = false,
|
||||
hideCityRail = false,
|
||||
}: {
|
||||
/** When true, render cafe list only (used inside /places hub). */
|
||||
embedded?: boolean;
|
||||
/** Parent already shows city chips / banner. */
|
||||
hideCityRail?: boolean;
|
||||
} = {}) {
|
||||
const config = useSocialConfig();
|
||||
const searchParams = useSearchParams();
|
||||
@ -326,26 +377,48 @@ export default function CafeDirectory({
|
||||
if (!cityParam) return "all";
|
||||
const exact = seedCafes.find((c) => c.city === cityParam)?.city;
|
||||
if (exact) return exact;
|
||||
const fuzzy = seedCafes.find((c) =>
|
||||
c.city.includes(cityParam) || cityParam.includes(c.city),
|
||||
const fuzzy = seedCafes.find(
|
||||
(c) => c.city.includes(cityParam) || cityParam.includes(c.city),
|
||||
)?.city;
|
||||
return fuzzy || "all";
|
||||
}, [cityParam, seedCafes]);
|
||||
const [queryChoice, setQueryChoice] = useState<{ source: string; value: string } | null>(null);
|
||||
const [cityChoice, setCityChoice] = useState<{ source: string; value: string } | null>(null);
|
||||
const query = queryChoice?.source === cityParam ? queryChoice.value : cityParam && initialCity === "all" ? cityParam : "";
|
||||
const city = cityChoice?.source === cityParam ? cityChoice.value : initialCity;
|
||||
const setQuery = (value: string) => setQueryChoice({ source: cityParam, value });
|
||||
const setCity = (value: string) => setCityChoice({ source: cityParam, value });
|
||||
const [sort, setSort] = useState("recommended");
|
||||
const selected =
|
||||
useSyncExternalStore(
|
||||
subscribeHash,
|
||||
() => location.hash.slice(1),
|
||||
() => "",
|
||||
) || seedCafes[0]?.id || "";
|
||||
|
||||
const [queryChoice, setQueryChoice] = useState<{
|
||||
source: string;
|
||||
value: string;
|
||||
} | null>(null);
|
||||
const [cityChoice, setCityChoice] = useState<{
|
||||
source: string;
|
||||
value: string;
|
||||
} | null>(null);
|
||||
const query =
|
||||
queryChoice?.source === cityParam
|
||||
? queryChoice.value
|
||||
: cityParam && initialCity === "all"
|
||||
? cityParam
|
||||
: "";
|
||||
const city =
|
||||
cityChoice?.source === cityParam ? cityChoice.value : initialCity;
|
||||
const setQuery = (value: string) =>
|
||||
setQueryChoice({ source: cityParam, value });
|
||||
const setCity = (value: string) =>
|
||||
setCityChoice({ source: cityParam, value });
|
||||
const [sort, setSort] = useState<"recommended" | "wifi" | "rating" | "saved">(
|
||||
"recommended",
|
||||
);
|
||||
const hashId = useSyncExternalStore(
|
||||
subscribeHash,
|
||||
() => location.hash.slice(1),
|
||||
() => "",
|
||||
);
|
||||
const [pickedId, setPickedId] = useState<string | null>(null);
|
||||
const [saved] = useLocalState<string[]>("saved-cafes", []);
|
||||
const id = useId();
|
||||
|
||||
const cities = useMemo(
|
||||
() => [...new Set(seedCafes.map((cafe) => cafe.city))],
|
||||
[seedCafes],
|
||||
);
|
||||
|
||||
const cafes = useMemo(
|
||||
() =>
|
||||
seedCafes
|
||||
@ -362,154 +435,192 @@ export default function CafeDirectory({
|
||||
? b.wifiMbps - a.wifiMbps
|
||||
: sort === "rating"
|
||||
? b.rating - a.rating
|
||||
: 0,
|
||||
: Number(b.partners) - Number(a.partners) || b.rating - a.rating,
|
||||
),
|
||||
[query, city, sort, saved, seedCafes],
|
||||
);
|
||||
const active = cafes.find((cafe) => cafe.id === selected) || cafes[0];
|
||||
|
||||
const selectedId = pickedId || hashId || "";
|
||||
const active = cafes.find((c) => c.id === selectedId) || null;
|
||||
|
||||
const selectCafe = (id: string) => {
|
||||
setPickedId(id);
|
||||
try {
|
||||
history.replaceState(history.state, "", `#${id}`);
|
||||
window.dispatchEvent(new Event("hashchange"));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const clearCafe = () => {
|
||||
setPickedId(null);
|
||||
try {
|
||||
const url = `${location.pathname}${location.search}`;
|
||||
history.replaceState(history.state, "", url);
|
||||
window.dispatchEvent(new Event("hashchange"));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const body = (
|
||||
<>
|
||||
<div className="sp-cafes">
|
||||
{!embedded ? (
|
||||
<>
|
||||
<PageIntro title={socialTx("同城,见一面")} accent="城市与咖啡馆">
|
||||
<div className="social-actions">
|
||||
<DemoBadge>
|
||||
{catalog.source === "remote" ? "最新地点" : "先看看这些地方"}
|
||||
</DemoBadge>
|
||||
<Link className="social-btn" href={socialPath("/people")}>
|
||||
{socialTx("找同城的人")}
|
||||
</Link>
|
||||
<Link className="social-btn" href={socialPath("/chat")}>
|
||||
<MessageCircle size={14} />
|
||||
{socialTx("群组约见面")}
|
||||
</Link>
|
||||
</div>
|
||||
</PageIntro>
|
||||
<p className="social-muted social-event-lead reveal">
|
||||
{socialTx("先选城市 → 找到同城的人 → 再挑一家咖啡馆出来坐坐。")}
|
||||
<header className="sp-cafe-page-head">
|
||||
<p className="sp-eyebrow">{socialTx("线下见面")}</p>
|
||||
<h1>
|
||||
{socialTx("咖啡馆")} <span>{socialTx("会场")}</span>
|
||||
</h1>
|
||||
<p className="sp-lead">
|
||||
{socialTx("先选城市,再挑一家适合见面的咖啡馆。")}
|
||||
</p>
|
||||
<div className="social-cafe-cities reveal">
|
||||
<CityDirectory compact />
|
||||
</header>
|
||||
) : null}
|
||||
|
||||
{!hideCityRail ? (
|
||||
<>
|
||||
<div className="sp-cafe-city-rail" role="tablist" aria-label={socialTx("城市")}>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={city === "all"}
|
||||
className={city === "all" ? "is-on" : ""}
|
||||
onClick={() => setCity("all")}
|
||||
>
|
||||
{socialTx("全部")}
|
||||
</button>
|
||||
{cities.map((name) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={city === name}
|
||||
className={city === name ? "is-on" : ""}
|
||||
onClick={() => setCity(name)}
|
||||
>
|
||||
<span aria-hidden>{cityEmoji(name)}</span>
|
||||
{name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<h3 className="social-section-label reveal" style={{ marginTop: 28 }}>
|
||||
{socialTx("适合见面的咖啡馆")}
|
||||
</h3>
|
||||
|
||||
{city !== "all" ? (
|
||||
<div
|
||||
className="sp-cafe-city-banner"
|
||||
style={
|
||||
cityCover(city)
|
||||
? { backgroundImage: `url(${cityCover(city)})` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="sp-cafe-city-banner-veil" aria-hidden />
|
||||
<div className="sp-cafe-city-banner-copy">
|
||||
<p>
|
||||
<MapPin size={13} aria-hidden /> {city} · {socialTx("线下会场")}
|
||||
</p>
|
||||
<strong>
|
||||
{cityEmoji(city)} {city}
|
||||
</strong>
|
||||
<em>
|
||||
{cafes.length} {socialTx("家咖啡馆")}
|
||||
</em>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
<div className="social-toolbar reveal">
|
||||
<SearchField
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
label={socialTx("搜索咖啡馆")}
|
||||
placeholder={socialTx("店名 / 城市 / 氛围")}
|
||||
/>
|
||||
|
||||
<div className="sp-cafe-toolbar">
|
||||
<label className="sp-cafe-search">
|
||||
<Search size={15} aria-hidden />
|
||||
<span className="sr-only">{socialTx("搜索咖啡馆")}</span>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={socialTx("店名 / 氛围")}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<select
|
||||
className="sp-cafe-sort-select"
|
||||
aria-label={socialTx("咖啡馆排序")}
|
||||
className="social-select"
|
||||
value={sort}
|
||||
onChange={(event) => setSort(event.target.value)}
|
||||
onChange={(e) =>
|
||||
setSort(
|
||||
e.target.value as "recommended" | "wifi" | "rating" | "saved",
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="recommended">{socialTx("推荐")}</option>
|
||||
<option value="wifi">{socialTx("网速")}</option>
|
||||
<option value="rating">{socialTx("评分")}</option>
|
||||
<option value="wifi">{socialTx("网速")}</option>
|
||||
<option value="saved">{socialTx("收藏")}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="social-filters social-city-filters reveal">
|
||||
{["all", ...new Set(seedCafes.map((cafe) => cafe.city))].map(
|
||||
(value) => (
|
||||
<button
|
||||
type="button"
|
||||
className={city === value ? "active" : ""}
|
||||
aria-pressed={city === value}
|
||||
key={value}
|
||||
onClick={() => setCity(value)}
|
||||
>
|
||||
{value === "all" ? "全部" : value}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<ResultSummary count={cafes.length} unit="家咖啡馆" filtered={Boolean(query || city !== "all" || sort !== "recommended")} onReset={() => { setQuery(""); setCity("all"); setSort("recommended"); }} />
|
||||
<div className="social-cafe-layout">
|
||||
<div className="social-grid social-cafe-grid">
|
||||
{cafes.map((cafe, index) => (
|
||||
<article
|
||||
key={cafe.id}
|
||||
id={cafe.id}
|
||||
className={`social-card social-panel-fx reveal cafe-color-${index % 4}${active?.id === cafe.id ? " active" : ""}`}
|
||||
style={{ ["--stagger" as string]: `${index * 70}ms` }}
|
||||
|
||||
<p className="sp-count">
|
||||
{cafes.length} {socialTx("家咖啡馆")}
|
||||
{city !== "all" ? ` · ${city}` : ""}
|
||||
</p>
|
||||
|
||||
<ul className="sp-cafe-list">
|
||||
{cafes.map((cafe) => {
|
||||
const open = active?.id === cafe.id;
|
||||
return (
|
||||
<li key={cafe.id} id={cafe.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={`sp-cafe-row${open ? " is-open" : ""}${cafe.partners ? " is-partner" : ""}`}
|
||||
aria-expanded={open}
|
||||
onClick={() => (open ? clearCafe() : selectCafe(cafe.id))}
|
||||
>
|
||||
<span className="sp-cafe-row-mark" aria-hidden>
|
||||
<Coffee size={18} strokeWidth={1.5} />
|
||||
</span>
|
||||
<span className="sp-cafe-row-main">
|
||||
<strong>{cafe.name}</strong>
|
||||
<em>
|
||||
<MapPin size={11} aria-hidden /> {cafe.city} · {cafe.vibe}
|
||||
</em>
|
||||
<span className="sp-cafe-row-meta">
|
||||
<span>★ {cafe.rating}</span>
|
||||
<span>WiFi {cafe.wifiMbps}M</span>
|
||||
{cafe.partners ? (
|
||||
<span className="is-tag">{socialTx("推荐见面点")}</span>
|
||||
) : null}
|
||||
</span>
|
||||
</span>
|
||||
<ArrowUpRight size={16} className="sp-cafe-row-go" aria-hidden />
|
||||
</button>
|
||||
{open ? <CafeSheet cafe={cafe} onClose={clearCafe} /> : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{!cafes.length ? (
|
||||
<EmptyState
|
||||
emoji="☕"
|
||||
title={socialTx("没有咖啡馆")}
|
||||
description={socialTx("换城市或清空筛选。")}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="sp-btn sp-btn-primary"
|
||||
onClick={() => {
|
||||
setQuery("");
|
||||
setCity("all");
|
||||
setSort("recommended");
|
||||
}}
|
||||
>
|
||||
<div className="social-cafe-art" aria-hidden="true">
|
||||
<Coffee size={45} strokeWidth={1} />
|
||||
<i />
|
||||
<span>{cafe.city}</span>
|
||||
</div>
|
||||
<div className="social-card-top">
|
||||
<span className="social-member-city">
|
||||
<MapPin size={12} />
|
||||
{cafe.city}
|
||||
</span>
|
||||
<BookmarkButton id={cafe.id} collection="saved-cafes" />
|
||||
</div>
|
||||
<strong>{cafe.name}</strong>
|
||||
<p>{cafe.vibe}</p>
|
||||
<div className="social-tags">
|
||||
<span>★ {cafe.rating}</span>
|
||||
<span>WiFi {cafe.wifiMbps}M</span>
|
||||
<span>{cafe.partners ? "推荐见面点" : "社区收录"}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn"
|
||||
aria-pressed={active?.id === cafe.id}
|
||||
aria-controls={id}
|
||||
onClick={() => {
|
||||
history.replaceState(history.state, "", `#${cafe.id}`);
|
||||
window.dispatchEvent(new Event("hashchange"));
|
||||
document.getElementById(id)?.scrollIntoView({
|
||||
behavior: matchMedia("(prefers-reduced-motion: reduce)")
|
||||
.matches
|
||||
? "instant"
|
||||
: "smooth",
|
||||
block: "start",
|
||||
});
|
||||
}}
|
||||
>
|
||||
{active?.id === cafe.id ? "查看中" : "详情"}
|
||||
<ArrowUpRight size={14} />
|
||||
</button>
|
||||
</article>
|
||||
))}
|
||||
{!cafes.length && (
|
||||
<EmptyState
|
||||
emoji="☕"
|
||||
title={socialTx("没有咖啡馆")}
|
||||
description="换城市或清空筛选。"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn"
|
||||
onClick={() => {
|
||||
setQuery("");
|
||||
setCity("all");
|
||||
setSort("recommended");
|
||||
}}
|
||||
>
|
||||
{socialTx("重置筛选")}
|
||||
</button>
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
{active && (
|
||||
<aside className="social-cafe-aside">
|
||||
<CafeDetail key={active.id} cafe={active} id={id} />
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
{socialTx("重置筛选")}
|
||||
</button>
|
||||
</EmptyState>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (embedded) return body;
|
||||
return <SiteShell title={socialTx("见一面")}>{body}</SiteShell>;
|
||||
return <SiteShell title={socialTx("咖啡馆")}>{body}</SiteShell>;
|
||||
}
|
||||
|
||||
@ -47,7 +47,9 @@ import {
|
||||
resolveTrialLimits,
|
||||
trialPaywallHint,
|
||||
} from "@social/lib/socialTrial";
|
||||
import { ensureGuestNick } from "@social/lib/guestNick";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
|
||||
/** 全站唯一聊天室频道 */
|
||||
export const SOCIAL_CHAT_ID = "general";
|
||||
@ -294,6 +296,7 @@ export function Conversation({
|
||||
const setDraft = chat.setDraft;
|
||||
const [emojiOpen, setEmojiOpen] = useState(false);
|
||||
const [composerError, setComposerError] = useState("");
|
||||
const [joinOpen, setJoinOpen] = useState(false);
|
||||
const [reply, setReply] = useState<ChatReplyTo | null>(null);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [pendingAtts, setPendingAtts] = useState<ChatAttachment[]>([]);
|
||||
@ -416,9 +419,12 @@ export function Conversation({
|
||||
}
|
||||
if (!chat.draft.trim() && !pendingAtts.length) return;
|
||||
if (!canUseTrial("chatMessages", trialLimits)) {
|
||||
setComposerError(socialTx(trialPaywallHint("chatMessages")));
|
||||
const hint = socialTx(trialPaywallHint("chatMessages"));
|
||||
setComposerError(hint);
|
||||
setJoinOpen(true);
|
||||
return;
|
||||
}
|
||||
ensureGuestNick();
|
||||
const submittedDraft = chat.draft;
|
||||
const mentions = Array.from(
|
||||
chat.draft.matchAll(/@([\w\u4e00-\u9fff-]{1,24})/g),
|
||||
@ -908,9 +914,14 @@ export function Conversation({
|
||||
onSubmit={(event) => void submit(event)}
|
||||
>
|
||||
{composerError && (
|
||||
<p className="social-status warn" role="alert">
|
||||
<button
|
||||
type="button"
|
||||
className="social-status warn social-chat-join-hint"
|
||||
role="alert"
|
||||
onClick={() => setJoinOpen(true)}
|
||||
>
|
||||
{composerError}
|
||||
</p>
|
||||
</button>
|
||||
)}
|
||||
{editingId && (
|
||||
<div className="social-reply-chip edit">
|
||||
@ -1109,15 +1120,6 @@ export function Conversation({
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<label className="social-nick-label">
|
||||
{socialTx("昵称")}
|
||||
<input
|
||||
aria-label={socialTx("聊天昵称")}
|
||||
value={chat.nick}
|
||||
maxLength={24}
|
||||
onChange={(event) => chat.setNick(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<small>{chat.draft.length}/2000</small>
|
||||
<button
|
||||
className="social-btn primary"
|
||||
@ -1148,6 +1150,7 @@ export function Conversation({
|
||||
{socialTx("放开以上传")}
|
||||
</div>
|
||||
) : null}
|
||||
<JoinPayModal open={joinOpen} onClose={() => setJoinOpen(false)} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -14,16 +14,10 @@ import {
|
||||
Camera,
|
||||
Check,
|
||||
Globe2,
|
||||
Heart,
|
||||
LockKeyhole,
|
||||
MapPin,
|
||||
MessageCircle,
|
||||
Radio,
|
||||
Send,
|
||||
} from "lucide-react";
|
||||
import { WechatOaModal } from "~/components/social-follow";
|
||||
import SiteShell from "./SiteShell";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
import AvatarSelfieModal, {
|
||||
type SelfieCapturePayload,
|
||||
} from "./AvatarSelfieModal";
|
||||
@ -60,11 +54,11 @@ import {
|
||||
type JoinProfileDraft,
|
||||
} from "@social/lib/joinFlow";
|
||||
import { archiveJoinLead } from "@social/lib/joinArchive";
|
||||
import { flagOpenJoinModalSoon, openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { setRosterPublished } from "@social/lib/discoveryRoster";
|
||||
import { loadJson, saveJson } from "@social/lib/storage";
|
||||
import { useLocalState } from "@social/lib/useLocalState";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { resolveSocialLandingCopy } from "@social/lib/landing";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import type { SocialRosterProfile } from "@social/lib/types";
|
||||
@ -102,9 +96,15 @@ export function CommunityFeedback() {
|
||||
});
|
||||
setDelivery("sent");
|
||||
setStatus("已提交,感谢反馈。");
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// 草稿仍在本机表单里;不要再装成「没网」——多数是服务端挂了
|
||||
setDelivery("local");
|
||||
setStatus("先留在你这边了,有网后再试一次");
|
||||
const msg = e instanceof Error ? e.message : "";
|
||||
setStatus(
|
||||
msg && msg.length < 120
|
||||
? `提交失败:${msg}。内容还在表单里,修好后点重试。`
|
||||
: "提交失败。内容还在表单里,请稍后点重试。",
|
||||
);
|
||||
} finally {
|
||||
lock.current = false;
|
||||
setBusy(false);
|
||||
@ -120,7 +120,7 @@ export function CommunityFeedback() {
|
||||
</div>
|
||||
<h2 className="social-feedback-title">{socialTx("哪里用得不顺手?告诉我们")}</h2>
|
||||
<p className="social-muted">
|
||||
{socialTx("发不出去也没关系,会先留在你这边,有网后再试。我们会看,但不保证马上回复。")}
|
||||
{socialTx("我们会看,但不保证马上回复。提交成功后会清空表单。")}
|
||||
</p>
|
||||
{delivery === "sent" ? (
|
||||
<div className="social-join-success">
|
||||
@ -278,56 +278,6 @@ function resolveJoinStep(param: string | null): JoinStep {
|
||||
return "pay";
|
||||
}
|
||||
|
||||
function JoinOnboardingLinks() {
|
||||
return (
|
||||
<>
|
||||
<h3 className="social-onboarding-heading">
|
||||
{socialTx("加入后可以先去这些地方")}
|
||||
</h3>
|
||||
<div className="social-grid social-onboarding-grid">
|
||||
{[
|
||||
{
|
||||
icon: MessageCircle,
|
||||
title: "群组聊天",
|
||||
desc: "先进群打个招呼,混个脸熟",
|
||||
href: socialPath("/chat"),
|
||||
cta: "进群聊",
|
||||
},
|
||||
{
|
||||
icon: Heart,
|
||||
title: "认识一下",
|
||||
desc: "左右滑,慢慢认识新朋友",
|
||||
href: socialPath("/date"),
|
||||
cta: "去看看",
|
||||
},
|
||||
{
|
||||
icon: Radio,
|
||||
title: "开视频聊聊",
|
||||
desc: "群组热身后,开麦或开视频",
|
||||
href: socialPath("/meetup"),
|
||||
cta: "去聊聊",
|
||||
},
|
||||
].map((item) => (
|
||||
<article
|
||||
className="social-card social-onboarding-card"
|
||||
key={item.title}
|
||||
>
|
||||
<div className="social-card-top">
|
||||
<item.icon size={24} strokeWidth={1.3} />
|
||||
</div>
|
||||
<h2>{item.title}</h2>
|
||||
<p className="social-muted">{item.desc}</p>
|
||||
<Link className="social-btn primary" href={item.href}>
|
||||
{item.cta}
|
||||
<ArrowUpRight size={14} />
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function JoinStepMark({ active }: { active: 2 | 3 | 4 }) {
|
||||
const label =
|
||||
active === 2
|
||||
@ -667,6 +617,10 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
lookingFor,
|
||||
discoverable: "1",
|
||||
updatedAt: roster.updatedAt || "",
|
||||
email:
|
||||
(typeof localStorage !== "undefined"
|
||||
? localStorage.getItem("userEmail") || ""
|
||||
: "") || "",
|
||||
});
|
||||
} catch {
|
||||
// Offline / API fail: keep local draft; still mark profile done so UX continues
|
||||
@ -725,7 +679,11 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
<JoinStepMark active={2} />
|
||||
<header className="social-join-desk-intro">
|
||||
<h1>{socialTx("完善资料,方便认识你")}</h1>
|
||||
<p>{socialTx("支付已完成。写得越完整,越容易碰到同频的人。")}</p>
|
||||
<p>
|
||||
{socialTx(
|
||||
"写得越完整,越容易碰到同频的人。头像请重新上传,不要用别人的照片。",
|
||||
)}
|
||||
</p>
|
||||
</header>
|
||||
<article className="social-join-live-card" aria-live="polite">
|
||||
<div className="social-join-live-glow" aria-hidden />
|
||||
@ -1229,6 +1187,7 @@ function JoinLivenessForm({ onDone }: { onDone: () => void }) {
|
||||
type="button"
|
||||
className="social-btn social-join-desk-submit"
|
||||
onClick={() => {
|
||||
// 只记「稍后再自拍」,绝不能写成 join_done / 加入完成
|
||||
void archiveJoinLead("liveness_skipped");
|
||||
onDone();
|
||||
}}
|
||||
@ -1250,23 +1209,20 @@ function JoinLivenessForm({ onDone }: { onDone: () => void }) {
|
||||
}
|
||||
|
||||
export function CommunityJoin() {
|
||||
const config = useSocialConfig();
|
||||
const { locale } = useSocialI18n();
|
||||
const copy = resolveSocialLandingCopy(config.copy, locale);
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const stepParam = searchParams.get("step");
|
||||
const [step, setStep] = useState<JoinStep>(() => stepFromParam(stepParam));
|
||||
const [payOpen, setPayOpen] = useState(false);
|
||||
const [oaOpen, setOaOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
const next = resolveJoinStep(stepParam);
|
||||
setStep(next);
|
||||
// Never invent "paid" here — only /paid (or localhost skip) may markJoinPaid.
|
||||
if (next === "pay" && stepParam && stepParam !== "pay") {
|
||||
router.replace(socialPath("/join"));
|
||||
// Bare /join or pay step: no dedicated page — bounce home + open modal.
|
||||
if (next === "pay") {
|
||||
flagOpenJoinModalSoon();
|
||||
router.replace(socialPath("/"));
|
||||
return;
|
||||
}
|
||||
setStep(next);
|
||||
// Never invent "paid" here — only /paid (or localhost skip) may markJoinPaid.
|
||||
if (next === "profile") {
|
||||
if (stepParam === "profile" && isJoinPaid()) {
|
||||
// Explicit re-fill — clear done so form is writable
|
||||
@ -1288,9 +1244,10 @@ export function CommunityJoin() {
|
||||
|
||||
const goDone = () => {
|
||||
setStep("done");
|
||||
void archiveJoinLead("join_done", {
|
||||
liveness: isLivenessVerified() ? "verified" : "skipped",
|
||||
});
|
||||
// 只有真人核验通过才算「加入完成」;跳过自拍停在 liveness_skipped
|
||||
if (isLivenessVerified()) {
|
||||
void archiveJoinLead("join_done", { liveness: "verified" });
|
||||
}
|
||||
router.replace(`${socialPath("/join")}?step=done`);
|
||||
};
|
||||
|
||||
@ -1304,23 +1261,18 @@ export function CommunityJoin() {
|
||||
const liveOk =
|
||||
(JSON.parse(liveSnap) as { livenessStatus?: string }).livenessStatus ===
|
||||
"verified";
|
||||
const rawFen = Number(config.copy.vipPriceFen);
|
||||
const fen =
|
||||
Number.isFinite(rawFen) && rawFen >= 0 ? Math.round(rawFen) : 10;
|
||||
const priceLabel =
|
||||
fen <= 0
|
||||
? socialTx("免费")
|
||||
: `¥${(fen / 100).toLocaleString("zh-CN", { maximumFractionDigits: 2 })}`;
|
||||
|
||||
// Pay landing removed — redirect handles it; avoid flash of page UI.
|
||||
if (step === "pay") {
|
||||
return (
|
||||
<div className="social-status" style={{ padding: "2rem" }}>
|
||||
{socialTx("正在打开加入…")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("加入社区")} immersive={focusMode}>
|
||||
{step === "pay" ? (
|
||||
<PageIntro
|
||||
title={socialTx("加入社区")}
|
||||
accent={`${socialTx("会费")} ${priceLabel}`}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{step === "profile" ? (
|
||||
<JoinProfileForm onDone={goLiveness} />
|
||||
) : null}
|
||||
@ -1368,74 +1320,6 @@ export function CommunityJoin() {
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{step === "pay" ? (
|
||||
<>
|
||||
<div className="social-join-paths">
|
||||
<article className="social-panel social-join-path reveal">
|
||||
<span className="social-page-kicker">
|
||||
<span />
|
||||
{socialTx("方式一")}
|
||||
</span>
|
||||
<span className="social-join-path-ico" aria-hidden>
|
||||
<LockKeyhole size={24} strokeWidth={1.4} />
|
||||
</span>
|
||||
<h2>
|
||||
{copy.socialPayJoinLabel} · {priceLabel}
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx(
|
||||
"先填邮箱并完成支付,支付成功后再填写个人资料。电脑、手机浏览器和微信里都会带你走合适的支付方式。",
|
||||
)}
|
||||
</p>
|
||||
{config.flags.payEnabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral"
|
||||
onClick={() => setPayOpen(true)}
|
||||
>
|
||||
{copy.socialPayJoinLabel} {priceLabel}
|
||||
<ArrowUpRight size={15} />
|
||||
</button>
|
||||
) : (
|
||||
<span className="social-status">
|
||||
{socialTx("暂时还不能购买")}
|
||||
</span>
|
||||
)}
|
||||
</article>
|
||||
<article className="social-panel social-join-path reveal">
|
||||
<span className="social-page-kicker">
|
||||
<span />
|
||||
{socialTx("方式二")}
|
||||
</span>
|
||||
<span className="social-join-path-ico" aria-hidden>
|
||||
<MessageCircle size={24} strokeWidth={1.4} />
|
||||
</span>
|
||||
<h2>{copy.socialOaJoinLabel}</h2>
|
||||
<p>
|
||||
关注
|
||||
{config.copy.wechatOaName
|
||||
? `「${config.copy.wechatOaName}」`
|
||||
: "公众号"}
|
||||
,先看看社区动态和活动,再决定要不要正式加入。
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn primary"
|
||||
onClick={() => setOaOpen(true)}
|
||||
>
|
||||
{copy.socialOaJoinLabel}
|
||||
<ArrowUpRight size={15} />
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{step === "pay" ? <JoinOnboardingLinks /> : null}
|
||||
|
||||
<JoinPayModal open={payOpen} onClose={() => setPayOpen(false)} />
|
||||
<WechatOaModal open={oaOpen} onClose={() => setOaOpen(false)} />
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
@ -1444,7 +1328,7 @@ export function CommunityMembership() {
|
||||
const config = useSocialConfig();
|
||||
const rawMemFen = Number(config.copy.vipPriceFen);
|
||||
const memFen =
|
||||
Number.isFinite(rawMemFen) && rawMemFen >= 0 ? Math.round(rawMemFen) : 10;
|
||||
Number.isFinite(rawMemFen) && rawMemFen >= 0 ? Math.round(rawMemFen) : 0;
|
||||
const price = (memFen / 100).toLocaleString("zh-CN", {
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
@ -1483,9 +1367,13 @@ export function CommunityMembership() {
|
||||
) : (
|
||||
<span className="social-status">{socialTx("暂时还不能购买")}</span>
|
||||
)}
|
||||
<Link className="social-btn" href={socialPath("/join")}>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn"
|
||||
onClick={() => openSocialJoinModal({ reason: "cta" })}
|
||||
>
|
||||
{socialTx("去加入社区")}
|
||||
</Link>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
<div className="social-grid">
|
||||
|
||||
@ -105,7 +105,7 @@ export default function ConnectionHero({
|
||||
type="button"
|
||||
onClick={onJoin}
|
||||
>
|
||||
{copy.socialJoinCta}
|
||||
{socialTx("加入社区")}
|
||||
</button>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
@ -385,7 +385,7 @@ export function ConnectionWays({ copy }: { copy: SocialLandingCopy }) {
|
||||
href: "/meetup",
|
||||
icon: Radio,
|
||||
title: copy.socialWayChat,
|
||||
sub: "聊天群组 · 语音视频",
|
||||
sub: "语音厅",
|
||||
cta: "去聊聊",
|
||||
className: "mint",
|
||||
},
|
||||
|
||||
@ -19,7 +19,7 @@ import {
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
import { DemoBadge, ShareButton, SocialDialog } from "./SocialUI";
|
||||
import { ShareButton, SocialDialog } from "./SocialUI";
|
||||
import { SocialMobileDock } from "./SocialNavigation";
|
||||
import type { SocialRosterMember } from "@social/lib/rosterMock";
|
||||
import { useDiscoveryRoster, SELF_MEMBER_ID } from "@social/lib/discoveryRoster";
|
||||
@ -272,7 +272,6 @@ export default function DateClient() {
|
||||
? THRESHOLD_MOBILE
|
||||
: THRESHOLD_DESKTOP;
|
||||
const likeOpacity = Math.min(1, Math.max(0, drag.x / stampThreshold));
|
||||
const passOpacity = Math.min(1, Math.max(0, -drag.x / stampThreshold));
|
||||
|
||||
return (
|
||||
<div className="social-root social-live-root social-skin social-date-root">
|
||||
@ -283,23 +282,22 @@ export default function DateClient() {
|
||||
{socialTx("首页")}
|
||||
</Link>
|
||||
<div>
|
||||
<strong>{socialTx("认识一下")}</strong>
|
||||
<strong>{socialTx("约会")}</strong>
|
||||
<p className="social-muted">
|
||||
左滑划走 · 右滑想认识
|
||||
左滑跳过 · 右滑想认识
|
||||
{totalForFilter
|
||||
? ` · 还剩 ${remaining}/${totalForFilter}`
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<DemoBadge>{socialTx("示例介绍,方便先逛逛")}</DemoBadge>
|
||||
</div>
|
||||
<div className="social-date-bar-tools">
|
||||
<div className="social-filters" aria-label={socialTx("筛选")}>
|
||||
{(
|
||||
[
|
||||
["all", "全部"],
|
||||
["f", "女生"],
|
||||
["m", "男生"],
|
||||
["f", "👩 女生"],
|
||||
["m", "👨 男生"],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button
|
||||
@ -323,7 +321,7 @@ export default function DateClient() {
|
||||
想认识 {liked.length}
|
||||
</button>
|
||||
) : null}
|
||||
<ShareButton path={socialPath("/date")} title={socialTx("游民社区 · 认识一下")} />
|
||||
<ShareButton path={socialPath("/date")} title={socialTx("游民社区 · 约会")} />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@ -410,19 +408,12 @@ export default function DateClient() {
|
||||
>
|
||||
{socialTx("想认识")}
|
||||
</span>
|
||||
<span
|
||||
className="social-date-stamp pass"
|
||||
style={{ opacity: fly?.dir === "pass" ? 1 : passOpacity }}
|
||||
>
|
||||
{socialTx("划走")}
|
||||
</span>
|
||||
<DateCardFace member={current} />
|
||||
</article>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="social-date-hint is-alive" aria-hidden={!current}>
|
||||
<span className="social-date-hint-side pass">← 划走</span>
|
||||
<span>{socialTx("拖卡片左右滑 · 或点下面按钮")}</span>
|
||||
<span className="social-date-hint-side like">{socialTx("想认识 →")}</span>
|
||||
</p>
|
||||
@ -637,8 +628,19 @@ function DateCardFace({ member }: { member: SocialRosterMember }) {
|
||||
) : null}
|
||||
<div className="social-date-meta">
|
||||
<div className="social-date-name">
|
||||
<h2>{member.name}</h2>
|
||||
<h2>
|
||||
<span className="social-date-gender" aria-hidden>
|
||||
{member.gender === "f" ? "👩" : member.gender === "m" ? "👨" : "🙂"}
|
||||
</span>{" "}
|
||||
{member.name}
|
||||
</h2>
|
||||
<p>
|
||||
{member.gender === "f"
|
||||
? "女生"
|
||||
: member.gender === "m"
|
||||
? "男生"
|
||||
: ""}
|
||||
{member.gender === "f" || member.gender === "m" ? " · " : ""}
|
||||
{member.title}
|
||||
{member.vibe ? ` · ${member.vibe}` : ""}
|
||||
</p>
|
||||
|
||||
@ -6,7 +6,6 @@ import {
|
||||
ArrowUpRight,
|
||||
CalendarPlus,
|
||||
Clock3,
|
||||
Globe2,
|
||||
MessageCircle,
|
||||
Radio,
|
||||
} from "lucide-react";
|
||||
@ -47,14 +46,14 @@ export default function EventDirectory() {
|
||||
(filter !== "saved" || saved.includes(item.id)),
|
||||
);
|
||||
return (
|
||||
<SiteShell title={socialTx("开视频聊聊")}>
|
||||
<PageIntro title={socialTx("随时,聊得来")} accent="群组 · 语音视频">
|
||||
<SiteShell title={socialTx("语音厅")}>
|
||||
<PageIntro title={socialTx("语音厅")} accent="开麦 · 开视频">
|
||||
<DemoBadge>
|
||||
{catalog.source === "remote" ? "最新场次" : "先看看有哪些场"}
|
||||
{catalog.source === "remote" ? "最新场次" : "场次"}
|
||||
</DemoBadge>
|
||||
</PageIntro>
|
||||
<p className="social-muted social-event-lead reveal">
|
||||
{socialTx("先进聊天群组热热身,再开语音或视频见面——比只打字更近一点。")}
|
||||
{socialTx("点进场次即开麦开摄像头,比只打字更近一点。")}
|
||||
</p>
|
||||
<div className="social-toolbar reveal">
|
||||
<SearchField
|
||||
@ -76,16 +75,10 @@ export default function EventDirectory() {
|
||||
className={filter === "saved" ? "active" : ""}
|
||||
onClick={() => setFilter("saved")}
|
||||
>
|
||||
{socialTx("我想参加的")}
|
||||
{socialTx("已收藏")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="social-status social-event-banner reveal">
|
||||
<Globe2 size={15} />
|
||||
<span>
|
||||
{socialTx("时间会按你所在时区显示。「想参加」只是先记一下,还不算正式报名。")}
|
||||
</span>
|
||||
</div>
|
||||
<ResultSummary count={events.length} unit="个场次" filtered={Boolean(query || filter !== "all")} onReset={() => { setQuery(""); setFilter("all"); }} />
|
||||
<div className="social-event-grid">
|
||||
{events.map((event, index) => {
|
||||
@ -123,17 +116,13 @@ export default function EventDirectory() {
|
||||
<div className="social-event-body">
|
||||
<div className="social-card-top">
|
||||
<span className="social-badge live">
|
||||
{event.mode === "hybrid"
|
||||
? "群组 · 可线下"
|
||||
: "聊天群组 · 语音视频"}
|
||||
{event.mode === "hybrid" ? "可线下" : "语音厅"}
|
||||
</span>
|
||||
<span className="social-badge">{socialTx("可以先看看")}</span>
|
||||
</div>
|
||||
<div className="social-meetup-faces" aria-hidden>
|
||||
{roster.slice(index + 2, index + 6).map((p) => (
|
||||
<SocialAvatar key={p.id} src={p.avatar} size={22} lazy />
|
||||
))}
|
||||
<em>{socialTx("示例成员")}</em>
|
||||
</div>
|
||||
<h2>{event.title}</h2>
|
||||
<p className="social-event-time">
|
||||
@ -147,19 +136,19 @@ export default function EventDirectory() {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZoneName: "short",
|
||||
})}` : "排期待更新,请在活动频道确认。"}
|
||||
})}` : "排期待更新"}
|
||||
</p>
|
||||
<div className="social-event-cta">
|
||||
<Link
|
||||
className="social-btn primary"
|
||||
href={socialPath(`/meetup/${event.id}`)}
|
||||
>
|
||||
{socialTx("进入聊聊")} <ArrowUpRight size={15} />
|
||||
{socialTx("进入")} <ArrowUpRight size={15} />
|
||||
</Link>
|
||||
<BookmarkButton
|
||||
id={event.id}
|
||||
collection="saved-events"
|
||||
label={socialTx("想参加")}
|
||||
label={socialTx("收藏")}
|
||||
/>
|
||||
</div>
|
||||
<div className="social-event-tools">
|
||||
|
||||
@ -9,13 +9,14 @@ import {
|
||||
} from "react";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "./SiteShell";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
import AttractiveRoster from "./AttractiveRoster";
|
||||
import ConnectionHero, { ConnectionWays } from "./ConnectionHero";
|
||||
import { useHomeLivenessGate } from "./HomeStatusStrip";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import FxBelt from "./FxBelt";
|
||||
import SectionSpark from "./SectionSpark";
|
||||
import CityDirectory from "./CityDirectory";
|
||||
import HomeCoffeeEntry from "./HomeCoffeeEntry";
|
||||
import SocialBrandLogo from "./SocialBrandLogo";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
import {
|
||||
@ -62,9 +63,9 @@ export default function HomeClient() {
|
||||
const roster = useDiscoveryRoster();
|
||||
// Dating strip: same face gate as /date — no face → never preview
|
||||
const datingRoster = useDiscoveryRoster({ requireFace: true });
|
||||
const { liveOk, verifyHref } = useHomeLivenessGate();
|
||||
const [joinOpen, setJoinOpen] = useState(false);
|
||||
const { liveOk } = useHomeLivenessGate();
|
||||
const [activeSection, setActiveSection] = useState("people");
|
||||
const openJoin = () => openSocialJoinModal({ reason: "cta" });
|
||||
const sessionSnap = useSyncExternalStore(
|
||||
subscribeSocialSession,
|
||||
() => JSON.stringify(getSocialSession()),
|
||||
@ -159,11 +160,11 @@ export default function HomeClient() {
|
||||
<i className="social-fx-orb o2" />
|
||||
<i className="social-fx-orb o3" />
|
||||
</div>
|
||||
<SiteShell home onJoin={() => setJoinOpen(true)}>
|
||||
<SiteShell home>
|
||||
<div className="connection-scroll-progress" aria-hidden="true" />
|
||||
<main id="social-main">
|
||||
<ConnectionHero
|
||||
onJoin={() => setJoinOpen(true)}
|
||||
onJoin={openJoin}
|
||||
promoUrl={promoUrl}
|
||||
copy={landingCopy}
|
||||
/>
|
||||
@ -211,7 +212,7 @@ export default function HomeClient() {
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<AttractiveRoster onJoin={() => setJoinOpen(true)} />
|
||||
<AttractiveRoster onJoin={openJoin} />
|
||||
|
||||
<section
|
||||
className="section section-compact social-section-alt"
|
||||
@ -233,12 +234,12 @@ export default function HomeClient() {
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx(
|
||||
"像翻相册一样:不感兴趣就划走,想认识就留下。记在你这边,之后再决定要不要打招呼。",
|
||||
"像翻相册一样:不感兴趣就跳过,想认识就留下。之后再决定要不要打招呼。",
|
||||
)}
|
||||
</p>
|
||||
<ul className="social-date-hero-steps">
|
||||
<li>
|
||||
<em>←</em> {socialTx("划走")}
|
||||
<em>←</em> {socialTx("跳过")}
|
||||
</li>
|
||||
<li>
|
||||
<em>→</em> {socialTx("想认识")}
|
||||
@ -324,9 +325,7 @@ export default function HomeClient() {
|
||||
{landingCopy.socialOnlineTitle}
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx(
|
||||
"先进聊天群组热热身,再开语音或视频见面。「想参加」会先记在你这边。",
|
||||
)}
|
||||
{socialTx("进语音厅直接开麦开摄像头,和大家面对面聊聊。")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="social-panel-grid social-panel-grid-2">
|
||||
@ -365,7 +364,7 @@ export default function HomeClient() {
|
||||
</div>
|
||||
<div className="social-panel-meta">
|
||||
<span>
|
||||
{m.city === "Online" ? "群组 · 语音视频" : m.city}
|
||||
{m.city === "Online" ? "语音厅" : m.city}
|
||||
</span>
|
||||
<time>
|
||||
{m.date} · {m.time}
|
||||
@ -375,15 +374,14 @@ export default function HomeClient() {
|
||||
{roster.slice(i + 1, i + 5).map((p) => (
|
||||
<SocialAvatar key={p.id} src={p.avatar} size={24} lazy />
|
||||
))}
|
||||
<em>+{6 + i} 想参加</em>
|
||||
</div>
|
||||
<h3>{m.title}</h3>
|
||||
<p>{socialTx("群里打个招呼 → 开麦 / 开视频 → 认识新朋友")}</p>
|
||||
<p>{socialTx("开麦 / 开视频 · 认识新朋友")}</p>
|
||||
<Link
|
||||
className="btn btn-primary btn-sm"
|
||||
href={socialPath(`/meetup/${m.id}`)}
|
||||
>
|
||||
{socialTx("进入聊聊")}
|
||||
{socialTx("进入语音厅")}
|
||||
<ArrowUpRight size={14} />
|
||||
</Link>
|
||||
</article>
|
||||
@ -399,7 +397,7 @@ export default function HomeClient() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => setJoinOpen(true)}
|
||||
onClick={openJoin}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</button>
|
||||
@ -409,30 +407,15 @@ export default function HomeClient() {
|
||||
|
||||
<FxBelt />
|
||||
|
||||
<div id="cities">
|
||||
<HomeCoffeeEntry />
|
||||
</div>
|
||||
|
||||
<section
|
||||
className="section section-compact"
|
||||
id="cities"
|
||||
aria-label={socialTx("同城见一面")}
|
||||
aria-label={socialTx("城市足迹")}
|
||||
>
|
||||
<div className="container">
|
||||
<div className="section-header reveal">
|
||||
<SectionSpark label="cities" />
|
||||
<span className="section-tag">
|
||||
<span>{socialTx("挑一座城")}</span>
|
||||
<span>{socialTx("再出来见面")}</span>
|
||||
</span>
|
||||
<h2>
|
||||
<span className="social-title-emoji" aria-hidden>
|
||||
🌆
|
||||
</span>
|
||||
{landingCopy.socialOfflineTitle}
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx(
|
||||
"认识了、聊过之后,出来见一面会更自然。先挑一座城市,再找适合见面的咖啡馆。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="social-map-teaser reveal">
|
||||
<div className="social-map-teaser-copy">
|
||||
<strong>{socialTx("地图摘要")}</strong>
|
||||
@ -449,30 +432,36 @@ export default function HomeClient() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
href={liveOk ? socialPath("/map") : verifyHref}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
{liveOk
|
||||
? socialTx("打开地图")
|
||||
: socialTx("去完善")}
|
||||
<ArrowUpRight size={15} aria-hidden />
|
||||
</Link>
|
||||
{liveOk ? (
|
||||
<Link href={socialPath("/map")} className="btn btn-primary">
|
||||
{socialTx("打开地图")}
|
||||
<ArrowUpRight size={15} aria-hidden />
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={openJoin}
|
||||
>
|
||||
{socialTx("去完善")}
|
||||
<ArrowUpRight size={15} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<CityDirectory compact limit={8} />
|
||||
<CityDirectory compact limit={6} />
|
||||
<div className="social-section-actions reveal">
|
||||
<Link href={socialPath("/places")} className="btn btn-primary">
|
||||
<Link href={socialPath("/coffeechat")} className="btn btn-primary">
|
||||
{socialTx("线下咖啡聊")}
|
||||
</Link>
|
||||
<Link href={socialPath("/places")} className="btn btn-ghost">
|
||||
{socialTx("逛城市")}
|
||||
</Link>
|
||||
<Link
|
||||
href={socialPath("/places?tab=cafes")}
|
||||
href={socialPath("/places")}
|
||||
className="btn btn-ghost"
|
||||
>
|
||||
{socialTx("咖啡馆见面")}
|
||||
</Link>
|
||||
<Link href={socialPath("/people")} className="btn btn-ghost">
|
||||
{socialTx("找同城的人")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@ -593,7 +582,7 @@ export default function HomeClient() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => setJoinOpen(true)}
|
||||
onClick={openJoin}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</button>
|
||||
@ -619,7 +608,7 @@ export default function HomeClient() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn connection-join"
|
||||
onClick={() => setJoinOpen(true)}
|
||||
onClick={openJoin}
|
||||
>
|
||||
{socialTx("加入游民社区")} <ArrowUpRight size={19} />
|
||||
</button>
|
||||
@ -639,19 +628,19 @@ export default function HomeClient() {
|
||||
<button
|
||||
type="button"
|
||||
className="social-footer-link"
|
||||
onClick={() => setJoinOpen(true)}
|
||||
onClick={openJoin}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</button>
|
||||
<Link href={socialPath("/people")}>{socialTx("想见的人")}</Link>
|
||||
<Link href={socialPath("/date")}>{socialTx("认识一下")}</Link>
|
||||
<Link href={socialPath("/meetup")}>{socialTx("开视频聊聊")}</Link>
|
||||
<Link href={socialPath("/date")}>{socialTx("约会")}</Link>
|
||||
<Link href={socialPath("/meetup")}>{socialTx("语音厅")}</Link>
|
||||
<Link href={socialPath("/chat")}>{socialTx("大家聊天")}</Link>
|
||||
</div>
|
||||
<div className="footer-links footer-links-secondary">
|
||||
<h4>{socialTx("见面 · 做事")}</h4>
|
||||
<Link href={socialPath("/places")}>{socialTx("城市")}</Link>
|
||||
<Link href={socialPath("/team")}>{socialTx("找搭子做事")}</Link>
|
||||
<Link href={socialPath("/team")}>{socialTx("找搭子")}</Link>
|
||||
<Link href={socialPath("/ebook")}>{socialTx("共创")}</Link>
|
||||
<Link href={socialPath("/feedback")}>{socialTx("说说想法")}</Link>
|
||||
</div>
|
||||
@ -659,7 +648,7 @@ export default function HomeClient() {
|
||||
<h4>{socialTx("更多")}</h4>
|
||||
<Link href={socialPath("/skills")}>{socialTx("技能交换")}</Link>
|
||||
<Link href={socialPath("/coffeechat")}>
|
||||
{socialTx("咖啡聊预约")}
|
||||
{socialTx("线下咖啡聊")}
|
||||
</Link>
|
||||
<Link href={socialPath("/wrapped")}>{socialTx("年度回顾")}</Link>
|
||||
<Link href="/portal">{socialTx("门户首页")}</Link>
|
||||
@ -702,8 +691,6 @@ export default function HomeClient() {
|
||||
</div>
|
||||
</footer>
|
||||
</SiteShell>
|
||||
|
||||
<JoinPayModal open={joinOpen} onClose={() => setJoinOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,69 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { ArrowUpRight, Coffee } from "lucide-react";
|
||||
import { ArrowUpRight, Coffee, MapPin } from "lucide-react";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import { SOCIAL_CITIES } from "@social/lib/cities";
|
||||
import SectionSpark from "./SectionSpark";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
|
||||
const HOST = {
|
||||
name: "Alice",
|
||||
city: "清迈 · Chiang Mai",
|
||||
city: "清迈",
|
||||
cityId: "chiangmai",
|
||||
avatar:
|
||||
"https://api.dicebear.com/7.x/lorelei/svg?seed=AliceHost&backgroundColor=f59e0b",
|
||||
};
|
||||
|
||||
const RAIL_IDS = ["chengdu", "dali", "chiangmai", "bali", "lisbon", "hangzhou"];
|
||||
|
||||
export default function HomeCoffeeEntry({
|
||||
/** When true, render on /coffeechat itself (CTA books instead of re-linking). */
|
||||
inPage = false,
|
||||
}: {
|
||||
inPage?: boolean;
|
||||
}) {
|
||||
// Nav / entry no longer hard-locks; trial limits apply on booking page.
|
||||
const href = inPage
|
||||
const cities = useMemo(
|
||||
() =>
|
||||
RAIL_IDS.map((id) => SOCIAL_CITIES.find((c) => c.id === id)).filter(
|
||||
Boolean,
|
||||
) as typeof SOCIAL_CITIES,
|
||||
[],
|
||||
);
|
||||
const [cityId, setCityId] = useState(cities[0]?.id || "chengdu");
|
||||
const active = cities.find((c) => c.id === cityId) || cities[0];
|
||||
|
||||
const bookHref = inPage
|
||||
? socialPath("/coffeechat/guest")
|
||||
: socialPath("/coffeechat");
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`section section-compact${inPage ? " home-coffee-on-page" : ""}`}
|
||||
className={`section section-compact home-coffee-city${inPage ? " home-coffee-on-page" : ""}`}
|
||||
id={inPage ? undefined : "coffeechat"}
|
||||
aria-label={socialTx("咖啡聊")}
|
||||
aria-label={socialTx("线下咖啡聊")}
|
||||
>
|
||||
<div className="container">
|
||||
<div className="section-header reveal">
|
||||
<SectionSpark label="coffee" />
|
||||
<span className="section-tag">
|
||||
<span>{socialTx("咖啡聊")}</span>
|
||||
<span>{socialTx("约一杯见面")}</span>
|
||||
<span>{socialTx("线下 Coffee")}</span>
|
||||
<span>{socialTx("城市见面")}</span>
|
||||
</span>
|
||||
<h2>
|
||||
<span className="social-title-emoji" aria-hidden>
|
||||
☕
|
||||
</span>
|
||||
{socialTx("咖啡聊预约")}
|
||||
{socialTx("挑一座城,约一杯线下咖啡")}
|
||||
</h2>
|
||||
<p>
|
||||
{socialTx(
|
||||
"不想自己硬约?先和主持人喝杯咖啡,轻松认识同城游民。",
|
||||
"咖啡聊预约就是线下见面:先选城,再约咖啡馆。不是线上会议。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Link href={href} className="home-coffee-card reveal">
|
||||
<div className="home-coffee-city-rail reveal" role="tablist">
|
||||
{cities.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={cityId === c.id}
|
||||
className={`home-coffee-city-chip${cityId === c.id ? " is-on" : ""}`}
|
||||
onClick={() => setCityId(c.id)}
|
||||
>
|
||||
<span aria-hidden>{c.emoji}</span>
|
||||
{c.name}
|
||||
</button>
|
||||
))}
|
||||
<Link href={socialPath("/places")} className="home-coffee-city-more">
|
||||
{socialTx("更多城市")} <ArrowUpRight size={14} />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{active ? (
|
||||
<div
|
||||
className="home-coffee-city-stage reveal"
|
||||
style={
|
||||
active.cover
|
||||
? { backgroundImage: `url(${active.cover})` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="home-coffee-city-stage-veil" />
|
||||
<div className="home-coffee-city-stage-copy">
|
||||
<p>
|
||||
<MapPin size={14} aria-hidden /> {active.country} ·{" "}
|
||||
{socialTx("线下会场")}
|
||||
</p>
|
||||
<strong>
|
||||
{active.emoji} {active.name}
|
||||
</strong>
|
||||
<em>{active.vibe}</em>
|
||||
<p className="home-coffee-city-blurb">
|
||||
{active.blurb ||
|
||||
socialTx("同城咖啡馆见面,破冰比私信快。")}
|
||||
</p>
|
||||
<div className="home-coffee-city-acts">
|
||||
<Link
|
||||
href={socialPath(`/places/${active.id}`)}
|
||||
className="btn btn-ghost btn-sm"
|
||||
>
|
||||
{socialTx("看这座城")}
|
||||
</Link>
|
||||
<Link
|
||||
href={socialPath("/places")}
|
||||
className="btn btn-ghost btn-sm"
|
||||
>
|
||||
{socialTx("咖啡馆")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Link href={bookHref} className="home-coffee-card reveal">
|
||||
<SocialAvatar src={HOST.avatar} size={64} />
|
||||
<div className="home-coffee-copy">
|
||||
<em>{socialTx("主持人")}</em>
|
||||
<em>
|
||||
{socialTx("线下主持人")} · {active?.name || HOST.city}
|
||||
</em>
|
||||
<strong>
|
||||
{HOST.name} · {HOST.city}
|
||||
{HOST.name} · {socialTx("咖啡馆轻聊")}
|
||||
</strong>
|
||||
<p>
|
||||
{socialTx("数字游民主持人 · 咖啡馆轻聊,帮你破冰同城")}
|
||||
{socialTx(
|
||||
"不想自己硬约?先和主持人喝杯咖啡,轻松认识同城游民。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<span className="btn btn-primary btn-sm">
|
||||
<Coffee size={14} /> {socialTx("去预约")}
|
||||
<Coffee size={14} /> {socialTx("去预约线下")}
|
||||
<ArrowUpRight size={14} />
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
@ -13,6 +13,7 @@ import {
|
||||
} from "@social/lib/livenessGate";
|
||||
import { loadJson } from "@social/lib/storage";
|
||||
import type { SocialRosterProfile } from "@social/lib/types";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
@ -72,9 +73,10 @@ export default function HomeStatusStrip() {
|
||||
const liveOk = state.livenessStatus === "verified";
|
||||
const livePending = state.livenessStatus === "pending";
|
||||
|
||||
let nextHref = socialPath("/join?step=profile");
|
||||
let nextHref: string | null = null;
|
||||
let nextLabel = socialTx("去完善");
|
||||
let nextHint = socialTx("先上传头像,再拍张自拍");
|
||||
let nextOpensJoin = true;
|
||||
|
||||
if (!faceOk) {
|
||||
nextHint = socialTx("下一步:上传一张清晰的正面头像");
|
||||
@ -86,6 +88,7 @@ export default function HomeStatusStrip() {
|
||||
nextHref = socialPath("/coffeechat");
|
||||
nextLabel = socialTx("去咖啡聊");
|
||||
nextHint = socialTx("都好了,可以去约会 / 咖啡聊");
|
||||
nextOpensJoin = false;
|
||||
}
|
||||
|
||||
const secondaryHref = liveOk
|
||||
@ -130,9 +133,19 @@ export default function HomeStatusStrip() {
|
||||
</ul>
|
||||
<p className="home-status-hint">{nextHint}</p>
|
||||
<div className="home-status-acts">
|
||||
<Link className="btn btn-primary btn-sm" href={nextHref}>
|
||||
{nextLabel} <ArrowUpRight size={14} />
|
||||
</Link>
|
||||
{nextOpensJoin || !nextHref ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => openSocialJoinModal({ reason: "gate" })}
|
||||
>
|
||||
{nextLabel} <ArrowUpRight size={14} />
|
||||
</button>
|
||||
) : (
|
||||
<Link className="btn btn-primary btn-sm" href={nextHref}>
|
||||
{nextLabel} <ArrowUpRight size={14} />
|
||||
</Link>
|
||||
)}
|
||||
<Link className="btn btn-ghost btn-sm" href={secondaryHref}>
|
||||
{secondaryLabel}
|
||||
</Link>
|
||||
@ -146,7 +159,7 @@ export default function HomeStatusStrip() {
|
||||
export function useHomeLivenessGate(): {
|
||||
faceOk: boolean;
|
||||
liveOk: boolean;
|
||||
verifyHref: string;
|
||||
openVerify: () => void;
|
||||
} {
|
||||
const liveSnap = useSyncExternalStore(
|
||||
subscribeLivenessState,
|
||||
@ -162,6 +175,6 @@ export function useHomeLivenessGate(): {
|
||||
return {
|
||||
faceOk: state.faceOk,
|
||||
liveOk: unlockSnap === "1",
|
||||
verifyHref: socialPath("/join"),
|
||||
openVerify: () => openSocialJoinModal({ reason: "gate" }),
|
||||
};
|
||||
}
|
||||
|
||||
@ -3,8 +3,13 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { ArrowUpRight, LockKeyhole, Sparkles, X } from "lucide-react";
|
||||
import { archiveJoinLead } from "@social/lib/joinArchive";
|
||||
import { markJoinPayIntent } from "@social/lib/joinFlow";
|
||||
import {
|
||||
markJoinPaid,
|
||||
markJoinPayIntent,
|
||||
skipJoinPayToProfile,
|
||||
} from "@social/lib/joinFlow";
|
||||
import { loginWithEmail } from "@social/lib/socialSession";
|
||||
import { refreshRemoteConfig } from "~/lib/use-remote-config";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
@ -15,9 +20,15 @@ type Props = {
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
function resolvePriceFen(raw: unknown): number | null {
|
||||
const n = Number(raw);
|
||||
// vipPriceFen=0 是合法免费;禁止 NaN 回落成 10 分假付费
|
||||
if (!Number.isFinite(n) || n < 0) return null;
|
||||
return Math.round(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加群:填邮箱 → 调起门户统一支付
|
||||
* PC/H5 → zpay;微信内 H5 → xpay(xorpay);小程序 WebView 提示走虚拟支付
|
||||
* 加群:填邮箱 → 付费调支付 / 免费直接进资料
|
||||
*/
|
||||
export default function JoinPayModal({ open, onClose }: Props) {
|
||||
return open ? <JoinPaySheet onClose={onClose} /> : null;
|
||||
@ -30,35 +41,56 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const config = useSocialConfig();
|
||||
const rawFen = Number(config.copy?.vipPriceFen);
|
||||
const priceFen =
|
||||
Number.isFinite(rawFen) && rawFen >= 0 ? Math.round(rawFen) : 10;
|
||||
const [email, setEmail] = useState(() => {
|
||||
try {
|
||||
return localStorage.getItem("userEmail") || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
const contextFen = resolvePriceFen(config.copy?.vipPriceFen);
|
||||
const [liveFen, setLiveFen] = useState<number | null>(contextFen);
|
||||
const [priceSyncing, setPriceSyncing] = useState(true);
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
|
||||
// 上下文被 SSE/轮询刷新时跟着变
|
||||
useEffect(() => {
|
||||
if (contextFen != null) setLiveFen(contextFen);
|
||||
}, [contextFen]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
const opener = document.activeElement as HTMLElement | null;
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
dialog?.showModal();
|
||||
setEmail("");
|
||||
inputRef.current?.focus();
|
||||
document.body.style.overflow = "hidden";
|
||||
|
||||
let cancelled = false;
|
||||
setPriceSyncing(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const fresh = await refreshRemoteConfig(true);
|
||||
if (cancelled) return;
|
||||
const fen = resolvePriceFen(fresh.copy?.vipPriceFen);
|
||||
if (fen != null) setLiveFen(fen);
|
||||
} catch {
|
||||
/* 用上下文价兜底 */
|
||||
} finally {
|
||||
if (!cancelled) setPriceSyncing(false);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
dialog?.close();
|
||||
document.body.style.overflow = previousOverflow;
|
||||
opener?.focus();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const priceFen = liveFen ?? contextFen;
|
||||
const isFree = priceFen != null && priceFen <= 0;
|
||||
const priceKnown = priceFen != null;
|
||||
|
||||
const submit = async () => {
|
||||
if (busy) return;
|
||||
if (busy || priceSyncing || !priceKnown) return;
|
||||
const value = email.trim().toLowerCase();
|
||||
if (!EMAIL_RE.test(value)) {
|
||||
setErr("请输入有效邮箱");
|
||||
@ -67,11 +99,26 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
|
||||
setErr("");
|
||||
setBusy(true);
|
||||
try {
|
||||
// 提交前再拉一次,防止弹窗打开后后台又改价
|
||||
const fresh = await refreshRemoteConfig(true);
|
||||
const fenNow = resolvePriceFen(fresh.copy?.vipPriceFen) ?? priceFen ?? 0;
|
||||
const freeNow = fenNow <= 0;
|
||||
setLiveFen(fenNow);
|
||||
|
||||
loginWithEmail(value);
|
||||
markJoinPayIntent();
|
||||
// Must await before pay redirect — otherwise fetch is aborted and admin sees no lead
|
||||
if (freeNow) {
|
||||
await archiveJoinLead("email_submit", {
|
||||
priceFen: 0,
|
||||
intent: "free",
|
||||
});
|
||||
markJoinPaid("free");
|
||||
onClose();
|
||||
skipJoinPayToProfile();
|
||||
return;
|
||||
}
|
||||
await archiveJoinLead("email_submit", {
|
||||
priceFen,
|
||||
priceFen: fenNow,
|
||||
intent: "pay",
|
||||
});
|
||||
|
||||
@ -88,15 +135,24 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
|
||||
const { triggerPay } = await import("@vip/app/lib/triggerPay");
|
||||
const returnUrl = `${window.location.origin}/paid?join=1`;
|
||||
await triggerPay(undefined, { returnUrl });
|
||||
void archiveJoinLead("pay_launched", { priceFen });
|
||||
void archiveJoinLead("pay_launched", { priceFen: fenNow });
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : "支付唤起失败,请稍后重试");
|
||||
setErr(e instanceof Error ? e.message : "操作失败,请稍后重试");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const busyLabel = isFree
|
||||
? socialTx("正在进入…")
|
||||
: socialTx("正在前往支付…");
|
||||
const ctaLabel = !priceKnown || priceSyncing
|
||||
? socialTx("同步价格中…")
|
||||
: isFree
|
||||
? socialTx("免费加入,填资料")
|
||||
: socialTx("确认并支付");
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
@ -127,10 +183,14 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
|
||||
</button>
|
||||
</header>
|
||||
<h2 id={titleId} className="social-join-title">
|
||||
{socialTx("加入游民社区")}
|
||||
{isFree ? socialTx("免费加入游民社区") : socialTx("加入游民社区")}
|
||||
</h2>
|
||||
<p id={descriptionId} className="social-muted">
|
||||
{socialTx("填写邮箱后继续")}
|
||||
{priceSyncing
|
||||
? socialTx("正在同步后台最新价格…")
|
||||
: isFree
|
||||
? socialTx("填写邮箱后直接完善资料,当前无需付款。")
|
||||
: socialTx("填写邮箱后继续支付")}
|
||||
</p>
|
||||
|
||||
<label className="social-join-field">
|
||||
@ -159,10 +219,10 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary social-join-submit"
|
||||
disabled={busy}
|
||||
disabled={busy || priceSyncing || !priceKnown}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{busy ? socialTx("正在前往支付…") : socialTx("确认")}
|
||||
{busy ? busyLabel : ctaLabel}
|
||||
<ArrowUpRight size={17} />
|
||||
</button>
|
||||
<p className="social-join-privacy">
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { isJoinPaid } from "@social/lib/joinFlow";
|
||||
@ -10,7 +9,7 @@ import {
|
||||
pathNeedsLiveness,
|
||||
subscribeLivenessState,
|
||||
} from "@social/lib/livenessGate";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
/** Soft invite until paid + profile + selfie — plain language for users. */
|
||||
@ -35,9 +34,13 @@ export default function LivenessGateBanner() {
|
||||
<strong>{socialTx("差一步就能畅玩")}</strong>
|
||||
<p>{body}</p>
|
||||
</div>
|
||||
<Link className="social-btn coral" href={socialPath("/join")}>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral"
|
||||
onClick={() => openSocialJoinModal({ reason: "gate" })}
|
||||
>
|
||||
{socialTx("去完善")}
|
||||
</Link>
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@ -27,6 +27,7 @@ import { socialApi } from "@social/lib/api";
|
||||
import { SOCIAL_CITIES } from "@social/lib/cities";
|
||||
import type { SocialMapCity } from "@social/lib/geoTypes";
|
||||
import { buildMapPersonPins, type MapPersonPin } from "@social/lib/mapPins";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import {
|
||||
@ -191,9 +192,13 @@ function MapClientInner() {
|
||||
<SiteShell title={socialTx("地图")} immersive>
|
||||
<div className="container" style={{ padding: "2rem 1rem" }}>
|
||||
<p>{socialTx(trialPaywallHint("mapOpens"))}</p>
|
||||
<Link className="social-btn coral" href={socialPath("/join")}>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral"
|
||||
onClick={() => openSocialJoinModal({ reason: "gate" })}
|
||||
>
|
||||
{socialTx("加入社区")}
|
||||
</Link>
|
||||
</button>
|
||||
</div>
|
||||
</SiteShell>
|
||||
);
|
||||
|
||||
@ -2,15 +2,16 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { MIROTALK_URL, SEED_CHANNELS } from "@social/lib/seed";
|
||||
import { loadJson, saveJson } from "@social/lib/storage";
|
||||
import { saveJson } from "@social/lib/storage";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { resolveSocialCatalog } from "@social/lib/resolveCatalog";
|
||||
import { useSocialChat } from "@social/lib/useSocialChat";
|
||||
import { ensureGuestNick } from "@social/lib/guestNick";
|
||||
import { getGuestId, socialApi } from "@social/lib/api";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { SocialMobileDock } from "./SocialNavigation";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
import { useAudienceRoster } from "@social/lib/useAudienceRoster";
|
||||
import { EmptyState } from "./SocialUI";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import {
|
||||
@ -66,8 +67,8 @@ function defaultLayout(): Layout {
|
||||
}
|
||||
|
||||
export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const router = useRouter();
|
||||
const config = useSocialConfig();
|
||||
const roster = useAudienceRoster();
|
||||
const meetups = useMemo(
|
||||
() => resolveSocialCatalog(config.copy.socialCatalogs).meetups,
|
||||
[config.copy.socialCatalogs],
|
||||
@ -76,7 +77,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
meetups.find((m) => m.id === meetupId) ||
|
||||
{
|
||||
id: meetupId,
|
||||
title: "开视频见面",
|
||||
title: "语音厅",
|
||||
city: "Online",
|
||||
date: "",
|
||||
time: "",
|
||||
@ -87,38 +88,196 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const channel =
|
||||
SEED_CHANNELS.find((c) => c.id === meetup.channelId) || SEED_CHANNELS[0];
|
||||
const chat = useSocialChat(channel.id);
|
||||
const roomId = meetup.mirotalkRoom || meetupId;
|
||||
const enteredAtRef = useRef(
|
||||
typeof performance !== "undefined" ? Date.now() : 0,
|
||||
);
|
||||
|
||||
const [layout, setLayout] = useState<Layout>("split");
|
||||
const [joinName, setJoinName] = useState("");
|
||||
const [videoReady, setVideoReady] = useState(false);
|
||||
// 首屏就带花名,iframe 可立刻挂上(秒开)
|
||||
const [joinName, setJoinName] = useState(() =>
|
||||
typeof window !== "undefined" ? ensureGuestNick() : "",
|
||||
);
|
||||
const [videoReady, setVideoReady] = useState(
|
||||
() => typeof window !== "undefined",
|
||||
);
|
||||
const [iframeLoading, setIframeLoading] = useState(true);
|
||||
const [frameKey, setFrameKey] = useState(0);
|
||||
const [loadSlow, setLoadSlow] = useState(false);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const silentRecRef = useRef<SilentRecorderHandle | null>(null);
|
||||
const sessionIdRef = useRef("");
|
||||
const startedRef = useRef(false);
|
||||
const endedRef = useRef(false);
|
||||
|
||||
const videoSrc = useMemo(
|
||||
() => joinUrl(meetup.mirotalkRoom, joinName || "游民"),
|
||||
() => joinUrl(meetup.mirotalkRoom, joinName || ensureGuestNick()),
|
||||
[meetup.mirotalkRoom, joinName],
|
||||
);
|
||||
|
||||
// 防止厅内跳到门户首页(同域 /join 挂断曾会变成首页嵌套)
|
||||
const guardIframeHome = useCallback(() => {
|
||||
const frame = iframeRef.current;
|
||||
if (!frame) return;
|
||||
try {
|
||||
const href = frame.contentWindow?.location?.href || "";
|
||||
if (!href || href === "about:blank") return;
|
||||
const isJoin = href.includes("/join");
|
||||
const isPortalHome =
|
||||
/nomadro\.(com|cn)\/?(\?|$)/.test(href) ||
|
||||
href.includes("/social") && !href.includes("/join");
|
||||
if (!isJoin && isPortalHome) {
|
||||
frame.src = videoSrc;
|
||||
}
|
||||
} catch {
|
||||
/* cross-origin mirotalk.* — 预期,无法读 href */
|
||||
}
|
||||
}, [videoSrc]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
setLayout(defaultLayout());
|
||||
}, []);
|
||||
|
||||
/** 回去看场次 / 离开视频 / 关页 = 结束本场:立刻「上传中」并停录 */
|
||||
const endRoomSession = useCallback(
|
||||
(reason = "leave") => {
|
||||
if (endedRef.current) return;
|
||||
endedRef.current = true;
|
||||
const sid =
|
||||
silentRecRef.current?.sessionId &&
|
||||
silentRecRef.current.sessionId !== "locking"
|
||||
? silentRecRef.current.sessionId
|
||||
: sessionIdRef.current;
|
||||
const durationSec = Math.max(
|
||||
0,
|
||||
Math.floor((Date.now() - (enteredAtRef.current || Date.now())) / 1000),
|
||||
);
|
||||
if (sid) {
|
||||
try {
|
||||
void fetch("/api/social/v1/room-archives/events", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sessionId: sid,
|
||||
channelId: channel.id,
|
||||
roomId,
|
||||
status: "uploading",
|
||||
name: `room-${roomId}-leave.webm`,
|
||||
error: reason,
|
||||
durationSec,
|
||||
startedAt: new Date(enteredAtRef.current || Date.now()).toISOString(),
|
||||
}),
|
||||
cache: "no-store",
|
||||
keepalive: true,
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
try {
|
||||
silentRecRef.current?.stop();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
silentRecRef.current = null;
|
||||
},
|
||||
[channel.id, roomId],
|
||||
);
|
||||
|
||||
const startSilentInBackground = useCallback(() => {
|
||||
if (silentRecRef.current) return;
|
||||
const lock: SilentRecorderHandle = {
|
||||
sessionId: sessionIdRef.current || "locking",
|
||||
stop: () => undefined,
|
||||
};
|
||||
silentRecRef.current = lock;
|
||||
void startSilentRoomArchive({
|
||||
channelId: channel.id,
|
||||
roomId,
|
||||
sessionId: sessionIdRef.current || undefined,
|
||||
}).then((handle) => {
|
||||
if (silentRecRef.current === lock) {
|
||||
silentRecRef.current = handle;
|
||||
if (handle?.sessionId) sessionIdRef.current = handle.sessionId;
|
||||
} else {
|
||||
handle?.stop();
|
||||
}
|
||||
});
|
||||
}, [channel.id, roomId]);
|
||||
|
||||
const startVideo = useCallback(
|
||||
(forceReload = false) => {
|
||||
const name = ensureGuestNick();
|
||||
chat.setNick(name);
|
||||
saveJson("nick", name);
|
||||
warmMirotalkOrigin();
|
||||
setJoinName(name);
|
||||
setIframeLoading(true);
|
||||
setLoadSlow(false);
|
||||
|
||||
// 先开厅(iframe),静默录像后台并行 —— 绝不能等 getUserMedia
|
||||
if (forceReload && videoReady) {
|
||||
setFrameKey((key) => key + 1);
|
||||
} else {
|
||||
setVideoReady(true);
|
||||
}
|
||||
startSilentInBackground();
|
||||
},
|
||||
[chat.setNick, videoReady, startSilentInBackground],
|
||||
);
|
||||
|
||||
// 进入页面直接开视频/语音,不要二次点「进入聊聊」
|
||||
useEffect(() => {
|
||||
const name = (loadJson("nick", "游民") || "游民").trim() || "游民";
|
||||
if (startedRef.current) return;
|
||||
startedRef.current = true;
|
||||
endedRef.current = false;
|
||||
enteredAtRef.current = Date.now();
|
||||
warmMirotalkOrigin();
|
||||
const name = ensureGuestNick();
|
||||
chat.setNick(name);
|
||||
saveJson("nick", name);
|
||||
setJoinName(name);
|
||||
setVideoReady(true);
|
||||
// 进厅埋点抢先落库(不依赖摄像头),后台立刻有「待上传」
|
||||
const sid = `arc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
||||
sessionIdRef.current = sid;
|
||||
void socialApi
|
||||
.roomArchiveEvent({
|
||||
sessionId: sid,
|
||||
channelId: channel.id,
|
||||
roomId,
|
||||
status: "pending",
|
||||
name: `room-${roomId}-pending.webm`,
|
||||
startedAt: new Date().toISOString(),
|
||||
durationSec: 0,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
startSilentInBackground();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount once
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!videoReady || !iframeLoading) return;
|
||||
const timer = setTimeout(() => setLoadSlow(true), 15000);
|
||||
return () => clearTimeout(timer);
|
||||
// overlay 最多挡 1.2s,超时直接让厅可见(秒开)
|
||||
const reveal = setTimeout(() => setIframeLoading(false), 1200);
|
||||
const slow = setTimeout(() => setLoadSlow(true), 8000);
|
||||
return () => {
|
||||
clearTimeout(reveal);
|
||||
clearTimeout(slow);
|
||||
};
|
||||
}, [videoReady, iframeLoading, frameKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!videoReady) return;
|
||||
const tick = window.setInterval(guardIframeHome, 1500);
|
||||
return () => window.clearInterval(tick);
|
||||
}, [videoReady, guardIframeHome, frameKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const thread = bottomRef.current?.parentElement;
|
||||
if (thread) thread.scrollTop = thread.scrollHeight;
|
||||
@ -126,37 +285,9 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
silentRecRef.current?.stop();
|
||||
silentRecRef.current = null;
|
||||
endRoomSession("unmount");
|
||||
};
|
||||
}, []);
|
||||
|
||||
/** 始终页内 iframe;绝不 location.assign 到 mirotalk.* 二级域 */
|
||||
const startVideo = useCallback(
|
||||
(forceReload = false) => {
|
||||
const name = chat.nick.trim() || "游民";
|
||||
saveJson("nick", name);
|
||||
warmMirotalkOrigin();
|
||||
setJoinName(name);
|
||||
setIframeLoading(true);
|
||||
setLoadSlow(false);
|
||||
if (forceReload && videoReady) {
|
||||
setFrameKey((key) => key + 1);
|
||||
} else {
|
||||
setVideoReady(true);
|
||||
}
|
||||
// Silent archive after browser media permission — no REC UI
|
||||
if (!silentRecRef.current) {
|
||||
void startSilentRoomArchive({
|
||||
channelId: channel.id,
|
||||
roomId: meetup.mirotalkRoom || meetupId,
|
||||
}).then((handle) => {
|
||||
if (handle) silentRecRef.current = handle;
|
||||
});
|
||||
}
|
||||
},
|
||||
[chat.nick, videoReady, channel.id, meetup.mirotalkRoom, meetupId],
|
||||
);
|
||||
}, [endRoomSession]);
|
||||
|
||||
const send = async () => {
|
||||
if (!chat.draft.trim() || chat.sending) return;
|
||||
@ -183,7 +314,15 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
<div className="social-root social-live-root social-skin social-meetup-live">
|
||||
<header className="social-live-bar">
|
||||
<div className="social-live-bar-main">
|
||||
<Link href={socialPath("/meetup")} className="social-nav-back">
|
||||
<Link
|
||||
href={socialPath("/meetup")}
|
||||
className="social-nav-back"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
endRoomSession("back");
|
||||
router.push(socialPath("/meetup"));
|
||||
}}
|
||||
>
|
||||
← 回去看场次
|
||||
</Link>
|
||||
<div>
|
||||
@ -200,9 +339,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
? "聊天已接通"
|
||||
: chat.status === "offline"
|
||||
? "聊天暂时断了"
|
||||
: chat.status === "preview"
|
||||
? "先看看示例"
|
||||
: "正在连上…"}
|
||||
: "正在连上…"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="social-live-bar-tools">
|
||||
@ -212,6 +349,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
type="button"
|
||||
className="social-btn"
|
||||
onClick={() => {
|
||||
endRoomSession("leave-video");
|
||||
setVideoReady(false);
|
||||
setLoadSlow(false);
|
||||
}}
|
||||
@ -227,28 +365,6 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<label className="social-live-nick">
|
||||
<span className="social-muted">{socialTx("昵称")}</span>
|
||||
<input
|
||||
value={chat.nick}
|
||||
onChange={(e) => chat.setNick(e.target.value)}
|
||||
onBlur={() => saveJson("nick", chat.nick.trim() || "游民")}
|
||||
maxLength={24}
|
||||
aria-label={socialTx("显示名")}
|
||||
/>
|
||||
</label>
|
||||
{videoReady &&
|
||||
chat.nick.trim() &&
|
||||
chat.nick.trim() !== joinName ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn"
|
||||
onClick={() => startVideo(true)}
|
||||
title={socialTx("用新名字重新进入视频")}
|
||||
>
|
||||
{socialTx("换名字重进")}
|
||||
</button>
|
||||
) : null}
|
||||
<div className="social-live-tabs" role="tablist" aria-label={socialTx("怎么看")}>
|
||||
{(["split", "video", "chat"] as const).map((m) => (
|
||||
<button
|
||||
@ -289,38 +405,17 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
|
||||
<div className={`social-live-stage layout-${layout}`}>
|
||||
{(layout === "split" || layout === "video") && (
|
||||
<section className="social-live-video" aria-label={socialTx("开视频")}>
|
||||
<section className="social-live-video" aria-label={socialTx("语音厅")}>
|
||||
{!videoReady ? (
|
||||
<div className="social-live-gate">
|
||||
<div className="social-live-radar" aria-hidden>
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
<span>LIVE</span>
|
||||
</div>
|
||||
<h2>{socialTx("群组 · 语音视频")}</h2>
|
||||
<p>
|
||||
进房默认开麦、开摄像头;不想露脸可进房后再关。本页内进入,不会跳到别的域名。
|
||||
</p>
|
||||
<div className="social-meetup-faces social-live-faces" aria-hidden>
|
||||
{roster
|
||||
.filter((m) => m.online)
|
||||
.slice(0, 5)
|
||||
.map((m) => (
|
||||
<SocialAvatar key={m.id} src={m.avatar} size={28} lazy />
|
||||
))}
|
||||
<em>{socialTx("示例成员 · 可先进入了解")}</em>
|
||||
</div>
|
||||
<p>{socialTx("接通中…")}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn primary"
|
||||
onClick={() => startVideo()}
|
||||
>
|
||||
{socialTx("进入聊聊")}
|
||||
{socialTx("重试连接")}
|
||||
</button>
|
||||
<p className="social-muted">
|
||||
「想参加」还不等于已经约好 · 随时可以离开回去看别的场
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="social-live-frame-wrap">
|
||||
@ -350,15 +445,15 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
)}
|
||||
<iframe
|
||||
key={frameKey}
|
||||
title={`${meetup.title} video`}
|
||||
ref={iframeRef}
|
||||
title={meetup.title}
|
||||
src={videoSrc}
|
||||
allow="camera; microphone; display-capture; autoplay; fullscreen"
|
||||
allowFullScreen
|
||||
className="social-live-iframe"
|
||||
allow="camera; microphone; display-capture; autoplay; fullscreen; clipboard-write"
|
||||
referrerPolicy="no-referrer-when-downgrade"
|
||||
loading="eager"
|
||||
onLoad={() => {
|
||||
setIframeLoading(false);
|
||||
setLoadSlow(false);
|
||||
guardIframeHome();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@ -367,69 +462,45 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
)}
|
||||
|
||||
{(layout === "split" || layout === "chat") && (
|
||||
<section className="social-live-chat" aria-label={socialTx("文字频道")}>
|
||||
<div className="social-live-chat-head">
|
||||
<strong>{channel.name}</strong>
|
||||
<span className="social-muted">{channel.topic}</span>
|
||||
</div>
|
||||
<div className="social-chat-thread social-live-thread">
|
||||
{!chat.messages.length ? (
|
||||
<div className="social-live-empty">
|
||||
<strong>{socialTx("文字频道还很安静")}</strong>
|
||||
<p>{socialTx("先打个招呼,或问问今晚谁在听。")}</p>
|
||||
</div>
|
||||
) : null}
|
||||
<section className="social-live-chat" aria-label={socialTx("场次聊天")}>
|
||||
<div className="social-live-thread">
|
||||
{chat.messages.map((m) => (
|
||||
<div
|
||||
<article
|
||||
key={m.id}
|
||||
className={`social-bubble${m.mine ? " mine" : ""}`}
|
||||
className={`social-message${m.mine ? " mine" : ""}`}
|
||||
>
|
||||
<header>
|
||||
{m.author}
|
||||
<time suppressHydrationWarning>
|
||||
{new Date(m.at).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</time>
|
||||
{m.delivery === "demo" ? <span>{socialTx("示例")}</span> : null}
|
||||
{m.delivery === "local" ? (
|
||||
<span>{socialTx("先留在你这边")}</span>
|
||||
) : null}
|
||||
</header>
|
||||
<p>{m.text}</p>
|
||||
</div>
|
||||
<div className="social-message-body">
|
||||
<header>
|
||||
<strong>{m.author}</strong>
|
||||
</header>
|
||||
<p>{m.text}</p>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
<div className="social-compose">
|
||||
<input
|
||||
<form
|
||||
className="social-chat-composer"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
value={chat.draft}
|
||||
onChange={(e) => chat.setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (
|
||||
e.key === "Enter" &&
|
||||
!e.shiftKey &&
|
||||
!e.nativeEvent.isComposing &&
|
||||
e.keyCode !== 229
|
||||
) {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
}
|
||||
}}
|
||||
placeholder={socialTx("发到活动文字频道…")}
|
||||
aria-label={socialTx("消息内容")}
|
||||
placeholder={socialTx("说点什么…")}
|
||||
rows={2}
|
||||
maxLength={2000}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn primary"
|
||||
disabled={!chat.draft.trim() || chat.sending}
|
||||
onClick={() => void send()}
|
||||
type="submit"
|
||||
disabled={chat.sending || !chat.draft.trim()}
|
||||
>
|
||||
{socialTx("发送")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -121,7 +121,7 @@ function PeopleDirectory({
|
||||
<SiteShell title={socialTx("想见的人")}>
|
||||
<PageIntro title={socialTx("想见的人")} accent="认识新朋友">
|
||||
<div className="social-actions">
|
||||
<DemoBadge>{list.length} 位 · 示例介绍,方便先逛逛</DemoBadge>
|
||||
<DemoBadge>{list.length} 位</DemoBadge>
|
||||
<Link className="social-btn social-btn-ghost" href={socialPath("/map")}>
|
||||
地图
|
||||
</Link>
|
||||
|
||||
@ -122,7 +122,6 @@ export default function PeopleProfileClient({ id }: { id: string }) {
|
||||
<Link href={socialPath("/people")} className="social-btn">
|
||||
<ArrowLeft size={15} /> {socialTx("回去看看大家")}
|
||||
</Link>
|
||||
<DemoBadge>{socialTx("示例介绍 · 方便先逛逛")}</DemoBadge>
|
||||
</div>
|
||||
|
||||
<header className="social-profile-hero">
|
||||
|
||||
@ -1,37 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense, useMemo, useState } from "react";
|
||||
import { Suspense, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import SiteShell from "./SiteShell";
|
||||
import CafeDirectory from "./CafeDirectory";
|
||||
import { PageIntro, SearchField, DemoBadge } from "./SocialUI";
|
||||
import { SOCIAL_CITIES, CITY_FILTER_TAGS } from "@social/lib/cities";
|
||||
import { createCitySearchDebouncer, type CitySearchHit } from "@social/lib/photon";
|
||||
import { SOCIAL_CITIES } from "@social/lib/cities";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
const debouncer = createCitySearchDebouncer(300);
|
||||
|
||||
type Tab = "cities" | "cafes";
|
||||
|
||||
function PlacesHub() {
|
||||
const params = useSearchParams();
|
||||
const router = useRouter();
|
||||
const tabParam = params.get("tab");
|
||||
const tab: Tab =
|
||||
tabParam === "cafes" || tabParam === "coffee" || tabParam === "meetup"
|
||||
? "cafes"
|
||||
: "cities";
|
||||
const cityParam = (params.get("city") || "").trim();
|
||||
const [query, setQuery] = useState("");
|
||||
const [tag, setTag] = useState("全部");
|
||||
const [remote, setRemote] = useState<CitySearchHit[]>([]);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [hotOnly, setHotOnly] = useState(false);
|
||||
|
||||
const setTab = (next: Tab) => {
|
||||
// Legacy ?tab=cafes — drop it; one page, no tabs.
|
||||
useEffect(() => {
|
||||
if (!params.get("tab")) return;
|
||||
const sp = new URLSearchParams(params.toString());
|
||||
if (next === "cafes") sp.set("tab", "cafes");
|
||||
else sp.delete("tab");
|
||||
sp.delete("tab");
|
||||
const q = sp.toString();
|
||||
router.replace(q ? `${socialPath("/places")}?${q}` : socialPath("/places"), {
|
||||
scroll: false,
|
||||
});
|
||||
}, [params, router]);
|
||||
|
||||
const setCity = (name: string | null) => {
|
||||
const sp = new URLSearchParams(params.toString());
|
||||
sp.delete("tab");
|
||||
if (name) sp.set("city", name);
|
||||
else sp.delete("city");
|
||||
const q = sp.toString();
|
||||
router.replace(q ? `${socialPath("/places")}?${q}` : socialPath("/places"), {
|
||||
scroll: false,
|
||||
@ -41,159 +41,172 @@ function PlacesHub() {
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return SOCIAL_CITIES.filter((c) => {
|
||||
const hay = `${c.name} ${c.country} ${c.vibe} ${c.tags.join(" ")}`.toLowerCase();
|
||||
const tagOk = tag === "全部" || (tag === "热门" ? c.hot : c.tags.includes(tag));
|
||||
return tagOk && (!q || hay.includes(q));
|
||||
if (hotOnly && !c.hot) return false;
|
||||
if (!q) return true;
|
||||
return `${c.name} ${c.country} ${c.vibe} ${c.tags.join(" ")}`
|
||||
.toLowerCase()
|
||||
.includes(q);
|
||||
});
|
||||
}, [query, tag]);
|
||||
}, [query, hotOnly]);
|
||||
|
||||
const onQuery = (v: string) => {
|
||||
setQuery(v);
|
||||
if (v.trim().length < 2) {
|
||||
setRemote([]);
|
||||
setSearching(false);
|
||||
debouncer.cancel();
|
||||
return;
|
||||
}
|
||||
setSearching(true);
|
||||
debouncer.search(
|
||||
v,
|
||||
(items) => {
|
||||
setRemote(items);
|
||||
setSearching(false);
|
||||
},
|
||||
() => setSearching(false),
|
||||
);
|
||||
};
|
||||
const activeCity =
|
||||
SOCIAL_CITIES.find(
|
||||
(c) =>
|
||||
cityParam &&
|
||||
(c.name === cityParam ||
|
||||
c.name.includes(cityParam) ||
|
||||
cityParam.includes(c.name)),
|
||||
) || null;
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("城市")}>
|
||||
<PageIntro title={socialTx("城市")} accent="旅居 · 见面 · 同城">
|
||||
<div className="social-actions">
|
||||
<DemoBadge>
|
||||
{tab === "cities" ? `${filtered.length} 座热门` : "咖啡馆见面点"}
|
||||
</DemoBadge>
|
||||
<Link className="social-btn social-btn-ghost" href={socialPath("/map")}>
|
||||
打开地图
|
||||
<div className="sp-hub">
|
||||
<header className="sp-cafe-head">
|
||||
<div>
|
||||
<p className="sp-eyebrow">{socialTx("线下见面")}</p>
|
||||
<h1>
|
||||
Nomadro <span>{socialTx("城市")}</span>
|
||||
</h1>
|
||||
</div>
|
||||
<Link className="sp-btn sp-btn-primary" href={socialPath("/coffeechat")}>
|
||||
{socialTx("线下咖啡聊")}
|
||||
</Link>
|
||||
</div>
|
||||
</PageIntro>
|
||||
</header>
|
||||
|
||||
<div className="social-places-tabs reveal" role="tablist" aria-label="城市功能">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === "cities"}
|
||||
className={tab === "cities" ? "active" : ""}
|
||||
onClick={() => setTab("cities")}
|
||||
>
|
||||
旅居城市
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === "cafes"}
|
||||
className={tab === "cafes" ? "active" : ""}
|
||||
onClick={() => setTab("cafes")}
|
||||
>
|
||||
咖啡馆见面
|
||||
</button>
|
||||
</div>
|
||||
<p className="sp-lead sp-lead--tight">
|
||||
{socialTx("先挑一座城,再约咖啡馆线下见面。简单两步。")}
|
||||
</p>
|
||||
|
||||
{tab === "cafes" ? (
|
||||
<Suspense fallback={<div className="social-status">加载咖啡馆…</div>}>
|
||||
<CafeDirectory embedded />
|
||||
</Suspense>
|
||||
) : (
|
||||
<>
|
||||
<div className="social-toolbar reveal">
|
||||
<SearchField
|
||||
<div className="sp-toolbar">
|
||||
<label className="sp-search">
|
||||
<span className="sr-only">{socialTx("搜索")}</span>
|
||||
<input
|
||||
value={query}
|
||||
onChange={onQuery}
|
||||
label={socialTx("搜索")}
|
||||
placeholder="城市 / 国家 / 氛围"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={socialTx("搜城市 / 国家")}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<div className="social-filters" aria-label="标签">
|
||||
{CITY_FILTER_TAGS.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={tag === t ? "active" : ""}
|
||||
aria-pressed={tag === t}
|
||||
onClick={() => setTag(t)}
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={`sp-hot${hotOnly ? " is-on" : ""}`}
|
||||
aria-pressed={hotOnly}
|
||||
onClick={() => setHotOnly((v) => !v)}
|
||||
>
|
||||
{socialTx("只看热门")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="sp-cafe-city-rail" role="listbox" aria-label={socialTx("城市")}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={!activeCity}
|
||||
className={!activeCity ? "is-on" : ""}
|
||||
onClick={() => setCity(null)}
|
||||
>
|
||||
{socialTx("全部")}
|
||||
</button>
|
||||
{filtered.map((city) => (
|
||||
<button
|
||||
key={city.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={activeCity?.id === city.id}
|
||||
className={activeCity?.id === city.id ? "is-on" : ""}
|
||||
onClick={() => setCity(city.name)}
|
||||
>
|
||||
<span aria-hidden>{city.emoji}</span>
|
||||
{city.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeCity ? (
|
||||
<div
|
||||
className="sp-cafe-city-banner"
|
||||
style={
|
||||
activeCity.cover
|
||||
? { backgroundImage: `url(${activeCity.cover})` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div className="sp-cafe-city-banner-veil" aria-hidden />
|
||||
<div className="sp-cafe-city-banner-copy">
|
||||
<p>
|
||||
{activeCity.emoji} {activeCity.country}
|
||||
{activeCity.hot ? ` · ${socialTx("热门")}` : ""}
|
||||
</p>
|
||||
<strong>{activeCity.name}</strong>
|
||||
<em>{activeCity.vibe}</em>
|
||||
<div className="sp-cafe-city-banner-acts">
|
||||
<Link
|
||||
className="sp-btn sp-btn-primary"
|
||||
href={socialPath(`/places/${activeCity.id}`)}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
{socialTx("看这座城")}
|
||||
</Link>
|
||||
<Link className="sp-btn" href={socialPath("/map")}>
|
||||
{socialTx("打开地图")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{remote.length > 0 || searching ? (
|
||||
<section className="social-places-remote reveal">
|
||||
<h2>{searching ? "搜索中…" : "搜索结果"}</h2>
|
||||
<ul className="social-places-remote-list">
|
||||
{remote.map((hit) => (
|
||||
<li key={hit.id}>
|
||||
{hit.id.startsWith("photon:") ? (
|
||||
<div className="social-places-remote-row">
|
||||
<strong>
|
||||
{hit.name}
|
||||
<span>
|
||||
{[hit.state, hit.country].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</strong>
|
||||
<Link
|
||||
className="social-btn social-btn-ghost"
|
||||
href={socialPath(
|
||||
`/map?lat=${hit.lat}&lng=${hit.lng}&q=${encodeURIComponent(hit.name)}`,
|
||||
)}
|
||||
>
|
||||
看地图
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<Link href={socialPath(`/places/${hit.id}`)}>
|
||||
<strong>
|
||||
{hit.emoji} {hit.name}
|
||||
<span>{hit.country}</span>
|
||||
</strong>
|
||||
<em>{hit.memberCount} 位</em>
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<div className="social-city-grid reveal">
|
||||
) : (
|
||||
<div className="sp-grid">
|
||||
{filtered.map((city) => (
|
||||
<Link
|
||||
<button
|
||||
key={city.id}
|
||||
href={socialPath(`/places/${city.id}`)}
|
||||
className="social-city-card"
|
||||
type="button"
|
||||
className="sp-card"
|
||||
style={
|
||||
city.cover
|
||||
? { backgroundImage: `url(${city.cover})` }
|
||||
: undefined
|
||||
}
|
||||
onClick={() => setCity(city.name)}
|
||||
>
|
||||
<span className="social-city-card-emoji">{city.emoji}</span>
|
||||
<strong>
|
||||
{city.name}
|
||||
<span>{city.country}</span>
|
||||
</strong>
|
||||
<p>{city.vibe}</p>
|
||||
<em>
|
||||
{city.members} 位 · {city.costHint}
|
||||
</em>
|
||||
</Link>
|
||||
<span className="sp-card-veil" aria-hidden />
|
||||
<span className="sp-card-body">
|
||||
<em>
|
||||
{city.emoji} {city.country}
|
||||
{city.hot ? ` · ${socialTx("热门")}` : ""}
|
||||
</em>
|
||||
<strong>{city.name}</strong>
|
||||
<p>{city.vibe}</p>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
)}
|
||||
|
||||
{!filtered.length ? (
|
||||
<p className="sp-muted">{socialTx("没有匹配的城市,换个关键词试试。")}</p>
|
||||
) : null}
|
||||
|
||||
<section className="sp-places-cafes" aria-label={socialTx("咖啡馆")}>
|
||||
<div className="sp-places-cafes-head">
|
||||
<h2>
|
||||
{activeCity
|
||||
? `${activeCity.name} · ${socialTx("咖啡馆")}`
|
||||
: socialTx("咖啡馆见面点")}
|
||||
</h2>
|
||||
<Link className="sp-link" href={socialPath("/map")}>
|
||||
{socialTx("打开地图")}
|
||||
</Link>
|
||||
</div>
|
||||
<Suspense fallback={<p className="sp-muted">{socialTx("加载咖啡馆…")}</p>}>
|
||||
<CafeDirectory embedded hideCityRail />
|
||||
</Suspense>
|
||||
</section>
|
||||
</div>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PlacesClient() {
|
||||
return (
|
||||
<Suspense fallback={<div className="social-status">加载城市…</div>}>
|
||||
<Suspense fallback={<p className="sp-muted">{socialTx("加载城市…")}</p>}>
|
||||
<PlacesHub />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
@ -28,6 +28,10 @@ import SocialBrandLogo from "./SocialBrandLogo";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
import NavAccountMenu from "./NavAccountMenu";
|
||||
import TrialNudgeBanner from "./TrialNudgeBanner";
|
||||
import {
|
||||
consumeOpenJoinModalFlag,
|
||||
subscribeSocialJoinModal,
|
||||
} from "@social/lib/joinModal";
|
||||
|
||||
export default function SiteShell({
|
||||
children,
|
||||
@ -68,6 +72,30 @@ export default function SiteShell({
|
||||
applySocialSkin(SOCIAL_SKIN_DEFAULT);
|
||||
}, []);
|
||||
|
||||
const openJoin = () => {
|
||||
setLoginOpen(true);
|
||||
onJoin?.();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeSocialJoinModal(() => setLoginOpen(true));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (consumeOpenJoinModalFlag()) setLoginOpen(true);
|
||||
}, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const q = new URLSearchParams(window.location.search);
|
||||
if (q.get("join") === "1" || q.get("social_join") === "1") {
|
||||
setLoginOpen(true);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
|
||||
useRevealMotion(home ? ".social-home" : ".social-workspace", [
|
||||
home,
|
||||
pathname,
|
||||
@ -136,25 +164,17 @@ export default function SiteShell({
|
||||
setOpenGroup(null);
|
||||
};
|
||||
|
||||
const joinBtn = onJoin ? (
|
||||
const joinBtn = (
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral social-nav-join"
|
||||
onClick={() => {
|
||||
closeMenus();
|
||||
onJoin();
|
||||
openJoin();
|
||||
}}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</button>
|
||||
) : (
|
||||
<Link
|
||||
href={socialPath("/join")}
|
||||
className="social-btn coral social-nav-join"
|
||||
onClick={closeMenus}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</Link>
|
||||
);
|
||||
|
||||
const nav = (
|
||||
@ -230,7 +250,7 @@ export default function SiteShell({
|
||||
className="social-btn social-nav-login"
|
||||
onClick={() => {
|
||||
closeMenus();
|
||||
setLoginOpen(true);
|
||||
openJoin();
|
||||
}}
|
||||
>
|
||||
{socialTx("登录")}
|
||||
@ -252,7 +272,7 @@ export default function SiteShell({
|
||||
className="social-btn social-nav-login"
|
||||
onClick={() => {
|
||||
closeMenus();
|
||||
setLoginOpen(true);
|
||||
openJoin();
|
||||
}}
|
||||
>
|
||||
{socialTx("登录")}
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
xProfileUrl,
|
||||
} from "~/components/social-follow";
|
||||
import { trackFollow } from "~/lib/analytics/track";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { isSocialHomePath, socialPath } from "@social/lib/socialPath";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
|
||||
@ -91,7 +92,13 @@ export function SocialFooter() {
|
||||
>
|
||||
{zh ? `关注 X ${formatXHandle()}` : `Follow ${formatXHandle()}`}
|
||||
</a>
|
||||
<Link href={socialPath("/join")}>{t.joinCommunity}</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="social-footer-link"
|
||||
onClick={() => openSocialJoinModal({ reason: "cta" })}
|
||||
>
|
||||
{t.joinCommunity}
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
|
||||
@ -19,6 +20,19 @@ export default function SocialQuickRail() {
|
||||
<nav className="social-quick-rail" aria-label={t.railAria}>
|
||||
<div ref={track} className="social-quick-rail-track">
|
||||
{t.rail.map((item) => {
|
||||
if (item.href === "/join") {
|
||||
return (
|
||||
<button
|
||||
key={item.href}
|
||||
type="button"
|
||||
className="social-quick-chip"
|
||||
onClick={() => openSocialJoinModal({ reason: "cta" })}
|
||||
>
|
||||
<span aria-hidden>{item.emoji}</span>
|
||||
{item.label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const href = socialPath(item.href);
|
||||
const active =
|
||||
item.href === "/ebook"
|
||||
|
||||
@ -103,7 +103,7 @@ export function DemoBadge({
|
||||
}) {
|
||||
return (
|
||||
<span className={["social-demo-badge", className].filter(Boolean).join(" ")}>
|
||||
{children ?? socialTx("示例介绍,方便先逛逛")}
|
||||
{children ?? socialTx("游民社区")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
import {
|
||||
@ -9,7 +8,7 @@ import {
|
||||
pathNeedsLiveness,
|
||||
subscribeLivenessState,
|
||||
} from "@social/lib/livenessGate";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import { resolveTrialLimits } from "@social/lib/socialTrial";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
@ -35,9 +34,13 @@ export default function TrialNudgeBanner() {
|
||||
<strong>{socialTx("先随便看看")}</strong>
|
||||
<p>{socialTx("聊几句、认识几个人都可以。想更深入,加入社区就行。")}</p>
|
||||
</div>
|
||||
<Link className="social-btn coral" href={socialPath("/join")}>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral"
|
||||
onClick={() => openSocialJoinModal({ reason: "gate" })}
|
||||
>
|
||||
{socialTx("加入社区")}
|
||||
</Link>
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import Link from "next/link";
|
||||
import { useMemo, useState } from "react";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { SocialFooter } from "@social/components/SocialNavigation";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import type { BlogAdSenseConfig, BlogPost, BlogPostMeta } from "@social/lib/blog/types";
|
||||
import { ADSENSE_MIN_WORDS } from "@social/lib/blog/types";
|
||||
@ -148,9 +149,13 @@ export default function BlogPostClient({
|
||||
<h2>Meet people on the road</h2>
|
||||
<p>Reading helps. Saying hello helps more.</p>
|
||||
<div className="sblog-cta-row">
|
||||
<Link href={socialPath("/join")} className="sblog-cta-primary">
|
||||
<button
|
||||
type="button"
|
||||
className="sblog-cta-primary"
|
||||
onClick={() => openSocialJoinModal({ reason: "cta" })}
|
||||
>
|
||||
Join community
|
||||
</Link>
|
||||
</button>
|
||||
<Link href={socialPath("/people")} className="sblog-cta-secondary">
|
||||
Browse people
|
||||
</Link>
|
||||
|
||||
@ -14,6 +14,22 @@ export function getGuestId(): string {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** 换邮箱必须换 guest,否则花名册/核验媒体会串到上一位。 */
|
||||
export function resetGuestId(): string {
|
||||
const id = uid("guest");
|
||||
saveJson(GUEST_KEY, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function socialEmail(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
try {
|
||||
return (localStorage.getItem("userEmail") || "").trim().toLowerCase();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
const _memTtl = new Map<string, { at: number; data: unknown }>();
|
||||
|
||||
async function req<T>(
|
||||
@ -27,8 +43,10 @@ async function req<T>(
|
||||
const hit = _memTtl.get(cacheKey);
|
||||
if (hit && Date.now() - hit.at < ttl) return hit.data as T;
|
||||
}
|
||||
const email = socialEmail();
|
||||
const headers: Record<string, string> = {
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
...(email ? { "X-Social-Email": email } : {}),
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
};
|
||||
let body = init?.body;
|
||||
@ -199,6 +217,43 @@ export const socialApi = {
|
||||
return (await res.json()) as import("./types").SocialChatAttachment;
|
||||
},
|
||||
|
||||
/** 语音厅录像埋点:进厅即 pending,后台立刻可见 */
|
||||
roomArchiveEvent: (body: {
|
||||
sessionId: string;
|
||||
channelId: string;
|
||||
roomId?: string;
|
||||
status: string;
|
||||
name?: string;
|
||||
size?: number;
|
||||
path?: string;
|
||||
error?: string;
|
||||
seq?: number;
|
||||
durationSec?: number;
|
||||
startedAt?: string;
|
||||
}) =>
|
||||
req<{
|
||||
ok?: boolean;
|
||||
sessionId: string;
|
||||
status: string;
|
||||
url?: string;
|
||||
durationSec?: number;
|
||||
}>("/room-archives/events", {
|
||||
method: "POST",
|
||||
json: {
|
||||
sessionId: body.sessionId,
|
||||
channelId: body.channelId,
|
||||
roomId: body.roomId || "",
|
||||
status: body.status,
|
||||
name: body.name || "",
|
||||
size: body.size || 0,
|
||||
path: body.path || "",
|
||||
error: body.error || "",
|
||||
seq: body.seq || 0,
|
||||
durationSec: body.durationSec || 0,
|
||||
startedAt: body.startedAt || "",
|
||||
},
|
||||
}),
|
||||
|
||||
postNote: (
|
||||
channelId: string,
|
||||
what: "recv" | "read" | "kp",
|
||||
@ -313,9 +368,14 @@ export const socialApi = {
|
||||
});
|
||||
form.append("video", vFile);
|
||||
}
|
||||
const email = socialEmail();
|
||||
if (email) form.append("email", email);
|
||||
const res = await fetch(`${BASE}/avatar/challenge`, {
|
||||
method: "POST",
|
||||
headers: { "X-Social-Guest-Id": getGuestId() },
|
||||
headers: {
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
...(email ? { "X-Social-Email": email } : {}),
|
||||
},
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(120000),
|
||||
@ -354,9 +414,13 @@ export const socialApi = {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
form.append("purpose", purpose);
|
||||
const email = socialEmail();
|
||||
const res = await fetch(`${BASE}/upload`, {
|
||||
method: "POST",
|
||||
headers: { "X-Social-Guest-Id": getGuestId() },
|
||||
headers: {
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
...(email ? { "X-Social-Email": email } : {}),
|
||||
},
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(60000),
|
||||
@ -395,8 +459,43 @@ export const socialApi = {
|
||||
};
|
||||
},
|
||||
|
||||
postFeedback: (payload: { kind: string; text: string; contact?: string }) =>
|
||||
req("/feedback", { method: "POST", json: payload }),
|
||||
/** Prefer portal local store (PB 挂了也能落盘);再打 social API。 */
|
||||
postFeedback: async (payload: {
|
||||
kind: string;
|
||||
text: string;
|
||||
contact?: string;
|
||||
}) => {
|
||||
const body = { ...payload, guestId: getGuestId() };
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
};
|
||||
const urls = ["/api/portal/feedback", `${BASE}/feedback`];
|
||||
let lastErr = "";
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
lastErr = await res.text().catch(() => `HTTP ${res.status}`);
|
||||
continue;
|
||||
}
|
||||
return (await res.json()) as {
|
||||
ok?: boolean;
|
||||
id?: string;
|
||||
stored?: string;
|
||||
};
|
||||
} catch (e) {
|
||||
lastErr = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
throw new Error(lastErr || "反馈提交失败");
|
||||
},
|
||||
|
||||
/** Join funnel archive — try portal + social (local rewrite often 404s old social). */
|
||||
postJoinLead: async (payload: {
|
||||
|
||||
@ -33,7 +33,7 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
{
|
||||
id: "chat",
|
||||
emoji: "💬",
|
||||
title: "大家聊天",
|
||||
title: "聊天群",
|
||||
desc: "打个招呼就好",
|
||||
href: "/chat",
|
||||
status: "live",
|
||||
@ -41,8 +41,8 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
{
|
||||
id: "meetup",
|
||||
emoji: "📹",
|
||||
title: "开视频聊聊",
|
||||
desc: "几个人一起开摄像头见面",
|
||||
title: "语音厅",
|
||||
desc: "几个人一起开麦聊聊",
|
||||
href: "/meetup",
|
||||
status: "live",
|
||||
},
|
||||
@ -59,8 +59,16 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
{
|
||||
id: "offline",
|
||||
title: "见一面",
|
||||
subtitle: "地图 · 城市 · 认识一下 · 我的介绍",
|
||||
subtitle: "线下 Coffee · 城市 · 咖啡馆 · 约会",
|
||||
features: [
|
||||
{
|
||||
id: "coffeechat",
|
||||
emoji: "☕",
|
||||
title: "线下咖啡聊",
|
||||
desc: "挑一座城 · 约咖啡馆见面 · 不是线上会",
|
||||
href: "/coffeechat",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "map",
|
||||
emoji: "🗺️",
|
||||
@ -73,22 +81,14 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
id: "places",
|
||||
emoji: "📍",
|
||||
title: "城市",
|
||||
desc: "旅居目的地 · 咖啡馆见面 · 同城的人",
|
||||
desc: "旅居目的地 · 线下咖啡会场 · 同城的人",
|
||||
href: "/places",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "coffeechat",
|
||||
emoji: "☕",
|
||||
title: "咖啡聊预约",
|
||||
desc: "选时段 · 预约确认(Cal.com 域模型自研)",
|
||||
href: "/coffeechat",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "date",
|
||||
emoji: "💕",
|
||||
title: "认识一下",
|
||||
title: "约会",
|
||||
desc: "左滑跳过 · 右滑想认识",
|
||||
href: "/date",
|
||||
status: "live",
|
||||
@ -106,24 +106,16 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
{
|
||||
id: "grow",
|
||||
title: "一起做事",
|
||||
subtitle: "找搭子 · 远程工作 · 共创 · 说说想法",
|
||||
subtitle: "找搭子 · 共创 · 远程工作 · 说说想法",
|
||||
features: [
|
||||
{
|
||||
id: "team",
|
||||
emoji: "🧑💻",
|
||||
title: "找搭子做事",
|
||||
title: "找搭子",
|
||||
desc: "帮忙、兼职、一起做点事",
|
||||
href: "/team",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "work",
|
||||
emoji: "🗂️",
|
||||
title: "远程工作",
|
||||
desc: "看板协作 · 实时文档 · 团队二次开发底座",
|
||||
href: "/work",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "cocreate",
|
||||
emoji: "✨",
|
||||
@ -132,6 +124,14 @@ export const SOCIAL_SECTIONS: SocialSection[] = [
|
||||
href: "/ebook",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "work",
|
||||
emoji: "🗂️",
|
||||
title: "远程工作",
|
||||
desc: "看板协作 · 实时文档 · 团队二次开发底座",
|
||||
href: "/work",
|
||||
status: "live",
|
||||
},
|
||||
{
|
||||
id: "feedback",
|
||||
emoji: "💡",
|
||||
|
||||
60
src/modules/social/lib/guestNick.ts
Normal file
60
src/modules/social/lib/guestNick.ts
Normal file
@ -0,0 +1,60 @@
|
||||
/** Unregistered chat display name — random, no 「游客」 input. */
|
||||
import { loadJson, saveJson } from "./storage";
|
||||
|
||||
const ADJ = [
|
||||
"云游",
|
||||
"漂泊",
|
||||
"远方",
|
||||
"晨光",
|
||||
"夜航",
|
||||
"星火",
|
||||
"季风",
|
||||
"海岸",
|
||||
"山野",
|
||||
"旷野",
|
||||
"南风",
|
||||
"北境",
|
||||
];
|
||||
const NOUN = [
|
||||
"旅人",
|
||||
"行者",
|
||||
"旅伴",
|
||||
"过客",
|
||||
"浪客",
|
||||
"游侠",
|
||||
"漫步",
|
||||
"候鸟",
|
||||
];
|
||||
|
||||
const BAD = new Set([
|
||||
"",
|
||||
"游民",
|
||||
"游客",
|
||||
"guest",
|
||||
"Guest",
|
||||
"匿名",
|
||||
"用户",
|
||||
]);
|
||||
|
||||
function isBadNick(nick: string): boolean {
|
||||
const t = nick.trim();
|
||||
if (!t || BAD.has(t)) return true;
|
||||
if (/^游客/.test(t) || /^guest/i.test(t)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function randomGuestNick(): string {
|
||||
const a = ADJ[Math.floor(Math.random() * ADJ.length)]!;
|
||||
const b = NOUN[Math.floor(Math.random() * NOUN.length)]!;
|
||||
const n = Math.floor(10 + Math.random() * 89);
|
||||
return `${a}${b}${n}`;
|
||||
}
|
||||
|
||||
/** Persist a usable nick for guests; never leave 「游客」. */
|
||||
export function ensureGuestNick(): string {
|
||||
const saved = (loadJson<string>("nick", "") || "").trim();
|
||||
if (!isBadNick(saved)) return saved;
|
||||
const next = randomGuestNick();
|
||||
saveJson("nick", next);
|
||||
return next;
|
||||
}
|
||||
@ -78,17 +78,17 @@ const zh: SocialDictionary = {
|
||||
id: "online",
|
||||
label: "认识人",
|
||||
items: [
|
||||
{ href: "/chat", label: "聊天群" },
|
||||
{ href: "/people", label: "想见的人" },
|
||||
{ href: "/coffeechat", label: "咖啡聊预约" },
|
||||
{ href: "/date", label: "认识一下" },
|
||||
{ href: "/meetup", label: "开视频聊聊" },
|
||||
{ href: "/chat", label: "大家聊天" },
|
||||
{ href: "/date", label: "约会" },
|
||||
{ href: "/meetup", label: "语音厅" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "offline",
|
||||
label: "见一面",
|
||||
items: [
|
||||
{ href: "/coffeechat", label: "线下咖啡聊" },
|
||||
{ href: "/map", label: "地图" },
|
||||
{ href: "/places", label: "城市" },
|
||||
],
|
||||
@ -97,9 +97,9 @@ const zh: SocialDictionary = {
|
||||
id: "together",
|
||||
label: "一起做事",
|
||||
items: [
|
||||
{ href: "/team", label: "找搭子做事" },
|
||||
{ href: "/work", label: "远程工作" },
|
||||
{ href: "/team", label: "找搭子" },
|
||||
{ href: "/ebook", label: "共创" },
|
||||
{ href: "/work", label: "远程工作" },
|
||||
{ href: "/feedback", label: "说说想法" },
|
||||
],
|
||||
},
|
||||
@ -107,19 +107,19 @@ const zh: SocialDictionary = {
|
||||
dock: [
|
||||
{ href: "/", label: "首页", short: "首页" },
|
||||
{ href: "/map", label: "地图", short: "地图" },
|
||||
{ href: "/chat", label: "大家聊天", short: "聊天" },
|
||||
{ href: "/chat", label: "聊天群", short: "聊天" },
|
||||
{ href: "/people", label: "想见的人", short: "看看谁" },
|
||||
],
|
||||
rail: [
|
||||
{ href: "/people", label: "想见的人", emoji: "👋" },
|
||||
{ href: "/map", label: "地图", emoji: "🗺️" },
|
||||
{ href: "/places", label: "城市", emoji: "📍" },
|
||||
{ href: "/coffeechat", label: "咖啡聊预约", emoji: "☕" },
|
||||
{ href: "/coffeechat", label: "线下咖啡聊", emoji: "☕" },
|
||||
{ href: "/skills", label: "技能交换", emoji: "🔄" },
|
||||
{ href: "/date", label: "认识一下", emoji: "💕" },
|
||||
{ href: "/meetup", label: "聊得来", emoji: "📡" },
|
||||
{ href: "/chat", label: "群聊", emoji: "💬" },
|
||||
{ href: "/team", label: "一起做事", emoji: "🚀" },
|
||||
{ href: "/date", label: "约会", emoji: "💕" },
|
||||
{ href: "/meetup", label: "语音厅", emoji: "📡" },
|
||||
{ href: "/chat", label: "聊天群", emoji: "💬" },
|
||||
{ href: "/team", label: "找搭子", emoji: "🚀" },
|
||||
{ href: "/work", label: "远程工作", emoji: "🗂️" },
|
||||
{ href: "/ebook", label: "共创", emoji: "🎨" },
|
||||
{ href: "/wrapped", label: "年度回顾", emoji: "✨" },
|
||||
@ -127,8 +127,8 @@ const zh: SocialDictionary = {
|
||||
],
|
||||
homePath: [
|
||||
{ href: "#people", label: "想见的人", emoji: "👋" },
|
||||
{ href: "#date", label: "认识一下", emoji: "💕" },
|
||||
{ href: "/coffeechat", label: "咖啡聊", emoji: "☕", external: true },
|
||||
{ href: "#date", label: "约会", emoji: "💕" },
|
||||
{ href: "/coffeechat", label: "线下咖啡", emoji: "☕", external: true },
|
||||
{ href: "/team", label: "技能交换", emoji: "🔄", external: true },
|
||||
{ href: "#cities", label: "城市", emoji: "📍" },
|
||||
{ href: "/map", label: "地图", emoji: "🗺️", external: true },
|
||||
@ -141,16 +141,16 @@ const zh: SocialDictionary = {
|
||||
socialHeroAccent: "同类",
|
||||
socialHeroLead:
|
||||
"换一座城市,不必重新孤独。\n从一句你好、一杯咖啡开始,找到一起生活、\n一起探索、一起做点什么的人。",
|
||||
socialJoinCta: "找到我的同频",
|
||||
socialJoinCta: "加入社区",
|
||||
socialInviteTitle: "下一站,和同类一起。",
|
||||
socialInviteLead:
|
||||
"无论你正在出发,还是已经在路上,这里都有一个属于你的位置。",
|
||||
socialOnlineTitle: "随时,聊得来",
|
||||
socialOfflineTitle: "同城,见一面",
|
||||
socialTeamTitle: "一起,做点事",
|
||||
socialWayGroup: "群组聊天",
|
||||
socialWayChat: "开视频聊聊",
|
||||
socialWayDate: "认识一下",
|
||||
socialWayGroup: "聊天群",
|
||||
socialWayChat: "语音厅",
|
||||
socialWayDate: "约会",
|
||||
socialWayCafe: "找个地方见面",
|
||||
socialWayTeam: "找搭子 · 共创",
|
||||
socialPayJoinLabel: "加入社区",
|
||||
@ -181,17 +181,17 @@ const en: SocialDictionary = {
|
||||
id: "online",
|
||||
label: "Meet online",
|
||||
items: [
|
||||
{ href: "/chat", label: "Chat rooms" },
|
||||
{ href: "/people", label: "People" },
|
||||
{ href: "/coffeechat", label: "Coffee booking" },
|
||||
{ href: "/date", label: "Say hi" },
|
||||
{ href: "/meetup", label: "Video chat" },
|
||||
{ href: "/chat", label: "Group chat" },
|
||||
{ href: "/date", label: "Dating" },
|
||||
{ href: "/meetup", label: "Voice lounge" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "offline",
|
||||
label: "Meet offline",
|
||||
items: [
|
||||
{ href: "/coffeechat", label: "Offline coffee" },
|
||||
{ href: "/map", label: "Map" },
|
||||
{ href: "/places", label: "Cities" },
|
||||
],
|
||||
@ -200,9 +200,9 @@ const en: SocialDictionary = {
|
||||
id: "together",
|
||||
label: "Build together",
|
||||
items: [
|
||||
{ href: "/team", label: "Find collaborators" },
|
||||
{ href: "/work", label: "Remote work" },
|
||||
{ href: "/team", label: "Find buddies" },
|
||||
{ href: "/ebook", label: "Co-create" },
|
||||
{ href: "/work", label: "Remote work" },
|
||||
{ href: "/feedback", label: "Feedback" },
|
||||
],
|
||||
},
|
||||
@ -210,19 +210,19 @@ const en: SocialDictionary = {
|
||||
dock: [
|
||||
{ href: "/", label: "Home", short: "Home" },
|
||||
{ href: "/map", label: "Map", short: "Map" },
|
||||
{ href: "/chat", label: "Group chat", short: "Chat" },
|
||||
{ href: "/chat", label: "Chat rooms", short: "Chat" },
|
||||
{ href: "/people", label: "People", short: "Who" },
|
||||
],
|
||||
rail: [
|
||||
{ href: "/people", label: "People", emoji: "👋" },
|
||||
{ href: "/map", label: "Map", emoji: "🗺️" },
|
||||
{ href: "/places", label: "Cities", emoji: "📍" },
|
||||
{ href: "/coffeechat", label: "Coffee booking", emoji: "☕" },
|
||||
{ href: "/coffeechat", label: "Offline coffee", emoji: "☕" },
|
||||
{ href: "/skills", label: "Skill swap", emoji: "🔄" },
|
||||
{ href: "/date", label: "Say hi", emoji: "💕" },
|
||||
{ href: "/meetup", label: "Sync", emoji: "📡" },
|
||||
{ href: "/chat", label: "Chat", emoji: "💬" },
|
||||
{ href: "/team", label: "Collaborate", emoji: "🚀" },
|
||||
{ href: "/date", label: "Dating", emoji: "💕" },
|
||||
{ href: "/meetup", label: "Voice lounge", emoji: "📡" },
|
||||
{ href: "/chat", label: "Chat rooms", emoji: "💬" },
|
||||
{ href: "/team", label: "Find buddies", emoji: "🚀" },
|
||||
{ href: "/work", label: "Remote work", emoji: "🗂️" },
|
||||
{ href: "/ebook", label: "Co-create", emoji: "🎨" },
|
||||
{ href: "/wrapped", label: "Year wrapped", emoji: "✨" },
|
||||
@ -230,7 +230,7 @@ const en: SocialDictionary = {
|
||||
],
|
||||
homePath: [
|
||||
{ href: "#people", label: "People", emoji: "👋" },
|
||||
{ href: "#date", label: "Say hi", emoji: "💕" },
|
||||
{ href: "#date", label: "Dating", emoji: "💕" },
|
||||
{ href: "/coffeechat", label: "Coffee chat", emoji: "☕", external: true },
|
||||
{ href: "#skills", label: "Skill swap", emoji: "🔄" },
|
||||
{ href: "#cities", label: "Cities", emoji: "📍" },
|
||||
@ -244,18 +244,18 @@ const en: SocialDictionary = {
|
||||
socialHeroAccent: "find your people",
|
||||
socialHeroLead:
|
||||
"Change cities without starting over alone.\nFrom a hello and a coffee, find people to live,\nexplore, and build with.",
|
||||
socialJoinCta: "Find my people",
|
||||
socialJoinCta: "Join community",
|
||||
socialInviteTitle: "Next stop — with people like you.",
|
||||
socialInviteLead:
|
||||
"Whether you are about to leave or already on the road, there is a place for you here.",
|
||||
socialOnlineTitle: "Anytime · good conversations",
|
||||
socialOfflineTitle: "Same city · meet in person",
|
||||
socialTeamTitle: "Together · make something",
|
||||
socialWayGroup: "Group chat",
|
||||
socialWayChat: "Video hangout",
|
||||
socialWayDate: "Say hi",
|
||||
socialWayGroup: "Chat rooms",
|
||||
socialWayChat: "Voice lounge",
|
||||
socialWayDate: "Dating",
|
||||
socialWayCafe: "Find a place to meet",
|
||||
socialWayTeam: "Collab · co-create",
|
||||
socialWayTeam: "Find buddies · co-create",
|
||||
socialPayJoinLabel: "Join community",
|
||||
socialOaJoinLabel: "Follow our WeChat OA",
|
||||
},
|
||||
|
||||
@ -2,10 +2,47 @@
|
||||
|
||||
import { socialApi } from "./api";
|
||||
import { getLivenessState } from "./livenessGate";
|
||||
import { isJoinPaid, isJoinProfileDone } from "./joinFlow";
|
||||
import { getJoinPaidFlag, isJoinProfileDone } from "./joinFlow";
|
||||
import { getSocialSession } from "./socialSession";
|
||||
|
||||
/** Persist join funnel event → admin social_join_leads (+ archives). Prefer await before navigation. */
|
||||
/** Stages that may write face / liveness onto the lead. */
|
||||
const FACE_LIVENESS_STAGES = new Set([
|
||||
"profile_done",
|
||||
"liveness_verified",
|
||||
"liveness_failed",
|
||||
"liveness_skipped",
|
||||
"join_done",
|
||||
]);
|
||||
|
||||
/** Stages that may set paid=1 (真付费). 仅邮箱 / 发起支付不算已付。 */
|
||||
const PAID_STAGES = new Set([
|
||||
"pay_confirmed",
|
||||
"profile_done",
|
||||
"liveness_verified",
|
||||
"liveness_skipped",
|
||||
"join_done",
|
||||
]);
|
||||
|
||||
function resolvePaidFlag(
|
||||
stage: string,
|
||||
extra?: Record<string, unknown>,
|
||||
): string {
|
||||
const intent = String(extra?.intent || "");
|
||||
const priceFen = Number(extra?.priceFen);
|
||||
const local = getJoinPaidFlag();
|
||||
// 临时免费:全程记 free,后台显示「免费」,绝不是「已付」
|
||||
if (
|
||||
intent === "free" ||
|
||||
local === "free" ||
|
||||
(Number.isFinite(priceFen) && priceFen <= 0)
|
||||
) {
|
||||
return "free";
|
||||
}
|
||||
if (!PAID_STAGES.has(stage)) return "";
|
||||
return local === "1" ? "1" : "";
|
||||
}
|
||||
|
||||
/** Persist join funnel event → admin social_join_leads (+ archives). */
|
||||
export async function archiveJoinLead(
|
||||
stage: string,
|
||||
extra?: Record<string, unknown>,
|
||||
@ -22,15 +59,18 @@ export async function archiveJoinLead(
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!email || !email.includes("@")) return;
|
||||
const live = getLivenessState();
|
||||
|
||||
const allowFace = FACE_LIVENESS_STAGES.has(stage);
|
||||
const live = allowFace ? getLivenessState() : null;
|
||||
|
||||
try {
|
||||
await socialApi.postJoinLead({
|
||||
email,
|
||||
stage,
|
||||
name: session?.name || email.split("@")[0] || "",
|
||||
paid: isJoinPaid() ? "1" : "",
|
||||
faceOk: live.faceOk ? "1" : "",
|
||||
livenessStatus: live.livenessStatus || "",
|
||||
paid: resolvePaidFlag(stage, extra),
|
||||
faceOk: allowFace && live?.faceOk ? "1" : "",
|
||||
livenessStatus: allowFace ? live?.livenessStatus || "none" : "none",
|
||||
ua: typeof navigator !== "undefined" ? navigator.userAgent : "",
|
||||
payload: {
|
||||
profileDone: isJoinProfileDone(),
|
||||
|
||||
@ -64,7 +64,7 @@ export const JOIN_INTENT_OPTIONS: JoinOption[] = [
|
||||
{ value: "meetup", labelZh: "线下聚会", labelEn: "Meet in person" },
|
||||
{ value: "online", labelZh: "线上分享", labelEn: "Online hangouts" },
|
||||
{ value: "cowork", labelZh: "远程 cowork", labelEn: "Remote cowork" },
|
||||
{ value: "collab", labelZh: "找搭子做事", labelEn: "Find collaborators" },
|
||||
{ value: "collab", labelZh: "找搭子", labelEn: "Find buddies" },
|
||||
{ value: "cofounder", labelZh: "找联创", labelEn: "Find a cofounder" },
|
||||
{ value: "friends", labelZh: "交朋友", labelEn: "Make friends" },
|
||||
{ value: "date", labelZh: "认识有缘人", labelEn: "Meet someone" },
|
||||
@ -128,11 +128,12 @@ function bumpSocialStorage(): void {
|
||||
window.dispatchEvent(new Event("nomadro-social-storage"));
|
||||
}
|
||||
|
||||
export function markJoinPaid(): void {
|
||||
/** Unlock join funnel. `"free"` = 临时免费(后台显示免费,不是已付);`"1"` = 真付费。 */
|
||||
export function markJoinPaid(mode: "1" | "free" = "1"): void {
|
||||
try {
|
||||
localStorage.setItem(JOIN_PAID_KEY, "1");
|
||||
localStorage.setItem(JOIN_PAID_KEY, mode);
|
||||
localStorage.setItem("paidType", "vip");
|
||||
sessionStorage.setItem(JOIN_PAID_KEY, "1");
|
||||
sessionStorage.setItem(JOIN_PAID_KEY, mode);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@ -140,6 +141,17 @@ export function markJoinPaid(): void {
|
||||
bumpSocialStorage();
|
||||
}
|
||||
|
||||
/** Local marker for archive: `1` | `free` | `` */
|
||||
export function getJoinPaidFlag(): "" | "1" | "free" {
|
||||
try {
|
||||
const v = localStorage.getItem(JOIN_PAID_KEY);
|
||||
if (v === "1" || v === "free") return v;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function clearJoinPayIntent(): void {
|
||||
try {
|
||||
localStorage.removeItem(JOIN_PENDING_PROFILE_KEY);
|
||||
@ -152,8 +164,9 @@ export function clearJoinPayIntent(): void {
|
||||
|
||||
export function isJoinPaid(): boolean {
|
||||
try {
|
||||
// Only the join-flow flag — do not treat generic VIP paidType as join-paid
|
||||
return localStorage.getItem(JOIN_PAID_KEY) === "1";
|
||||
// free 与真付费都算「已解锁进资料」;勿把 generic VIP paidType 当 join
|
||||
const v = localStorage.getItem(JOIN_PAID_KEY);
|
||||
return v === "1" || v === "free";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@ -190,8 +203,10 @@ export function hasJoinPayIntent(): boolean {
|
||||
try {
|
||||
if (localStorage.getItem(JOIN_PENDING_PROFILE_KEY) === "1") return true;
|
||||
if (sessionStorage.getItem(JOIN_PENDING_PROFILE_KEY) === "1") return true;
|
||||
if (localStorage.getItem(JOIN_PAID_KEY) === "1") return true;
|
||||
if (sessionStorage.getItem(JOIN_PAID_KEY) === "1") return true;
|
||||
const paid = localStorage.getItem(JOIN_PAID_KEY);
|
||||
if (paid === "1" || paid === "free") return true;
|
||||
const sess = sessionStorage.getItem(JOIN_PAID_KEY);
|
||||
if (sess === "1" || sess === "free") return true;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@ -247,9 +262,9 @@ export function isJoinPaySkipAllowed(): boolean {
|
||||
return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
|
||||
}
|
||||
|
||||
/** Dev helper: pretend pay succeeded and open the profile step. */
|
||||
/** Dev helper / 免费入口:已标记则不覆盖 free→1。 */
|
||||
export function skipJoinPayToProfile(): void {
|
||||
markJoinPayIntent();
|
||||
markJoinPaid();
|
||||
if (!isJoinPaid()) markJoinPaid("1");
|
||||
window.location.assign(JOIN_PROFILE_RETURN);
|
||||
}
|
||||
|
||||
48
src/modules/social/lib/joinModal.ts
Normal file
48
src/modules/social/lib/joinModal.ts
Normal file
@ -0,0 +1,48 @@
|
||||
/** Open join / login sheet on the current page — never navigate to /social/join for gate. */
|
||||
|
||||
export const SOCIAL_JOIN_MODAL_EVENT = "nomadro-open-join-modal";
|
||||
|
||||
export type OpenJoinModalDetail = {
|
||||
/** Optional reason for analytics / future step routing */
|
||||
reason?: "join" | "login" | "gate" | "cta";
|
||||
};
|
||||
|
||||
export function openSocialJoinModal(detail: OpenJoinModalDetail = {}): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(SOCIAL_JOIN_MODAL_EVENT, { detail }),
|
||||
);
|
||||
}
|
||||
|
||||
export function subscribeSocialJoinModal(
|
||||
handler: (detail: OpenJoinModalDetail) => void,
|
||||
): () => void {
|
||||
const onEvent = (event: Event) => {
|
||||
const detail =
|
||||
event instanceof CustomEvent
|
||||
? ((event.detail || {}) as OpenJoinModalDetail)
|
||||
: {};
|
||||
handler(detail);
|
||||
};
|
||||
window.addEventListener(SOCIAL_JOIN_MODAL_EVENT, onEvent);
|
||||
return () => window.removeEventListener(SOCIAL_JOIN_MODAL_EVENT, onEvent);
|
||||
}
|
||||
|
||||
/** Persist intent across a soft redirect away from /social/join. */
|
||||
export function flagOpenJoinModalSoon(): void {
|
||||
try {
|
||||
sessionStorage.setItem("social-open-join-modal", "1");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeOpenJoinModalFlag(): boolean {
|
||||
try {
|
||||
if (sessionStorage.getItem("social-open-join-modal") !== "1") return false;
|
||||
sessionStorage.removeItem("social-open-join-modal");
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -76,7 +76,8 @@ export function markLivenessVerified(opts?: { videoUrl?: string }): void {
|
||||
/** Paid + profile(avatar) + live verify — unlock chat / AV / dating / coffee. */
|
||||
export function isCommunityUnlocked(): boolean {
|
||||
try {
|
||||
if (localStorage.getItem("social-join-paid") !== "1") return false;
|
||||
const paid = localStorage.getItem("social-join-paid");
|
||||
if (paid !== "1" && paid !== "free") return false;
|
||||
if (localStorage.getItem("social-join-profile-done") !== "1") return false;
|
||||
} catch {
|
||||
return false;
|
||||
@ -132,6 +133,17 @@ export function isFaceOk(): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** 换邮箱 / 退出时清空本机人脸与核验,禁止串号到下一位访客。 */
|
||||
export function clearLivenessState(): void {
|
||||
saveJson(LIVENESS_KEY, { ...EMPTY });
|
||||
try {
|
||||
localStorage.removeItem(FACE_OK_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
bump();
|
||||
}
|
||||
|
||||
/**
|
||||
* Locked until live selfie passes:
|
||||
* 群聊 / 语音视频 / 约会 / 咖啡聊 / 地图 / 「一起做事」下拉相关。
|
||||
|
||||
@ -162,6 +162,13 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"再出来见面": "Then meet up",
|
||||
|
||||
"认识一下": "Say hi",
|
||||
"约会": "Dating",
|
||||
"聊天群": "Chat rooms",
|
||||
"语音厅": "Voice lounge",
|
||||
"找搭子": "Find buddies",
|
||||
"游民社区 · 约会": "Nomad Social · Dating",
|
||||
"找搭子做事": "Find buddies",
|
||||
"开视频聊聊": "Voice lounge",
|
||||
"群组 · 语音视频": "Group · voice & video",
|
||||
"还不等于已经约好": "not a confirmed booking",
|
||||
"或者看看全部场次": "or browse all sessions",
|
||||
@ -249,6 +256,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"一个聊天室": "One chat room",
|
||||
"进入群聊": "Enter group chat",
|
||||
"大家聊天": "Group chat",
|
||||
"大家聊聊": "Chat rooms",
|
||||
"简单好找": "Simple to find",
|
||||
"都在这里说一声就行": "Just say something here",
|
||||
"先在群里打个招呼": "Say hi in the group first",
|
||||
@ -440,6 +448,8 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"我的主页": "My page",
|
||||
"退出登录": "Sign out",
|
||||
"现场自拍": "Live selfie",
|
||||
"录制中 · 全程存档": "Recording · full archive",
|
||||
"录屏失败,请重开摄像头再试一次": "Recording failed — reopen the camera and retry",
|
||||
"正对镜头,脸放进圈内": "Face the camera — keep your face in the oval",
|
||||
"脸放进圈内,倒计时后请转头":
|
||||
"Keep your face in the oval — turn your head after the countdown",
|
||||
@ -607,6 +617,28 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"左右滑": "Swipe",
|
||||
"一张一张认识": "Meet one by one",
|
||||
"咖啡聊": "Coffee chat",
|
||||
"线下咖啡聊": "Offline coffee",
|
||||
"线下 Coffee": "Offline Coffee",
|
||||
"城市见面": "Meet in city",
|
||||
"挑一座城,约一杯线下咖啡": "Pick a city, book offline coffee",
|
||||
"咖啡聊预约就是线下见面:先选城,再约咖啡馆。不是线上会议。":
|
||||
"Coffeechat means IRL: pick a city, then a café — not a video call.",
|
||||
"线下会场": "Offline venue",
|
||||
"见面点": "Meet spots",
|
||||
"会场": "Venues",
|
||||
"先选城市,再挑一家适合见面的咖啡馆。":
|
||||
"Pick a city, then a café that works for meeting up.",
|
||||
"换城市或清空筛选。": "Try another city or clear filters.",
|
||||
"店名 / 氛围": "Name / vibe",
|
||||
"看这座城": "Explore city",
|
||||
"咖啡馆": "Cafés",
|
||||
"同城咖啡馆见面,破冰比私信快。":
|
||||
"Meet at a local café — faster than DMs.",
|
||||
"线下主持人": "Offline host",
|
||||
"咖啡馆轻聊": "Café chat",
|
||||
"去预约线下": "Book offline",
|
||||
"更多城市": "More cities",
|
||||
"城市足迹": "City footprint",
|
||||
"约一杯见面": "Book a café meet",
|
||||
"技能板": "Skill board",
|
||||
"互换互助": "Trade & help",
|
||||
@ -626,6 +658,19 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"打开地图": "Open map",
|
||||
"逛城市": "Browse cities",
|
||||
"咖啡馆见面": "Café meetups",
|
||||
"咖啡馆见面点": "Café meet spots",
|
||||
"线下见面": "Meet offline",
|
||||
"先挑一座城,再约咖啡馆线下见面。简单两步。":
|
||||
"Pick a city, then a café. Two steps.",
|
||||
"挑城市": "Cities",
|
||||
"搜城市 / 国家": "Search city / country",
|
||||
"只看热门": "Hot only",
|
||||
"座城市": "cities",
|
||||
"没有匹配的城市,换个关键词试试。": "No cities matched — try another keyword.",
|
||||
"加载咖啡馆…": "Loading cafés…",
|
||||
"加载城市…": "Loading cities…",
|
||||
"城市功能": "City tools",
|
||||
"热门": "Hot",
|
||||
"清迈": "Chiang Mai",
|
||||
"巴厘岛": "Bali",
|
||||
"大理": "Dali",
|
||||
|
||||
@ -287,19 +287,15 @@ export const TEAM_KIND_LABEL: Record<SocialTeamKind, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* 自研 MiroTalk:生产门户同域 `/join`(nginx → 本机 :9300),禁止跳 mirotalk.* 二级域。
|
||||
* Override: NEXT_PUBLIC_MIROTALK_URL(本地可指 https://mirotalk.nomadro.com)。
|
||||
* 语音厅 iframe 必须打到 MiroTalk 实例。
|
||||
* 禁止再用门户同域 origin+/join:挂断后 MiroTalk 会跳到 `/`,同域下变成门户首页嵌在视频框里。
|
||||
* Override: NEXT_PUBLIC_MIROTALK_URL
|
||||
*/
|
||||
function defaultMirotalkUrl(): string {
|
||||
if (typeof window !== "undefined") {
|
||||
const h = window.location.hostname;
|
||||
if (
|
||||
h === "nomadro.com" ||
|
||||
h === "www.nomadro.com" ||
|
||||
h === "nomadro.cn" ||
|
||||
h === "www.nomadro.cn"
|
||||
) {
|
||||
return window.location.origin;
|
||||
if (h.endsWith(".nomadro.cn") || h === "nomadro.cn") {
|
||||
return "https://mirotalk.nomadro.cn";
|
||||
}
|
||||
}
|
||||
return "https://mirotalk.nomadro.com";
|
||||
|
||||
@ -1,81 +1,315 @@
|
||||
"use client";
|
||||
|
||||
import { socialApi } from "./api";
|
||||
import { getGuestId, socialApi } from "./api";
|
||||
|
||||
/**
|
||||
* Silent AV archive while user is in a voice/video room.
|
||||
* No REC badge / UI — starts after getUserMedia permission is granted.
|
||||
* Silent AV archive + 埋点状态机
|
||||
* pending → recording → uploading → uploaded(denied/failed 也会进后台)
|
||||
* 退出厅:立刻打「上传中」,传完变「已上传」——不能卡在「录制中」
|
||||
*/
|
||||
export type SilentRecorderHandle = {
|
||||
stop: () => void;
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
function sessionKey(roomId: string) {
|
||||
return `nomadro-room-arc:${roomId || "default"}`;
|
||||
}
|
||||
|
||||
function newSessionId(roomId: string) {
|
||||
try {
|
||||
const key = sessionKey(roomId);
|
||||
const existing = sessionStorage.getItem(key);
|
||||
if (existing && existing.startsWith("arc_")) return existing;
|
||||
const sid = `arc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
sessionStorage.setItem(key, sid);
|
||||
return sid;
|
||||
} catch {
|
||||
return `arc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function clearSessionId(roomId: string) {
|
||||
try {
|
||||
sessionStorage.removeItem(sessionKey(roomId));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
async function openArchiveStream(): Promise<MediaStream | null> {
|
||||
if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia) {
|
||||
return null;
|
||||
}
|
||||
const attempts: MediaStreamConstraints[] = [
|
||||
{
|
||||
audio: true,
|
||||
video: { facingMode: "user", width: { ideal: 640 }, height: { ideal: 480 } },
|
||||
},
|
||||
{ audio: true, video: true },
|
||||
{ audio: true, video: false },
|
||||
];
|
||||
for (let round = 0; round < 2; round++) {
|
||||
for (const constraints of attempts) {
|
||||
try {
|
||||
return await navigator.mediaDevices.getUserMedia(constraints);
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 离页用 keepalive,保证退出瞬间后台状态就变 */
|
||||
function trackEventNow(
|
||||
opts: {
|
||||
sessionId: string;
|
||||
channelId: string;
|
||||
roomId: string;
|
||||
startedAt: number;
|
||||
},
|
||||
status: string,
|
||||
extra?: { name?: string; size?: number; path?: string; error?: string; seq?: number },
|
||||
keepalive = false,
|
||||
) {
|
||||
const durationSec = Math.max(
|
||||
0,
|
||||
Math.floor((Date.now() - (opts.startedAt || Date.now())) / 1000),
|
||||
);
|
||||
const payload = {
|
||||
sessionId: opts.sessionId,
|
||||
channelId: opts.channelId,
|
||||
roomId: opts.roomId || "",
|
||||
status,
|
||||
name: extra?.name || "",
|
||||
size: extra?.size || 0,
|
||||
path: extra?.path || "",
|
||||
error: extra?.error || "",
|
||||
seq: extra?.seq || 0,
|
||||
durationSec,
|
||||
startedAt: new Date(opts.startedAt).toISOString(),
|
||||
};
|
||||
const body = JSON.stringify(payload);
|
||||
if (keepalive && typeof fetch !== "undefined") {
|
||||
try {
|
||||
void fetch("/api/social/v1/room-archives/events", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
},
|
||||
body,
|
||||
cache: "no-store",
|
||||
keepalive: true,
|
||||
});
|
||||
return Promise.resolve();
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
return socialApi
|
||||
.roomArchiveEvent(payload)
|
||||
.then(() => undefined)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
async function trackEvent(
|
||||
opts: {
|
||||
sessionId: string;
|
||||
channelId: string;
|
||||
roomId: string;
|
||||
startedAt: number;
|
||||
},
|
||||
status: string,
|
||||
extra?: { name?: string; size?: number; path?: string; error?: string; seq?: number },
|
||||
) {
|
||||
await trackEventNow(opts, status, extra, false);
|
||||
}
|
||||
|
||||
async function uploadArchiveFile(
|
||||
channelId: string,
|
||||
file: File,
|
||||
sessionId: string,
|
||||
): Promise<void> {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
form.append("kind", "room-archive");
|
||||
form.append("session_id", sessionId);
|
||||
const res = await fetch(
|
||||
`/api/social/v1/channels/${encodeURIComponent(channelId)}/upload`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "X-Social-Guest-Id": getGuestId() },
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
},
|
||||
);
|
||||
if (!res.ok) throw new Error(`upload ${res.status}`);
|
||||
}
|
||||
|
||||
/** 进厅瞬间落「待上传」,再开摄像头/录像 */
|
||||
export async function startSilentRoomArchive(opts: {
|
||||
channelId: string;
|
||||
roomId: string;
|
||||
sessionId?: string;
|
||||
}): Promise<SilentRecorderHandle | null> {
|
||||
if (typeof window === "undefined" || typeof MediaRecorder === "undefined") {
|
||||
return null;
|
||||
if (typeof window === "undefined") return null;
|
||||
|
||||
const sessionId = opts.sessionId || newSessionId(opts.roomId);
|
||||
const startedAt = Date.now();
|
||||
const ctx = {
|
||||
sessionId,
|
||||
channelId: opts.channelId,
|
||||
roomId: opts.roomId,
|
||||
startedAt,
|
||||
};
|
||||
|
||||
// 埋点不阻塞开厅:pending 立刻 keepalive 打出
|
||||
void trackEventNow(
|
||||
ctx,
|
||||
"pending",
|
||||
{ name: `room-${opts.roomId || opts.channelId}-pending.webm` },
|
||||
true,
|
||||
);
|
||||
|
||||
if (typeof MediaRecorder === "undefined") {
|
||||
await trackEvent(ctx, "failed", { error: "MediaRecorder unsupported" });
|
||||
clearSessionId(opts.roomId);
|
||||
return { stop: () => undefined, sessionId };
|
||||
}
|
||||
let stream: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: true,
|
||||
video: { facingMode: "user", width: { ideal: 640 }, height: { ideal: 480 } },
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
const stream = await openArchiveStream();
|
||||
if (!stream) {
|
||||
await trackEvent(ctx, "denied", { error: "getUserMedia denied" });
|
||||
clearSessionId(opts.roomId);
|
||||
return { stop: () => undefined, sessionId };
|
||||
}
|
||||
|
||||
await trackEvent(ctx, "recording");
|
||||
|
||||
const mimeCandidates = [
|
||||
"video/webm;codecs=vp9,opus",
|
||||
"video/webm;codecs=vp8,opus",
|
||||
"video/webm",
|
||||
"audio/webm;codecs=opus",
|
||||
"audio/webm",
|
||||
];
|
||||
const hasVideo = stream.getVideoTracks().length > 0;
|
||||
const mime =
|
||||
mimeCandidates.find((m) => MediaRecorder.isTypeSupported(m)) || "";
|
||||
mimeCandidates.find((m) => {
|
||||
if (!MediaRecorder.isTypeSupported(m)) return false;
|
||||
if (!hasVideo && m.startsWith("video/")) return false;
|
||||
return true;
|
||||
}) || "";
|
||||
|
||||
const chunks: BlobPart[] = [];
|
||||
let recorder: MediaRecorder;
|
||||
try {
|
||||
recorder = mime
|
||||
? new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 600_000 })
|
||||
? new MediaRecorder(stream, {
|
||||
mimeType: mime,
|
||||
...(hasVideo
|
||||
? { videoBitsPerSecond: 600_000 }
|
||||
: { audioBitsPerSecond: 64_000 }),
|
||||
})
|
||||
: new MediaRecorder(stream);
|
||||
} catch {
|
||||
} catch (e) {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
return null;
|
||||
await trackEvent(ctx, "failed", {
|
||||
error: e instanceof Error ? e.message : "recorder init failed",
|
||||
});
|
||||
clearSessionId(opts.roomId);
|
||||
return { stop: () => undefined, sessionId };
|
||||
}
|
||||
|
||||
let stopped = false;
|
||||
let seq = 0;
|
||||
let flushing: Promise<void> = Promise.resolve();
|
||||
let uploadedOnce = false;
|
||||
|
||||
const flush = async (final = false) => {
|
||||
if (!chunks.length) return;
|
||||
const blob = new Blob(chunks, { type: recorder.mimeType || "video/webm" });
|
||||
chunks.length = 0;
|
||||
if (blob.size < 8_000 && !final) return;
|
||||
const uploadBlob = async (blob: Blob, final: boolean) => {
|
||||
if (!final && blob.size < 8_000) return;
|
||||
if (blob.size <= 0) {
|
||||
if (final && !uploadedOnce) {
|
||||
await trackEventNow(ctx, "failed", { error: "empty recording on leave" }, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const file = new File(
|
||||
[blob],
|
||||
`room-${opts.roomId}-${Date.now()}-${seq++}.webm`,
|
||||
{ type: blob.type || "video/webm" },
|
||||
`room-${opts.roomId}-${Date.now()}-${seq}.webm`,
|
||||
{ type: blob.type || recorder.mimeType || "video/webm" },
|
||||
);
|
||||
await trackEventNow(
|
||||
ctx,
|
||||
"uploading",
|
||||
{ name: file.name, size: file.size, seq },
|
||||
final,
|
||||
);
|
||||
try {
|
||||
await socialApi.upload(opts.channelId, file, "room-archive");
|
||||
} catch {
|
||||
/* keep silent — archive is best-effort */
|
||||
await uploadArchiveFile(opts.channelId, file, sessionId);
|
||||
uploadedOnce = true;
|
||||
await trackEventNow(
|
||||
ctx,
|
||||
"uploaded",
|
||||
{ name: file.name, size: file.size, seq },
|
||||
final,
|
||||
);
|
||||
seq += 1;
|
||||
} catch (e) {
|
||||
await trackEventNow(
|
||||
ctx,
|
||||
"failed",
|
||||
{
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
error: e instanceof Error ? e.message : "upload failed",
|
||||
seq,
|
||||
},
|
||||
final,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const flush = (final = false) => {
|
||||
if (!chunks.length) {
|
||||
if (final && !uploadedOnce) {
|
||||
return trackEventNow(ctx, "failed", { error: "left with no media chunks" }, true);
|
||||
}
|
||||
return flushing;
|
||||
}
|
||||
const blob = new Blob(chunks, {
|
||||
type: recorder.mimeType || (hasVideo ? "video/webm" : "audio/webm"),
|
||||
});
|
||||
chunks.length = 0;
|
||||
flushing = flushing.then(() => uploadBlob(blob, final));
|
||||
return flushing;
|
||||
};
|
||||
|
||||
recorder.ondataavailable = (ev) => {
|
||||
if (ev.data && ev.data.size > 0) chunks.push(ev.data);
|
||||
};
|
||||
recorder.onstop = () => {
|
||||
void flush(true).finally(() => {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
clearSessionId(opts.roomId);
|
||||
});
|
||||
};
|
||||
|
||||
// Slice every ~25s so long rooms still archive mid-session
|
||||
recorder.start(25_000);
|
||||
recorder.start(60_000);
|
||||
window.setTimeout(() => {
|
||||
if (stopped || recorder.state !== "recording") return;
|
||||
try {
|
||||
recorder.requestData();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
void flush(false);
|
||||
}, 3_000);
|
||||
|
||||
const tick = window.setInterval(() => {
|
||||
if (stopped || recorder.state !== "recording") return;
|
||||
try {
|
||||
@ -84,18 +318,43 @@ export async function startSilentRoomArchive(opts: {
|
||||
/* ignore */
|
||||
}
|
||||
void flush(false);
|
||||
}, 28_000);
|
||||
}, 60_000);
|
||||
|
||||
const forceStopAndUpload = () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
window.clearInterval(tick);
|
||||
window.removeEventListener("pagehide", forceStopAndUpload);
|
||||
// 退出瞬间:后台立刻从「录制中」→「上传中」
|
||||
void trackEventNow(ctx, "uploading", { error: "leaving room" }, true);
|
||||
try {
|
||||
if (recorder.state === "recording") {
|
||||
try {
|
||||
recorder.requestData();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
recorder.stop();
|
||||
} else {
|
||||
void flush(true);
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
clearSessionId(opts.roomId);
|
||||
}
|
||||
} catch {
|
||||
void flush(true);
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
clearSessionId(opts.roomId);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("pagehide", forceStopAndUpload);
|
||||
window.addEventListener("beforeunload", forceStopAndUpload);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
stop: () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
window.clearInterval(tick);
|
||||
try {
|
||||
if (recorder.state !== "inactive") recorder.stop();
|
||||
} catch {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
}
|
||||
window.removeEventListener("beforeunload", forceStopAndUpload);
|
||||
forceStopAndUpload();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -2,10 +2,23 @@
|
||||
|
||||
/** Lightweight email session for social join / test-phase auth. */
|
||||
|
||||
import { resetGuestId } from "./api";
|
||||
import { clearLivenessState } from "./livenessGate";
|
||||
import { removeJson } from "./storage";
|
||||
|
||||
const EMAIL_KEY = "userEmail";
|
||||
const NAME_KEY = "userName";
|
||||
const CHANGE = "nomadro-social-storage";
|
||||
|
||||
/** Profile / discovery keys bound to one email — must not leak across accounts. */
|
||||
const ACCOUNT_JSON_KEYS = [
|
||||
"join-profile",
|
||||
"roster",
|
||||
"nick",
|
||||
"feedback-draft",
|
||||
"feedback-delivery",
|
||||
] as const;
|
||||
|
||||
export type SocialSession = {
|
||||
email: string;
|
||||
name: string;
|
||||
@ -16,6 +29,27 @@ function bump(): void {
|
||||
window.dispatchEvent(new Event(CHANGE));
|
||||
}
|
||||
|
||||
/** Drop join/pay/face/profile that belong to the previous email. */
|
||||
export function clearAccountBoundLocalState(): void {
|
||||
try {
|
||||
localStorage.removeItem("social-join-paid");
|
||||
localStorage.removeItem("social-join-profile-done");
|
||||
localStorage.removeItem("social-join-pending-profile");
|
||||
localStorage.removeItem("paidType");
|
||||
sessionStorage.removeItem("social-join-paid");
|
||||
sessionStorage.removeItem("social-join-pending-profile");
|
||||
sessionStorage.removeItem("social-join-profile-done");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
for (const key of ACCOUNT_JSON_KEYS) {
|
||||
removeJson(key);
|
||||
}
|
||||
clearLivenessState();
|
||||
// 必须换 guest,否则后台按 guestId 拉花名册会串上一位的头像/自拍
|
||||
resetGuestId();
|
||||
}
|
||||
|
||||
export function getSocialSession(): SocialSession | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
@ -39,6 +73,11 @@ export function isSocialLoggedIn(): boolean {
|
||||
export function loginWithEmail(email: string, name?: string): SocialSession {
|
||||
const value = email.trim().toLowerCase();
|
||||
if (!value.includes("@")) throw new Error("invalid email");
|
||||
const prev = (localStorage.getItem(EMAIL_KEY) || "").trim().toLowerCase();
|
||||
// 换邮箱 / 首登:清空上一位资料头像核验,禁止串号
|
||||
if (prev !== value) {
|
||||
clearAccountBoundLocalState();
|
||||
}
|
||||
const nick =
|
||||
(name || "").trim() || value.split("@")[0] || "游民";
|
||||
localStorage.setItem(EMAIL_KEY, value);
|
||||
@ -52,13 +91,10 @@ export function logoutSocialSession(): void {
|
||||
try {
|
||||
localStorage.removeItem(EMAIL_KEY);
|
||||
localStorage.removeItem(NAME_KEY);
|
||||
localStorage.removeItem("social-join-paid");
|
||||
localStorage.removeItem("social-join-profile-done");
|
||||
localStorage.removeItem("social-join-pending-profile");
|
||||
localStorage.removeItem("paidType");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
clearAccountBoundLocalState();
|
||||
bump();
|
||||
}
|
||||
|
||||
|
||||
@ -34,6 +34,22 @@ export function saveJson<T>(key: string, value: T): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop a namespaced social key (and in-memory fallback). */
|
||||
export function removeJson(key: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
memory.delete(key);
|
||||
try {
|
||||
window.localStorage.removeItem(PREFIX + key);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
window.dispatchEvent(new Event("nomadro-social-storage"));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function uid(prefix = "id"): string {
|
||||
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { socialApi, getGuestId } from "./api";
|
||||
import { SEED_MESSAGES } from "./seed";
|
||||
import { loadJson, saveJson, uid } from "./storage";
|
||||
import { ensureGuestNick } from "./guestNick";
|
||||
import { useLocalState } from "./useLocalState";
|
||||
import type {
|
||||
SocialChatAttachment,
|
||||
@ -69,12 +70,17 @@ export function useSocialChat(channelId: string) {
|
||||
return (cached?.length ? cached : seeds).slice(-200);
|
||||
});
|
||||
const [draft, setDraft] = useLocalState(`chat-draft:${channelId}`, "");
|
||||
const [nick, setNick] = useLocalState("nick", "游民");
|
||||
const [nick, setNick] = useLocalState("nick", "云游旅人");
|
||||
const persistTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => {
|
||||
const cached = loadJson<SocialChatMessage[]>(`chat:${channelId}`, seeds);
|
||||
setMessages((cached?.length ? cached : seeds).slice(-200));
|
||||
}, [channelId, seeds]);
|
||||
useEffect(() => {
|
||||
const next = ensureGuestNick();
|
||||
if (next) setNick(next);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- seed guest nick once per channel
|
||||
}, [channelId]);
|
||||
const [status, setStatus] = useState<
|
||||
"connecting" | "online" | "offline" | "preview"
|
||||
>("connecting");
|
||||
@ -131,8 +137,7 @@ export function useSocialChat(channelId: string) {
|
||||
|
||||
const beatPresence = async () => {
|
||||
try {
|
||||
const nick = loadJson<string>("nick", "游民");
|
||||
const info = await socialApi.presence(channelId, nick);
|
||||
const info = await socialApi.presence(channelId, ensureGuestNick());
|
||||
if (!cancelled) setOnline(Number(info.online || 0));
|
||||
} catch {
|
||||
/* optional */
|
||||
@ -297,7 +302,7 @@ export function useSocialChat(channelId: string) {
|
||||
return false;
|
||||
lock.current = true;
|
||||
setSending(true);
|
||||
const author = nick.trim() || "游民";
|
||||
const author = (nick.trim() || ensureGuestNick()).slice(0, 24);
|
||||
const clientId = options.retryId || uid("c");
|
||||
try {
|
||||
const saved = await socialApi.sendMessage(
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
/**
|
||||
* 门户 / VIP 埋点入口(旁路)
|
||||
* - 关键事件 → ntfy(带 host 标签)
|
||||
* - 关键事件 → ntfy(Markdown 富文本 + icon + 操作按钮)
|
||||
* - 全量转发 API_URL/api/track 入库(admin.nomadro.com Events)
|
||||
* - 失败仍 200,绝不拖垮业务页
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { publishNtfy } from "~/lib/ntfy";
|
||||
import { buildTrackNtfyPayload } from "~/lib/ntfy-rich";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@ -113,15 +114,13 @@ function ntfyBudgetOk(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function shortUid(uid: string | undefined): string {
|
||||
const u = (uid || "").trim();
|
||||
if (!u) return "-";
|
||||
return u.length > 10 ? `…${u.slice(-8)}` : u;
|
||||
}
|
||||
|
||||
function siteLabel(host: string, client: string): string {
|
||||
const h = (host || "").toLowerCase();
|
||||
if (h.endsWith("nomadro.com") || client.includes("com") || client === "web_intl")
|
||||
if (
|
||||
h.endsWith("nomadro.com") ||
|
||||
client.includes("com") ||
|
||||
client === "web_intl"
|
||||
)
|
||||
return "nomadro.com";
|
||||
if (h.endsWith("nomadro.cn") || client.includes("cn")) return "nomadro.cn";
|
||||
return h || client || "web";
|
||||
@ -167,6 +166,8 @@ export async function POST(request: NextRequest) {
|
||||
openid?: string;
|
||||
client?: string;
|
||||
host?: string;
|
||||
identity?: Record<string, unknown>;
|
||||
session?: string;
|
||||
};
|
||||
const events = Array.isArray(body.events) ? body.events.slice(0, 20) : [];
|
||||
const openid = (body.openid || "").trim().slice(0, 64);
|
||||
@ -177,9 +178,11 @@ export async function POST(request: NextRequest) {
|
||||
request.headers.get("host") ||
|
||||
"";
|
||||
const site = siteLabel(host, client);
|
||||
const identity = body.identity && typeof body.identity === "object"
|
||||
? body.identity
|
||||
: {};
|
||||
let notified = 0;
|
||||
|
||||
// 并行:入库 + 关键 ntfy
|
||||
void forwardToApi({ events, openid, client });
|
||||
|
||||
for (const raw of events) {
|
||||
@ -187,25 +190,36 @@ export async function POST(request: NextRequest) {
|
||||
if (!name || !NTFY_EVENTS.has(name)) continue;
|
||||
if (!ntfyBudgetOk()) continue;
|
||||
|
||||
const page = String(raw?.page || "").slice(0, 64);
|
||||
const label = String(raw?.label || "").slice(0, 120);
|
||||
const audience =
|
||||
typeof raw?.props?.audience === "string"
|
||||
? String(raw.props.audience)
|
||||
: "";
|
||||
const parts = [`用户 ${shortUid(openid)}`, site];
|
||||
if (audience) parts.push(audience);
|
||||
if (page) parts.push(`页 ${page}`);
|
||||
if (label) parts.push(label);
|
||||
const mergedProps: Record<string, unknown> = {
|
||||
...identity,
|
||||
...(raw.props && typeof raw.props === "object" ? raw.props : {}),
|
||||
};
|
||||
if (body.session && !mergedProps.session) {
|
||||
mergedProps.session = String(body.session).slice(0, 48);
|
||||
}
|
||||
if (host && !mergedProps.host) mergedProps.host = host;
|
||||
|
||||
const title = `[${site}] ${TITLE[name] || name}`.slice(0, 80);
|
||||
const payload = buildTrackNtfyPayload({
|
||||
name,
|
||||
title,
|
||||
site,
|
||||
openid,
|
||||
client,
|
||||
event: {
|
||||
name,
|
||||
page: raw.page,
|
||||
label: raw.label,
|
||||
props: mergedProps,
|
||||
ts: raw.ts || Date.now(),
|
||||
},
|
||||
tags: TAGS[name] || "bar_chart,globe_with_meridians",
|
||||
priority: PRIORITY[name] ?? 3,
|
||||
topic: process.env.NTFY_TOPIC_COM?.trim() || undefined,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await publishNtfy({
|
||||
title: `[${site}] ${TITLE[name] || name}`.slice(0, 80),
|
||||
message: parts.join(" · ").slice(0, 400),
|
||||
tags: TAGS[name] || "bar_chart,globe_with_meridians",
|
||||
priority: PRIORITY[name] ?? 3,
|
||||
topic: process.env.NTFY_TOPIC_COM?.trim() || undefined,
|
||||
});
|
||||
const result = await publishNtfy(payload);
|
||||
if (result.ok) notified += 1;
|
||||
} catch {
|
||||
/* ignore */
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
* 读取门户写入的远程配置缓存(与 ~/lib/use-remote-config CACHE_KEY 对齐)
|
||||
* VIP 垂直仓不直接依赖门户路径,只读 localStorage。
|
||||
*/
|
||||
const WEB_CACHE_KEY = "nomadro_web_remote_config_v1";
|
||||
const WEB_CACHE_KEY = "nomadro_web_remote_config_v2";
|
||||
|
||||
export type VipRemoteCopy = {
|
||||
vipPriceFen?: number;
|
||||
@ -28,8 +28,10 @@ export function readPortalRemoteCopy(): VipRemoteCopy {
|
||||
};
|
||||
const copy = parsed?.config?.copy || {};
|
||||
const flags = parsed?.config?.flags || {};
|
||||
// 0 = 免费;禁止 `Number(x) || undefined` 把 0 吞掉后回落到 ¥0.1
|
||||
const fenRaw = Number(copy.vipPriceFen);
|
||||
return {
|
||||
vipPriceFen: Number(copy.vipPriceFen) || undefined,
|
||||
vipPriceFen: Number.isFinite(fenRaw) ? fenRaw : undefined,
|
||||
vipProductId: copy.vipProductId,
|
||||
vipCta: copy.vipCta,
|
||||
payEnabled: flags.payEnabled,
|
||||
|
||||
@ -365,11 +365,34 @@ export async function triggerPay(
|
||||
client: bundle.module.track.clientTag,
|
||||
});
|
||||
// 金额以管理后台 remote-config.copy.vipPriceFen 为准(分);测试模式固定 10 分。
|
||||
// vipPriceFen=0 是合法免费;不可用 `||` 回落,否则会误收 ¥0.1。
|
||||
const remoteFen = Number(remote.vipPriceFen);
|
||||
const safeFen =
|
||||
Number.isFinite(remoteFen) && remoteFen >= 0
|
||||
? Math.round(remoteFen)
|
||||
: getPaymentConfig().defaultAmount ?? 10;
|
||||
if (!testOn && safeFen <= 0) {
|
||||
trackPay("fail", {
|
||||
reason: "free_mode",
|
||||
audience: bundle.module.track.propAudience,
|
||||
});
|
||||
if (typeof window !== "undefined") {
|
||||
window.alert(
|
||||
bundle.module.id === "intl"
|
||||
? "This plan is free — no payment needed"
|
||||
: "当前为免费模式,无需付款",
|
||||
);
|
||||
try {
|
||||
const u = new URL(returnUrl || window.location.href);
|
||||
u.searchParams.set("join", "1");
|
||||
u.searchParams.set("free", "1");
|
||||
window.location.assign(u.toString());
|
||||
} catch {
|
||||
window.location.assign("/paid?join=1&free=1");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const totalFee = testOn ? 10 : safeFen;
|
||||
const profile = getDisplayProfile();
|
||||
const shouldShowLaunchOverlay =
|
||||
|
||||
@ -82,10 +82,18 @@ function SuccessPanel({ anonymousUserId }: { anonymousUserId: string | null }) {
|
||||
// Social join: pay first → skip VIP email panel → fill profile on /social/join
|
||||
try {
|
||||
if (hasJoinPayIntent()) {
|
||||
markJoinPaid();
|
||||
const free =
|
||||
typeof window !== "undefined" &&
|
||||
new URLSearchParams(window.location.search).get("free") === "1";
|
||||
markJoinPaid(free ? "free" : "1");
|
||||
markJoinPayIntent();
|
||||
void import("@social/lib/joinArchive")
|
||||
.then(({ archiveJoinLead }) => archiveJoinLead("pay_confirmed"))
|
||||
.then(({ archiveJoinLead }) =>
|
||||
archiveJoinLead(
|
||||
free ? "email_submit" : "pay_confirmed",
|
||||
free ? { intent: "free", priceFen: 0 } : undefined,
|
||||
),
|
||||
)
|
||||
.catch(() => undefined);
|
||||
window.location.replace(JOIN_PROFILE_RETURN);
|
||||
return;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user