67 lines
2.6 KiB
TypeScript
67 lines
2.6 KiB
TypeScript
import { defineStore } from 'pinia'
|
||
import { useWebRTC } from '@/composables/useWebRTC'
|
||
import { useAuthStore } from '@/stores/auth'
|
||
import { useChatStore } from '@/stores/chat'
|
||
import { storage } from '@/utils/storage'
|
||
import type { Contact } from '@/types/api'
|
||
|
||
// 定义 Pinia Store
|
||
export const useWebRTCStore = defineStore('webrtc', () => {
|
||
const authStore = useAuthStore()
|
||
const chatStore = useChatStore()
|
||
|
||
// --- 回调:处理收到来电 ---
|
||
// 注意:这里不再切换 currentTarget。
|
||
// 原实现来电时把 currentTarget 硬切成来电者,但绕过了 selectChat(不加载消息/成员/已读),
|
||
// 会把用户正在看的聊天窗切成空白;而且来电者信息应由通话窗自己用信令携带的
|
||
// callerName/callerAvatar 显示,不依赖 currentTarget。
|
||
function handleIncomingCall(_senderUserId: string) {
|
||
// 保留回调入口以便未来扩展(如系统通知),当前无需改动会话状态
|
||
}
|
||
|
||
// --- 回调:获取房间ID策略 ---
|
||
// 这个函数非常关键,它定义了如何找到两个人聊天的房间ID
|
||
// 必须在 useWebRTC 之前定义,因为它被作为参数传入
|
||
// 优先级说明:显式接收者对应的房间 > 当前聊天窗口 > 本地缓存。
|
||
// 原实现把 storage 里的 selected_room_id 缓存放在第一位,
|
||
// 该缓存可能是上次会话遗留的过期值,导致通话被建到错误的房间里
|
||
function getRoomId(receiverUserId?: string): string {
|
||
// 策略 1: 如果提供了接收者ID,从联系人列表中查找对应的 room_id(最准确)
|
||
if (receiverUserId) {
|
||
const contact = chatStore.contacts.find((c) =>
|
||
c.user_id === receiverUserId ||
|
||
c.id === receiverUserId ||
|
||
c.contact_user_id === receiverUserId ||
|
||
c.contact_id === receiverUserId
|
||
)
|
||
if (contact && contact.room_id) {
|
||
return contact.room_id
|
||
}
|
||
}
|
||
|
||
// 策略 2: 使用当前打开的聊天窗口的 room_id
|
||
const currentTarget = chatStore.currentTarget
|
||
if (currentTarget && currentTarget.room_id) {
|
||
return currentTarget.room_id
|
||
}
|
||
|
||
// 策略 3: 本地存储的选中房间ID仅作最后兜底(可能过期,不可优先信任)
|
||
const cachedRoomId = storage.getSelectedRoomId()
|
||
if (cachedRoomId) {
|
||
return cachedRoomId
|
||
}
|
||
|
||
// 如果都找不到,返回空字符串,后续逻辑会报错提示
|
||
return ''
|
||
}
|
||
|
||
// --- 创建 WebRTC 实例 ---
|
||
// 传入当前用户ID,以及上述定义的两个回调
|
||
const webrtc = useWebRTC(authStore.user?.id || '', handleIncomingCall, getRoomId)
|
||
|
||
return {
|
||
webrtc,
|
||
getRoomId,
|
||
}
|
||
})
|