代码优化,变量名称调整

This commit is contained in:
2022-02-10 13:56:01 +08:00
parent e2243bcc99
commit 13aed4abf5
20 changed files with 258 additions and 452 deletions

View File

@@ -2,17 +2,7 @@
<view> <view>
<view v-for="(item, index) in conversations" :key="index" :class="['message', { 'is-top': item.isTop }]" <view v-for="(item, index) in conversations" :key="index" :class="['message', { 'is-top': item.isTop }]"
:data-item="item" @longpress="onLongPress" @click="toDetail(item)"> :data-item="item" @longpress="onLongPress" @click="toDetail(item)">
<view class="avatar"> <message-cell :item="item" />
<u-badge max="99" shape="horn" absolute :offset="[-5, -8]" :value="item.unreadMessageCount" />
<u-avatar text="群" shape="square" size="44" />
</view>
<view class="content u-border-bottom">
<view class="header">
<view class="name">群组名称</view>
<view class="time">{{ item.sentTime|timeCustomCN }}</view>
</view>
<message-preview class="preview" :msg="item.latestMessage" :user="item.latestMessage.userInfo" />
</view>
</view> </view>
<view class="shade" @click="hidePop" v-show="showPop"> <view class="shade" @click="hidePop" v-show="showPop">
@@ -26,9 +16,9 @@
</template> </template>
<script> <script>
import messagePreview from './messagePreview'
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 messageCell from './messageCell'
export default { export default {
props: { props: {
@@ -40,7 +30,7 @@
} }
}, },
components: { components: {
messagePreview messageCell
}, },
data() { data() {
return { return {
@@ -55,13 +45,7 @@
pickedItem: {}, pickedItem: {},
} }
}, },
computed: {
friend() {
return function(targetId) {
return this.$store.getters.userInfo(targetId)
}
}
},
methods: { methods: {
// 隐藏功能菜单 // 隐藏功能菜单
hidePop() { hidePop() {
@@ -114,6 +98,7 @@
uni.navigateTo({ uni.navigateTo({
url: '/pages/im/group/chat?targetId=' + item.targetId url: '/pages/im/group/chat?targetId=' + item.targetId
}) })
this.hidePop()
} }
} }
} }
@@ -122,46 +107,9 @@
<style lang="scss" scoped> <style lang="scss" scoped>
.message { .message {
background: white; background: white;
padding: 20rpx 0 0 20rpx;
position: relative;
display: flex;
&.is-top { &.is-top {
background: $window-color; background: $window-color;
border-bottom: #e8e8e8;
}
.avatar {
position: relative;
.u-badge {
z-index: 998;
}
}
.content {
margin-left: 30rpx;
width: calc(100% - 46px);
box-sizing: border-box;
position: relative;
.header {
display: flex;
justify-content: space-between;
.name {
font-size: $title-size + 2;
color: #454545;
color: #454545;
}
.time {
font-size: $title-size-sm;
color: $text-gray-m;
position: absolute;
right: 30rpx;
}
}
} }
} }

View File

@@ -2,18 +2,7 @@
<view> <view>
<view v-for="(item, index) in conversations" :key="index" :class="['message', { 'is-top': item.isTop }]" <view v-for="(item, index) in conversations" :key="index" :class="['message', { 'is-top': item.isTop }]"
:data-item="item" @longpress="onLongPress" @click="toDetail(item)"> :data-item="item" @longpress="onLongPress" @click="toDetail(item)">
<view class="avatar" @click="toFriend(item.targetId)"> <message-cell :item="item" />
<u-badge max="99" shape="horn" absolute :offset="[-5, -8]"
:value="item.unreadMessageCount" />
<u-avatar :src="friend(item.targetId).portraitUrl" shape="square" size="44" />
</view>
<view class="content u-border-bottom">
<view class="header">
<view class="name">{{ friend(item.targetId).name }}</view>
<view class="time">{{ item.sentTime|timeCustomCN }}</view>
</view>
<message-preview class="preview" :msg="item.latestMessage" />
</view>
</view> </view>
<view class="shade" @click="hidePop" v-show="showPop"> <view class="shade" @click="hidePop" v-show="showPop">
@@ -27,9 +16,9 @@
</template> </template>
<script> <script>
import messagePreview from './messagePreview'
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 messageCell from './messageCell'
export default { export default {
props: { props: {
@@ -54,12 +43,12 @@
} }
}, },
components: { components: {
messagePreview messageCell
}, },
computed: { computed: {
friend() { contact() {
return function(targetId) { return function(targetId) {
return this.$store.getters.userInfo(targetId) return this.$store.getters.contactInfo(targetId)
} }
} }
}, },
@@ -117,11 +106,6 @@
uni.navigateTo({ uni.navigateTo({
url: '/pages/im/private/chat?targetId=' + item.targetId url: '/pages/im/private/chat?targetId=' + item.targetId
}) })
},
toFriend(targetId) {
uni.navigateTo({
url: '/pages/im/friends/info?targetId=' + targetId
})
} }
} }
} }
@@ -130,46 +114,9 @@
<style lang="scss" scoped> <style lang="scss" scoped>
.message { .message {
background: white; background: white;
padding: 20rpx 0 0 20rpx;
position: relative;
display: flex;
&.is-top { &.is-top {
background: $window-color; background: $window-color;
border-bottom: #e8e8e8;
}
.avatar {
position: relative;
.u-badge {
z-index: 998;
}
}
.content {
margin-left: 30rpx;
width: calc(100% - 46px);
box-sizing: border-box;
position: relative;
.header {
display: flex;
justify-content: space-between;
.name {
font-size: $title-size + 2;
color: #454545;
color: #454545;
}
.time {
font-size: $title-size-sm;
color: $text-gray-m;
position: absolute;
right: 30rpx;
}
}
} }
} }

