Browse Source

优化代码

master
袁磊 6 months ago
parent
commit
f6485a3bb0
  1. 4
      App.vue
  2. 44
      pages/home/user.vue
  3. 18
      pages/setting/setting.vue
  4. 11
      pages/user/login.vue
  5. 5
      store/modules/user.js
  6. 6
      uni_modules/vrapile-im/components/vrapile-im/vrapile-im.vue
  7. 660
      uni_modules/vrapile-im/pages/chat/chatFriend.vue
  8. 352
      uni_modules/vrapile-im/pages/home/chatHome.vue
  9. 36
      uni_modules/vrapile-im/pages_init.json
  10. 52
      uni_modules/vrapile-im/readme.md
  11. 220
      uni_modules/vrapile-im/static/style/nine-chat-friend-001.scss
  12. 148
      uni_modules/vrapile-im/static/style/nine-chat-home-001.scss
  13. 2
      uni_modules/vrapile-im/store/getters.js
  14. 287
      uni_modules/vrapile-im/store/modules/chat.js
  15. 216
      uni_modules/vrapile-im/store/modules/socket.js
  16. 154
      uni_modules/vrapile-im/utils/nineTool.js
  17. 2
      uni_modules/vrapile-im/utils/storage.js
  18. 134
      uni_modules/vrapile-im/utils/tiosocket.js
  19. 1
      utils/request.js

4
App.vue

