IM部分的备注,消息发送代码分离

This commit is contained in:
2022-02-07 11:01:36 +08:00
parent d19f1378a6
commit b202a62d5d
5 changed files with 807 additions and 713 deletions

View File

@@ -5,6 +5,7 @@
export default { export default {
onLaunch: function() { onLaunch: function() {
im.initIm('lmxuhwaglu76d') im.initIm('lmxuhwaglu76d')
return
//#ifdef APP-PLUS //#ifdef APP-PLUS
// 获取系统版本号 // 获取系统版本号
getVersions({ getVersions({

View File

@@ -15,9 +15,9 @@
<view class="item" @click="scanQrCode"> <view class="item" @click="scanQrCode">
<uni-icons color="#555" type="scan" size="22"></uni-icons> <uni-icons color="#555" type="scan" size="22"></uni-icons>
</view> </view>
<view class="item" @click="onNav('', {})"> <!-- <view class="item" @click="onNav('', {})">
<uni-icons color="#555" custom-prefix="iconfont" type="icon-gengduo2" size="22"></uni-icons> <uni-icons color="#555" custom-prefix="iconfont" type="icon-gengduo2" size="22"></uni-icons>
</view> </view> -->
</view> </view>
</view> </view>
</view> </view>
@@ -130,14 +130,16 @@
} }
} }
}, },
methods: { methods: {
// 隐藏功能菜单
hidePop() { hidePop() {
this.showPop = false this.showPop = false
this.pickedItem = {} this.pickedItem = {}
setTimeout(() => { setTimeout(() => {
this.showShade = false this.showShade = false
}, 250) }, 250)
}, },
// 点击会话功能菜单
pickerMenu(e) { pickerMenu(e) {
const index = Number(e.currentTarget.dataset.index) const index = Number(e.currentTarget.dataset.index)
@@ -150,7 +152,8 @@
im.setNotifyBadge() im.setNotifyBadge()
this.getConversationList() this.getConversationList()
this.hidePop() this.hidePop()
}, },
// 长按会话,展示功能菜单
onLongPress(e) { onLongPress(e) {
let [touches, style, item] = [e.touches[0], "", e.currentTarget.dataset.item] let [touches, style, item] = [e.touches[0], "", e.currentTarget.dataset.item]
@@ -217,7 +220,8 @@
params params
}) })
} }
}, },
// 调起扫码
scanQrCode() { scanQrCode() {
uni.scanCode({ uni.scanCode({
success: (res) => { success: (res) => {

View File

@@ -1,418 +1,417 @@
<template> <template>
<view class="chat"> <view class="chat">
<!-- chat --> <!-- chat -->
<list class="chat-scroll"> <list class="chat-scroll">
<cell class="cell" v-for="(item, index) in messages" :key="index"> <cell class="cell" v-for="(item, index) in messages" :key="index">
<view class="cell-time"> <view class="cell-time">
<text class="cell-time-text">{{ customCN(item.sentTime) }}</text> <text class="cell-time-text">{{ customCN(item.sentTime) }}</text>
</view> </view>
<view class="cell-item" :class="item.messageDirection == 1 ? 'right' : 'left'"> <view class="cell-item" :class="item.messageDirection == 1 ? 'right' : 'left'">
<image class="active" :src="userInfo.portraitUrl" mode="aspectFill" <image class="active" :src="userInfo.portraitUrl" mode="aspectFill"
@click="showFriend(targetId, item.messageDirection)"></image> @click="showFriend(targetId, item.messageDirection)"></image>
<view class="msg"> <view class="msg">
<imAUDIO v-if="item.objectName === 'RC:HQVCMsg'" :guest="item.messageDirection == 1" <imAUDIO v-if="item.objectName === 'RC:HQVCMsg'" :guest="item.messageDirection == 1"
:msg="item.content"></imAUDIO> :msg="item.content"></imAUDIO>
<imIMG v-if="item.objectName === 'RC:ImgMsg'" :guest="item.messageDirection == 1" <imIMG v-if="item.objectName === 'RC:ImgMsg'" :guest="item.messageDirection == 1"
:msg="item.content.content"></imIMG> :msg="item.content.content"></imIMG>
<imTXT v-if="item.objectName === 'RC:TxtMsg'" :guest="item.messageDirection == 1" <imTXT v-if="item.objectName === 'RC:TxtMsg'" :guest="item.messageDirection == 1"
:msg="item.content.content"></imTXT> :msg="item.content.content"></imTXT>
<view class="state" v-if="item.messageDirection == 1"> <view class="state" v-if="item.messageDirection == 1">
<text class="state-text">{{ item.sentStatus == 50 ? '已读': '未读'}}</text> <text class="state-text">{{ item.sentStatus == 50 ? '已读': '未读'}}</text>
</view> </view>
</view> </view>
</view> </view>
</cell> </cell>
<cell class="cell-footer" ref="chatBottom"></cell> <cell class="cell-footer" ref="chatBottom"></cell>
</list> </list>
<!-- footer --> <!-- footer -->
<view class="chat-footer"> <view class="chat-footer">
<view class="msg-type" @click="msgType"> <view class="msg-type" @click="msgType">
<image class="msg-type-icon" src="@/static/icon/key-icon.png" v-if="importTabs === 0" mode="widthFix"> <image class="msg-type-icon" src="@/static/icon/key-icon.png" v-if="importTabs === 0" mode="widthFix">
</image> </image>
<image class="msg-type-icon" src="@/static/icon/msg-icon.png" v-if="importTabs === 1" mode="widthFix"> <image class="msg-type-icon" src="@/static/icon/msg-icon.png" v-if="importTabs === 1" mode="widthFix">
</image> </image>
</view> </view>
<block v-if="importTabs === 0"> <block v-if="importTabs === 0">
<view class="chat-mp3" hover-class="chat-hover" @touchstart="startAudio" @touchend="chendAudio"> <view class="chat-mp3" hover-class="chat-hover" @touchstart="startAudio" @touchend="chendAudio">
<text class="chat-mp3-text">按住说话</text> <text class="chat-mp3-text">按住说话</text>
</view> </view>
</block> </block>
<block v-if="importTabs === 1"> <block v-if="importTabs === 1">
<input class="chat-input" type="text" v-model="inputTxt" confirm-type="发送" @confirm="send" <input class="chat-input" type="text" v-model="inputTxt" confirm-type="发送" @confirm="send"
cursor-spacing="10" /> cursor-spacing="10" />
</block> </block>
<text class="chat-push" size="mini" @click="send">发送</text> <text class="chat-push" size="mini" @click="send">发送</text>
</view> </view>
<!-- 录音中提示 --> <!-- 录音中提示 -->
<view class="audio-transcribe" v-if="showAudioTranscribe"> <view class="audio-transcribe" v-if="showAudioTranscribe">
<image class="audio-transcribe-src" src="@/static/icon/record-icon.png" mode="widthFix"></image> <image class="audio-transcribe-src" src="@/static/icon/record-icon.png" mode="widthFix"></image>
<text class="audio-transcribe-text">录音中 {{transcribeTime}} s</text> <text class="audio-transcribe-text">录音中 {{transcribeTime}} s</text>
</view> </view>
</view> </view>
</template> </template>
<script> <script>
import { import {
timeCustomCN timeCustomCN
} from '@/utils/filters.js' } from '@/utils/filters.js'
import * as RongIMLib from "@/uni_modules/RongCloud-IMWrapper/js_sdk/index" import * as RongIMLib from "@/uni_modules/RongCloud-IMWrapper/js_sdk/index"
import im from '@/utils/im/index.js' import im from '@/utils/im/index.js'
import permision from "@/js_sdk/wa-permission/permission.js" import permision from "@/js_sdk/wa-permission/permission.js"
import imAUDIO from '@/components/im/imAUDIO' import imAUDIO from '@/components/im/imAUDIO'
import imIMG from '@/components/im/imIMG' import imIMG from '@/components/im/imIMG'
import imTXT from '@/components/im/imTXT' import imTXT from '@/components/im/imTXT'
var transcribe var transcribe
var recorderManager = uni.getRecorderManager() var recorderManager = uni.getRecorderManager()
const ChatList = uni.requireNativePlugin('dom') const ChatList = uni.requireNativePlugin('dom')
export default { export default {
data() { data() {
return { return {
targetId: '', targetId: '',
scrollIntoID: 'chatID_0', scrollIntoID: 'chatID_0',
inputTxt: '', inputTxt: '',
messages: [], messages: [],
conversationType: 1, conversationType: 1,
userInfo: { userInfo: {
name: '', name: '',
userId: '', userId: '',
portraitUrl: '' portraitUrl: ''
}, },
importTabs: 1, importTabs: 1,
showAudioTranscribe: false, showAudioTranscribe: false,
transcribeTime: 60, transcribeTime: 60,
audioSrc: '', audioContextPaused: true
audioContextPaused: true }
} },
}, components: {
components: { imAUDIO,
imAUDIO, imIMG,
imIMG, imTXT
imTXT },
}, onLoad(e) {
onLoad(e) { this.targetId = e.targetId
this.targetId = e.targetId this.conversationType = e.conversationType // 会话类型
this.conversationType = e.conversationType // 会话类型 this.userInfo = this.$store.getters.userInfo(this.targetId)
this.userInfo = this.$store.getters.userInfo(this.targetId) uni.setNavigationBarTitle({
uni.setNavigationBarTitle({ title: this.$store.getters.userInfo(this.targetId).name
title: this.$store.getters.userInfo(this.targetId).name })
})
RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime())
RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime()) im.setNotifyBadge()
im.setNotifyBadge() RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
this.getMessageList()
this.getMessageList()
// 监听消息回执
// 监听消息回执 RongIMLib.addReadReceiptReceivedListener(({
RongIMLib.addReadReceiptReceivedListener(({ data
data }) => {
}) => { if (data.targetId == this.targetId) {
if (data.targetId == this.targetId) { this.getMessageList()
this.getMessageList() }
} })
})
// 监听收到新消息,判断是否是当前会话,更新会话内容
// 监听收到新消息,判断是否是当前会话,更新会话内容 uni.$on('onReceiveMessage', (msg) => {
uni.$on('onReceiveMessage', (msg) => { if (msg.targetId == this.targetId) {
if (msg.targetId == this.targetId) { RongIMLib.clearMessagesUnreadStatus(msg.conversationType, msg.targetId, msg.sentTime)
RongIMLib.clearMessagesUnreadStatus(msg.conversationType, msg.targetId, msg.sentTime) RongIMLib.sendReadReceiptMessage(msg.conversationType, msg.targetId, msg.sentTime)
RongIMLib.sendReadReceiptMessage(msg.conversationType, msg.targetId, msg.sentTime) this.getMessageList()
this.getMessageList() im.setNotifyBadge()
im.setNotifyBadge() }
} })
}) },
}, beforeDestroy() {
beforeDestroy() { uni.$off('onReceiveMessage')
uni.$off('onReceiveMessage') },
}, onUnload() {
onUnload() { RongIMLib.clearReadReceiptReceivedListener()
RongIMLib.clearReadReceiptReceivedListener() },
}, computed: {
computed: { disabled() {
disabled() { return this.inputTxt.length == 0
return this.inputTxt.length == 0 }
} },
}, onNavigationBarButtonTap(e) {
onNavigationBarButtonTap(e) { if (e.index == 0) {
if (e.index == 0) { uni.navigateTo({
uni.navigateTo({ url: '/pages/im/private/setting?targetId=' + this.targetId +
url: '/pages/im/private/setting?targetId=' + this.targetId + '&conversationType=' + this.conversationType,
'&conversationType=' + this.conversationType, events: {
events: { messageClear: () => {
messageClear: () => { this.getMessageList()
this.getMessageList() console.log('聊天消息被清空');
console.log('聊天消息被清空'); }
} }
} })
}) }
} },
}, methods: {
methods: { customCN(val) {
customCN(val) { return timeCustomCN(val)
return timeCustomCN(val) },
}, // 检查安卓录制权限
// 检查安卓录制权限 async getAndroidPermission() {
async getAndroidPermission() { return await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
return await permision.requestAndroidPermission('android.permission.RECORD_AUDIO') },
}, // 切换聊天信息
// 切换聊天信息 msgType() {
msgType() { this.importTabs = this.importTabs === 1 ? 0 : 1
this.importTabs = this.importTabs === 1 ? 0 : 1 },
}, // 录制语音消息
// 录制语音消息 startAudio(e) {
startAudio(e) { this.getAndroidPermission().then(code => {
this.getAndroidPermission().then(code => { switch (code) {
switch (code) { case 1:
case 1: this.showAudioTranscribe = true
this.showAudioTranscribe = true recorderManager.start()
recorderManager.start() transcribe = setInterval(() => {
transcribe = setInterval(() => { this.transcribeTime -= 1
this.transcribeTime -= 1 if (this.transcribeTime === 0) {
if (this.transcribeTime === 0) { this.chendAudio()
this.chendAudio() }
} }, 1000)
}, 1000) break;
break; case 0:
case 0: uni.showToast({
uni.showToast({ title: '暂无麦克风权限,请前往应用设置开启麦克风',
title: '暂无麦克风权限,请前往应用设置开启麦克风', icon: 'none'
icon: 'none' })
}) break;
break; case -1:
case -1: uni.showToast({
uni.showToast({ title: '应用权限错误',
title: '应用权限错误', icon: 'none'
icon: 'none' })
}) break;
break; }
} })
}) },
}, // 结束录音
// 结束录音 chendAudio(e) {
chendAudio(e) { if (!this.showAudioTranscribe) return
if (!this.showAudioTranscribe) return recorderManager.stop()
recorderManager.stop() clearInterval(transcribe)
clearInterval(transcribe) // 监听录音结束
// 监听录音结束 recorderManager.onStop(res => {
recorderManager.onStop(res => { im.sentVoice(this.conversationType, this.targetId, res.tempFilePath, (60 - this
if (res.tempFilePath) this.audioSrc = res.tempFilePath .transcribeTime), () => {
im.sendVoiceMsg(this.conversationType, this.targetId, res.tempFilePath, (60 - this this.getMessageList()
.transcribeTime), () => { })
this.getMessageList() this.transcribeTime = 60
}) this.showAudioTranscribe = false
this.transcribeTime = 60 })
this.showAudioTranscribe = false },
}) getMessageList() {
}, // 获取消息列表
getMessageList() { const objectNames = [
// 获取消息列表 'RC:TxtMsg',
const objectNames = [ 'RC:VcMsg',
'RC:TxtMsg', 'RC:HQVCMsg',
'RC:VcMsg', 'RC:ImgMsg',
'RC:HQVCMsg', 'RC:GIFMsg',
'RC:ImgMsg', 'RC:ImgTextMsg',
'RC:GIFMsg', 'RC:FileMsg',
'RC:ImgTextMsg', 'RC:LBSMsg',
'RC:FileMsg', 'RC:SightMsg',
'RC:LBSMsg', 'RC:ReferenceMsg',
'RC:SightMsg', 'RC:CombineMsg'
'RC:ReferenceMsg', ]
'RC:CombineMsg' const timeStamp = new Date().getTime()
] const count = 10 // 获取的消息数量
const timeStamp = new Date().getTime() const isForward = true // 是否向前获取
const count = 30 // 获取的消息数量 RongIMLib.getHistoryMessagesByTimestamp(this.conversationType, this.targetId, objectNames, timeStamp,
const isForward = true // 是否向前获取 count,
RongIMLib.getHistoryMessagesByTimestamp(this.conversationType, this.targetId, objectNames, timeStamp, isForward,
count, ({
isForward, code,
({ messages
code,
messages
}) => { }) => {
if (code === 0) { if (code === 0) {
this.messages = messages.reverse() this.messages = messages.reverse()
this.scrollBottom() this.scrollBottom()
} }
} }
) )
}, },
send() { send() {
if (this.inputTxt === '') return if (this.inputTxt === '') return
im.sendMsg(this.conversationType, this.targetId, this.inputTxt, () => { im.sentText(this.conversationType, this.targetId, this.inputTxt, () => {
this.getMessageList() setTimeout(() => {
this.inputTxt = '' this.getMessageList()
}) }, 500)
}, this.inputTxt = ''
showFriend(targetId, type) { })
uni.navigateTo({ },
url: type === 1 ? '/pages/im/friends/mine?targetId=' + targetId : showFriend(targetId, type) {
'/pages/im/friends/info?targetId=' + targetId uni.navigateTo({
}) url: type === 1 ? '/pages/im/friends/mine?targetId=' + targetId :
}, '/pages/im/friends/info?targetId=' + targetId
scrollBottom() { })
setTimeout(() => { },
let el = this.$refs.chatBottom scrollBottom() {
ChatList.scrollToElement(el, { setTimeout(() => {
animated: true let el = this.$refs.chatBottom
}) ChatList.scrollToElement(el, {
}, 100) animated: true
} })
} }, 100)
}
} }
</script> }
</script>
<style scoped>
.audio-transcribe { <style scoped>
background: rgba(0, 0, 0, .6); .audio-transcribe {
position: fixed; background: rgba(0, 0, 0, .6);
height: 200rpx; position: fixed;
width: 300rpx; height: 200rpx;
border-radius: 10rpx; width: 300rpx;
z-index: 99; border-radius: 10rpx;
top: 550rpx; z-index: 99;
left: 225rpx; top: 550rpx;
flex-direction: column; left: 225rpx;
align-items: center; flex-direction: column;
justify-content: center; align-items: center;
} justify-content: center;
}
.audio-transcribe-src {
width: 88rpx; .audio-transcribe-src {
height: 88rpx; width: 88rpx;
} height: 88rpx;
}
.audio-transcribe-text {
font-size: 28rpx; .audio-transcribe-text {
color: #FFFFFF; font-size: 28rpx;
} color: #FFFFFF;
}
/* 窗口 */
.chat { /* 窗口 */
background: #F3F6FB; .chat {
flex: 1; background: #F3F6FB;
} flex: 1;
}
.chat-scroll {
flex: 1; .chat-scroll {
} flex: 1;
}
.cell {
padding: 10rpx 30rpx; .cell {
} padding: 10rpx 30rpx;
}
.cell-time {
justify-content: center; .cell-time {
align-items: center; justify-content: center;
padding-bottom: 20rpx; align-items: center;
} padding-bottom: 20rpx;
}
.cell-time-text {
background: #fff; .cell-time-text {
font-size: 24rpx; background: #fff;
color: #666; font-size: 24rpx;
line-height: 40rpx; color: #666;
padding: 0 20rpx; line-height: 40rpx;
border-radius: 10rpx; padding: 0 20rpx;
} border-radius: 10rpx;
}
.cell-item {
width: 690rpx; .cell-item {
justify-content: flex-start; width: 690rpx;
} justify-content: flex-start;
}
.cell-footer {
height: 20rpx; .cell-footer {
} height: 20rpx;
}
.active {
width: 78rpx; .active {
height: 78rpx; width: 78rpx;
background-color: white; height: 78rpx;
border-radius: 10rpx; background-color: white;
} border-radius: 10rpx;
}
.msg {
margin: 0 20rpx; .msg {
} margin: 0 20rpx;
}
.state {
padding-top: 10rpx; .state {
} padding-top: 10rpx;
}
.state-text {
font-size: 24rpx; .state-text {
color: #666; font-size: 24rpx;
} color: #666;
}
.cell-item.left {
flex-direction: row; .cell-item.left {
} flex-direction: row;
}
.cell-item.right {
flex-direction: row-reverse; .cell-item.right {
} flex-direction: row-reverse;
}
.cell-item.right .state {
flex-direction: row; .cell-item.right .state {
justify-content: flex-end; flex-direction: row;
} justify-content: flex-end;
}
/* footer */
.chat-footer { /* footer */
background: white; .chat-footer {
padding: 20rpx 30rpx; background: white;
display: flex; padding: 20rpx 30rpx;
justify-content: space-between; display: flex;
flex-direction: row; justify-content: space-between;
} flex-direction: row;
}
.msg-type {
width: 70rpx; .msg-type {
height: 70rpx; width: 70rpx;
} height: 70rpx;
}
.msg-type>.msg-type-icon {
margin: 5rpx; .msg-type>.msg-type-icon {
width: 60rpx; margin: 5rpx;
height: 60rpx; width: 60rpx;
} height: 60rpx;
}
.chat-mp3 {
background: #F3F6FB; .chat-mp3 {
height: 70rpx; background: #F3F6FB;
line-height: 70rpx; height: 70rpx;
justify-content: center; line-height: 70rpx;
align-items: center; justify-content: center;
width: 460rpx; align-items: center;
border-radius: 10rpx; width: 460rpx;
margin-right: 15rpx; border-radius: 10rpx;
} margin-right: 15rpx;
}
.chat-mp3-text {
font-size: 30rpx; .chat-mp3-text {
color: #333; font-size: 30rpx;
} color: #333;
}
.chat-input {
background: #F3F6FB; .chat-input {
height: 70rpx; background: #F3F6FB;
width: 460rpx; height: 70rpx;
border-radius: 10rpx; width: 460rpx;
margin-right: 15rpx; border-radius: 10rpx;
padding: 0 20rpx; margin-right: 15rpx;
} padding: 0 20rpx;
}
.chat-push {
background: #34CE98; .chat-push {
color: white; background: #34CE98;
width: 120rpx; color: white;
line-height: 70rpx; width: 120rpx;
text-align: center; line-height: 70rpx;
border-radius: 10rpx; text-align: center;
font-size: 30rpx; border-radius: 10rpx;
font-weight: bold; font-size: 30rpx;
} font-weight: bold;
}
</style> </style>

