【新增】 IM基础模块

This commit is contained in:
2022-01-18 13:56:23 +08:00
parent 61d389bef4
commit 7c6916b4ae
14 changed files with 1499 additions and 930 deletions

136
App.vue
View File

@@ -1,68 +1,74 @@
<script>
<script> import {
import { getVersions } from './apis/interfaces/versions' getVersions
import im from '@/public/im' } from './apis/interfaces/versions'
export default { import im from '@/utils/im/index.js'
onLaunch: function() {
//#ifdef APP-PLUS export default {
// 获取系统版本号 onLaunch: function() {
getVersions({ im.initIm('lmxuhwaglu76d')
platform: plus.os.name,
version : plus.runtime.versionCode //#ifdef APP-PLUS
}).then(res => { // 获取系统版本号
if(res.update){ getVersions({
uni.showModal({ platform: plus.os.name,
title: "更新提示", version: plus.runtime.versionCode
content: res.note || '版本更新信息', }).then(res => {
confirmText: "更新", if (res.update) {
success: modalRes => { uni.showModal({
if (modalRes.confirm) { title: "更新提示",
if (plus.os.name == "Android") { content: res.note || '版本更新信息',
uni.showToast({ confirmText: "更新",
title: '新版本下载中,将在下载完成后自动为您安装更新包', success: modalRes => {
icon : 'none' if (modalRes.confirm) {
}) if (plus.os.name == "Android") {
uni.downloadFile({ uni.showToast({
url : res.info.download, title: '新版本下载中,将在下载完成后自动为您安装更新包',
success : apkPick=> { icon: 'none'
plus.runtime.install(apkPick.tempFilePath, '', installRES => { })
// 安装完成用于提示新版本引导,暂时无用 uni.downloadFile({
}, installERR => { url: res.info.download,
// 安装失败 success: apkPick => {
}) plus.runtime.install(apkPick
}, .tempFilePath, '',
fail(err){ installRES => {
uni.showToast({ // 安装完成用于提示新版本引导,暂时无用
title: '安装包下载失败,请检查您的网络或稍后重试', }, installERR => {
icon : 'none' // 安装失败
}) })
} },
}) fail(err) {
// plus.runtime.openURL(res.info.download, err => { uni.showToast({
// console.log(err) title: '安装包下载失败,请检查您的网络或稍后重试',
// }, 'com.android.browser'); icon: 'none'
} else{ })
uni.showToast({ }
title: 'IOS应用暂未上架请打开测试(TestFlight)工具点击更新', })
icon : 'none' // plus.runtime.openURL(res.info.download, err => {
}) // console.log(err)
} // }, 'com.android.browser');
} } else {
} uni.showToast({
}) title: 'IOS应用暂未上架请打开测试(TestFlight)工具点击更新',
} icon: 'none'
}).catch(err => { })
uni.showToast({ }
title: err.message, }
icon : 'none' }
}) })
}) }
//#endif }).catch(err => {
} uni.showToast({
} title: err.message,
icon: 'none'
})
})
//#endif
}
}
</script> </script>
<style lang="scss"> <style lang="scss">
@import "uview-ui/index.scss"; @import "uview-ui/index.scss";
@import "@/static/iconfont.css"; @import "@/static/iconfont.css";
</style> </style>

20
apis/interfaces/im.js Normal file
View File

@@ -0,0 +1,20 @@
import {
request
} from '../index'
const getFriends = () => {
return request({
url: 'im/friends',
})
}
const getUserInfo = async (targetId) => {
const [err, res] = await request({
url: 'im/userInfo/' + targetId,
})
return res
}
export {
getFriends
}

65
main.js
View File

@@ -1,34 +1,33 @@
/* /*
* @Description: * @Description:
* @Author: Aimee·Zhang * @Author: Aimee·Zhang
* @Date: 2022-01-05 09:01:12 * @Date: 2022-01-05 09:01:12
* @LastEditors: Aimee·Zhang * @LastEditors: Aimee·Zhang
* @LastEditTime: 2022-01-12 16:35:13 * @LastEditTime: 2022-01-12 16:35:13
*/ */
import App from './App' import App from './App'
import Vue from 'vue'
// #ifndef VUE3 import store from './store'
import Vue from 'vue' import uView from 'uview-ui'
import store from './store' import filters from './utils/filters.js'
import uView from 'uview-ui'; import {
import { router, RouterMount } from 'router' router,
Vue.use(uView); RouterMount
Vue.use(router) } from 'router'
Vue.config.productionTip = false
Vue.prototype.$store = store Object.keys(filters).forEach(key => {
App.mpType = 'app' Vue.filter(key, filters[key])
const app = new Vue({ })
...App
}) Vue.use(uView);
Vue.use(router)
Vue.config.productionTip = false
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount() app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif

