Last active: 2 years ago
import { Message } from '@/projects/court/hooks/zego/useMessage';
import { ZegoBroadcastMessageInfo } from 'zego-express-engine-webrtm/sdk/code/zh/ZegoExpressEntity';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ZegoStreamList } from 'zego-express-engine-webrtc/sdk/code/zh/ZegoExpressEntity.web';
import { ZegoUser } from 'zego-express-engine-webrtc/sdk/src/common/zego.entity';
import { nanoid } from 'nanoid';
import { RoomState } from '@/projects/court/hooks/zego/useZego';
import { RootState } from '..';
export const initRoomState = {
appID: 0,
roomId: '',
// 用户 id 为当前登陆展台的手机号,必须先登陆
userId: '',
userName: '',
token: '',
id: '',
};
export type RoomUserMsg = {
type: 'ADD' | 'DELETE';
user: ZegoUser;
};
export interface ZegoState {
// 房间状态
roomState: RoomState;
// 当前房间内用户
userList: ZegoUser[];
// 当前房间推流用户
currentUsers: ZegoStreamList[];
// 房间内消息
messageList: Message[];
// 用户进入或离开消息
roomUserMsg: RoomUserMsg[];
}
const initialState: ZegoState = {
roomState: initRoomState,
userList: [],
currentUsers: [],
messageList: [],
roomUserMsg: [],
};
export const zegoSlice = createSlice({
name: 'zego',
initialState,
reducers: {
setList(s, action: PayloadAction<Partial<ZegoState>>) {
return {
...s,
...action.payload,
};
},
// 房间状态
updateRoom(s, action: PayloadAction<Partial<RoomState>>) {
s.roomState = {
...s.roomState,
...action.payload,
};
},
// 用户列表
addUser(s, action: PayloadAction<ZegoUser[]>) {
s.userList = s.userList.concat(action.payload);
},
removeUser(s, action: PayloadAction<ZegoUser[]>) {
action.payload.forEach((user) => {
const index = s.userList.findIndex(
(duser) => duser.userID === user.userID
);
if (!~index) return;
s.userList.splice(index, 1);
});
},
// 用户进入或离开房间 参数是全部用户
updateRoomMsg(s, action: PayloadAction<RoomUserMsg[]>) {
s.roomUserMsg = action.payload;
},
// 消息列表
addMessage(s, action: PayloadAction<Message>) {
s.messageList.push(action.payload);
},
receiveMessage(s, action: PayloadAction<ZegoBroadcastMessageInfo[]>) {
const cleanDup = (msg: ZegoBroadcastMessageInfo) => {
const messages = s.messageList.filter((m) => m.content.type === 'msg');
const duplicateMsg = messages.find(
(m) => m.content.messageID === msg.messageID
);
if (duplicateMsg) return;
const message: Message = {
id: nanoid(),
sending: false,
content: {
type: 'msg',
...msg,
},
};
s.messageList.push(message);
};
action.payload.forEach(cleanDup);
},
},
});
export const {
setList,
removeUser,
addUser,
addMessage,
receiveMessage,
updateRoom,
updateRoomMsg,
} = zegoSlice.actions;
export default zegoSlice.reducer;
export const selectRoomState = (s: RootState) => s.zego.roomState;
export const selectMessageList = (s: RootState) => s.zego.messageList;
export const selectUserList = (s: RootState) => s.zego.userList;