更改发送消息模式为promise

This commit is contained in:
2022-02-28 13:45:17 +08:00
parent bf94cca533
commit 39b8f158c0
9 changed files with 647 additions and 466 deletions

View File

@@ -0,0 +1,183 @@
<template xlang="wxml" minapp="mpvue">
<view>
</view>
</template>
<script>
export default {
name: 'tki-file-manager',
props: {},
data() {
return {
}
},
methods: {
_openFile() {
// #ifdef APP-PLUS
if (plus.os.name.toLowerCase() != "android") {
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {}
});
return false
}
let that = this
// java 代码来自 http://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
let main = plus.android.runtimeMainActivity();
let Intent = plus.android.importClass("android.content.Intent");
//
let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
//fileIntent.setType(“image/*”);//选择图片
//fileIntent.setType(“audio/*”); //选择音频
//fileIntent.setType(“video/*”); //选择视频 mp4 3gp 是android支持的视频格式
//fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
fileIntent.setType("*/*"); //无类型限制
fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
main.startActivityForResult(fileIntent, 1);
// 获取回调
main.onActivityResult = function (requestCode, resultCode, data) {
let Activity = plus.android.importClass("android.app.Activity");
let ContentUris = plus.android.importClass("android.content.ContentUris");
let Cursor = plus.android.importClass("android.database.Cursor");
let Uri = plus.android.importClass("android.net.Uri");
let Build = plus.android.importClass("android.os.Build");
let Environment = plus.android.importClass("android.os.Environment");
let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
let MediaStore = plus.android.importClass("android.provider.MediaStore");
// 给系统导入 contentResolver
let contentResolver = main.getContentResolver()
plus.android.importClass(contentResolver);
// 返回路径
let path = '';
if (resultCode == Activity.RESULT_OK) {
let uri = data.getData()
if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
path = uri.getPath();
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
path = getPath(this, uri);
} else { //4.4以下下系统调用方法
path = getRealPathFromURI(uri)
}
// 回调
that.$emit('result', path)
}
// 4.4 以上 从Uri 获取文件绝对路径
function getPath(context, uri) {
let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
let scheme = uri.getScheme().toLowerCase()
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
let docId = DocumentsContract.getDocumentId(uri);
let split = docId.split(":");
let type = split[0];
// 如果是手机内部存储
if ("primary" == type.toLowerCase()) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return '/storage/' + type + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
let id = DocumentsContract.getDocumentId(uri);
let split = id.split(":");
return split[1]
// console.log(id)
// let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
// return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
let docId = DocumentsContract.getDocumentId(uri);
let split = docId.split(":");
let type = split[0];
let contentUri = null;
if ("image" == type.toLowerCase()) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video" == type.toLowerCase()) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio" == type.toLowerCase()) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
let selection = "_id=?";
let selectionArgs = [split[1]];
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content" == scheme) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file" == scheme) {
return uri.getPath();
}
}
// 4.4 以下 获取 绝对路径
function getRealPathFromURI(uri) {
let res = null
let proj = [MediaStore.Images.Media.DATA]
let cursor = contentResolver.query(uri, proj, null, null, null);
if (null != cursor && cursor.moveToFirst()) { ;
let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
cursor.close();
}
return res;
}
// 通过uri 查找出绝对路径
function getDataColumn(context, uri, selection, selectionArgs) {
let cursor = null;
let column = "_data";
let projection = [column];
// let contentResolver = context.getContentResolver()
// plus.android.importClass(contentResolver);
cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
let column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}
function isExternalStorageDocument(uri) {
return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
}
function isDownloadsDocument(uri) {
return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
}
function isMediaDocument(uri) {
return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
}
}
// #endif
// #ifndef APP-PLUS
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {
}
});
// #endif
},
},
onLoad() {
// plus.io.resolveLocalFileSystemURL( '/storage/emulated/0', function(fs) {
// var directoryReader = fs.createReader();
// directoryReader.readEntries(function(entries) {
// var i;
// for (i = 0; i < entries.length; i++) {
// console.log(entries[i].name);
// }
// }, function(e) {
// console.log("Read entries failed: " + e.message);
// });
// }, function(e) {
// console.log("Request file system failed: " + e.message);
// });
}
}
</script>

22
main.js
View File