View File

@@ -1,292 +1,228 @@
import * as RongIMLib from '@/uni_modules/RongCloud-IMWrapper/js_sdk/index'
import * as RongIMLib from '@/uni_modules/RongCloud-IMWrapper/js_sdk/index' import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index' import store from '@/store/index.js'
import store from '@/store/index.js' import message from './message.js'
import { import {
getFriends, getFriends,
getUserInfo, getUserInfo,
getImToken getImToken
} from '@/apis/interfaces/im.js' } from '@/apis/interfaces/im.js'
const initIm = (KEY) => { const initIm = (KEY) => {
RongIMLib.init(KEY) RongIMLib.init(KEY)
CallLib.init() CallLib.init()
addListeners() addListeners()
// 初始化的时候 自动链接 // 初始化的时候 自动链接
if (store.getters.getToken !== '') { if (store.getters.getToken !== '') {
getImToken().then(res => { getImToken().then(res => {
connect(res.token, res.userInfo, () => {}) connect(res.token, res.userInfo, () => {})
}) })
} }
} }
const setNotifyBadge = () => { const setNotifyBadge = () => {
// 获取未读消息数量 // 获取未读消息数量
RongIMLib.getTotalUnreadCount(({ RongIMLib.getTotalUnreadCount(({
code, code,
count count
}) => { }) => {
if (code === 0) { if (code === 0) {
// #ifdef APP-PLUS // #ifdef APP-PLUS
plus.runtime.setBadgeNumber(count) plus.runtime.setBadgeNumber(count)
// #endif // #endif
if (count > 0) { if (count > 0) {
uni.setTabBarBadge({ uni.setTabBarBadge({
index: 3, index: 3,
text: String(count > 99 ? '99+' : count) text: String(count > 99 ? '99+' : count)
}) })
} else { } else {
uni.removeTabBarBadge({ uni.removeTabBarBadge({
index: 3 index: 3
}) })
} }
} }
}) })
} }
/** /**
* 连接IM服务 * 连接IM服务
* @param {string} token token * @param {string} token token
* @param {object} userInfo {userId: string, name: string, portraitUrl: string} * @param {object} userInfo {userId: string, name: string, portraitUrl: string}
*/ */
const connect = (token, userInfo, callback) => { const connect = (token, userInfo, callback) => {
RongIMLib.connect(token, res => { RongIMLib.connect(token, res => {
console.log('连接结果', res); console.log('连接结果', res);
callback(res) callback(res)
}) })
store.dispatch('setSenderInfo', userInfo) store.dispatch('setSenderInfo', userInfo)
setNotifyBadge() setNotifyBadge()
const model = uni.model.friendModel const model = uni.model.friendModel
model.find((err, results) => { model.find((err, results) => {
console.log('好友列表', results); console.log('好友列表', results);
results.map(item => { results.map(item => {
store.dispatch('updateFriends', item) store.dispatch('updateFriends', item)
}) })
}) })
} }
/** /**
* 断开链接 * 断开链接
*/ */
const disconnect = () => { const disconnect = () => {
RongIMLib.disconnect() RongIMLib.disconnect()
// 移除提醒数量 // 移除提醒数量
// #ifdef APP-PLUS // #ifdef APP-PLUS
plus.runtime.setBadgeNumber(0) plus.runtime.setBadgeNumber(0)
// #endif // #endif
uni.removeTabBarBadge({ uni.removeTabBarBadge({
index: 3 index: 3
}) })
} }
// 允许通知的消息类型,触发更新消息列表操作 // 允许通知的消息类型,触发更新消息列表操作
const notifyMsgTypes = [ const notifyMsgTypes = [
'RC:TxtMsg', 'RC:TxtMsg',
'RC:VcMsg', 'RC:VcMsg',
'RC:HQVCMsg', 'RC:HQVCMsg',
'RC:ImgMsg', 'RC:ImgMsg',
'RC:GIFMsg', 'RC:GIFMsg',
'RC:ImgTextMsg', 'RC:ImgTextMsg',
'RC:FileMsg', 'RC:FileMsg',
'RC:LBSMsg', 'RC:LBSMsg',
'RC:SightMsg', 'RC:SightMsg',
'RC:ReferenceMsg', 'RC:ReferenceMsg',
'RC:CombineMsg', 'RC:CombineMsg',
] ]
function inArray(search, array) { function inArray(search, array) {
for (var i in array) { for (var i in array) {
if (array[i] == search) { if (array[i] == search) {
return true; return true;
} }
} }
return false; return false;
} }
const addListeners = () => { const addListeners = () => {
// 添加连接状态监听函数 // 添加连接状态监听函数
RongIMLib.addConnectionStatusListener((res) => { RongIMLib.addConnectionStatusListener((res) => {
console.log('连接状态监听', res.data.status); console.log('连接状态监听', res.data.status);
uni.$emit('onConnectionStatusChange', res.data.status) uni.$emit('onConnectionStatusChange', res.data.status)
}) })
// 添加消息监听函数 // 添加消息监听函数
RongIMLib.addReceiveMessageListener((res) => { RongIMLib.addReceiveMessageListener((res) => {
console.log('收到消息', res.data.message); console.log('收到消息', res.data.message);
const message = res.data.message const message = res.data.message
if (inArray(message.objectName, notifyMsgTypes)) { if (inArray(message.objectName, notifyMsgTypes)) {
console.log('new Message'); console.log('new Message');
newMessage(message) newMessage(message)
} }
}) })
// 监听通话呼入 // 音视频通话相关的
CallLib.onCallReceived(({ // 监听通话呼入
data CallLib.onCallReceived(({
}) => { data
console.log('onCallReceived', data) }) => {
uni.navigateTo({
uni.navigateTo({ url: '/pages/im/private/call?targetId=' + data.targetId + '&mediaType=' +
url: '/pages/im/private/call?targetId=' + data.targetId + '&mediaType=' + data.mediaType
data.mediaType })
}) })
}) // 通话建立成功
CallLib.onCallConnected(() => {
// 通话建立成功 uni.$emit('onCallConnected');
CallLib.onCallConnected(() => { })
uni.$emit('onCallConnected'); // 外呼
}) CallLib.onCallOutgoing((res) => {
uni.$emit('onCallOutgoing');
CallLib.onCallOutgoing((res) => { })
uni.$emit('onCallOutgoing'); // 远端响铃
}) CallLib.onRemoteUserRinging((res) => {
CallLib.onRemoteUserRinging((res) => { uni.$emit('onRemoteUserRinging');
uni.$emit('onRemoteUserRinging'); })
}) // 远端加入
CallLib.onRemoteUserJoined((res) => { CallLib.onRemoteUserJoined((res) => {
uni.$emit('onRemoteUserJoined'); uni.$emit('onRemoteUserJoined');
}) })
CallLib.onCallDisconnected((res) => { // 断开链接
console.log('断开链接', res); CallLib.onCallDisconnected((res) => {
uni.$emit('onCallDisconnected'); console.log('断开链接', res);
}) uni.$emit('onCallDisconnected');
CallLib.onRemoteUserLeft((res) => { })
console.log('远端离开', res); // 远端挂断
uni.$emit('onRemoteUserLeft'); CallLib.onRemoteUserLeft((res) => {
}) console.log('远端离开', res);
} uni.$emit('onRemoteUserLeft');
})
// 维护消息列表 }
const newMessage = (msg) => {
RongIMLib.getConversationNotificationStatus(msg.conversationType, msg.targetId, ({ // 维护消息列表,检查是否需要通知声音,设置新消息提醒的数量
code, const newMessage = (msg) => {
status RongIMLib.getConversationNotificationStatus(msg.conversationType, msg.targetId, ({
}) => { code,
if (code === 0) { status
if (status) { }) => {
triTone() if (code === 0) {
} if (status) {
} triTone()
}); }
}
setNotifyBadge() });
if (!store.getters.hasUser(msg.targetId)) { setNotifyBadge()
syncUserInfo(msg.targetId)
} if (!store.getters.hasUser(msg.targetId)) {
syncUserInfo(msg.targetId)
uni.$emit('onReceiveMessage', msg); }
// store.dispatch('newMessage', msg)
} uni.$emit('onReceiveMessage', msg);
}
function syncUserInfo(targetId) {
getUserInfo(targetId).then(res => { function syncUserInfo(targetId) {
store.dispatch('updateFriends', res) getUserInfo(targetId).then(res => {
}) store.dispatch('updateFriends', res)
} })
}
// 播放状态
let tipState = false // 播放状态
let tipState = false
const triTone = () => {
if (tipState == false) { const triTone = () => {
const innerAudioContext = uni.createInnerAudioContext() if (tipState == false) {
innerAudioContext.autoplay = true const innerAudioContext = uni.createInnerAudioContext()
innerAudioContext.src = '/utils/im/sounds/new-msg.mp3' innerAudioContext.autoplay = true
innerAudioContext.onPlay(() => { innerAudioContext.src = '/utils/im/sounds/new-msg.mp3'
tipState = true innerAudioContext.onPlay(() => {
}) tipState = true
innerAudioContext.onEnded(() => { })
tipState = false innerAudioContext.onEnded(() => {
}) tipState = false
} })
} }
}
/**
* 发送消息 /**
* @param {number} conversationType 消息类型 * 同步好友信息,保存头像地址等
* @param {string} targetId 会话id */
* @param {string} content 消息内容 const syncFriends = () => {
* @param {function} callback 回调函数 getFriends().then(res => {
*/ res.map(item => {
const sendMsg = (conversationType, targetId, content, callback) => { console.log('item', item);
const msg = { store.dispatch('updateFriends', item)
conversationType: conversationType, })
targetId: String(targetId), })
content: { }
objectName: 'RC:TxtMsg',
content: content, export default {
user: store.getters.sender initIm,
} connect,
} setNotifyBadge,
RongIMLib.sendMessage(msg, ({ syncFriends,
code, syncUserInfo,
messageId ...message
}) => {
if (code === 0) {
callback(messageId)
} else {
uni.showToast({
icon: 'none',
title: '发送失败'
})
}
})
}
/**
* conversationType 会话类型
* voiceUrl 本地的录音路径
* time 录音时长
*/
const sendVoiceMsg = (conversationType, targetId, voiceUrl, time, callback) => {
console.log('sendVoiceMsg', plus.io.convertLocalFileSystemURL(voiceUrl));
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:HQVCMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(voiceUrl),
duration: time
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
/**
* 同步好友信息,保存头像地址等
*/
const syncFriends = () => {
getFriends().then(res => {
res.map(item => {
console.log('item', item);
store.dispatch('updateFriends', item)
})
})
}
export default {
initIm,
connect,
sendMsg,
sendVoiceMsg,
setNotifyBadge,
syncFriends,
syncUserInfo
} }

154
utils/im/message.js Normal file
View File

@@ -0,0 +1,154 @@
import store from '@/store/index.js'
import * as RongIMLib from '@/uni_modules/RongCloud-IMWrapper/js_sdk/index'
/**
* 发送文本消息
* @param {number} conversationType 消息类型
* @param {string} targetId 会话id
* @param {string} content 消息内容
* @param {function} callback 回调函数
*/
const sentText = (conversationType, targetId, content, callback) => {
console.log('发送');
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: '发送失败'
})
}
})
}
/**
* 发送消息
* @param {number} conversationType 消息类型
* @param {string} targetId 会话id
* @param {string} voiceUrl 录音的本地路径
* @param {integer} time 录音时长
* @param {function} callback 录音时长
*/
const sentVoice = (conversationType, targetId, voiceUrl, time, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:HQVCMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(voiceUrl),
duration: time
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
const sentImage = (conversationType, targetId, imageUrl, time, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:ImgMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(imageUrl),
duration: time
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
const sentGif = (conversationType, targetId, gifUrl, time, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:GIFMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(gifUrl),
duration: time
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
const sendFile = (conversationType, targetId, fileUrl, time, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:FileMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(fileUrl),
duration: time
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
export default {
sentText,
sentVoice,
sentImage,
sentGif,
sendFile
}