import { ref, onMounted, onUnmounted, watch } from 'vue'; import { getConversationSync, getMessageSync, getChatKey } from '@/api/common' import { Base64 } from 'js-base64' import { useUserStore } from '@/store/user' import { useLoginType } from '@/store/loginType' import { useIMStore } from '@/store/im' // 配置悟空IM import { MessageText, Channel, WKSDK, ChannelTypePerson, // Conversation, // Message, StreamItem, ChannelTypeGroup, MessageStatus, SyncOptions, MessageExtra, MessageContent } from "wukongimjssdk" const HISTORY_QUERY = { limit: 30, startMessageSeq: 0, endMessageSeq: 0, pullMode: 1 } const ConnectStatus = { Disconnect: 0, // 断开连接 Connected: 1, // 连接成功 Connecting: 2, // 连接中 ConnectFail: 3, // 连接错误 ConnectKick: 4, // 连接被踢,服务器要求客户端断开(一般是账号在其他地方登录,被踢) } // api 接入 export function useDataSource () { const userStore = useUserStore() const loginType = useLoginType() // 最近会话数据源 if (!WKSDK.shared().config.provider.syncConversationsCallback) { WKSDK.shared().config.provider.syncConversationsCallback = async () => { const query = { msg_count: 100 } if (loginType.loginType === 'enterprise') { Object.assign(query, { enterpriseId: userStore.baseInfo.enterpriseId }) } const resultConversations = [] const resp = await getConversationSync(query) // console.log(resp) const conversationList = resp if (conversationList) { conversationList.forEach(conversation => { conversation.channel = new Channel(conversation.channel_id, conversation.channel_type) conversation.unread = +(conversation.unread || 0) resultConversations.push(conversation) }) } return resultConversations } } if (!WKSDK.shared().config.provider.syncMessagesCallback) { // 同步频道消息数据源 WKSDK.shared().config.provider.syncMessagesCallback = async function(channel) { // 后端提供的获取频道消息列表的接口数据 然后构建成 Message对象数组返回 let resultMessages = new Array() const { startMessageSeq: start_message_seq, endMessageSeq: end_message_seq, limit, pullMode: pull_mode } = HISTORY_QUERY const query = { channel_id: channel.channelID, channel_type: channel.channelType, start_message_seq, end_message_seq, limit, pull_mode, } if (loginType.loginType === 'enterprise') { Object.assign(query, { enterpriseId: userStore.baseInfo.enterpriseId }) } const resp = await getMessageSync(query) const messageList = resp && resp["messages"] if (messageList) { messageList.forEach((msg) => { // const message = Convert.toMessage(msg); // msg.channel = new Channel(msg.channel_id, msg.channel_type) msg.payload = JSON.parse(Base64.decode(msg.payload)) resultMessages.push(msg); }); } const more = resp.more === 1 return { more, resultMessages } } } } // function toConversation (conversationMap) { // const conversation = new Conversation() // conversation.channel = new Channel(conversationMap['channel_id'], conversationMap['channel_type']) // conversation.unread = conversationMap['unread'] || 0; // conversation.timestamp = conversationMap['timestamp'] || 0; // // let recents = conversationMap["recents"]; // // if (recents && recents.length > 0) { // // const messageModel = toMessage(recents[0]); // // conversation.lastMessage = messageModel // // } // conversation.extra = {} // return conversation // } // function toMessage(msgMap) { // const message = new Message(); // if (msgMap['message_idstr']) { // message.messageID = msgMap['message_idstr']; // } // // else { // // message.messageID = new BigNumber(msgMap['message_id']).toString(); // // } // if (msgMap["header"]) { // message.header.reddot = msgMap["header"]["red_dot"] === 1 ? true : false // } // // if (msgMap["setting"]) { // // message.setting = Setting.fromUint8(msgMap["setting"]) // // } // if (msgMap["revoke"]) { // message.remoteExtra.revoke = msgMap["revoke"] === 1 ? true : false // } // if(msgMap["message_extra"]) { // const messageExtra = msgMap["message_extra"] // message.remoteExtra = this.toMessageExtra(messageExtra) // } // message.clientSeq = msgMap["client_seq"] // message.channel = new Channel(msgMap['channel_id'], msgMap['channel_type']); // message.messageSeq = msgMap["message_seq"] // message.clientMsgNo = msgMap["client_msg_no"] // message.streamNo = msgMap["stream_no"] // message.streamFlag = msgMap["stream_flag"] // message.fromUID = msgMap["from_uid"] // message.timestamp = msgMap["timestamp"] // message.status = MessageStatus.Normal // const contentObj = JSON.parse(Base64.decode(msgMap["payload"])) // // const contentObj = JSON.parse(decodedBuffer.toString('utf8')) // let contentType = 0 // if (contentObj) { // contentType = contentObj.type // } // const messageContent = WKSDK.shared().getMessageContent(contentType) // if (contentObj) { // messageContent.decode(this.stringToUint8Array(JSON.stringify(contentObj))) // } // message.content = messageContent // message.isDeleted = msgMap["is_deleted"] === 1 // const streamMaps = msgMap["streams"] // if(streamMaps && streamMaps.length>0) { // const streams = [] // for (const streamMap of streamMaps) { // const streamItem = new StreamItem() // streamItem.clientMsgNo = streamMap["client_msg_no"] // streamItem.streamSeq = streamMap["stream_seq"] // streams.push(streamItem) // } // message.streams = streams // } // return message // } async function getKey () { const userStore = useUserStore() const loginType = useLoginType() const keyQuery = { userId: userStore.userInfo.id } if (loginType.loginType === 'enterprise') { Object.assign(keyQuery, { enterpriseId: userStore.baseInfo.enterpriseId }) } const { uid, wsUrl, token } = await getChatKey(keyQuery) return { uid, wsUrl, token } } export const useIM = async () => { const IM = useIMStore() const unreadCount = ref(0) const connected = ref(0) // 通过自身userId和企业id获取token和uid const { uid, wsUrl, token } = await getKey() IM.setUid(uid) // 单机模式可以直接设置地址 WKSDK.shared().config.addr = 'ws://' + wsUrl // 默认端口为5200 // 认证信息 WKSDK.shared().config.uid = uid // 用户uid(需要在悟空通讯端注册过) WKSDK.shared().config.token = token // 用户token (需要在悟空通讯端注册过) // onMounted(() => { // console.log('1') // 连接状态监听 WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener) // console.log('2') // 常规消息监听 WKSDK.shared().chatManager.addMessageListener(messageListen) // 连接 // console.log('连接') WKSDK.shared().connectManager.connect() // }) onUnmounted(() => { WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener) // 常规消息监听移除 WKSDK.shared().chatManager.removeMessageListener(messageListen) // 连接状态监听移除 WKSDK.shared().connectManager.disconnect() }) async function messageListen (message) { console.log('收到消息', message) IM.setFromChannel(message.channel.channelID) const count = WKSDK.shared().conversationManager.getAllUnreadCount() IM.setNewMsg(count) unreadCount.value = count // console.log('未读消息数', count) // 创建通道 } async function connectStatusListener (status) { // console.log('连接状态', status === ConnectStatus.Connected) connected.value = status === ConnectStatus.Connected } return { unreadCount, connected } } export function initConnect (callback = () => {}) { const IM = useIMStore() const conversationList = ref([]) const messageItems = ref([]) watch( () => IM.newMsg, () => { // 未读消息变化 syncConversation() // 拉取最新消息 查看是否是自己的数据 }, { deep: true, immediate: true } ) onMounted(async () => { // 消息发送状态监听 WKSDK.shared().chatManager.addMessageStatusListener(statusListen) // 常规消息监听 // WKSDK.shared().chatManager.addMessageListener(messageListen) }) onUnmounted(() => { // 消息发送状态监听移除 WKSDK.shared().chatManager.removeMessageStatusListener(statusListen) // 常规消息监听移除 // WKSDK.shared().chatManager.removeMessageListener(messageListen) }) // 消息发送状态监听 function statusListen (packet) { if (packet.reasonCode === 1) { // 发送成功 console.log('发送成功') // 添加一组成功数据 callback() } else { // 发送失败 console.log('发送失败') // 添加一组失败数据 // callback() } } // 常规消息监听 // async function messageListen (message) { // console.log('收到消息', message) // syncConversation() // } // 同步最近会话 async function syncConversation () { const res = await WKSDK.shared().conversationManager.sync() conversationList.value = res return res // return new Promise((resolve, reject) => { // WKSDK.shared().conversationManager.sync().then(res => { // conversationList.value = res // resolve(res) // }).catch(error => { // reject(error) // }) // }) } return { // connected, conversationList, messageItems, // channel } } // export async function getRecentMessages (channel) { // const { resultMessages, more } = await WKSDK.shared().chatManager.syncMessages(channel, HISTORY_QUERY) // // console.log(res) // // return resultMessages.map(_e => { // // _e.payload = JSON.parse(Base64.decode(_e.payload)) // // return _e // // }) // } // 发起聊天 export async function initChart (userId, enterpriseId) { const channel = ref() // const list = ref([]) const query = { userId, enterpriseId } // 创建聊天频道 const { uid } = await getChatKey(query) const _channel = new Channel(uid, ChannelTypePerson) channel.value = _channel const conversation = WKSDK.shared().conversationManager.findConversation(_channel) if(!conversation) { // 如果最近会话不存在,则创建一个空的会话 WKSDK.shared().conversationManager.createEmptyConversation(_channel) } const res = await getMoreMessages(1, _channel) return { channel, ...res } } // 翻页 export async function getMoreMessages (pageSize, channel) { const list = ref([]) Object.assign(HISTORY_QUERY, { startMessageSeq: (pageSize - 1) * HISTORY_QUERY.limit }) const { resultMessages, more } = await WKSDK.shared().chatManager.syncMessages(channel) list.value = resultMessages return { list, more } } export function send (text, _channel) { const _text = new MessageText(text) // 文本消息 console.log('发送', _text, _channel) WKSDK.shared().chatManager.send(_text, _channel) }