View File

@@ -0,0 +1,85 @@
<template>
<view class="message--cell">
<view class="avatar">
<u-badge max="99" shape="horn" absolute :offset="[-5, -8]" :value="item.unreadMessageCount" />
<u-avatar :src="contact(item.targetId).portraitUrl" shape="square" size="44" />
</view>
<view class="content">
<view class="header">
<view class="name">{{ contact(item.targetId).name }}</view>
<view class="time">{{ item.sentTime|timeCustomCN }}</view>
</view>
<message-preview class="preview" :msg="item.latestMessage" :conversationType="item.conversationType"
:user="item.latestMessage.userInfo" />
</view>
</view>
</template>
<script>
import messagePreview from './messagePreview'
export default {
props: {
item: {
type: Object,
default: function() {
return {}
}
}
},
computed: {
contact() {
return function(targetId) {
return this.$store.getters.contactInfo(targetId)
}
}
},
components: {
messagePreview
}
}
</script>
<style lang="scss" scoped>
.message--cell {
display: flex;
padding: 20rpx 0 0 20rpx;
.avatar {
position: relative;
.u-badge {
z-index: 998;
}
}
.content {
margin-left: 30rpx;
box-sizing: border-box;
position: relative;
flex: 1;
border-bottom-width: 0.5px !important;
border-color: $u-border-color !important;
border-bottom-style: solid;
.header {
display: flex;
justify-content: space-between;
.name {
font-size: $title-size + 2;
color: #454545;
color: #454545;
}
.time {
font-size: $title-size-sm;
color: $text-gray-m;
position: absolute;
right: 30rpx;
}
}
}
}
</style>

View File

