Forráskód Böngészése

企微聊天获取新消息改为webSocket

Long 2 hete
szülő
commit
b7b906829b

+ 3 - 3
src/components/VideoPlayer/VueAliplayer.vue

@@ -1,13 +1,13 @@
 <template>
   <div class="prism-player" :id="playerId" :style="playStyle">
-      <img  v-show="isShowPlay" @click="play()" :src="playIcon" class="btnPlay" />
+      <lemon-image  v-show="isShowPlay" @click="play()" :src="playIcon" class="btnPlay" />
   </div>
 </template>
 
 <script>
-import image from '../LemonUI/components/message/image.vue';
+import lemonImage from '../LemonUI/components/message/image.vue';
   export default {
-  components: { image },
+  components: { lemonImage },
     name: "Aliplayer",
     props: {
       source: {

+ 11 - 2
src/layout/index.vue

@@ -50,7 +50,7 @@
       </div>
     </div>
 
-    <el-dialog append-to-body width="1200px" :visible.sync="qw.open" :title="qw.title" :show-close="false">
+    <el-dialog append-to-body width="auto" custom-class="im-dialog" :visible.sync="qw.open" :title="qw.title" :show-close="false">
       <div class="qw-im-content">
         <QwIM :showQw="qw.open"/>
       </div>
@@ -330,9 +330,18 @@ export default {
   }
 }
 
+::v-deep .im-dialog {
+  div.el-dialog__header {
+    display: none;
+  }
+  .el-dialog__body {
+    padding: 0px !important;
+  }
+}
+
 .qw-im-content {
   width: 100%;
-  height: 730px;
+  height: 100%;
 }
 
 </style>

+ 65 - 0
src/utils/ImSocket.js

@@ -0,0 +1,65 @@
+export class ImSocket {
+  /**
+   * @param {string} url - WebSocket 服务器地址
+   * @param {number} checkInterval - 检查连接状态的时间间隔,单位毫秒
+   * @param {number} reconnectDelay - 连接断开后重连的延迟,单位毫秒
+   */
+  constructor(url, checkInterval = 5000, reconnectDelay = 3000) {
+    this.url = url;
+    this.checkInterval = checkInterval;
+    this.reconnectDelay = reconnectDelay;
+    this.ws = null;
+    this.isManualClose = false;
+    this.connect();
+    this.startHeartbeat();
+    this.onMessageCallback = null;
+  }
+
+  connect() {
+    this.ws = new WebSocket(this.url);
+
+    // 绑定事件
+    this.ws.onopen = (event) => {};
+
+    this.ws.onmessage = (event) => {
+      // 根据需要处理消息
+      if (this.onMessageCallback) this.onMessageCallback(event.data);
+    };
+
+    this.ws.onerror = (error) => {};
+
+    this.ws.onclose = (event) => {
+      // 如果不是主动关闭,则重连
+      if (!this.isManualClose) {
+        setTimeout(() => this.reconnect(), this.reconnectDelay);
+      }
+    };
+  }
+
+  reconnect() {
+    this.connect();
+  }
+
+  // 定时检查连接状态
+  startHeartbeat() {
+    this.heartbeatTimer = setInterval(() => {
+      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
+        this.reconnect();
+      }
+    }, this.checkInterval);
+  }
+
+  // 主动关闭 WebSocket 连接,并清除定时任务
+  close() {
+    this.isManualClose = true;
+    if (this.heartbeatTimer) {
+      clearInterval(this.heartbeatTimer);
+    }
+    if (this.ws) {
+      this.ws.close();
+    }
+  }
+  onMessage(callback) {
+    this.onMessageCallback = callback;
+  }
+}

+ 39 - 59
src/views/qw/qwChat/qq.vue

@@ -1,7 +1,7 @@
 <template>
   <div style="width: 100%;height: 100%">
 
-    <el-tabs type="card" v-model="appKey" @tab-click="qwUserChange">
+    <el-tabs class="im-tabs" type="card" v-model="appKey" @tab-click="qwUserChange">
       <el-tab-pane
         v-for="item in qwUserList"
         :key="item.id"
@@ -91,6 +91,8 @@ import EmojiData from "@/components/LemonUI/database/emoji";
 import '@/components/LemonUI/index.css';
 import VideoPlayer from '@/components/VideoPlayer/VueAliplayer.vue'
 import UserDetail from "@/views/qw/qwChat/userDetail/index.vue";
+import {ImSocket} from "@/utils/ImSocket";
+import {getToken} from '@/utils/auth'
 
 let pages = {};
 export default {
@@ -152,9 +154,7 @@ export default {
         title: '',
         open: false
       },
-      messagePollingTimer: null, // 定时器引用
-      pollingInterval: 5000,     // 轮询间隔(毫秒)
-      lastMessageIdMap: {},      // 记录每个会话最后一条消息ID
+      imSocket: null,
     };
   },
   created(){
@@ -166,6 +166,7 @@ export default {
         this.appKey = this.qwUser.appKey;
         this.setQwUserInfo();
         this.getConversation();
+        this.initImSocket(this.qwUser.companyId)
       }else {
         this.qwUser={};
       }
@@ -177,19 +178,10 @@ export default {
         this.$nextTick(() => {
           this.$refs.IMUI.messageViewToBottom();
         });
-        this.startMessagePolling()
-      }
-      else {
-        this.stopMessagePolling();
       }
     }
   },
   mounted() {
-    this.$watch('appKey', (newValue, oldValue) => {
-      if (newValue) {
-        console.log("appkey====",newValue);
-      }
-    });
     this.showQW=true;
     const IMUI = this.$refs.IMUI;
 
@@ -204,13 +196,27 @@ export default {
       }
     ]);
     IMUI.initEmoji(EmojiData);
