Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API. Co-authored-by: Cursor <cursoragent@cursor.com>
539 lines
18 KiB
TypeScript
539 lines
18 KiB
TypeScript
"use client";
|
||
|
||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||
import Link from "next/link";
|
||
import { useRouter } from "next/navigation";
|
||
import { resolveMirotalkUrl, SEED_CHANNELS } from "@social/lib/seed";
|
||
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 { EmptyState } from "./SocialUI";
|
||
import { socialTx } from "@social/lib/socialTx";
|
||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||
import { txMeetup } from "@social/lib/localizeEntity";
|
||
import {
|
||
startSilentRoomArchive,
|
||
type SilentRecorderHandle,
|
||
} from "@social/lib/silentRoomRecorder";
|
||
|
||
type Layout = "split" | "video" | "chat";
|
||
|
||
/**
|
||
* 自研 MiroTalk 厅 URL;只作 iframe src。
|
||
* 必须带 name=:跳过「进入房间」昵称弹窗,直接进语音/视频画面。
|
||
* audio/video=1 强制开麦开摄像头(服务端 checkInitConfig 已按 URL 覆盖 mute 记忆)。
|
||
*/
|
||
function joinUrl(room: string, name: string) {
|
||
const nick = (name || "guest").trim().slice(0, 32) || "guest";
|
||
const q = new URLSearchParams({
|
||
room,
|
||
name: nick,
|
||
notify: "0",
|
||
chat: "0",
|
||
audio: "1",
|
||
video: "1",
|
||
});
|
||
return `${resolveMirotalkUrl().replace(/\/$/, "")}/join?${q.toString()}`;
|
||
}
|
||
|
||
/** Same-origin only: pre-fill MiroTalk init nick input. */
|
||
function seedMirotalkNick(name: string) {
|
||
try {
|
||
const nick = (name || "").trim();
|
||
if (!nick || typeof window === "undefined") return;
|
||
const origin = new URL(resolveMirotalkUrl()).origin;
|
||
if (origin !== window.location.origin) return;
|
||
window.localStorage.setItem("peer_name", nick);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
|
||
function warmMirotalkOrigin() {
|
||
try {
|
||
const origin = new URL(resolveMirotalkUrl()).origin;
|
||
// Same-origin portal already warm; still prefetch assets path
|
||
for (const rel of ["dns-prefetch", "preconnect"] as const) {
|
||
if (document.querySelector(`link[rel="${rel}"][href="${origin}"]`))
|
||
continue;
|
||
const link = document.createElement("link");
|
||
link.rel = rel;
|
||
link.href = origin;
|
||
if (rel === "preconnect") link.crossOrigin = "anonymous";
|
||
document.head.appendChild(link);
|
||
}
|
||
void fetch(`${origin}/js/nomadro-speed.js`, {
|
||
mode: "no-cors",
|
||
credentials: "omit",
|
||
cache: "force-cache",
|
||
}).catch(() => undefined);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
|
||
function defaultLayout(): Layout {
|
||
if (
|
||
typeof window !== "undefined" &&
|
||
window.matchMedia("(max-width: 768px)").matches
|
||
) {
|
||
return "video";
|
||
}
|
||
return "split";
|
||
}
|
||
|
||
export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||
useSocialI18n();
|
||
const router = useRouter();
|
||
const config = useSocialConfig();
|
||
const meetups = useMemo(
|
||
() => resolveSocialCatalog(config.copy.socialCatalogs).meetups,
|
||
[config.copy.socialCatalogs],
|
||
);
|
||
const meetup =
|
||
meetups.find((m) => m.id === meetupId) ||
|
||
{
|
||
id: meetupId,
|
||
title: "语音厅",
|
||
city: "Online",
|
||
date: "",
|
||
time: "",
|
||
mode: "online" as const,
|
||
mirotalkRoom: meetupId,
|
||
channelId: "meetup-live",
|
||
};
|
||
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");
|
||
// 首屏就带花名,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(() => {
|
||
const nick = joinName || ensureGuestNick();
|
||
seedMirotalkNick(nick);
|
||
// 必须用 roomId:线下场次 seed 里 mirotalkRoom="" 时不能塞空 room(iframe 黑屏 + 乱提示)
|
||
return joinUrl(roomId, nick);
|
||
}, [roomId, 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);
|
||
seedMirotalkNick(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(() => {
|
||
if (startedRef.current) return;
|
||
startedRef.current = true;
|
||
endedRef.current = false;
|
||
enteredAtRef.current = Date.now();
|
||
warmMirotalkOrigin();
|
||
const name = ensureGuestNick();
|
||
chat.setNick(name);
|
||
saveJson("nick", name);
|
||
seedMirotalkNick(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;
|
||
// 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;
|
||
}, [chat.messages]);
|
||
|
||
useEffect(() => {
|
||
return () => {
|
||
endRoomSession("unmount");
|
||
};
|
||
}, [endRoomSession]);
|
||
|
||
const send = async () => {
|
||
if (!chat.draft.trim() || chat.sending) return;
|
||
await chat.send(chat.draft);
|
||
};
|
||
|
||
if (!meetups.some((item) => item.id === meetupId)) {
|
||
return (
|
||
<div className="social-root social-live-root social-meetup-live">
|
||
<EmptyState
|
||
title={socialTx("没有找到这个场次")}
|
||
description="场次可能已下线,请返回选择其他活动。"
|
||
>
|
||
<Link className="social-btn primary" href={socialPath("/meetup")}>
|
||
{socialTx("查看全部场次")}
|
||
</Link>
|
||
</EmptyState>
|
||
<SocialMobileDock />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<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"
|
||
onClick={(e) => {
|
||
e.preventDefault();
|
||
endRoomSession("back");
|
||
router.push(socialPath("/meetup"));
|
||
}}
|
||
>
|
||
← {socialTx("回去看场次")}
|
||
</Link>
|
||
<div>
|
||
<strong>{txMeetup(meetup).title}</strong>
|
||
<p className="social-muted">
|
||
{[meetup.date, meetup.time].filter(Boolean).join(" ")}
|
||
{channel.topic ? ` · ${socialTx(channel.topic)}` : ""}
|
||
</p>
|
||
</div>
|
||
<span
|
||
className={`social-live-conn ${chat.status === "offline" ? "is-off" : chat.status === "online" ? "is-on" : ""}`}
|
||
role="status"
|
||
>
|
||
{chat.status === "online"
|
||
? socialTx("聊天已接通")
|
||
: chat.status === "offline"
|
||
? socialTx("聊天暂时断了")
|
||
: socialTx("正在连上…")}
|
||
</span>
|
||
</div>
|
||
<div className="social-live-bar-tools">
|
||
{videoReady && (
|
||
<div className="social-actions">
|
||
<button
|
||
type="button"
|
||
className="social-btn"
|
||
onClick={() => {
|
||
endRoomSession("leave-video");
|
||
setVideoReady(false);
|
||
setLoadSlow(false);
|
||
}}
|
||
>
|
||
{socialTx("离开视频")}
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="social-btn"
|
||
onClick={() => startVideo(true)}
|
||
>
|
||
{socialTx("重新连接")}
|
||
</button>
|
||
</div>
|
||
)}
|
||
<div className="social-live-tabs" role="tablist" aria-label={socialTx("怎么看")}>
|
||
{(["split", "video", "chat"] as const).map((m) => (
|
||
<button
|
||
key={m}
|
||
type="button"
|
||
role="tab"
|
||
aria-selected={layout === m}
|
||
tabIndex={layout === m ? 0 : -1}
|
||
onKeyDown={(event) => {
|
||
const modes = ["split", "video", "chat"] as const;
|
||
const index = modes.indexOf(m);
|
||
const next =
|
||
event.key === "ArrowRight"
|
||
? (index + 1) % 3
|
||
: event.key === "ArrowLeft"
|
||
? (index + 2) % 3
|
||
: event.key === "Home"
|
||
? 0
|
||
: event.key === "End"
|
||
? 2
|
||
: -1;
|
||
if (next < 0) return;
|
||
event.preventDefault();
|
||
setLayout(modes[next]);
|
||
event.currentTarget.parentElement
|
||
?.querySelectorAll<HTMLButtonElement>("button")
|
||
[next]?.focus();
|
||
}}
|
||
className={`social-live-tab${layout === m ? " active" : ""}`}
|
||
onClick={() => setLayout(m)}
|
||
>
|
||
{m === "split" ? "一起看" : m === "video" ? "只看视频" : "只看聊天"}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
</header>
|
||
|
||
<div className={`social-live-stage layout-${layout}`}>
|
||
{(layout === "split" || layout === "video") && (
|
||
<section className="social-live-video" aria-label={socialTx("语音厅")}>
|
||
{!videoReady ? (
|
||
<div className="social-live-gate">
|
||
<p>{socialTx("接通中…")}</p>
|
||
<button
|
||
type="button"
|
||
className="social-btn primary"
|
||
onClick={() => startVideo()}
|
||
>
|
||
{socialTx("重试连接")}
|
||
</button>
|
||
</div>
|
||
) : (
|
||
<div className="social-live-frame-wrap">
|
||
{iframeLoading && (
|
||
<div
|
||
className="social-live-iframe-overlay social-live-iframe-overlay--thin"
|
||
aria-live="polite"
|
||
>
|
||
<div className="social-live-iframe-mark" aria-hidden>
|
||
N
|
||
</div>
|
||
<p>
|
||
{loadSlow
|
||
? "连接较慢,可以重试"
|
||
: "接通中…"}
|
||
</p>
|
||
{loadSlow && (
|
||
<button
|
||
type="button"
|
||
className="social-btn"
|
||
onClick={() => startVideo(true)}
|
||
>
|
||
{socialTx("重试连接")}
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
<iframe
|
||
key={frameKey}
|
||
ref={iframeRef}
|
||
title={txMeetup(meetup).title}
|
||
src={videoSrc}
|
||
allow="camera; microphone; speaker-selection; display-capture; autoplay; fullscreen; clipboard-read; clipboard-write"
|
||
allowFullScreen
|
||
referrerPolicy="origin"
|
||
className="social-live-iframe"
|
||
onLoad={() => {
|
||
setIframeLoading(false);
|
||
guardIframeHome();
|
||
}}
|
||
/>
|
||
</div>
|
||
)}
|
||
</section>
|
||
)}
|
||
|
||
{(layout === "split" || layout === "chat") && (
|
||
<section className="social-live-chat" aria-label={socialTx("场次聊天")}>
|
||
<div className="social-live-thread">
|
||
{chat.messages.map((m) => (
|
||
<article
|
||
key={m.id}
|
||
className={`social-message${m.mine ? " mine" : ""}`}
|
||
>
|
||
<div className="social-message-body">
|
||
<header>
|
||
<strong>{m.author}</strong>
|
||
</header>
|
||
<p>{m.text}</p>
|
||
</div>
|
||
</article>
|
||
))}
|
||
<div ref={bottomRef} />
|
||
</div>
|
||
<form
|
||
className="social-chat-composer"
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
void send();
|
||
}}
|
||
>
|
||
<textarea
|
||
value={chat.draft}
|
||
onChange={(e) => chat.setDraft(e.target.value)}
|
||
placeholder={socialTx("说点什么…")}
|
||
rows={2}
|
||
maxLength={2000}
|
||
/>
|
||
<button
|
||
className="social-btn primary"
|
||
type="submit"
|
||
disabled={chat.sending || !chat.draft.trim()}
|
||
>
|
||
{socialTx("发送")}
|
||
</button>
|
||
</form>
|
||
</section>
|
||
)}
|
||
</div>
|
||
<SocialMobileDock />
|
||
</div>
|
||
);
|
||
}
|