"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("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(null); const iframeRef = useRef(null); const silentRecRef = useRef(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 (
{socialTx("查看全部场次")}
); } return (
{ e.preventDefault(); endRoomSession("back"); router.push(socialPath("/meetup")); }} > ← {socialTx("回去看场次")}
{txMeetup(meetup).title}

{[meetup.date, meetup.time].filter(Boolean).join(" ")} {channel.topic ? ` · ${socialTx(channel.topic)}` : ""}

{chat.status === "online" ? socialTx("聊天已接通") : chat.status === "offline" ? socialTx("聊天暂时断了") : socialTx("正在连上…")}
{videoReady && (
)}
{(["split", "video", "chat"] as const).map((m) => ( ))}
{(layout === "split" || layout === "video") && (
{!videoReady ? (

{socialTx("接通中…")}

) : (
{iframeLoading && (
N

{loadSlow ? "连接较慢,可以重试" : "接通中…"}

{loadSlow && ( )}
)}