@@ -31,21 +31,21 @@ Vue.use(router)
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.prototype.$store = store Vue.prototype.$store = store
usqlite.connect({ uni.$sql = usqlite.connect({
name: 'zh-health', // 数据库名称 name: 'zh-health', // 数据库名称
path: '_doc/health.db', // 路径 path: '_doc/health.db', // 路径
}, (err, res) => { }, (err, res) => {
uni.getStorage({ uni.getStorage({
key: 'FIRST_RUN', key: 'FIRST_RUN',
fail: () => { fail: () => {
contactModel.create((err, res) => { contactModel.create((err, res) => {
console.error('SQLITE 创建表格', err, res) console.error('SQLITE 创建表格', err, res)
uni.setStorageSync('FIRST_RUN', true) uni.setStorageSync('FIRST_RUN', true)
}) })
} }
}) })
}) })
App.mpType = 'app' App.mpType = 'app'
const app = new Vue({ const app = new Vue({
store, store,

View File

@@ -1,79 +1,87 @@
<template> <template>
<view class="emoji--lay" v-show="show"> <view class="emoji--lay" v-show="show">
<scroll-view class="scroll" :scroll-y="true"> <scroll-view class="scroll" :scroll-y="true">
<view class="emoji-flex"> <view class="emoji-flex">
<view class="item" v-for="(item, index) in emojiArr" :key="index" @click="$emit('onEmoji', item)">{{item.emoji}}</view> <view class="item" v-for="(item, index) in emojiArr" :key="index" @click="$emit('onEmoji', item)">
</view> {{item.emoji}}
</scroll-view> </view>
<view class="tool"> </view>
<!-- <view class="item" @click="$emit('delete')">删除</view> --> </scroll-view>
<view class="item sent" @click="$emit('sent')">发送</view> <view class="tool">
</view> <!-- <view class="item" @click="$emit('delete')">删除</view> -->
</view> <view class="item sent" @click="$emit('sent')">发送</view>
</template> </view>
</view>
<script> </template>
import emoji from '@/static/im/emoji'
export default{ <script>
props:{ import emoji from '@/static/im/emoji'
show: { export default {
type: Boolean, props: {
default: () => { show: {
return false type: Boolean,
} default: () => {
} return false
}, }
data(){ }
return { },
emojiArr: emoji data() {
} return {
} emojiArr: emoji
} }
</script> }
}
<style lang="scss" scoped> </script>
.emoji--lay{
height: 600rpx; <style lang="scss" scoped>
position: relative; .emoji--lay {
.scroll{ height: 600rpx;
height: 600rpx; position: relative;
.emoji-flex{
padding: 15rpx 15rpx 120rpx; .scroll {
display: flex; height: 600rpx;
flex-wrap: wrap;
.item{ .emoji-flex {
margin: 10rpx 15rpx; padding: 15rpx 15rpx 120rpx;
font-size: 52rpx; display: flex;
width: calc(12.5% - 30rpx); flex-wrap: wrap;
box-sizing: border-box;
} .item {
} margin: 10rpx 15rpx;
} font-size: 52rpx;
.tool{ width: calc(12.5% - 30rpx);
position: absolute; box-sizing: border-box;
bottom: 0; }
left: 0; }
right: 0; }
background-image: linear-gradient(to top, #FFF, rgba(255, 255, 255, .0));
display: flex; .tool {
justify-content: flex-end; position: absolute;
padding: 20rpx 30rpx 30rpx; bottom: 0;
.item{ left: 0;
line-height: 70rpx; right: 0;
border-radius: 35rpx; background-image: linear-gradient(to top, #FFF, rgba(255, 255, 255, .0));
width: 140rpx; display: flex;
text-align: center; justify-content: flex-end;
font-size: 28rpx; padding: 20rpx 30rpx 30rpx;
margin-left: 20rpx;
background: white; .item {
border: solid 1rpx #f5f5f5; line-height: 70rpx;
box-sizing: border-box; border-radius: 35rpx;
&.sent{ width: 140rpx;
border-color: #34CE98; text-align: center;
background: #34CE98; font-size: 28rpx;
color: white; margin-left: 20rpx;
} background: white;
} border: solid 1rpx #f5f5f5;
} box-sizing: border-box;
}
&.sent {
border-color: #34CE98;
background: #34CE98;
color: white;
}
}
}
}
</style> </style>

View File

@@ -25,6 +25,8 @@
<text class="text">文件</text> <text class="text">文件</text>
</view> </view>
<tki-file-manager ref="filemanager" @result="resultPath"></tki-file-manager>
<u-action-sheet :actions="callActions" cancelText="取消" @close="callShow = false" @select="singleCall" <u-action-sheet :actions="callActions" cancelText="取消" @close="callShow = false" @select="singleCall"
:show="callShow"> :show="callShow">
</u-action-sheet> </u-action-sheet>
@@ -34,11 +36,15 @@
<script> <script>
import im from '@/utils/im/index.js' import im from '@/utils/im/index.js'
import imBase from '../../mixins/imBase.js' import imBase from '../../mixins/imBase.js'
import tkiFileManager from "@/components/tki-file-manager/tki-file-manager.vue"
export default { export default {
mixins: [ mixins: [
imBase imBase
], ],
components: [
tkiFileManager
],
data() { data() {
return { return {
callActions: [{ callActions: [{
@@ -68,6 +74,11 @@
} }
}, },
methods: { methods: {
resultPath(path) {
im.sentFile(this.conversationType, this.targetId, path).then(res => {
console.log('发送文件', res);
})
},
singleCall(e) { singleCall(e) {
uni.navigateTo({ uni.navigateTo({
url: '/pages/im/private/call?targetId=' + this.targetId + '&mediaType=' + e.type + url: '/pages/im/private/call?targetId=' + this.targetId + '&mediaType=' + e.type +
@@ -81,10 +92,15 @@
count: 9, count: 9,
sourceType: ['album'], sourceType: ['album'],
success: res => { success: res => {
im.sentImage(this.conversationType, this.targetId, res.tempFilePaths[0], let funs = []
this.sender, (res) => { res.tempFilePaths.map((item, index) => {
this.success() funs[index] = im.sentImage(this.conversationType, this
}) .targetId, item)
})
Promise.all(funs).then(res => {
this.success()
})
} }
}) })
break; break;
@@ -92,8 +108,8 @@
uni.chooseImage({ uni.chooseImage({
sourceType: ['camera'], sourceType: ['camera'],
success: res => { success: res => {
im.sentImage(this.conversationType, this.targetId, res.tempFilePaths[0], im.sentImage(this.conversationType, this.targetId, res.tempFilePaths[0])
this.sender, (res) => { .then((res) => {
this.success() this.success()
}) })
} }
@@ -116,10 +132,12 @@
}) })
break; break;
case 'file': case 'file':
uni.showToast({ this.$refs.filemanager._openFile()
icon: 'none',
title: '功能正在开发中' // uni.showToast({
}) // icon: 'none',
// title: '功能正在开发中'
// })
break; break;
} }
}, },

View File

@@ -1,17 +1,7 @@
<template> <template>
<view class="sent--text"> <view class="sent--text">
<input <input class="input" type="text" :auto-blur="true" :focus="focusState" v-model="inputTxt" confirm-type="send"
class="input" cursor-spacing="10" @focus="focus" @blur="blur" @confirm="sent" />
type="text"
:auto-blur="true"
:focus="focusState"
v-model="inputTxt"
confirm-type="send"
cursor-spacing="10"
@focus="focus"
@blur="blur"
@confirm="sent"
/>
</view> </view>
</template> </template>
@@ -55,33 +45,33 @@
focusState: false, focusState: false,
inputTxt: '' inputTxt: ''
} }
}, },
created(){ created() {
uni.$on('emojiValue', res => { uni.$on('emojiValue', res => {
this.inputTxt = res.value this.inputTxt = res.value
}) })
}, },
methods: { methods: {
sent() { sent() {
if (!this.disabled) { if (!this.disabled) {
im.sentText(this.conversationType, this.targetId, this.inputTxt, this.sender, () => { im.sentText(this.conversationType, this.targetId, this.inputTxt).then(() => {
RongIMLib.clearTextMessageDraft(this.conversationType, this.targetId) RongIMLib.clearTextMessageDraft(this.conversationType, this.targetId)
this.$emit('success') this.$emit('success')
this.inputTxt = '' this.inputTxt = ''
}) })
} }
}, },
focus() { focus() {
this.$emit('focus') this.$emit('focus')
}, },
blur(e) { blur(e) {
uni.hideKeyboard() uni.hideKeyboard()
this.$emit('blur', e.detail) this.$emit('blur', e.detail)
} }
}, },
destroyed() { destroyed() {
uni.$off('emojiValue') uni.$off('emojiValue')
} }
} }
</script> </script>
@@ -91,6 +81,7 @@
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
.input { .input {
background: #F3F6FB; background: #F3F6FB;
height: 70rpx; height: 70rpx;

View File

@@ -1,21 +1,22 @@
<template> <template>
<view class="send--voice"> <view class="send--voice">
<view class="voice" hover-class="chat-hover" @touchstart="startRecord" @touchend="stopRecord" @touchmove="touchmove"> <view class="voice" hover-class="chat-hover" @touchstart="startRecord" @touchend="stopRecord"
@touchmove="touchmove">
<text class="button">按住 说话</text> <text class="button">按住 说话</text>
</view> </view>
<!-- 录音层 --> <!-- 录音层 -->
<view class="lay" v-if="showRecordTip"> <view class="lay" v-if="showRecordTip">
<view class="lay-header"> <view class="lay-header">
<view class="modal"> <view class="modal">
<image class="icon" src="@/static/icon/record-icon.png" mode="widthFix"></image> <image class="icon" src="@/static/icon/record-icon.png" mode="widthFix"></image>
<text class="text">录音中 {{recordTime}} s</text> <text class="text">录音中 {{recordTime}} s</text>
</view> </view>
</view> </view>
<view class="lay-toast">上滑取消</view> <view class="lay-toast">上滑取消</view>
<view class="lay-footer"> <view class="lay-footer">
<image class="lay-footer-icon videoFlicker" src="@/static/icon/audio_green.png" mode="widthFix"></image> <image class="lay-footer-icon videoFlicker" src="@/static/icon/audio_green.png" mode="widthFix"></image>
<view class="lay-footer-text">松开发送</view> <view class="lay-footer-text">松开发送</view>
</view> </view>
</view> </view>
</view> </view>
</template> </template>
@@ -23,8 +24,8 @@
<script> <script>
import im from '@/utils/im/index.js' import im from '@/utils/im/index.js'
import permision from '@/utils/permission.js' import permision from '@/utils/permission.js'
import imBase from '../../mixins/imBase.js' import imBase from '../../mixins/imBase.js'
export default { export default {
mixins: [ mixins: [
imBase imBase
@@ -41,15 +42,15 @@
}, },
data() { data() {
return { return {
showRecordTip: false, showRecordTip: false,
recordTime: 60, recordTime: 60,
interval: 0, interval: 0,
maxRecordTime: 60, maxRecordTime: 60,
recorderManager: null, recorderManager: null,
mp3AudioSrc: null, mp3AudioSrc: null,
isMoveCancel: false, isMoveCancel: false,
isBetaPlay: false, // 暂时无用 isBetaPlay: false, // 暂时无用
startOffsetTop: 0 startOffsetTop: 0
} }
}, },
computed: { computed: {
@@ -57,20 +58,20 @@
return this.$store.getters.sender return this.$store.getters.sender
} }
}, },
created() { created() {
this.recorderManager = uni.getRecorderManager() this.recorderManager = uni.getRecorderManager()
}, },
methods: { methods: {
// 检查安卓录制权限 // 检查安卓录制权限
async getAndroidPermission() { async getAndroidPermission() {
return await permision.requestAndroidPermission('android.permission.RECORD_AUDIO') return await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
}, },
// 录制语音消息 // 录制语音消息
startRecord(e) { startRecord(e) {
this.getAndroidPermission().then(code => { this.getAndroidPermission().then(code => {
switch (code) { switch (code) {
case 1: case 1:
this.startOffsetTop = e.target.offsetTop this.startOffsetTop = e.target.offsetTop
this.showRecordTip = true this.showRecordTip = true
this.recorderManager.start() this.recorderManager.start()
this.interval = setInterval(() => { this.interval = setInterval(() => {
@@ -96,103 +97,103 @@
}) })
}, },
// 结束录音 // 结束录音
stopRecord(e) { stopRecord(e) {
if (!this.showRecordTip) return if (!this.showRecordTip) return
// 延迟500毫秒结束录音 // 延迟500毫秒结束录音
setTimeout(()=> { setTimeout(() => {
this.recorderManager.stop() this.recorderManager.stop()
clearInterval(this.interval) clearInterval(this.interval)
// 监听录音结束 // 监听录音结束
this.recorderManager.onStop(res => { this.recorderManager.onStop(res => {
if(this.isMoveCancel) { if (this.isMoveCancel) {
this.isMoveCancel = false this.isMoveCancel = false
return return
} }
if((this.maxRecordTime - this.recordTime) <= 0){ if ((this.maxRecordTime - this.recordTime) <= 0) {
uni.showToast({ uni.showToast({
title: '说话时间太短', title: '说话时间太短',
icon : 'none', icon: 'none',
}) })
this.showRecordTip = false this.showRecordTip = false
return return
} }
this.mp3AudioSrc = res.tempFilePath this.mp3AudioSrc = res.tempFilePath
this.showRecordTip = false this.showRecordTip = false
this.senVoice() this.senVoice()
}) })
},500) }, 500)
}, },
// 发送语音消息 // 发送语音消息
senVoice(){ senVoice() {
if(this.mp3AudioSrc === null) { if (this.mp3AudioSrc === null) {
uni.showToast({ uni.showToast({
title: '发送失败, 暂无音频信息', title: '发送失败, 暂无音频信息',
icon : 'none' icon: 'none'
}) })
return return
} }
im.sentVoice(this.conversationType, this.targetId, this.mp3AudioSrc, (this.maxRecordTime - im.sentVoice(this.conversationType, this.targetId, this.mp3AudioSrc, (this.maxRecordTime -
this.recordTime), this.sender, () => { this.recordTime)).then(() => {
this.recordTime = this.maxRecordTime this.recordTime = this.maxRecordTime
this.mp3AudioSrc = null this.mp3AudioSrc = null
setTimeout(() => { setTimeout(() => {
this.$emit('success') this.$emit('success')
this.toastAudiMp3() this.toastAudiMp3()
}, 500) }, 500)
}) })
}, },
// 移动按钮 // 移动按钮
touchmove(e){ touchmove(e) {
if(this.startOffsetTop - e.changedTouches[0].pageY > 100){ if (this.startOffsetTop - e.changedTouches[0].pageY > 100) {
if(this.showRecordTip){ if (this.showRecordTip) {
this.isMoveCancel = true this.isMoveCancel = true
this.showRecordTip = false this.showRecordTip = false
this.recorderManager.stop() this.recorderManager.stop()
clearInterval(this.interval) clearInterval(this.interval)
this.recordTime = this.maxRecordTime this.recordTime = this.maxRecordTime
this.mp3AudioSrc = null this.mp3AudioSrc = null
return return
} }
} }
}, },
// 试听语音 // 试听语音
startPlay() { startPlay() {
let betaAudio = uni.createInnerAudioContext() let betaAudio = uni.createInnerAudioContext()
betaAudio.src = this.mp3AudioSrc; betaAudio.src = this.mp3AudioSrc;
// 在播放中 // 在播放中
if(this.isBetaPlay){ if (this.isBetaPlay) {
betaAudio.stop() betaAudio.stop()
betaAudio.onStop(() => { betaAudio.onStop(() => {
this.isBetaPlay = false; this.isBetaPlay = false;
betaAudio.destroy() betaAudio.destroy()
}) })
return return
} }
// 监听音频播放中 // 监听音频播放中
betaAudio.play() betaAudio.play()
betaAudio.onPlay(() => { betaAudio.onPlay(() => {
this.isBetaPlay = true; this.isBetaPlay = true;
}) })
// 监听音频结束 // 监听音频结束
betaAudio.onEnded(() => { betaAudio.onEnded(() => {
this.isBetaPlay = false; this.isBetaPlay = false;
betaAudio.destroy() betaAudio.destroy()
}) })
}, },
// 播放提示音乐 // 播放提示音乐
toastAudiMp3(){ toastAudiMp3() {
let toastAudio = uni.createInnerAudioContext() let toastAudio = uni.createInnerAudioContext()
toastAudio.src = require('@/static/im/toast/sentVoice.mp3') toastAudio.src = require('@/static/im/toast/sentVoice.mp3')
toastAudio.autoplay = true toastAudio.autoplay = true
toastAudio.volume = .1 toastAudio.volume = .1
toastAudio.onEnded(() => { toastAudio.onEnded(() => {
toastAudio.destroy() toastAudio.destroy()
}) })
} }
} }
} }
</script> </script>
<style> <style>
@keyframes playFlicker { @keyframes playFlicker {
0% { 0% {
@@ -225,77 +226,86 @@
width: 400rpx; width: 400rpx;
border-radius: 10rpx; border-radius: 10rpx;
margin-right: 15rpx; margin-right: 15rpx;
padding: 0 20rpx; padding: 0 20rpx;
font-weight: bold; font-weight: bold;
.button { .button {
font-size: 30rpx; font-size: 30rpx;
color: #333; color: #333;
} }
} }
.lay{
position: absolute; .lay {
left: 0; position: absolute;
top: 0; left: 0;
z-index: 9; top: 0;
background: rgba($color: #000000, $alpha: .5); z-index: 9;
height: 100vh; background: rgba($color: #000000, $alpha: .5);
width: 100vw; height: 100vh;
box-sizing: border-box; width: 100vw;
.lay-header{ box-sizing: border-box;
height: calc(100vh - 140px);
display: flex; .lay-header {
justify-content: center; height: calc(100vh - 140px);
align-items: center; display: flex;
.modal { justify-content: center;
display: flex; align-items: center;
background: rgba(0, 0, 0, .6);
position: fixed; .modal {
height: 200rpx; display: flex;
width: 300rpx; background: rgba(0, 0, 0, .6);
border-radius: 10rpx; position: fixed;
z-index: 99; height: 200rpx;
flex-direction: column; width: 300rpx;
align-items: center; border-radius: 10rpx;
justify-content: center; z-index: 99;
.icon { flex-direction: column;
width: 88rpx; align-items: center;
height: 88rpx; justify-content: center;
}
.icon {
.text { width: 88rpx;
font-size: 28rpx; height: 88rpx;
color: #FFFFFF; }
}
} .text {
} font-size: 28rpx;
.lay-toast{ color: #FFFFFF;
text-align: center; }
color: rgba($color: #fff, $alpha: .8); }
font-size: 28rpx; }
}
.lay-footer{ .lay-toast {
background-color: white; text-align: center;
height: 100px; color: rgba($color: #fff, $alpha: .8);
border-radius: 50% 50% 0 0; font-size: 28rpx;
position: absolute; }
bottom: 0;
left: 0; .lay-footer {
right: 0; background-color: white;
text-align: center; height: 100px;
display: flex; border-radius: 50% 50% 0 0;
justify-content: center; position: absolute;
flex-direction: column; bottom: 0;
align-items: center; left: 0;
.lay-footer-icon{ right: 0;
width: 58rpx; text-align: center;
height: 58rpx; display: flex;
} justify-content: center;
.lay-footer-text{ flex-direction: column;
line-height: 40rpx; align-items: center;
color: gray;
font-size: 28rpx; .lay-footer-icon {
} width: 58rpx;
} height: 58rpx;
}
.lay-footer-text {
line-height: 40rpx;
color: gray;
font-size: 28rpx;
}
}
} }
} }
</style> </style>

View File

@@ -1,6 +1,7 @@
<template> <template>
<view class="chat"> <view class="chat">
<sent-message-bar id="msgbar" :conversationType="conversationType" :targetId="targetId" @onSuccess="getNewMessage()" /> <sent-message-bar id="msgbar" :conversationType="conversationType" :targetId="targetId"
@onSuccess="getNewMessage()" />
<view class="shade" @click="hidePop" v-show="showPop"> <view class="shade" @click="hidePop" v-show="showPop">
<view class="pop" :style="popStyle" :class="{'show':showPop}"> <view class="pop" :style="popStyle" :class="{'show':showPop}">
@@ -31,13 +32,13 @@
import showMessageCell from '../components/showMessageCell' import showMessageCell from '../components/showMessageCell'
import utils from '@/utils/index.js' import utils from '@/utils/index.js'
import onGroupDismiss from '../mixins/onGroupDismiss.js' import onGroupDismiss from '../mixins/onGroupDismiss.js'
import imBase from '../mixins/imBase.js' import imBase from '../mixins/imBase.js'
import messageActions from '../mixins/messageActions.js' import messageActions from '../mixins/messageActions.js'
export default { export default {
mixins: [ mixins: [
imBase, imBase,
onGroupDismiss, onGroupDismiss,
messageActions messageActions
], ],
components: { components: {
@@ -52,8 +53,8 @@
messages: [], messages: [],
groupInfo: { groupInfo: {
name: '' name: ''
}, },
placeHeight: uni.getSystemInfoSync().windowHeight, placeHeight: uni.getSystemInfoSync().windowHeight,
bottomHeihgt: 56 bottomHeihgt: 56
} }
}, },
@@ -71,21 +72,21 @@
onShow() { onShow() {
this.initGroupInfo() this.initGroupInfo()
}, },
onLoad(e) { onLoad(e) {
const query = uni.createSelectorQuery().in(this); const query = uni.createSelectorQuery().in(this);
this.$nextTick(function() { this.$nextTick(function() {
query.select('#msgbar').boundingClientRect(bottom => { query.select('#msgbar').boundingClientRect(bottom => {
this.bottomHeihgt = bottom.height this.bottomHeihgt = bottom.height
}).exec(); }).exec();
}) })
// 监听键盘高度变化 // 监听键盘高度变化
uni.onKeyboardHeightChange(keyboard => { uni.onKeyboardHeightChange(keyboard => {
query.select('#scroll').boundingClientRect(scroll => { query.select('#scroll').boundingClientRect(scroll => {
const placeHeight = this.windowHeight - scroll.height - keyboard.height - this const placeHeight = this.windowHeight - scroll.height - keyboard.height - this
.bottomHeihgt .bottomHeihgt
this.placeHeight = placeHeight > 0 ? placeHeight : 0 this.placeHeight = placeHeight > 0 ? placeHeight : 0
}).exec(); }).exec();
}) })
this.targetId = e.targetId this.targetId = e.targetId
// 获取历史消息列表 // 获取历史消息列表
this.getMessageList() this.getMessageList()
@@ -116,7 +117,7 @@
}) })
// 清理聊天记录 // 清理聊天记录
uni.$once('cleanGroupMessage', this.getMessageList) uni.$once('cleanGroupMessage', this.getMessageList)
uni.$on('onRecallMessage_' + this.targetId, (message) => { uni.$on('onRecallMessage_' + this.targetId, (message) => {
this.messages = this.messages.map(item => { this.messages = this.messages.map(item => {
if (message.messageId == item.messageId) { if (message.messageId == item.messageId) {
return message return message
@@ -175,12 +176,9 @@
20, 20,
true, true,
(messages) => { (messages) => {
console.log('获取消息列表', messages);
const msgs = messages.filter(item => item.receivedStatus == 0) const msgs = messages.filter(item => item.receivedStatus == 0)
console.log('未读消息', msgs);
if (msgs.length) { if (msgs.length) {
RongIMLib.sendReadReceiptResponse(3, this.targetId, msgs, (res) => { RongIMLib.sendReadReceiptResponse(3, this.targetId, msgs, (res) => {
console.error('发送群聊已读回执成功', res);
msgs.map(item => { msgs.map(item => {
RongIMLib.setMessageReceivedStatus(item.messageId, 1) RongIMLib.setMessageReceivedStatus(item.messageId, 1)
}) })
@@ -245,7 +243,7 @@
height: 100%; height: 100%;
z-index: 999; z-index: 999;
.pop { .pop {
border-radius: 10rpx; border-radius: 10rpx;
position: fixed; position: fixed;
z-index: 101; z-index: 101;

View File

@@ -80,35 +80,37 @@ const getGroupPendinglist = (targetId, callback) => {
* @param {string} content 消息内容 * @param {string} content 消息内容
* @param {function} callback 回调函数 * @param {function} callback 回调函数
*/ */
const sentText = (conversationType, targetId, content, user, callback) => { const sentText = (conversationType, targetId, content) => {
const msg = { return new Promise((resolve, reject) => {
conversationType: conversationType, const msg = {
targetId: String(targetId), conversationType: conversationType,
content: { targetId: String(targetId),
objectName: 'RC:TxtMsg', content: {
content: content, objectName: 'RC:TxtMsg',
userInfo: user content: content,
} userInfo: store.getters.sender
}
RongIMLib.sendMessage(msg, ({
code,
messageId
}) => {
if (code === 0) {
if (conversationType == 3) {
RongIMLib.sendReadReceiptRequest(messageId, (res) => {
console.log('发送回执请求', res);
})
} }
callback(messageId)
} else {
console.log('发送失败', msg);
uni.showToast({
icon: 'none',
title: '发送失败' + code
})
} }
RongIMLib.sendMessage(msg, ({
code,
messageId
}) => {
if (code === 0) {
if (conversationType == 3) {
RongIMLib.sendReadReceiptRequest(messageId, (res) => {
console.log('发送回执请求', res);
})
}
resolve(messageId)
} else {
uni.showToast({
icon: 'none',
title: '发送失败' + code
})
reject(code)
}
})
}) })
} }
@@ -118,112 +120,84 @@ const sentText = (conversationType, targetId, content, user, callback) => {
* @param {string} targetId 会话id * @param {string} targetId 会话id
* @param {string} voiceUrl 录音的本地路径 * @param {string} voiceUrl 录音的本地路径
* @param {integer} time 录音时长 * @param {integer} time 录音时长
* @param {function} callback 录音时长 * @param {function} user 本人信息
*/ */
const sentVoice = (conversationType, targetId, voiceUrl, time, user, callback) => { const sentVoice = (conversationType, targetId, voiceUrl, time) => {
const msg = { return new Promise((resolve, reject) => {
conversationType: conversationType, const msg = {
targetId: String(targetId), conversationType: conversationType,
content: { targetId: String(targetId),
objectName: 'RC:HQVCMsg', content: {
local: 'file:///' + plus.io.convertLocalFileSystemURL(voiceUrl), objectName: 'RC:HQVCMsg',
duration: time == 0 ? 1 : time, local: 'file://' + plus.io.convertLocalFileSystemURL(voiceUrl),
userInfo: user duration: time == 0 ? 1 : time,
} userInfo: store.getters.sender
} }
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
} }
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
resolve(messageId);
},
progress: (progress, messageId) => {},
cancel: (messageId) => {},
error: (errorCode, messageId) => {
reject(errorCode);
}
})
}) })
} }
const sentImage = (conversationType, targetId, imageUrl, user, callback) => { // 发送的图片可能会涉及到一次多张用Promise来确保前端一次性清算
const msg = { const sentImage = (conversationType, targetId, imageUrl) => {
conversationType: conversationType, return new Promise((resolve, reject) => {
targetId: String(targetId), uni.getImageInfo({
content: { src: imageUrl,
objectName: 'RC:ImgMsg', success: (imgInfo) => {
local: 'file:///' + plus.io.convertLocalFileSystemURL(imageUrl), const msg = {
userInfo: user conversationType: conversationType,
} targetId: String(targetId),
} content: {
RongIMLib.sendMediaMessage(msg, { objectName: 'RC:ImgMsg',
success: (messageId) => { local: imgInfo.path,
callback(messageId); userInfo: store.getters.sender
}, }
progress: (progress, messageId) => { }
console.log(messageId); RongIMLib.sendMediaMessage(msg, {
}, success: (messageId) => {
cancel: (messageId) => { resolve(messageId)
// 发送取消回调 },
}, progress: (progress, messageId) => {},
error: (errorCode, messageId) => { cancel: (messageId) => {},
console.log(errorCode, messageId); error: (errorCode, messageId) => {
} reject(errorCode)
}
})
}
})
}) })
} }
const sentGif = (conversationType, targetId, gifUrl, time, user, callback) => { const sentFile = (conversationType, targetId, fileUrl) => {
const msg = { return new Promise((resolve, reject) => {
conversationType: conversationType, const msg = {
targetId: String(targetId), conversationType: conversationType,
content: { targetId: String(targetId),
objectName: 'RC:GIFMsg', content: {
local: 'file:///' + plus.io.convertLocalFileSystemURL(gifUrl), objectName: 'RC:FileMsg',
duration: time, local: 'file:///' + plus.io.convertLocalFileSystemURL(fileUrl),
userInfo: user userInfo: store.getters.sender
} }
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
}
})
}
const sendFile = (conversationType, targetId, fileUrl, time, user, callback) => {
const msg = {
conversationType: conversationType,
targetId: String(targetId),
content: {
objectName: 'RC:FileMsg',
local: 'file:///' + plus.io.convertLocalFileSystemURL(fileUrl),
duration: time,
userInfo: user
}
}
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
callback(messageId);
},
progress: (progress, messageId) => {
console.log(messageId);
},
cancel: (messageId) => {
// 发送取消回调
},
error: (errorCode, messageId) => {
console.log(errorCode, messageId);
} }
RongIMLib.sendMediaMessage(msg, {
success: (messageId) => {
resolve(messageId)
},
progress: (progress, messageId) => {},
cancel: (messageId) => {},
error: (errorCode, messageId) => {
reject(errorCode)
}
})
}) })
} }
@@ -234,6 +208,5 @@ export default {
sentText, sentText,
sentVoice, sentVoice,
sentImage, sentImage,
sentGif, sentFile
sendFile
} }

View File

@@ -1,6 +1,6 @@
import { import {
usqlite usqlite
} from '@/uni_modules/onemue-USQLite/js_sdk/usqlite.js' } from '@/uni_modules/onemue-USQLite/js_sdk/usqlite.js'
const contactModel = usqlite.model('contacts', { const contactModel = usqlite.model('contacts', {
targetId: { targetId: {