【新增】 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

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
}