123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999 |
- // src/stores/websocket.js
- import { defineStore } from "pinia";
- import { $root as protobuf } from "@/common/proto/proto";
- import { useWalletStore } from "@/stores/modules/walletStore";
- import { getMessageApi, friendRequest, groupList } from "@/api/path/im.api";
- import { showDialog, showNotify } from 'vant';
- import { useSystemStore } from "@/stores/modules/systemStore";
- import * as MsgType from "@/common/constant/msgType";
- import {
- setMessageHook,
- handleMessageHook,
- } from "@/views/im/hook/messagesHook";
- // 配置常量
- const WS_CONFIG = {
- HEARTBEAT_INTERVAL: 30000, // 30秒
- HEARTBEAT_TIMEOUT: 10000, // 10秒
- HEARTBEAT_RETRY_LIMIT: 3,
- RECONNECT_BASE_INTERVAL: 1000,
- RECONNECT_MAX_INTERVAL: 30000,
- RECONNECT_MAX_ATTEMPTS: Infinity,
- RECONNECT_MULTIPLIER: 1.5,
- MESSAGE_QUEUE_MAX_SIZE: 100,
- MESSAGE_QUEUE_FLUSH_INTERVAL: 5000,
- };
- export const useWebSocketStore = defineStore("webSocketStore", {
- state: () => ({
- socket: null,
- peer: null,
- connectionState: "disconnected", // 'connecting', 'connected', 'disconnecting', 'error'
- reconnectAttempts: 0,
- sessionId:null,//当前会话id
- messages: [],
- groupMembersList:{},//群成员列表
- toUserInfo: {}, // 会话目标信息
- toUserAudioInfo: {}, // 会话目标音频信息
- unreadMessages: [],
- uuid: null,
- onMessageCallbacks: [],
- messageQueue: [],
- lastActivityTime: 0,
- stats: {
- sentMessages: 0,
- receivedMessages: 0,
- failedMessages: 0,
- reconnects: 0,
- },
- heartbeat: {
- timer: null,
- timeout: null,
- retryCount: 0,
- },
- reconnect: {
- timer: null,
- currentAttempt: 0,
- },
- queueFlushTimer: null,
- loading:false,
- applyfriend:{},//好友申请数据
- unread:false,//判断有无好友申请
- chatDelAuth: {}, //控制会话权限
- chatGroupAuth: {}, // 群会话权限
- chatRefresh:0,//强制刷新会话列表
- needRefreshIm:0,//软刷新会话列表
- indexs:0,// 接收消息计数器
- isassign:'',//是否@自己
- }),
- persist: {
- key: "toUserInfo",
- storage: localStorage,
- paths: ["toUserInfo", "uuid"],
- serializer: {
- serialize: (state) =>
- JSON.stringify({
- toUserInfo: state.toUserInfo,
- uuid: state.uuid,
- }),
- deserialize: (str) => {
- const data = JSON.parse(str);
- return {
- toUserInfo: data.toUserInfo || {},
- uuid: data.uuid || null,
- };
- },
- },
- },
- getters: {
- isConnected(state) {
- return state.connectionState === "connected";
- },
- hasUnreadMessages(state) {
- return state.unreadMessages.length > 0;
- },
- connectionStatus(state) {
- return state.connectionState;
- },
- },
- actions: {
- // 监听前后台切换
- changeAppState(state) {
- // if(state){
- // // 前台
- // }
- // else {
- // // 后台
- // }
- // 检测是否断开连接
- if(!this.isConnected){
- console.warn("前后台切换Websocket 已断开重新连接");
- this.disconnect();
- this.connect(this.uuid);
- }
- },
- // 监听网络变化
- changeNetworkState(state) {
- // 检测是否断开连接
- if(!this.isConnected){
- console.warn("网络波动Websocket 已断开重新连接");
- this.disconnect();
- this.connect(this.uuid);
- }
- },
- // 初始化连接
- connect(userUuid, callback) {
- if (!userUuid) {
- console.error("连接失败: 缺少 userUuid");
- return;
- }
- // 如果正在连接或已连接,则先断开
- if (
- this.connectionState === "connected" ||
- this.connectionState === "connecting"
- ) {
- this.disconnect();
- }
- this.uuid = userUuid;
- this.connectionState = "connecting";
- this.stats.reconnects++;
- try {
- const wsUrl = `${import.meta.env.VITE_PRO_IM_WSS}?user=${userUuid}`;
- this.socket = new WebSocket(wsUrl);
- this.socket.onopen = () => {
- this.connectionState = "connected";
- this.reconnect.currentAttempt = 0;
- this.lastActivityTime = Date.now();
- this.startHeartbeat();
- this.startQueueFlush();
- if (callback && typeof callback === "function") {
- callback();
- }
- console.log("WebSocket 连接成功");
- showNotify({ type: 'success', message: '服务器连接成功' });
- this.flushMessageQueue(); // 连接成功后立即发送队列中的消息
- };
- this.socket.onmessage = (event) => {
- this.lastActivityTime = Date.now();
- this.handleMessage(event.data);
- };
- this.socket.onclose = () => {
- this.connectionState = "disconnected";
- showNotify({ type: 'warning', message: '服务器连接断开' });
- this.cleanupTimers();
- if (
- this.reconnect.currentAttempt < WS_CONFIG.RECONNECT_MAX_ATTEMPTS
- ) {
- console.error("WebSocket被关闭, 重新连接");
- this.scheduleReconnect();
- }
- };
- this.socket.onerror = (error) => {
- this.connectionState = "error";
- console.error("WebSocket 错误并 重新连接:", error);
- showNotify({ type: 'warning', message: '服务器连接断开' });
- this.cleanupTimers();
- this.scheduleReconnect();
- };
- } catch (error) {
- console.error("创建 WebSocket 失败并 重新连接:", error);
- this.connectionState = "error";
- this.scheduleReconnect();
- }
- },
- // 断开连接
- disconnect() {
- this.connectionState = "disconnecting";
- this.cleanupTimers();
- if (this.socket) {
- try {
- this.socket.close();
- } catch (e) {
- console.error("关闭 WebSocket 时出错:", e);
- }
- this.socket = null;
- }
- if (this.peer) {
- this.peer.close();
- this.peer = null;
- }
- this.connectionState = "disconnected";
- },
- // 清理所有定时器
- cleanupTimers() {
- if (this.heartbeat.timer) clearTimeout(this.heartbeat.timer);
- if (this.heartbeat.timeout) clearTimeout(this.heartbeat.timeout);
- if (this.reconnect.timer) clearTimeout(this.reconnect.timer);
- if (this.queueFlushTimer) clearInterval(this.queueFlushTimer);
- this.heartbeat.timer = null;
- this.heartbeat.timeout = null;
- this.reconnect.timer = null;
- this.queueFlushTimer = null;
- this.heartbeat.retryCount = 0;
- },
- // 启动心跳检测
- startHeartbeat() {
- this.cleanupHeartbeat();
- this.heartbeat.timer = setTimeout(() => {
- if (this.isConnected) {
- try {
- const pingMsg = {
- type: "heatbeat",
- content: "ping",
- timestamp: Date.now(),
- };
- this.sendRawMessage(pingMsg);
- // 设置响应超时检测
- this.heartbeat.timeout = setTimeout(() => {
- this.heartbeat.retryCount++;
- if (
- this.heartbeat.retryCount >= WS_CONFIG.HEARTBEAT_RETRY_LIMIT
- ) {
- console.error("心跳响应超时,关闭连接并重新连接");
- this.disconnect();
- } else {
- if(this.heartbeat.retryCount > 1){
- console.warn(
- `心跳无响应,第${this.heartbeat.retryCount - 1}次重试`
- );
- }
- this.startHeartbeat(); // 重新发送心跳
- }
- }, WS_CONFIG.HEARTBEAT_TIMEOUT);
- } catch (error) {
- console.error("心跳发送失败:", error);
- this.scheduleReconnect();
- }
- }
- }, WS_CONFIG.HEARTBEAT_INTERVAL);
- },
- // 清理心跳定时器
- cleanupHeartbeat() {
- if (this.heartbeat.timer) clearTimeout(this.heartbeat.timer);
- if (this.heartbeat.timeout) clearTimeout(this.heartbeat.timeout);
- this.heartbeat.timer = null;
- this.heartbeat.timeout = null;
- },
- // 安排重连
- scheduleReconnect() {
- if (this.reconnect.timer) return;
- this.reconnect.currentAttempt++;
- // 指数退避算法计算重连间隔
- const delay = Math.min(
- WS_CONFIG.RECONNECT_BASE_INTERVAL *
- Math.pow(
- WS_CONFIG.RECONNECT_MULTIPLIER,
- this.reconnect.currentAttempt - 1
- ),
- WS_CONFIG.RECONNECT_MAX_INTERVAL
- );
- console.log(
- `将在 ${delay}ms 后尝试第 ${this.reconnect.currentAttempt} 次重连`
- );
- this.reconnect.timer = setTimeout(() => {
- this.reconnect.timer = null;
- if (!this.isConnected && this.uuid) {
- this.connect(this.uuid);
- }
- }, delay);
- },
- // 发送原始消息(不经过队列)
- sendRawMessage(messageData) {
- if (!this.isConnected) {
- throw new Error("WebSocket 未连接");
- }
- try {
- const MessageType = protobuf.lookupType("protocol.Message");
- const messagePB = MessageType.create(messageData);
- const buffer = MessageType.encode(messagePB).finish();
- this.socket.send(buffer);
- this.stats.sentMessages++;
- return true;
- } catch (error) {
- console.error("消息编码错误:", error);
- this.stats.failedMessages++;
- return false;
- }
- },
- // 发送消息(自动排队)
- sendMessage(messageData) {
- const walletStore = useWalletStore();
- // 构造完整消息
- const fullMessage = {
- fromUsername: this.toUserInfo.nickname,
- avatar: walletStore.avatar,
- to: this.toUserInfo.uuid,
- from: walletStore.account,
- ...messageData,
- timestamp: Date.now(),
- };
- // 如果连接正常,直接发送
- if (this.isConnected) {
- const success = this.sendRawMessage(fullMessage);
- if (success) {
- setMessageHook(fullMessage, this);
- return true;
- }
- }
- // 如果发送失败或未连接,加入队列
- if (this.messageQueue.length < WS_CONFIG.MESSAGE_QUEUE_MAX_SIZE) {
- this.messageQueue.push(fullMessage);
- console.log("消息已加入队列,等待发送");
- return true;
- } else {
- console.error("消息队列已满,丢弃消息");
- return false;
- }
- },
- // 启动队列刷新定时器
- startQueueFlush() {
- if (this.queueFlushTimer) return;
- this.queueFlushTimer = setInterval(() => {
- this.flushMessageQueue();
- }, WS_CONFIG.MESSAGE_QUEUE_FLUSH_INTERVAL);
- },
- // 发送队列中的所有消息
- flushMessageQueue() {
- if (!this.isConnected || this.messageQueue.length === 0) return;
- while (this.messageQueue.length > 0) {
- const message = this.messageQueue.shift();
- try {
- const success = this.sendRawMessage(message);
- if (success) {
- setMessageHook(message, this);
- } else {
- // 发送失败,重新放回队列开头
- this.messageQueue.unshift(message);
- break;
- }
- } catch (error) {
- console.error("发送队列消息失败:", error);
- this.messageQueue.unshift(message);
- break;
- }
- }
- },
- // 处理接收到的消息
- handleMessage(data) {
- const MessageType = protobuf.lookupType("protocol.Message");
- const reader = new FileReader();
- reader.onload = (event) => {
- try {
- const messagePB = MessageType.decode(
- new Uint8Array(event.target.result)
- );
- const message = MessageType.toObject(messagePB, {
- longs: String,
- enums: String,
- bytes: String,
- });
- this.stats.receivedMessages++;
- this.lastActivityTime = Date.now();
- handleMessageHook(message, this);
- // 调用所有回调函数
- this.onMessageCallbacks.forEach((cb) => {
- try {
- cb(message);
- } catch (e) {
- console.error("消息回调错误:", e);
- }
- });
- if (message.type === "heatbeat") {
- this.heartbeat.retryCount = 0; // 重置心跳重试计数
- return;
- }
- } catch (error) {
- console.error("消息解码错误:", error);
- this.stats.failedMessages++;
- }
- };
- reader.readAsArrayBuffer(data);
- },
- // ************功能*************//
- // 添加消息回调
- addOnMessageCallback(cb) {
- if (typeof cb === "function" && !this.onMessageCallbacks.includes(cb)) {
- this.onMessageCallbacks.push(cb);
- }
- },
- // 移除消息回调
- removeOnMessageCallback(cb) {
- this.onMessageCallbacks = this.onMessageCallbacks.filter(
- (item) => item !== cb
- );
- },
- // 新消息入栈本地
- pushMessage(message, sessionId = null) {
- const systemStore = useSystemStore();
- if(!sessionId){
- sessionId = message.from;
- }
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- if (sessionId == message.from){
- // this.getMessages({ uuid: message.from, friendUsername: message.to, messageType: message.messageType },true);
- }
- }
- systemStore.messageList[sessionId].push(message);
- // 检测当前消息
- if (this.toUserInfo.uuid === sessionId) {
- this.messages.push(message);
- this.indexs +=1;
- }
- // console.log('pushMessage', systemStore.messageList, this.messages)
- // 更新会话最新消息
- this.updateSessionNewMessage(message, sessionId)
- },
- // 更新本地真实消息id
- modifyMessageId(message, msg, sessionId = null) {
- // console.log(msg, message, sessionId)
- const systemStore = useSystemStore();
- if(!sessionId){
- sessionId = message.from;
- }
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- }
- systemStore.messageList[sessionId] = [...systemStore.messageList[sessionId]].map(item => {
- // 消息发送成功确认
- if (!item.id && msg.msgId && item.msgId + '' === msg.msgId + '') return {...item, id: msg.id, msgId: undefined, err: !msg.id?true:undefined};
- // 阅后即焚
- // console.log(item.id, msg?.id)
- if (item.id + '' === msg?.id + '') return {...item, isTemp: true, content: "", url: ""};
- return item;
- });
- // 检测当前消息
- if (this.toUserInfo.uuid === sessionId) {
- this.messages = [...this.messages].map(item => {
- // 消息发送成功确认
- if (!item.id && msg.msgId && item.msgId + '' === msg?.msgId + '') return { ...item, id: msg.id, msgId: undefined, err: !msg.id?true:undefined};
- // 阅后即焚
- if (item.id + '' === msg?.id + '') return { ...item, isTemp: true, content: "", url: ""};
- return item;
- });
- }
- console.log("修改消息", message, sessionId, systemStore.messageList,this.messages);
- },
- // 更新本地消息
- modifyMessage(message, msgId, sessionId = null) {
- const systemStore = useSystemStore();
- if(!sessionId){
- sessionId = message.from;
- }
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- }
- systemStore.messageList[sessionId] = [...systemStore.messageList[sessionId]].map(item => {
- if(typeof msgId === 'function'){
- let msg = {};
- if(msg = msgId(item, sessionId)){
- return { ...item, ...msg};
- }
- }
- else if (item.id + '' === msgId + '') return {...item, ...message};
- return item;
- });
- // 检测当前消息
- if (this.toUserInfo.uuid === sessionId) {
- this.messages = [...this.messages].map(item => {
- if(typeof msgId === 'function'){
- let msg = {};
- if(msg = msgId(item, sessionId)){
- return {...item,...msg};
- }
- }
- else if (item.id + '' === msgId + '') return {...item, ...message};
- return item;
- });
- }
- // console.log('this.messages',this.messages)
- },
- // 删除本地消息
- deleteMessage(message, msgId, sessionId = null) {
- const systemStore = useSystemStore();
- if(!sessionId){
- sessionId = message.from;
- }
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- }
- // 删除所有消息
- if (msgId === true || msgId === 'all') {
- systemStore.messageList[sessionId] = [];
- if (this.toUserInfo.uuid === sessionId) {
- this.messages = [];
- }
- return;
- }
- // console.log("删除消息", message, sessionId, systemStore.messageList, this.messages);
- systemStore.messageList[sessionId] = systemStore.messageList[sessionId].filter(item => {
- if (item.id + '' === msgId + '') return false;
- return true;
- });
- // 检测当前消息
- if (this.toUserInfo.uuid === sessionId) {
- this.messages = this.messages.filter(item => {
- if (item.id + '' === msgId + '') return false;
- return true;
- });
- }
- },
- // 发送消息已收到
- systemReceiptMessage(message, msg){
- if(!msg || !msg.uniqueId){
- return;
- }
- const response = {
- from: message.to,
- to: message.from,
- messageType: MsgType.MESSAGE_SYSTEM_RECEIPT,
- content: JSON.stringify({
- uniqueId: msg.uniqueId,
- timestamp: Date.now(),
- }),
- };
- // console.log("systemReceiptMessage", response);
- this.sendMessage(response)
- },
- // 获取会话消息
- getSessionMessages(sessionId) {
- const systemStore = useSystemStore();
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- }
- return [...systemStore.messageList[sessionId]];
- },
- // 设置当前会话消息
- setSessionMessages(sessionId, messages,all=false) {
- const systemStore = useSystemStore();
- let data = Array.isArray(messages) ? messages : (typeof messages === 'object' ? [messages] : []);
- if (!systemStore.messageList[sessionId]) {
- systemStore.messageList[sessionId] = [];
- }
- if(all){
- systemStore.messageList[sessionId] = data //.filter(val=>!systemStore.messageList[sessionId].find(v=>v.id == val.id))
- return;
- }
- systemStore.messageList[sessionId] = data;
- },
- // 更换会话
- changeSessionMessage(sessionId) {
- this.sessionId = sessionId;
- this.messages = this.getSessionMessages(sessionId);
- },
- // 获取历史消息
- async getMessages(params,all=false) {
- const router = useRouter();
- const systemStore = useSystemStore();
- this.loading = true // 开始加载
- this.changeSessionMessage(params.uuid);
- if (this.messages.length > 0 && !all) {
- this.loading = false;
- return;
- }
- try {
- const res = await getMessageApi({
- messageType: params.messageType,
- uuid: params.uuid,
- friendUsername: params.friendUsername,
- });
- if(res.code == 200){
- this.setSessionMessages(this.sessionId, (res.data || []), all);
- this.changeSessionMessage(this.sessionId);
- // return this.messages;
- }else{
- showDialog({
- title: '提示',
- message: res.msg,
- confirmButtonColor:"#4765dd",
- }).then(() => {
- systemStore.needRefreshIm = true;
- router.back();
- });
- }
- } catch (error) {
- console.error("获取消息失败:", error);
- throw error;
- } finally {
- this.loading = false // 结束加载
- }
- },
- // 更新会话列表消息
- updateSessionNewMessage(message, sessionId, msg = null) {
- console.log("更新会话列表消息:", message, sessionId, msg);
- // 过滤接收的系统消息
- if (MsgType.MSG_SYSTEM_GROUP.includes(message.messageType)){
- return;
- }
- const systemStore = useSystemStore();
- let index = systemStore.ImsessionList.findIndex(val=> val.uuid == sessionId);
- // 已读未读
- let unReadNum = 0;
- const ts = message.timestamp || Math.floor(Date.now());
- const time = new Date(ts).toLocaleString().replaceAll("/", "-");
- // 消息类型映射
- const mapSet = {
- [MsgType.MSG_TYPE.FILE]: '[文件]',
- [MsgType.MSG_TYPE.IMAGE]: '[图片]',
- [MsgType.MSG_TYPE.AUDIO]: '[音频]',
- [MsgType.MSG_TYPE.VIDEO]: '[视频]',
- [MsgType.MSG_TYPE.AUDIO_ONLINE]: '[语音通话]',
- [MsgType.MSG_TYPE.VIDEO_ONLINE]: '[视频通话]',
- // [Constant.CANCELL_AUDIO_ONLINE]:'[通话结束]',
- // [Constant.REJECT_AUDIO_ONLINE]: '[对方拒绝]',
- // [Constant.CANCELL_VIDEO_ONLINE]: '[通话结束]',
- // [Constant.REJECT_VIDEO_ONLINE]: '[对方拒绝]',
- };
- // 检测最新消息
- let lastMsg = message.contentType === MsgType.MSG_TYPE.TEXT || message.contentType === MsgType.MSG_TYPE.NOTICE ? (msg?msg.content : message.content) : (mapSet[message.contentType] || '[语音视频]');
- // let lastMsg = msg ? msg.content : message.content;
- // 阅后即焚消息
- if(message.isTemp){
- lastMsg = '[阅后即焚]';
- }
- // 额外数据
- const ext = {
- updatedAt: time,
- };
- // 修改群公告信息
- if (message.nickname) {
- ext.sessionName = message.nickname
- }
- if (message.notice) {
- ext.notice = message.notice
- }
- if (message.slience || message.slience === 0) {
- ext.slience = message.slience
- }
- if (message.stick || message.stick === 0) {
- ext.stick = message.stick
- }
- // 补充消息完整性
- // 更新并排序
- if(index >= 0){
- systemStore.ImsessionList = [...systemStore.ImsessionList].map((item)=>{
- if (item.uuid == sessionId){
- // console.log('111', item, lastMsg, lastMsg,item.message)
- return { ...item, ...ext, unReadNum: item.unReadNum + 1, message: lastMsg || item.message};
- }
- return item;
- }).sort((a, b) => b.stick - a.stick || new Date(b.updatedAt) - new Date(a.updatedAt));
- // 软刷新会话列表
- this.needRefreshIm += 1;
- return;
- }
- // 强制刷新会话列表
- this.chatRefresh += 1;
- },
- // 修改好友备注后,将好友会话名称更改
- updateNote(newName,uuid){
- const systemStore = useSystemStore();
- systemStore.ImsessionList = [...systemStore.ImsessionList].map((item) => {
- if (item.uuid == uuid) {
- return { ...item, sessionName: newName };
- }
- return item;
- })
- if (this.toUserInfo.uuid == uuid){
- this.toUserInfo.sessionName = newName;
- }
- },
- // ************ 接收方 方法 ************//
- // 监听好友系统消息
- listenFriendSystem(message) {
- // 好友申请
- if (message.messageType == MsgType.MESSAGE_APPLY_FRIEND) {
- this.addFriendApply(message.from);
- }
- // 好友通过
- if (message.messageType == MsgType.MESSAGE_PASS_FRIEND) {
- // 移除好友申请记录
- this.deleteFriendApply(message.from);
- // 恢复会话功能
- this.funRestoreDelAuth(message.from);
- // 需要更新会话或创建会话
- this.chatRefresh += 1;
- }
- // 好友删除
- if (message.messageType == MsgType.MESSAGE_DELETE_FRIEND) {
- // 禁用会话功能
- this.funDeleteDelAuth(message.from);
- // 需要删除会话
- // 删除本地消息记录
- this.deleteMessage(message, true);
- }
- },
- // 监控群系统消息
- listenGroupSystemMessage(message, msg = null) {
- console.log('群系统消息', message, msg);
- // 解散群/提出群/退群
- if (message.messageType == MsgType.DELETE_GROUP || message.messageType == MsgType.REMOVE_GROUP || message.messageType == MsgType.EXIT_GROUP) {
- // 如果存在于users中(被提出或退出的人)或者解散群
- if ((msg && msg.users && msg.users.includes(message.to)) || message.messageType == MsgType.DELETE_GROUP) {
- // 禁用会话功能
- this.funDeleteDelAuth(message.from);
- // 删除会话
- this.deleteSessionChat(message.from);
- }
- }
- // 创建群/加入群/邀请入群
- if (message.messageType == MsgType.CREATE_GROUP || message.messageType == MsgType.JION_GROUP || message.messageType == MsgType.INVITATION_GROUP) {
- // console.log('群系统消息', message, msg);
- if (message.messageType == MsgType.JION_GROUP || message.messageType == MsgType.INVITATION_GROUP) {
- // 恢复会话功能
- this.funRestoreDelAuth(message.from);
- }
- // 刷新会话列表
- this.chatRefresh += 1;
- }
- // 群通知
- if (message.messageType == MsgType.MESSAGE_NOTICE_GROUP) {
- // 更新群名称和群公告
- this.funGroupNotice(msg);
- }
- // 处理群置顶
- if (message.messageType === MsgType.MESSAGE_STICKY_GROUP) {
- }
- // 更新群成员列表
- this.fetchGroupMembers(message.from,true);
- // 处理@群成员
- if (message.messageType == MsgType.MESSAGE_CC_GROUP){
- let ccArr = msg?.cc.split(',');
- if (this.groupMembersList && this.groupMembersList[message.from]) {
- this.isassign = this.groupMembersList[message.from].filter(val => ccArr.includes(val.userId + '')).find(val => val.uuid == message.to)
- }
- }
- // 处理群个人昵称
- if (message.messageType == MsgType.MESSAGE_NICKNAME_GROUP){
- this.modifyMessage(message,(val)=>{
- return msg.uuid == val.fromUuid?{
- fromUsername: msg.name
- } : (msg.uuid == val.toUuid ? {
- toUsername: msg.name
- }:{})
- });
- // 个人群昵称
- if (msg.name) {
- this.updateSessionNewMessage({ name: msg.name }, msg.uuid);
- if (this.toUserInfo.uuid === msg.uuid) {
- this.toUserInfo.nickname = msg.name
- }
- }
- }
- },
- // 语音视频通知
- // 群通知更新群名称和公告
- funGroupNotice(msg){
- this.toUserInfo = {
- ...this.toUserInfo,
- // 群公告
- notice: msg && msg.notice?msg.notice: this.toUserInfo.notice,
- nickname: msg && msg.name?msg.name:this.toUserInfo.nickname,
- // 群名称
- sessionName: msg && msg.name?msg.name:this.toUserInfo.sessionName,
- }
- },
- // 群消息置顶
- funGroupTop(message = null) {
- },
- // ************ 发送方 方法 ************//
- // 同意或者拒绝好友操作
- funApprovalFriend(message){
- if (message.messageType == MsgType.MESSAGE_REJECT_FRIEND || message.messageType == MsgType.MESSAGE_PASS_FRIEND) {
- console.log(message, this.applyfriend);
-
- // 删除申请记录
- this.deleteFriendApply(message.to);
- // 恢复会话权限
- this.funRestoreDelAuth(message.to);
- // 刷新/更新会话列表
- this.chatRefresh += 1;
- }
- this.funDeleteFriend(message)
- },
- // 删除好友操作
- funDeleteFriend(message) {
- if (message.messageType == MsgType.MESSAGE_DELETE_FRIEND) {
- // 禁用会话功能
- this.funDeleteDelAuth(message.to);
- // 删除本地消息记录
- this.deleteMessage(message, true,message.to);
- // 更新会话列表
- }
- },
- // ************ 公用 ************//
- // 删除好友申请记录
- deleteFriendApply(uuid){
- if (this.applyfriend[uuid]) {
- delete this.applyfriend[uuid]
- }
- this.unread = Object.keys(this.applyfriend).length > 0;
- },
- // 更新好友申请记录
- updateFriendApply(list){
- Array.isArray(list) && list.forEach(val=>{
- if (typeof val == 'string'){
- this.applyfriend[val] = 1;
- return;
- }
- this.applyfriend[val.uuid] = 1
- });
- this.unread = Object.keys(this.applyfriend).length > 0;
- },
- // 添加好友申请记录
- addFriendApply(uuid){
- this.applyfriend[uuid] = 1;
- this.unread = true;
- },
- // 初始化好友申请记录
- async funInitfriend(uuid,force=false){
- console.log('好友申请数据',this.applyfriend)
- if (!force && Object.keys(this.applyfriend).length > 0){
- this.unread = true;
- return
- };
- this.applyfriend = {}
- const res = await friendRequest({ uuid, status: 1,state:1 });
- this.updateFriendApply(res.data || []);
- },
- // 初始化用户群权限
- async funInitGroupAuth(uuid){
- },
- // 更新用户群权限
- updateGroupAuth(data){
- Array.isArray(data) && data.forEach(item=>{
- if(typeof item === 'string'){
- this.chatGroupAuth[item] = 1;
- return;
- }
- this.chatGroupAuth[item.uuid] = 1
- });
- console.log(this.chatGroupAuth)
- },
- // 校验会话权限
- verifyChatAuth(uuid){
- if(this.chatDelAuth[uuid] && !this.chatGroupAuth[uuid]){
- return false;
- }
- return true;
- },
- //恢复会话权限
- funRestoreDelAuth(uuid) {
- if (this.chatDelAuth[uuid]) {
- delete this.chatDelAuth[uuid]
- }
- this.chatGroupAuth[uuid] = 1;
- },
- // 禁用会话权限
- funDeleteDelAuth(uuid){
- this.chatDelAuth[uuid] = 1;
- if(this.chatGroupAuth[uuid]){
- delete this.chatGroupAuth[uuid]
- }
- },
- // 更新会话未读状态
- funUpdateUnread(uuid) {
- const systemStore = useSystemStore();
- let index = systemStore.ImsessionList ? systemStore.ImsessionList.findIndex(s => (s.uuid || s.id) === uuid) : -1;
- if (index > -1) {
- systemStore.ImsessionList[index].unReadNum = 0;
- }
- },
- // 删除会话列表
- deleteSessionChat(uuid) {
- const systemStore = useSystemStore();
- let sessions = systemStore.ImsessionList ? [...systemStore.ImsessionList] : [];
- let index = sessions.findIndex(s => (s.uuid || s.id) === uuid);
- if (index > -1) {
- sessions.splice(index, 1);
- systemStore.ImsessionList = sessions;
- }
- },
- // 群成员列表
- async fetchGroupMembers(uuid,force = false) {
- // if (this.toUserInfo.type !== 'group') {
- // return []
- // }
- // 如果已有缓存且不强制刷新,直接返回
- if (!force && this.groupMembersList[uuid]) {
- return this.groupMembersList[uuid]
- }
- try {
- const res = await groupList(uuid)
- const members = res.data || []
- // 更新缓存
- this.groupMembersList[uuid] = members
- return members
- } catch (e) {
- console.error('获取群成员失败', e)
- return []
- }
- },
- // 清除数据
- deleteData(){
- const systemStore = useSystemStore();
- systemStore.messageList = {};
- this.messages = [];
- this.groupMembersList = {};
- this.toUserInfo = {};
- this.toUserAudioInfo = {};
- this.messageQueue = [];
- systemStore.ImsessionList = [];
- this.onMessageCallbacks = [];
- this.applyfriend = {};
- this.unread = false;
- this.chatDelAuth = {};
- this.chatGroupAuth = {};
- this.chatRefresh = 0;
- this.needRefreshIm = 0;
- this.indexs = 0;
- this.isassign = false;
- this.disconnect();
- }
- },
- });
|