@@ -1,28 +1,28 @@
<template> <template>
<view> <view>
<view class="preview" v-if="msg.objectName=='RC:TxtMsg'"> <view class="preview" v-if="msg.objectName=='RC:TxtMsg'">
<text v-if="user.name">{{ user.name }}:</text>{{ msg.content || '' }} <text v-if="conversationType == 3">{{ user.name }}: </text>{{ msg.content || '' }}
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:HQVCMsg'"> <view class="preview" v-if="msg.objectName=='RC:HQVCMsg'">
<text v-if="user.name">{{ user.name }}:</text>[语音] <text v-if="conversationType == 3">{{ user.name }}: </text>[语音]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:ImgMsg'"> <view class="preview" v-if="msg.objectName=='RC:ImgMsg'">
<text v-if="user.name">{{ user.name }}:</text>[图片] <text v-if="conversationType == 3">{{ user.name }}: </text>[图片]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:GIFMsg'"> <view class="preview" v-if="msg.objectName=='RC:GIFMsg'">
<text v-if="user.name">{{ user.name }}:</text>[表情] <text v-if="conversationType == 3">{{ user.name }}: </text>[表情]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:FileMsg'"> <view class="preview" v-if="msg.objectName=='RC:FileMsg'">
<text v-if="user.name">{{ user.name }}:</text>[文件] <text v-if="conversationType == 3">{{ user.name }}: </text>[文件]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:LBSMsg'"> <view class="preview" v-if="msg.objectName=='RC:LBSMsg'">
<text v-if="user.name">{{ user.name }}:</text>[位置] <text v-if="conversationType == 3">{{ user.name }}: </text>[位置]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:AudioMsg'"> <view class="preview" v-if="msg.objectName=='RC:AudioMsg'">
<text v-if="user.name">{{ user.name }}:</text>[语音通话] <text v-if="conversationType == 3">{{ user.name }}: </text>[语音通话]
</view> </view>
<view class="preview" v-if="msg.objectName=='RC:VideoMsg'"> <view class="preview" v-if="msg.objectName=='RC:VideoMsg'">
<text v-if="user.name">{{ user.name }}:</text>[视频通话] <text v-if="conversationType == 3">{{ user.name }}: </text>[视频通话]
</view> </view>
</view> </view>
</template> </template>
@@ -34,6 +34,10 @@
type: Object, type: Object,
default: {} default: {}
}, },
conversationType: {
type: Number,
default: 0
},
user: { user: {
type: Object, type: Object,
default: function() { default: function() {

View File

@@ -12,7 +12,7 @@
@success="onSuccess" /> @success="onSuccess" />
<sent-text v-if="chatType === 1" :conversationType="conversationType" :targetId="targetId" <sent-text v-if="chatType === 1" :conversationType="conversationType" :targetId="targetId"
@success="onSuccess" /> @success="onSuccess" />
<view class="msg-type msg-popups" @click="scrollBottom('msgPopups')"> <view class="msg-type msg-popups" @click="showPopups = !showPopups">
<image class="icon" src="@/static/icon/popups-icon.png"></image> <image class="icon" src="@/static/icon/popups-icon.png"></image>
</view> </view>
</view> </view>
@@ -27,7 +27,6 @@
import sentVoice from '../components/sentVoice' import sentVoice from '../components/sentVoice'
import sentPopups from '../components/sentPopups' import sentPopups from '../components/sentPopups'
export default { export default {
props: { props: {
conversationType: { conversationType: {

View File

@@ -17,9 +17,9 @@
<view v-for="(friendItem, index) in item" :key="index" class="friend-flex u-border-bottom" <view v-for="(friendItem, index) in item" :key="index" class="friend-flex u-border-bottom"
@click="toFriend(friendItem.userId)"> @click="toFriend(friendItem.userId)">
<u-avatar size="40" shape="square" :src="friend(friendItem.userId).portraitUrl" /> <u-avatar size="40" shape="square" :src="contact(friendItem.userId).portraitUrl" />
<view class="info"> <view class="info">
<view class="name">{{ friend(friendItem.userId).name }}</view> <view class="name">{{ contact(friendItem.userId).name }}</view>
<view class="address">{{ friendItem.address }}</view> <view class="address">{{ friendItem.address }}</view>
</view> </view>
</view> </view>
@@ -48,9 +48,9 @@
}; };
}, },
computed: { computed: {
friend() { contact() {
return function(targetId) { return function(targetId) {
return this.$store.getters.userInfo(targetId) return this.$store.getters.contactInfo(targetId)
} }
} }
}, },

View File

@@ -5,8 +5,8 @@
<u-avatar :src="userInfo.portraitUrl || require('@/static/user/cover.png')" shape="square" size="50" <u-avatar :src="userInfo.portraitUrl || require('@/static/user/cover.png')" shape="square" size="50"
bg-color="#fff"></u-avatar> bg-color="#fff"></u-avatar>
<view class="info-text"> <view class="info-text">
<view class="nickname">{{userInfo.name}}</view> <view class="nickname">{{ userInfo.name }}</view>
<view class="address" @longpress="copyAddress">地址{{userInfo.address}}</view> <view class="address" @longpress="copyAddress">地址{{ userInfo.address }}</view>
</view> </view>
</view> </view>
<!-- 用户资料 --> <!-- 用户资料 -->

View File

@@ -49,23 +49,17 @@
}, },
onLoad(e) { onLoad(e) {
this.targetId = e.targetId this.targetId = e.targetId
this.initMessageList() this.getMessageList()
uni.$on('onReceiveGroupMessage', (msg) => { uni.$on('onReceiveGroupMessage', (msg) => {
if (msg.targetId == this.targetId) { if (msg.targetId == this.targetId) {
this.initMessageList() this.getMessageList()
} }
}) })
}, },
onBackPress() {
uni.$off('onReceiveGroupMessage')
},
methods: { methods: {
initMessageList() {
this.getMessageList()
// 清理当前会话,未读消息数量
RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime())
// 发送消息已读状态给对方
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
// 更新badge提醒数量
im.setNotifyBadge()
},
// 获取消息列表 // 获取消息列表
getMessageList() { getMessageList() {
im.getMessageList( im.getMessageList(
@@ -75,16 +69,19 @@
20, 20,
true, true,
(messages) => { (messages) => {
console.log('获取到的消息', messages);
this.messages = messages.reverse() this.messages = messages.reverse()
this.scrollBottom() this.scrollBottom()
}) })
}, },
// 滚动到底部 // 滚动到底部
scrollBottom(type) { scrollBottom(type) {
if (type === 'msgPopups') { // 清理当前会话,未读消息数量
this.showPopups = !this.showPopups RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime() + 1100)
} // 发送消息已读状态给对方
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
// 更新badge提醒数量
im.setNotifyBadge()
setTimeout(() => { setTimeout(() => {
let el = this.$refs.chatBottom let el = this.$refs.chatBottom
ChatList.scrollToElement(el, { ChatList.scrollToElement(el, {

View File

@@ -54,7 +54,6 @@
export default { export default {
data() { data() {
return { return {
isShown: true, // 当前页面显示状态
showType: 1, // 0 单聊1 群聊 showType: 1, // 0 单聊1 群聊
conversations: [], // 会话列表 conversations: [], // 会话列表
groupConversations: [], groupConversations: [],
@@ -81,6 +80,8 @@
this.getPrivateConversationList() this.getPrivateConversationList()
this.getGroupConversationList() this.getGroupConversationList()
} }
console.log('开始监听');
// 监听新消息 // 监听新消息
uni.$on('onReceivePrivateMessage', (msg) => { uni.$on('onReceivePrivateMessage', (msg) => {
this.getPrivateConversationList() this.getPrivateConversationList()
@@ -88,13 +89,11 @@
uni.$on('onReceiveGroupMessage', (msg) => { uni.$on('onReceiveGroupMessage', (msg) => {
this.getGroupConversationList() this.getGroupConversationList()
}) })
this.isShown = true
}, },
onHide() { onHide() {
uni.$off('onReceivePrivateMessage') uni.$off('onReceivePrivateMessage')
uni.$off('onReceiveGroupMessage') uni.$off('onReceiveGroupMessage')
this.isShown = false console.log('index 隐藏');
}, },
onNavigationBarButtonTap(e) { onNavigationBarButtonTap(e) {
if (e.index == 0) { if (e.index == 0) {

View File

@@ -62,12 +62,12 @@
}, },
onLoad(e) { onLoad(e) {
this.targetId = e.targetId this.targetId = e.targetId
this.userInfo = this.$store.getters.userInfo(this.targetId) this.userInfo = this.$store.getters.contactInfo(this.targetId)
uni.setNavigationBarTitle({ uni.setNavigationBarTitle({
title: this.userInfo.name title: this.userInfo.name
}) })
// 获取消息列表 // 获取消息列表
this.initMessageList() this.getMessageList()
// 监听消息已读状态 // 监听消息已读状态
uni.$on('onReadReceiptReceived', (data) => { uni.$on('onReadReceiptReceived', (data) => {
if (data.targetId == this.targetId) { if (data.targetId == this.targetId) {
@@ -77,20 +77,11 @@
// 监听收到新消息,判断是否是当前会话,更新会话内容 // 监听收到新消息,判断是否是当前会话,更新会话内容
uni.$on('onReceivePrivateMessage', (msg) => { uni.$on('onReceivePrivateMessage', (msg) => {
if (msg.targetId == this.targetId) { if (msg.targetId == this.targetId) {
this.initMessageList() this.getMessageList()
} }
}) })
}, },
methods: { methods: {
initMessageList() {
this.getMessageList()
// 清理当前会话,未读消息数量
RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime())
// 发送消息已读状态给对方
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
// 更新badge提醒数量
im.setNotifyBadge()
},
customCN(val) { customCN(val) {
return timeCustomCN(val) return timeCustomCN(val)
}, },
@@ -103,7 +94,6 @@
10, 10,
true, true,
(messages) => { (messages) => {
console.log('获取到的消息', messages);
this.messages = messages.reverse() this.messages = messages.reverse()
this.scrollBottom() this.scrollBottom()
}) })
@@ -117,9 +107,12 @@
}, },
// 滚动到底部 // 滚动到底部
scrollBottom(type) { scrollBottom(type) {
if (type === 'msgPopups') { // 清理当前会话,未读消息数量
this.showPopups = !this.showPopups RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime() + 1100)
} // 发送消息已读状态给对方
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
// 更新badge提醒数量
im.setNotifyBadge()
setTimeout(() => { setTimeout(() => {
let el = this.$refs.chatBottom let el = this.$refs.chatBottom
ChatList.scrollToElement(el, { ChatList.scrollToElement(el, {

View File

@@ -2,135 +2,134 @@ import im from "@/utils/im/index.js"
export default { export default {
state: { state: {
friends: {}, contacts: {},
myInfo: {} myInfo: {}
}, },
getters: { getters: {
friends(state) { contacts(state) {
return state.friends return state.contacts
}, },
userInfo: (state) => (targetId) => { contactInfo: (state) => (targetId) => {
if (state.friends[targetId]) { if (state.contacts[targetId]) {
const info = state.friends[targetId] const info = state.contacts[targetId]
return { return {
userId: info.userId,
name: info.name, name: info.name,
hash: info.hash,
portraitUrl: info.localAvatar ? info.localAvatar : require('@/static/user/cover.png') portraitUrl: info.localAvatar ? info.localAvatar : require('@/static/user/cover.png')
} }
} else { } else {
return { return {
userId: '',
name: '', name: '',
hash: '',
portraitUrl: '' portraitUrl: ''
} }
} }
}, },
// 联系人是否存在
contactIsExist: (state) => (targetId) => {
return Boolean(state.contacts[targetId])
},
sender(state) { sender(state) {
return state.myInfo return state.myInfo
} }
}, },
mutations: { mutations: {
updateFriendInfo(state, userInfo) { updateContactInfo(state, contactInfo) {
Vue.set(state.friends, userInfo.userId, userInfo) Vue.set(state.contacts, contactInfo.targetId, contactInfo)
}, },
SET_state_sender(state, userInfo) { setSenderInfo(state, contactInfo) {
state.myInfo = { state.myInfo = {
userId: userInfo.userId, userId: contactInfo.targetId,
name: userInfo.name, name: contactInfo.name,
portraitUrl: userInfo.portraitUrl portraitUrl: contactInfo.portraitUrl
} }
} }
}, },
actions: { actions: {
setSenderInfo({ setSenderInfo({
commit commit
}, userInfo) { }, contactInfo) {
commit('SET_state_sender', userInfo) commit('setSenderInfo', contactInfo)
}, },
// 载入好友信息 // 载入好友信息
launchFriend({ launchContact({
commit commit
}, data) { }, data) {
commit('updateFriendInfo', data) commit('updateContactInfo', data)
}, },
// 更新好友信息这个时候要校验hash值了 // 更新好友信息这个时候要校验hash值了
updateFriend({ updateContact({
commit commit
}, userInfo) { }, contactInfo) {
const model = uni.model.friendModel const model = uni.model.contactModel
model.find('userId=' + userInfo.userId, (err, result) => { model.find('targetId=' + contactInfo.targetId, (err, result) => {
if (userInfo.hash != result[0].hash) { if (contactInfo.hash != result[0].hash) {
commit('updateFriendInfo', userInfo) commit('updateContactInfo', contactInfo)
if (userInfo.portraitUrl && userInfo.portraitUrl != result[0].portraitUrl) { if (contactInfo.portraitUrl && contactInfo.portraitUrl != result[0].portraitUrl) {
saveAvatar(userInfo, (savedFilePath) => { saveAvatar(contactInfo, (savedFilePath) => {
const info = { const info = {
userId: userInfo.userId, targetId: contactInfo.targetId,
name: userInfo.name, name: contactInfo.name,
hash: userInfo.hash, hash: contactInfo.hash,
portraitUrl: userInfo.portraitUrl, portraitUrl: contactInfo.portraitUrl,
localAvatar: savedFilePath localAvatar: savedFilePath
} }
model.update('userId=' + userInfo.userId, info, (err, res) => { model.update('targetId=' + contactInfo.targetId, info, (err, res) => {})
}) commit('updateContactInfo', info)
commit('updateFriendInfo', info)
}) })
} else { } else {
const info = { const info = {
userId: userInfo.userId, targetId: contactInfo.targetId,
name: userInfo.name, name: contactInfo.name,
hash: userInfo.hash, hash: contactInfo.hash,
portraitUrl: userInfo.portraitUrl, portraitUrl: contactInfo.portraitUrl,
localAvatar: result[0].localAvatar localAvatar: result[0].localAvatar
} }
model.update('userId=' + userInfo.userId, info, (err, res) => { model.update('targetId=' + contactInfo.targetId, info, (err, res) => {})
})
} }
} else { } else {}
}
}) })
}, },
// 初始化好友信息 // 初始化好友信息
initFriend({ initContact({
commit commit
}, userInfo) { }, contactInfo) {
// 将好友信息保存到vuex的内存中方便立即使用 // 将好友信息保存到vuex的内存中方便立即使用
commit('updateFriendInfo', userInfo) commit('updateContactInfo', contactInfo)
const model = uni.model.friendModel const model = uni.model.contactModel
// 用户头像,是否需要下载到本地 // 用户头像,是否需要下载到本地
if (userInfo.portraitUrl) { if (contactInfo.portraitUrl) {
saveAvatar(userInfo, (savedFilePath) => { saveAvatar(contactInfo, (savedFilePath) => {
const info = { const info = {
userId: userInfo.userId, targetId: contactInfo.targetId,
name: userInfo.name, name: contactInfo.name,
hash: userInfo.hash, hash: contactInfo.hash,
portraitUrl: userInfo.portraitUrl, portraitUrl: contactInfo.portraitUrl,
localAvatar: savedFilePath localAvatar: savedFilePath
} }
model.insert(info, (err, res) => { model.insert(info, (err, res) => {})
})
// 保存头像后,更新信息 // 保存头像后,更新信息
commit('updateFriendInfo', info) commit('updateContactInfo', info)
}) })
} else { } else {
// 直接将信息,写入数据库 // 直接将信息,写入数据库
const info = { const info = {
userId: userInfo.userId, targetId: contactInfo.targetId,
name: userInfo.name, name: contactInfo.name,
hash: userInfo.hash, hash: contactInfo.hash,
portraitUrl: userInfo.portraitUrl, portraitUrl: contactInfo.portraitUrl,
localAvatar: '' localAvatar: ''
} }
model.insert(info, (err, res) => { model.insert(info, (err, res) => {})
})
} }
} }
} }
} }
const saveAvatar = (userInfo, callback) => { const saveAvatar = (contactInfo, callback) => {
uni.downloadFile({ uni.downloadFile({
url: userInfo.portraitUrl, url: contactInfo.portraitUrl,
success: ({ success: ({
tempFilePath tempFilePath
}) => { }) => {
@@ -143,7 +142,6 @@ const saveAvatar = (userInfo, callback) => {
} }
}) })
}, },
fail: (err) => { fail: (err) => {}
}
}) })
} }

View File

@@ -1,23 +0,0 @@
[{
"objectName": "RC:TxtMsg",
"receivedTime": 1643080237399,
"extra": "",
"messageUId": "BUFC-3FSU-OLE4-I31K",
"conversationType": 1,
"messageDirection": 2,
"senderUserId": "10041",
"content": {
"content": "你好,这是 1710 条消息条消息条消息条消息条消息条消息条消息条消息条消息0.97796900 1642741562",
"objectName": "RC:TxtMsg",
"userInfo": {
"userId": "10041",
"name": "我是eth",
"portraitUrl": "http://storage.zh.shangkelian.cn/images/2022/01/12/3d2a103386df6822db7e5290272e8bc2.png"
}
},
"targetId": "10041",
"sentTime": 1642741563003,
"messageId": 2,
"receivedStatus": 1,
"sentStatus": 30
}]

View File

@@ -2,6 +2,7 @@ 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 message from './message.js'
import listeners from './listeners.js'
import { import {
getFriends, getFriends,
getUserInfo, getUserInfo,
@@ -47,7 +48,7 @@ const setNotifyBadge = () => {
/** /**
* 连接IM服务 * 连接IM服务
* @param {string} token token * @param {string} token token
* @param {object} userInfo {userId: string, name: string, portraitUrl: string} * @param {object} userInfo {targetId: string, name: string, portraitUrl: string}
*/ */
const connect = (token, userInfo, callback) => { const connect = (token, userInfo, callback) => {
RongIMLib.connect(token, res => { RongIMLib.connect(token, res => {
@@ -57,15 +58,15 @@ const connect = (token, userInfo, callback) => {
// 设置未读消息数量 // 设置未读消息数量
setNotifyBadge() setNotifyBadge()
// 首次运行获取好友列表 // 首次运行获取好友列表
const FK = 'IFT_' + userInfo.userId const FK = 'IFTJ_' + userInfo.targetId
uni.getStorage({ uni.getStorage({
key: FK, key: FK,
success: () => { success: () => {
const model = uni.model.friendModel const model = uni.model.contactModel
model.find((err, results) => { model.find((err, results) => {
results.map(item => { results.map(item => {
store.dispatch('launchFriend', item) store.dispatch('launchContact', item)
}) })
}) })
}, },
@@ -73,9 +74,9 @@ const connect = (token, userInfo, callback) => {
// 程序是首次运行,初始化加载好友信息 // 程序是首次运行,初始化加载好友信息
getFriends().then(res => { getFriends().then(res => {
res.map(item => { res.map(item => {
store.dispatch('initFriend', item) store.dispatch('initContact', item)
}) })
uni.setStorageSync(FK, userInfo.userId) uni.setStorageSync(FK, userInfo.targetId)
}) })
} }
}) })
@@ -114,32 +115,38 @@ const notifyMsgTypes = [
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) => {
const message = res.data.message const message = res.data.message
console.log('收到消息', message); console.log('收到消息', message)
if (inArray(message.objectName, notifyMsgTypes)) { if (inArray(message.objectName, notifyMsgTypes)) {
console.log('通知并计数的消息'); if (!store.getters.contactIsExist(message.targetId)) {
getUserInfo(message.targetId).then(res => {
store.dispatch('initContact', res)
}).catch(err => {
console.log('ERR', err)
})
}
newMessage(message) newMessage(message)
} else if (message.objectName === RongIMLib.ObjectName.ProfileNotification) { } else if (message.objectName === RongIMLib.ObjectName.ProfileNotification) {
store.dispatch('updateFriend', JSON.parse(message.content.data)) store.dispatch('updateContact', JSON.parse(message.content.data))
// 调用完更新之后,删除这条消息 // 调用完更新之后,删除这条消息
RongIMLib.deleteMessagesByIds([message.messageId], ({ RongIMLib.deleteMessagesByIds([message.messageId], ({
code code
}) => { }) => {
console.log('消息删除结果', code); console.log('消息删除结果', code)
}) })
} else if (message.objectName === RongIMLib.ObjectName.ContactNotification) { } else if (message.objectName === RongIMLib.ObjectName.ContactNotification) {
// 触发一个新好友的通知事件 // 触发一个新好友的通知事件
@@ -166,29 +173,29 @@ const addListeners = () => {
}) })
// 通话建立成功 // 通话建立成功
CallLib.onCallConnected(() => { CallLib.onCallConnected(() => {
uni.$emit('onCallConnected'); uni.$emit('onCallConnected')
}) })
// 外呼 // 外呼
CallLib.onCallOutgoing((res) => { CallLib.onCallOutgoing((res) => {
uni.$emit('onCallOutgoing'); 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) => { CallLib.onCallDisconnected((res) => {
console.log('断开链接', res); console.log('断开链接', res)
uni.$emit('onCallDisconnected'); uni.$emit('onCallDisconnected')
}) })
// 远端挂断 // 远端挂断
CallLib.onRemoteUserLeft((res) => { CallLib.onRemoteUserLeft((res) => {
console.log('远端离开', res); console.log('远端离开', res)
uni.$emit('onRemoteUserLeft'); uni.$emit('onRemoteUserLeft')
}) })
} }
@@ -203,12 +210,12 @@ const newMessage = (msg) => {
triTone() triTone()
} }
} }
}); })
setNotifyBadge() setNotifyBadge()
if (msg.conversationType === RongIMLib.ConversationType.PRIVATE) { if (msg.conversationType === RongIMLib.ConversationType.PRIVATE) {
uni.$emit('onReceivePrivateMessage', msg); uni.$emit('onReceivePrivateMessage', msg)
} else { } else {
uni.$emit('onReceiveGroupMessage', msg); uni.$emit('onReceiveGroupMessage', msg)
} }
} }

0
utils/im/listeners.js Normal file
View File

View File

@@ -66,9 +66,10 @@ const sentText = (conversationType, targetId, content, user, callback) => {
if (code === 0) { if (code === 0) {
callback(messageId) callback(messageId)
} else { } else {
console.log('发送失败', msg);
uni.showToast({ uni.showToast({
icon: 'none', icon: 'none',
title: '发送失败' title: '发送失败' + code
}) })
} }
}) })

View File

@@ -2,8 +2,8 @@ import {
usqlite usqlite
} from '@/uni_modules/onemue-USQLite/js_sdk/usqlite.js' } from '@/uni_modules/onemue-USQLite/js_sdk/usqlite.js'
const friendModel = usqlite.model('friends', { const contactModel = usqlite.model('contacts', {
userId: { targetId: {
type: String, type: String,
primaryKey: true, primaryKey: true,
unique: true unique: true
@@ -18,5 +18,5 @@ const friendModel = usqlite.model('friends', {
}) })
export default { export default {
friendModel contactModel
} }

View File

@@ -1,20 +0,0 @@
{
"objectName": "RC:ProfileNtf",
"receivedTime": 1644312766084,
"extra": "",
"messageUId": "BUR2-MQHQ-SMIO-I32D",
"conversationType": 6,
"messageDirection": 2,
"senderUserId": "10047",
"content": {
"extra": "",
"operation": "Update",
"objectName": "RC:ProfileNtf",
"data": "{\"a\":2,\"m\":\"修改用户信息\"}"
},
"targetId": "10047",
"sentTime": 1644312766699,
"messageId": 26,
"receivedStatus": 0,
"sentStatus": 30
}

View File

@@ -1,27 +0,0 @@
[{
"latestMessage": {
"content": "你好,这是 725 条消息条消息条消息条消息条消息条消息条消息条消息条消息0.47447800 1644388415",
"objectName": "RC:TxtMsg",
"userInfo": {
"userId": "10051",
"name": "Jason.Chen",
"extra": "",
"portraitUrl": ""
}
},
"objectName": "RC:TxtMsg",
"receivedTime": 1644388414889,
"sentTime": 1644388415510,
"draft": "",
"conversationType": 3,
"receivedStatus": 0,
"conversationTitle": "",
"sentStatus": 30,
"mentionedCount": 0,
"latestMessageId": 98,
"isTop": false,
"senderUserId": "10005",
"unreadMessageCount": 3,
"hasUnreadMentioned": false,
"targetId": "TG001"
}]

View File

@@ -1,51 +0,0 @@
{
"type": "Engine:OnCallReceived",
"module": "RongCloud-Call-RCUniCall",
"data": {
"endTime": 0,
"users": [{
"userId": "10051",
"enableCamera": false,
"mediaId": "420111350",
"mediaType": 1,
"userType": 0,
"enableMicrophone": false
}, {
"userId": "10047",
"enableCamera": false,
"mediaType": 1,
"userType": 0,
"enableMicrophone": false
}],
"inviter": {
"userId": "10051",
"enableCamera": false,
"mediaId": "420111350",
"mediaType": 1,
"userType": 0,
"enableMicrophone": false
},
"caller": {
"userId": "10051",
"enableCamera": false,
"mediaId": "420111350",
"mediaType": 1,
"userType": 0,
"enableMicrophone": false
},
"connectedTime": 0,
"extra": "",
"startTime": 0,
"mediaType": 1,
"callId": "c28cb9d8-6581-474c-bfa5-9872a4824b65",
"targetId": "10051",
"callType": 0,
"mine": {
"userId": "10047",
"enableCamera": false,
"mediaType": 1,
"userType": 0,
"enableMicrophone": false
}
}
}

View File

@@ -1,51 +0,0 @@
{
"type": "Engine:OnCallReceived",
"module": "RongCloud-Call-RCUniCall",
"data": {
"endTime": 0,
"users": [{
"userId": "10051",
"enableCamera": false,
"mediaId": "420068630",
"mediaType": 0,
"userType": 0,
"enableMicrophone": false
}, {
"userId": "10047",
"enableCamera": true,
"mediaType": 0,
"userType": 0,
"enableMicrophone": false
}],
"inviter": {
"userId": "10051",
"enableCamera": false,
"mediaId": "420068630",
"mediaType": 0,
"userType": 0,
"enableMicrophone": false
},
"caller": {
"userId": "10051",
"enableCamera": false,
"mediaId": "420068630",
"mediaType": 0,
"userType": 0,
"enableMicrophone": false
},
"connectedTime": 0,
"extra": "",
"startTime": 0,
"mediaType": 0,
"callId": "1a1462b8-b63b-40a9-bf95-963e810ac49a",
"targetId": "10051",
"callType": 0,
"mine": {
"userId": "10047",
"enableCamera": true,
"mediaType": 0,
"userType": 0,
"enableMicrophone": false
}
}
}