Commit e5e57fc6 by liimin

新增添加待上传指令

1 parent b107158c
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-04 19:42:00
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:35:46
* @FilePath: \gl_tape\utils\recordManager\Record.js
*/
import store from '../../store/index'
import utils from '../utils'
import { FileStatus } from '../common/constants'
class Record {
key = 'preRecord'
timer = null
timer_interval = 60 * 1000
record = null
path = ''
newRecord = null
constructor(record) {
this.newRecord = record
this.recordManager = uni.$recordManager
this.dbManager = uni.$dbManager
}
getRecords() {
return this.recordManager.getRecords(this.key)
}
getRecord() {
return this.recordManager.getRecord(this.key)
}
addRecord(record = this.record) {
uni.$logger.local.info('〖接待记录Record〗 == 新增记录' + JSON.stringify(record))
this.recordManager.addRecord(record, this.key)
}
updateRecord(record = this.record) {
uni.$logger.local.info('〖接待记录Record〗 == 更新记录' + JSON.stringify(record))
this.recordManager.updateRecord(record, this.key)
}
removeRecord(id) {
uni.$logger.local.info('〖接待记录Record〗 == 删除待提交记录!' + id)
this.recordManager.removeRecord(id, this.key)
}
async getFilePath() {
return this.path || (await utils.getFileSaveFolderOnClient())
}
async save(record = this.record) {
try {
uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
this.clearLoopTimer()
await this.saveTempFile(record)
const { recordUrlList, tempFilePath, ...__record } = record
__record.recordUrlList = await this.analysisUrlList(recordUrlList)
await this.dbManager.addRecord(__record)
await this.clearLocalRecord(record)
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
}
}
async clearLocalRecord(record = this.record) {
const { id, tempFilePath } = record
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
await this.removeFile(tempFilePath)
uni.$logger.local.info('〖接待记录Record〗 == 删除接待记录' + id)
this.removeRecord(id)
record = null
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
}
async analysisUrlList(recordUrlList) {
if (!recordUrlList?.length) return []
try {
const __path = await this.getFilePath()
const __list = recordUrlList.reduce((arr, item) => {
if (item?.file) {
arr.push({
status: FileStatus.Waiting,
file: __path + item.file.replace(/.+\/(\d+\.mp3)/, '$1')
})
} else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
}
return arr
}, [])
return __list
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message)
}
}
/**
* 更新记录
* @param {Object} records - 接待记录对象
* @param {Object} isUpdate - 是否更新记录 false 添加记录
* @returns - 返回保存后的文件路径
*/
// addOrUpdate() {
// this.updateRecord()
// }
async add() {
const id = utils.uuid()
this.record = {
id,
...this.newRecord,
receptionStartTime: this.getTimeNow(),
receptionEndTime: '',
recordUrlList: []
}
this.addRecord()
this.addAudio()
}
/**
* 保存文件
* @param {Object} record - 接待记录对象
* @returns - 返回保存后的文件路径
*/
async saveTempFile(record = this.record) {
const { tempFilePath, recordUrlList } = record
const lastIndex = recordUrlList.length - 1
if (lastIndex < 0 || !tempFilePath) return
const { file } = recordUrlList[lastIndex]
const saveResultPath = await this.saveFilePath(tempFilePath)
if (saveResultPath) {
uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
await this.removeFile(file)
record.recordUrlList[lastIndex].file = saveResultPath
}
return saveResultPath
}
async saveFilePath(tempFilePath) {
uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
if (!tempFilePath) return
const saveResult = await uni.saveFile({
tempFilePath
})
let saveResultPath = saveResult[1]?.savedFilePath
uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
return saveResultPath
}
removeFile(filePath) {
if (!filePath) return
return new Promise(resolve => {
uni.removeSavedFile({
filePath,
complete: resolve
})
})
}
async saveLastVideo() {
const __path = await this.saveTempFile()
__path && this.updateRecord()
}
setLoopAudio() {
this.clearLoopTimer()
this.timer = setInterval(this.saveLastVideo.bind(this), this.timer_interval)
}
clearLoopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
get preRecord() {
return this.getRecord()
}
get currentRecord() {
return this.record
}
setReceptionEndTime() {
this.record.receptionEndTime = this.getTimeNow()
}
getTimeNow() {
return utils.convertDateTimeFormat(new Date(), '/')
}
withError() {
this.record.endReasonType = 1
}
/**
* 添加音频
* @param {Object} isUpdate - 是否更新音频
* @returns {void}
*/
// Update the record with the new information
async addAudio() {
this.clearLoopTimer()
uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
await this.saveLastVideo()
await this.addNewAudio()
this.setLoopAudio()
}
async addNewAudio() {
const lastAudio = await this.getAudioFilePath()
uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
this.record.tempFilePath = lastAudio
const __path = await this.saveFilePath(lastAudio)
this.record.recordUrlList.push({ file: __path })
this.updateRecord()
}
async getAudioPathName() {
return new Promise(async (resolve, reject) => {
const path = await utils.getAudioFilePath()
plus.io.resolveLocalFileSystemURL(
path,
e => {
var dirR = e.createReader()
dirR.readEntries(
function (er) {
Promise.all(
er.map((item, index) => {
return new Promise(resolve => {
item.getMetadata(metadata => {
resolve({
index: index,
name: item.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
})
})
})
).then(results => {
results = results.filter(i => i.name.startsWith('uniapp_temp'))
// 找到修改时间最晚的文件
const latest = results.reduce(
(acc, current) => {
if (current.modificationTime > acc.modificationTime) {
return current
}
return acc
},
{ modificationTime: 0 }
)
// 修改时间最晚的文件名
resolve(latest.name)
})
},
err => {
reject(err)
}
)
},
err => {}
)
})
}
async getAudioFilePath() {
const pathName = await this.getAudioPathName()
return this.getAudioPath(pathName)
}
async getAudioPath(name) {
return new Promise(async (resolve, reject) => {
const path = await utils.getAudioFilePath(name + '/recorder')
plus.io.resolveLocalFileSystemURL(
path,
e => {
var dirR = e.createReader()
dirR.readEntries(
function (er) {
Promise.all(
er.map((item, index) => {
return new Promise(resolve => {
item.getMetadata(metadata => {
resolve({
index: index,
name: item.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
})
})
})
).then(results => {
// 找到修改时间最晚的文件
const latest = results.reduce(
(acc, current) => {
if (current.modificationTime > acc.modificationTime) {
return current
}
return acc
},
{ modificationTime: 0 }
)
// 修改时间最晚的文件名
resolve(path + '/' + latest.name)
})
},
err => {
reject(err)
}
)
},
err => {}
)
})
}
updatePreRecords(items) {
if (items) {
Object.assign(this.record, items)
this.updateRecord()
}
return this.record
}
setRecords(records) {
this.recordManager.setRecords(records, 'preRecordList')
store.dispatch('audio/setPerRecordNumber', records.length)
}
}
export default Record
class RecorderManager {
startOptions = {
duration: 600000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
}
constructor({ onStart, onStop, onError }) {
this.recorderManager = uni.getRecorderManager()
this.onStart = onStart
this.onStop = onStop
this.onError = onError
}
init() {
this.recorderManager.onStart(() => {
this.onStart()
})
this.recorderManager.onError(err => {
this.onError(err)
})
this.recorderManager.onStop(res => {
this.onStop(res)
})
}
start(options) {
const opt = Object.assign({}, this.startOptions, options)
this.recorderManager.start(opt)
}
stop() {
this.recorderManager.stop()
}
}
export default RecorderManager
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: limin
* @LastEditTime: 2024-11-28 16:31:22
* @FilePath: \gl_tape\mixin\click.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
const recorderManager = uni.getRecorderManager()
const plug = uni.requireNativePlugin('html5app-recordaudio')
import interruptRecord from '@/utils/recordManager/interruptRecord'
const UPLOAD_STATUS = {
// 上传状态
success: 1,
fail: 2
}
const AUDIO_STATUS = {
START: 'start', //录音中
END: 'end', //录音结束
ABNORMAL: 'abnormal' //40分钟未触碰平板,断开录音,不提交记录
}
const audioTime = 1 * 60 * 1000
let timer_interval = null
import { mapMutations, mapState } from 'vuex'
import utils from '@/utils/utils.js'
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update-nvue.js'
export default {
data() {
return {
voicePath: '',
times: 0,
timeout: 240,
reaction: 1
}
},
async mounted() {
uni.$logger.local.info(`进入接待首页!`)
this.handleCheck() // 检查更新
this.handleSave(false)
// 获取当前页面栈数组
// const pages = getCurrentPages()
// const currentPage = pages[pages.length - 1]
// const route = currentPage.route
// const url = ['pages/equity/index', 'pages/boutique/index']
// if (url.includes(route)) return
// this.initTime()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
changeData: {
handler(val) {
console.log(val, 'val', this.audioInfo.audioStatus)
if (this.audioInfo.audioStatus != AUDIO_STATUS.START) return
const { customerInfo, booksList, receptionStatus } = val
const params = this.getParams(customerInfo, booksList, receptionStatus)
interruptRecord.updatePreRecords(params)
},
deep: true
}
},
computed: {
...mapState('audio', ['receptionStatus', 'booksList', 'audioInfo']),
...mapState(['user.customerInfo']),
changeData() {
const customerInfo = this.$store?.state?.user?.customerInfo || {}
const booksList = this.booksList || []
const receptionStatus = this.receptionStatus
return { customerInfo, booksList, receptionStatus }
}
},
methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setAudioInfo']),
handleCheck() {
const { textList, tempFileURL, version } = uni.$storage.get('mock_data')
const res = utils.compareVersions(plus?.runtime?.version, version)
if (res > -1) {
return
}
const e = {
result: {
is_silently: false,
is_mandatory: true,
name: '',
title: '',
contents: textList.join('\n'),
version: version,
url: tempFileURL,
stable_publish: true
}
}
checkUpdate(e)
},
// //关闭提示
tipCancel() {
this.stopAudio()
this.setReceptionStatus(0)
this.setAudioInfo({ endReasonType: 1 })
if (this.$refs.tipBox) {
this.$refs.tipBox.close()
let { sceneType } = uni.$storage.get('userInfo')
uni.reLaunch({
url: sceneType == 0 ? '/pages/equity/index' : '/pages/boutique/index'
})
}
},
//结束提示
tipConfirm() {
this.times = 0
this.$refs.tipBox?.close()
},
closeAudio() {
this.endWatchClick()
this.stopAudio(AUDIO_STATUS.ABNORMAL)
this.setReceptionStatus(0)
this.setAudioInfo({ endReasonType: 1 })
},
getParams(customerInfo, booksList, receptionStatus) {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = uni.$storage.get('userInfo'),
{ customerName, phoneNumber, salesUuid, carModel, staffName } = customerInfo || {},
receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
}
}),
{ receptionStartTime, receptionEndTime, endReasonType } = this.audioInfo,
{ deviceId: appCode } = uni.getDeviceInfo(),
receptionTrack = this.$store.state.user.receptionTrack,
receptionCustomerMaterialPointList = []
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId: shopMerchantId,
businessScene: sceneType,
staffUuid: uuid,
staffName: name
})
})
let params = {
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
carModel,
endReasonType, //原因 1.异常 0.正常
customerName,
phoneNumber,
appCode,
loginPhone: phone,
salesName: staffName,
salesUuid,
receptionStatus, //接待结果 1.成交 0.战败
receptionStartTime,
receptionEndTime,
receptionCustomerPaySourceList, //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
merchantId: shopMerchantId,
merchantName,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType: channelType || 1, //1问界 2 比亚迪 3 其他
receptionCustomerMaterialPointList
}
return params
},
/**
* 修改文件名。
* @param {string} oldFilePath 旧的文件路径
* @param {string} newFileName 新的文件名
*/
renameFile(oldFilePath, newFileName) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
oldFilePath,
entry => {
console.log(111)
entry.getParent(
_oldFile => {
console.log(222)
entry.moveTo(
_oldFile,
'/' + newFileName,
newFilePath => {
resolve()
uni.$logger.local.info(`文件重命名成功!${newFilePath.fullPath}`)
// console.log('newFilePath', newFilePath.fullPath)
},
() => {
reject()
}
)
},
() => {
reject()
}
)
},
() => {
reject()
}
)
})
},
//开始录音
startAudio: utils.throttle(async function () {
if (this.audioInfo.audioStatus == AUDIO_STATUS.START) return
uni.$logger.local.info('开始接待')
this.setBooks([])
this.$store.dispatch('clearCustomerInfo')
this.setReceptionStatus('')
this.initTime()
this.setAudioInfo({ audioList: [], audioStatus: AUDIO_STATUS.START })
recorderManager.onStart(() => {
uni.$logger.local.info('开启录音!')
//开始录音保持记录,1s延时是因为第一段录音结束时间的文件修改时间等于第二段开始的文件修改时间,加上1s延时,就不会这个问题
setTimeout(() => {
const params = this.getParams(this.$store.state.user.customerInfo, this.booksList, this.receptionStatus)
interruptRecord.addPreRecords(params)
}, 1000)
})
recorderManager.start({
duration: audioTime,
sampleRate: 16000,
numberOfChannels: 1
})
recorderManager.onStop(async res => {
//第一段录音结束,还在接待中,则开启第二段录音
if (this.audioInfo.audioStatus == AUDIO_STATUS.START) {
uni.$logger.local.info('接待中,再次开启录音!')
uni.getRecorderManager().start({
duration: audioTime,
sampleRate: 16000,
numberOfChannels: 1
})
} else {
uni.$logger.local.info('断开录音!')
}
})
}, 300),
/**
* 保存记录
* 首先查看有没有没有保存的记录records,没有就直接返回
* 存在没有保存的记录,首先把临时的录音文件,保存永久的录音文件,并重新命名
* @params {boolean} isNormal 是否是正常保存
* @returns {void}
*/
async handleSave(isNormal = true) {
const records = interruptRecord.getPreRecord()
console.log(records, 'records')
if (!records) return
uni.$logger.local.info(`${isNormal ? '正常' : '异常'}保存记录`)
if (isNormal) {
Object.assign(records, this.getParams(this.$store.state.user.customerInfo, this.booksList, this.receptionStatus))
}
const audioPath = records.audioPath
let recordUrlList = []
const { phone } = uni.$storage.get('userInfo')
try {
// 把临时文件保存为永久录音文件
for (let i = 0; i < audioPath.length; i++) {
uni.$logger.local.info(`获取文件路径${audioPath[i]} `)
const saveResult = await uni.saveFile({
tempFilePath: audioPath[i]
})
let oldFilePath
const getPreAudioList = interruptRecord.getPreAudioList || []
if (saveResult[1] && saveResult[1].savedFilePath) {
oldFilePath = saveResult[1].savedFilePath
this.removeSavedFile(getPreAudioList[i])
uni.$logger.local.info(`保存文件结果路径${oldFilePath}`)
} else {
oldFilePath = getPreAudioList[i]
uni.$logger.local.info(`临时文件不存在,找到之前保存的文件${oldFilePath}`)
}
let newFileName = String(phone).slice(-4) + '_' + oldFilePath.replace(/.+\/(\d+\.mp3)/, '$1')
try {
await this.renameFile(oldFilePath, newFileName)
} catch {
uni.$logger.local.error(`${newFileName}文件重命名失败`)
newFileName = oldFilePath.replace(/.+\/(\d+\.mp3)/, '$1')
}
const newFilePath = oldFilePath.replace(/(.+\/)(\d+\.mp3)/, '') + newFileName
const path = await utils.getFileSaveFolderOnClient()
recordUrlList.push({ status: UPLOAD_STATUS.fail, file: path + newFilePath })
}
} catch (error) {
recordUrlList = []
uni.$logger.local.error(`${phone}上传保存失败:${JSON.stringify(error)}`)
}
delete records.audioPath
let saveRecords = Object.assign(records, { recordUrlList })
// 如果是正常保存,保存为待上传,并删除待提交记录,如果是异常保存,则更新待提交记录
if (isNormal) {
this.saveRecord(saveRecords)
} else {
interruptRecord.updatePreRecords(saveRecords, true)
}
},
removeSavedFile(filePath) {
uni.removeSavedFile({
filePath: filePath,
complete: function (res) {
uni.$logger.local.info(`删除轮询的文件${filePath}`)
}
})
},
/**
* 删除待提交记录
* @returns {void}
*/
removeRecords() {
const records = interruptRecord.getPreRecord()
interruptRecord.removePreRecord(records.id)
},
/**
* 保存待上传的记录,并删除待提交的记录
* @param {object} record 记录信息
* @returns {void}
*/
async saveRecord(record) {
uni.$logger.local.info(`添加记录${JSON.stringify(record)}`)
// const unlock = await uni.$recordManager.lock()
console.log('record', record)
await uni.$dbManager.addRecord(record)
interruptRecord.removePreRecord(record.id)
// unlock()
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
stopAudio: utils.throttle(async function (status) {
uni.$logger.local.info('结束接待!')
// const result = await this.$permision.requestAndroidPermission(
// "android.permission.RECORD_AUDIO"
// );
// if (result !== 1) {
// uni.showToast({
// title: "为了记录语音通话,请打开录音权限",
// icon: "none",
// });
// return;
// }
//如果是40分钟未触碰平板,只要断开录音即可
if (status == AUDIO_STATUS.ABNORMAL) {
this.setAudioInfo({ audioStatus: AUDIO_STATUS.ABNORMAL })
uni.$logger.local.info('40分钟未触碰平板,断开录音!')
recorderManager.stop()
return
}
//如果是40分钟未触碰平板后完成接待,需要保存记录
if (this.audioInfo.audioStatus == AUDIO_STATUS.ABNORMAL && status != true) {
uni.$logger.local.info('40分钟未触碰平板,保存记录!')
this.setAudioInfo({ audioStatus: AUDIO_STATUS.END })
this.handleSave()
return
}
if (this.audioInfo.audioStatus != AUDIO_STATUS.START) {
return
}
this.setAudioInfo({ audioStatus: AUDIO_STATUS.END })
//直接退出
uni.showLoading({
mask: true
})
setTimeout(() => {
uni.hideLoading()
if (this.audioInfo.audioStatus == AUDIO_STATUS.END) {
this.handleSave()
}
}, 3000)
this.endWatchClick()
if (status) {
uni.$logger.local.info('退出接待,不保存记录!')
this.removeRecords()
}
recorderManager.stop()
}, 1500),
//监听点击事件
initTime() {
if (timer_interval) {
this.endWatchClick()
}
timer_interval = setInterval(() => {
this.times++
console.log(this.times, 'this.times')
if (this.times >= this.timeout) {
//关闭录音
this.closeAudio()
}
}, 1000 * 10)
},
endWatchClick() {
console.log(timer_interval, 'endWatchClick')
if (timer_interval) clearInterval(timer_interval)
timer_interval = null
this.times = 0
},
handleTouchStart() {
this.times = 0
}
},
beforeCreate() {
// this.endWatchClick && this.endWatchClick()
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: limin
* @LastEditTime: 2024-12-06 14:46:47
* @FilePath: \gl_tape\utils\recordManager\click.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import utils from '@/utils/utils.js'
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update-nvue.js'
const timer = Object.freeze({
duration: 40 * 60 * 1000,
interval: 30 * 1000,
timeout: duration / interval
})
let counter = 0
let timer_interval = null
export default {
data() {
return {
reaction: 1
}
},
async mounted() {
this.versionCheck() // 检查更新
},
methods: {
versionCheck() {
const { textList, tempFileURL, version } = uni.$storage.get('mock_data')
const res = utils.compareVersions(plus?.runtime?.version, version)
if (res > -1) {
return
}
const e = {
result: {
is_silently: false,
is_mandatory: true,
name: '',
title: '',
contents: textList.join('\n'),
version: version,
url: tempFileURL,
stable_publish: true
}
}
checkUpdate(e)
},
// //关闭提示
tipCancel() {
this.audioManager.stop()
this.saveRecord()
this.setReceptionStatus(0)
this.setAudioInfo({ endReasonType: 1 })
if (this.$refs.tipBox) {
this.$refs.tipBox.close()
let { sceneType } = uni.$storage.get('userInfo')
uni.reLaunch({
url: sceneType == 0 ? '/pages/equity/index' : '/pages/boutique/index'
})
}
},
async saveRecord() {
const preRecord = this.record.preRecord
return this.record.save(preRecord)
},
//结束提示
tipConfirm() {
counter = 0
this.$refs.tipBox?.close()
},
closeAudio() {
this.endWatchClick()
this.audioManager.stop()
this.setReceptionStatus(0)
this.setAudioInfo({ endReasonType: 1 })
},
//监听点击事件
initTime() {
this.endWatchClick()
timer_interval = setInterval(() => {
if (counter >= timer.timeout) {
//关闭录音
this.closeAudio()
}
counter++
}, timer.interval)
},
endWatchClick() {
if (timer_interval) clearInterval(timer_interval)
timer_interval = null
counter = 0
},
handleTouchStart() {
counter = 0
}
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-10-14 17:38:35
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-11-20 17:27:29
* @FilePath: \gl-tape\utils\recordManager\interruptRecord.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import RecordManager from '../RecordManager.js'
import utils from '@/utils/utils.js'
import { storageApi } from '../cache'
import store from '@/store'
let Interval = null
class InterruptRecord extends RecordManager {
constructor() {
super()
const records = this.getRecords()
store.dispatch('audio/setPerRecordNumber', records.length)
// console.log(store)
// storageApi.removeRecords('preRecordList')
// storageApi.removeRecords('preRecordId')
// storageApi.removeRecords('recordList')
}
records = {}
pathName = null
audioPath = null
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
getRecords() {
console.log(storageApi.getRecords('preRecordList'), 'ddd')
return storageApi.getRecords('preRecordList') || []
}
/**
* 获取待提交的记录id
*
*/
getPreRecord() {
const id = storageApi.getRecords('preRecordId')
if (!id) {
return
}
return this.getRecordById(id)
}
/**
* 删除待提交的记录
*
*/
removePreRecord(id) {
uni.$logger.local.info(`删除待提交的记录${id}`)
this.removeRecord(id)
storageApi.setRecords('', 'preRecordId')
clearInterval(Interval)
}
/**
* 初始化保存记录
*
* @param {string} name - 录音文件目录名
* @returns {void} - 此函数不返回任何值
*/
async addPreRecords(params) {
if (storageApi.getRecords('preRecordId')) {
uni.$logger.local.info(`添加录音${storageApi.getRecords('preRecordId')}`)
this.addPreAudio()
return
}
const pathName = await this.getAudioPathName()
const audioPath = await this.getAudioPath(pathName)
this.audioPath = audioPath
const id = utils.uuid()
storageApi.setRecords(id, 'preRecordId')
const ids = storageApi.getRecords('preRecordId')
console.log(ids, 'id')
this.records = {
id,
...params,
audioPath: [audioPath]
}
uni.$logger.local.info(`开始保存记录${id}`)
const records = this.getRecords() || []
records.push(this.records)
this.setRecords(records)
this.setLoopAudio()
storageApi.setRecords('', 'preAudioList')
}
/**
* 30s保存录音文件
*
*/
setLoopAudio() {
Interval = setInterval(() => {
this.updateAudio()
}, 1000 * 30)
}
async updateAudio() {
const len = this.records.audioPath.length - 1
const saveResult = await uni.saveFile({
tempFilePath: this.audioPath
})
const preAudioList = storageApi.getRecords('preAudioList') || []
const filePath = preAudioList[len]
const savedFilePath = saveResult[1].savedFilePath
if (filePath) {
uni.removeSavedFile({
filePath: filePath,
complete: () => {
console.log('complete')
}
})
}
preAudioList[len] = savedFilePath
console.log(preAudioList, 'preAudioList')
storageApi.setRecords(preAudioList, 'preAudioList')
}
get getPreAudioList() {
return storageApi.getRecords('preAudioList')
}
/**
* 添加录音文件
*
* @returns {void} - 此函数不返回任何值
*/
async addPreAudio() {
clearInterval(Interval)
this.updateAudio()
const pathName = await this.getAudioPathName()
const audioPath = await this.getAudioPath(pathName)
this.audioPath = audioPath
const addAudioPath = [...this.records.audioPath, audioPath]
this.records.audioPath.push(audioPath)
const records = this.getPreRecord()
const params = { ...records, audioPath: addAudioPath }
this.updateRecord(params)
this.setLoopAudio()
}
/**
* 更新参数
*
* @returns {void} - 此函数不返回任何值
*/
updatePreRecords(params, isRemoveId) {
if (isRemoveId) {
uni.$logger.local.info(`清除正在接待记录的id`)
storageApi.setRecords('', 'preRecordId')
clearInterval(Interval)
}
const updateParams = { ...this.records, ...params }
console.log(updateParams, 'updateParams')
this.updateRecord(updateParams)
}
/**
* 获取录音文件全路径
*
* @param {string} name - 录音文件目录名
* @returns {void} - 此函数不返回任何值
*/
async getAudioPath(name) {
console.log(name, 'name')
return new Promise(async (resolve, reject) => {
const path = await utils.getAudioFilePath(name + '/recorder')
console.log(path, 'path')
plus.io.resolveLocalFileSystemURL(
path,
e => {
var dirR = e.createReader()
dirR.readEntries(
function (er) {
Promise.all(
er.map((item, index) => {
return new Promise(resolve => {
item.getMetadata(metadata => {
resolve({
index: index,
name: item.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
})
})
})
).then(results => {
console.log(results, 'results')
// 找到修改时间最晚的文件
const latest = results.reduce(
(acc, current) => {
if (current.modificationTime > acc.modificationTime) {
return current
}
return acc
},
{ modificationTime: 0 }
)
// 修改时间最晚的文件名
resolve(path + '/' + latest.name)
})
},
err => {
reject(err)
}
)
},
err => {}
)
})
}
/**
* 获取录音文件名
*
* @returns {void} - 此函数不返回任何值
*/
async getAudioPathName() {
return new Promise(async (resolve, reject) => {
const path = await utils.getAudioFilePath()
plus.io.resolveLocalFileSystemURL(
path,
e => {
var dirR = e.createReader()
dirR.readEntries(
function (er) {
Promise.all(
er.map((item, index) => {
console.log(item, 'item')
return new Promise(resolve => {
item.getMetadata(metadata => {
resolve({
index: index,
name: item.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
})
})
})
).then(results => {
console.log(results, 'results')
results = results.filter(i => i.name.startsWith('uniapp_temp'))
// 找到修改时间最晚的文件
const latest = results.reduce(
(acc, current) => {
if (current.modificationTime > acc.modificationTime) {
return current
}
return acc
},
{ modificationTime: 0 }
)
// 修改时间最晚的文件名
resolve(latest.name)
})
},
err => {
reject(err)
}
)
},
err => {}
)
})
}
/**
* 设置记录列表
*
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
setRecords(records) {
storageApi.setRecords(records, 'preRecordList')
console.log(records, 'records')
store.dispatch('audio/setPerRecordNumber', records.length)
}
}
export default new InterruptRecord()
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: limin
* @LastEditTime: 2024-12-06 14:44:19
* @FilePath: \gl_tape\utils\recordManager\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import AudioManager from './AudioManager'
import Record from './Record'
const UPLOAD_STATUS = {
// 上传状态
success: 1,
fail: 2
}
const AUDIO_STATUS = {
START: 'start', //录音中
END: 'end', //录音结束
ABNORMAL: 'abnormal' //40分钟未触碰平板,断开录音,不提交记录
}
import { mapMutations, mapState } from 'vuex'
import utils from '@/utils/utils.js'
export default {
data() {
return {
voicePath: '',
times: 0,
timeout: 240,
reaction: 1,
audioManager: null,
record: null
}
},
async mounted() {
this.audioManager = AudioManager.getInstance()
this.record = this.audioManager.record
this.recovery()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
changeData: {
handler(val) {
console.log(val, 'val', this.audioInfo.audioStatus)
if (!this.audioManager.isRecording) return
const { customerInfo, booksList, receptionStatus } = val
this.record.updatePreRecords(customerInfo, booksList, receptionStatus)
},
deep: true
}
},
computed: {
...mapState('audio', ['receptionStatus', 'booksList', 'audioInfo']),
...mapState(['user.customerInfo']),
changeData() {
const customerInfo = this.$store?.state?.user?.customerInfo || {}
const booksList = this.booksList || []
const receptionStatus = this.receptionStatus
return { customerInfo, booksList, receptionStatus }
}
},
methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setAudioInfo']),
//开始录音
startAudio: utils.throttle(async function () {
if (this.audioManager.isRecording) return
uni.$logger.local.info('开始接待')
this.setBooks([])
this.$store.dispatch('clearCustomerInfo')
this.setReceptionStatus('')
this.initTime()
// this.setAudioInfo({ audioList: [], audioStatus: AUDIO_STATUS.START })
this.audioManager.start()
}, 300),
onAudioStart() {
if (this.audioManager.counter === 0) {
this.record.add(this.customerInfo, this.booksList, this.receptionStatus)
} else {
this.record.addAudio()
}
},
onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.info('接待中,再次开启录音!')
this.audioManager.start()
} else {
uni.$logger.local.info('断开录音!')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
async recovery() {
const records = this.record.getRecords()
if (!records.length) return
while (records.length) {
const record = records.shift()
await this.record.save(record)
}
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
stopAudio(status) {
this.endWatchClick()
this.audioManager.stop()
const preRecord = this.record.preRecord
//直接退出
if (status) {
uni.$logger.local.info('退出接待,不保存记录!')
this.record.removeRecord(preRecord.id)
return
}
this.record.save(preRecord)
}
}
}
...@@ -12,6 +12,7 @@ import SetPollingIntervalWorker from './workers/SetPollingIntervalWorker' ...@@ -12,6 +12,7 @@ import SetPollingIntervalWorker from './workers/SetPollingIntervalWorker'
import TempRecordsWorker from './workers/TempRecordsWorker' import TempRecordsWorker from './workers/TempRecordsWorker'
import RemoveTempRecordWorker from './workers/RemoveTempRecordWorker' import RemoveTempRecordWorker from './workers/RemoveTempRecordWorker'
import AddTempRecordWorker from './workers/AddTempRecordWorker' import AddTempRecordWorker from './workers/AddTempRecordWorker'
import AddRecordWorker from './workers/AddRecordWorker'
import { Command } from './constants' import { Command } from './constants'
const Workers = { const Workers = {
[Command.GetLog]: LogsWorker, [Command.GetLog]: LogsWorker,
...@@ -26,7 +27,8 @@ const Workers = { ...@@ -26,7 +27,8 @@ const Workers = {
[Command.SetPollingInterval]: SetPollingIntervalWorker, [Command.SetPollingInterval]: SetPollingIntervalWorker,
[Command.TempRecords]: TempRecordsWorker, [Command.TempRecords]: TempRecordsWorker,
[Command.RemoveTempRecord]: RemoveTempRecordWorker, [Command.RemoveTempRecord]: RemoveTempRecordWorker,
[Command.AddTempRecord]: AddTempRecordWorker [Command.AddTempRecord]: AddTempRecordWorker,
[Command.AddRecord]: AddRecordWorker
} }
export default { export default {
create: cmd => Workers[cmd] || CommonWorker create: cmd => Workers[cmd] || CommonWorker
......
...@@ -11,6 +11,7 @@ const Command = { ...@@ -11,6 +11,7 @@ const Command = {
Records: 'records', Records: 'records',
TempRecords: 'tempRecords', TempRecords: 'tempRecords',
RemoveTempRecord: 'removeTempRecord', RemoveTempRecord: 'removeTempRecord',
AddTempRecord: 'addTempRecord' AddTempRecord: 'addTempRecord',
AddRecord: 'addRecord'
} }
export { Command } export { Command }
import { RecordDto } from '@/utils/recordManager/index'
export default class AddRecordWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const record = data.data
if (!record) {
throw new Error(`数据格式错误,请提供 record 数据`)
}
const keys = Object.keys(record)
const dto = new RecordDto({})
const existKeys = ['id', 'recordUrlList']
keys.forEach(key => {
if (!existKeys.includes(key) && !dto.hasOwnProperty(key)) {
throw new Error(`数据格式错误,表中没有 ${key} 字段`)
}
})
await uni.$dbTempRecord.addRecord(record)
const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg })
} catch (error) {
const msg = `写入待上传记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
import { RecordDto } from "@/utils/recordManager/index" import { RecordDto } from '@/utils/recordManager/index'
export default class AddTempRecordWorker { export default class AddTempRecordWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const record = data.data const record = data.data
if(!record){ if (!record) {
throw new Error(`数据格式错误,请提供 record 数据`) throw new Error(`数据格式错误,请提供 record 数据`)
} }
const keys = Object.keys(record) const keys = Object.keys(record)
const dto = new RecordDto({}) const dto = new RecordDto({})
const existKeys = ['id', 'recordUrlList','tempFilePath']
keys.forEach(key => { keys.forEach(key => {
if(!dto.hasOwnProperty(key)){ if (!existKeys.includes(key) && !dto.hasOwnProperty(key)) {
throw new Error(`数据格式错误,表中没有 ${key}字段`) throw new Error(`数据格式错误,表中没有 ${key} 字段`)
} }
}) })
await uni.$dbTempRecord.addRecord(record) await uni.$dbTempRecord.addRecord(record)
const msg = `写入待提交记录成功 temp record -> ${record}` const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg }) ws.send({ code: 200, msg })
} catch (error) { } catch (error) {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!