nomadro/src/modules/social/lib/api.ts
Eric 344886172d Fix join leads so portal writes reach PocketBase for admin.
Await same-origin social forward and fall back when portal only stored local JSON.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 19:27:06 +08:00

872 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { loadJson, saveJson, uid } from "./storage";
const BASE = "/api/social/v1";
const GUEST_KEY = "guest-id";
export function getGuestId(): string {
let id = loadJson<string>(GUEST_KEY, "");
if (!id) {
id = uid("guest");
saveJson(GUEST_KEY, id);
}
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>(
path: string,
init?: RequestInit & { json?: unknown; ttlMs?: number },
): Promise<T> {
const method = (init?.method || "GET").toUpperCase();
const ttl = init?.ttlMs || 0;
const cacheKey = ttl > 0 && method === "GET" ? `${method}:${path}` : "";
if (cacheKey) {
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;
if (init?.json !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.json);
}
const { ttlMs: _ttlMs, json: _json, ...rest } = init || {};
const res = await fetch(`${BASE}${path}`, {
...rest,
headers,
body,
cache: "no-store",
signal: init?.signal || AbortSignal.timeout(8000),
});
if (!res.ok) {
const err = await res.text().catch(() => "");
let msg = err || `HTTP ${res.status}`;
try {
const parsed = JSON.parse(err) as { detail?: unknown };
if (typeof parsed.detail === "string") msg = parsed.detail;
else if (Array.isArray(parsed.detail)) {
msg = parsed.detail
.map((d) =>
typeof d === "object" && d && "msg" in d
? String((d as { msg: string }).msg)
: String(d),
)
.join("; ");
}
} catch {
/* keep raw */
}
throw new Error(msg);
}
const data = (await res.json()) as T;
if (cacheKey) _memTtl.set(cacheKey, { at: Date.now(), data });
return data;
}
export type SocialRealtimeToken = {
ok: boolean;
enabled: boolean;
wsUrl: string;
token: string;
channel: string;
};
export const socialApi = {
health: () =>
req<{ ok: boolean; isolated?: boolean; centrifugo?: boolean }>("/health"),
realtimeToken: (channelId: string) =>
req<SocialRealtimeToken>(
`/realtime/token?channel_id=${encodeURIComponent(channelId)}`,
),
channelDesc: (channelId: string) =>
req<{
channelId: string;
seq: number;
recv: number;
read: number;
unread: number;
online?: number;
peers?: Array<{ guestId: string; nick: string }>;
}>(`/channels/${encodeURIComponent(channelId)}/desc`),
presence: (channelId: string, nick?: string) =>
req<{
channelId: string;
online: number;
peers: Array<{ guestId: string; nick: string }>;
}>(`/channels/${encodeURIComponent(channelId)}/presence`, {
method: "POST",
json: { nick: nick || "游民" },
}),
/** Global who's-online heartbeat (social shell). */
rosterPresence: (opts?: {
nick?: string;
city?: string;
avatar?: string;
softStatusSync?: boolean;
}) =>
req<{
channelId: string;
online: number;
peers: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
cityOnline?: number;
cityPeers?: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
}>("/roster/presence", {
method: "POST",
json: {
nick: opts?.nick || "游民",
city: opts?.city || "",
avatar: opts?.avatar || "",
softStatusSync: opts?.softStatusSync !== false,
},
}),
rosterOnline: (opts?: { city?: string; limit?: number }) => {
const q = new URLSearchParams();
if (opts?.city) q.set("city", opts.city);
if (opts?.limit) q.set("limit", String(opts.limit));
const qs = q.toString();
return req<{
ok: boolean;
online: number;
peers: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
city?: string;
cityOnline?: number;
cityPeers?: Array<{
guestId: string;
nick: string;
city?: string;
avatar?: string;
}>;
}>(`/roster/online${qs ? `?${qs}` : ""}`, { ttlMs: 0 });
},
listMessages: (
channelId: string,
opts?: { limit?: number; since?: number; before?: number; q?: string },
) => {
const q = new URLSearchParams();
if (opts?.limit) q.set("limit", String(opts.limit));
if (opts?.since != null) q.set("since", String(opts.since));
if (opts?.before != null) q.set("before", String(opts.before));
if (opts?.q) q.set("q", opts.q);
const qs = q.toString();
return req<{
items: import("./types").SocialChatMessage[];
seq?: number;
}>(
`/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ""}`,
);
},
sendMessage: (
channelId: string,
author: string,
text: string,
clientId?: string,
extra?: {
replyTo?: import("./types").SocialChatReplyTo | null;
attachments?: import("./types").SocialChatAttachment[];
mentions?: string[];
},
) =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages`,
{
method: "POST",
json: {
author,
text,
clientId,
replyTo: extra?.replyTo || undefined,
attachments: extra?.attachments || [],
mentions: extra?.mentions || [],
},
},
),
editMessage: (channelId: string, msgId: string, text: string) =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}`,
{ method: "PATCH", json: { text } },
),
recallMessage: (channelId: string, msgId: string) =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/recall`,
{ method: "POST", json: {} },
),
reactMessage: (channelId: string, msgId: string, emoji: string) =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/react`,
{ method: "POST", json: { emoji } },
),
pinMessage: (channelId: string, msgId: string, pinned = true) =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/pin`,
{ method: "POST", json: { pinned } },
),
reportMessage: (channelId: string, msgId: string, reason = "") =>
req<import("./types").SocialChatMessage>(
`/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/report`,
{ method: "POST", json: { reason } },
),
upload: async (channelId: string, file: File, kind?: string) => {
const form = new FormData();
form.append("file", file);
form.append("kind", kind || "file");
const res = await fetch(
`${BASE}/channels/${encodeURIComponent(channelId)}/upload`,
{
method: "POST",
headers: { "X-Social-Guest-Id": getGuestId() },
body: form,
cache: "no-store",
signal: AbortSignal.timeout(60000),
},
);
if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`));
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",
seq = 0,
) =>
req<{ ok?: boolean; what: string; seq?: number; recv?: number; read?: number }>(
`/channels/${encodeURIComponent(channelId)}/notes`,
{ method: "POST", json: { what, seq } },
),
listReviews: (cafeId: string) =>
req<{
items: Array<{
id: string;
cafeId: string;
author: string;
score: number;
text: string;
photoNote?: string;
at: string;
}>;
}>(`/cafes/${encodeURIComponent(cafeId)}/reviews`, { ttlMs: 30_000 }),
postReview: (
cafeId: string,
payload: {
author: string;
score: number;
text: string;
photoNote?: string;
},
) =>
req(`/cafes/${encodeURIComponent(cafeId)}/reviews`, {
method: "POST",
json: payload,
}),
getRoster: () => req<{ item: Record<string, string> | null }>("/roster/me"),
saveRoster: (payload: Record<string, string>) =>
req("/roster/me", { method: "PUT", json: payload }),
/** Ranked public profiles: same-city → online → tag match. */
discoveryRoster: (opts?: {
city?: string;
limit?: number;
/** Dating feed — server hides avatars without a detected face. */
requireFace?: boolean;
}) => {
const q = new URLSearchParams();
if (opts?.city) q.set("city", opts.city);
if (opts?.limit) q.set("limit", String(opts.limit));
if (opts?.requireFace) q.set("requireFace", "1");
const qs = q.toString();
return req<{
ok: boolean;
viewerCity: string;
count: number;
requireFace?: boolean;
items: Array<{
guestId: string;
name: string;
title: string;
city: string;
skills: string;
bio: string;
avatar: string;
gender: string;
intents: string;
availability: string;
status: string;
lookingFor: string;
online: boolean;
tags: string[];
score: number;
updatedAt: string;
linktree?: string;
faceOk?: boolean;
}>;
// Dating face filter must not stick on stale cached faceOk=true
}>(`/roster/discovery${qs ? `?${qs}` : ""}`, {
ttlMs: opts?.requireFace ? 0 : 20_000,
});
},
/** Live challenge: front + turn frames + full camera recording for audit. */
uploadAvatarChallenge: async (
front: Blob,
turn: Blob,
video?: Blob | null,
videoMime = "video/webm",
) => {
const form = new FormData();
// Explicit File+MIME — bare Blob parts often become application/octet-stream
const frontFile =
front instanceof File && front.type.startsWith("image/")
? front
: new File([front], "front.jpg", { type: "image/jpeg" });
const turnFile =
turn instanceof File && turn.type.startsWith("image/")
? turn
: new File([turn], "turn.jpg", { type: "image/jpeg" });
form.append("front", frontFile);
form.append("turn", turnFile);
if (video && video.size > 0) {
const ext = videoMime.includes("mp4") ? "mp4" : "webm";
const vFile =
video instanceof File
? video
: new File([video], `liveness.${ext}`, {
type: videoMime || "video/webm",
});
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(),
...(email ? { "X-Social-Email": email } : {}),
},
body: form,
cache: "no-store",
signal: AbortSignal.timeout(120000),
});
if (!res.ok) {
let msg = "";
try {
const body = (await res.json()) as { detail?: unknown };
if (typeof body?.detail === "string") msg = body.detail;
} catch {
msg = await res.text().catch(() => "");
}
throw new Error(msg || `核验失败 HTTP ${res.status}`);
}
return (await res.json()) as {
ok: boolean;
url: string;
avatarUrl?: string;
object_key: string;
storage?: string;
livenessStatus?: string;
faceOk?: boolean;
videoUrl?: string;
frontUrl?: string;
turnUrl?: string;
auditId?: string;
challenge?: {
similarity?: number;
yaw_delta?: number;
};
};
},
/** Image → SeaweedFS S3 (s3.nomadro.com) via social_svc; local fallback. */
uploadAvatar: async (file: File, purpose = "avatar") => {
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(),
...(email ? { "X-Social-Email": email } : {}),
},
body: form,
cache: "no-store",
signal: AbortSignal.timeout(60000),
});
if (!res.ok) {
let msg = "";
try {
const body = (await res.json()) as { detail?: unknown };
if (typeof body?.detail === "string") msg = body.detail;
else if (Array.isArray(body?.detail)) {
msg = body.detail
.map((d) =>
typeof d === "string"
? d
: d && typeof d === "object" && "msg" in d
? String((d as { msg: unknown }).msg)
: "",
)
.filter(Boolean)
.join("; ");
}
} catch {
msg = await res.text().catch(() => "");
}
throw new Error(msg || `上传失败 HTTP ${res.status}`);
}
return (await res.json()) as {
ok: boolean;
url: string;
object_key: string;
storage?: string;
faceOk?: boolean;
faceCheckEnabled?: boolean;
livenessRequired?: boolean;
face?: { ok: boolean; faces: number; engine: string };
};
},
/** 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.
* Prefer portal (local file + server-side forward to SOCIAL_API_URL).
* Never hard-hit production from localhost — that polluted admin.nomadro.com
* and created duplicate leads during local QA.
*/
postJoinLead: async (payload: {
email: string;
stage?: string;
name?: string;
paid?: string;
faceOk?: string;
livenessStatus?: string;
ua?: string;
payload?: Record<string, unknown>;
}) => {
const body = { ...payload, guestId: getGuestId() };
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Social-Guest-Id": getGuestId(),
};
// Portal first (server forwards via SOCIAL_API_URL); social rewrite as fallback.
const urls = ["/api/portal/join-leads", `${BASE}/join/leads`];
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;
}
const data = (await res.json()) as {
ok: boolean;
id?: string;
email?: string;
stage?: string;
stored?: string;
forwarded?: boolean;
};
// Portal may return ok with only local JSON — admin reads PB.
// Keep trying social rewrite until a PB write succeeds.
if (data?.ok === false) continue;
if (
url.startsWith("/api/portal/join-leads") &&
data?.forwarded !== true &&
data?.stored === "local"
) {
lastErr = "portal local-only; try social";
continue;
}
return data;
} catch (e) {
lastErr = e instanceof Error ? e.message : String(e);
}
}
throw new Error(lastErr || "join lead failed");
},
applyGig: (
gigId: string,
payload: { name: string; contact: string; note?: string },
) =>
req(`/gigs/${encodeURIComponent(gigId)}/apply`, {
method: "POST",
json: payload,
}),
mapCities: (bbox?: {
west: number;
south: number;
east: number;
north: number;
}) => {
const q = new URLSearchParams();
if (bbox) {
q.set("west", String(bbox.west));
q.set("south", String(bbox.south));
q.set("east", String(bbox.east));
q.set("north", String(bbox.north));
}
const qs = q.toString();
return req<{ items: import("./geoTypes").SocialMapCity[]; source?: string }>(
`/map/cities${qs ? `?${qs}` : ""}`,
{ ttlMs: 20_000 },
);
},
citiesSearch: (
q: string,
opts?: { limit?: number; lang?: string; signal?: AbortSignal },
) => {
const sp = new URLSearchParams({ q });
if (opts?.limit) sp.set("limit", String(opts.limit));
if (opts?.lang) sp.set("lang", opts.lang);
return req<{ items: import("./geoTypes").SocialMapCity[]; q: string }>(
`/cities/search?${sp}`,
{ signal: opts?.signal },
);
},
cityDetail: (cityId: string) =>
req<{
item: import("./geoTypes").SocialMapCity & {
recentArrivals?: Array<{
guestId: string;
city: string;
status: string;
arrival_date: string;
departure_date: string;
}>;
};
}>(`/cities/${encodeURIComponent(cityId)}`, { ttlMs: 30_000 }),
peopleGeo: (opts?: {
city?: string;
cityId?: string;
currentlyHere?: boolean;
arrivingSoon?: boolean;
profession?: string;
interest?: string;
language?: string;
}) => {
const sp = new URLSearchParams();
if (opts?.city) sp.set("city", opts.city);
if (opts?.cityId) sp.set("cityId", opts.cityId);
if (opts?.currentlyHere) sp.set("currentlyHere", "true");
if (opts?.arrivingSoon) sp.set("arrivingSoon", "true");
if (opts?.profession) sp.set("profession", opts.profession);
if (opts?.interest) sp.set("interest", opts.interest);
if (opts?.language) sp.set("language", opts.language);
const qs = sp.toString();
return req<{
items: Array<{
guestId: string;
city: string;
cityId: string;
status: string;
arrival_date: string;
departure_date: string;
h3Res: string;
}>;
}>(`/people${qs ? `?${qs}` : ""}`);
},
travelOverlaps: () =>
req<{ items: import("./geoTypes").TravelOverlap[] }>("/travel-overlaps"),
listTrips: () =>
req<{ items: import("./geoTypes").SocialTrip[] }>("/trips"),
createTrip: (payload: {
city: string;
city_id?: string;
country?: string;
lat?: number;
lng?: number;
arrival_date?: string;
departure_date?: string;
visibility?: string;
status?: string;
}) =>
req<{ item: import("./geoTypes").SocialTrip }>("/trips", {
method: "POST",
json: payload,
}),
updateTrip: (
tripId: string,
payload: Partial<{
city: string;
city_id: string;
country: string;
lat: number;
lng: number;
arrival_date: string;
departure_date: string;
visibility: string;
status: string;
}>,
) =>
req<{ item: import("./geoTypes").SocialTrip }>(
`/trips/${encodeURIComponent(tripId)}`,
{ method: "PATCH", json: payload },
),
deleteTrip: (tripId: string) =>
req<{ ok: boolean }>(`/trips/${encodeURIComponent(tripId)}`, {
method: "DELETE",
}),
listSkills: (opts?: { city?: string; limit?: number }) => {
const q = new URLSearchParams();
if (opts?.city) q.set("city", opts.city);
if (opts?.limit) q.set("limit", String(opts.limit));
const qs = q.toString();
return req<{
ok: boolean;
items: Array<{
id: string;
guestId: string;
author: string;
city: string;
offer: string;
want: string;
note: string;
status: string;
createdAt: string;
}>;
}>(`/skills${qs ? `?${qs}` : ""}`, { ttlMs: 15_000 });
},
createSkill: (payload: {
author: string;
city: string;
offer: string;
want: string;
note?: string;
}) => req("/skills", { method: "POST", json: payload }),
closeSkill: (id: string) =>
req(`/skills/${encodeURIComponent(id)}/close`, { method: "POST" }),
postMeetupReview: (payload: {
toGuest: string;
toName?: string;
bookingId?: string;
punctuality: number;
chemistry: number;
professionalism: number;
text?: string;
}) => req("/reviews", { method: "POST", json: payload }),
getReviews: (guestId: string) =>
req<{
ok: boolean;
count: number;
averages: {
punctuality: number;
chemistry: number;
professionalism: number;
overall: number;
} | null;
items: Array<{
id: string;
punctuality: number;
chemistry: number;
professionalism: number;
text: string;
avg: number;
createdAt: string;
}>;
}>(`/reviews/${encodeURIComponent(guestId)}`, { ttlMs: 20_000 }),
blockUser: (blockedGuest: string, reason?: string) =>
req("/blocks", {
method: "POST",
json: { blockedGuest, reason: reason || "" },
}),
unblockUser: (blockedGuest: string) =>
req(`/blocks/${encodeURIComponent(blockedGuest)}`, { method: "DELETE" }),
listBlocks: () =>
req<{ ok: boolean; items: Array<{ blockedGuest: string; reason: string }> }>(
"/blocks",
),
reportUser: (payload: {
targetGuest: string;
targetName?: string;
reason: string;
detail?: string;
}) => req("/reports", { method: "POST", json: payload }),
notifyLike: (toGuest: string, fromName: string) =>
req("/social-events/like", {
method: "POST",
json: { toGuest, fromName },
}),
notifyBoardJoin: (ownerGuest: string, actorName: string, boardTitle: string) =>
req("/social-events/board-join", {
method: "POST",
json: { ownerGuest, actorName, boardTitle },
}),
getWrapped: (year?: number) => {
const q = year ? `?year=${year}` : "";
return req<{
ok: boolean;
year: number;
name: string;
homeCity: string;
cities: string[];
cityCount: number;
peopleMet: number;
meetups: number;
skillPosts: number;
livenessVerified: boolean;
}>(`/wrapped${q}`);
},
fireCityDigest: (city: string, weekly = false) =>
req("/digests/city", {
method: "POST",
json: { city, weekly },
}),
};