View File

@@ -20,7 +20,8 @@
"modules" : { "modules" : {
"OAuth" : {}, "OAuth" : {},
"Payment" : {}, "Payment" : {},
"Share" : {} "Share" : {},
"SQLite" : {}
}, },
/* */ /* */
"distribute" : { "distribute" : {
@@ -29,6 +30,7 @@
"permissions" : [ "permissions" : [
"<uses-feature android:name=\"android.hardware.camera\"/>", "<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>", "<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>", "<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>", "<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>", "<uses-permission android:name=\"android.permission.CAMERA\"/>",
@@ -36,12 +38,15 @@
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>", "<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>", "<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>", "<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>",
"<uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\"/>", "<uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>", "<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>", "<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>", "<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.USE_FINGERPRINT\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>", "<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>", "<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>" "<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
], ],
"autoSdkPermissions" : true "autoSdkPermissions" : true
@@ -63,8 +68,14 @@
"__platform__" : [ "android" ] "__platform__" : [ "android" ]
} }
}, },
"share" : {}, "share" : {
"ad" : {} "weixin" : {
"appid" : "wxb7e3c263a2a37ab9",
"UniversalLinks" : ""
}
},
"ad" : {},
"push" : {}
}, },
"icons" : { "icons" : {
"android" : { "android" : {

View File

@@ -1,26 +1,26 @@
{ {
"name": "zhhealth", "name": "zhhealth",
"version": "1.0.0", "version": "1.0.0",
"description": "ZH健康", "description": "ZH健康",
"main": "main.js", "main": "main.js",
"dependencies": { "dependencies": {
"@rongcloud/imlib-uni": "^5.1.3-release.3", "@rongcloud/imlib-uni": "^5.1.3-release.3",
"bitcore-lib": "^8.25.25", "bitcore-lib": "^8.25.25",
"bitcore-mnemonic": "^8.25.25", "bitcore-mnemonic": "^8.25.25",
"moment": "^2.29.1", "moment": "^2.29.1",
"uni-read-pages": "^1.0.5", "uni-read-pages": "^1.0.5",
"uni-simple-router": "^2.0.7", "uni-simple-router": "^2.0.7",
"uview-ui": "^2.0.19", "uview-ui": "^2.0.19",
"vuex": "^3.6.2" "vuex": "^3.6.2"
}, },
"devDependencies": {}, "devDependencies": {},
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.yuzhankeji.cn/TmOct5/ZhHealth.git" "url": "https://git.yuzhankeji.cn/TmOct5/ZhHealth.git"
}, },
"author": "唐明明", "author": "唐明明",
"license": "ISC" "license": "ISC"
} }

1094
pages.json

File diff suppressed because it is too large Load Diff

276
pages/im/detail.vue Normal file
View File

@@ -0,0 +1,276 @@
<template>
<div>
<scroll-view ref="scrollview" :scroll-y="true" class="scroll" :scroll-into-view="scrollIntoID"
:scroll-with-animation="false">
<view v-for="(item,index) in messages" :id="'chatId_'+index">
<div :class="item.messageDirection == 1 ? 'right' : 'left'">
<div class="avatar" v-if="item.messageDirection == 2">
<u-avatar :src="userInfo.portraitUrl" @click="showFriend" shape="square" />
</div>
<div class="msg">
{{ item.content.content }}
<div class="status" v-if="item.messageDirection == 1">
<u-icon v-if="item.sentStatus == 50" name="checkbox-mark" />
<span v-else>未读</span>
</div>
</div>
<div class="avatar" v-if="item.messageDirection == 1">
<u-avatar text="Me" @click="showMine" shape="square" />
</div>
</div>
<div class="time">{{ item.sentTime|timeCustomCN }}</div>
</view>
</scroll-view>
<div class="footer">
<div class="left">
<u-icon name="volume" />
</div>
<div class="middle">
<u--input autoBlur confirmHold confirmType="send" @confirm="send" v-model="inputTxt" />
</div>
<div class="right">
<u-button type="primary" v-if="showSendButton" class="custom-style" text="发送" @click="send"></u-button>
<u-icon v-else name="plus" />
</div>
</div>
</div>
</template>
<script>
import * as RongIMLib from '@rongcloud/imlib-uni'
import im from '@/utils/im/index.js'
export default {
data() {
return {
targetId: '',
scrollIntoID: 'chatID_0',
inputTxt: '',
messages: [],
conversationType: 1,
totalCount: 0,
userInfo: {
name: '',
userId: '',
portraitUrl: ''
}
}
},
onLoad(e) {
this.targetId = e.targetId
this.conversationType = e.conversationType // 会话类型
// 消息总数量
RongIMLib.getMessageCount(this.conversationType, this.targetId, ({
code,
count
}) => {
if (code == 0) {
this.totalCount = count
}
})
this.userInfo = this.$store.getters.userInfo(this.targetId)
uni.setNavigationBarTitle({
title: this.$store.getters.userInfo(this.targetId).name
})
RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime())
im.setNotifyBadge()
RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())
this.getMessageList()
// 监听消息回执
RongIMLib.addReadReceiptReceivedListener((result) => {
const res = result.data.message
if (res.targetId == this.targetId) {
this.getMessageList()
}
})
},
onUnload() {
RongIMLib.clearReadReceiptReceivedListener()
},
computed: {
showSendButton() {
return this.inputTxt.length > 0
}
},
watch: {
'$store.getters.newMessage': function(msg) {
if (msg.targetId == this.targetId) {
RongIMLib.clearMessagesUnreadStatus(msg.conversationType, msg.targetId, msg.sentTime)
RongIMLib.sendReadReceiptMessage(msg.conversationType, msg.targetId, msg.sentTime)
this.getMessageList()
im.setNotifyBadge()
}
}
},
methods: {
getMessageList() {
// 获取消息列表
const objectNames = [
'RC:TxtMsg',
'RC:VcMsg',
'RC:HQVCMsg',
'RC:ImgMsg',
'RC:GIFMsg',
'RC:ImgTextMsg',
'RC:FileMsg',
'RC:LBSMsg',
'RC:SightMsg',
'RC:ReferenceMsg',
'RC:CombineMsg'
]
const timeStamp = new Date().getTime()
const count = 20 // 获取的消息数量
const isForward = true // 是否向前获取
RongIMLib.getHistoryMessagesByTimestamp(this.conversationType, this.targetId, objectNames, timeStamp,
count,
isForward,
({
code,
messages
}) => {
if (code === 0) {
this.messages = messages.reverse()
this.scrollBottom()
}
}
)
},
send() {
im.sendMsg(this.conversationType, this.targetId, this.inputTxt, () => {
this.getMessageList()
this.inputTxt = ''
})
},
showFriend() {
uni.navigateTo({
url: '/pages/im/friends/info?targetId=' + this.targetId
})
},
showMine() {
uni.navigateTo({
url: '/pages/im/friends/mine'
})
},
scrollBottom() {
this.$nextTick(function() {
setTimeout(() => {
let len = this.messages.length
if (len) {
if (this.scrollIntoID == "chatId_" + (len - 1)) {
this.scrollIntoID = "chatId_" + (len - 2)
this.scrollBottom()
} else if (this.scrollIntoID == "chatId_" + (len - 2)) {
this.scrollIntoID = "chatId_" + (len - 1)
} else {
this.scrollIntoID = "chatId_" + (len - 1)
}
} else {
this.scrollIntoID = "chatId_0";
}
}, 50)
})
}
}
}
</script>
<style lang="scss" scoped>
$footer-height: 55px;
.scroll {
height: calc(100vh - 55px);
padding: 0 $uni-spacing-col-lg;
}
.footer {
width: 100%;
display: flex;
position: fixed;
bottom: 0;
left: 0;
align-items: center;
height: $footer-height;
background-color: $uni-bg-color-grey;
.u-icon {
padding: $uni-spacing-col-sm;
border: 1px solid $u-content-color;
border-radius: $uni-border-radius-circle;
}
.left {
padding: 0 $uni-spacing-col-lg;
justify-content: center;
}
.middle {
flex: 1;
.u-input {
background-color: $uni-bg-color;
}
}
.right {
padding: 0 $uni-spacing-col-lg;
justify-content: center;
}
}
.custom-style {
height: 36px;
}
.time {
text-align: center;
font-size: $uni-font-size-sm;
color: $u-light-color;
}
.left,
.right {
display: flex;
align-items: top;
.avatar {
margin-top: $uni-spacing-col-base;
}
.msg {
font-size: $uni-font-size-lg;
margin: $uni-spacing-col-base;
padding: $uni-spacing-col-base + 5rpx;
word-wrap: break-word;
width: 70%;
border-radius: $uni-border-radius-base;
position: relative;
.status {
position: absolute;
right: 8rpx;
bottom: 5rpx;
font-size: $uni-font-size-base / 1.5;
color: $uni-text-color-grey;
}
}
}
.left {
.msg {
background-color: $uni-bg-color-grey;
}
}
.right {
justify-content: flex-end;
.msg {
background-color: $u-primary-disabled;
}
}
</style>

