Commit f6e02a3a by 前端

合并

1 parent 428e7961
...@@ -7,7 +7,17 @@ const WsTyps = { ...@@ -7,7 +7,17 @@ const WsTyps = {
Eroor:'error', Eroor:'error',
Disconnected:'disconnect' Disconnected:'disconnect'
} }
const FileStatus = {
Error:0,
NoFile:1,
Waiting:2,
Uploading:3,
NotExist:4,
Uploaded:5,
Completed:6 //状态4 的 完成状态
}
export { export {
WsTyps WsTyps,
FileStatus
} }
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-01 15:06:40
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-19 16:43:04
* @FilePath: \gl-tape\utils\logger\LogCat.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { getTime } from './util' import { getTime } from './util'
import { serializeIfObject } from '../utils'
class LogCat { class LogCat {
main = plus.android.runtimeMainActivity() main = plus.android.runtimeMainActivity()
File = plus.android.importClass('java.io.File') File = plus.android.importClass('java.io.File')
...@@ -27,15 +20,13 @@ class LogCat { ...@@ -27,15 +20,13 @@ class LogCat {
} }
console.log('日志文件存放路径->', this.LogPath) console.log('日志文件存放路径->', this.LogPath)
} }
writeLog(tag, msg) { writeLog(tag, messages) {
let msg = serializeIfObject(messages)
let date = getTime('YYYY-MM-DD') let date = getTime('YYYY-MM-DD')
let datetime = getTime() let datetime = getTime()
//文件名 //文件名
let fileName = this.LogPath + '/' + date + '.txt' let fileName = this.LogPath + '/' + date + '.txt'
//写入的内容 //写入的内容
if (typeof msg == 'object') {
msg = JSON.stringify(msg)
}
let content = `${datetime} [${tag}] : ${msg}\n` let content = `${datetime} [${tag}] : ${msg}\n`
console.log(content.replace(/\n/g, '')) console.log(content.replace(/\n/g, ''))
let path = new this.File(this.LogPath) let path = new this.File(this.LogPath)
......
import Record from "./Record";
class AudioManager {
startOptions = {
duration: 600000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
}
__isRecording = false
__counter = 0
static instance = null;
constructor(onStart, onStop, onError) {
if (AudioManager.instance) {
return AudioManager.instance;
}
this.recorderManager = uni.getRecorderManager()
this.recorderManager.onStart(onStart)
this.recorderManager.onStop(onStop)
this.recorderManager.onError(onError)
this.__record = new Record()
AudioManager.instance = this;
}
start() {
this.__counter++
this.recorderManager.start(this.startOptions)
}
stop() {
this.__counter = 0
this.__isRecording = false
this.recorderManager.stop()
}
onStop(res) {}
get isRecording() {
return this.__isRecording
}
set isRecording(val) {
this.__isRecording = val
}
get counter() {
return this.__counter
}
get record() {
return this.__record
}
onError(err) {}
}
AudioManager.getInstance = () => {
if (!AudioManager.instance) {
AudioManager.instance = new AudioManager();
}
return AudioManager.instance;
};
export default AudioManager
import { getRecords } from "../cache/storageApi"
class Record {
key = 'preRecord'
timer = null
timer_interval
constructor() {
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.recordManager.addRecord(record, this.key)
}
updateRecord(record) {
this.recordManager.updateRecord(record, this.key)
}
removeRecord(id) {
this.recordManager.removeRecord(id,this.key)
}
async save(record) {
const __record = await this.saveTempFile(record)
await this.dbManager.addRecord(__record)
this.removeRecord(record.id)
}
addOrUpdate(record) {
const record = this.recordManager.getRecordById(record.id, this.key)
if (record) {
this.updateRecord(record)
} else {
this.addRecord(record)
}
}
async add(customerInfo, booksList, receptionStatus) {
const params = this.getParams(customerInfo, booksList, receptionStatus)
const id = utils.uuid()
this.record = {
id,
...params,
recordUrlList: []
}
return this.addAudio()
}
async saveTempFile(record) {
const lastIndex = record.recordUrlList.length - 1
if (lastIndex < 0) return
const filePath = record.recordUrlList[lastIndex]
const saveResult = await uni.saveFile({
tempFilePath: filePath
})
if (filePath) {
uni.removeSavedFile({
filePath,
complete: () => console.log('complete')
})
}
record.recordUrlList[lastIndex] = saveResult[1].savedFilePath
return record
}
async saveLastVideo() {
const record = this.preRecord
const __record = await this.saveTempFile(record)
this.updateRecord(__record)
}
setLoopAudio() {
this.timer = setInterval(() => {
this.saveLastVideo()
}, 1000 * 30)
}
get preRecord() {
return this.record
}
async addAudio() {
clearInterval(this.timer)
await this.saveTempFile()
const lastAudio = await this.getAudioFilePath()
this.record.recordUrlList.push(lastAudio)
this.addOrUpdate(this.record)
this.setLoopAudio()
}
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 => {}
)
})
}
async getAudioFilePath() {
const pathName = await this.getAudioPathName()
return this.getAudioFilePath(pathName)
}
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 => {}
)
})
}
updatePreRecords(customerInfo, booksList, receptionStatus) {
const params = this.getParams(customerInfo, booksList, receptionStatus)
const updateParams = { ...this.record, ...params }
console.log(updateParams, 'updateParams')
this.updateRecord(updateParams)
}
setRecords(records) {
this.recordManager.setRecords(records, 'preRecordList')
console.log(records, 'records')
store.dispatch('audio/setPerRecordNumber', records.length)
}
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
}
}
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-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
}
}
}
...@@ -4,120 +4,15 @@ import { storageApi } from "@/utils/cache"; ...@@ -4,120 +4,15 @@ import { storageApi } from "@/utils/cache";
* 记录管理器类 * 记录管理器类
* 用于管理记录列表 * 用于管理记录列表
*/ */
class RecordManager { class recorder {
/** /**
* RecordManager 类的构造函数 * RecordManager 类的构造函数
* 用于初始化 RecordManager 实例 * 用于初始化 RecordManager 实例
*/ */
constructor() {} constructor() {}
// 单例模式
static instance = null;
// 读写锁
locker = false;
/**
* 获取 RecordManager 的单例实例
* 如果 instance 不存在,则创建一个新实例并赋值给 instance
* @return {RecordManager} RecordManager 的单例实例
*/
static getInstance() {
if (!RecordManager.instance) {
RecordManager.instance = new RecordManager();
}
return RecordManager.instance;
}
/**
* 异步获取锁
* 如果锁已被占用,则在一段时间后重新尝试获取锁
* 如果成功获取锁,将返回一个 Promise,该 Promise 包含一个解锁函数。
* @return {Promise} 一个 Promise,在锁可用时兑现,并返回一个解锁函数
*/
async lock() {
return new Promise((resolve) => {
if (this.locker) {
setTimeout(() => {
this.lock();
}, 100);
} else {
this.locker = true;
resolve(this.unlock);
}
});
}
/**
* 释放本地存储的读写锁
*/
unlock() {
this.locker = false;
}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
const records = this.getRecords();
records.push(record);
this.setRecords(records);
return records;
}
/**
* 移除一个ID对应的记录
*
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord(id) {
let records = this.getRecords();
records = records.filter((i) => i.id !== id);
this.setRecords(records);
return records;
}
/**
* 获取并移除当前对象记录列表中的最后一条记录
*
* @returns {Object} - 被移除的最后一条记录对象,如果记录列表为空,则返回 undefined
*/
getRecord() {
const records = this.getRecords();
return records.pop();
}
/**
* 根据给定的 ID 获取一条记录
*
* @param {number} id - 要获取的记录的 ID
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*/
getRecordById(id) {
const records = this.getRecords();
return records.find((i) => i.id === id);
}
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
getRecords() {
return storageApi.getRecords();
}
/**
* 设置记录列表
*
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
setRecords(records) {
storageApi.setRecords(records);
}
/**
* 清除所有记录
*
* @returns {void} - 此函数不返回任何值
*/
clearRecords() {
storageApi.removeRecords();
}
} }
export default RecordManager export default recorder
/*
* @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)
}
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!