聊天完成

This commit is contained in:
luyuan 2020-08-07 14:44:11 +08:00
parent c1a3a11781
commit 93c412a515
Signed by: theluyuan
GPG Key ID: A7972FD973317FF3
34 changed files with 1481 additions and 41 deletions

View File

@ -0,0 +1,62 @@
<template>
<div class="goeasy-audio-player" @click="playAudio">
<div class="audio-facade" :style="{width:Math.ceil(duration)*7 + 50 + 'px'}">
<div class="audio-facade-bg" :class="{'play-icon':play}"> </div>
<div>{{Math.ceil(duration) || 0}}</div>
</div>
</div>
</template>
<script>
const innerAudioContext = uni.createInnerAudioContext();
export default {
name: "GoEasyAudioPlayer",
props : ['src', 'duration'],
data () {
return {
play : false
}
},
methods : {
playAudio () {
this.play = true;
innerAudioContext.src = this.src;
innerAudioContext.play();
setTimeout(() => {
this.play = false;
}, this.duration*1000)
}
}
}
</script>
<style scoped>
.goeasy-audio-player{
margin-top: 12rpx;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
.audio-facade{
min-width: 20rpx;
padding: 6rpx 10rpx;
height: 72rpx;
line-height: 72rpx;
background: #D02129;
font-size: 24rpx;
border-radius: 14rpx;
color: #ffffff;
display: flex;
}
.audio-facade-bg{
background: url("./images/voice.png") no-repeat center;
background-size: 30rpx;
width: 40rpx;
}
.audio-facade-bg.play-icon{
background: url("./images/play.gif") no-repeat center;
background-size: 30rpx;
-moz-transform:rotate(180deg);
-webkit-transform:rotate(180deg);
-o-transform:rotate(180deg);
transform:rotate(180deg);
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 B

View File

@ -0,0 +1,55 @@
<template>
<video
v-if="show"
class="video-player"
controls = ""
@play="onPlayStart"
id="videoPlayer"
autoplay="true"
@fullscreenchange="onVideoFullScreenChange"
:src="url">
</video>
</template>
<script>
export default {
name: "GoEasyVideoPlayer",
data () {
return {
show : false,
context: null,
url: ''
}
},
methods : {
play (video) {
this.show = true;
this.url = video.url;
this.context = uni.createVideoContext('videoPlayer');
},
onVideoFullScreenChange (e) {
//退
if(this.show && !e.detail.fullScreen){
this.show = false;
this.context.stop();
}
},
onPlayStart () {
//
this.context.requestFullScreen({
direction : 0
});
}
}
}
</script>
<style scoped>
.video-player{
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 B

View File

@ -1,11 +1,12 @@
import Vue from 'vue'
import App from './App'
import IMService from './static/imservice.js'
import uView from "uview-ui";
Vue.use(uView);
Vue.config.productionTip = false
Vue.prototype.imService = new IMService();
Vue.prototype.a = 1;
App.mpType = 'app'
const app = new Vue({

View File

@ -37,6 +37,15 @@
}
}
},
{
"path": "pages/messages/privateChat",
"style": {
"navigationBarTitleText": "uni-app",
"app-plus": {
"titleNView": true
}
}
},
{
"path": "pages/index/index",
"style": {
@ -59,17 +68,17 @@
}
}
}
},
{
"path": "pages/index/otherdetails",
"style": {
"navigationBarTitleText": "试穿订单详情",
"app-plus": {
"titleNView": {
"titleColor": "#333333"
}
}
}
},
{
"path": "pages/index/otherdetails",
"style": {
"navigationBarTitleText": "试穿订单详情",
"app-plus": {
"titleNView": {
"titleColor": "#333333"
}
}
}
},
{
"path": "pages/release/video",
@ -146,7 +155,7 @@
"titleColor": "#333333",
"buttons": [ //,
{
"text": "保存",
"text": "保存",
"fontSize":"14px"
}
]
@ -285,4 +294,4 @@
}]
}
}
}

View File

