|
@@ -3,6 +3,7 @@ import { defineStore } from "pinia";
|
|
|
import { $root as protobuf } from "@/common/proto/proto";
|
|
|
import * as Constant from "@/common/constant/Constant";
|
|
|
import { useWalletStore } from "@/stores/modules/walletStore";
|
|
|
+import { getMessageApi } from "@/api/path/im.api"
|
|
|
|
|
|
export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
// 状态定义
|
|
@@ -15,7 +16,7 @@ export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
reconnectInterval: 3000, // 重连间隔
|
|
|
messages: [], // 消息列表
|
|
|
unreadMessages: [], // 未读消息列表
|
|
|
- lastMessage: null, // 最后一条消息
|
|
|
+ uuid: null,
|
|
|
|
|
|
// 心跳检测配置
|
|
|
heartCheck: {
|
|
@@ -30,10 +31,20 @@ export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
getters: {
|
|
|
isConnected: (state) => state.socket?.readyState === WebSocket.OPEN,
|
|
|
hasUnreadMessages: (state) => state.unreadMessages.length > 0,
|
|
|
+
|
|
|
+
|
|
|
},
|
|
|
|
|
|
// 方法
|
|
|
actions: {
|
|
|
+ async getMessages(params){
|
|
|
+ const { data } = await getMessageApi({
|
|
|
+ messageType: params.messageType,
|
|
|
+ uuid: params.uuid,
|
|
|
+ friendUsername: params.friendUsername,
|
|
|
+ })
|
|
|
+ this.messages = data || []
|
|
|
+ },
|
|
|
// 初始化socket
|
|
|
startHeartbeat() {
|
|
|
const self = this;
|
|
@@ -73,6 +84,7 @@ export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
},
|
|
|
// 链接ws
|
|
|
connect(userUuid) {
|
|
|
+ if(!userUuid) return
|
|
|
console.log("开始连接...");
|
|
|
this.disconnect(); // 确保先断开现有连接
|
|
|
|
|
@@ -121,10 +133,13 @@ export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
});
|
|
|
|
|
|
console.log("收到消息:", message);
|
|
|
-
|
|
|
- // 更新状态
|
|
|
- this.messages.push(message);
|
|
|
- this.lastMessage = message;
|
|
|
+ if([1,2].includes(message.messageType)){
|
|
|
+ // 更新状态
|
|
|
+ this.messages.push({
|
|
|
+ ...message,
|
|
|
+ toUsername: message.to,
|
|
|
+ });
|
|
|
+ }
|
|
|
|
|
|
if (message.type === "heatbeat") return;
|
|
|
|
|
@@ -216,12 +231,19 @@ export const useWebSocketStore = defineStore("webSocketStore", {
|
|
|
fromUsername: walletStore.username,
|
|
|
from: walletStore.account,
|
|
|
};
|
|
|
-
|
|
|
+ if([1,2].includes(message.messageType)){
|
|
|
+ this.messages.push({
|
|
|
+ ...data,
|
|
|
+ toUsername: data.friendUsername
|
|
|
+ });
|
|
|
+ }
|
|
|
try {
|
|
|
const MessageType = protobuf.lookupType("protocol.Message");
|
|
|
const messagePB = MessageType.create(data);
|
|
|
const buffer = MessageType.encode(messagePB).finish();
|
|
|
this.socket.send(buffer);
|
|
|
+
|
|
|
+
|
|
|
return true;
|
|
|
} catch (error) {
|
|
|
console.error("消息编码错误:", error);
|