-
-    this.startMessagePolling(); // 启动定时轮询
   },
   beforeDestroy() {
-    this.stopMessagePolling();
+    if (this.imSocket) {
+      this.imSocket.close();
+    }
   },
   methods: {
+    initImSocket(companyId) {
+      this.imSocket = new ImSocket(`ws://127.0.0.1:8667/qwImSocket/${companyId}?token=${getToken()}`);
+      this.imSocket.onMessage(data => {
+        const { IMUI } = this.$refs;
+        let message = JSON.parse(data);
+        this.appendRemoteMessage(message)
+        let conversation = IMUI.findConversation(message.toContactId);
+        if (conversation.msgId) {
+          conversation.lastSendTime = message.sendTime;
+          conversation.lastContent = message.content;
+          IMUI.topPopConversations(conversation);
+        }
+      })
+    },
     // 切换企微账号
     qwUserChange(tab, event){
       this.appKey = tab.name;
@@ -219,7 +225,6 @@ export default {
       this.getConversation();   //获取会话信息
       this.setQwUserInfo();
     },
-
     setQwUserInfo(){
       this.userData.id=this.qwUser.id;
       this.userData.displayName=this.qwUser.qwUserName;
@@ -229,12 +234,6 @@ export default {
       const IMUI = this.$refs.IMUI;
       getConversations(this.qwUser.id).then(response => {
         this.conversationData = response.data;
-        // 初始化msgId
-        if (Array.isArray(response.data)) {
-          response.data.forEach(conversation => {
-            this.lastMessageIdMap[conversation.conversationId] = conversation.msgId || 0;
-          });
-        }
         IMUI.initConversations(response.data);
         const fstConversation = this.conversationData[0];
         if(fstConversation) {
@@ -352,6 +351,14 @@ export default {
           }
         });
       }
+      // image
+      else if(message.type === "image"){
+        console.log("Event:image-click", message, next, file)
+      }
+      // file
+      else if(message.type === "file"){
+        console.log("Event:file-click", message, next, file)
+      }
     },
     handleMenuAvatarClick() {
       console.log("Event:menu-avatar-click");
@@ -489,42 +496,6 @@ export default {
         this.$refs.userDetail.getDetail(sessionId);
       }, 1);
     },
-    startMessagePolling() {
-      this.stopMessagePolling(); // 避免重复启动
-      this.messagePollingTimer = setInterval(() => {
-        this.fetchAllConversationsLatestMessages();
-      }, this.pollingInterval);
-    },
-    stopMessagePolling() {
-      if (this.messagePollingTimer) {
-        clearInterval(this.messagePollingTimer);
-        this.messagePollingTimer = null;
-      }
-    },
-    fetchAllConversationsLatestMessages() {
-      if (!this.qwUser || !this.conversationData) return;
-      this.conversationData.forEach(conversation => {
-        const lastMsgId = this.lastMessageIdMap[conversation.conversationId] || 0;
-        const params = {
-          pageNum: 1,
-          pageSize: 20,
-          conversationId: conversation.conversationId,
-          userId: this.qwUser.id,
-          msgId: lastMsgId // 用消息ID拉取新消息
-        };
-        getMessageList(params).then(response => {
-          if (response.code === 200 && response.data && response.data.list) {
-            response.data.list.forEach(msg => {
-              // 更新lastMessageIdMap
-              if (!this.lastMessageIdMap[conversation.conversationId] || msg.id > this.lastMessageIdMap[conversation.conversationId]) {
-                this.lastMessageIdMap[conversation.conversationId] = msg.id;
-              }
-              this.appendMessageAction(msg);
-            });
-          }
-        });
-      });
-    },
   },
 };
 </script>
@@ -569,6 +540,15 @@ export default {
   margin-top: 0 !important;
 }
 
+::v-deep .im-tabs {
+  .el-tabs__header {
+    margin: 0 !important;
+    .el-tabs__item {
+      border-bottom: 0 !important;
+    }
+  }
+}
+
 </style>