View File

@@ -1,188 +1,131 @@
<template> <template>
<view class="content"> <div>
<block v-if="messageArr.length < 1"> <u-popup overlay mode="left" closeable closeOnClickOverlay :show="showLeft" @close="showLeft = false">
<view class="vertical null-list"> <leftMenu></leftMenu>
<u-empty </u-popup>
icon="http://cdn.uviewui.com/uview/empty/message.png"
textColor="#999" <div class="container">
text="暂无好友消息" <div class="msg-item u-border-bottom" v-for="(item, index) in conversations" @click="toDetail(item)">
> <div class="avatar">
<template> <u-badge numberType="ellipsis" max="99" shape="horn" absolute :offset="[-7, -7]"
<view class="null-list-btn" @click="openChum">开启聊天</view> :value="item.unreadMessageCount" />
</template> <u-avatar shape="square" :src="friend(item.targetId).portraitUrl"></u-avatar>
</u-empty> </div>
</view> <div class="content ">
</block> <div class="name">
<block v-else> <h3>{{ friend(item.targetId).name }}</h3>
<view v-for="(item, index) in messageArr" :key="index" class="mssage-box"> <span class="time">{{ item.sentTime|timeCustomCN }}</span>
<view class="mssage-action" @click="openChum"> </div>
<block v-if="item.cover === ''"> <div class="u-line-1">{{ item.latestMessage.content }}</div>
<u-avatar </div>
clsss="mssage-action-cover" </div>
size="44" </div>
:text="item.text" <u-loadmore status="nomore" />
font-size="14" </div>
randomBgColor </template>
></u-avatar>
</block> <script>
<block v-else> import * as RongIMLib from '@rongcloud/imlib-uni'
<u-avatar import im from '@/utils/im/index.js'
clsss="mssage-action-cover" import leftMenu from './components/left_menu.vue'
:src="item.cover"
size="44" export default {
></u-avatar> components: {
</block> leftMenu
<view class="mssage-action-content"> },
<view class="mssage-header"> data() {
<view class="header-name">{{item.name}}</view> return {
<view class="header-time">{{item.time}}</view> isShown: true, // 当前页面显示状态
</view> conversations: [], // 会话列表
<view class="mssage-msg">{{item.message}}</view> showLeft: false
</view> }
</view> },
</view> computed: {
</block> friend() {
</view> return function(targetId) {
</template> return this.$store.getters.userInfo(targetId)
}
<script> }
// import { init, connect } from '@rongcloud/imlib-uni' },
export default { onLoad() {},
data() { onShow() {
return { this.getConversationList()
messageArr : [ this.isShown = true
{ },
cover: 'https://cdn.uviewui.com/uview/album/1.jpg', onHide() {
name: '班班五月', this.isShown = false
message: '咱们进直播间了吗?上课啦~今天教大家【拆解项目背后的逻辑】', },
time: '昨天' onNavigationBarButtonTap(e) {
}, if (e.index == 0) {
{ this.showLeft = true
cover: 'https://cdn.uviewui.com/uview/album/4.jpg', }
name: '周磊', },
message: '[语音]', watch: {
time: '周一' '$store.getters.newMessage': function(n, o) {
}, if (this.isShown) {
{ this.getConversationList()
cover: '', }
text: 'S', }
name: 'SKY', },
message: '谢谢', methods: {
time: '2022/1/5' getFriend(targetId) {
}, return this.$store.getters.userInfo(targetId)
{ },
cover: 'https://cdn.uviewui.com/uview/album/5.jpg', getConversationList() {
name: '俊少', const count = 1000
message: '[语音]', const timestamp = 0 // 会话的时间戳获取这个时间戳之前的会话列表0 表示从最新开始获取)会话类型
time: '2022/1/4' RongIMLib.getConversationList(undefined, count, timestamp, (res) => {
}, if (res.code === 0 && res.conversations.length > 0) {
], this.conversations = res.conversations
optionsAction: [ }
{ })
text: '删除', },
style: { // 进入聊天的详情页面,清理未读消息数量
backgroundColor: '#e6576b' toDetail(item) {
} uni.navigateTo({
} url: '/pages/im/detail?targetId=' + item.targetId +
] '&conversationType=' + item.conversationType
}; })
}, }
methods:{ }
openChum(){ }
uni.showToast({ </script>
title: '聊聊系统正在开发中,敬请期待',
icon : 'none' <style scoped lang="scss">
}) .container {
} padding: 0 $uni-spacing-col-lg $uni-spacing-col-lg $uni-spacing-col-lg;
}, }
onNavigationBarButtonTap(e) {
.msg-item {
switch (e.index){ display: flex;
case 1: align-items: center;
uni.showToast({ padding: $uni-spacing-col-lg 0;
title: '聊聊好友系统正在开发中,敬请期待',
icon : 'none' .avatar {
}) position: relative;
break; margin-right: $uni-spacing-col-lg;
case 0:
uni.showToast({ .u-badge {
title: '聊聊扫一扫系统正在开发中,敬请期待', z-index: 9;
icon : 'none' }
}) }
break;
} .content {
} flex: 1;
}
</script> .name {
display: flex;
<style lang="scss" scoped> justify-content: space-between;
.content{
background-color: $window-color; .time {
min-height: 100vh; font-size: $uni-font-size-sm;
.null-list{ color: $uni-text-color-grey;
height: 100vh; }
text-align: center; }
&-btn{
margin-top: $margin * 2; .u-line-1 {
line-height: 70rpx; color: $u-info;
color: $main-color; }
border:solid 1rpx $main-color; }
padding: 0 ($padding*3); }
font-size: $title-size-m;
border-radius: 35rpx;
box-sizing: border-box;
}
}
.mssage-box{
background: white;
.mssage-action{
position: relative;
padding: 20rpx $padding;
&::after{
position: absolute;
left: $padding + 108;
right: 0;
bottom: 0;
content: " ";
height: 1rpx;
background: $border-color;
}
&-content{
position: absolute;
top: 20rpx;
height: 44px;
left: $padding + 108;
right: $margin;
display: flex;
flex-direction: column;
justify-content: center;
.mssage-header{
display: flex;
font-size: $title-size;
line-height: 40rpx;
justify-content: space-between;
.header-name{
flex: 1;
@extend .nowrap;
}
.header-time{
padding-left: $padding;
font-size: $title-size-sm - 2;
color: $text-gray;
}
}
.mssage-msg{
font-size: $title-size-sm - 2;
color: $text-gray;
@extend .nowrap;
}
}
}
&-item:last-child{
.mssage-action::after{
display: none;
}
}
}
}
</style> </style>

View File

@@ -1,37 +0,0 @@
/**
* Web唐明明
* 匆匆数载恍如梦,岁月迢迢华发增。
* 碌碌无为枉半生,一朝惊醒万事空。
* moduleName: 融云im
*/
import {
init,
connect,
addConnectionStatusListener,
addReceiveMessageListener
} from '@rongcloud/imlib-uni'
export default {
// 初始化
imInit(){
init('lmxuhwaglu76d')
connect('token', res => {
console.log(res)
})
this.imMonitor()
},
// 监听器
imMonitor(){
// 添加连接状态监听函数
addConnectionStatusListener(res => {
console.log(res.data)
})
// 添加消息监听函数
addReceiveMessageListener(res => {
console.log(res)
})
}
}

View File

@@ -1,42 +1,45 @@
/**
/** * Web唐明明
* Web唐明明 * 匆匆数载恍如梦,岁月迢迢华发增。
* 匆匆数载恍如梦,岁月迢迢华发增 * 碌碌无为枉半生,一朝惊醒万事空
* 碌碌无为枉半生,一朝惊醒万事空。 */
*/
import Vue from 'vue'
import Vue from 'vue' import Vuex from 'vuex'
import Vuex from 'vuex' import im from './modules/im.js'
Vue.use(Vuex) Vue.use(Vuex)
export default new Vuex.Store({ export default new Vuex.Store({
state: { state: {
token : uni.getStorageSync('token') || '', token: uni.getStorageSync('token') || '',
address : {}, address: {},
refresh : 0 refresh: 0
}, },
getters: { getters: {
getToken: state => { getToken: state => {
return state.token return state.token
}, },
getAddress: state => { getAddress: state => {
return state.address return state.address
}, },
getRefresh: state => { getRefresh: state => {
return state.refresh return state.refresh
} }
}, },
mutations: { mutations: {
setToken(state, tokenString) { setToken(state, tokenString) {
state.token = tokenString state.token = tokenString
uni.setStorageSync('token', tokenString) uni.setStorageSync('token', tokenString)
}, },
setAddress(state, value) { setAddress(state, value) {
state.address = value state.address = value
}, },
setRefresh(state, value) { setRefresh(state, value) {
state.refresh = value state.refresh = value
} }
} },
modules: {
im
}
}) })

57
store/modules/im.js Normal file
View File

@@ -0,0 +1,57 @@
import {
getUserInfo
} from "@/apis/interfaces/im.js"
export default {
state: {
newMsg: {},
friends: [],
sender: {}
},
getters: {
newMessage(state) {
return state.newMsg
},
friends(state) {
return state.friends
},
userInfo: (state) => (targetId) => {
if (state.friends.filter((item) => item.userId == targetId)[0]) {
return state.friends.filter((item) => String(item.userId) == targetId)[0]
} else {
return getUserInfo()
}
},
sender(state) {
return state.sender
}
},
mutations: {
newMessage(state, msg) {
Vue.set(state, 'newMsg', msg)
},
updateFriends(state, list) {
state.friends = list
},
SET_state_sender(state, userInfo) {
state.sender = userInfo
}
},
actions: {
newMessage({
commit
}, msg) {
commit('newMessage', msg)
},
updateFriends({
commit
}, list) {
commit('updateFriends', list)
},
setSenderInfo({
commit
}, userInfo) {
commit('SET_state_sender', userInfo)
}
}
}

89
utils/filters.js Normal file
View File

@@ -0,0 +1,89 @@
import store from '@/store/index.js'
/*
* 截断hash
*/
const filterHash = (str, num) => {
let length = num || 16
return String(str).substr(0, length) + '...' + String(str).substr(-4)
}
const timeCustomCN = (val) => {
val = timeStamp(val, 'Y-m-d H:i:s')
let currentDate = new Date();
let currentD = currentDate.getDate();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth() + 1;
let date = val.substring(0, 19);
date = date.replace(/-/g, '/');
let valDate = new Date(date);
let valD = valDate.getDate();
let valYear = valDate.getFullYear();
let valMonth = valDate.getMonth() + 1;
// 判断是否属于今天,计算时分
let difftime = (currentDate - valDate) / 1000;
if (currentYear === valYear && currentMonth === valMonth && currentD === valD) {
let minute = parseInt(difftime % 3600 / 60);
if (minute <= 60) {
return minute === 0 ? '刚刚' : minute + '分钟前';
} else {
return (minute * 60).toFixed(0) + '小时前';
}
} else {
// 计算天
if (currentYear === valYear && currentMonth === valMonth && currentD - 1 === valD) {
return '昨天';
} else {
let days = Math.abs(currentDate.getTime() - valDate.getTime()) / (1000 * 60 * 60 * 24);
return Math.ceil(days) + '天前';
}
}
}
const timeStamp = (timestamp, formats) => {
/*
** 时间戳转换成指定格式日期
** eg.
** dateFormat(11111111111111, 'Y年m月d日 H时i分')
** → "2322年02月06日 03时45分"
*/
// formats格式包括
// 1. Y-m-d
// 2. Y-m-d H:i:s
// 3. Y年m月d日
// 4. Y年m月d日 H时i分
formats = formats || 'Y-m-d';
var zero = function(value) {
if (value < 10) {
return '0' + value;
}
return value;
};
var myDate = timestamp ? new Date(timestamp) : new Date();
var year = myDate.getFullYear();
var month = zero(myDate.getMonth() + 1);
var day = zero(myDate.getDate());
var hour = zero(myDate.getHours());
var minite = zero(myDate.getMinutes());
var second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
}
export default {
filterHash,
timeCustomCN
}

44
utils/im/api.js Normal file
View File

@@ -0,0 +1,44 @@
const api_url = 'http://api.zh.shangkelian.cn/api/im'
/**
* 获取币种余额
*/
export const getToken = (uid) => {
return new Promise((resolve, reject) => {
uni.request({
method: 'GET',
url: api_url + '/token/' + uid,
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data.data)
} else {
reject(res.message)
}
}
})
})
}
/**
* 获取好友列表
*/
export const getFriends = () => {
return new Promise((resolve, reject) => {
uni.request({
method: 'GET',
url: api_url + '/friends',
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data.data)
} else {
reject(res.message)
}
}
})
})
}
export default {
getToken,
getFriends
}

142
utils/im/index.js Normal file
View File

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