提交后台前端基础框架
This commit is contained in:
45
Backend/src/plugins/recorder/record-sdk.js
Executable file
45
Backend/src/plugins/recorder/record-sdk.js
Executable file
@@ -0,0 +1,45 @@
|
||||
import Recorder from './recorder'
|
||||
|
||||
export default class Record {
|
||||
startRecord(param) {
|
||||
let self = this
|
||||
try {
|
||||
Recorder.get(rec => {
|
||||
if (rec.error) return param.error(rec.error)
|
||||
self.recorder = rec
|
||||
self.recorder.start()
|
||||
param.success('开始录音')
|
||||
})
|
||||
} catch (e) {
|
||||
param.error('开始录音失败' + e)
|
||||
}
|
||||
}
|
||||
|
||||
stopRecord(param) {
|
||||
let self = this
|
||||
try {
|
||||
let blobData = self.recorder.getBlob()
|
||||
param.success(blobData)
|
||||
} catch (e) {
|
||||
param.error('结束录音失败' + e)
|
||||
}
|
||||
}
|
||||
|
||||
play(audio) {
|
||||
let self = this
|
||||
try {
|
||||
self.recorder.play(audio)
|
||||
} catch (e) {
|
||||
console.error('录音播放失败' + e)
|
||||
}
|
||||
}
|
||||
|
||||
clear(audio) {
|
||||
let self = this
|
||||
try {
|
||||
self.recorder.clear(audio)
|
||||
} catch (e) {
|
||||
console.error('清空录音失败' + e)
|
||||
}
|
||||
}
|
||||
}
|
||||
239
Backend/src/plugins/recorder/recorder.js
Executable file
239
Backend/src/plugins/recorder/recorder.js
Executable file
@@ -0,0 +1,239 @@
|
||||
export default class Recorder {
|
||||
constructor(stream, config) {
|
||||
//兼容
|
||||
window.URL = window.URL || window.webkitURL
|
||||
navigator.getUserMedia =
|
||||
navigator.getUserMedia ||
|
||||
navigator.webkitGetUserMedia ||
|
||||
navigator.mozGetUserMedia ||
|
||||
navigator.msGetUserMedia
|
||||
|
||||
config = config || {}
|
||||
config.sampleBits = config.sampleBits || 16 //采样数位 8, 16
|
||||
config.sampleRate = config.sampleRate || 8000 //采样率(1/6 44100)
|
||||
|
||||
this.context = new (window.webkitAudioContext || window.AudioContext)()
|
||||
this.audioInput = this.context.createMediaStreamSource(stream)
|
||||
this.createScript =
|
||||
this.context.createScriptProcessor || this.context.createJavaScriptNode
|
||||
this.recorder = this.createScript.apply(this.context, [4096, 1, 1])
|
||||
|
||||
this.audioData = {
|
||||
size: 0, //录音文件长度
|
||||
buffer: [], //录音缓存
|
||||
inputSampleRate: this.context.sampleRate, //输入采样率
|
||||
inputSampleBits: 16, //输入采样数位 8, 16
|
||||
outputSampleRate: config.sampleRate, //输出采样率
|
||||
oututSampleBits: config.sampleBits, //输出采样数位 8, 16
|
||||
input: function(data) {
|
||||
this.buffer.push(new Float32Array(data))
|
||||
this.size += data.length
|
||||
},
|
||||
compress: function() {
|
||||
//合并压缩
|
||||
//合并
|
||||
let data = new Float32Array(this.size)
|
||||
let offset = 0
|
||||
for (let i = 0; i < this.buffer.length; i++) {
|
||||
data.set(this.buffer[i], offset)
|
||||
offset += this.buffer[i].length
|
||||
}
|
||||
//压缩
|
||||
let compression = parseInt(this.inputSampleRate / this.outputSampleRate)
|
||||
let length = data.length / compression
|
||||
let result = new Float32Array(length)
|
||||
let index = 0,
|
||||
j = 0
|
||||
while (index < length) {
|
||||
result[index] = data[j]
|
||||
j += compression
|
||||
index++
|
||||
}
|
||||
return result
|
||||
},
|
||||
encodeWAV: function() {
|
||||
let sampleRate = Math.min(this.inputSampleRate, this.outputSampleRate)
|
||||
let sampleBits = Math.min(this.inputSampleBits, this.oututSampleBits)
|
||||
let bytes = this.compress()
|
||||
let dataLength = bytes.length * (sampleBits / 8)
|
||||
let buffer = new ArrayBuffer(44 + dataLength)
|
||||
let data = new DataView(buffer)
|
||||
|
||||
let channelCount = 1 //单声道
|
||||
let offset = 0
|
||||
|
||||
let writeString = function(str) {
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
data.setUint8(offset + i, str.charCodeAt(i))
|
||||
}
|
||||
}
|
||||
|
||||
// 资源交换文件标识符
|
||||
writeString('RIFF')
|
||||
offset += 4
|
||||
// 下个地址开始到文件尾总字节数,即文件大小-8
|
||||
data.setUint32(offset, 36 + dataLength, true)
|
||||
offset += 4
|
||||
// WAV文件标志
|
||||
writeString('WAVE')
|
||||
offset += 4
|
||||
// 波形格式标志
|
||||
writeString('fmt ')
|
||||
offset += 4
|
||||
// 过滤字节,一般为 0x10 = 16
|
||||
data.setUint32(offset, 16, true)
|
||||
offset += 4
|
||||
// 格式类别 (PCM形式采样数据)
|
||||
data.setUint16(offset, 1, true)
|
||||
offset += 2
|
||||
// 通道数
|
||||
data.setUint16(offset, channelCount, true)
|
||||
offset += 2
|
||||
// 采样率,每秒样本数,表示每个通道的播放速度
|
||||
data.setUint32(offset, sampleRate, true)
|
||||
offset += 4
|
||||
// 波形数据传输率 (每秒平均字节数) 单声道×每秒数据位数×每样本数据位/8
|
||||
data.setUint32(
|
||||
offset,
|
||||
channelCount * sampleRate * (sampleBits / 8),
|
||||
true
|
||||
)
|
||||
offset += 4
|
||||
// 快数据调整数 采样一次占用字节数 单声道×每样本的数据位数/8
|
||||
data.setUint16(offset, channelCount * (sampleBits / 8), true)
|
||||
offset += 2
|
||||
// 每样本数据位数
|
||||
data.setUint16(offset, sampleBits, true)
|
||||
offset += 2
|
||||
// 数据标识符
|
||||
writeString('data')
|
||||
offset += 4
|
||||
// 采样数据总数,即数据总大小-44
|
||||
data.setUint32(offset, dataLength, true)
|
||||
offset += 4
|
||||
// 写入采样数据
|
||||
if (sampleBits === 8) {
|
||||
for (let i = 0; i < bytes.length; i++, offset++) {
|
||||
let s = Math.max(-1, Math.min(1, bytes[i]))
|
||||
let val = s < 0 ? s * 0x8000 : s * 0x7fff
|
||||
val = parseInt(255 / (65535 / (val + 32768)))
|
||||
data.setInt8(offset, val, true)
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < bytes.length; i++, offset += 2) {
|
||||
let s = Math.max(-1, Math.min(1, bytes[i]))
|
||||
data.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true)
|
||||
}
|
||||
}
|
||||
return new Blob([data], {
|
||||
type: 'audio/wav',
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//开始录音
|
||||
start() {
|
||||
this.audioInput.connect(this.recorder)
|
||||
this.recorder.connect(this.context.destination)
|
||||
|
||||
//音频采集
|
||||
let self = this
|
||||
this.recorder.onaudioprocess = function(e) {
|
||||
self.audioData.input(e.inputBuffer.getChannelData(0))
|
||||
}
|
||||
}
|
||||
|
||||
//停止
|
||||
stop() {
|
||||
this.recorder.disconnect()
|
||||
}
|
||||
|
||||
//获取音频文件
|
||||
getBlob() {
|
||||
this.stop()
|
||||
return this.audioData.encodeWAV()
|
||||
}
|
||||
|
||||
//回放
|
||||
play(audio) {
|
||||
audio.src = window.URL.createObjectURL(this.getBlob())
|
||||
}
|
||||
|
||||
//清理缓存的录音数据
|
||||
clear(audio) {
|
||||
this.audioData.buffer = []
|
||||
this.audioData.size = 0
|
||||
audio.src = ''
|
||||
}
|
||||
|
||||
static checkError(e) {
|
||||
const { name } = e
|
||||
let errorMsg = ''
|
||||
switch (name) {
|
||||
case 'AbortError':
|
||||
errorMsg = '录音设备无法被使用'
|
||||
break
|
||||
case 'NotAllowedError':
|
||||
errorMsg = '用户已禁止网页调用录音设备'
|
||||
break
|
||||
case 'PermissionDeniedError':
|
||||
errorMsg = '用户已禁止网页调用录音设备'
|
||||
break // 用户拒绝
|
||||
case 'NotFoundError':
|
||||
errorMsg = '录音设备未找到'
|
||||
break
|
||||
case 'DevicesNotFoundError':
|
||||
errorMsg = '录音设备未找到'
|
||||
break
|
||||
case 'NotReadableError':
|
||||
errorMsg = '录音设备无法使用'
|
||||
break
|
||||
case 'NotSupportedError':
|
||||
errorMsg = '不支持录音功能'
|
||||
break
|
||||
case 'MandatoryUnsatisfiedError':
|
||||
errorMsg = '无法发现指定的硬件设备'
|
||||
break
|
||||
default:
|
||||
errorMsg = '录音调用错误'
|
||||
break
|
||||
}
|
||||
return {
|
||||
error: errorMsg,
|
||||
}
|
||||
}
|
||||
|
||||
static get(callback, config) {
|
||||
if (callback) {
|
||||
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
||||
navigator.mediaDevices
|
||||
.getUserMedia({
|
||||
audio: true,
|
||||
video: false,
|
||||
})
|
||||
.then(stream => {
|
||||
let rec = new Recorder(stream, config)
|
||||
callback(rec)
|
||||
})
|
||||
.catch(e => {
|
||||
callback(Recorder.checkError(e))
|
||||
})
|
||||
} else {
|
||||
navigator
|
||||
.getUserMedia({
|
||||
audio: true,
|
||||
video: false,
|
||||
})
|
||||
.then(stream => {
|
||||
let rec = new Recorder(stream, config)
|
||||
callback(rec)
|
||||
})
|
||||
.catch(e => {
|
||||
// Recorder.checkError(e)
|
||||
callback(Recorder.checkError(e))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
76
Backend/src/plugins/sms-lock.js
Executable file
76
Backend/src/plugins/sms-lock.js
Executable file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 短信倒计时锁
|
||||
*/
|
||||
class SmsLock {
|
||||
// 发送倒计时默认60秒
|
||||
time = null
|
||||
|
||||
// 计时器
|
||||
timer = null
|
||||
|
||||
// 倒计时默认60秒
|
||||
lockTime = 60
|
||||
|
||||
// 锁标记名称
|
||||
lockName = ''
|
||||
|
||||
/**
|
||||
* 实例化构造方法
|
||||
*
|
||||
* @param {String} purpose 唯一标识
|
||||
* @param {Number} time
|
||||
*/
|
||||
constructor(purpose, lockTime = 60) {
|
||||
this.lockTime = lockTime
|
||||
this.lockName = `SMSLOCK_${purpose}`
|
||||
|
||||
this.init()
|
||||
}
|
||||
|
||||
// 开始计时
|
||||
start(time = null) {
|
||||
this.time = time == null || time >= this.lockTime ? this.lockTime : time
|
||||
|
||||
this.clearInterval()
|
||||
|
||||
this.timer = setInterval(() => {
|
||||
if (this.time == 0) {
|
||||
this.clearInterval()
|
||||
this.time = null
|
||||
localStorage.removeItem(this.lockName)
|
||||
return
|
||||
}
|
||||
|
||||
this.time--
|
||||
|
||||
// 设置本地缓存
|
||||
localStorage.setItem(this.lockName, this.getTime() + this.time)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
// 页面刷新初始化
|
||||
init() {
|
||||
let result = localStorage.getItem(this.lockName)
|
||||
|
||||
if (result == null) return
|
||||
|
||||
let time = result - this.getTime()
|
||||
if (time > 0) {
|
||||
this.start(time)
|
||||
} else {
|
||||
localStorage.removeItem(this.lockName)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前时间
|
||||
getTime() {
|
||||
return Math.floor(new Date().getTime() / 1000)
|
||||
}
|
||||
|
||||
// 清除计时器
|
||||
clearInterval() {
|
||||
clearInterval(this.timer)
|
||||
}
|
||||
}
|
||||
|
||||
export default SmsLock
|
||||
51
Backend/src/plugins/socket/event/app-message-event.js
Executable file
51
Backend/src/plugins/socket/event/app-message-event.js
Executable file
@@ -0,0 +1,51 @@
|
||||
import store from '@/store'
|
||||
import { Notification } from 'element-ui'
|
||||
|
||||
/**
|
||||
* 处理App消息
|
||||
*/
|
||||
class AppMessageEvent {
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
constructor() {
|
||||
this.$notify = Notification
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户的ID
|
||||
*/
|
||||
get UserId() {
|
||||
return store.state.user.uid
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断消息是否来自当前对话
|
||||
*
|
||||
* @param {Number} source 聊天消息类型(1:私聊,2:群聊)
|
||||
* @param {Number} receive_id 接收者ID
|
||||
* @param {Number} user_id 发送者ID
|
||||
*/
|
||||
isChatting(source, receive_id, user_id) {
|
||||
if (source != store.state.dialogue.source) {
|
||||
return false
|
||||
} else if (source == 1) {
|
||||
if (store.state.dialogue.receive_id == receive_id) {
|
||||
return true
|
||||
} else if (store.state.dialogue.receive_id == user_id) {
|
||||
return true
|
||||
}
|
||||
} else if (source == 2) {
|
||||
if (
|
||||
store.state.dialogue.receive_id == receive_id ||
|
||||
store.state.dialogue.receive_id == this.UserId
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export default AppMessageEvent
|
||||
47
Backend/src/plugins/socket/event/friend-apply-event.js
Executable file
47
Backend/src/plugins/socket/event/friend-apply-event.js
Executable file
@@ -0,0 +1,47 @@
|
||||
import AppMessageEvent from './app-message-event'
|
||||
import store from '@/store'
|
||||
import router from '@/router'
|
||||
|
||||
/**
|
||||
* 好友邀请消息处理
|
||||
*/
|
||||
class FriendApplyEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
store.commit('INCR_APPLY_NUM')
|
||||
|
||||
this.$notify({
|
||||
title: '好友申请',
|
||||
dangerouslyUseHTMLString: true,
|
||||
message: `<p style="color:red;margin-top:10px;">您有一条好友申请消息,请注意查收...</p>`,
|
||||
duration: 0,
|
||||
type: 'info',
|
||||
customClass: 'pointer',
|
||||
onClick: function() {
|
||||
store.commit('SET_APPLY_NUM', 0)
|
||||
router.push({
|
||||
path: '/contacts/apply',
|
||||
query: { t: new Date().getTime() },
|
||||
})
|
||||
this.close()
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default FriendApplyEvent
|
||||
31
Backend/src/plugins/socket/event/group-join-event.js
Executable file
31
Backend/src/plugins/socket/event/group-join-event.js
Executable file
@@ -0,0 +1,31 @@
|
||||
import AppMessageEvent from './app-message-event'
|
||||
|
||||
/**
|
||||
* 好友邀请消息处理
|
||||
*/
|
||||
class GroupJoinEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
this.$notify({
|
||||
message: '您有一条入群消息通知,请注意查收...',
|
||||
duration: 5000,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default GroupJoinEvent
|
||||
37
Backend/src/plugins/socket/event/keyboard-event.js
Executable file
37
Backend/src/plugins/socket/event/keyboard-event.js
Executable file
@@ -0,0 +1,37 @@
|
||||
import AppMessageEvent from './app-message-event'
|
||||
import store from '@/store'
|
||||
|
||||
/**
|
||||
* 好友邀请消息处理
|
||||
*/
|
||||
class KeyboardEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
if (store.state.dialogue.index_name == null) return false
|
||||
|
||||
this.isShow() && store.commit('UPDATE_KEYBOARD_EVENT')
|
||||
}
|
||||
|
||||
isShow() {
|
||||
let [source, receive_id] = store.state.dialogue.index_name.split('_')
|
||||
|
||||
return !(source == 2 || receive_id != this.resource.send_user)
|
||||
}
|
||||
}
|
||||
|
||||
export default KeyboardEvent
|
||||
31
Backend/src/plugins/socket/event/login-event.js
Executable file
31
Backend/src/plugins/socket/event/login-event.js
Executable file
@@ -0,0 +1,31 @@
|
||||
import AppMessageEvent from './app-message-event'
|
||||
import store from '@/store'
|
||||
/**
|
||||
* 好友邀请消息处理
|
||||
*/
|
||||
class LoginEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
store.dispatch('ACT_UPDATE_FRIEND_STATUS', {
|
||||
status: this.resource.status,
|
||||
friendId: parseInt(this.resource.user_id),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default LoginEvent
|
||||
49
Backend/src/plugins/socket/event/revoke-event.js
Executable file
49
Backend/src/plugins/socket/event/revoke-event.js
Executable file
@@ -0,0 +1,49 @@
|
||||
import AppMessageEvent from './app-message-event'
|
||||
import store from '@/store'
|
||||
|
||||
/**
|
||||
* 好友邀请消息处理
|
||||
*/
|
||||
class RevokeEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
if (
|
||||
!this.isChatting(
|
||||
this.resource.source,
|
||||
this.resource.receive_id,
|
||||
this.resource.user_id
|
||||
)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
let record_id = this.resource.record_id
|
||||
let index = store.state.dialogue.records.findIndex(
|
||||
item => item.id === record_id
|
||||
)
|
||||
|
||||
store.commit('UPDATE_DIALOGUE', {
|
||||
index,
|
||||
item: {
|
||||
is_revoke: 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default RevokeEvent
|
||||
232
Backend/src/plugins/socket/event/talk-event.js
Executable file
232
Backend/src/plugins/socket/event/talk-event.js
Executable file
@@ -0,0 +1,232 @@
|
||||
import Vue from 'vue'
|
||||
import store from '@/store'
|
||||
import router from '@/router'
|
||||
import AppMessageEvent from './app-message-event'
|
||||
import { parseTime } from '@/utils/functions'
|
||||
import { formateTalkItem, findTalkIndex } from '@/utils/talk'
|
||||
import { ServeClearTalkUnreadNum, ServeCreateTalkList } from '@/api/chat'
|
||||
|
||||
/**
|
||||
* 聊天消息处理
|
||||
*/
|
||||
class TalkEvent extends AppMessageEvent {
|
||||
/**
|
||||
* @var resource 资源
|
||||
*/
|
||||
resource
|
||||
|
||||
/**
|
||||
* 初始化构造方法
|
||||
*
|
||||
* @param {Object} resource Socket消息
|
||||
*/
|
||||
constructor(resource) {
|
||||
super()
|
||||
|
||||
this.resource = resource
|
||||
}
|
||||
|
||||
handle() {
|
||||
const indexName = this.getIndexName()
|
||||
if (!this.isTalkPage()) {
|
||||
if (this.resource.send_user != this.UserId) {
|
||||
this.showMessageNocice(indexName)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const index = findTalkIndex(indexName)
|
||||
if (index == -1) {
|
||||
// 判断消息来源是否在对话列表中...
|
||||
this.loadTalkItem()
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
this.isChatting(
|
||||
this.resource.source_type,
|
||||
this.resource.receive_user,
|
||||
this.resource.send_user
|
||||
)
|
||||
) {
|
||||
this.updateTalkRecord(index)
|
||||
} else {
|
||||
this.updateTalkItem(index)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示消息提示
|
||||
*
|
||||
* @param {String} index_name
|
||||
* @returns
|
||||
*/
|
||||
showMessageNocice(index_name) {
|
||||
let tag = this.resource.data.source == 1 ? '[私信]' : '[群聊]'
|
||||
let group_name = this.resource.data.group_name || '好友'
|
||||
let nickname = this.resource.data.nickname || this.resource.data.group_name
|
||||
let content = this.getTalkText()
|
||||
|
||||
this.$notify({
|
||||
title: `${tag} 聊天通知`,
|
||||
message: `「${group_name}」@${nickname} : ${content}`,
|
||||
duration: 3000000,
|
||||
customClass: 'talk-notify pointer',
|
||||
onClick: function() {
|
||||
sessionStorage.setItem('send_message_index_name', index_name)
|
||||
router.push('/')
|
||||
this.close()
|
||||
},
|
||||
position: 'bottom-right',
|
||||
})
|
||||
|
||||
store.commit('INCR_UNREAD_NUM')
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新对话记录
|
||||
*
|
||||
* @param {Number} index 聊天列表的索引
|
||||
*/
|
||||
updateTalkRecord(index) {
|
||||
let record = this.resource.data
|
||||
record.float =
|
||||
record.user_id == 0
|
||||
? 'center'
|
||||
: record.user_id == this.UserId
|
||||
? 'right'
|
||||
: 'left'
|
||||
|
||||
store.commit('PUSH_DIALOGUE', record)
|
||||
|
||||
// 获取聊天面板元素节点
|
||||
let elChatPanel = document.getElementById('lumenChatPanel')
|
||||
|
||||
// 判断的滚动条是否在底部
|
||||
let isBottom =
|
||||
Math.ceil(elChatPanel.scrollTop) + elChatPanel.clientHeight >=
|
||||
elChatPanel.scrollHeight
|
||||
|
||||
if (isBottom || record.user_id == this.UserId) {
|
||||
Vue.nextTick(() => {
|
||||
// 更新聊天面板滚动条置底
|
||||
elChatPanel.scrollTop = elChatPanel.scrollHeight
|
||||
})
|
||||
} else {
|
||||
store.commit('SET_TLAK_UNREAD_MESSAGE', {
|
||||
content: this.getTalkText(),
|
||||
nickname: record.nickname,
|
||||
})
|
||||
}
|
||||
|
||||
store.commit('UPDATE_TALK_ITEM', {
|
||||
index,
|
||||
item: {
|
||||
msg_text: this.getTalkText(),
|
||||
updated_at: parseTime(new Date()),
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
this.resource.data.source == 1 &&
|
||||
this.UserId !== this.resource.data.user_id
|
||||
) {
|
||||
// 更新未读消息
|
||||
ServeClearTalkUnreadNum({
|
||||
type: store.state.dialogue.source,
|
||||
receive: store.state.dialogue.receive_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新对话列表记录
|
||||
*
|
||||
* @param {Number} index 聊天列表的索引
|
||||
*/
|
||||
updateTalkItem(index) {
|
||||
store.commit('INCR_UNREAD_NUM')
|
||||
if (index == -1) {
|
||||
// 对话列表不存在需请求后端...
|
||||
return
|
||||
}
|
||||
|
||||
store.commit('UPDATE_TALK_MESSAGE', {
|
||||
index,
|
||||
item: {
|
||||
msg_text: this.getTalkText(),
|
||||
updated_at: parseTime(new Date()),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取聊天列表左侧的对话信息
|
||||
*/
|
||||
getTalkText() {
|
||||
let text = this.resource.data.content
|
||||
switch (this.resource.data.msg_type) {
|
||||
case 2:
|
||||
let file_type = this.resource.data.file.file_type
|
||||
text = file_type == 1 ? '[图片消息]' : '[文件消息]'
|
||||
break
|
||||
case 4:
|
||||
text = '[会话记录]'
|
||||
break
|
||||
case 5:
|
||||
text = '[代码消息]'
|
||||
break
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断用户是否打开对话页
|
||||
*/
|
||||
isTalkPage() {
|
||||
let path = router.currentRoute.fullPath
|
||||
return !(path != '/message' && path != '/')
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过消息获取消息对应的对话索引
|
||||
*/
|
||||
getIndexName() {
|
||||
let message = this.resource
|
||||
if (
|
||||
message.source_type == 2 ||
|
||||
(message.source_type == 1 && message.send_user == this.UserId)
|
||||
) {
|
||||
return `${message.source_type}_${message.receive_user}`
|
||||
}
|
||||
|
||||
return `${message.source_type}_${message.send_user}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载对接节点
|
||||
*/
|
||||
loadTalkItem() {
|
||||
let receive_id = this.resource.send_user
|
||||
let type = this.resource.source_type
|
||||
|
||||
if (type == 2 || this.resource.send_user == this.UserId) {
|
||||
receive_id = this.resource.receive_user
|
||||
}
|
||||
|
||||
ServeCreateTalkList({
|
||||
type,
|
||||
receive_id,
|
||||
}).then(({ code, data }) => {
|
||||
if (code == 200) {
|
||||
let { talkItem } = data
|
||||
talkItem.unread_num++
|
||||
store.commit('INSERT_TALK_ITEM', formateTalkItem(talkItem))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default TalkEvent
|
||||
239
Backend/src/plugins/socket/ws-socket.js
Executable file
239
Backend/src/plugins/socket/ws-socket.js
Executable file
@@ -0,0 +1,239 @@
|
||||
class WsSocket {
|
||||
/**
|
||||
* Websocket 连接
|
||||
*
|
||||
* @var Websocket
|
||||
*/
|
||||
connect
|
||||
|
||||
/**
|
||||
* 服务器连接地址
|
||||
*/
|
||||
url
|
||||
|
||||
/**
|
||||
* 配置信息
|
||||
*
|
||||
* @var Object
|
||||
*/
|
||||
config = {
|
||||
heartbeat: {
|
||||
enabled: true, // 是否发送心跳包
|
||||
time: 10000, // 心跳包发送间隔时长
|
||||
setInterval: null, // 心跳包计时器
|
||||
},
|
||||
reconnect: {
|
||||
lockReconnect: false,
|
||||
setTimeout: null, // 计时器对象
|
||||
time: 5000, // 重连间隔时间
|
||||
number: 50, // 重连次数
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义绑定消息事件
|
||||
*
|
||||
* @var Array
|
||||
*/
|
||||
onCallBacks = []
|
||||
|
||||
/**
|
||||
* 创建 WsSocket 的实例
|
||||
*
|
||||
* @param {Function} urlCallBack url闭包函数
|
||||
* @param {Object} events 原生 WebSocket 绑定事件
|
||||
*/
|
||||
constructor(urlCallBack, events) {
|
||||
this.urlCallBack = urlCallBack
|
||||
|
||||
// 定义 WebSocket 原生方法
|
||||
this.events = Object.assign(
|
||||
{
|
||||
onError: evt => {},
|
||||
onOpen: evt => {},
|
||||
onClose: evt => {},
|
||||
},
|
||||
events
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件绑定
|
||||
*
|
||||
* @param {String} event 事件名
|
||||
* @param {Function} callBack 回调方法
|
||||
*/
|
||||
on(event, callBack) {
|
||||
this.onCallBacks[event] = callBack
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 WebSocket
|
||||
*/
|
||||
loadSocket() {
|
||||
// 判断当前是否已经连接
|
||||
if (this.connect != null) {
|
||||
this.connect.close()
|
||||
this.connect = null
|
||||
}
|
||||
|
||||
this.url = this.urlCallBack()
|
||||
const connect = new WebSocket(this.url)
|
||||
connect.onerror = this.onError.bind(this)
|
||||
connect.onopen = this.onOpen.bind(this)
|
||||
connect.onmessage = this.onMessage.bind(this)
|
||||
connect.onclose = this.onClose.bind(this)
|
||||
|
||||
this.connect = connect
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接 Websocket
|
||||
*/
|
||||
connection() {
|
||||
this.loadSocket()
|
||||
}
|
||||
|
||||
/**
|
||||
* 掉线重连 Websocket
|
||||
*/
|
||||
reconnect() {
|
||||
let reconnect = this.config.reconnect
|
||||
if (reconnect.lockReconnect || reconnect.number == 0) {
|
||||
return
|
||||
}
|
||||
|
||||
this.config.reconnect.lockReconnect = true
|
||||
|
||||
// 没连接上会一直重连,设置延迟避免请求过多
|
||||
reconnect.setTimeout && clearTimeout(reconnect.setTimeout)
|
||||
|
||||
this.config.reconnect.setTimeout = setTimeout(() => {
|
||||
this.connection()
|
||||
|
||||
this.config.reconnect.lockReconnect = false
|
||||
this.config.reconnect.number--
|
||||
|
||||
console.log(
|
||||
`网络连接已断开,正在尝试重新连接(${this.config.reconnect.number})...`
|
||||
)
|
||||
}, reconnect.time)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析接受的消息
|
||||
*
|
||||
* @param {Object} evt Websocket 消息
|
||||
*/
|
||||
onParse(evt) {
|
||||
let [eventType, message] = JSON.parse(evt.data)
|
||||
|
||||
return {
|
||||
event: eventType,
|
||||
data: message,
|
||||
orginData: evt.data,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开连接
|
||||
*
|
||||
* @param {Object} evt Websocket 消息
|
||||
*/
|
||||
onOpen(evt) {
|
||||
this.events.onOpen(evt)
|
||||
|
||||
if (this.config.heartbeat.enabled) {
|
||||
this.heartbeat()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭连接
|
||||
*
|
||||
* @param {Object} evt Websocket 消息
|
||||
*/
|
||||
onClose(evt) {
|
||||
if (this.config.heartbeat.enabled) {
|
||||
clearInterval(this.config.heartbeat.setInterval)
|
||||
}
|
||||
|
||||
if (evt.code == 1006) {
|
||||
this.reconnect()
|
||||
}
|
||||
|
||||
this.events.onClose(evt)
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接错误
|
||||
*
|
||||
* @param {Object} evt Websocket 消息
|
||||
*/
|
||||
onError(evt) {
|
||||
this.events.onError(evt)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收消息
|
||||
*
|
||||
* @param {Object} evt Websocket 消息
|
||||
*/
|
||||
onMessage(evt) {
|
||||
let result = this.onParse(evt)
|
||||
|
||||
// 判断消息事件是否被绑定
|
||||
if (this.onCallBacks.hasOwnProperty(result.event)) {
|
||||
this.onCallBacks[result.event](result.data, result.orginData)
|
||||
} else {
|
||||
console.warn(`WsSocket 消息事件[${result.event}]未绑定...`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket心跳检测
|
||||
*/
|
||||
heartbeat() {
|
||||
this.config.heartbeat.setInterval = setInterval(() => {
|
||||
this.connect.send('PING')
|
||||
}, this.config.heartbeat.time)
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天发送数据
|
||||
*
|
||||
* @param {Object} mesage
|
||||
*/
|
||||
send(mesage) {
|
||||
this.connect.send(JSON.stringify(mesage))
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭连接
|
||||
*/
|
||||
close(){
|
||||
this.connect.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送消息
|
||||
*
|
||||
* @param {String} event 事件名
|
||||
* @param {Object} data 数据
|
||||
*/
|
||||
emit(event, data) {
|
||||
if (this.connect && this.connect.readyState === 1) {
|
||||
this.connect.send(
|
||||
JSON.stringify({
|
||||
event,
|
||||
data,
|
||||
})
|
||||
)
|
||||
} else {
|
||||
console.error('WebSocket 连接已关闭...', this.connect)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default WsSocket
|
||||
Reference in New Issue
Block a user