@ -59,8 +59,8 @@
},
initWebSocket(){
if(getToken()){
store.dispatch('GetChatList').then(res => {
store.dispatch('ConnSocket');
socketStore.dispatch('GetChatList').then(res => {
socketStore.dispatch('ConnSocket');
});
}
}

44
pages/home/user.vue

@ -49,49 +49,6 @@
</view>
</view>
<view v-if="userInfo.userId" class="nine-nav-001-item mt15">
<view class="nine-nav-001-item-left">
<image class="image35" mode="scaleToFill" src="/static/image/user/c5.png"></image>
<text class="nine-nav-001-item-left-text">我的钱包</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<view v-if="userInfo.userId" class="nine-nav-001-item mt15">
<view class="nine-nav-001-item-left">
<image class="image35" mode="scaleToFill" src="/static/image/user/c1.png"></image>
<text class="nine-nav-001-item-left-text">我的订单</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<view v-if="userInfo.userId" class="nine-nav-001-item">
<view class="nine-nav-001-item-left">
<image class="image35" mode="scaleToFill" src="/static/image/user/c8.png"></image>
<text class="nine-nav-001-item-left-text">我的卡券</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<view class="nine-nav-001-item">
<view class="nine-nav-001-item-left">
<image class="image35" mode="scaleToFill" src="/static/image/user/c7.png"></image>
<text class="nine-nav-001-item-left-text">购物车</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<!--#ifndef MP-ALIPAY-->
<view class="nine-nav-001-item mt15">
<view class="nine-nav-001-item-left">
<image class="image35" mode="scaleToFill" src="/static/image/user/c6.png"></image>
@ -102,7 +59,6 @@
</image>
</view>
</view>
<!--#endif-->
<view class="nine-nav-001-item mt15" @click="openUrl('/pages/setting/setting')">
<view class="nine-nav-001-item-left">

18
pages/setting/setting.vue

@ -11,15 +11,6 @@
</image>
</view>
</view>
<view v-if="userInfo.userId" class="nine-nav-001-item mt10">
<view class="nine-nav-001-item-left">
<text class="nine-nav-001-item-left-text">修改密码</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<view class="nine-nav-001-item mt10" @click="openUrl('/pages/setting/contact')">
<view class="nine-nav-001-item-left">
<text class="nine-nav-001-item-left-text">联系我们</text>
@ -29,15 +20,6 @@
</image>
</view>
</view>
<view class="nine-nav-001-item">
<view class="nine-nav-001-item-left">
<text class="nine-nav-001-item-left-text">清空缓存</text>
</view>
<view class="nine-nav-001-item-right">
<image class="nine-nav-001-item-right-image" mode="scaleToFill" src="/static/image/user/cc.png">
</image>
</view>
</view>
<view class="nine-nav-001-item" @click="openUrl('/pages/setting/about')">
<view class="nine-nav-001-item-left">
<text class="nine-nav-001-item-left-text">关于</text>

11
pages/user/login.vue

@ -85,7 +85,7 @@
this.password = loginInfo.password;
if(!this.userName){
this.usernamefocus();
}else if(this.loginType == 0){
}else if(this.loginType == 0){
this.passwordfocus();
}else{
this.verifyfocus();
@ -144,7 +144,6 @@
this.verifyfocus();
return;
}
this.loading("正在登录...");
store.dispatch('Login', {
loginType: this.loginType,
userName: this.userName.trim(),
@ -153,19 +152,11 @@
registerFlag: "Y"
}).then(() => {
this.loginSuccess()
}).catch(() => {
this.closeLoading()
})
},
loginSuccess() {
store.dispatch('GetInfo').then(res => {
socketStore.dispatch('GetChatList', {userId: store.state.user.userInfo.userId}).then(res=>{
socketStore.dispatch('ConnSocket', { url: import.meta.env.VITE_APP_SOCKET_URL, token: getToken() });
});
this.reLaunch('/pages/home/user')
this.closeLoading()
}).catch(()=>{
this.closeLoading()
})
},
registerClick() {

5
store/modules/user.js

@ -1,4 +1,5 @@
import store from '@/store'
import socketStore from '@/uni_modules/vrapile-im/store'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo } from '@/api/login'
@ -66,6 +67,10 @@ const user = {
commit('SET_USER_INFO', user)
commit('SET_NAME', userName)
commit('SET_AVATAR', avatar)
socketStore.dispatch('GetChatList').then(res => {
socketStore.dispatch('ConnSocket');
});
resolve(res)
}).catch(error => {
reject(error)

6
uni_modules/vrapile-im/components/vrapile-im/vrapile-im.vue

@ -1,5 +1,5 @@
<template>
<view>
vrapile-im页面组件此文件不会被引用
</view>
<view>
vrapile-im页面组件此文件不会被引用
</view>
</template>

660
uni_modules/vrapile-im/pages/chat/chatFriend.vue

@ -1,337 +1,337 @@
<template>
<view class="nine-content-001">
<view class="chat-body">
<view class="chat-body-main">
<view v-if="chatObject.haveHistory==0" class="chat-body-history">
没有更多消息了
</view>
<view v-else class="chat-body-history chat-body-history-have" @click="handleHistoryMessage(false)">
查看更多消息
</view>
<view class="chat-body-message">
<view v-for="(item, index) in messageList" :key="index">
<view class="chat-conversation" :class="item.fromId == userInfo.userId?'chat-conversation-mine':''">
<view class="chat-conversation-image">
<image class="chat-conversation-image-image" v-if="item.fromId != userInfo.userId" :src="getUserAvatar(item.fromId, item.avatar)"></image>
<image class="chat-conversation-image-image" v-else :src="userInfo.avatar || defaultAvatar"></image>
</view>
<view class="chat-conversation-text">
<view class="chat-conversation-text-time" v-if="item.sendType == 1 && item.fromId != userInfo.userId">{{getUserName(item.fromId, item.fromName)}}</view>
<view class="chat-conversation-text-time">{{formatTime(item.sendTime)}}</view>
<view class="chat-conversation-text-text nine-user-select">{{item.content}}</view>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="chat-footer">
<view class="chat-footer-send">
<view @click="handleVoice" class="chat-footer-send-voice">
<image class="chat-footer-send-image" :src="iconVoice"></image>
</view>
<view v-if="isVoice" @longpress="handleSay" class="chat-footer-send-say">
<span>按住 说话</span>
</view>
<view v-else class="chat-footer-send-input">
<input @confirm="handleSend" class="input" v-model="inputText" />
</view>
<view @click="handleEmoji" class="chat-footer-send-emoji">
<image class="chat-footer-send-image" :src="iconEmoji"></image>
</view>
<view v-if="inputText" @click="handleSend" class="chat-footer-send-button">
<span class="chat-footer-send-button-span">发送</span>
</view>
<view v-else @click="handleMore" class="chat-footer-send-more">
<image class="chat-footer-send-image" :src="iconMore"></image>
</view>
</view>
</view>
</view>
<view class="nine-content-001">
<view class="chat-body">
<view class="chat-body-main">
<view v-if="chatObject.haveHistory==0" class="chat-body-history">
没有更多消息了
</view>
<view v-else class="chat-body-history chat-body-history-have" @click="handleHistoryMessage(false)">
查看更多消息
</view>
<view class="chat-body-message">
<view v-for="(item, index) in messageList" :key="index">
<view class="chat-conversation" :class="item.fromId == userInfo.userId?'chat-conversation-mine':''">
<view class="chat-conversation-image">
<image class="chat-conversation-image-image" v-if="item.fromId != userInfo.userId" :src="getUserAvatar(item.fromId, item.avatar)"></image>
<image class="chat-conversation-image-image" v-else :src="userInfo.avatar || defaultAvatar"></image>
</view>
<view class="chat-conversation-text">
<view class="chat-conversation-text-time" v-if="item.sendType == 1 && item.fromId != userInfo.userId">{{getUserName(item.fromId, item.fromName)}}</view>
<view class="chat-conversation-text-time">{{formatTime(item.sendTime)}}</view>
<view class="chat-conversation-text-text nine-user-select">{{item.content}}</view>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="chat-footer">
<view class="chat-footer-send">
<view @click="handleVoice" class="chat-footer-send-voice">
<image class="chat-footer-send-image" :src="iconVoice"></image>
</view>
<view v-if="isVoice" @longpress="handleSay" class="chat-footer-send-say">
<span>按住 说话</span>
</view>
<view v-else class="chat-footer-send-input">
<input @confirm="handleSend" class="input" v-model="inputText" />
</view>
<view @click="handleEmoji" class="chat-footer-send-emoji">
<image class="chat-footer-send-image" :src="iconEmoji"></image>
</view>
<view v-if="inputText" @click="handleSend" class="chat-footer-send-button">
<span class="chat-footer-send-button-span">发送</span>
</view>
<view v-else @click="handleMore" class="chat-footer-send-more">
<image class="chat-footer-send-image" :src="iconMore"></image>
</view>
</view>
</view>
</view>
</template>
<script>
import { mapState } from 'vuex'
import store from '@/uni_modules/vrapile-im/store'
import { getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// storekey
import storeOut from '@/store'
import { getMessageByChatKey } from '@/api/chat'
export default {
data() {
return {
userInfo: {},
chatObject: {},
messageList: [],
noHistory: true,
isVoice: false,
inputText: "",
// key
key: null,
//
defaultAvatar: '/uni_modules/vrapile-im/static/image/yy.png',
//
iconMessage: "/uni_modules/vrapile-im/static/image/message.png",
//
iconVoice: "/uni_modules/vrapile-im/static/image/voice.png",
//
iconEmoji: "/uni_modules/vrapile-im/static/image/emoji.png",
//
iconMore: "/uni_modules/vrapile-im/static/image/more.png",
}
},
computed: {
...mapState({
websocketData: state => store.state.socket.websocketData
}),
getChatList() {
return store.state.chat.chatList;
},
getUserAvatar() {
return (userId, defaultAvatar) => {
return store.getters.getUserAvatar(userId, defaultAvatar);
}
},
getUserName() {
return (userId, defaultName) => {
return store.getters.getUserName(userId, defaultName);
}
}
},
onLoad(options){
this.userInfo = storeOut.state.user.userInfo;
if(!this.userInfo.userId){
this.navigateToLogin();
}
try{
this.key = options.data;
}catch(e){
this.switchTab("/uni_modules/vrapile-im/pages/home/chatHome");
}
},
//
onPullDownRefresh() {
if(this.chatObject.haveHistory==1){
this.handleHistoryMessage(true);
}
setTimeout(() => {
uni.stopPullDownRefresh();
}, 500);
},
onShow(){
for(let i=0; i < this.getChatList.length; i++){
if(this.getChatList[i]["key"] == this.key){
this.chatObject = this.getChatList[i];
uni.setNavigationBarTitle({
title: this.chatObject.name || "好友"
})
this.messageList = this.getChatList[i].messageList;
this.scrollToBottom();
if(this.messageList.length == 0 && this.chatObject.haveHistory==1){
this.handleHistoryMessage(true);
}else{
this.handleRead();
}
break;
}
}
},
//
watch: {
websocketData: {
handler(newVal, oldval) {
if(newVal && newVal.length > 0
&& (newVal[newVal.length-1]["toId"] == this.userInfo.userId
|| newVal[newVal.length-1]["fromId"] == this.userInfo.userId)){
this.scrollToBottom();
this.handleRead();
}
},
immediate: true,
deep: true
}
},
methods: {
//
scrollToBottom() {
setTimeout(() => {
uni.pageScrollTo({
scrollTop: 2000000,
duration : 10
})
}, 500);
},
//
handleVoice() {
this.isVoice = !this.isVoice;
},
//
handleSay() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一条语音消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleEmoji() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一个表情消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleMore() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一个更多的消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleRead() {
let sendInfo = {
code: 3,
message: {
//id
toId: this.chatObject.id,
//
userId: this.userInfo.userId,
//0-|1-
sendType: this.chatObject.type,
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
store.commit('READ_MESSAGE', this.key);
store.commit('COUNT_MESSAGE');
},
//
handleSend() {
if(!this.inputText){
return;
}
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: this.inputText,
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
this.inputText = "";
},
//
handleHistoryMessage(scrollFlag=false){
let limit = this.chatObject["messageList"].length + 10;
getMessageByChatKey({
type: this.chatObject.type,
key: this.chatObject["key"],
groupId: this.chatObject.id,
limit: limit
}).then(res => {
if(res.data.length > 0){
this.messageList = res.data;
this.chatObject["messageList"] = this.messageList;
let lastMessage = res.data[res.data.length-1];
this.chatObject["messageLast"] = lastMessage;
if(lastMessage["sendType"] == 0){
this.chatObject["messageShow"] = lastMessage["content"];
}else{
this.chatObject["messageShow"] = store.getters.getUserName(lastMessage["fromId"], lastMessage["fromName"]) + ": " + lastMessage["content"]
}
this.chatObject["messageTime"] = this.formatDate(lastMessage["sendTime"]);
}
if(res.data.length < limit){
this.chatObject["haveHistory"] = 0;
}
for(let i=0; i < this.getChatList.length; i++){
if(this.getChatList[i]["key"] == this.key){
this.$set(this.getChatList, i, this.chatObject)
break;
}
}
if(scrollFlag){
this.scrollToBottom();
}
});
}
}
}
import { mapState } from 'vuex'
import store from '@/uni_modules/vrapile-im/store'
import { getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// storekey
import storeOut from '@/store'
import { getMessageByChatKey } from '@/api/chat'
export default {
data() {
return {
userInfo: {},
chatObject: {},
messageList: [],
noHistory: true,
isVoice: false,
inputText: "",
// key
key: null,
//
defaultAvatar: '/uni_modules/vrapile-im/static/image/yy.png',
//
iconMessage: "/uni_modules/vrapile-im/static/image/message.png",
//
iconVoice: "/uni_modules/vrapile-im/static/image/voice.png",
//
iconEmoji: "/uni_modules/vrapile-im/static/image/emoji.png",
//
iconMore: "/uni_modules/vrapile-im/static/image/more.png",
}
},
computed: {
...mapState({
websocketData: state => store.state.socket.websocketData
}),
getChatList() {
return store.state.chat.chatList;
},
getUserAvatar() {
return (userId, defaultAvatar) => {
return store.getters.getUserAvatar(userId, defaultAvatar);
}
},
getUserName() {
return (userId, defaultName) => {
return store.getters.getUserName(userId, defaultName);
}
}
},
onLoad(options){
this.userInfo = storeOut.state.user.userInfo;
if(!this.userInfo.userId){
this.navigateToLogin();
}
try{
this.key = options.data;
}catch(e){
this.switchTab("/uni_modules/vrapile-im/pages/home/chatHome");
}
},
//
onPullDownRefresh() {
if(this.chatObject.haveHistory==1){
this.handleHistoryMessage(true);
}
setTimeout(() => {
uni.stopPullDownRefresh();
}, 500);
},
onShow(){
for(let i=0; i < this.getChatList.length; i++){
if(this.getChatList[i]["key"] == this.key){
this.chatObject = this.getChatList[i];
uni.setNavigationBarTitle({
title: this.chatObject.name || "好友"
})
this.messageList = this.getChatList[i].messageList;
this.scrollToBottom();
if(this.messageList.length == 0 && this.chatObject.haveHistory==1){
this.handleHistoryMessage(true);
}else{
this.handleRead();
}
break;
}
}
},
//
watch: {
websocketData: {
handler(newVal, oldval) {
if(newVal && newVal.length > 0
&& (newVal[newVal.length-1]["toId"] == this.userInfo.userId
|| newVal[newVal.length-1]["fromId"] == this.userInfo.userId)){
this.scrollToBottom();
this.handleRead();
}
},
immediate: true,
deep: true
}
},
methods: {
//
scrollToBottom() {
setTimeout(() => {
uni.pageScrollTo({
scrollTop: 2000000,
duration : 10
})
}, 500);
},
//
handleVoice() {
this.isVoice = !this.isVoice;
},
//
handleSay() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一条语音消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleEmoji() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一个表情消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleMore() {
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: "您发送了一个更多的消息",
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
},
//
handleRead() {
let sendInfo = {
code: 3,
message: {
//id
toId: this.chatObject.id,
//
userId: this.userInfo.userId,
//0-|1-
sendType: this.chatObject.type,
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
store.commit('READ_MESSAGE', this.key);
store.commit('COUNT_MESSAGE');
},
//
handleSend() {
if(!this.inputText){
return;
}
let sendInfo = {
code: 2,
message: {
// 0-|1-|2-|3-|4-
messageType: 0,
//id
toId: this.chatObject.id,
//
fromId: this.userInfo.userId,
//
fromName: this.userInfo.userName,
//
content: this.inputText,
//0-|1-
sendType: this.chatObject.type,
//
extend: null
},
};
uni.sendSocketMessage({
data: JSON.stringify(sendInfo)
})
this.inputText = "";
},
//
handleHistoryMessage(scrollFlag=false){
let limit = this.chatObject["messageList"].length + 10;
getMessageByChatKey({
type: this.chatObject.type,
key: this.chatObject["key"],
groupId: this.chatObject.id,
limit: limit
}).then(res => {
if(res.data.length > 0){
this.messageList = res.data;
this.chatObject["messageList"] = this.messageList;
let lastMessage = res.data[res.data.length-1];
this.chatObject["messageLast"] = lastMessage;
if(lastMessage["sendType"] == 0){
this.chatObject["messageShow"] = lastMessage["content"];
}else{
this.chatObject["messageShow"] = store.getters.getUserName(lastMessage["fromId"], lastMessage["fromName"]) + ": " + lastMessage["content"]
}
this.chatObject["messageTime"] = this.formatDate(lastMessage["sendTime"]);
}
if(res.data.length < limit){
this.chatObject["haveHistory"] = 0;
}
for(let i=0; i < this.getChatList.length; i++){
if(this.getChatList[i]["key"] == this.key){
this.$set(this.getChatList, i, this.chatObject)
break;
}
}
if(scrollFlag){
this.scrollToBottom();
}
});
}
}
}
</script>
<style scoped>
/* 重写外部nine-chat-friend-001.scss可实现样式改变 */
@import '/uni_modules/vrapile-im/static/style/nine-chat-friend-001.scss';
@import '/static/style/nine-chat-friend-001.scss';
/* 重写外部nine-chat-friend-001.scss可实现样式改变 */
@import '/uni_modules/vrapile-im/static/style/nine-chat-friend-001.scss';
@import '/static/style/nine-chat-friend-001.scss';
</style>

352
uni_modules/vrapile-im/pages/home/chatHome.vue

@ -1,184 +1,184 @@
<template>
<view class="nine-content-002">
<view class="chat-search">
<input class="chat-search-input" v-model="searchVal"/>
<uni-icons class="chat-search-image" type="search" size="24"></uni-icons>
</view>
<view class="chat-list">
<view class="chat-list-item" v-for="(item,index) in getChatFilterList" :key="index" @click="goToChat(item.key)">
<view class="chat-list-item-left">
<image class="chat-list-item-left-image" mode="scaleToFill" v-if="item.fromId != userInfo.userId" :src="getUserAvatar(item.fromId, item.avatar)"></image>
<image class="chat-list-item-left-image" mode="scaleToFill" v-else :src="userInfo.avatar || defaultAvatar"></image>
<view v-if="item.messageNum > 0" class="chat-list-item-left-mark">
{{ item.messageNum < 100 ? item.messageNum : 99 }}
</view>
</view>
<view class="chat-list-item-center">
<view class="chat-list-item-center-top">
{{ item.name }}
</view>
<view class="chat-list-item-center-bottom">
{{ item.messageShow || "&nbsp;" }}
</view>
</view>
<view class="chat-list-item-right">
<view class="chat-list-item-right-top">
{{ item.messageTime || '\xa0' }}
</view>
<view class="chat-list-item-right-bottom">
<image class="chat-list-item-right-bottom-image" mode="scaleToFill" :src="iconMessage">
</image>
</view>
</view>
</view>
</view>
</view>
<view class="nine-content-002">
<view class="chat-search">
<input class="chat-search-input" v-model="searchVal"/>
<uni-icons class="chat-search-image" type="search" size="24"></uni-icons>
</view>
<view class="chat-list">
<view class="chat-list-item" v-for="(item,index) in getChatFilterList" :key="index" @click="goToChat(item.key)">
<view class="chat-list-item-left">
<image class="chat-list-item-left-image" mode="scaleToFill" v-if="item.fromId != userInfo.userId" :src="getUserAvatar(item.fromId, item.avatar)"></image>
<image class="chat-list-item-left-image" mode="scaleToFill" v-else :src="userInfo.avatar || defaultAvatar"></image>
<view v-if="item.messageNum > 0" class="chat-list-item-left-mark">
{{ item.messageNum < 100 ? item.messageNum : 99 }}
</view>
</view>
<view class="chat-list-item-center">
<view class="chat-list-item-center-top">
{{ item.name }}
</view>
<view class="chat-list-item-center-bottom">
{{ item.messageShow || "&nbsp;" }}
</view>
</view>
<view class="chat-list-item-right">
<view class="chat-list-item-right-top">
{{ item.messageTime || '\xa0' }}
</view>
<view class="chat-list-item-right-bottom">
<image class="chat-list-item-right-bottom-image" mode="scaleToFill" :src="iconMessage">
</image>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import { mapState } from 'vuex'
import store from '@/uni_modules/vrapile-im/store'
import { getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// storewebsockettokentokenkey
import storeOut from '@/store'
import { mapState } from 'vuex'
import store from '@/uni_modules/vrapile-im/store'
import { getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// storewebsockettokentokenkey
import storeOut from '@/store'
import { getToken } from '@/utils/token'
import { getMessageByChatKey } from '@/api/chat'
export default {
data() {
return {
userInfo: {},
searchVal: "",
//
defaultAvatar: '/uni_modules/vrapile-im/static/image/yy.png',
//
iconMessage: "/uni_modules/vrapile-im/static/image/message.png"
}
},
computed: {
...mapState({
websocketData: state => store.state.socket.websocketData
}),
getChatList() {
return store.state.chat.chatList;
},
getChatFilterList() {
let list = JSON.parse(JSON.stringify(store.state.chat.chatList))
list.sort((a, b) => {
if(a.messageNum > 0 && b.messageNum > 0){
return b.messageLast.sendTime - a.messageLast.sendTime
}
if(a.messageList.length == 0 || b.messageList.length == 0){
return b.messageList.length - a.messageList.length
}
if(a.messageNum == 0 && b.messageNum == 0){
return b.messageLast.sendTime - a.messageLast.sendTime
}
return b.messageNum - a.messageNum
})
if(this.searchVal){
return list.filter(item => {
if(item.name && item.name.includes(this.searchVal)
|| item.remarkName && item.remarkName.includes(this.searchVal)
|| item.userName && item.userName.includes(this.searchVal)){
return item;
}
for(let message of item.messageList){
if(message.content && message.content.includes(this.searchVal)){
return item;
}
}
});
}
return list;
},
getUserAvatar() {
return (userId, defaultAvatar) => {
return store.getters.getUserAvatar(userId, defaultAvatar);
}
}
},
onLoad(options){
this.userInfo = storeOut.state.user.userInfo;
},
onShow(){
setTimeout(()=>{
this.dealUnReadMessage();
store.commit('COUNT_MESSAGE');
}, 500)
setTimeout(()=>{
this.noListDo();
}, 3000)
},
activated(){
store.commit('COUNT_MESSAGE');
},
//
watch: {
websocketData: {
handler(newVal, oldval) {
for(let i=0;i<this.getChatList.length;i++){
this.$set(this.getChatList, i, this.getChatList[i])
}
},
immediate: true,
deep: true
}
},
methods: {
//
dealUnReadMessage() {
for(let i=0;i<this.getChatList.length;i++){
if(this.getChatList[i]["messageList"].length == 0 && this.getChatList[i]["haveHistory"] == 1){
this.handleHistoryMessage(i, false);
}
}
},
// socket
noListDo(){
if(storeOut.state.user.userInfo.userId && (!this.getChatList || this.getChatList.length == 0)){
store.dispatch('GetChatList', {userId: storeOut.state.user.userInfo.userId}).then(res => {
store.dispatch('ConnSocket', { url: import.meta.env.VITE_APP_SOCKET_URL, token: getToken() });
});
}
},
//
handleHistoryMessage(i, scrollFlag){
let limit = this.getChatList[i]["messageList"].length + 10;
getMessageByChatKey({
type: this.getChatList[i].type,
key: this.getChatList[i]["key"],
groupId: this.getChatList[i].id,
limit: limit
}).then(res => {
if(res.data.length > 0){
this.getChatList[i]["messageList"] = res.data;
let lastMessage = res.data[res.data.length-1];
this.getChatList[i]["messageLast"] = lastMessage;
if(lastMessage["sendType"] == 0){
this.getChatList[i]["messageShow"] = lastMessage["content"];
}else{
this.getChatList[i]["messageShow"] = store.getters.getUserName(lastMessage["fromId"], lastMessage["fromName"]) + ": " + lastMessage["content"]
}
this.getChatList[i]["messageTime"] = this.formatDate(lastMessage["sendTime"]);
}
if(res.data.length < limit){
this.getChatList[i]["haveHistory"] = 0;
}
this.$set(this.getChatList, i, this.getChatList[i])
});
},
//
goToChat(key) {
this.navigateTo("/uni_modules/vrapile-im/pages/chat/chatFriend?data=" + key)
}
}
}
import { getMessageByChatKey } from '@/api/chat'
export default {
data() {
return {
userInfo: {},
searchVal: "",
//
defaultAvatar: '/uni_modules/vrapile-im/static/image/yy.png',
//
iconMessage: "/uni_modules/vrapile-im/static/image/message.png"
}
},
computed: {
...mapState({
websocketData: state => store.state.socket.websocketData
}),
getChatList() {
return store.state.chat.chatList;
},
getChatFilterList() {
let list = JSON.parse(JSON.stringify(store.state.chat.chatList))
list.sort((a, b) => {
if(a.messageNum > 0 && b.messageNum > 0){
return b.messageLast.sendTime - a.messageLast.sendTime
}
if(a.messageList.length == 0 || b.messageList.length == 0){
return b.messageList.length - a.messageList.length
}
if(a.messageNum == 0 && b.messageNum == 0){
return b.messageLast.sendTime - a.messageLast.sendTime
}
return b.messageNum - a.messageNum
})
if(this.searchVal){
return list.filter(item => {
if(item.name && item.name.includes(this.searchVal)
|| item.remarkName && item.remarkName.includes(this.searchVal)
|| item.userName && item.userName.includes(this.searchVal)){
return item;
}
for(let message of item.messageList){
if(message.content && message.content.includes(this.searchVal)){
return item;
}
}
});
}
return list;
},
getUserAvatar() {
return (userId, defaultAvatar) => {
return store.getters.getUserAvatar(userId, defaultAvatar);
}
}
},
onLoad(options){
this.userInfo = storeOut.state.user.userInfo;
},
onShow(){
setTimeout(()=>{
this.dealUnReadMessage();
store.commit('COUNT_MESSAGE');
}, 500)
setTimeout(()=>{
this.noListDo();
}, 3000)
},
activated(){
store.commit('COUNT_MESSAGE');
},
//
watch: {
websocketData: {
handler(newVal, oldval) {
for(let i=0;i<this.getChatList.length;i++){
this.$set(this.getChatList, i, this.getChatList[i])
}
},
immediate: true,
deep: true
}
},
methods: {
//
dealUnReadMessage() {
for(let i=0;i<this.getChatList.length;i++){
if(this.getChatList[i]["messageList"].length == 0 && this.getChatList[i]["haveHistory"] == 1){
this.handleHistoryMessage(i, false);
}
}
},
// socket
noListDo(){
if(storeOut.state.user.userInfo.userId && (!this.getChatList || this.getChatList.length == 0)){
store.dispatch('GetChatList').then(res => {
store.dispatch('ConnSocket');
});
}
},
//
handleHistoryMessage(i, scrollFlag){
let limit = this.getChatList[i]["messageList"].length + 10;
getMessageByChatKey({
type: this.getChatList[i].type,
key: this.getChatList[i]["key"],
groupId: this.getChatList[i].id,
limit: limit
}).then(res => {
if(res.data.length > 0){
this.getChatList[i]["messageList"] = res.data;
let lastMessage = res.data[res.data.length-1];
this.getChatList[i]["messageLast"] = lastMessage;
if(lastMessage["sendType"] == 0){
this.getChatList[i]["messageShow"] = lastMessage["content"];
}else{
this.getChatList[i]["messageShow"] = store.getters.getUserName(lastMessage["fromId"], lastMessage["fromName"]) + ": " + lastMessage["content"]
}
this.getChatList[i]["messageTime"] = this.formatDate(lastMessage["sendTime"]);
}
if(res.data.length < limit){
this.getChatList[i]["haveHistory"] = 0;
}
this.$set(this.getChatList, i, this.getChatList[i])
});
},
//
goToChat(key) {
this.navigateTo("/uni_modules/vrapile-im/pages/chat/chatFriend?data=" + key)
}
}
}
</script>
<style scoped>
/* 重写外部nine-chat-home-001.scss可实现样式改变 */
@import '/uni_modules/vrapile-im/static/style/nine-chat-home-001.scss';
@import '/static/style/nine-chat-home-001.scss';
/* 重写外部nine-chat-home-001.scss可实现样式改变 */
@import '/uni_modules/vrapile-im/static/style/nine-chat-home-001.scss';
@import '/static/style/nine-chat-home-001.scss';
</style>

36
uni_modules/vrapile-im/pages_init.json

@ -1,20 +1,20 @@
{
"pages": [
//
{
"path": "uni_modules/vrapile-im/pages/home/chatHome",
"style": {
"navigationBarTitleText": "消息",
"enablePullDownRefresh": false
}
},
//
{
"path": "uni_modules/vrapile-im/pages/chat/chatFriend",
"style": {
"navigationBarTitleText": "聊天",
"enablePullDownRefresh": true
}
}
]
"pages": [
//
{
"path": "uni_modules/vrapile-im/pages/home/chatHome",
"style": {
"navigationBarTitleText": "消息",
"enablePullDownRefresh": false
}
},
//
{
"path": "uni_modules/vrapile-im/pages/chat/chatFriend",
"style": {
"navigationBarTitleText": "聊天",
"enablePullDownRefresh": true
}
}
]
}

52
uni_modules/vrapile-im/readme.md

@ -19,18 +19,18 @@
导入组件后,会在 pages.json 中自动注册组件,若未注册可手动添加
``` javascript
{
"path": "uni_modules/vrapile-im/pages/home/chatHome",
"style": {
"enablePullDownRefresh": false,
"navigationBarTitleText": "消息"
}
"path": "uni_modules/vrapile-im/pages/home/chatHome",
"style": {
"enablePullDownRefresh": false,
"navigationBarTitleText": "消息"
}
},
{
"path": "uni_modules/vrapile-im/pages/chat/chatFriend",
"style": {
"enablePullDownRefresh": false,
"navigationBarTitleText": "聊天"
}
"path": "uni_modules/vrapile-im/pages/chat/chatFriend",
"style": {
"enablePullDownRefresh": false,
"navigationBarTitleText": "聊天"
}
}
```
@ -38,21 +38,17 @@
``` javascript
"tabBar": {
"selectedColor": "#0000ff",
"list": [
{
"pagePath": "uni_modules/vrapile-im/pages/home/chatHome",
"iconPath": "static/image/tabbar/chat.png",
"selectedIconPath": "static/image/tabbar/chat-fill.png",
"text": "消息"
},
{
"pagePath": "pages/home/user",
"iconPath": "static/image/tabbar/user.png",
"selectedIconPath": "static/image/tabbar/user-fill.png",
"text": "我的"
}
]
"selectedColor": "#0000ff",
"list": [
...
{
"pagePath": "uni_modules/vrapile-im/pages/home/chatHome",
"iconPath": "static/image/tabbar/chat.png",
"selectedIconPath": "static/image/tabbar/chat-fill.png",
"text": "消息"
},
...
]
},
```
@ -64,7 +60,7 @@
<br><br>
## 演示说明
<font color="gray">*以下所有工程共用一个后端,账号互通
<font color="gray">*以下系统共用一个后端,账号互通
( 账号/密码:visitor/visitor )*</font>
<br><br>
@ -79,7 +75,7 @@
演示商城效果:<font color="gray">*H5中可下载安卓App*</font>
<br>
<a href="https://www.ninecloud.top/unine/index.html" target="_blank">
https://www.ninecloud.top/unine/index.html
https://www.ninecloud.top/unine/index.html
</a>
<img src="https://fs.ninecloud.top/uniapp/unine/qrcode.png" width="300">
@ -88,7 +84,7 @@
演示PC前端:<font color="gray">*与此组件无关,可用于多端消息互相发送测试*</font>
<br>
<a href="https://www.ninecloud.top/msw/index" target="_blank">
https://www.ninecloud.top/msw/index
https://www.ninecloud.top/msw/index
</a>
<br><br><br><br>

220
uni_modules/vrapile-im/static/style/nine-chat-friend-001.scss

@ -1,165 +1,165 @@
html, body, #app{
height: 100%;
background-color: #f1f1f1;
height: 100%;
background-color: #f1f1f1;
}
.nine-content-001{
display: flex;
flex-direction: column;
width: 750rpx;
height: calc(100vh - 0px);
margin: 0;
padding: 0;
background-color: #f1f1f1;
display: flex;
flex-direction: column;
width: 750rpx;
height: calc(100vh - 0px);
margin: 0;
padding: 0;
background-color: #f1f1f1;
}
.chat-body {
/* #ifdef MP-WEIXIN */
background-color: #fff;
/* #endif */
/* #ifdef MP-WEIXIN */
background-color: #fff;
/* #endif */
}
.chat-body-main{
padding-top: 20rpx;
padding-left: 20rpx;
padding-right: 20rpx;
box-sizing: border-box;
-webkit-overflow-scrolling: touch;
padding-bottom: 100rpx;
padding-top: 20rpx;
padding-left: 20rpx;
padding-right: 20rpx;
box-sizing: border-box;
-webkit-overflow-scrolling: touch;
padding-bottom: 100rpx;
}
.chat-body-history{
width: 100%;
height: 90rpx;
line-height: 90rpx;
font-size: 24rpx;
color: grey;
text-align: center;
width: 100%;
height: 90rpx;
line-height: 90rpx;
font-size: 24rpx;
color: grey;
text-align: center;
}
.chat-body-history-have{
color: rgb(79, 172, 249);
color: rgb(79, 172, 249);
}
.chat-conversation{
display: flex;
align-items: flex-start;
padding: 20rpx 5rpx;
word-break: break-all;
display: flex;
align-items: flex-start;
padding: 20rpx 5rpx;
word-break: break-all;
}
.chat-conversation-text{
flex: 1;
display: flex;
flex-direction: column;
align-items: flex-start;
margin: 0 20rpx;
flex: 1;
display: flex;
flex-direction: column;
align-items: flex-start;
margin: 0 20rpx;
}
.chat-conversation-text-time{
font-size: 10px;
color: gray;
font-size: 10px;
color: gray;
}
.chat-conversation-text-text{
position: relative;
display: flex;
align-items: center;
max-width: 70%;
min-height: 45rpx;
padding: 15rpx 20rpx;
border-radius: 10rpx;
background-color: #FFF;
/* #ifdef MP-WEIXIN */
background-color: #f1f1f1;
/* #endif */
position: relative;
display: flex;
align-items: center;
max-width: 70%;
min-height: 45rpx;
padding: 15rpx 20rpx;
border-radius: 10rpx;
background-color: #FFF;
/* #ifdef MP-WEIXIN */
background-color: #f1f1f1;
/* #endif */
}
.chat-conversation-text-text::after {
content: '';
position: absolute;
top: 16rpx;
left: -35rpx;
border-width: 19rpx;
border-style: solid;
border-top-color: transparent;
border-left-color: transparent;
border-right-color: #FFF;
/* #ifdef MP-WEIXIN */
border-right-color: #f1f1f1;
/* #endif */
border-bottom-color: transparent;
content: '';
position: absolute;
top: 16rpx;
left: -35rpx;
border-width: 19rpx;
border-style: solid;
border-top-color: transparent;
border-left-color: transparent;
border-right-color: #FFF;
/* #ifdef MP-WEIXIN */
border-right-color: #f1f1f1;
/* #endif */
border-bottom-color: transparent;
}
.chat-conversation-mine{
align-items: flex-start;
flex-direction: row-reverse;
align-items: flex-start;
flex-direction: row-reverse;
}
.chat-conversation-mine .chat-conversation-text{
align-items: flex-end;
align-items: flex-end;
}
.chat-conversation-mine .chat-conversation-text-time{
text-align: right;
text-align: right;
}
.chat-conversation-mine .chat-conversation-text-text{
background: #9ede86 !important;
background: #9ede86 !important;
}
.chat-conversation-mine .chat-conversation-text-text::after {
left: auto !important;
right: -35rpx !important;
border-left-color: #9ede86 !important;
border-right-color: transparent !important;
left: auto !important;
right: -35rpx !important;
border-left-color: #9ede86 !important;
border-right-color: transparent !important;
}
.chat-conversation-image{
}
.chat-conversation-image-image{
width: 80rpx;
height: 80rpx;
padding: 5rpx;
border-radius: 10rpx;
width: 80rpx;
height: 80rpx;
padding: 5rpx;
border-radius: 10rpx;
}
.chat-footer {
position: fixed;
left: 0;
right: 0;
bottom: 0;
height: 100rpx;
background-color: #fff;
display: flex;
/* #ifdef MP-WEIXIN */
border-top: 1rpx solid #f1f1f1;
/* #endif */
position: fixed;
left: 0;
right: 0;
bottom: 0;
height: 100rpx;
background-color: #fff;
display: flex;
/* #ifdef MP-WEIXIN */
border-top: 1rpx solid #f1f1f1;
/* #endif */
}
.chat-footer-send{
flex-grow: 1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 10rpx;
flex-grow: 1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 10rpx;
}
.chat-footer-send-image{
padding: 0 10rpx;
width: 60rpx;
height: 60rpx;
padding: 0 10rpx;
width: 60rpx;
height: 60rpx;
}
.chat-footer-send-input{
flex-grow: 1;
text-align: left;
padding: 15rpx;
border-radius: 5rpx;
background-color: #f9f9f9;
flex-grow: 1;
text-align: left;
padding: 15rpx;
border-radius: 5rpx;
background-color: #f9f9f9;
}
.chat-footer-send-say{
flex-grow: 1;
text-align: center;
padding: 20rpx;
border-radius: 5rpx;
background-color: #f9f9f9;
flex-grow: 1;
text-align: center;
padding: 20rpx;
border-radius: 5rpx;
background-color: #f9f9f9;
}
.chat-footer-send-button{
line-height: 65rpx;
margin: 0 10rpx;
color: #FFFFFF;
background-color: #0000ff;
border-radius: 10rpx;
line-height: 65rpx;
margin: 0 10rpx;
color: #FFFFFF;
background-color: #0000ff;
border-radius: 10rpx;
}
.chat-footer-send-button-span{
padding: 0 25rpx;
padding: 0 25rpx;
}
// 允许文本复制
.nine-user-select {
cursor: auto;
-webkit-user-select: text;
user-select: text;
cursor: auto;
-webkit-user-select: text;
user-select: text;
}

148
uni_modules/vrapile-im/static/style/nine-chat-home-001.scss

@ -1,112 +1,112 @@
html, body, #app{
height: 100%;
background-color: #f1f1f1;
height: 100%;
background-color: #f1f1f1;
}
.nine-content-002{
display: flex;
flex-direction: column;
width: 750rpx;
height: calc(100vh - 50px);
/* #ifndef H5 */
height: calc(100vh - 0px);
/* #endif */
margin: 0;
padding: 0;
background-color: #f1f1f1;
display: flex;
flex-direction: column;
width: 750rpx;
height: calc(100vh - 50px);
/* #ifndef H5 */
height: calc(100vh - 0px);
/* #endif */
margin: 0;
padding: 0;
background-color: #f1f1f1;
}
.chat-search{
display: flex;
align-items: center;
padding: 5rpx;
background-color: #ffffff;
display: flex;
align-items: center;
padding: 5rpx;
background-color: #ffffff;
}
.chat-search-image{
height: 45rpx;
line-height: 45rpx;
padding: 10rpx;
background-color: #f8f8f8;
height: 45rpx;
line-height: 45rpx;
padding: 10rpx;
background-color: #f8f8f8;
}
.chat-search-input{
width: 100%;
height: 45rpx;
line-height: 45rpx;
padding: 10rpx;
font-size: 16px;
background-color: #f8f8f8;
width: 100%;
height: 45rpx;
line-height: 45rpx;
padding: 10rpx;
font-size: 16px;
background-color: #f8f8f8;
}
.chat-list{
flex: 1;
padding: 0;
overflow-y: auto;
flex: 1;
padding: 0;
overflow-y: auto;
}
.chat-list-item{
display: flex;
align-items: center;
justify-content: space-between;
margin: 2rpx 0;
padding: 15rpx 10rpx;
border-radius: 10rpx;
background-color: #ffffff;
display: flex;
align-items: center;
justify-content: space-between;
margin: 2rpx 0;
padding: 15rpx 10rpx;
border-radius: 10rpx;
background-color: #ffffff;
}
.chat-list-item-left{
position: relative;
width: 84rpx;
height: 84rpx;
position: relative;
width: 84rpx;
height: 84rpx;
}
.chat-list-item-left-image{
width: 82rpx;
height: 82rpx;
border: 1rpx solid #f1f1f1;
border-radius: 5rpx;
width: 82rpx;
height: 82rpx;
border: 1rpx solid #f1f1f1;
border-radius: 5rpx;
}
.chat-list-item-left-mark{
position: absolute;
width: 30rpx;
top: -13rpx;
right: -13rpx;
padding: 1rpx;
border-radius: 50%;
font-size: 12px;
color: white;
background-color: red;
text-align: center;
position: absolute;
width: 30rpx;
top: -13rpx;
right: -13rpx;
padding: 1rpx;
border-radius: 50%;
font-size: 12px;
color: white;
background-color: red;
text-align: center;
}
.chat-list-item-center{
width: 450rpx;
margin: 0 20rpx;
width: 450rpx;
margin: 0 20rpx;
}
.chat-list-item-center-top{
width: 450rpx;
font-size: 16px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 450rpx;
font-size: 16px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.chat-list-item-center-bottom{
width: 450rpx;
font-size: 12px;
color: #969696;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 450rpx;
font-size: 12px;
color: #969696;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.chat-list-item-right{
width: 130rpx;
color: #a7a7a7;
width: 130rpx;
color: #a7a7a7;
}
.chat-list-item-right-top{
font-size: 12px;
text-align: right;
font-size: 12px;
text-align: right;
}
.chat-list-item-right-bottom{
padding-top: 15rpx;
text-align: right;
padding-top: 15rpx;
text-align: right;
}
.chat-list-item-right-bottom-image{
width: 25rpx;
height: 30rpx;
width: 25rpx;
height: 30rpx;
}

2
uni_modules/vrapile-im/store/getters.js

@ -4,7 +4,7 @@ const getters = {
groupList: state => state.chat.groupList,
userObject: state => state.chat.userObject,
groupObject: state => state.chat.groupObject,
websocket: state => state.socket.websocket,
websocketData: state => state.socket.websocketData
}

287
uni_modules/vrapile-im/store/modules/chat.js

@ -2,163 +2,164 @@ import storage from '@/uni_modules/vrapile-im/utils/storage'
import constant from '@/uni_modules/vrapile-im/utils/constant'
import { getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// 外部需提供获取用户好友,获取用户所有群,以及群中所有用户三个接口
// 外部需提供获取用户好友,获取用户所有群,以及群中所有用户三个接口
import { getUserAllFriend, getUserAllGroup, getGroupUser } from '@/api/chat'
const chat = {
state: {
friendList: storage.get(constant.friendList) || [],
groupList: storage.get(constant.groupList) || [],
userObject: storage.get(constant.userObject) || {},
groupObject: storage.get(constant.groupObject) || {},
chatList: storage.get(constant.chatList) || []
},
mutations: {
// 清空聊天列表
CLEAN_CHAT_LIST: (state) => {
state.chatList = new Array();
storage.set(constant.chatList, new Array());
state.friendList = new Array();
storage.set(constant.friendList, new Array());
state.groupList = new Array();
storage.set(constant.groupList, new Array());
state.userObject = {};
storage.set(constant.userObject, {});
state.groupObject = {};
storage.set(constant.groupObject, {});
},
// 存储好友聊天列表
SET_CHAT_FRIEND_LIST: (state, data) => {
state.friendList = data;
storage.set(constant.friendList, data)
for(let item of data){
item["key"] = getChatKey(item["type"], item["friendId"], item["userId"])
item["haveHistory"] = 1;
item["id"] = item["friendId"];
item["name"] = item["remarkName"] || item["nickName"];
item["messageNum"] = 0;
item["messageList"] = [];
item["messageShow"] = "";
item["messageLast"] = {};
state.chatList.push(item)
}
storage.set(constant.chatList, state.chatList)
},
// 存储群聊列表
SET_CHAT_GROUP_LIST: (state, data) => {
state.groupList = data;
storage.set(constant.groupList, data)
for(let item of data){
item["key"] = getChatKey(item["type"], item["id"], item["userId"])
item["haveHistory"] = 1;
item["id"] = item["id"];
item["name"] = item["remarkName"] || item["name"]
item["messageNum"] = 0;
item["messageList"] = [];
item["messageShow"] = "";
item["messageLast"] = {};
state.chatList.push(item)
}
storage.set(constant.chatList, state.chatList)
},
// 存储用户对象,方便寻找用户名,头像等
SET_USER_OBJECT: (state, userObject) => {
state.userObject[userObject.userId] = userObject;
storage.set(constant.userObject, state.userObject);
},
// 存储群组对象,方便寻找群组名,头像等
SET_GROUP_OBJECT: (state, groupObject) => {
state.groupObject[groupObject.id] = groupObject;
storage.set(constant.groupObject, state.groupObject);
}
},
state: {
friendList: storage.get(constant.friendList) || [],
groupList: storage.get(constant.groupList) || [],
userObject: storage.get(constant.userObject) || {},
groupObject: storage.get(constant.groupObject) || {},
chatList: storage.get(constant.chatList) || []
},
mutations: {
// 清空聊天列表
CLEAN_CHAT_LIST: (state) => {
state.chatList = new Array();
storage.set(constant.chatList, new Array());
state.friendList = new Array();
storage.set(constant.friendList, new Array());
state.groupList = new Array();
storage.set(constant.groupList, new Array());
state.userObject = {};
storage.set(constant.userObject, {});
state.groupObject = {};
storage.set(constant.groupObject, {});
},
// 存储好友聊天列表
SET_CHAT_FRIEND_LIST: (state, data) => {
state.friendList = data;
storage.set(constant.friendList, data)
for(let item of data){
item["key"] = getChatKey(item["type"], item["friendId"], item["userId"])
item["haveHistory"] = 1;
item["id"] = item["friendId"];
item["name"] = item["remarkName"] || item["nickName"];
item["messageNum"] = 0;
item["messageList"] = [];
item["messageShow"] = "";
item["messageLast"] = {};
state.chatList.push(item)
}
storage.set(constant.chatList, state.chatList)
},
// 存储群聊列表
SET_CHAT_GROUP_LIST: (state, data) => {
state.groupList = data;
storage.set(constant.groupList, data)
for(let item of data){
item["key"] = getChatKey(item["type"], item["id"], item["userId"])
item["haveHistory"] = 1;
item["id"] = item["id"];
item["name"] = item["remarkName"] || item["name"]
item["messageNum"] = 0;
item["messageList"] = [];
item["messageShow"] = "";
item["messageLast"] = {};
state.chatList.push(item)
}
storage.set(constant.chatList, state.chatList)
},
// 存储用户对象,方便寻找用户名,头像等
SET_USER_OBJECT: (state, userObject) => {
state.userObject[userObject.userId] = userObject;
storage.set(constant.userObject, state.userObject);
},
// 存储群组对象,方便寻找群组名,头像等
SET_GROUP_OBJECT: (state, groupObject) => {
state.groupObject[groupObject.id] = groupObject;
storage.set(constant.groupObject, state.groupObject);
}
},
actions: {
// 获取登录用户所有聊天列表
GetChatList({ commit, state }, params) {
// 获取登录用户所有聊天列表
GetChatList({ commit, state }, params) {
return new Promise((resolve, reject) => {
commit('CLEAN_CHAT_LIST');
// 查询好友
getUserAllFriend().then(res => {
let listFriend = []
for(let itemFriend of res.data){
commit('CLEAN_CHAT_LIST');
// 查询好友
getUserAllFriend().then(res => {
let listFriend = []
for(let itemFriend of res.data){
delete itemFriend["createBy"]
delete itemFriend["updateBy"]
delete itemFriend["createTime"]
delete itemFriend["updateTime"]
listFriend.push({type: 0, ...itemFriend, userId: params.userId})
commit('SET_USER_OBJECT', {...itemFriend, userId: itemFriend.friendId})
}
listFriend.push({type: 0, ...itemFriend})
commit('SET_USER_OBJECT', {...itemFriend, userId: itemFriend.friendId})
}
commit('SET_CHAT_FRIEND_LIST', listFriend)
// 查询群组
getUserAllGroup().then(res1 => {
let listGroup = []
for(let itemGroup of res1.data){
delete itemGroup["createBy"]
delete itemGroup["updateBy"]
delete itemGroup["createTime"]
delete itemGroup["updateTime"]
listGroup.push({type: 1, ...itemGroup, userId: params.userId})
// 查询群组人员
getGroupUser(itemGroup.id).then(res2 => {
for(let itemGroupUser of res2.data){
delete itemGroupUser["createBy"]
delete itemGroupUser["updateBy"]
delete itemGroupUser["createTime"]
delete itemGroupUser["updateTime"]
delete itemGroupUser["groupId"]
delete itemGroupUser["groupName"]
commit('SET_USER_OBJECT', itemGroupUser)
}
resolve(res2)
});
delete itemGroup["createBy"]
delete itemGroup["updateBy"]
delete itemGroup["createTime"]
delete itemGroup["updateTime"]
commit('SET_GROUP_OBJECT', itemGroup)
}
commit('SET_CHAT_GROUP_LIST', listGroup)
}).catch(error => {
reject(error)
})
// 查询群组
getUserAllGroup().then(res1 => {
let listGroup = []
for(let itemGroup of res1.data){
delete itemGroup["createBy"];
delete itemGroup["updateBy"];
delete itemGroup["createTime"];
delete itemGroup["updateTime"];
listGroup.push({type: 1, ...itemGroup});
// 查询群组人员
getGroupUser(itemGroup.id).then(res2 => {
for(let itemGroupUser of res2.data){
delete itemGroupUser["createBy"];
delete itemGroupUser["updateBy"];
delete itemGroupUser["createTime"];
delete itemGroupUser["updateTime"];
delete itemGroupUser["groupId"];
delete itemGroupUser["groupName"];
commit('SET_USER_OBJECT', itemGroupUser);
}
});
delete itemGroup["createBy"];
delete itemGroup["updateBy"];
delete itemGroup["createTime"];
delete itemGroup["updateTime"];
commit('SET_GROUP_OBJECT', itemGroup);
}
commit('SET_CHAT_GROUP_LIST', listGroup);
}).catch(error => {
reject(error);
})
}).catch(error => {
reject(error)
reject(error);
}).finally(() => {
resolve();
})
})
}
}
},
getters: {
getUserAvatar: (state) => (userId, defaultAvatar) => {
if(state.userObject[userId] && state.userObject[userId]["avatar"]){
return state.userObject[userId]["avatar"]
}
return defaultAvatar || '/uni_modules/vrapile-im/static/image/yy.png';
},
getGroupAvatar: (state) => (groupId, defaultAvatar) => {
if(state.groupObject[groupId] && state.groupObject[groupId]["avatar"]){
return state.groupObject[groupId]["avatar"]
}
return defaultAvatar || '/uni_modules/vrapile-im/static/image/yy.png';
},
getUserName: (state) => (userId, defaultName) => {
if(state.userObject[userId]){
return state.userObject[userId]["remarkName"] || state.userObject[userId]["nickName"] || defaultName
}
return defaultName || "无名";
},
getGroupName: (state) => (groupId, defaultName) => {
if(state.groupObject[groupId]){
return state.groupObject[userId]["remarkName"] || state.groupObject[userId]["name"] || defaultName
}
return defaultName || "无名";
}
}
getters: {
getUserAvatar: (state) => (userId, defaultAvatar) => {
if(state.userObject[userId] && state.userObject[userId]["avatar"]){
return state.userObject[userId]["avatar"]
}
return defaultAvatar || '/uni_modules/vrapile-im/static/image/yy.png';
},
getGroupAvatar: (state) => (groupId, defaultAvatar) => {
if(state.groupObject[groupId] && state.groupObject[groupId]["avatar"]){
return state.groupObject[groupId]["avatar"]
}
return defaultAvatar || '/uni_modules/vrapile-im/static/image/yy.png';
},
getUserName: (state) => (userId, defaultName) => {
if(state.userObject[userId]){
return state.userObject[userId]["remarkName"] || state.userObject[userId]["nickName"] || defaultName
}
return defaultName || "无名";
},
getGroupName: (state) => (groupId, defaultName) => {
if(state.groupObject[groupId]){
return state.groupObject[userId]["remarkName"] || state.groupObject[userId]["name"] || defaultName
}
return defaultName || "无名";
}
}
}
export default chat

216
uni_modules/vrapile-im/store/modules/socket.js

@ -2,117 +2,119 @@ import store from '@/uni_modules/vrapile-im/store'
import storage from '@/uni_modules/vrapile-im/utils/storage'
import constant from '@/uni_modules/vrapile-im/utils/constant'
import { formatDate } from '@/uni_modules/vrapile-im/utils/nineTool';
import { TioSocket, getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
import { TioSocket, getChatKey } from '@/uni_modules/vrapile-im/utils/tiosocket';
// 外部需提供获取token函数并可以获取token
import { getToken } from '@/utils/token'
const socket = {
state: {
websocket: storage.get(constant.websocket),
websocketData: storage.get(constant.websocketData)
},
mutations: {
// 存储登录链接
SET_SOCKET: (state, socket) => {
state.websocket = socket;
storage.set(constant.websocket, socket)
},
// 添加socket消息
ADD_MESSAGE: (state, message) => {
state.websocketData.push(message)
storage.set(constant.websocketData, state.websocketData)
// 添加消息
for(let i=0;i<store.state.chat.chatList.length;i++){
let item = store.state.chat.chatList[i];
let key = getChatKey(message["sendType"], message["toId"], message["fromId"])
if(store.state.chat.chatList[i]["key"] == key){
store.state.chat.chatList[i]["messageList"].push(message)
store.state.chat.chatList[i]["messageTime"] = formatDate(message["sendTime"]);
store.state.chat.chatList[i]["messageLast"] = message;
store.state.chat.chatList[i]["haveHistory"] = 1;
// 自己发送的消息,总消息数是否加1,如果不加,取消下方注释内容
// if(store.state.user.userInfo.userId && store.state.user.userInfo.userId != message["fromId"]){
store.state.chat.chatList[i]["messageNum"] += 1;
// }
if(store.state.chat.chatList[i]["type"] == 0){
store.state.chat.chatList[i]["messageShow"] = message["content"];
}else{
store.state.chat.chatList[i]["messageShow"] = store.getters.getUserName(message["fromId"], message["fromName"]) + ": " + message["content"]
}
storage.set(constant.chatList, store.state.chat.chatList);
break;
}
}
store.commit('COUNT_MESSAGE');
},
// 回执已读消息
READ_MESSAGE: (state, k) => {
// 删除未读消息
for(let i=0;i<state.websocketData.length;i++){
let key = getChatKey(state.websocketData[i]["sendType"], state.websocketData[i]["toId"], state.websocketData[i]["fromId"])
if(key == k){
state.websocketData.splice(i, 1);
i--;
}
}
storage.set(constant.websocketData, state.websocketData)
// 重置已读消息数量
for(let i=0;i<store.state.chat.chatList.length;i++){
if(store.state.chat.chatList[i].key == k){
store.state.chat.chatList[i].messageNum = 0;
storage.set(constant.chatList, store.state.chat.chatList)
break;
}
}
store.commit('COUNT_MESSAGE');
},
// 统计消息总数
COUNT_MESSAGE: (state) => {
let unReadNum = 0
for(let i=0;i<store.state.chat.chatList.length;i++){
unReadNum += store.state.chat.chatList[i].messageNum*1;
}
try{
if(unReadNum > 0){
uni.setTabBarBadge({
index: getApp().globalData.msgTabBarIndex,
text: String(unReadNum),
fail: (e) => {
// console.log(e)
}
})
}else{
uni.removeTabBarBadge({
index: getApp().globalData.msgTabBarIndex,
fail: (e) => {
// console.log(e)
}
})
}
}catch(e){
}
},
// 清空消息
CLEAN_MESSAGE: (state, message) => {
state.websocketData = new Array();
storage.set(constant.websocketData, new Array())
}
},
state: {
websocket: storage.get(constant.websocket),
websocketData: storage.get(constant.websocketData)
},
mutations: {
// 存储登录链接
SET_SOCKET: (state, socket) => {
state.websocket = socket;
storage.set(constant.websocket, socket)
},
// 添加socket消息
ADD_MESSAGE: (state, message) => {
state.websocketData.push(message)
storage.set(constant.websocketData, state.websocketData)
// 添加消息
for(let i=0;i<store.state.chat.chatList.length;i++){
let item = store.state.chat.chatList[i];
let key = getChatKey(message["sendType"], message["toId"], message["fromId"])
if(store.state.chat.chatList[i]["key"] == key){
store.state.chat.chatList[i]["messageList"].push(message)
store.state.chat.chatList[i]["messageTime"] = formatDate(message["sendTime"]);
store.state.chat.chatList[i]["messageLast"] = message;
store.state.chat.chatList[i]["haveHistory"] = 1;
// 自己发送的消息,总消息数是否加1,如果不加,取消下方注释内容
// if(store.state.user.userInfo.userId && store.state.user.userInfo.userId != message["fromId"]){
store.state.chat.chatList[i]["messageNum"] += 1;
// }
if(store.state.chat.chatList[i]["type"] == 0){
store.state.chat.chatList[i]["messageShow"] = message["content"];
}else{
store.state.chat.chatList[i]["messageShow"] = store.getters.getUserName(message["fromId"], message["fromName"]) + ": " + message["content"]
}
storage.set(constant.chatList, store.state.chat.chatList);
break;
}
}
store.commit('COUNT_MESSAGE');
},
// 回执已读消息
READ_MESSAGE: (state, k) => {
// 删除未读消息
for(let i=0;i<state.websocketData.length;i++){
let key = getChatKey(state.websocketData[i]["sendType"], state.websocketData[i]["toId"], state.websocketData[i]["fromId"])
if(key == k){
state.websocketData.splice(i, 1);
i--;
}
}
storage.set(constant.websocketData, state.websocketData)
// 重置已读消息数量
for(let i=0;i<store.state.chat.chatList.length;i++){
if(store.state.chat.chatList[i].key == k){
store.state.chat.chatList[i].messageNum = 0;
storage.set(constant.chatList, store.state.chat.chatList)
break;
}
}
store.commit('COUNT_MESSAGE');
},
// 统计消息总数
COUNT_MESSAGE: (state) => {
let unReadNum = 0
for(let i=0;i<store.state.chat.chatList.length;i++){
unReadNum += store.state.chat.chatList[i].messageNum*1;
}
try{
if(unReadNum > 0){
uni.setTabBarBadge({
index: getApp().globalData.chatIndex,
text: String(unReadNum),
fail: (e) => {
// console.log(e)
}
})
}else{
uni.removeTabBarBadge({
index: getApp().globalData.chatIndex,
fail: (e) => {
// console.log(e)
}
})
}
}catch(e){
}
},
// 清空消息
CLEAN_MESSAGE: (state, message) => {
state.websocketData = new Array();
storage.set(constant.websocketData, new Array())
}
},
actions: {
// 连接websocket
ConnSocket({ commit, state }, params) {
// 连接websocket
ConnSocket({ commit, state }, params) {
return new Promise((resolve, reject) => {
let url = params.url;
let heartbeatTimeout = 50000; // 心跳超时时间,单位:毫秒
let reconnInterval = 5000; // 重连间隔时间,单位:毫秒
let paramStr = "app=udemo-im&token=" + params.token
let socket = new TioSocket(url, paramStr, heartbeatTimeout, reconnInterval);
socket.connect(false);
})
}
let url = import.meta.env.VITE_APP_SOCKET_URL;
let heartbeatTimeout = 50000; // 心跳超时时间,单位:毫秒
let reconnInterval = 5000; // 重连间隔时间,单位:毫秒
let paramStr = "app="+import.meta.env.VITE_APP_FLAG+"&token=" + getToken();
let socket = new TioSocket(url, paramStr, heartbeatTimeout, reconnInterval);
socket.connect(false);
})
}
}
}

154
uni_modules/vrapile-im/utils/nineTool.js

@ -1,39 +1,39 @@
export function isNull(o) {
if(o === 0 || o === "0"){
return false;
}
if(o == "undefined" || o == null || o == ""){
return true;
}
return false;
if(o === 0 || o === "0"){
return false;
}
if(o == "undefined" || o == null || o == ""){
return true;
}
return false;
}
export function isPhone(o) {
if(/^1[23456789]\d{9}$/.test(o)){
return true;
}
return false;
if(/^1[23456789]\d{9}$/.test(o)){
return true;
}
return false;
}
export function isMail(o) {
if(/^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$/.test(o)){
return true;
}
return false;
if(/^([a-z0-9A-Z]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$/.test(o)){
return true;
}
return false;
}
export function isNumber(value) {
return !isNaN(parseFloat(value)) && isFinite(value)
}
export function isLetter(o) {
if(/^[A-Za-z]+$/.test(o)){
return true;
}
return false;
if(/^[A-Za-z]+$/.test(o)){
return true;
}
return false;
}
export function isNumberOrLetter(o) {
if(/^[A-Za-z0-9]+$/.test(o)){
return true;
}
return false;
if(/^[A-Za-z0-9]+$/.test(o)){
return true;
}
return false;
}
// 日期格式化
@ -83,11 +83,11 @@ export function formatDate(time, option) {
} else {
time = +time
}
if (option) {
return parseTime(time, option)
}
if (option) {
return parseTime(time, option)
}
const d = new Date(time)
const now = Date.now()
@ -117,19 +117,19 @@ export function formatDate(time, option) {
}
if(diff < 3600 * 24 * 365) {
return (
(d.getMonth()*1 + 1) +
(d.getMonth()*1 + 1) +
'月' +
d.getDate() +
'日'
)
} else {
return (
d.getFullYear() +
'年' +
(d.getMonth()*1 + 1) +
'月'
)
}
return (
d.getFullYear() +
'年' +
(d.getMonth()*1 + 1) +
'月'
)
}
}
export function formatTime(time, option) {
@ -138,29 +138,29 @@ export function formatTime(time, option) {
} else {
time = +time
}
if (option) {
if (option) {
return parseTime(time, option)
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
return (
d.getFullYear() +
'-' +
((d.getMonth()*1 + 1) + "").padStart(2,0) +
'-' +
(d.getDate() + '').padStart(2,0) +
' ' +
(d.getHours() + '').padStart(2,0) +
':' +
(d.getMinutes() + '').padStart(2,0) +
':' +
(d.getSeconds() + '').padStart(2,0)
)
return (
d.getFullYear() +
'-' +
((d.getMonth()*1 + 1) + "").padStart(2,0) +
'-' +
(d.getDate() + '').padStart(2,0) +
' ' +
(d.getHours() + '').padStart(2,0) +
':' +
(d.getMinutes() + '').padStart(2,0) +
':' +
(d.getSeconds() + '').padStart(2,0)
)
}
// number:要格式化的数字,
@ -306,24 +306,24 @@ export function GetOs () {
}
export function getRandom(len){
let data = Math.random() + "";
let index = 2;
while(data[index] == 0){
index++;
}
return data.substr(index, len);
let data = Math.random() + "";
let index = 2;
while(data[index] == 0){
index++;
}
return data.substr(index, len);
}
export function getLongRandom(len){
if(len <= 16){
return getRandom(len)
}
let data = Math.random() + "";
let index = 2;
while(data[index] == 0){
index++;
}
return parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}') + "" + data.substr(index, len-16);
if(len <= 16){
return getRandom(len)
}
let data = Math.random() + "";
let index = 2;
while(data[index] == 0){
index++;
}
return parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}') + "" + data.substr(index, len-16);
}
export function moveInArray(array, fromIndex, toIndex) {
@ -332,17 +332,17 @@ export function moveInArray(array, fromIndex, toIndex) {
}
export function jsonCharBigInt(s){
if(typeof s !== 'string'){
return s
}
let re = /([\\]?['|"]{1})(\w+[\\]?['|"]{1}[ |\n|r|\t]*:[ |\n|r|\t]*)([-]?\d{15,})/g
return s.replaceAll(re, "$1$2$1$3$1")
if(typeof s !== 'string'){
return s
}
let re = /([\\]?['|"]{1})(\w+[\\]?['|"]{1}[ |\n|r|\t]*:[ |\n|r|\t]*)([-]?\d{15,})/g
return s.replaceAll(re, "$1$2$1$3$1")
}
export function jsonParse(s){
if(typeof s !== 'string'){
return s
}
let re = /([\\]?['|"]{1})(\w+[\\]?['|"]{1}[ |\n|r|\t]*:[ |\n|r|\t]*)([-]?\d{15,})/g
return JSON.parse(s.replaceAll(re, "$1$2$1$3$1"))
if(typeof s !== 'string'){
return s
}
let re = /([\\]?['|"]{1})(\w+[\\]?['|"]{1}[ |\n|r|\t]*:[ |\n|r|\t]*)([-]?\d{15,})/g
return JSON.parse(s.replaceAll(re, "$1$2$1$3$1"))
}

2
uni_modules/vrapile-im/utils/storage.js

@ -5,7 +5,7 @@ let storageKey = 'vrapile_im_socket_storage_data'
// 存储节点变量名
let storageNodeKeys = [constant.chatList, constant.friendList, constant.groupList,
constant.userObject, constant.groupObject, constant.websocket, constant.websocketData]
constant.userObject, constant.groupObject, constant.websocket, constant.websocketData]
const storage = {
set: function(key, value) {

134
uni_modules/vrapile-im/utils/tiosocket.js

@ -31,58 +31,58 @@ export class TioSocket {
this.ws = null;
this.connect = function(isReconnect) {
// 这里连接的时候,先关闭,避免出现多个连接
uni.closeSocket({
success:() => {
this.ws = uni.connectSocket({
url: this.firstUrl,
success(res) {
console.log("WebSocket成功关闭,连接成功")
},
fail(err) {
console.log("WebSocket成功关闭,连接失败:" + err)
}
});
},
fail:() => {
this.ws = uni.connectSocket({
url: this.firstUrl,
success(res) {
console.log("WebSocket关闭失败,连接成功")
},
fail(err) {
console.log("WebSocket关闭失败,连接失败:" + err)
}
});
}
})
// 这里连接的时候,先关闭,避免出现多个连接
uni.closeSocket({
success:() => {
this.ws = uni.connectSocket({
url: this.firstUrl,
success(res) {
console.log("WebSocket成功关闭,连接成功")
},
fail(err) {
console.log("WebSocket成功关闭,连接失败:" + err)
}
});
},
fail:() => {
this.ws = uni.connectSocket({
url: this.firstUrl,
success(res) {
console.log("WebSocket关闭失败,连接成功")
},
fail(err) {
console.log("WebSocket关闭失败,连接失败:" + err)
}
});
}
})
this.ws.onOpen((e) => {
if(!isReconnect){
uni.sendSocketMessage({
data: JSON.stringify({code:1})
})
store.commit('CLEAN_MESSAGE', {})
}
if(!isReconnect){
uni.sendSocketMessage({
data: JSON.stringify({code:1})
})
store.commit('CLEAN_MESSAGE', {})
}
this.reset();
})
store.commit('SET_SOCKET', this)
this.ws.onMessage((e) => {
let data = JSON.parse(e.data);
if(data.code == 2){
store.commit('ADD_MESSAGE', data.message)
}
this.reset();
})
store.commit('SET_SOCKET', this)
this.ws.onMessage((e) => {
let data = JSON.parse(e.data);
if(data.code == 2){
store.commit('ADD_MESSAGE', data.message)
}
this.reset();
})
this.ws.onClose((e) => {
console.error("WebSocket关闭了:" + JSON.stringify(e))
console.error("WebSocket关闭了:" + JSON.stringify(e))
this.clearAllTimeoutTask();
})
this.ws.onError((e) => {
console.error("WebSocket错误了:" + JSON.stringify(e))
console.error("WebSocket错误了:" + JSON.stringify(e))
this.clearAllTimeoutTask();
if(!this.closeByUser){
this.reconn();
@ -99,31 +99,31 @@ export class TioSocket {
if (this.lockReconnect) { return;}
this.lockReconnect = true;
this.reconnIntervalTask = setTimeout(() => {
this.ws = this.connect(true)
this.lockReconnect = false;
this.ws = this.connect(true)
this.lockReconnect = false;
}, this.reconnInterval)
}
this.ping = () => {
uni.sendSocketMessage({
data: JSON.stringify({code:0})
})
uni.sendSocketMessage({
data: JSON.stringify({code:0})
})
};
this.send = (data) => {
uni.sendSocketMessage({
data: data
})
uni.sendSocketMessage({
data: data
})
};
this.close = (bool) => {
this.lockReconnect = false;
this.closeByUser = bool;
uni.closeSocket({
success:() => {
console.info("WebSocket关闭成功")
}
})
uni.closeSocket({
success:() => {
console.info("WebSocket关闭成功")
}
})
};
this.reset = () => {
@ -168,14 +168,14 @@ export class TioSocket {
*
*/
export function getChatKey(type, chatId, fromId) {
// 私聊
if(type == 0){
if(chatId*1 < fromId*1){
return "im:message:friend-" + chatId + "-" + fromId
}else{
return "im:message:friend-" + fromId + "-" + chatId
}
}else{
return "im:message:group-" + chatId
}
// 私聊
if(type == 0){
if(chatId*1 < fromId*1){
return "im:message:friend-" + chatId + "-" + fromId
}else{
return "im:message:friend-" + fromId + "-" + chatId
}
}else{
return "im:message:group-" + chatId
}
}

1
utils/request.js

@ -18,6 +18,7 @@ const request = config => {
config.header['Authorization'] = 'Vrapile ' + getToken()
}
config.header["Content-Language"] = "zh_CN";
config.header["platform"] = getApp().globalData.appId;
config.header["terminal"] = getApp().globalData.terminal;
config.header["nodeId"] = getNodeId();

Loading…
Cancel
Save