@ -99,7 +99,7 @@ export default {
return
}
//
uni.clearStorage();
// uni.clearStorage();
// 10
if(this.state==1){
this.$u.api.login({ member_name: this.zhanghaoA, member_password: this.mimaA }).then(res => {

View File

@ -7,12 +7,12 @@
</view>
</view>
<!-- 消息列表 -->
<view class="massage_list" v-for="(item,index) in list" :key="index">
<view class="massage_list" v-for="(item,index) in list" :key="index" @click="gochat(item)">
<view class="images">
<image :src="item.url" ></image>
<image :src="item.avatar" ></image>
</view>
<view class="names">{{item.name}}</view>
<view class="content">{{item.content}}</view>
<view class="content u-line-1">{{item.text}}</view>
<view class="times">{{item.time}}</view>
</view>
<u-toast ref="uToast" />
@ -23,32 +23,41 @@
data() {
return {
keyword: '搜索',
list: [{
name: '瘦瘦',
content: "木糖少女小紫薯西装领连衣裙夏季新款女装装领连衣裙夏季装领连衣裙夏季装领连衣裙夏季夏收腰格子格纹裙子",
url: '../../static/image/tosign/tosigin(5).png',
id : '1',
time : '1015'
},
{
name: '瘦瘦',
content: "木糖少女小紫薯西装领连衣裙夏季新款女装装领连衣裙夏季装领连衣裙夏季装领连衣裙夏季夏收腰格子格纹裙子",
url: '../../static/image/tosign/tosigin(5).png',
id : '1',
time : '1015'
},
{
name: '瘦瘦',
content: "木糖少女小紫薯西装领连衣裙夏季新款女装装领连衣裙夏季装领连衣裙夏季装领连衣裙夏季夏收腰格子格纹裙子",
url: '../../static/image/tosign/tosigin(5).png',
id : '1',
time : '1015'
},
list: [
],
};
},
methods: {
gochat(id){
console.log(id)
this.$u.route({
url:"/pages/messages/privateChat",
params:{
id:JSON.stringify(id)
}
})
},
onFriendListChange(onlineFriends) {
//todo:UniappMAPH5H5
//
console.log(onlineFriends,121212)
this.information_dl = onlineFriends;
this.$forceUpdate();
},
},
onShow(){
this.list = this.imService.friends;
this.imService.onFriendListChange=this.onFriendListChange;
},
onLoad(){
const user = uni.getStorageSync('userinfo');
console.log(user)
this.imService.login(user.userId,"","")
this.imService.connectIM()
this.information_dl = this.imService.friends;
}
};
</script>

View File

@ -0,0 +1,615 @@
<template>
<div class="chatInterface">
<div class="chat-scroll-container">
<scroll-view ref="myScroll" scroll-y="true" class="scroll-view" :scroll-into-view="contentPosition">
<div :class="[allHistoryLoaded ? 'top gray' : 'top']" @click="loadMoreHistoryMessage">
<span class="description">{{allHistoryLoaded ? '已经没有更多的历史消息' : '点击加载更多历史消息'}}</span>
</div>
<!--已经收到的消息-->
<div v-for="(message, key) in messages || []"
:id="'message_' + message.timestamp"
:key="message.timestamp"
class = "message-item"
:class="{'self' : message.senderId == (currentUser && currentUser.uuid)}">
<div :class="friend.online ? 'avatar' : 'avatar offline-gray'"
v-if="message.senderId != (currentUser && currentUser.uuid)">
<image :src="friend.avatar" ></image>
</div>
<div class="avatar" v-else>
<image :src="currentUser.avatar"></image>
</div>
<div class="content">
<span class="text-content" v-if="message.type =='text'">{{message.payload.text}}</span>
<image class="image-content" v-if="message.type == 'image'" :src="message.payload.url" :data-url="message.payload.url" @click="showImageFullScreen" mode="widthFix" @load="scrollToBottom"></image>
<div class="video-snapshot" v-if="message.type == 'video'" :data-url="message.payload.video.url" @click="playVideo">
<image :src="message.payload.thumbnail.url" mode="aspectFit" @load="scrollToBottom"></image>
<div class="video-play-icon"></div>
</div>
<GoEasyAudioPlayer v-if="message.type =='audio'" :src="message.payload.url" :duration="message.payload.duration" />
</div>
</div>
<!--发送中的消息-->
<div v-for="(message, index) in pendingMessages || []"
:key="index"
:id="'pendingMessage_' + index"
class = "message-item"
:class="{'self' : message.senderId == (currentUser && currentUser.uuid)}">
<div :class="friend.online ? 'avatar' : 'avatar offline-gray'"
v-if="message.senderId != (currentUser && currentUser.uuid)">
<image :src="friend.avatar"></image>
</div>
<div class="avatar" v-else>
<image :src="currentUser.avatar"></image>
</div>
<div class="content">
<b class="pending"></b>
<span class="text-content" v-if="message.type =='text'">{{message.payload.text}}</span>
<image class="image-content" v-if="message.type == 'image'" :src="message.payload.url" mode="widthFix" @load="scrollToBottom"></image>
<div v-if="message.type == 'video'" class="video-snapshot">
<image :src="message.payload.thumbnail.url" mode="aspectFit" @load="scrollToBottom"></image>
<div class="video-play-icon"></div>
</div>
<GoEasyAudioPlayer v-if="message.type =='audio'" :src="message.payload.url" :duration="message.payload.duration" />
</div>
</div>
</scroll-view>
</div>
<div class="action-box" v-if="!video.visible">
<div class="action-top">
<div :class="[audio.visible ? 'record-icon record-open':'record-icon']" @click="switchAudioKeyboard"></div>
<div class="record-input" @longpress="onRecordStart" @touchend="onRecordEnd" v-if="audio.visible" >{{audio.recording ? '松开发送' : '按住录音'}}</div>
<div class="message-input" v-else>
<input type="text" placeholder="发送消息" v-model="content">
</div>
<div class="file-icon img-video" @click="sendImage"></div>
<div class="file-icon" @click="sendVideo"></div>
<span class="send-message-btn" @click="sendMessage">发送</span>
</div>
</div>
<div class="record-loading" v-if="audio.recording"></div>
<video style="width:100%;height: 100%" :src="video.url" v-if="video.visible" id="videoPlayer" autoplay="true" @fullscreenchange="onVideoFullScreenChange" @play="onVideoPlayStart"></video>
</div>
</template>
<script>
import GoEasyAudioPlayer from "../../components/GoEasyAudioPlayer/GoEasyAudioPlayer";
const recorderManager = uni.getRecorderManager();
export default {
name: "privateChat",
components : {
GoEasyAudioPlayer,
},
data() {
return {
//
content: '',
friend: null,
currentUser: null,
//
messages: [],
//
pendingMessages : [],
//
allHistoryLoaded: false,
contentPosition : '',
audio : {
//
recording : false,
//
visible : false
},
video : {
visible : false,
url : '',
context : null
}
}
},
watch : {
//
pendingMessages(){
this.scrollToBottom()
}
},
onReady () {
this.video.context = uni.createVideoContext('videoPlayer');
},
onLoad(options) {
if(!this.imService.currentUser){
uni.navigateTo({
url : '../login/login'
});
}
//
this.friend = JSON.parse(options.id);
this.currentUser = this.imService.currentUser;
let privateMessages = this.imService.getPrivateMessages(this.friend.uuid);
this.messages = privateMessages.sentMessages;
this.pendingMessages = privateMessages.pendingMessages;
uni.setNavigationBarTitle({
title : this.friend.name
});
setTimeout(() => {
uni.setNavigationBarColor({
backgroundColor : '#D02129',
frontColor : '#ffffff'
});
}, 10);
this.initialListeners();
//
this.scrollToBottom()
},
onUnload() {
//退
this.imService.onNewPrivateMessageReceive = (friendId, message)=> {};
this.imService.onPrivateHistoryLoad = (friendId, messages) =>{};
//
this.imService.resetFriendUnReadMessage(this.friend);
},
methods: {
initialListeners () {
//
this.imService.onNewPrivateMessageReceive = (friendId, message)=> {
if (friendId == this.friend.uuid) {
//
this.scrollToBottom()
}
};
//
this.imService.onPrivateHistoryLoad = (friendId, messages) =>{
if (messages.length == 0) {
//
this.allHistoryLoaded = true
}
};
//
this.initRecorderListeners();
},
initRecorderListeners(){
var self = this;
//
recorderManager.onStart(function(){
self.audio.recording = true;
});
//
recorderManager.onStop(function(res){
self.audio.recording = false;
self.imService.sendPrivateAudioMessage(self.friend.uuid, res)
});
//
recorderManager.onError(function(res){
console.log("录音报错:",res);
})
},
sendMessage() {//
if (this.content.trim() != '') {
this.imService.sendPrivateTextMessage(this.friend.uuid, this.content);
let that = this
setTimeout(function(){
that.scrollToBottom();
},500)
}
this.content = "";
},
loadMoreHistoryMessage() {//
let lastMessageTimeStamp = Date.now();
let lastMessage = this.messages[0];
if (lastMessage) {
lastMessageTimeStamp = lastMessage.timestamp;
}
this.imService.loadPrivateHistoryMessage(this.friend.uuid, lastMessageTimeStamp);
},
onRecordStart () {
try{
recorderManager.start();
}catch(e){
console.log("e:",e);
uni.showModal({
title: '录音错误',
content : '请在app和小程序端体验录音Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
});
}
},
onRecordEnd () {
try{
recorderManager.stop();
}catch(e){
console.log("e:",e);
uni.showModal({
title: '录音错误',
content : '请在app和小程序端体验录音Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
});
}
},
sendVideo () {//
uni.chooseVideo({
success : (res) => {
console.log(res)
this.imService.sendPrivateVideoMessage(this.friend.uuid, res)
}
})
},
sendImage() {
uni.chooseImage({
count :1,
success :(res) => {
console.log(res)
this.imService.sendPrivateImageMessage(this.friend.uuid,res);
}
})
},
showImageFullScreen (e) {
var imagesUrl = [e.currentTarget.dataset.url];
uni.previewImage({
urls: imagesUrl
});
},
//
switchAudioKeyboard() {
this.audio.visible = !this.audio.visible;
},
playVideo (e) {
this.video.visible = true;
this.video.url =e.currentTarget.dataset.url;
},
onVideoPlayStart () {
this.video.context.requestFullScreen({
direction : 0
});
},
onVideoFullScreenChange (e) {
//退
if(this.video.visible && !e.detail.fullScreen){
this.video.visible = false;
this.video.context.stop();
}
},
scrollToBottom () {
this.$nextTick(() => {
if(this.messages && this.messages.length !=0){
this.contentPosition = 'message_' + (this.messages[this.messages.length-1].timestamp || '');
}
})
}
}
}
</script>
<style >
page {
height: 100%;;
}
uni-page-body, uni-page-refresh {
height: 100%;;
}
.chatInterface{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
.chatInterface .chat-scroll-container{
overflow: hidden;
padding-left: 20rpx;
padding-right: 20rpx;
height: 100%;
display: flex;
flex: 1;
}
.chatInterface .scroll-view{
flex: 1;
overflow: auto;
box-sizing: border-box;
}
.chatInterface .top{
font-size: 24rpx;
height: 90rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
-webkit-tap-highlight-color: transparent;
color: blue;
}
.chatInterface .top .description{
text-decoration: underline;
}
.chatInterface .message-item{
/* max-height: 400rpx; */
margin-top: 40rpx;
overflow: hidden;
}
.chatInterface .avatar{
width: 80rpx;
height: 80rpx;
margin-right:20rpx ;
}
.chatInterface .message-item.self .avatar{
margin-left: 20rpx;
}
.chatInterface .message-item .avatar image{
width: 100%;
height: 100%;
}
.chatInterface .content{
font-size: 34rpx;
line-height: 44rpx;
/* max-height: 400rpx; */
display: flex;
align-items: center;
justify-content: right;
}
.chatInterface .content .image-content{
padding: 16rpx;
border-radius: 12rpx;
width: 300rpx;
height: 300rpx;
}
.chatInterface .content .text-content{
padding: 16rpx;
border-radius: 12rpx;
max-width: 520rpx;
}
.chatInterface .content .pending{
background: url("../../static/images/pending.gif") no-repeat center;
background-size: 30rpx;
width: 30rpx;
height: 30rpx;
margin-right: 10rpx;
flex-grow: 0;
flex-shrink: 0;
}
.chatInterface .action-box{
display: flex;
height: 80rpx;
padding-top: 20rpx;
padding-bottom: 20rpx;
backdrop-filter: blur(0.27rpx);
width: 100%;
}
.chatInterface .action-top{
display: flex;
padding-top: 20rpx;
padding-bottom: 20rpx;
backdrop-filter: blur(0.27rem);
height: 80rpx;
width: 100%;
}
.chatInterface .record-icon{
font-size: 32rpx;
width: 80rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
background: url("../../static/images/record-appearance-icon.png") no-repeat center;
background-size: 50%;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
.chatInterface .action-top .file-icon{
background: url("../../static/images/vedio.png") no-repeat center;
background-size: 70%;
color: #9D9D9D;
position: relative;
width:80rpx;
height: 80rpx;
line-height: 80rpx;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
.chatInterface .record-icon.record-open{
background: url("../../static/images/jianpan.png") no-repeat center;
background-size: 70%;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
.chatInterface .action-top .img-video{
background: url("../../static/images/file.png") no-repeat center;
background-size: 74%;
}
.chatInterface .record-input{
width: 480rpx;
height: 80rpx;
line-height: 80rpx;
border-radius: 12rpx;
font-size: 28rpx;
background: #cccccc;
color: #ffffff;
text-align: center;
}
.chatInterface .message-input{
border-radius: 12rpx;
}
.chatInterface .message-input input{
width: 440rpx;
height: 80rpx;
line-height: 80rpx;
padding-left: 20rpx;
font-size: 28rpx;
}
.chatInterface .send-message-btn{
font-size: 32rpx;
width: 80rpx;
line-height: 80rpx;
}
.record-loading{
position: absolute;
top:50%;
left: 50%;
width: 300rpx;
height: 300rpx;
margin: -150rpx -150rpx;
background: #262628;
background: url("../../static/images/recording-loading.gif") no-repeat center;
background-size: 100%;
border-radius: 40rpx;
}
.chatInterface .img-layer{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #000000;
z-index: 9999;
padding: 6rpx;
display: flex;
justify-content: center;
align-items: center;
}
.chatInterface .img-layer uni-image {
height: 100%!important;
}
.chatInterface .img-layer {
height: 100%!important;
width: 100%!important;
}
.chatInterface .content .file-content .file-info{
height: 0.5rem;
width: 1.5rem;
display: flex;
flex-direction: column;
padding: 0 0.1rem;
}
.chatInterface .content .file-content .file-info .title{
height: 0.3rem;
line-height: 0.3rem;
overflow: hidden;
font-size: 0.16rem;
padding: 0;
white-space: nowrap;
text-overflow: ellipsis;
word-break: break-all;
color: #262628;
text-align: left;
}
.chatInterface .content .file-content .file-info .size{
font-size: 0.14rem;
height: 0.2rem;
line-height: 0.2rem;
padding: 0;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
word-break: break-all;
color: #999999;
text-align: left;
}
.chatInterface .video-snapshot{
position: relative;
height: 300rpx;
max-width: 400rpx;
background: #000000;
}
.chatInterface .video-snapshot image{
max-height: 300rpx;
max-width: 400rpx;
}
.chatInterface .video-snapshot video{
max-height: 300rpx;
max-width: 400rpx;
}
.video-snapshot .video-play-icon{
position: absolute;
width: 40rpx;
height: 40rpx;
border-radius: 20rpx;
background:url("../../static/images/play.png") no-repeat center;
background-size: 100%;
top:50%;
left: 50%;
margin:-20rpx;
}
.chatInterface .avatar{
overflow: hidden;
float: left;
}
.chatInterface .avatar img{
width: 100%;
height: 100%;
display: block;
}
.chatInterface .content{
float: left;
overflow: hidden;
}
.chatInterface .content span{
font-family: Source Han Sans CN;
letter-spacing: -0.41px;
color: #262628;
background: #efefef;
display: inline-block;
word-break: break-all;
}
.chatInterface .message-item.self{
margin-right: 0;
}
.chatInterface .message-item.self .avatar{
margin-right: 0;
float: right;
}
.chatInterface .message-item.self .content{
text-align: right;
float: right;
}
.chatInterface .message-item.self .content span{
color: #ffffff;
background:#D02129;
word-break: break-all;
text-align: left;
max-width: 520rpx;
}
.chatInterface .action-box{
background: #FAFAFA;
display: flex;
align-content: center;
align-items: center;
}
.chatInterface .message-input{
background: #efefef;
border: 0;
outline: none;
}
.chatInterface .send-message-btn{
flex-grow: 1;
text-align: center;
color: #95949A;
}
.chatInterface .member-layer{
width:100%;
height: 100%;
background: #FFFFFF;
top: 0;
left: 0;
position: absolute;
}
.member-layer .member{
display: flex;
flex-wrap: wrap;
}
.chatInterface .group-icon{
position: absolute;
}
.chatInterface .gray{
color: gray!important;
text-decoration: none!important;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 B

BIN
static/images/Avatar-1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
static/images/Avatar-2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
static/images/Avatar-3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

BIN
static/images/Avatar-4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
static/images/Vector.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 714 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 808 B

BIN
static/images/file-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 B

BIN
static/images/file.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 463 B

BIN
static/images/green-dot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 373 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 502 B

BIN
static/images/group.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
static/images/im.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

BIN
static/images/jianpan.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 932 B

BIN
static/images/loading.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
static/images/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

BIN
static/images/pending.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 B

BIN
static/images/play.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 620 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
static/images/vedio.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 472 B

610
static/imservice.js Normal file
View File

@ -0,0 +1,610 @@
/*
* @Author: jack.lu
* @Date: 2020-4-21 10:10:20
* @Last Modified by: jack.lu
* @Last Modified time: 2020-4-21 15:01:41
*/
import GoEasyIM from './goeasy-im-1.0.9';
import restApi from './restapi';
function Friend(uuid, name, avatar,time = "", text = "",date = "") {
this.uuid = uuid;
this.name = name;
this.avatar = avatar;
this.online = false;
this.unReadMessage = 0;
this.text = text;
this.time = time;
this.date = date
}
function Group(uuid, name, avatar) {
this.uuid = uuid;
this.name = name;
this.avatar = avatar;
this.unReadMessage = 0;
}
function CurrentUser(uuid, name, avatar) {
this.uuid = uuid;
this.name = name;
this.avatar = avatar;
}
function IMService() {
this.im = GoEasyIM.getInstance({
host:'hangzhou.goeasy.io',//qos=1
appkey:'BC-453aa755c4ea48148abefc55a86df283'
});
//当前“我”
this.currentUser = null;
//我的好友
this.friends = {};
this.friendsarr = [];
//我的群
this.groups = {};
//私聊消息记录map格式每个好友对应一个数组
this.privateMessages = {};
//群聊消息记录map格式每个群对应一个数组
this.groupMessages = {};
/*
* 监听器们
*
* 可以在页面里根据需求重写以下监听器
* 便于当各种事件触发时页面能够执行对应的响应
*
*/
//收到一条私聊消息
this.onNewPrivateMessageReceive = function (friendId, message) {};
//完成一次私聊历史加载
this.onPrivateHistoryLoad = function (friendId, messages) {};
//收到一条群聊消息
this.onNewGroupMessageReceive = function (groupId, message) {};
//完成一次群聊历史加载
this.onGroupHistoryLoad = function (groupId, messages) {};
//好友列表发生改变
this.onFriendListChange = function (friends) {};
//群列表发生改变
this.onGroupListChange = function (groups) {};
}
//登录
IMService.prototype.login = function (uuid, name, avatar) {
//初始化当前用户
this.currentUser = new CurrentUser(uuid, name, avatar);
//初始化联系人信息,包括群
this.initialContacts();
return true;
};
//初始化联系人信息
IMService.prototype.initialContacts = function (friendList) {
//查询并初始化好友信息
// let friendList = restApi.findFriends(this.currentUser);
let value = uni.getStorageSync('imlist');
console.log(value)
if(value != undefined && !value){
return ;
}
value = JSON.parse(value)
let that = this
console.log(value)
for(let i of value){
const token = uni.getStorageSync('token');
console.log(token)
uni.request({
url:"https://dmmall.sdbairui.com/api/Specialci/getAtwillUserInfo",
data:{
userId:i[0]
},
method:"POST",
header:{
"Authorization" : 'Bearer' + " " + token
},
success(res){
console.log(res)
that.friends[i[0]] = new Friend(res.data.data.member_id, res.data.data.member_nickname, res.data.data.member_avatar,i[1],i[2]);
console.log(that.friends)
let sorts = function (friends){
let paixu = function (a,b){
if(a.date > b.date){
return 0;
}else{
return 1;
}
}
friends.sort(paixu)
}
that.friendsarr = []
for(let i in that.friends){
console.log(i)
that.friendsarr.push(that.friends[i])
}
sorts(that.friendsarr)
console.log("历史记录")
that.onFriendListChange(that.friends);
}
})
}
//将用户列表初始化为一个map便于后续根据friendId得到friend
// friendList.map(friend => {
// this.friends[friend.uuid] = new Friend(friend.uuid, friend.name, friend.avatar);
// });
//查询并初始化与自己相关的群信息
// let groupList = restApi.findGroups(this.currentUser);
// //将群列表初始化为一个map方便后续根据groupId索引
// groupList.map(group => {
// this.groups[group.uuid] = new Group(group.uuid, group.name, group.avatar);
// });
};
//获取群成员
IMService.prototype.getGroupMembers = function (groupId) {
let members = restApi.findGroupMembers(groupId);
let membersMap = {};
members.map(item => {
membersMap[item.uuid] = item
});
return membersMap;
};
IMService.prototype.getGroupMessages = function (groupId) {
if (!this.groupMessages[groupId]) {
this.groupMessages[groupId] = {
sentMessages:[],
pendingMessages:[]
};
}
return this.groupMessages[groupId]
};
IMService.prototype.getPrivateMessages = function (friendId) {
if (!this.privateMessages[friendId]) {
this.privateMessages[friendId] = {
sentMessages:[],
pendingMessages:[]
};
}
return this.privateMessages[friendId]
};
//重置群聊未读消息
IMService.prototype.resetGroupUnReadMessage = function (group) {
this.groups[group.uuid].unReadMessage = 0;
this.onGroupListChange(this.groups);
};
//将好友的未读消息数字清零
IMService.prototype.resetFriendUnReadMessage = function (friend) {
if(friend && friend.uuid){
this.friends[friend.uuid].unReadMessage = 0;
}
this.onFriendListChange(this.friends);
};
//连接GoEasy
IMService.prototype.connectIM = function () {
//初始化IM相关的监听器
try {
this.initialIMListeners();
} catch (error) {
console.log(123)
}
try {
this.im.connect({
id: this.currentUser.uuid,
data: {
avatar: this.currentUser.avatar,
name: this.currentUser.name
}
}).then(() => {
console.log('连接成功')
//订阅与自己相关的群信息
this.subscribeGroupMessage();
//初始化好友们的在线状态
this.initialFriendOnlineStatus();
//订阅我的好友们的上下线信息
this.subscribeFriendsPresence();
}).catch(error => {
console.log('连接失败,请确保网络正常appkey和host正确code:' + error.code + " content:" + error.content);
this.connectIM()
});
} catch (error) {
console.log(12323)
}
};
//IM监听
IMService.prototype.initialIMListeners = function () {
this.im.on(GoEasyIM.EVENT.CONNECTED, () => {
console.log('连接成功.')
});
this.im.on(GoEasyIM.EVENT.DISCONNECTED, () => {
console.log('连接断开.')
});
//监听好友上下线
this.im.on(GoEasyIM.EVENT.USER_PRESENCE, (user) => {
console.log(user)
//更新好友在线状态
let onlineStatus = user.action == 'online' ? true : false;
let friend = this.friends[user.userId];
friend.online = onlineStatus;
//如果页面传入了相应的listener执行listener
this.onFriendListChange(this.friends);
});
//监听私聊消息
this.im.on(GoEasyIM.EVENT.PRIVATE_MESSAGE_RECEIVED, (message) => {
console.log(message)
//如果不是自己发的,朋友未读消息数 +1
if (message.senderId != this.currentUser.uuid) {
let friend = this.friends[message.senderId];
console.log(friend)
// return ;
let sorts = function (friends){
let paixu = function (a,b){
if(a.date > b.date){
return 0;
}else{
return 1;
}
}
friends.sort(paixu)
}
let that = this
if(!friend && friend == undefined){
const token = uni.getStorageSync('token');
console.log(token)
uni.request({
url:"https://dmmall.sdbairui.com/api/Specialci/getAtwillUserInfo",
data:{
userId:message.senderId
},
method:"POST",
header:{
"Authorization" : 'Bearer' + " " + token
},
success(res){
console.log(res)
that.friends[message.senderId] = new Friend(res.data.data.member_id, res.data.data.member_nickname, res.data.data.member_avatar);
friend = that.friends[message.senderId];
console.log(friend)
friend.unReadMessage++;
friend.text = message.type != "text" ? "其他消息" : message.payload.text
let time = new Date(message.timestamp)
friend.date = message.timestamp
friend.time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()
console.log(that.friends)
that.friendsarr = []
for(let i in that.friends){
console.log(i)
that.friendsarr.push(that.friends[i])
}
sorts(that.friendsarr)
let arr = []
for(let i in that.friends){
arr.push([that.friends[i].uuid,that.friends[i].time,that.friends[i].text,that.friends[i].date])
}
console.log(arr)
uni.setStorageSync('imlist',JSON.stringify(arr))
let value = uni.getStorageSync('imlist');
console.log(value)
that.onFriendListChange(that.friends);
}
})
}else{
console.log(friend)
friend.unReadMessage++;
friend.text = message.type != "text" ? "其他消息" : message.payload.text
let time = new Date(message.timestamp)
friend.date = message.timestamp
friend.time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()
console.log(this.friends)
that.friendsarr = []
for(let i in this.friends){
that.friendsarr.push(this.friends[i])
}
sorts(that.friendsarr)
let arr = []
for(let i in that.friends){
arr.push([that.friends[i].uuid,that.friends[i].time,that.friends[i].text,that.friends[i].date])
}
console.log(arr)
uni.setStorageSync('imlist',JSON.stringify(arr))
let value = uni.getStorageSync('imlist');
console.log(value)
this.onFriendListChange(this.friends);
}
// let value = uni.getStorageSync('imlist');
// value = JSON.parse(value)
// if(value.indexOf(message.senderId) == -1){
// value.unshift(message.senderId)
// }
// uni.setStorageSync('imlist',JSON.stringify(value))
}
//更新私聊消息记录
let friendId;
if (this.currentUser.uuid == message.senderId) {
friendId = message.receiverId;
} else {
friendId = message.senderId;
}
removePrivatePendingMessage(this, friendId, message);
let friendMessages = this.getPrivateMessages(friendId);
friendMessages.sentMessages.push(message);
//如果页面传入了相应的listener执行listener
this.onNewPrivateMessageReceive(friendId, message);
});
//监听群聊消息
this.im.on(GoEasyIM.EVENT.GROUP_MESSAGE_RECEIVED, (message) => {
let groupId = message.groupId;
//群未读消息+1
let group = this.groups[groupId];
group.unReadMessage++;
removeGroupPendingMessage(this, groupId, message);
//如果页面传入了相应的listener执行listener
this.onGroupListChange(this.groups);
//更新群聊消息记录
let groupMessages = this.getGroupMessages(groupId);
let sentMessages = groupMessages.sentMessages;
sentMessages.push(message);
//如果页面传入了相应的listener执行listener
this.onNewGroupMessageReceive(groupId, message);
})
};
//订阅群消息
IMService.prototype.subscribeGroupMessage = function () {
let groupIds = Object.keys(this.groups);
this.im.subscribeGroup(groupIds)
.then(() => {
console.log('订阅群消息成功')
})
.catch(error => {
console.log('订阅群消息失败')
console.log(error)
})
};
//初始化好友在线状态
IMService.prototype.initialFriendOnlineStatus = function () {
let friendIds = Object.keys(this.friends);
this.im.hereNow({
userIds: friendIds
}).then(result => {
let onlineFriends = result.content;
onlineFriends.map(user => {
let friend = this.friends[user.userId];
friend.online = true;
});
this.onFriendListChange(this.friends);
}).catch(error => {
console.log(error)
if (error.code == 401) {
console.log("获取在线用户失败您尚未开通用户在线状态请登录GoEasy查看应用详情里自助启用.");
}
})
};
//监听所有好友上下线
IMService.prototype.subscribeFriendsPresence = function () {
let friendIds = Object.keys(this.friends);
this.im.subscribeUserPresence(friendIds)
.then(() => {
console.log('监听好友上下线成功')
})
.catch(error => {
console.log(error);
if (error.code == 401) {
console.log("监听好友上下线失败您尚未开通用户状态提醒请登录GoEasy查看应用详情里自助启用.");
}
});
};
//加载单聊历史消息
IMService.prototype.loadPrivateHistoryMessage = function (friendId, timeStamp) {
this.im.history({
friendId: friendId,
lastTimestamp: timeStamp
}).then(result => {
let history = result.content;
let privateMessages = this.getPrivateMessages(friendId);
let friendMessages = privateMessages.sentMessages;
for (let i = history.length - 1; i >=0; i--) {
friendMessages.unshift(history[i])
}
//如果页面传入了相应的listener执行listener
this.onPrivateHistoryLoad(friendId, history);
}).catch(error => {
console.log(error);
if (error.code == 401) {
console.log("您尚未开通历史消息请登录GoEasy查看应用详情里自助启用.");
}
})
};
//发送私聊消息
IMService.prototype.sendPrivateTextMessage = function (friendId, text) {
let textMessage = this.im.createTextMessage({
text: text
});
this.sendPrivateMessage(friendId, textMessage);
};
//私聊图片消息
IMService.prototype.sendPrivateImageMessage = function (friendId, imageFile) {
let imageMessage = this.im.createImageMessage({
file: imageFile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendPrivateMessage(friendId, imageMessage);
};
//私聊视频消息
IMService.prototype.sendPrivateVideoMessage = function (friendId, videoFile) {
let videoMessage = this.im.createVideoMessage({
file: videoFile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendPrivateMessage(friendId, videoMessage);
};
IMService.prototype.sendPrivateAudioMessage = function (friendId, audiofile) {
let audioMessage = this.im.createAudioMessage({
file: audiofile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendPrivateMessage(friendId, audioMessage);
};
//发送私聊消息
IMService.prototype.sendPrivateMessage = function (friendId, message) {
//加入pendingMessage列表成功后将会被挪除
let privateMessages = this.getPrivateMessages(friendId);
privateMessages.pendingMessages.push(message);
//发送
this.im.sendPrivateMessage(friendId, message)
.then((res) => {
console.log(res)
})
.catch(e => {
console.log(e)
})
};
//发送群聊消息
IMService.prototype.sendGroupTextMessage = function (groupId, message) {
let textMessage = this.im.createTextMessage({
text:message
});
this.sendGroupMessage(groupId, textMessage);
};
//私聊图片消息
IMService.prototype.sendGroupImageMessage = function (groupId, imageFile) {
let imageMessage = this.im.createImageMessage({
file: imageFile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendGroupMessage(groupId, imageMessage);
};
//私聊视频消息
IMService.prototype.sendGroupVideoMessage = function (groupId, videoFile) {
let videoMessage = this.im.createVideoMessage({
file: videoFile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendGroupMessage(groupId, videoMessage);
};
IMService.prototype.sendGroupAudioMessage = function (groupId, audioFile) {
let audioMessage = this.im.createAudioMessage({
file: audioFile,
onProgress :function (progress) {
console.log(progress)
}
});
this.sendGroupMessage(groupId, audioMessage);
};
IMService.prototype.sendGroupMessage =function(groupId, groupMessage) {
//先放入Pending列表待成功后挪除
let groupMessages = this.getGroupMessages(groupId);
let pendingMessages = groupMessages.pendingMessages;
pendingMessages.push(groupMessage)
this.im.sendGroupMessage(groupId, groupMessage)
.then((res) => {
console.log(res)
})
.catch(e => {
console.log(e)
})
}
//群聊历史消息
IMService.prototype.loadGroupHistoryMessage = function (groupId, timeStamp) {
this.im.history({
groupId: groupId,
lastTimestamp: timeStamp
}).then(result => {
let history = result.content;
let groupMessages = this.getGroupMessages(groupId);
let sentGroupMessages = groupMessages.sentMessages;
for (let i = history.length - 1; i >= 0; i--) {
sentGroupMessages.unshift(history[i]);
}
this.onGroupHistoryLoad(groupId, history);
}).catch(error => {
console.log(error)
if (error.code == 401) {
console.log("您尚未开通历史消息请登录GoEasy查看应用详情里自助启用.");
}
})
};
IMService.prototype.disconnect = function () {
this.im.disconnect()
};
function removePrivatePendingMessage(imService,friendId, message){
let privateMessages = imService.getPrivateMessages(friendId);
let pendingMessages = privateMessages.pendingMessages;
let pendingMessageIndex = pendingMessages.findIndex(item => item.messageId == message.messageId);
if(pendingMessageIndex > -1) {
pendingMessages.splice(pendingMessageIndex,1);
}
}
function removeGroupPendingMessage(imService,groupId, message){
let groupMessages = imService.getGroupMessages(groupId);
let pendingMessages = groupMessages.pendingMessages;
let pendingMessageIndex = pendingMessages.findIndex(item => item.messageId == message.messageId);
if(pendingMessageIndex > -1) {
pendingMessages.splice(pendingMessageIndex,1);
}
}
export default IMService;

79
static/restapi.js Normal file
View File

@ -0,0 +1,79 @@
//用户数据示例
let users = [
{
"uuid": "08c0a6ec-a42b-47b2-bb1e-15e0f5f9a19a",
"name": "Mattie",
"password": "123",
"avatar": '../../static/images/Avatar-1.png'
},
{
"uuid": "3bb179af-bcc5-4fe0-9dac-c05688484649",
"name": "Wallace",
"password": "123",
"avatar": '../../static/images/Avatar-2.png'
},
{
"uuid": "fdee46b0-4b01-4590-bdba-6586d7617f95",
"name": "Tracy",
"password": "123",
"avatar": '../../static/images/Avatar-3.png'
},
{
"uuid": "33c3693b-dbb0-4bc9-99c6-fa77b9eb763f",
"name": "Juanita",
"password": "123",
"avatar": '../../static/images/Avatar-4.png'
}
];
//群数据示例
let groups = [
{
"uuid": "group-a42b-47b2-bb1e-15e0f5f9a19a",
"name": "群1",
"userList": ['08c0a6ec-a42b-47b2-bb1e-15e0f5f9a19a', '3bb179af-bcc5-4fe0-9dac-c05688484649', 'fdee46b0-4b01-4590-bdba-6586d7617f95', '33c3693b-dbb0-4bc9-99c6-fa77b9eb763f']
},
{
"uuid": "group-4b01-4590-bdba-6586d7617f95",
"name": "群2",
"userList": ['08c0a6ec-a42b-47b2-bb1e-15e0f5f9a19a', 'fdee46b0-4b01-4590-bdba-6586d7617f95', '33c3693b-dbb0-4bc9-99c6-fa77b9eb763f']
},
{
"uuid": "group-dbb0-4bc9-99c6-fa77b9eb763f",
"name": "群3",
"userList": ['08c0a6ec-a42b-47b2-bb1e-15e0f5f9a19a', '3bb179af-bcc5-4fe0-9dac-c05688484649']
}
];
function RestApi() {
}
RestApi.prototype.findFriends = function (user) {
var friendList = users.filter(v => v.uuid != user.uuid);
return friendList;
}
RestApi.prototype.findGroups = function (user) {
var groupList = groups.filter(v => v.userList.find(id => id == user.uuid));
return groupList;
}
RestApi.prototype.findUser = function (username, password) {
var user = users.find(user => (user.name == username && user.password == password))
return user;
}
RestApi.prototype.findGroupMembers = function (groupId) {
let members = [];
let group = groups.find(v => v.uuid == groupId);
users.map(user => {
if (group.userList.find(v => v == user.uuid)) {
members.push(user)
}
});
return members;
}
export default new RestApi();