diff --git a/backend/src/main/java/com/imeeting/service/biz/impl/RealtimeMeetingSessionStateServiceImpl.java b/backend/src/main/java/com/imeeting/service/biz/impl/RealtimeMeetingSessionStateServiceImpl.java index b19e76b..8489d49 100644 --- a/backend/src/main/java/com/imeeting/service/biz/impl/RealtimeMeetingSessionStateServiceImpl.java +++ b/backend/src/main/java/com/imeeting/service/biz/impl/RealtimeMeetingSessionStateServiceImpl.java @@ -27,6 +27,7 @@ import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.function.Supplier; @Service @Slf4j @@ -41,6 +42,12 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe private final RealtimeMeetingPublisherLease publisherLease; private final ApplicationEventPublisher eventPublisher; + /** + * 会话状态分段锁数量,见 {@link #computeInMeetingLock}。 + */ + private static final int MEETING_STATE_LOCK_STRIPES = 256; + private final Object[] meetingStateLocks = createMeetingStateLocks(); + @Value("${imeeting.realtime.resume-window-minutes:30}") private String resumeWindowMinutesValue; @@ -49,6 +56,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public void initSessionIfAbsent(Long meetingId, Long tenantId, Long userId) { + runInMeetingLock(meetingId, () -> initSessionIfAbsentInLock(meetingId, tenantId, userId)); + } + + private void initSessionIfAbsentInLock(Long meetingId, Long tenantId, Long userId) { RealtimeMeetingSessionState state = readState(meetingId); if (state != null) { return; @@ -67,6 +78,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public void rememberResumeConfig(Long meetingId, RealtimeMeetingResumeConfig resumeConfig) { + runInMeetingLock(meetingId, () -> rememberResumeConfigInLock(meetingId, resumeConfig)); + } + + private void rememberResumeConfigInLock(Long meetingId, RealtimeMeetingResumeConfig resumeConfig) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); state.setResumeConfig(resumeConfig); state.setUpdatedAt(System.currentTimeMillis()); @@ -78,6 +93,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe if (meetingId == null || speakerContextId == null || speakerContextId.isBlank()) { return; } + runInMeetingLock(meetingId, () -> rememberSpeakerContextInLock(meetingId, speakerContextId)); + } + + private void rememberSpeakerContextInLock(Long meetingId, String speakerContextId) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); RealtimeMeetingResumeConfig resumeConfig = state.getResumeConfig(); if (resumeConfig == null) { @@ -94,6 +113,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe if (meetingId == null || upstreamSessionId == null || upstreamSessionId.isBlank()) { return; } + runInMeetingLock(meetingId, () -> rememberUpstreamSessionIdInLock(meetingId, upstreamSessionId)); + } + + private void rememberUpstreamSessionIdInLock(Long meetingId, String upstreamSessionId) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); RealtimeMeetingResumeConfig resumeConfig = state.getResumeConfig(); if (resumeConfig == null) { @@ -107,6 +130,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public void assertCanOpenSession(Long meetingId) { + runInMeetingLock(meetingId, () -> assertCanOpenSessionInLock(meetingId)); + } + + private void assertCanOpenSessionInLock(Long meetingId) { RealtimeMeetingSessionStatusVO status = getStatus(meetingId); if (status == null) { return; @@ -143,6 +170,16 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe return false; } + boolean activated = computeInMeetingLock(meetingId, () -> activateInLock(meetingId, connectionId)); + if (activated) { + // 发布激活事件:推送订阅挂载由监听器完成,避免会话状态服务反向依赖推送层形成 Bean 循环依赖。 + // 事件在锁外发布:监听器会按参会人挂接推送订阅(Redis/DB 访问),避免拉长会议锁的持有时间。 + eventPublisher.publishEvent(new RealtimeMeetingSessionActivatedEvent(meetingId)); + } + return activated; + } + + private boolean activateInLock(Long meetingId, String connectionId) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); if ("COMPLETING".equals(state.getStatus()) || "COMPLETED".equals(state.getStatus())) { return false; @@ -167,8 +204,6 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe sessionCache.clearResumeTimeout(meetingId); sessionCache.clearEmptyTimeout(meetingId); - // 发布激活事件:推送订阅挂载由监听器完成,避免会话状态服务反向依赖推送层形成 Bean 循环依赖 - eventPublisher.publishEvent(new RealtimeMeetingSessionActivatedEvent(meetingId)); return true; } @@ -219,6 +254,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public RealtimeMeetingSessionStatusVO pause(Long meetingId) { + return computeInMeetingLock(meetingId, () -> pauseInLock(meetingId)); + } + + private RealtimeMeetingSessionStatusVO pauseInLock(Long meetingId) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); if ("COMPLETING".equals(state.getStatus()) || "COMPLETED".equals(state.getStatus())) { return toStatusVO(state); @@ -236,7 +275,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe if (meetingId == null || connectionId == null || connectionId.isBlank()) { return; } + runInMeetingLock(meetingId, () -> pauseByDisconnectInLock(meetingId, connectionId)); + } + private void pauseByDisconnectInLock(Long meetingId, String connectionId) { RealtimeMeetingSessionState state = readState(meetingId); if (state == null) { return; @@ -258,6 +300,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public void refreshAfterTranscriptCapture(Long meetingId, long transcriptCount) { + runInMeetingLock(meetingId, () -> refreshAfterTranscriptCaptureInLock(meetingId, transcriptCount)); + } + + private void refreshAfterTranscriptCaptureInLock(Long meetingId, long transcriptCount) { RealtimeMeetingSessionState state = getOrCreateState(meetingId); long now = System.currentTimeMillis(); @@ -278,6 +324,10 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public boolean markCompletingIfResumeExpired(Long meetingId) { + return computeInMeetingLock(meetingId, () -> markCompletingIfResumeExpiredInLock(meetingId)); + } + + private boolean markCompletingIfResumeExpiredInLock(Long meetingId) { boolean locked = meetingLockCache.tryAcquireRealtimeTimeoutLock(meetingId, Duration.ofMinutes(1)); if (!locked) { return false; @@ -316,20 +366,36 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe @Override public void expireEmptySession(Long meetingId) { + boolean cleared = computeInMeetingLock(meetingId, () -> clearEmptySessionIfExpiredInLock(meetingId)); + if (cleared) { + publishSessionClosed(meetingId); + } + } + + private boolean clearEmptySessionIfExpiredInLock(Long meetingId) { RealtimeMeetingSessionState state = readState(meetingId); if (state == null) { - return; + return false; } if ("PAUSED_EMPTY".equals(state.getStatus())) { - clear(meetingId); + sessionCache.clearAll(meetingId); + return true; } + return false; } @Override public void clear(Long meetingId) { - sessionCache.clearAll(meetingId); - // 发布会话结束事件:推送订阅回收由监听器完成,避免会话状态服务反向依赖推送层形成 Bean 循环依赖 - eventPublisher.publishEvent(new RealtimeMeetingSessionClosedEvent(meetingId)); + runInMeetingLock(meetingId, () -> sessionCache.clearAll(meetingId)); + publishSessionClosed(meetingId); + } + + /** + * 发布会话结束事件:推送订阅回收由监听器完成,避免会话状态服务反向依赖推送层形成 Bean 循环依赖。 + * 刻意在锁外发布,避免监听器的 Redis/DB 访问拉长会议锁的持有时间。 + */ + private void publishSessionClosed(Long meetingId) { + eventPublisher.publishEvent(new RealtimeMeetingSessionClosedEvent(meetingId)); } private RealtimeMeetingSessionStatusVO pauseState(Long meetingId, RealtimeMeetingSessionState state) { @@ -454,6 +520,53 @@ public class RealtimeMeetingSessionStateServiceImpl implements RealtimeMeetingSe sessionCache.saveState(state); } + /** + * 在会话状态分段锁内执行「读-改-写」并返回结果;所有会话状态写入口统一走这里。 + * + *

会话状态在 Redis 中按整个 JSON 字符串存取({@link RealtimeMeetingSessionCache#saveState}), + * 任何一处读改写都会整体覆盖其它分支的并发修改。此前转写回调(ASR 线程)与 WebSocket 断开暂停 + * 各持一把互不相干的 meetingLocks、gRPC 侧激活完全无锁,会互相覆盖 transcriptCountSnapshot / + * hasTranscript,进而让 {@link #markCompletingIfResumeExpiredInLock} 拿到失真的快照 + * 误判为空会议并清掉转写。 + * + *

用固定分段数而不是按 meetingId 缓存锁对象:缓存锁对象需在释放时判断能否移除,而 + * 「判断可移除」与「获取锁」之间存在竞态,会让同一 meetingId 先后拿到两把不同的锁,反而失去互斥。 + * 分段锁无生命周期管理、无内存增长,代价只是极小概率的跨会议误争用。 + * + *

只覆盖本实例:多实例部署下同一 meetingId 的并发读改写仍有窗口,本方案不引入跨实例锁。 + * + *

持锁期间可能同步发布会话事件(监听器会做 Redis/DB 访问)。监听链路 + * (RealtimeMeetingPushSubscriptionListener → RealtimeMeetingPushSubscriptionManager)不反向依赖本服务, + * 因此不构成锁环;若后续给监听器新增对本服务的依赖,必须改为异步发布。 + */ + private T computeInMeetingLock(Long meetingId, Supplier action) { + if (meetingId == null) { + return action.get(); + } + synchronized (meetingStateLock(meetingId)) { + return action.get(); + } + } + + private void runInMeetingLock(Long meetingId, Runnable action) { + computeInMeetingLock(meetingId, () -> { + action.run(); + return null; + }); + } + + private Object meetingStateLock(Long meetingId) { + return meetingStateLocks[(int) Math.floorMod(meetingId.longValue(), (long) MEETING_STATE_LOCK_STRIPES)]; + } + + private static Object[] createMeetingStateLocks() { + Object[] locks = new Object[MEETING_STATE_LOCK_STRIPES]; + for (int index = 0; index < locks.length; index++) { + locks[index] = new Object(); + } + return locks; + } + private long getResumeWindowMinutes() { return parseLongOrDefault(resumeWindowMinutesValue, 30L, "resume-window-minutes"); } diff --git a/backend/src/main/java/com/imeeting/service/realtime/impl/LocalRealtimeAsrChannel.java b/backend/src/main/java/com/imeeting/service/realtime/impl/LocalRealtimeAsrChannel.java index e8636e0..25dec8a 100644 --- a/backend/src/main/java/com/imeeting/service/realtime/impl/LocalRealtimeAsrChannel.java +++ b/backend/src/main/java/com/imeeting/service/realtime/impl/LocalRealtimeAsrChannel.java @@ -46,8 +46,14 @@ public class LocalRealtimeAsrChannel implements RealtimeAsrChannel { private static final String STATE_UPSTREAM_SESSION_ID = "upstreamSessionId"; private static final String STATE_RECONNECTING = "reconnecting"; private static final String STATE_RECONNECT_ATTEMPT = "reconnectAttempt"; + private static final String STATE_LAST_PING_LOG_AT = "lastPingLogAt"; private static final int MAX_RECONNECT_ATTEMPTS = 3; private static final int MAX_RECONNECT_BUFFER_FRAMES = 40; + /** + * 上游 ASR 保活 ping 的 info 日志最小间隔。 + *

前端断开后上游连接按设计继续保活,ping 会周期性到达,不限流会把日志刷满。 + */ + private static final long PING_LOG_INTERVAL_MILLIS = 60_000L; private static final CompletableFuture COMPLETED = CompletableFuture.completedFuture(null); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String STOP_MESSAGE = "{\"type\":\"stop\"}"; @@ -635,12 +641,31 @@ public class LocalRealtimeAsrChannel implements RealtimeAsrChannel { @Override public java.util.concurrent.CompletionStage onPing(java.net.http.WebSocket webSocket, ByteBuffer message) { webSocket.sendPong(copyBuffer(message)); - log.info("上游 ASR ping 已本地响应:meetingId={}, sessionId={}, bytes={}", - context.getMeetingId(), currentConnectionId(context), message.remaining()); + if (shouldLogPing()) { + log.info("上游 ASR ping 已本地响应:meetingId={}, sessionId={}, bytes={}", + context.getMeetingId(), currentConnectionId(context), message.remaining()); + } else if (log.isDebugEnabled()) { + log.debug("上游 ASR ping 已本地响应:meetingId={}, sessionId={}, bytes={}", + context.getMeetingId(), currentConnectionId(context), message.remaining()); + } webSocket.request(1); return COMPLETED; } + /** + * 同一上游连接每 {@link #PING_LOG_INTERVAL_MILLIS} 最多放行一条 info,其余降为 debug。 + * 保留「首条可见 + 周期性可见」的可观测性,同时避免刷屏。 + */ + private boolean shouldLogPing() { + long now = System.currentTimeMillis(); + Object last = context.getChannelState().get(STATE_LAST_PING_LOG_AT); + if (last instanceof Number number && now - number.longValue() < PING_LOG_INTERVAL_MILLIS) { + return false; + } + context.getChannelState().put(STATE_LAST_PING_LOG_AT, now); + return true; + } + @Override public java.util.concurrent.CompletionStage onPong(java.net.http.WebSocket webSocket, ByteBuffer message) { log.debug("上游 ASR pong 已本地忽略:meetingId={}, sessionId={}, bytes={}", diff --git a/frontend/src/hooks/useHotWordGroupLimit.ts b/frontend/src/hooks/useHotWordGroupLimit.ts new file mode 100644 index 0000000..4ac593d --- /dev/null +++ b/frontend/src/hooks/useHotWordGroupLimit.ts @@ -0,0 +1,21 @@ +import {useDict} from "./useDict"; + +const HOT_WORD_GROUP_LIMIT_DICT_TYPE = "biz_hotword_group_limit"; +const DEFAULT_HOT_WORD_GROUP_LIMIT = 200; +const MAX_JAVA_INTEGER = 2147483647; +const POSITIVE_INTEGER_PATTERN = /^\+?\d+$/; + +export function useHotWordGroupLimit() { + const {items, loading} = useDict(HOT_WORD_GROUP_LIMIT_DICT_TYPE); + for (const item of items) { + const itemValue = item.itemValue?.trim() || ""; + if (!POSITIVE_INTEGER_PATTERN.test(itemValue)) { + continue; + } + const configuredLimit = Number(itemValue); + if (Number.isSafeInteger(configuredLimit) && configuredLimit > 0 && configuredLimit <= MAX_JAVA_INTEGER) { + return {limit: configuredLimit, loading}; + } + } + return {limit: DEFAULT_HOT_WORD_GROUP_LIMIT, loading}; +} diff --git a/frontend/src/utils/realtimePublisher.js b/frontend/src/utils/realtimePublisher.js new file mode 100644 index 0000000..4007a9b --- /dev/null +++ b/frontend/src/utils/realtimePublisher.js @@ -0,0 +1,3 @@ +export function isRealtimeMeetingPublisher(creatorId, userId) { + return creatorId !== undefined && creatorId !== null && creatorId === userId; +} diff --git a/imeeting-h5/src/pages/realtime-meeting-preview/index.css b/imeeting-h5/src/pages/realtime-meeting-preview/index.css new file mode 100644 index 0000000..8f83b70 --- /dev/null +++ b/imeeting-h5/src/pages/realtime-meeting-preview/index.css @@ -0,0 +1,159 @@ +.realtime-preview-page { + box-sizing: border-box; + display: grid; + grid-template-rows: auto auto minmax(0, 1fr); + gap: 20px; + width: min(100%, 1120px); + height: 100dvh; + margin: 0 auto; + padding: 28px 24px; + overflow: hidden; + color: #14213d; +} + +.realtime-preview-loading { + display: grid; + min-height: 100vh; + place-items: center; +} + +.realtime-preview-header, +.realtime-preview-hero, +.realtime-preview-section-title, +.realtime-preview-item-meta, +.realtime-preview-meta { + display: flex; + align-items: center; +} + +.realtime-preview-header, +.realtime-preview-section-title, +.realtime-preview-item-meta { + justify-content: space-between; +} + +.realtime-preview-hero { + justify-content: space-between; + gap: 24px; + margin: 0; + padding: 32px; + border-radius: 24px; + color: #fff; + background: linear-gradient(135deg, #123c74, #206ea4); +} + +.realtime-preview-hero p { + margin: 0 0 8px; + opacity: 0.78; +} + +.realtime-preview-hero h1 { + margin: 0; + font-size: clamp(24px, 3vw, 38px); + line-height: 1.2; +} + +.realtime-preview-meta { + flex-wrap: wrap; + justify-content: flex-end; + gap: 12px 20px; + font-size: 14px; + opacity: 0.9; +} + +.realtime-preview-meta span { + display: inline-flex; + align-items: center; + gap: 7px; +} + +.realtime-preview-transcripts { + display: flex; + min-height: 0; + flex-direction: column; + overflow: hidden; + border: 1px solid rgba(20, 33, 61, 0.08); + border-radius: 20px; + background: rgba(255, 255, 255, 0.94); + box-shadow: 0 18px 48px rgba(20, 33, 61, 0.08); +} + +.realtime-preview-section-title { + padding: 18px 24px; + border-bottom: 1px solid rgba(20, 33, 61, 0.08); + color: #607089; + font-size: 14px; +} + +.realtime-preview-section-title > div { + display: inline-flex; + align-items: center; + gap: 9px; + color: #14213d; + font-weight: 700; +} + +.realtime-preview-live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #22a06b; + box-shadow: 0 0 0 5px rgba(34, 160, 107, 0.12); +} + +.realtime-preview-list { + display: grid; + min-height: 0; + flex: 1; + gap: 1px; + overflow-y: auto; + background: rgba(20, 33, 61, 0.06); +} + +.realtime-preview-item { + padding: 20px 24px; + background: #fff; +} + +.realtime-preview-item-meta { + gap: 16px; + color: #607089; + font-size: 13px; +} + +.realtime-preview-item-meta strong { + color: #1f5f95; +} + +.realtime-preview-item p { + margin: 9px 0 0; + color: #26364f; + font-size: 16px; + line-height: 1.8; + white-space: pre-wrap; +} + +@media (max-width: 768px) { + .realtime-preview-page { + gap: 16px; + padding: 16px 14px; + } + + .realtime-preview-hero { + align-items: flex-start; + flex-direction: column; + gap: 18px; + padding: 24px 20px; + border-radius: 18px; + } + + .realtime-preview-meta { + justify-content: flex-start; + } + + .realtime-preview-section-title, + .realtime-preview-item { + padding-right: 18px; + padding-left: 18px; + } +} diff --git a/imeeting-h5/src/pages/realtime-meeting-preview/index.tsx b/imeeting-h5/src/pages/realtime-meeting-preview/index.tsx new file mode 100644 index 0000000..8d33b7a --- /dev/null +++ b/imeeting-h5/src/pages/realtime-meeting-preview/index.tsx @@ -0,0 +1,375 @@ +import {ArrowLeftOutlined, ClockCircleOutlined, TeamOutlined} from "@ant-design/icons"; +import {App, Button, Empty, Spin, Tag} from "antd"; +import {useEffect, useMemo, useRef, useState} from "react"; +import {useNavigate, useParams, useSearchParams} from "react-router-dom"; + +import { + createPublicRealtimeSubscriptionSession, + getPublicMeetingPreview, + getPublicRealtimeMeetingSessionStatus, +} from "@/api/meeting"; +import type {MeetingTranscriptVO, MeetingVO, RealtimeMeetingSessionStatusVO} from "@/types"; + +import "./index.css"; + +type RealtimeSegment = { + text?: unknown; + sentence_id?: unknown; + sentence_key?: unknown; + speaker_id?: unknown; + speaker_name?: unknown; + start?: unknown; + end?: unknown; +}; + +const isRealtimeEnded = (status: RealtimeMeetingSessionStatusVO["status"]) => ( + status === "COMPLETING" || status === "COMPLETED" +); + +const getSessionStatusText = (status: RealtimeMeetingSessionStatusVO["status"]) => { + if (status === "ACTIVE") { + return "实时转写中"; + } + if (status === "IDLE") { + return "等待会议开始"; + } + return "录音已暂停,等待继续"; +}; + +const hashSentenceKey = (value: string) => { + let hash = 0; + for (let index = 0; index < value.length; index += 1) { + hash = ((hash << 5) - hash) + value.charCodeAt(index); + hash |= 0; + } + return Math.max(1, Math.abs(hash)); +}; + +/** 转写列表保留的最大条数;超出后丢弃最早的记录,避免长会议内存与渲染持续增长。 */ +const MAX_TRANSCRIPT_ITEMS = 2000; + +const trimTranscripts = (items: MeetingTranscriptVO[]) => ( + items.length > MAX_TRANSCRIPT_ITEMS ? items.slice(items.length - MAX_TRANSCRIPT_ITEMS) : items +); + +/** + * 建立订阅长连接失败后的退避:3→6→12→24→60 秒封顶,成功后立即重置。 + * 后端签发订阅令牌按每 IP 每分钟 20 次限流(办公网 NAT 出口下所有访客共用同一配额), + * 固定 3 秒重试会贴着上限,退避后最坏情况降到 1~2 次/分钟。 + */ +const CONNECT_BACKOFF_BASE_MILLIS = 3000; +const CONNECT_BACKOFF_MAX_MILLIS = 60000; +/** 令牌提前判失效的安全余量,避免在过期边界上发起连接。 */ +const SESSION_TOKEN_EXPIRE_MARGIN_MILLIS = 5000; + +type CachedSession = { + /** 令牌绑定的会议;同路由切换会议参数时组件不会卸载,必须按会议校验,避免复用上一个会议的令牌。 */ + meetingId: number; + token: string; + path: string; + expiresAt: number; +}; + +const toMilliseconds = (value: unknown) => (typeof value === "number" ? Math.round(value * 1000) : undefined); + +const formatTime = (value?: number) => { + if (value === undefined) { + return ""; + } + const totalSeconds = Math.floor(value / 1000); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`; +}; + +const getSegment = (eventData: string): RealtimeSegment | null => { + try { + const message = JSON.parse(eventData) as { data?: unknown }; + if (!message.data || typeof message.data !== "object") { + return null; + } + const segment = message.data as RealtimeSegment; + return typeof segment.text === "string" && segment.text.trim() ? segment : null; + } catch { + return null; + } +}; + +export default function RealtimeMeetingPreviewPage() { + const {message} = App.useApp(); + const navigate = useNavigate(); + const {id} = useParams<{ id: string }>(); + const [searchParams] = useSearchParams(); + const [meeting, setMeeting] = useState(null); + const [transcripts, setTranscripts] = useState([]); + const [sessionStatus, setSessionStatus] = useState("IDLE"); + const [loading, setLoading] = useState(true); + const socketRef = useRef(null); + const openingRef = useRef(false); + const transcriptListRef = useRef(null); + /** 复用未过期的订阅令牌:后端令牌 10 分钟内有效且不会被消费,重连无需重新申请配额。 */ + const sessionRef = useRef(null); + const connectAttemptRef = useRef(0); + const nextConnectAtRef = useRef(0); + + const meetingId = useMemo(() => Number(id), [id]); + const accessPassword = useMemo(() => (searchParams.get("accessPassword") || "").trim(), [searchParams]); + const previewPath = useMemo(() => { + const query = accessPassword ? `?accessPassword=${encodeURIComponent(accessPassword)}` : ""; + return `/meetings/${meetingId}/preview${query}`; + }, [accessPassword, meetingId]); + + const leaveRealtime = () => { + socketRef.current?.close(); + socketRef.current = null; + navigate(previewPath, {replace: true}); + }; + + useEffect(() => { + if (!meetingId || Number.isNaN(meetingId)) { + leaveRealtime(); + return; + } + let disposed = false; + const load = async () => { + try { + const [previewResp, statusResp] = await Promise.all([ + getPublicMeetingPreview(meetingId, accessPassword || undefined), + getPublicRealtimeMeetingSessionStatus(meetingId, accessPassword || undefined), + ]); + if (disposed) { + return; + } + const preview = previewResp.data.data; + const status = statusResp.data.data.status; + if (preview.meeting.meetingType !== "REALTIME" || isRealtimeEnded(status)) { + leaveRealtime(); + return; + } + setMeeting(preview.meeting); + setTranscripts(preview.transcripts || []); + setSessionStatus(status); + } catch { + if (!disposed) { + message.error("实时会议不可用,已返回会议预览"); + leaveRealtime(); + } + } finally { + if (!disposed) { + setLoading(false); + } + } + }; + void load(); + return () => { + disposed = true; + }; + }, [accessPassword, meetingId, message, navigate, previewPath]); + + useEffect(() => { + const list = transcriptListRef.current; + if (list) { + list.scrollTop = list.scrollHeight; + } + }, [transcripts]); + + useEffect(() => { + if (!meeting) { + return; + } + let disposed = false; + const resetConnectBackoff = () => { + connectAttemptRef.current = 0; + nextConnectAtRef.current = 0; + }; + const recordConnectFailure = () => { + connectAttemptRef.current += 1; + const delay = Math.min( + CONNECT_BACKOFF_BASE_MILLIS * (2 ** (connectAttemptRef.current - 1)), + CONNECT_BACKOFF_MAX_MILLIS, + ); + nextConnectAtRef.current = Date.now() + delay; + }; + const mergeTranscript = (segment: RealtimeSegment) => { + const content = String(segment.text).trim(); + const startTime = toMilliseconds(segment.start); + const endTime = toMilliseconds(segment.end); + const sentenceKey = String(segment.sentence_key || segment.sentence_id || `${content}-${startTime || ""}`); + const syntheticId = -Math.abs(Number(segment.sentence_id) || hashSentenceKey(sentenceKey)); + setTranscripts((current) => { + const next: MeetingTranscriptVO = { + id: syntheticId, + speakerId: String(segment.speaker_id || ""), + speakerName: String(segment.speaker_name || ""), + content, + startTime, + endTime, + }; + const index = current.findIndex((item) => item.id === syntheticId + || (item.content === next.content && item.startTime === next.startTime)); + if (index >= 0) { + const updated = current.slice(); + updated[index] = {...updated[index], ...next}; + return updated; + } + const appended = [...current, next]; + // 转写按时间递增到达是常态,此时直接追加即可;只有乱序包才走全量排序。 + const last = current[current.length - 1]; + const inOrder = !last + || (next.startTime ?? Number.MAX_SAFE_INTEGER) >= (last.startTime ?? Number.MAX_SAFE_INTEGER); + if (!inOrder) { + appended.sort((left, right) => (left.startTime ?? Number.MAX_SAFE_INTEGER) + - (right.startTime ?? Number.MAX_SAFE_INTEGER)); + } + return trimTranscripts(appended); + }); + }; + const connect = async () => { + if (disposed || openingRef.current || socketRef.current?.readyState === WebSocket.OPEN + || socketRef.current?.readyState === WebSocket.CONNECTING) { + return; + } + if (Date.now() < nextConnectAtRef.current) { + return; + } + openingRef.current = true; + try { + let session = sessionRef.current; + if (!session || session.meetingId !== meeting.id || session.expiresAt <= Date.now()) { + const response = await createPublicRealtimeSubscriptionSession( + meeting.id, + accessPassword || undefined, + {suppressErrorToast: true}, + ); + const created = response.data.data; + if (!created?.sessionToken) { + recordConnectFailure(); + return; + } + session = { + meetingId: meeting.id, + token: created.sessionToken, + path: created.path, + expiresAt: Date.now() + Math.max( + 0, + (created.expiresInSeconds || 0) * 1000 - SESSION_TOKEN_EXPIRE_MARGIN_MILLIS, + ), + }; + sessionRef.current = session; + } + if (disposed) { + return; + } + const protocol = window.location.protocol === "https:" ? "wss" : "ws"; + const socket = new WebSocket(`${protocol}://${window.location.host}${session.path}?sessionToken=${encodeURIComponent(session.token)}`); + socketRef.current = socket; + let opened = false; + socket.onopen = () => { + // 连接真正建立才算成功:重置退避,后续重连继续复用令牌,不再消耗订阅配额。 + opened = true; + resetConnectBackoff(); + }; + socket.onmessage = (event) => { + const segment = getSegment(String(event.data)); + if (segment) { + mergeTranscript(segment); + } + }; + socket.onclose = () => { + if (socketRef.current === socket) { + socketRef.current = null; + } + if (!opened && !disposed) { + // 握手被拒(令牌失效或会议状态已变化)时丢弃令牌,下次改为重新申请,避免拿着废令牌一直重试。 + sessionRef.current = null; + recordConnectFailure(); + } + }; + } catch { + // 轮询会在会议仍活跃时重试建立只读订阅,失败按退避序列推迟下一次尝试。 + recordConnectFailure(); + } finally { + openingRef.current = false; + } + }; + const checkSession = async () => { + try { + const response = await getPublicRealtimeMeetingSessionStatus(meeting.id, accessPassword || undefined); + if (disposed) { + return; + } + const status = response.data.data.status; + setSessionStatus(status); + if (isRealtimeEnded(status)) { + leaveRealtime(); + return; + } + if (status === "ACTIVE") { + await connect(); + return; + } + socketRef.current?.close(); + socketRef.current = null; + } catch { + // 短暂网络错误由下一次轮询恢复,避免错误跳出仍在进行的会议。 + } + }; + void checkSession(); + const timer = window.setInterval(() => { + void checkSession(); + }, 3000); + return () => { + disposed = true; + window.clearInterval(timer); + socketRef.current?.close(); + socketRef.current = null; + }; + }, [accessPassword, meeting, navigate, previewPath]); + + if (loading || !meeting) { + return

; + } + + return ( +
+
+ + {getSessionStatusText(sessionStatus)} +
+
+
+

{getSessionStatusText(sessionStatus)}

+

{meeting.title || "未命名会议"}

+
+
+ {meeting.participantUsers?.length || 0} 人参会 + 仅可查看实时转写 +
+
+
+
+
+ + 实时识别结果 +
+ {transcripts.length} 条 +
+ {transcripts.length ? ( +
+ {transcripts.map((item) => ( +
+
+ {item.speakerName || item.speakerLabel || "发言人"} + {formatTime(item.startTime)} +
+

{item.content}

+
+ ))} +
+ ) : ( + + )} +
+
+ ); +}