Ship room-archive identity + join gates, and fix ntfy Beijing time for second timestamps.

Room archives resolve guest nick/email for admin lists; social join/date/people/coffee use clearer access gates; ntfy no longer shows 1970 when track.ts sends Unix seconds.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-05 20:52:37 +08:00
parent d830097b00
commit 83f87e5ef3
24 changed files with 1116 additions and 189 deletions

View File

@ -17,12 +17,16 @@ _BEIJING = ZoneInfo("Asia/Shanghai")
def format_beijing_time(ts: float | int | None = None) -> str:
"""Admin / ntfy 统一北京时间。"""
"""Admin / ntfy 统一北京时间。ts 兼容 Unix 秒或毫秒。"""
try:
if ts is None:
d = datetime.now(_BEIJING)
else:
d = datetime.fromtimestamp(float(ts), tz=_BEIJING)
n = float(ts)
# JS Date.now() 毫秒 ≈ 1e12+;track 常用秒 ≈ 1e9
if n >= 1e12:
n = n / 1000.0
d = datetime.fromtimestamp(n, tz=_BEIJING)
return d.strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return datetime.now(_BEIJING).strftime("%Y-%m-%d %H:%M:%S")

View File

@ -2273,6 +2273,11 @@ def admin_list_trips(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[
def _file_public_url(r: dict[str, Any]) -> str:
path = str(r.get("path") or "")
file_id = str(r.get("file_id") or r.get("id") or "")
# 身份烙在 #fragment,播放地址要剥掉
if "#" in path and (
path.startswith("http://") or path.startswith("https://") or path.startswith("/api/")
):
path = path.split("#", 1)[0]
if path.startswith("http://") or path.startswith("https://"):
return path
if path.startswith("/api/"):
@ -2301,6 +2306,8 @@ def _room_archive_status_from_row(r: dict[str, Any]) -> str:
for st in ("pending", "recording", "uploading", "failed", "denied"):
if low.startswith(f"{st}://"):
return st
if low.startswith("uploaded://"):
return "uploaded"
if path.startswith("http://") or path.startswith("https://") or path.startswith("/api/"):
return "uploaded"
if path.startswith("/var/") or path.startswith("/www/"):
@ -2319,8 +2326,15 @@ def _room_archive_meta_path(
path: str = "",
duration_sec: int = 0,
started_at: str = "",
nick: str = "",
email: str = "",
) -> str:
from urllib.parse import quote
st = (status or "pending").strip().lower()
nick_n = (nick or "").strip()[:64]
email_n = (email or "").strip().lower()[:120]
# 已上传 S3 URL:把身份烙进 fragment,列表仍可解析(不影响播放)
if st == "uploaded" and path and (
path.startswith("http://")
or path.startswith("https://")
@ -2328,10 +2342,22 @@ def _room_archive_meta_path(
or path.startswith("/var/")
or path.startswith("/www/")
):
return path
base = path.split("#", 1)[0]
frag = []
if nick_n:
frag.append(f"nick={quote(nick_n, safe='')}")
if email_n:
frag.append(f"email={quote(email_n, safe='')}")
if room_id:
frag.append(f"room={quote(str(room_id)[:80], safe='')}")
return f"{base}#{'&'.join(frag)}" if frag else base
q = []
if room_id:
q.append(f"room={room_id[:80]}")
if nick_n:
q.append(f"nick={quote(nick_n, safe='')}")
if email_n:
q.append(f"email={quote(email_n, safe='')}")
if error:
q.append(f"err={error[:120]}")
if duration_sec and int(duration_sec) > 0:
@ -2342,6 +2368,88 @@ def _room_archive_meta_path(
return f"{st}://room-archive/{session_id}{tail}"
def _parse_meta_fragment(path: str) -> dict[str, str]:
if "#" not in path:
return {}
try:
from urllib.parse import parse_qs, unquote
frag = path.split("#", 1)[1]
return {k: unquote(v[0] if v else "") for k, v in parse_qs(frag).items()}
except Exception:
return {}
def _guest_identity_index() -> dict[str, dict[str, str]]:
"""guest_id → {nick,email,name,label} from roster + join_leads + 最近聊天花名。"""
out: dict[str, dict[str, str]] = {}
def _put(gid: str, *, nick: str = "", email: str = "") -> None:
gid = (gid or "").strip()
if not gid:
return
prev = out.get(gid) or {}
n = (nick or str(prev.get("nick") or "")).strip()
em = (email or str(prev.get("email") or "")).strip().lower()
if n in {"游民", "游客", "guest", "Guest", "匿名", "用户"}:
n = str(prev.get("nick") or "")
out[gid] = {
"nick": n,
"name": n,
"email": em,
"label": n or (em.split("@")[0] if em else "") or gid[:16],
}
try:
for r in get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=5000):
_put(
str(r.get("guest_id") or ""),
nick=str(r.get("name") or ""),
email=str(r.get("email") or ""),
)
except Exception:
pass
try:
for r in get_pb().list_all(C_JOIN_LEADS, sort="-updated_at", hard_limit=5000):
_put(
str(r.get("guest_id") or ""),
nick=str(r.get("name") or ""),
email=str(r.get("email") or ""),
)
except Exception:
pass
# 聊天 nick 兜底(test15 / test14 常只在消息 author 里)
try:
for r in get_pb().list_all(C_MESSAGES, sort="-created_at", hard_limit=2000):
gid = str(r.get("guest_id") or "").strip()
if not gid:
continue
if str((out.get(gid) or {}).get("nick") or "").strip():
continue
_put(gid, nick=str(r.get("nick") or ""))
except Exception:
pass
return out
def _identity_from_archive_row(
r: dict[str, Any], id_index: dict[str, dict[str, str]] | None = None
) -> dict[str, str]:
gid = str(r.get("guest_id") or "").strip()
path = str(r.get("path") or "")
qs = _parse_meta_qs(path)
frag = _parse_meta_fragment(path)
nick = (frag.get("nick") or qs.get("nick") or "").strip()
email = (frag.get("email") or qs.get("email") or "").strip().lower()
hit = (id_index or {}).get(gid) or {}
if not nick:
nick = str(hit.get("nick") or hit.get("name") or "").strip()
if not email:
email = str(hit.get("email") or "").strip().lower()
label = nick or (email.split("@")[0] if email else "") or (gid[:16] if gid else "—")
return {"nick": nick, "email": email, "label": label, "guestId": gid}
def _parse_meta_qs(path: str) -> dict[str, str]:
if "://" not in path or "?" not in path:
# uploaded S3 URL may embed nothing; try name later
@ -2410,8 +2518,15 @@ def _room_id_from_row(r: dict[str, Any]) -> str:
return qs["room"][:120]
name = str(r.get("name") or "")
if name.startswith("room-") and ".webm" in name:
core = name[5:].split(".webm")[0]
core = core.split("__")[0]
core = name[5:].split(".webm")[0].split("__")[0]
if core.endswith("-pending"):
return core[: -len("-pending")][:120]
if core.endswith("-leave"):
return core[: -len("-leave")][:120]
# room-<roomId>-<ts>-<seq>
parts = core.rsplit("-", 2)
if len(parts) >= 3 and parts[-1].isdigit() and parts[-2].isdigit():
return "-".join(parts[:-2])[:120]
return core[:120]
return ""
@ -2431,6 +2546,114 @@ def _is_room_archive_row(r: dict[str, Any]) -> bool:
return False
def find_open_room_archive_session(
*,
guest_id: str,
channel_id: str = "",
filename: str = "",
) -> str:
"""上传丢 session_id 时:挂到同 guest 最近一条未完成的 room-archive。"""
init_pb()
gid = (guest_id or "").strip()
if not gid:
return ""
ch = (channel_id or "").strip()
# filename 仅作弱提示:room-<roomId>-...
room_hint = ""
name = (filename or "").strip()
if name.startswith("room-"):
core = name[5:].split(".webm")[0].split("__")[0]
# 去掉末尾时间戳/序号:...-1730123456789-0
parts = core.rsplit("-", 2)
if len(parts) >= 3 and parts[-1].isdigit() and parts[-2].isdigit():
room_hint = "-".join(parts[:-2])[:120]
elif core.endswith("-pending"):
room_hint = core[: -len("-pending")][:120]
else:
room_hint = core[:120]
rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=800)
open_sts = {"pending", "recording", "uploading"}
fallback = ""
for r in rows:
if not _is_room_archive_row(r):
continue
if str(r.get("guest_id") or "") != gid:
continue
st = _room_archive_status_from_row(r)
if st not in open_sts:
continue
rch = str(r.get("channel_id") or "")
if ch and rch and rch != ch:
continue
fid = str(r.get("file_id") or r.get("id") or "").strip()
if not fid:
continue
rid = _room_id_from_row(r)
if room_hint and rid and (room_hint in rid or rid in room_hint or room_hint == rid):
return fid[:80]
if not fallback:
fallback = fid[:80]
return fallback
def _supersede_sibling_open_archives(
*,
keep_session_id: str,
guest_id: str,
channel_id: str,
room_id: str = "",
) -> None:
"""同 guest+厅 已有 uploaded 时,把其它卡死的 pending/recording 标 failed。"""
gid = (guest_id or "").strip()
keep = (keep_session_id or "").strip()
if not gid or not keep:
return
ch = (channel_id or "").strip()
room = (room_id or "").strip()
try:
rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=800)
except Exception:
return
now = _now()
for r in rows:
if not _is_room_archive_row(r):
continue
fid = str(r.get("file_id") or "").strip()
if not fid or fid == keep:
continue
if str(r.get("guest_id") or "") != gid:
continue
if ch and str(r.get("channel_id") or "") not in {ch, "", "meetup-live"}:
if str(r.get("channel_id") or "") and str(r.get("channel_id") or "") != ch:
continue
rid = _room_id_from_row(r)
if room and rid and room not in rid and rid not in room:
continue
st = _room_archive_status_from_row(r)
if st not in {"pending", "recording"}:
continue
# 空壳未完成 → 被同场 uploaded 取代
try:
get_pb().upsert(
C_FILES,
filter=f"file_id={pb_quote(fid)}",
payload={
"path": _room_archive_meta_path(
"failed",
fid,
room_id=rid or room,
error="superseded by uploaded sibling",
duration_sec=_duration_from_row(r),
started_at=_parse_meta_qs(str(r.get("path") or "")).get("t0") or "",
),
"kind": "room-archive",
"updated_at": now,
},
)
except Exception:
pass
def upsert_room_archive_event(
*,
session_id: str,
@ -2446,6 +2669,8 @@ def upsert_room_archive_event(
seq: int = 0,
duration_sec: int = 0,
started_at: str = "",
nick: str = "",
email: str = "",
) -> dict[str, Any]:
"""进厅埋点 → 后台立刻可见;状态:pending/recording/uploading/uploaded/failed/denied。"""
init_pb()
@ -2459,13 +2684,32 @@ def upsert_room_archive_event(
room = (room_id or "")[:120]
dur = max(0, int(duration_sec or 0))
t0 = (started_at or "").strip()[:40]
nick_n = (nick or "").strip()[:64]
email_n = (email or "").strip().lower()[:120]
# 无显式身份时从花名册/报名补全,后台列表才能显示 test15 而非 guest_xxx
if gid and (not nick_n or not email_n):
try:
ident = _identity_from_archive_row({"guest_id": gid, "path": ""}, _guest_identity_index())
if not nick_n:
nick_n = str(ident.get("nick") or "")[:64]
if not email_n:
email_n = str(ident.get("email") or "")[:120]
except Exception:
pass
fname = (name or "").strip()[:160] or f"room-{room or ch}-{sid}.webm"
if dur > 0 and "__" not in fname and fname.endswith(".webm"):
fname = fname[:-5] + f"__{dur}s.webm"
existing = get_pb().first(C_FILES, filter=f"file_id={pb_quote(sid)}")
prev_qs = _parse_meta_qs(str((existing or {}).get("path") or ""))
prev_frag = _parse_meta_fragment(str((existing or {}).get("path") or ""))
if not t0:
t0 = prev_qs.get("t0") or ""
if not room:
room = (prev_qs.get("room") or prev_frag.get("room") or "")[:120]
if not nick_n:
nick_n = (prev_frag.get("nick") or prev_qs.get("nick") or "")[:64]
if not email_n:
email_n = (prev_frag.get("email") or prev_qs.get("email") or "")[:120]
if not dur:
try:
dur = max(0, int(prev_qs.get("dur") or 0))
@ -2481,12 +2725,16 @@ def upsert_room_archive_event(
path=path,
duration_sec=dur,
started_at=t0,
nick=nick_n,
email=email_n,
)
snap = {
"sessionId": sid,
"channelId": ch,
"guestId": gid,
"roomId": room,
"nick": nick_n,
"email": email_n,
"status": st,
"name": fname,
"size": int(size or 0),
@ -2526,17 +2774,38 @@ def upsert_room_archive_event(
prev_st = _room_archive_status_from_row(existing or {})
prev_path = str((existing or {}).get("path") or "")
if prev_st == "uploaded" and st != "uploaded":
body["path"] = prev_path
keep = _room_archive_meta_path(
"uploaded",
sid,
room_id=room,
path=prev_path.split("#", 1)[0],
nick=nick_n,
email=email_n,
duration_sec=dur,
started_at=t0,
)
body["path"] = keep
body["name"] = str((existing or {}).get("name") or body["name"])
st = "uploaded"
final_path = prev_path
final_path = keep
if st == "uploaded" and not (
final_path.startswith("http")
or final_path.startswith("/api/")
or final_path.startswith("/var")
or final_path.startswith("/www")
):
body["path"] = prev_path or final_path
keep_src = (prev_path or final_path).split("#", 1)[0]
body["path"] = _room_archive_meta_path(
"uploaded",
sid,
room_id=room,
path=keep_src,
nick=nick_n,
email=email_n,
duration_sec=dur,
started_at=t0,
)
final_path = body["path"]
# 已上传真文件时把时长烙进文件名,方便列表展示
if st == "uploaded" and dur > 0:
nm = str(body.get("name") or "")
@ -2544,17 +2813,31 @@ def upsert_room_archive_event(
body["name"] = nm[:-5] + f"__{dur}s.webm"
get_pb().upsert(C_FILES, filter=f"file_id={pb_quote(sid)}", payload=body)
if st == "uploaded":
try:
_supersede_sibling_open_archives(
keep_session_id=sid,
guest_id=body.get("guest_id") or gid,
channel_id=ch,
room_id=room or _room_id_from_row({**body, "path": final_path}),
)
except Exception:
pass
play = ""
if st == "uploaded":
play = _file_public_url({**body, "file_id": sid})
if "://" in play and not play.startswith("http") and not play.startswith("/api/"):
play = ""
label = nick_n or (email_n.split("@")[0] if email_n else "") or (gid[:16] if gid else "")
return {
"ok": True,
"sessionId": sid,
"status": st,
"channelId": ch,
"guestId": gid,
"guestNick": nick_n,
"guestEmail": email_n,
"guestLabel": label,
"roomId": room,
"name": body.get("name") or fname,
"size": body["size"],
@ -2608,6 +2891,10 @@ def admin_list_room_archives(
gone = _soft_deleted_ids("files") | _soft_deleted_ids("room_archives")
needle = (q or "").strip().lower()
items = []
from datetime import datetime, timezone
now_utc = datetime.now(timezone.utc)
id_index = _guest_identity_index()
for r in rows:
fid = str(r.get("file_id") or r.get("id") or "")
rid = str(r.get("id") or "")
@ -2621,20 +2908,21 @@ def admin_list_room_archives(
continue
st = _room_archive_status_from_row(r)
dur = _duration_from_row(r)
age = 0.0
try:
raw = str(r.get("created_at") or "").replace("Z", "+00:00")
start = datetime.fromisoformat(raw)
if start.tzinfo is None:
start = start.replace(tzinfo=timezone.utc)
age = (now_utc - start).total_seconds()
except Exception:
age = 0.0
# 空壳「上传中」超过 2 分钟视为失败(离厅未真正传完)
if st == "uploading" and int(r.get("size") or 0) <= 0:
try:
from datetime import datetime, timezone
raw = str(r.get("created_at") or "").replace("Z", "+00:00")
start = datetime.fromisoformat(raw)
if start.tzinfo is None:
start = start.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - start).total_seconds()
if age > 120:
st = "failed"
except Exception:
pass
if st == "uploading" and int(r.get("size") or 0) <= 0 and age > 120:
st = "failed"
# 卡死「待上传/录制中」超过 30 分钟 → 失败(人已走、没录像)
if st in {"pending", "recording"} and age > 1800:
st = "failed"
play = ""
if st == "uploaded":
play = _file_public_url(r)
@ -2642,6 +2930,11 @@ def admin_list_room_archives(
"://" in play and not play.startswith("http") and not play.startswith("/api/")
):
play = ""
room = _room_id_from_row(r)
# 厅 id 也可能在 S3 URL fragment
if not room:
room = (_parse_meta_fragment(str(r.get("path") or "")).get("room") or "")[:120]
ident = _identity_from_archive_row(r, id_index)
items.append(
{
"id": r.get("id"),
@ -2649,7 +2942,12 @@ def admin_list_room_archives(
"sessionId": r.get("file_id") or r.get("id") or "",
"channelId": r.get("channel_id") or "",
"guestId": r.get("guest_id") or "",
"roomId": _room_id_from_row(r),
"guestNick": ident.get("nick") or "",
"guestEmail": ident.get("email") or "",
"guestLabel": ident.get("label") or "",
"nick": ident.get("nick") or "",
"email": ident.get("email") or "",
"roomId": room,
"kind": "room-archive",
"status": st,
"statusLabel": {
@ -2671,12 +2969,44 @@ def admin_list_room_archives(
"at": r.get("created_at") or "",
}
)
# 同 guest + room/channel:已有「已上传」则隐藏被取代的空壳 pending/recording
uploaded_keys: set[str] = set()
for x in items:
if x.get("status") != "uploaded":
continue
g = str(x.get("guestId") or "")
room = str(x.get("roomId") or "")
ch = str(x.get("channelId") or "")
if g and room:
uploaded_keys.add(f"{g}|r|{room}")
if g and ch:
uploaded_keys.add(f"{g}|c|{ch}")
if uploaded_keys:
pruned = []
for x in items:
st = str(x.get("status") or "")
# 同场已有已上传:藏空壳 pending/recording,以及被 supersede 的空 failed
if st in {"pending", "recording", "failed"} and int(x.get("size") or 0) <= 0 and not x.get("url"):
g = str(x.get("guestId") or "")
room = str(x.get("roomId") or "")
ch = str(x.get("channelId") or "")
if (g and room and f"{g}|r|{room}" in uploaded_keys) or (
g and ch and f"{g}|c|{ch}" in uploaded_keys
):
continue
pruned.append(x)
items = pruned
if needle:
items = [
x
for x in items
if needle in str(x.get("name") or "").lower()
or needle in str(x.get("guestId") or "").lower()
or needle in str(x.get("guestNick") or "").lower()
or needle in str(x.get("guestEmail") or "").lower()
or needle in str(x.get("guestLabel") or "").lower()
or needle in str(x.get("channelId") or "").lower()
or needle in str(x.get("status") or "").lower()
or needle in str(x.get("statusLabel") or "").lower()

View File

@ -685,6 +685,8 @@ class RoomArchiveEventIn(BaseModel):
seq: int = Field(default=0, ge=0)
durationSec: int = Field(default=0, ge=0)
startedAt: str = Field(default="", max_length=40)
nick: str = Field(default="", max_length=64)
email: str = Field(default="", max_length=120)
@router.post("/room-archives/events")
@ -712,6 +714,8 @@ async def room_archive_event(
seq=body.seq,
duration_sec=body.durationSec,
started_at=body.startedAt,
nick=body.nick,
email=body.email,
)
try:
@ -728,6 +732,8 @@ async def upload_file(
file: UploadFile = File(...),
kind: str = Form(default="file"),
session_id: str = Form(default=""),
session_id_q: str | None = Query(default=None, alias="session_id"),
kind_q: str | None = Query(default=None, alias="kind"),
x_social_guest_id: str | None = Header(default=None),
guest: str | None = Query(default=None),
):
@ -738,6 +744,8 @@ async def upload_file(
if len(raw) > SOCIAL_UPLOAD_MAX_BYTES:
raise HTTPException(status_code=413, detail="file too large")
mime = file.content_type or "application/octet-stream"
# Form 丢字段时用 query 兜底(本地 Next rewrite → 线上 API 曾丢 session_id)
kind = (kind or kind_q or "file").strip() or "file"
guessed = kind
if guessed in {"room-archive", "meetup-archive"}:
guessed = "video"
@ -749,12 +757,22 @@ async def upload_file(
elif mime.startswith("audio/"):
guessed = "audio"
sid = (session_id or "").strip()[:80]
sid = ((session_id or session_id_q or "").strip())[:80]
# 语音/视频厅静默存档 → SeaweedFS S3;元数据 path 写公网 URL
if kind in {"room-archive", "meetup-archive"} or (
guessed == "video" and (file.filename or "").startswith("room-")
):
# 无 session 时:挂到该 guest 最近一条未完成的 room-archive,避免孤儿「已上传」
if not sid:
try:
store.init_db()
sid = store.find_open_room_archive_session(
guest_id=peer, channel_id=channel_id, filename=file.filename or ""
) or ""
except Exception:
sid = ""
if sid:
try:
store.init_db()

View File

@ -977,6 +977,21 @@ def upsert_join_lead(
)
def find_open_room_archive_session(
*,
guest_id: str,
channel_id: str = "",
filename: str = "",
) -> str:
from social_svc import pb_data
return pb_data.find_open_room_archive_session(
guest_id=guest_id,
channel_id=channel_id,
filename=filename,
)
def upsert_room_archive_event(
*,
session_id: str,
@ -992,6 +1007,8 @@ def upsert_room_archive_event(
seq: int = 0,
duration_sec: int = 0,
started_at: str = "",
nick: str = "",
email: str = "",
) -> dict:
from social_svc import pb_data
@ -1009,6 +1026,8 @@ def upsert_room_archive_event(
seq=seq,
duration_sec=duration_sec,
started_at=started_at,
nick=nick,
email=email,
)

View File

@ -23,7 +23,11 @@ export function looksLikeUrl(v: unknown): v is string {
}
export function resolveMediaUrl(raw: string): string {
const s = raw.trim()
let s = raw.trim()
// 身份烙在 #nick= / #email=,<video src> 带 hash 会黑屏 0:00
if ((s.startsWith('http://') || s.startsWith('https://') || s.startsWith('/')) && s.includes('#')) {
s = s.split('#', 1)[0]
}
if (s.startsWith('data:') || s.startsWith('https://') || s.startsWith('http://')) return s
// social IM / 录像挂在门户同域,不在 api.nomadro.com
if (s.startsWith('/api/social/')) return `https://nomadro.com${s}`
@ -71,7 +75,13 @@ export function MediaValue({ value, fieldKey = '', label, compact }: Props) {
return (
<figure className={`com-media ${compact ? 'com-media-sm' : ''}`}>
{label ? <figcaption>{label}</figcaption> : null}
<video src={src} controls playsInline preload="metadata" />
<video
src={src}
controls
playsInline
preload="metadata"
crossOrigin="anonymous"
/>
<a className="com-media-link" href={src} target="_blank" rel="noreferrer">
打开视频
</a>

View File

@ -1154,7 +1154,27 @@ export default function Social() {
<code>{short(row.channelId, 12)}</code>
</td>
<td>
<code className="com-id">{short(row.guestId, 12)}</code>
{section === 'roomArchives' &&
(row.guestLabel || row.guestNick || row.nick) ? (
<div>
<strong>
{short(
String(row.guestLabel || row.guestNick || row.nick),
18,
)}
</strong>
{row.guestEmail ? (
<div className="com-muted" style={{ fontSize: 11 }}>
{short(String(row.guestEmail), 22)}
</div>
) : null}
<div className="com-muted" style={{ fontSize: 10 }}>
<code className="com-id">{short(row.guestId, 12)}</code>
</div>
</div>
) : (
<code className="com-id">{short(row.guestId, 12)}</code>
)}
</td>
<td>{fmtTime(row.at)}</td>
</>

View File

@ -59,7 +59,12 @@ function shortUid(uid: string | undefined): string {
}
function fmtTime(ts?: number): string {
const d = ts && Number.isFinite(ts) ? new Date(ts) : new Date();
// track.ts 发的是 Unix 秒;Date 要毫秒。兼容误传毫秒。
let d = new Date();
if (ts != null && Number.isFinite(ts)) {
const n = Number(ts);
d = new Date(n < 1e12 ? n * 1000 : n);
}
try {
const stamp = new Intl.DateTimeFormat("zh-CN", {
timeZone: "Asia/Shanghai",

View File

@ -16,8 +16,9 @@ import {
canUseTrial,
consumeTrial,
resolveTrialLimits,
trialPaywallHint,
} from "@social/lib/socialTrial";
import { openSocialJoinModal } from "@social/lib/joinModal";
import { resolveJoinAccessGate } from "@social/lib/joinFlow";
import { useSocialConfig } from "@social/components/SocialExperience";
import "./coffee.css";
@ -99,10 +100,28 @@ export default function CoffeeBookPage({
return () => controller.abort();
}, [loadSlots]);
function openCoffeeJoinGate() {
const gate = resolveJoinAccessGate("coffee");
setErr(null);
if (gate.kind === "continue") {
router.push(gate.href);
return;
}
// 游客:直接弹加入/注册,别只甩一句红字
openSocialJoinModal({
reason: "gate",
hint: socialTx(
gate.kind === "join-modal"
? gate.hint
: "约咖啡前请先加入社区,填邮箱即可开始",
),
});
}
async function submit() {
if (!slot || !name.trim() || submitting.current || loadingSlots || slotsFor !== day) return;
if (!canUseTrial("coffeeBookings", trialLimits)) {
setErr(socialTx(trialPaywallHint("coffeeBookings")));
openCoffeeJoinGate();
return;
}
submitting.current = true;

View File

@ -403,7 +403,8 @@ html[data-theme="light"] .social-ambient {
}
.social-date-deck {
width: min(100%, 420px);
aspect-ratio: 3 / 4.15;
/* 高度由 interaction.css 用剩余视口计算;勿再强制 aspect-ratio */
aspect-ratio: auto;
max-height: min(68dvh, 640px);
}
.social-date-card {
@ -440,7 +441,7 @@ html[data-theme="light"] .social-ambient {
}
.social-date-actions {
gap: 18px;
margin-top: 18px;
margin-top: 4px;
}
.social-date-act {
width: 64px;

View File

@ -2675,7 +2675,9 @@
padding-bottom: calc(12px + 72px + env(safe-area-inset-bottom, 0px));
}
.social-date-root .social-date-deck {
height: min(520px, calc(100dvh - 300px));
height: auto;
max-height: min(520px, calc(100dvh - 300px));
aspect-ratio: auto;
}
.social-mobile-dock a {
display: flex;

View File

@ -820,11 +820,12 @@
font-size: 11px;
}
.social-date-root .social-date-bar-tools {
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
flex: 0 0 auto;
gap: 8px;
}
.social-date-root .social-date-filters {
width: 100%;
}
.social-date-root .social-date-stage {
padding: 4px 12px 0;
}
@ -837,8 +838,10 @@
width: 100%;
max-width: 420px;
margin-inline: auto;
height: min(52dvh, 480px);
min-height: 300px;
height: auto;
max-height: min(52dvh, 480px);
min-height: 260px;
aspect-ratio: auto;
}
.social-date-card.is-top {
touch-action: none;
@ -865,10 +868,6 @@
width: 66px;
height: 66px;
}
.social-date-root .social-date-bar-tools .social-filters {
flex: 1;
min-width: 0;
}
.social-date-root .social-date-bar-tools .social-btn {
flex: 0 0 auto;
min-height: 36px;
@ -1536,10 +1535,9 @@ html[data-theme="light"] .social-mobile-dock a[aria-current="page"] {
}
.social-chat-live .social-composer-toolbar button[type="submit"] { order: 2; margin-left: auto; }
.social-date-root {
height: auto;
max-height: none;
overflow-x: clip;
overflow-y: visible;
height: 100dvh;
max-height: 100dvh;
overflow: hidden;
}
.social-meetup-live .social-live-video { overflow-y: auto; overscroll-behavior: contain; }
.social-meetup-live .social-live-gate { flex: 1 0 auto; min-height: min-content; }

View File

@ -1605,18 +1605,60 @@
/* —— Date / 约会 swipe deck —— */
.social-date-root {
display: flex;
flex-direction: column;
height: 100dvh;
max-height: 100dvh;
overflow: hidden;
background:
radial-gradient(ellipse 70% 45% at 50% 0%, rgba(255, 107, 107, 0.16), transparent 60%),
var(--sc-bg, #0a0e17);
}
.social-date-bar {
flex-shrink: 0;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 10px;
padding-bottom: 10px;
}
.social-date-bar-top {
display: flex;
flex-wrap: nowrap;
align-items: center;
justify-content: space-between;
gap: 12px;
min-width: 0;
}
.social-date-bar-top .social-live-bar-main {
flex: 1 1 auto;
min-width: 0;
flex-wrap: nowrap;
}
.social-date-bar-tools {
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
gap: 10px;
gap: 8px;
flex: 0 0 auto;
}
.social-date-filters {
display: flex;
flex-wrap: nowrap;
align-items: center;
gap: 8px;
width: 100%;
overflow-x: auto;
scrollbar-width: none;
-webkit-overflow-scrolling: touch;
}
.social-date-filters::-webkit-scrollbar {
display: none;
}
.social-date-filters button {
flex: 0 0 auto;
min-height: 36px;
padding: 0 14px;
}
.social-date-stage {
flex: 1;
@ -1624,15 +1666,23 @@
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 18px;
padding: 12px 16px 24px;
justify-content: flex-start;
gap: 12px;
padding: 8px 16px 16px;
overflow: hidden;
}
.social-date-deck {
position: relative;
/* 绝对定位卡片不撑高;靠 flex 吃满舞台剩余高度 */
flex: 1 1 0;
align-self: center;
width: min(420px, 100%);
height: min(620px, calc(100dvh - 220px));
min-height: 420px;
min-height: 280px;
max-height: min(620px, calc(100dvh - 210px));
aspect-ratio: auto;
/* 裁掉飞出残留,避免 PC 左侧鬼影 */
overflow: hidden;
isolation: isolate;
}
.social-date-card {
position: absolute;
@ -1645,10 +1695,12 @@
touch-action: none;
user-select: none;
will-change: transform;
backface-visibility: hidden;
}
.social-date-card.is-next {
transform: scale(0.96) translateY(12px);
opacity: 0.75;
z-index: 1;
transform: scale(0.96) translateY(10px);
opacity: 0.72;
pointer-events: none;
}
.social-date-card.is-top {
@ -1660,21 +1712,32 @@
cursor: grabbing;
transition: none;
}
.social-date-card.is-leaving {
z-index: 4;
pointer-events: none;
transition: none;
}
.social-date-card.is-fly-like {
animation: social-date-fly-like 0.28s ease-in forwards;
animation: social-date-fly-like 0.3s ease-in forwards;
}
.social-date-card.is-fly-pass {
animation: social-date-fly-pass 0.28s ease-in forwards;
animation: social-date-fly-pass 0.3s ease-in forwards;
}
@keyframes social-date-fly-like {
from {
opacity: 1;
}
to {
transform: translate3d(130vw, 40px, 0) rotate(28deg);
transform: translate3d(120%, 40px, 0) rotate(18deg);
opacity: 0;
}
}
@keyframes social-date-fly-pass {
from {
opacity: 1;
}
to {
transform: translate3d(-130vw, 40px, 0) rotate(-28deg);
transform: translate3d(-120%, 40px, 0) rotate(-18deg);
opacity: 0;
}
}
@ -1821,9 +1884,10 @@
}
.social-date-online-pill {
position: absolute;
top: 18px;
left: 50%;
transform: translateX(-50%);
top: 14px;
left: 14px;
right: auto;
transform: none;
z-index: 2;
padding: 5px 12px;
border-radius: 999px;
@ -1834,6 +1898,10 @@
letter-spacing: 0.02em;
box-shadow: 0 8px 20px rgba(34, 197, 94, 0.35);
}
.social-date-photo-dots ~ .social-date-online-pill,
.social-date-card:has(.social-date-photo-dots) .social-date-online-pill {
top: 28px;
}
.social-date-bio {
display: -webkit-box;
-webkit-line-clamp: 2;
@ -1845,9 +1913,11 @@
}
.social-date-actions {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
gap: 18px;
margin-top: 0;
}
.social-date-act {
display: grid;
@ -1904,12 +1974,14 @@
}
.social-date-likes {
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
justify-content: center;
gap: 10px;
flex-shrink: 0;
width: min(420px, 100%);
padding: 10px 14px;
max-width: 100%;
padding: 8px 14px;
border-radius: 999px;
border: 1px solid rgba(255, 107, 107, 0.28);
background: rgba(255, 107, 107, 0.08);
@ -1975,9 +2047,12 @@
pointer-events: none;
}
@media (max-width: 640px) {
.social-date-root {
padding-bottom: calc(72px + env(safe-area-inset-bottom, 0px));
}
.social-date-deck {
height: min(560px, calc(100dvh - 240px));
min-height: 380px;
max-height: min(520px, calc(100dvh - 280px));
min-height: 260px;
}
.social-date-act {
width: 58px;
@ -1987,12 +2062,22 @@
width: 66px;
height: 66px;
}
}
@media (prefers-reduced-motion: reduce) {
.social-date-card.is-top,
.social-date-card.is-fly-like,
.social-date-card.is-fly-pass {
transition: none;
animation: none;
.social-date-hint {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.social-date-card.is-top {
transition: none;
}
/* 离场仍瞬时消失,靠 JS timeout / onAnimationEnd 清掉,禁止卡在半空 */
.social-date-card.is-fly-like,
.social-date-card.is-fly-pass {
animation: social-date-fly-instant 1ms linear forwards;
}
}
@keyframes social-date-fly-instant {
to {
opacity: 0;
}
}

View File

@ -1186,11 +1186,14 @@ html[data-theme="light"] .social-workspace .nav-group-panel {
@media (prefers-reduced-motion: reduce) {
.social-burst-float,
.social-video-tile.is-ghost,
.social-home .social-date-hero-card,
.social-date-root .social-date-card {
.social-home .social-date-hero-card {
animation: none !important;
transition: none !important;
}
/* 约会离场动画由 interaction.css 接管,勿全局杀掉导致鬼影卡死 */
.social-date-root .social-date-card.is-top {
transition: none !important;
}
}
/* —— H5 / mobile first polish —— */
@ -1332,18 +1335,18 @@ html[data-theme="light"] .social-workspace .nav-group-panel {
}
.social-date-root .social-date-bar {
flex-wrap: wrap;
gap: 8px;
padding: 10px 12px;
}
.social-date-root .social-date-bar-tools {
width: 100%;
justify-content: space-between;
.social-date-root .social-date-bar-top {
gap: 8px;
}
.social-date-root .social-date-deck {
width: min(100%, 420px);
height: min(58dvh, 560px);
min-height: 360px;
height: auto;
max-height: min(58dvh, 560px);
min-height: 280px;
aspect-ratio: auto;
}
.social-date-root .social-date-actions {
gap: 14px;

View File

@ -21,6 +21,7 @@ import {
import SocialAvatar from "./SocialAvatar";
import { ShareButton, SocialDialog } from "./SocialUI";
import { SocialMobileDock } from "./SocialNavigation";
import JoinPayModal from "./JoinPayModal";
import type { SocialRosterMember } from "@social/lib/rosterMock";
import { useDiscoveryRoster, SELF_MEMBER_ID } from "@social/lib/discoveryRoster";
import { socialPath } from "@social/lib/socialPath";
@ -29,6 +30,8 @@ import { useLocalState } from "@social/lib/useLocalState";
import { socialApi } from "@social/lib/api";
import { loadJson } from "@social/lib/storage";
import { socialTx } from "@social/lib/socialTx";
import { openSocialJoinModal } from "@social/lib/joinModal";
import { resolveJoinAccessGate } from "@social/lib/joinFlow";
import {
canUseTrial,
consumeTrial,
@ -36,6 +39,7 @@ import {
trialPaywallHint,
} from "@social/lib/socialTrial";
import { useSocialConfig } from "./SocialExperience";
import { useRouter } from "next/navigation";
type Filter = "all" | "f" | "m";
type Decision = "like" | "pass";
@ -58,6 +62,7 @@ function shuffle<T>(list: T[]) {
}
export default function DateClient() {
const router = useRouter();
const config = useSocialConfig();
const trialLimits = resolveTrialLimits(config);
// Dating: never show profiles whose avatar has no detected face
@ -85,25 +90,58 @@ export default function DateClient() {
const history = useMemo<HistoryEntry[]>(() => storedHistory.length ? storedHistory : Object.entries(swipes).map(([id, decision]) => ({ id, decision })), [storedHistory, swipes]);
const [order, setOrder] = useState<string[]>([]);
const [drag, setDrag] = useState({ x: 0, y: 0, active: false });
const [fly, setFly] = useState<null | { id: string; dir: Decision }>(null);
/** 已切走、正在飞出的卡(与 current 分离,避免叠层鬼影) */
const [leaving, setLeaving] = useState<null | {
member: SocialRosterMember;
dir: Decision;
}>(null);
const [toast, setToast] = useState("");
const [matchId, setMatchId] = useState<string | null>(null);
const [likesOpen, setLikesOpen] = useState(false);
const [joinOpen, setJoinOpen] = useState(false);
const [joinHint, setJoinHint] = useState(() =>
socialTx(trialPaywallHint("dateViews")),
);
const start = useRef({ x: 0, y: 0 });
const dragging = useRef(false);
const dragRef = useRef({ x: 0, y: 0 });
const pointerIdRef = useRef<number | null>(null);
const topCardRef = useRef<HTMLElement | null>(null);
const busy = useRef(false);
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const swipeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const leaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (toastTimer.current) clearTimeout(toastTimer.current);
if (swipeTimer.current) clearTimeout(swipeTimer.current);
if (leaveTimer.current) clearTimeout(leaveTimer.current);
},
[],
);
// HMR / 异常中断后 busy 可能卡死;leaving 清空时强制解锁
useEffect(() => {
if (!leaving) busy.current = false;
}, [leaving]);
useEffect(() => {
busy.current = false;
}, []);
const releasePointer = useCallback(() => {
const el = topCardRef.current;
const pid = pointerIdRef.current;
if (el && pid != null) {
try {
if (el.hasPointerCapture?.(pid)) el.releasePointerCapture(pid);
} catch {
/* ignore */
}
}
pointerIdRef.current = null;
dragging.current = false;
}, []);
const deck = useMemo(() => {
const ids = [...order, ...roster.map((member) => member.id).filter((id) => !order.includes(id))];
return ids
@ -136,46 +174,85 @@ export default function DateClient() {
toastTimer.current = setTimeout(() => setToast(""), 1600);
}, []);
const finishLeaving = useCallback(() => {
if (leaveTimer.current) {
clearTimeout(leaveTimer.current);
leaveTimer.current = null;
}
setLeaving((prev) => (prev ? null : prev));
busy.current = false;
}, []);
const commit = useCallback(
(member: SocialRosterMember, decision: Decision) => {
if (busy.current || fly) return;
if (leaving || busy.current) return;
if (!canUseTrial("dateViews", trialLimits)) {
flash(socialTx(trialPaywallHint("dateViews")));
releasePointer();
setDrag({ x: 0, y: 0, active: false });
dragRef.current = { x: 0, y: 0 };
const gate = resolveJoinAccessGate("date");
if (gate.kind === "continue") {
router.push(gate.href);
return;
}
const hint = socialTx(
gate.kind === "join-modal" ? gate.hint : trialPaywallHint("dateViews"),
);
setJoinHint(hint);
setJoinOpen(true);
openSocialJoinModal({ reason: "gate", hint });
return;
}
busy.current = true;
setFly({ id: member.id, dir: decision });
releasePointer();
dragRef.current = { x: 0, y: 0 };
setDrag({ x: 0, y: 0, active: false });
// 立刻从牌堆移除,顶卡换成下一位;离场卡单独飞出
consumeTrial("dateViews", trialLimits);
setSwipes((prev) => ({ ...prev, [member.id]: decision }));
setHistory((prev) => [
...prev,
{ id: member.id, decision, previouslyLiked: Boolean(likes[member.id]) },
]);
setLeaving({ member, dir: decision });
try {
navigator.vibrate?.(decision === "like" ? [12, 30, 12] : 8);
} catch {
/* ignore */
}
swipeTimer.current = setTimeout(() => {
consumeTrial("dateViews", trialLimits);
setSwipes((prev) => ({ ...prev, [member.id]: decision }));
setHistory((prev) => [...prev, { id: member.id, decision, previouslyLiked: Boolean(likes[member.id]) }]);
if (decision === "like") {
setRosterLike(member.id, true);
setMatchId(member.id);
flash(`想认识 ${member.name}`);
const me = loadJson<{ name?: string }>("roster", {});
void socialApi
.notifyLike(member.id, me.name || "游民")
.catch(() => undefined);
} else {
flash("已跳过");
}
setFly(null);
setDrag({ x: 0, y: 0, active: false });
dragRef.current = { x: 0, y: 0 };
busy.current = false;
}, 280);
if (decision === "like") {
setRosterLike(member.id, true);
setMatchId(member.id);
flash(`想认识 ${member.name}`);
const me = loadJson<{ name?: string }>("roster", {});
void socialApi
.notifyLike(member.id, me.name || "游民")
.catch(() => undefined);
} else {
flash("已跳过");
}
if (leaveTimer.current) clearTimeout(leaveTimer.current);
leaveTimer.current = setTimeout(finishLeaving, 320);
},
[fly, setSwipes, setHistory, flash, likes, trialLimits],
[
leaving,
setSwipes,
setHistory,
flash,
likes,
trialLimits,
releasePointer,
finishLeaving,
router,
],
);
const undo = useCallback(() => {
if (busy.current || fly || !history.length) return;
if (busy.current || leaving || !history.length) return;
const last = history[history.length - 1];
setHistory(history.slice(0, -1));
setSwipes((prev) => {
@ -185,21 +262,29 @@ export default function DateClient() {
});
if (last.decision === "like") setRosterLike(last.id, Boolean(last.previouslyLiked));
setMatchId(null);
setLeaving(null);
setDrag({ x: 0, y: 0, active: false });
dragRef.current = { x: 0, y: 0 };
flash("已撤销");
}, [history, fly, setSwipes, setHistory, flash]);
}, [history, leaving, setSwipes, setHistory, flash]);
const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
if ((event.target as HTMLElement).closest("button, a, input") || event.button !== 0) return;
if (!current || fly || busy.current) return;
if (!current || leaving || busy.current) return;
dragging.current = true;
topCardRef.current = event.currentTarget;
pointerIdRef.current = event.pointerId;
start.current = { x: event.clientX, y: event.clientY };
event.currentTarget.setPointerCapture(event.pointerId);
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
/* ignore */
}
setDrag({ x: 0, y: 0, active: true });
};
const onPointerMove = (event: ReactPointerEvent<HTMLElement>) => {
if (!dragging.current || !current || fly) return;
if (!dragging.current || !current || leaving || busy.current) return;
const nextDrag = {
x: event.clientX - start.current.x,
y: (event.clientY - start.current.y) * 0.35,
@ -209,13 +294,16 @@ export default function DateClient() {
};
const onPointerUp = () => {
if (!dragging.current || !current || fly) return;
dragging.current = false;
if (!dragging.current || !current || leaving || busy.current) {
releasePointer();
return;
}
const x = dragRef.current.x;
const threshold =
typeof window !== "undefined" && window.matchMedia("(max-width: 900px)").matches
? THRESHOLD_MOBILE
: THRESHOLD_DESKTOP;
releasePointer();
if (x > threshold) commit(current, "like");
else if (x < -threshold) commit(current, "pass");
else {
@ -225,13 +313,14 @@ export default function DateClient() {
};
const resetDeck = () => {
if (swipeTimer.current) clearTimeout(swipeTimer.current);
if (leaveTimer.current) clearTimeout(leaveTimer.current);
releasePointer();
setSwipes({});
setHistory([]);
setOrder(shuffle(roster.map((m) => m.id)));
setDrag({ x: 0, y: 0, active: false });
dragRef.current = { x: 0, y: 0 };
setFly(null);
setLeaving(null);
setMatchId(null);
setLikesOpen(false);
busy.current = false;
@ -265,6 +354,7 @@ export default function DateClient() {
return () => window.removeEventListener("keydown", onKey);
}, [current, commit, undo, likesOpen, matchId]);
const locked = Boolean(leaving) || busy.current;
const rotate = drag.x / 18;
const stampThreshold =
typeof window !== "undefined" &&
@ -276,52 +366,53 @@ export default function DateClient() {
return (
<div className="social-root social-live-root social-skin social-date-root">
<header className="social-live-bar social-date-bar">
<div className="social-live-bar-main">
<Link href={socialPath("/")} className="social-nav-back">
<ArrowLeft size={14} />
{socialTx("首页")}
</Link>
<div>
<strong>{socialTx("约会")}</strong>
<p className="social-muted">
左滑跳过 · 右滑想认识
{totalForFilter
? ` · 还剩 ${remaining}/${totalForFilter}`
: ""}
</p>
<div className="social-date-bar-top">
<div className="social-live-bar-main">
<Link href={socialPath("/")} className="social-nav-back">
<ArrowLeft size={14} />
{socialTx("首页")}
</Link>
<div>
<strong>{socialTx("约会")}</strong>
<p className="social-muted">
{totalForFilter
? `还剩 ${remaining}/${totalForFilter}`
: socialTx("左滑跳过 · 右滑想认识")}
</p>
</div>
</div>
<div className="social-date-bar-tools">
{liked.length > 0 ? (
<button
type="button"
className="social-btn"
onClick={() => setLikesOpen(true)}
>
<Heart size={14} />
想认识 {liked.length}
</button>
) : null}
<ShareButton path={socialPath("/date")} title={socialTx("游民社区 · 约会")} />
</div>
</div>
<div className="social-date-bar-tools">
<div className="social-filters" aria-label={socialTx("筛选")}>
{(
[
["all", "全部"],
["f", "👩 女生"],
["m", "👨 男生"],
] as const
).map(([id, label]) => (
<button
key={id}
type="button"
className={filter === id ? "active" : ""}
aria-pressed={filter === id}
onClick={() => setFilter(id)}
>
{label}
</button>
))}
</div>
{liked.length > 0 ? (
<div className="social-filters social-date-filters" aria-label={socialTx("筛选")}>
{(
[
["all", "全部"],
["f", "女生"],
["m", "男生"],
] as const
).map(([id, label]) => (
<button
key={id}
type="button"
className="social-btn"
onClick={() => setLikesOpen(true)}
className={filter === id ? "active" : ""}
aria-pressed={filter === id}
onClick={() => setFilter(id)}
>
<Heart size={14} />
想认识 {liked.length}
{label}
</button>
) : null}
<ShareButton path={socialPath("/date")} title={socialTx("游民社区 · 约会")} />
))}
</div>
</header>
@ -378,39 +469,62 @@ export default function DateClient() {
)}
{next && (
<article className="social-date-card is-next" aria-hidden inert>
<article
key={`next-${next.id}`}
className="social-date-card is-next"
aria-hidden
inert
>
<DateCardFace member={next} />
</article>
)}
{current && (
<article
className={`social-date-card is-top${drag.active ? " is-dragging" : ""}${fly ? ` is-fly-${fly.dir}` : ""}`}
style={
fly
? undefined
: {
transform: `translate3d(${drag.x}px, ${drag.y}px, 0) rotate(${rotate}deg)`,
}
}
key={`top-${current.id}`}
ref={(el) => {
topCardRef.current = el;
}}
className={`social-date-card is-top${drag.active ? " is-dragging" : ""}`}
style={{
transform: `translate3d(${drag.x}px, ${drag.y}px, 0) rotate(${rotate}deg)`,
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={() => {
dragging.current = false;
releasePointer();
dragRef.current = { x: 0, y: 0 };
setDrag({ x: 0, y: 0, active: false });
}}
>
<span
className="social-date-stamp like"
style={{ opacity: fly?.dir === "like" ? 1 : likeOpacity }}
style={{ opacity: likeOpacity }}
>
{socialTx("想认识")}
</span>
<DateCardFace member={current} />
</article>
)}
{leaving && (
<article
key={`leave-${leaving.member.id}`}
className={`social-date-card is-leaving is-fly-${leaving.dir}`}
aria-hidden
inert
onAnimationEnd={finishLeaving}
>
<span
className="social-date-stamp like"
style={{ opacity: leaving.dir === "like" ? 1 : 0 }}
>
{socialTx("想认识")}
</span>
<DateCardFace member={leaving.member} />
</article>
)}
</div>
<p className="social-date-hint is-alive" aria-hidden={!current}>
@ -421,7 +535,7 @@ export default function DateClient() {
<button
type="button"
className="social-date-act pass"
disabled={!current || Boolean(fly)}
disabled={!current || locked}
aria-label={socialTx("跳过")}
onClick={() => current && commit(current, "pass")}
>
@ -430,7 +544,7 @@ export default function DateClient() {
<button
type="button"
className="social-date-act reset"
disabled={!history.length}
disabled={!history.length || locked}
aria-label={socialTx("撤销上一次")}
onClick={undo}
>
@ -439,7 +553,7 @@ export default function DateClient() {
<button
type="button"
className="social-date-act like"
disabled={!current || Boolean(fly)}
disabled={!current || locked}
aria-label={socialTx("想认识")}
onClick={() => current && commit(current, "like")}
>
@ -580,6 +694,11 @@ export default function DateClient() {
</div>
</SocialDialog>
) : null}
<JoinPayModal
open={joinOpen}
onClose={() => setJoinOpen(false)}
hint={joinHint}
/>
<SocialMobileDock />
</div>
);

View File

@ -17,6 +17,8 @@ import { socialTx } from "@social/lib/socialTx";
type Props = {
open: boolean;
onClose: () => void;
/** 触发原因文案,如约会试玩用尽 */
hint?: string;
};
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@ -31,11 +33,14 @@ function resolvePriceFen(raw: unknown): number | null {
/**
* 加群:填邮箱 → 付费调支付 / 免费直接进资料
*/
export default function JoinPayModal({ open, onClose }: Props) {
return open ? <JoinPaySheet onClose={onClose} /> : null;
export default function JoinPayModal({ open, onClose, hint }: Props) {
return open ? <JoinPaySheet onClose={onClose} hint={hint} /> : null;
}
function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
function JoinPaySheet({
onClose,
hint,
}: Pick<Props, "onClose" | "hint">) {
const titleId = useId();
const descriptionId = useId();
const errorId = useId();
@ -191,13 +196,15 @@ function JoinPaySheet({ onClose }: Pick<Props, "onClose">) {
<h2 id={titleId} className="social-join-title">
{socialTx("加入游民社区")}
</h2>
{!isFree ? (
<p id={descriptionId} className="social-muted">
{priceSyncing
? socialTx("正在同步后台最新价格…")
: socialTx("填写邮箱后继续支付")}
</p>
) : null}
<p id={descriptionId} className="social-muted">
{hint
? socialTx(hint)
: !isFree
? priceSyncing
? socialTx("正在同步后台最新价格…")
: socialTx("填写邮箱后继续支付")
: socialTx("填邮箱即可继续,资料下一步再完善")}
</p>
<label className="social-join-field">
{socialTx("邮箱")}

View File

@ -1,8 +1,8 @@
"use client";
import { useMemo, useState } from "react";
import { useMemo, useState, useSyncExternalStore, type MouseEvent } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useRouter, useSearchParams } from "next/navigation";
import { Sparkles } from "lucide-react";
import SiteShell from "./SiteShell";
import SocialAvatar from "./SocialAvatar";
@ -18,6 +18,17 @@ import { SOCIAL_CITIES } from "@social/lib/cities";
import { socialPath } from "@social/lib/socialPath";
import { useRosterLikes } from "@social/lib/useRosterLikes";
import { socialTx } from "@social/lib/socialTx";
import { openSocialJoinModal } from "@social/lib/joinModal";
import { resolvePeopleProfileGate } from "@social/lib/joinFlow";
import {
getCommunityUnlockServerSnapshot,
getCommunityUnlockSnapshot,
subscribeLivenessState,
} from "@social/lib/livenessGate";
import {
getSocialSession,
subscribeSocialSession,
} from "@social/lib/socialSession";
const PROFESSION_HINTS = ["设计", "开发", "内容", "产品", "摄影", "全栈"];
const INTEREST_HINTS = ["咖啡局", "冲浪", "瑜伽", "夜跑", "出海", "开源"];
@ -47,6 +58,7 @@ function PeopleDirectory({
initialHere: boolean;
initialSoon: boolean;
}) {
const router = useRouter();
const roster = useDiscoveryRoster();
const [query, setQuery] = useState(initialQuery);
const [filter, setFilter] = useState("all");
@ -56,6 +68,33 @@ function PeopleDirectory({
const [currentlyHere, setCurrentlyHere] = useState(initialHere);
const [arrivingSoon, setArrivingSoon] = useState(initialSoon);
const likes = useRosterLikes();
const unlocked =
useSyncExternalStore(
subscribeLivenessState,
getCommunityUnlockSnapshot,
getCommunityUnlockServerSnapshot,
) === "1";
// 邮箱会话变化时重算 gate(已登录 → 完善资料,而非再弹注册)
useSyncExternalStore(
subscribeSocialSession,
() => getSocialSession()?.email || "",
() => "",
);
const openProfile = (event: MouseEvent, personId: string) => {
if (personId === SELF_MEMBER_ID || unlocked) return;
event.preventDefault();
const gate = resolvePeopleProfileGate();
if (gate.kind === "allow") return;
if (gate.kind === "continue") {
router.push(gate.href);
return;
}
openSocialJoinModal({
reason: "gate",
hint: socialTx(gate.hint),
});
};
const list = useMemo(
() =>
@ -235,6 +274,7 @@ function PeopleDirectory({
href={socialPath(`/people/${person.id}`)}
className={`social-people-chip social-chip-pop is-rich reveal${person.online ? " is-online" : ""}`}
style={{ ["--stagger" as string]: `${Math.min(index, 12) * 40}ms` }}
onClick={(event) => openProfile(event, person.id)}
>
<span className="social-people-chip-ava">
<SocialAvatar

View File

@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useState, useSyncExternalStore } from "react";
import Link from "next/link";
import {
ArrowLeft,
@ -33,6 +33,17 @@ import { socialApi } from "@social/lib/api";
import { loadJson } from "@social/lib/storage";
import { socialPath } from "@social/lib/socialPath";
import { socialTx } from "@social/lib/socialTx";
import { openSocialJoinModal } from "@social/lib/joinModal";
import { resolvePeopleProfileGate } from "@social/lib/joinFlow";
import {
getCommunityUnlockServerSnapshot,
getCommunityUnlockSnapshot,
subscribeLivenessState,
} from "@social/lib/livenessGate";
import {
getSocialSession,
subscribeSocialSession,
} from "@social/lib/socialSession";
type ReviewSummary = {
count: number;
@ -60,9 +71,42 @@ export default function PeopleProfileClient({ id }: { id: string }) {
const likes = useRosterLikes();
const [reviews, setReviews] = useState<ReviewSummary | null>(null);
const unlocked =
useSyncExternalStore(
subscribeLivenessState,
getCommunityUnlockSnapshot,
getCommunityUnlockServerSnapshot,
) === "1";
useSyncExternalStore(
subscribeSocialSession,
() => getSocialSession()?.email || "",
() => "",
);
const gate = resolvePeopleProfileGate();
const canView =
unlocked ||
gate.kind === "allow" ||
!member ||
member.id === SELF_MEMBER_ID;
useEffect(() => {
if (!member || member.id === SELF_MEMBER_ID) return;
if (canView || !member) return;
if (gate.kind === "join-modal") {
openSocialJoinModal({
reason: "gate",
hint: socialTx(gate.hint),
});
return;
}
if (gate.kind === "continue") {
// 已有邮箱:强制跳去完善资料 / 核验
window.location.assign(gate.href);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- kind/href 驱动一次跳转
}, [canView, member, gate.kind]);
useEffect(() => {
if (!member || member.id === SELF_MEMBER_ID || !canView) return;
void socialApi
.getReviews(member.id)
.then((r) =>
@ -73,7 +117,7 @@ export default function PeopleProfileClient({ id }: { id: string }) {
}),
)
.catch(() => setReviews(null));
}, [member]);
}, [member, canView]);
if (!member) {
return (
@ -91,6 +135,46 @@ export default function PeopleProfileClient({ id }: { id: string }) {
);
}
if (!canView) {
const title =
gate.kind === "continue"
? socialTx(gate.title)
: gate.kind === "join-modal"
? socialTx(gate.title)
: socialTx("注册后查看完整资料");
const hint =
gate.kind === "continue" || gate.kind === "join-modal"
? socialTx(gate.hint)
: socialTx("查看完整资料前,请先注册加入社区");
return (
<SiteShell title={socialTx("想见的人")}>
<EmptyState emoji="🔒" title={title} description={hint}>
{gate.kind === "continue" ? (
<Link className="social-btn primary" href={gate.href}>
{socialTx(gate.title)}
</Link>
) : (
<button
type="button"
className="social-btn primary"
onClick={() =>
openSocialJoinModal({
reason: "gate",
hint,
})
}
>
{socialTx("加入社区")}
</button>
)}
<Link className="social-btn" href={socialPath("/people")}>
{socialTx("回去看看大家")}
</Link>
</EmptyState>
</SiteShell>
);
}
const liked = !!likes[member.id];
const cityKey = member.city.split(/[·/]/)[0].trim();
const similar = roster

View File

@ -56,6 +56,7 @@ export default function SiteShell({
const [menuOpen, setMenuOpen] = useState(false);
const [scrolled, setScrolled] = useState(false);
const [loginOpen, setLoginOpen] = useState(false);
const [joinHint, setJoinHint] = useState<string | undefined>(undefined);
const pathname = usePathname();
const menuId = useId();
const menuButtonRef = useRef<HTMLButtonElement>(null);
@ -79,7 +80,10 @@ export default function SiteShell({
};
useEffect(() => {
return subscribeSocialJoinModal(() => setLoginOpen(true));
return subscribeSocialJoinModal((detail) => {
setJoinHint(detail.hint || undefined);
setLoginOpen(true);
});
}, []);
useEffect(() => {
@ -300,7 +304,14 @@ export default function SiteShell({
);
const authModal = (
<JoinPayModal open={loginOpen} onClose={() => setLoginOpen(false)} />
<JoinPayModal
open={loginOpen}
hint={joinHint}
onClose={() => {
setLoginOpen(false);
setJoinHint(undefined);
}}
/>
);
if (home) {

View File

@ -288,6 +288,8 @@ export const socialApi = {
seq?: number;
durationSec?: number;
startedAt?: string;
nick?: string;
email?: string;
}) =>
req<{
ok?: boolean;
@ -309,6 +311,8 @@ export const socialApi = {
seq: body.seq || 0,
durationSec: body.durationSec || 0,
startedAt: body.startedAt || "",
nick: body.nick || "",
email: body.email || "",
},
}),

View File

@ -1,5 +1,11 @@
/** Social join: pay first, then complete profile. */
import {
isCommunityUnlocked,
isLivenessVerified,
} from "./livenessGate";
import { isSocialLoggedIn } from "./socialSession";
export const JOIN_PENDING_PROFILE_KEY = "social-join-pending-profile";
export const JOIN_PAID_KEY = "social-join-paid";
export const JOIN_PROFILE_DONE_KEY = "social-join-profile-done";
@ -178,6 +184,107 @@ export function isJoinPaid(): boolean {
*/
export { isCommunityUnlocked as isJoinUnlocked } from "./livenessGate";
export type PeopleProfileGate =
| { kind: "allow" }
/** 游客:弹注册 */
| { kind: "join-modal"; title: string; hint: string }
/** 已有邮箱:强制去完成资料 / 核验 / 支付 */
| { kind: "continue"; href: string; title: string; hint: string };
export type JoinGatePurpose = "people" | "coffee" | "date";
const JOIN_GATE_COPY: Record<
JoinGatePurpose,
{
guestTitle: string;
guestHint: string;
profileHint: string;
liveHint: string;
payHint: string;
avatarHint: string;
}
> = {
people: {
guestTitle: "注册后查看完整资料",
guestHint: "查看完整资料前,请先注册加入社区",
profileHint: "你已登录,请先填写个人资料再查看其他人",
liveHint: "完成自拍确认后即可查看其他人资料",
payHint: "你已登录邮箱,请继续完成加入后再查看资料",
avatarHint: "补全头像等资料后即可查看其他人",
},
coffee: {
guestTitle: "加入社区后预约咖啡聊",
guestHint: "约咖啡前请先加入社区,填邮箱即可开始",
profileHint: "你已登录,请先填写个人资料再预约咖啡聊",
liveHint: "完成自拍确认后即可预约咖啡聊",
payHint: "你已登录邮箱,请继续完成加入后再预约",
avatarHint: "补全头像等资料后即可预约咖啡聊",
},
date: {
guestTitle: "加入社区后继续认识人",
guestHint: "今日免费额度用完了。注册加入社区,继续认识同频的人",
profileHint: "你已登录,请先填写个人资料再继续约会",
liveHint: "完成自拍确认后即可继续约会",
payHint: "你已登录邮箱,请继续完成加入后再继续",
avatarHint: "补全头像等资料后即可继续约会",
},
};
/**
* 约会 / 想见的人 / 咖啡聊等拦截:
* - 未登录 → 注册弹窗
* - 已有邮箱但未完成加入 → 跳转完善资料(或支付 / 本人确认)
*/
export function resolveJoinAccessGate(
purpose: JoinGatePurpose = "people",
): PeopleProfileGate {
const copy = JOIN_GATE_COPY[purpose];
if (isCommunityUnlocked()) return { kind: "allow" };
if (!isSocialLoggedIn()) {
return {
kind: "join-modal",
title: copy.guestTitle,
hint: copy.guestHint,
};
}
// 已有邮箱:优先强制完善资料(未付费时 join 页会自行拦到支付步)
if (!isJoinProfileDone()) {
return {
kind: "continue",
href: JOIN_PROFILE_RETURN,
title: "请先完善资料",
hint: copy.profileHint,
};
}
if (!isLivenessVerified()) {
return {
kind: "continue",
href: JOIN_LIVENESS_RETURN,
title: "请先完成本人确认",
hint: copy.liveHint,
};
}
if (!isJoinPaid()) {
return {
kind: "continue",
href: "/social/join",
title: "继续完成加入",
hint: copy.payHint,
};
}
return {
kind: "continue",
href: JOIN_PROFILE_RETURN,
title: "请先完善资料",
hint: copy.avatarHint,
};
}
/** @deprecated 用 resolveJoinAccessGate("people") */
export function resolvePeopleProfileGate(): PeopleProfileGate {
return resolveJoinAccessGate("people");
}
export function isJoinProfileDone(): boolean {
try {
return localStorage.getItem(JOIN_PROFILE_DONE_KEY) === "1";

View File

@ -5,6 +5,8 @@ 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";
/** 弹窗说明,如「查看资料前请先注册」 */
hint?: string;
};
export function openSocialJoinModal(detail: OpenJoinModalDetail = {}): void {

View File

@ -393,7 +393,45 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"Say hi and meet a few people. Want more? Just join.",
"想继续聊下去?加入社区就行": "Want to keep chatting? Join the community",
"想再多认识几个人?加入社区吧": "Want to meet more people? Join the community",
"今日免费额度用完了。注册加入社区,继续认识同频的人":
"Today's free swipes are used up. Join to keep meeting people",
"填邮箱即可继续,资料下一步再完善":
"Enter your email to continue — profile comes next",
"查看完整资料前,请先注册加入社区":
"Join the community to view full profiles",
"注册后查看完整资料": "Join to view full profiles",
"继续完成加入": "Finish joining",
"你已登录邮箱,请继续完成加入后再查看资料":
"You're signed in — finish joining to view profiles",
"请先完善资料": "Complete your profile first",
"你已登录,请先填写个人资料再查看其他人":
"You're signed in — fill in your profile to view others",
"请先完成本人确认": "Verify yourself first",
"完成自拍确认后即可查看其他人资料":
"Finish selfie verification to view profiles",
"补全头像等资料后即可查看其他人":
"Add your photo and details to view others",
"约咖啡前,先加入社区": "Join before booking coffee",
"约咖啡前请先加入社区,填邮箱即可开始":
"Join the community to book coffee — email is enough to start",
"加入社区后预约咖啡聊": "Join to book coffee chats",
"你已登录,请先填写个人资料再预约咖啡聊":
"You're signed in — complete your profile to book coffee",
"完成自拍确认后即可预约咖啡聊":
"Finish selfie verification to book coffee",
"你已登录邮箱,请继续完成加入后再预约":
"You're signed in — finish joining to book",
"补全头像等资料后即可预约咖啡聊":
"Add your photo and details to book coffee",
"加入社区后继续认识人": "Join to keep meeting people",
"你已登录,请先填写个人资料再继续约会":
"You're signed in — complete your profile to keep dating",
"完成自拍确认后即可继续约会":
"Finish selfie verification to keep dating",
"你已登录邮箱,请继续完成加入后再继续":
"You're signed in — finish joining to continue",
"补全头像等资料后即可继续约会":
"Add your photo and details to keep dating",
"想接着逛?先加入社区": "Want to keep exploring? Join first",
"想用更多功能,先加入社区": "Join to unlock more",
"登录": "Log in",

View File

@ -122,7 +122,7 @@ export function trialPaywallHint(action: TrialAction): string {
case "chatMessages":
return "想继续聊下去?加入社区就行";
case "dateViews":
return "想再多认识几个人?加入社区吧";
return "今日免费额度用完了。注册加入社区,继续认识同频的人";
case "coffeeBookings":
return "约咖啡前,先加入社区";
case "mapOpens":

View File

@ -211,7 +211,8 @@ export async function POST(request: NextRequest) {
page: raw.page,
label: raw.label,
props: mergedProps,
ts: raw.ts || Date.now(),
// track 客户端发 Unix 秒;缺省也用秒,交给 ntfy-rich 统一换算
ts: Number(raw.ts) > 0 ? Number(raw.ts) : Date.now() / 1000,
},
tags: TAGS[name] || "bar_chart,globe_with_meridians",
priority: PRIORITY[name] ?? 3,