Files
ZhHealth/utils/im/index.js

147 lines
3.4 KiB
JavaScript

import * as RongIMLib from '@rongcloud/imlib-uni'
import store from '@/store/index.js'
import {
getFriends
} from '@/apis/interfaces/im.js'
const initIm = (KEY) => {
RongIMLib.init(KEY)
addListeners()
}
const setNotifyBadge = (count) => {
// 获取未读消息数量
RongIMLib.getTotalUnreadCount(({
code,
count
}) => {
if (code === 0) {
if (count > 0) {
uni.setTabBarBadge({
index: 2,
text: String(count > 99 ? '99+' : count)
})
} else {
uni.removeTabBarBadge({
index: 2
})
}
}
})
}
/**
* 连接IM服务
* @param {string} token token
* @param {object} userInfo {userId: string, name: string, portraitUrl: string}
*/
const connect = (token, userInfo) => {
RongIMLib.connect(token, res => {
console.log('连接结果', res);
})
store.dispatch('setSenderInfo', userInfo)
setNotifyBadge()
}
const disconnect = () => {
RongIMLib.disconnect()
}
const addListeners = () => {
// 添加连接状态监听函数
RongIMLib.addConnectionStatusListener((res) => {
console.log('连接状态监', res.data.status);
})
// 添加消息监听函数
RongIMLib.addReceiveMessageListener((res) => {
console.log('收到消息', res.data.message);
newMessage(res.data.message)
})
}
// 维护消息列表
const newMessage = (msg) => {
RongIMLib.getConversationNotificationStatus(msg.conversationType, msg.targetId, ({
code,
status
}) => {
if (code === 0) {
if (status) {
triTone()
}
}
});
setNotifyBadge()
store.dispatch('newMessage', msg)
}
// 播放状态
let tipState = false
const triTone = () => {
if (tipState == false) {
const innerAudioContext = uni.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = '/static/tri-tone.mp3'
innerAudioContext.onPlay(() => {
tipState = true
})
innerAudioContext.onEnded(() => {
tipState = false
})
}
}
/**
* 发送消息
* @param {number} conversationType 消息类型
* @param {string} targetId 会话id
* @param {string} content 消息内容
* @param {function} callback 回调函数
*/
const sendMsg = (conversationType, targetId, content, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:TxtMsg',
content: content,
user: store.getters.sender
}
}
RongIMLib.sendMessage(msg, ({
code,
messageId
}) => {
if (code === 0) {
callback(messageId)
} else {
uni.showToast({
icon: 'none',
title: '发送失败'
})
}
})
}
/**
* 同步好友信息,保存头像地址等
*/
const syncFriends = () => {
getFriends().then(res => {
store.dispatch('updateFriends', res)
})
}
export default {
initIm,
connect,
sendMsg,
setNotifyBadge,
syncFriends
}