Commit 47d844c0 by liimin

1

1 parent dde65788
......@@ -10,7 +10,7 @@ class OSSUpLoader {
/**
* 文件的 MIME 类型
*/
mime = 'audio/mp3'
mime = 'audio/mpeg'
/**
* 本地保存文件路径(待上传文件路径)
*/
......@@ -65,6 +65,7 @@ class OSSUpLoader {
*/
retryInterval = 3 * 1000
currentCheckpoint
lastProgress = 0
/**
* OSS 存储桶中的目标文件夹路径
*/
......@@ -74,7 +75,7 @@ class OSSUpLoader {
*/
constructor({ region = this.region, bucket = this.bucket, accessKeyId, accessKeySecret, stsToken, mime = this.mime, partSize = this.partSize, parallel = this.parallel, timeout = this.timeout, filePath, retryCountMax = this.retryCountMax, retryInterval = this.retryInterval, ossFolder = this.ossFolder }) {
if (partSize < this.minPartSize) {
throw new Error(common.constants.CODE.FILE_PART_SIZE_TOO_SMALL)
throw new Error(common.constants.MESSAGE.FILE_PART_SIZE_TOO_SMALL)
}
this.mime = mime
this.partSize = partSize
......@@ -93,6 +94,16 @@ class OSSUpLoader {
stsToken
})
}
_normalizeFileName(fileName) {
let name = String(fileName || '')
name = name.split(/[\/\\]+/).pop()
name = name.replace(/\.\.+/g, '')
name = name.replace(/[^a-zA-Z0-9._-]/g, '')
if (!name) {
name = Date.now() + '.mp3'
}
return name
}
/**
* 上传文件到指定的 OSS 存储空间
* @param {string} fileName - 要上传的文件名
......@@ -100,11 +111,12 @@ class OSSUpLoader {
* @throws {Error} 如果文件路径转换失败,将抛出错误
*/
upload(fileName, callback) {
const safeName = this._normalizeFileName(fileName)
this._pathToFile(
this.filePath + fileName,
this.filePath + safeName,
function (result) {
if (result.code === common.constants.CODE.FILE_PATH_TRANSFORM_SUCCESS) {
this._upload(fileName, result.data.file, callback)
this._upload(safeName, result.data.file, callback)
} else {
callback(result)
}
......@@ -127,7 +139,9 @@ class OSSUpLoader {
// 获取分片上传进度、断点和返回值。
progress: (p, checkpoint, res) => {
this.currentCheckpoint = checkpoint
console.log(p)
if (p - this.lastProgress >= 0.1 || p === 1) {
this.lastProgress = p
}
},
// 设置并发上传的分片数量。
parallel: this.parallel,
......@@ -142,6 +156,7 @@ class OSSUpLoader {
// console.log('upload success: %j', JSON.stringify(res));
this.currentCheckpoint = null
this.retryCount = 0
this.lastProgress = 0
callback(
common.genCallBacks('FILE_UPLOAD_OSS_SUCCESS', {
oss: res
......@@ -150,7 +165,7 @@ class OSSUpLoader {
} else {
callback(
common.genCallBacks('FILE_UPLOAD_OSS_FAIL', {
errMsg: `OSS返回错误 状态码: ${res.status}`,
errMsg: `OSS返回错误 状态码: ${res && res.res && res.res.statusCode ? res.res.statusCode : res && res.status ? res.status : 'unknown'}`,
oss: res
})
)
......@@ -205,11 +220,11 @@ class OSSUpLoader {
callback(common.genCallBacks('FILE_PATH_TRANSFORM_FAIL'))
}
}
xhr.onerror = function (errType, errMsg) {
xhr.onerror = function (event) {
callback(
common.genCallBacks('FILE_PATH_REQUEST_FAIL', {
errType,
errMsg
errType: event && event.type,
errMsg: 'network error'
})
)
}
......@@ -222,6 +237,8 @@ class OSSUpLoader {
destroy() {
this.retryCount = 0
this.client = null
this.currentCheckpoint = null
this.lastProgress = 0
}
}
......
......@@ -2,13 +2,12 @@
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54
* @LastEditors: limin
* @LastEditTime: 2025-08-12 10:32:25
* @FilePath: \gl_tape\mixin\record\recorder.js
* @LastEditTime: 2025-12-22 11:02:51
* @FilePath: \simgle_app\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { AudioManager, TempRecord, RecordDto, helpler } from '../../utils/recordManager/index'
import { mapMutations, mapState, mapGetters } from 'vuex'
import utils from '@/utils/utils.js'
import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js'
export default {
......@@ -18,7 +17,7 @@ export default {
}
},
async mounted() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onError)
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onAudioError)
this.initDto()
this.record = new TempRecord(this.tempRecord, this.triggleTempNumber)
this.triggleTempNumber()
......@@ -64,14 +63,22 @@ export default {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setPerRecordNumber']),
...mapMutations(['clearCustomerInfo']),
//开始录音
startAudio: utils.throttle(async function (isInitData = true) {
const isPermission = await this.checkBeforeStart()
if (!isPermission) return
uni.$logger.local.info('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime()
this.audioManager.start()
}, 300),
async startAudio(isInitData = true) {
if (this._startAudioPromise) return this._startAudioPromise
this._startAudioPromise = (async () => {
try {
const isPermission = await this.checkBeforeStart()
if (!isPermission) return
uni.$logger.local.info('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime()
this.audioManager.start()
} finally {
this._startAudioPromise = null
}
})()
return this._startAudioPromise
},
initReception() {
this.setBooks([])
......@@ -105,7 +112,12 @@ export default {
async stopAudio(isNotSave = false) {
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ')
this.stop()
await this.saveAndClearRecord(isNotSave)
try {
await this.saveAndClearRecord(isNotSave)
} catch (error) {
uni.$logger.local.error(`〖接待管理Recorder〗 == 结束接待保存失败: ${error.message}`)
this.reportError('结束接待保存失败', error.message)
}
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
......@@ -136,7 +148,7 @@ export default {
this.tempRecord = null
},
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo()
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo() || {}
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
......@@ -198,6 +210,7 @@ export default {
return this.record
},
async triggleTempNumber() {
if (!this.record) return
const _records = await this.record.getRecords()
this.setPerRecordNumber(_records.length)
},
......
......@@ -7,36 +7,12 @@ import { FileStatus } from '../../utils/common'
import { serializeIfObject } from '../../utils/utils'
import dayjs from 'dayjs'
import TimeoutManager from '@/utils/TimeoutManager.js'
const UPLOAD_INTERVAL = 5 * 60 * 1000
const UPLOAD_INTERVAL = 0.5 * 60 * 1000
const TIME_OUT_TIME = 15 * 60 * 1000
export default {
mounted() {
this.init()
this.on()
// uni.$dbManager.updateRecord({"recordUrlList": [
// {
// "status": 4,
// "file": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/5727_17321755265103.mp3"
// },
// {
// "status": 5,
// "file": "http://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/5727_17321755265894.mp3",
// "filePathOnClient": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/5727_17321755265894.mp3"
// }
// ],salesName:'王欣伟'},{id:'14B558C5-284E-4567-878B-6B1511C8B790'}).then(res => {
// console.log(111,res)
// uni.$dbManager.getRecordById('14B558C5-284E-4567-878B-6B1511C8B790').then(res => {
// console.log(222,res)
// })
// })
// uni.$dbManager.removeRecord(null).then(res => {
// console.log(111,res)
// uni.$dbManager.drop().then(res => {
// console.log(222,res)
// })
// })
},
methods: {
async init() {
......@@ -47,11 +23,10 @@ export default {
// 初始化操作队列
this.operationQueue = new OperationQueue()
this.timeoutManager = new TimeoutManager()
this._pumpTimer = null
this._pumpRunning = false
// 开始轮询
this.startPolling()
// uni.$logger.local.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888} }, msg:'test', tag : { key: 'tag', value: 'tagtest' } })
// uni.$logger.local.getFiles('20240905','2024-09/05')
// uni.$logger.local.removeOverDays(1)
} catch (error) {
this.reportError(`【上传管理Uploader】初始化失败 error:${error.message}`, error.message)
}
......@@ -78,18 +53,11 @@ export default {
uni.$logger.local.info(`【上传管理Uploader】 == 文件上传回调!`)
this.save(data)
},
async checkDB() {
try {
const isSuccess = uni.$dbManager.init()
if (!isSuccess) {
this.toLogin()
return
}
} catch (error) {
uni.$logger.error(`【上传管理Uploader】 == 初始化数据库失败:${error.message}`)
this.toLogin()
}
/**
* 生成任务唯一标识 Key
*/
_getTaskKey(recordId, fileName) {
return `${recordId || ''}_${fileName || ''}`
},
/**
* 保存文件信息并更新记录
......@@ -106,15 +74,30 @@ export default {
uni.$logger.local.error(`【上传管理Uploader】 == 上传文件信息解析异常`)
return
}
// 竞态保护:判断回调是否属于当前任务
const callbackKey = this._getTaskKey(fileInfo.recordId, fileInfo.fileName)
const isCurrentTask = this._currentKey && callbackKey === this._currentKey
if (!isCurrentTask) {
uni.$logger.local.warn(`【上传管理Uploader】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态,不结束任务`)
}
const record = await uni.$dbManager.getRecordById(fileInfo.recordId)
const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord)
// 只有当前任务匹配时,才触发任务结束逻辑
if (isCurrentTask) {
uni.$logger.local.info('【上传管理Uploader】 == 本次任务完成,开启下一次上传任务!')
this.endTask()
}
} catch (error) {
this.reportError(`【上传管理Uploader】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
} finally {
uni.$logger.local.info('【上传管理Uploader】 == 本次任务完成,开启下一次上传任务!')
this.endTask()
}
// finally {
// uni.$logger.local.info('【上传管理Uploader】 == 本次任务完成,开启下一次上传任务!')
// this.endTask()
// }
},
/**
* 解析文件信息
......@@ -123,23 +106,83 @@ export default {
* @returns {Object} - 解析后的文件信息对象
*/
parseFileInfo(data) {
uni.$logger.local.info(`【上传管理Uploader】 == 开始文件信息解析-> ${JSON.stringify(data)}`)
// 如果是无文件状态,直接返回基础信息
if ([FileStatus.NoFile, FileStatus.NotExist].includes(data.status)) {
let { recordId, filePath, fileName, status } = data
status = status == FileStatus.NotExist ? FileStatus.Completed : FileStatus.NoFile //Completed NoFile 状态用于区分 正常上传的Uploaded状态.后续获取服务器文件路径过滤
return { recordId, clientPath: filePath + fileName, serverPath: null, fileName, status }
}
// 获取上传结果,如果失败直接返回 null
const { recordId, fileName, filePath, code, data: fileData, message } = data.detail.data[0]
if (code !== 0) {
const __message = `【上传管理Uploader】 == 文件上传回调,解析异常: code->${code} message->${message}`
uni.$logger.local.error(__message)
this.reportError(__message, data, recordId, filePath + fileName)
try {
const input = serializeIfObject(data)
uni.$logger.local.info(`【上传管理Uploader】 == 开始文件信息解析-> ${input}`)
if (!data) return null
const { status } = data
// 1. 处理无文件或文件不存在的特殊状态
if ([FileStatus.NoFile, FileStatus.NotExist].includes(status)) {
return this._parseNoFileStatus(data)
}
// 2. 处理正常上传回调
return this._parseUploadedFile(data)
} catch (error) {
uni.$logger.local.error(`【上传管理Uploader】 == 解析文件信息异常: ${error.message}`)
return null
}
},
_parseNoFileStatus(data) {
const { recordId, fileName, filePath, status } = data
const clientPath = (filePath || '') + (fileName || '')
if (!recordId) {
this.reportError('【上传管理Uploader】 == 缺少记录ID', data)
return null
}
return {
recordId: String(recordId),
clientPath,
serverPath: null,
fileName: String(fileName || ''),
status: status == FileStatus.NotExist ? FileStatus.Completed : FileStatus.NoFile
}
},
_parseUploadedFile(data) {
const payload = data?.detail?.data?.[0]
const { recordId, fileName, filePath } = payload || {}
const clientPath = (filePath || '') + (fileName || '')
// 1. 校验 payload 结构
if (!payload || typeof payload !== 'object') {
this._reportParseError('回调数据格式错误', data, data?.recordId, clientPath)
return null
}
// 返回成功上传的文件信息
return { recordId, fileName, clientPath: filePath + fileName, serverPath: fileData.oss.res.requestUrls[0].split('?')[0], status: FileStatus.Uploaded }
// 2. 校验 recordId
if (!recordId) {
this._reportParseError('文件上传回调,缺少recordId', data, undefined, clientPath)
return null
}
// 3. 校验业务状态码和 OSS URL
const { code, message, data: fileData } = payload
const serverUrl = fileData?.oss?.res?.requestUrls?.[0]
if (code !== 0 || !serverUrl) {
this._reportParseError(`解析异常: code->${code} message->${message}`, data, recordId, clientPath)
return null
}
return {
recordId,
fileName,
clientPath,
serverPath: String(serverUrl).split('?')[0],
status: FileStatus.Uploaded
}
},
_reportParseError(msg, data, recordId, filePath) {
const fullMsg = `【上传管理Uploader】 == ${msg}`
uni.$logger.local.error(fullMsg)
this.reportError(fullMsg, data, recordId, filePath)
},
/**
......@@ -151,46 +194,42 @@ export default {
*/
_changeFilePathToServer(record, fileInfo) {
try {
// record = Array.isArray(record) ? record[0] : record // sqlite 返回数组
// 深度克隆记录对象,以避免修改原始数据
const _record = deepClone(record)
uni.$logger.local.info(`【上传管理Uploader】 == 开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(_record.recordUrlList)}`)
// 如果是无文件状态,直接返回基础信息
uni.$logger.local.info(`【上传管理Uploader】 == 开始更新文件路径: ${JSON.stringify(_record.recordUrlList)}`)
// 场景1: 无文件状态 (NoFile)
if (fileInfo.status === FileStatus.NoFile) {
_record.status = FileStatus.NoFile
// 如果接待结束时间不存在,则设置为接待开始时间
_record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime
_record.recordUrlList = []
uni.$logger.local.info(`【上传管理Uploader】 == 当前记录没有接待语音文件,已将状态设置为无文件状态: ${JSON.stringify(_record)}`)
uni.$logger.local.info(`【上传管理Uploader】 == 记录被标记为无文件状态`)
return _record
}
// console.log(_record)
// 正常文件上传和文件丢失的记录执行此逻辑
// 场景2: 正常更新文件状态
_record.recordUrlList = this.urlListFilter(_record.recordUrlList)
const item = _record.recordUrlList.find(item => {
const isLegal = this.isLegalFile(fileInfo.fileName)
return isLegal ? item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName) : !this.isLegalFile(item.file)
const targetFile = _record.recordUrlList.find(item => {
// 匹配逻辑: 优先匹配绝对路径,其次匹配文件名后缀
if (!this.isLegalFile(fileInfo.fileName)) return !this.isLegalFile(item.file)
return item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName)
})
if (item) {
let info2Update = {
status: fileInfo.status
}
if (info2Update.status === FileStatus.Uploaded) {
// 正常文件上传的数据才更新服务器文件和本地文件路径 后面删除本地文件的时候 现过滤出正常上传的文件然后再获取到对应的文件删除
Object.assign(info2Update, {
file: fileInfo.serverPath,
filePathOnClient: fileInfo.clientPath
})
if (targetFile) {
targetFile.status = fileInfo.status
// 仅当上传成功时,才回填服务器路径
if (fileInfo.status === FileStatus.Uploaded) {
targetFile.file = fileInfo.serverPath
targetFile.filePathOnClient = fileInfo.clientPath
}
Object.assign(item, info2Update)
uni.$logger.local.info(`【上传管理Uploader】 == 修改文件路径完成!!`)
uni.$logger.local.info(`【上传管理Uploader】 == 文件状态已更新: ${fileInfo.fileName} -> ${fileInfo.status}`)
} else {
uni.$logger.local.info(`【上传管理Uploader】 == 未找到记录 == fileInfo -> ${JSON.stringify(fileInfo)}`)
uni.$logger.local.warn(`【上传管理Uploader】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`)
}
uni.$logger.local.info(`【上传管理Uploader】 == 替换完成!! record.recordUrlList-> ${JSON.stringify(_record.recordUrlList)}`)
return _record
} catch (error) {
uni.$logger.error(`【上传管理Uploader】 == 修改文件路径失败!! error-> ${error.message}`)
uni.$logger.error(`【上传管理Uploader】 == 修改文件路径失败: ${error.message}`)
throw new Error('【上传管理Uploader】 == 修改文件路径失败!!')
}
},
......@@ -235,37 +274,18 @@ export default {
* @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。
*/
async initWebview() {
const MAX_RETRIES = 500 // 最多尝试500次,每次间隔100ms,总共50秒
const INTERVAL = 100
try {
const currentWebview = this.$parent.$scope.$getAppWebview()
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const wv = currentWebview.children()[0]
if (wv) {
wv.setStyle({ top: '100%', height: 300 })
return wv
}
await new Promise(resolve => setTimeout(resolve, INTERVAL))
const currentWebview = this.$parent?.$scope?.$getAppWebview()
const wv = currentWebview?.children()?.[0]
if (wv) {
wv.setStyle({ top: '100%', height: 300 })
return wv
}
throw new Error('WebView initialization timeout')
return null
} catch (error) {
this.reportError(`初始化Webview失败 error:${error.message}`, error.message)
// this.toLogin()
throw error
}
},
toLogin() {
uni.hideLoading()
uni.showModal({
title: '错误',
content: '初始化失败,请重新登录系统',
showCancel: false,
success(res) {
uni.reLaunch({
url: '/pages/common/login'
})
}
})
return null
}
},
/**
* 入列操作
......@@ -285,6 +305,9 @@ export default {
uni.$logger.local.info('【上传管理Uploader】 == 创建快照成功! 文件个数:' + this.snapshot.size)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 获取快照失败 error:${error.message}`, error.message)
if (!this.snapshot) {
this.snapshot = new Queue([])
}
}
},
/**
......@@ -317,15 +340,22 @@ export default {
} else {
try {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
uni.$logger.local.info(`【上传管理Uploader】 == 获取Token成功!!', lsaccessKeySecret: ${lsaccessKeySecret}`)
// 通过WebView的evalJS方法,将密钥和ID等信息传递给WebView中的JavaScript代码 执行文件上传
this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
this._safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, record.fileName, record.filePath, record.recordId)
} catch (error) {
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
this.endTask()
throw error
}
}
},
_safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, fileName, filePath, recordId) {
if (!this.wv) {
throw new Error('WebView is not initialized')
}
const args = [lsaccessKeyId, lsaccessKeySecret, securityToken, fileName, filePath, recordId].map(v => JSON.stringify(String(v || '')))
const script = `msgFromUniapp(${args.join(',')})`
this.wv.evalJS(script)
},
/**
* 从客户端删除文件
* 这个函数用于从客户端的本地存储中删除指定的文件
......@@ -360,46 +390,60 @@ export default {
uni.$logger.local.info(`【上传管理Uploader】 == 开始保存或更新接待记录!!`)
try {
const { status, ...record } = data
const fileList = record.recordUrlList
// 判断接待记录的状态,如果是没有文件或者所有文件都已经上传或完成
if (status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))) {
// 过滤出状态为已上传的文件,提取其文件路径 并更新记录的 recordUrlList
const updatedFile = fileList.filter(file => file.status == FileStatus.Uploaded)
const pathArr = updatedFile.map(i => i.file)
// 过滤出存在本地文件路径的文件,提取其本地文件路径 以便记录保存完成后 删除
const originalFileArr = updatedFile.map(i => i.filePathOnClient) //正常上传的文件才删除本地文件
uni.$logger.local.info(`【上传管理Uploader】 == 本条接待所有文件已经上传和处理完毕!!`)
uni.$logger.local.info(`【上传管理Uploader】 == 已上传的文件: ${JSON.stringify(pathArr)}`)
uni.$logger.local.info(`【上传管理Uploader】 == 本地文件: ${JSON.stringify(originalFileArr)}`)
const params = Object.assign(record, { recordUrlList: pathArr })
// 如果接待结束时间不存在,则向服务器请求接待结束时间
if (!params.receptionEndTime) {
params.receptionEndTime = await this._requestReceptionEndTime(pathArr, params.receptionStartTime)
}
uni.$logger.local.info(`【上传管理Uploader】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
//向服务器发送请求,保存接待记录
const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.info(`【上传管理Uploader】 == 服务器返回结果: ${JSON.stringify(res)}`)
// 如果服务器返回结果成功
if (res) {
// 移除本地文件
await this._removeRecordFiles(originalFileArr)
// 从记录管理器中移除记录
await this._removeRecordById(record.id)
}
const fileList = Array.isArray(record.recordUrlList) ? record.recordUrlList : []
const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))
if (isAllCompleted) {
await this._handleCompletedRecord(record, fileList)
} else {
// 如果记录中还有未处理文件,记录日志并更新记录
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`)
// 更新接待记录
await uni.$dbManager.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
await this._handleIncompleteRecord(record)
}
} catch (error) {
// 如果保存或更新接待记录失败,记录错误信息并抛出错误
this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data.id, data.filePath + data.fileName)
this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data?.id)
}
},
/**
* 处理已完成(所有文件上传完毕)的记录
*/
async _handleCompletedRecord(record, fileList) {
// 1. 整理文件路径
const uploadedFiles = fileList.filter(file => file.status == FileStatus.Uploaded)
const serverPaths = uploadedFiles.map(i => i.file)
const localPaths = uploadedFiles.map(i => i.filePathOnClient)
uni.$logger.local.info(`【上传管理Uploader】 == 本条接待所有文件已经上传和处理完毕!!`)
uni.$logger.local.info(`【上传管理Uploader】 == 已上传的文件: ${JSON.stringify(serverPaths)}`)
// 2. 准备提交参数
const params = { ...record, recordUrlList: serverPaths }
if (!params.receptionEndTime) {
params.receptionEndTime = await this._requestReceptionEndTime(serverPaths, params.receptionStartTime)
}
// 3. 提交到服务器
uni.$logger.local.info(`【上传管理Uploader】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.info(`【上传管理Uploader】 == 服务器返回结果: ${JSON.stringify(res)}`)
// 4. 清理本地数据
if (res) {
await this._removeRecordFiles(localPaths)
await this._removeRecordById(record.id)
}
},
/**
* 处理未完成的记录(仅更新本地状态)
*/
async _handleIncompleteRecord(record) {
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`)
await uni.$dbManager.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
},
/**
* 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间
* @param {Array} recordUrlList - 包含文件URL的数组
......@@ -478,7 +522,7 @@ export default {
for (const file of recordUrlList) {
try {
// 如果文件状态为已上传或已完成,则跳过该文件
if (!file.status || file.status == FileStatus.Uploaded || file.status == FileStatus.Completed) continue
if (file.status === FileStatus.Uploaded || file.status === FileStatus.Completed) continue
const aFullPath = file.file.split('/')
const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/'
......@@ -500,7 +544,9 @@ export default {
}
return result
} catch (error) {
throw new Error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
// throw new Error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
uni.$logger.local.error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
return result
}
},
......@@ -539,64 +585,19 @@ export default {
},
isLegalFile(file) {
return file && file.endsWith('.mp3')
return file && String(file).toLowerCase().endsWith('.mp3')
},
/**
* 轮询函数
* 这个函数会检查网络连接状态,如果网络在线,则执行上传操作
* 如果网络不在线,则记录错误信息并在指定的时间间隔后重试
*/
async polling() {
try {
// 如果快照对象不存在,则立即返回 轮询会停止
if (this.snapshot === null) return uni.$logger.info('stooooooooooooop')
if (this.$store.getters.isInBackgound) {
uni.$logger.info('【上传管理Uploader】 == APP在后台运行,不进行文件上传!')
this.waitting()
return
}
// 检查网络是否在线
const isOnline = await uni.$isNetWork()
// 如果网络在线,则执行上传操作
if (isOnline) {
await this.upload()
} else {
this.reportError('【上传管理Uploader】 == 网络异常,稍后再试')
this.waitting()
}
} catch (error) {
this.reportError(`【上传管理Uploader】 == 异常,error->${error.message}`)
this.waitting()
}
},
async waitting() {
await this.wait() //添加等待 解决异常情况下,无间隔死循环
this.polling()
await this.wait()
this._scheduleNext(0)
},
async wait(time = TIME_OUT_TIME) {
const msg = await this.timeoutManager.addTimeout(this.interval, time)
async wait(waitTime = this.interval, outTime = TIME_OUT_TIME) {
const msg = await this.timeoutManager.addTimeout(waitTime, outTime)
if (msg === 'abort') this.snapshot = null
},
/**
* 执行上传操作
* 这个函数用于执行上传操作
* 首先,获取当前记录的快照
* 然后,调用 flattenData 方法将快照扁平化
* 最后,调用 uploadRecord 方法上传记录
*/
async upload() {
if (this.snapshot.size == 0) {
await this.enQueue()
await this.waitting()
} else {
let record = this.snapshot.dequeue()
this.beginTask(record)
}
},
/**
* 开始处理任务
* 这个函数用于将一个任务加入到操作队列中,并在任务完成后进行轮询
* @param {Object} record - 要处理的记录对象
......@@ -604,7 +605,8 @@ export default {
*/
async beginTask(record) {
// 将任务函数加入到操作队列中,并在任务完成后调用 polling 函数进行下一轮轮询
this.operationQueue.enqueue(() => this.task(record), `文件ID: ${record.recordId}@${record.fileName}`).finally(this.polling)
const label = 'TaskKey: '+this._getTaskKey(record?.recordId, record?.fileName)
this.operationQueue.enqueue(() => this.task(record), label).finally(() => this._scheduleNext(0))
},
/**
......@@ -616,6 +618,8 @@ export default {
task(record) {
return new Promise(resolve => {
this.updateResolve = resolve
this._taskStartTime = Date.now() // 记录任务开始时间
this._currentKey = this._getTaskKey(record.recordId, record.fileName)
this.uploadRecord(record)
})
},
......@@ -626,7 +630,9 @@ export default {
* @returns {void} - 此函数不返回任何值
*/
endTask() {
this.updateResolve && this.updateResolve(), (this.updateResolve = null)
this.updateResolve && this.updateResolve()
this.updateResolve = null
this._taskStartTime = null
},
/**
* 停止文件上传轮询并清除队列
......@@ -638,6 +644,10 @@ export default {
this.snapshot.clear()
this.snapshot = null
}
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
if (this.operationQueue) {
this.operationQueue.clear() // 取消所有待处理的操作
}
......@@ -683,11 +693,8 @@ export default {
}
setTimeout(async () => {
await this.enQueue()
this.polling()
this._scheduleNext(0)
}, 0)
// setTimeout(() => {
// this.startPolling(true)
// }, 1000)
uni.$logger.local.info(`【上传管理Uploader】 =========开始轮询========`)
},
/**
......@@ -697,6 +704,88 @@ export default {
this.timeoutManager?.cancelAllTasks()
this.endTask()
},
async _schedulerPump() {
if (this._pumpRunning) return
this._pumpRunning = true
try {
if (await this._shouldPausePump()) {
await this.waitting()
return
}
if (this.snapshot === null) return
if (!this.snapshot || this.snapshot.size === 0) {
await this.enQueue()
await this.waitting()
return
}
const record = this.snapshot.dequeue()
this.beginTask(record)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 异常,error->${error.message}`)
await this.waitting()
} finally {
this._pumpRunning = false
}
},
/**
* 检查是否应该暂停泵
* 包含: WebView就绪检查、后台运行检查、网络检查、任务队列状态检查
*/
async _shouldPausePump() {
// 1. 检查 WebView 是否就绪 (懒加载重试)
if (!this.wv) {
uni.$logger.local.info('【上传管理Uploader】 == WebView未就绪,尝试重新初始化...')
this.wv = await this.initWebview()
if (!this.wv) {
uni.$logger.local.warn('【上传管理Uploader】 == WebView 初始化失败,跳过本次轮询')
return true
}
}
// 2. 检查是否在后台
if (this.$store.getters.isInBackgound) {
uni.$logger.local.info('【上传管理Uploader】 == APP在后台运行,不进行文件上传!')
return true
}
// 3. 检查网络状态
const isOnline = await uni.$isNetWork()
if (!isOnline) {
this.reportError('【上传管理Uploader】 == 网络异常,稍后再试')
return true
}
// 4. 检查当前是否已有任务在执行
if (this.updateResolve || this.operationQueue?.processing) {
return true
}
return false
},
_scheduleNext(ms = 0) {
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(
() => {
this._checkTaskTimeout()
this._schedulerPump()
},
Math.max(0, ms)
)
},
/**
* 看门狗:检查当前任务是否超时
* 防止异常情况下任务永久卡死导致队列阻塞
*/
_checkTaskTimeout() {
if (!this._taskStartTime || !this.updateResolve) return
const TIMEOUT_THRESHOLD = 5 * 60 * 1000 // 5分钟
const isTimeout = Date.now() - this._taskStartTime > TIMEOUT_THRESHOLD
if (isTimeout) {
uni.$logger.local.error('【上传管理Uploader】 == 看门狗检测到任务卡死超过5分钟,强制重启轮询!')
this.endTask()
}
},
off() {
// 取消监听停止轮询事件
uni.$off(Command.StopPolling, this.stopPolling)
......
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: yangming@didihu.com.cn yangming@didihu.com.cn
* @LastEditTime: 2025-05-21 15:17:55
* @FilePath: \gl_tape\mixin\timeout.js
* @LastEditors: limin
* @LastEditTime: 2025-12-19 13:55:50
* @FilePath: \simgle_app\mixin\timeout.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
const TIMER_DURATION = 40 * 60 * 1000 //40分钟
......@@ -13,15 +13,23 @@ export default {
methods: {
//结束提示
stopRecorder() {
this.setReceptionStatus(0)
this.record.withError()
this.stop()
if (typeof this.setReceptionStatus === 'function') {
this.setReceptionStatus(0)
}
if (this.record && typeof this.record.withError === 'function') {
this.record.withError()
}
if (typeof this.stop === 'function') {
this.stop()
}
uni.$logger.local.info('== 长时间未触碰平板断开录音 ==')
},
//监听点击事件
initTime() {
uni.$logger.local.info('== 触碰平板开始计时 ==')
this.endWatchClick()
this.__counter = 0
this.__timer = null
this.__timer = setInterval(() => {
if (this.__counter >= TIMER_TIMEOUT) {
//关闭录音
......@@ -37,10 +45,10 @@ export default {
endWatchClick() {
if (this.__timer) {
clearInterval(this.__timer)
this.__timer = null
this.__counter = 0
uni.$logger.local.info('== 停止监听未触碰平板事件 == __timer:' + this.__timer + ' __counter:' + this.__counter)
}
this.__timer = null
this.__counter = 0
uni.$logger.local.info('== 停止监听未触碰平板事件 == __timer:' + this.__timer + ' __counter:' + this.__counter)
},
handleTouchStart() {
if (this.__counter > 0) {
......@@ -53,5 +61,7 @@ export default {
if (this.__timer) {
clearInterval(this.__timer)
}
this.__timer = null
this.__counter = 0
}
}
......@@ -4,8 +4,8 @@
* @Author: limin
* @Date: 2024-11-22 08:18:23
* @LastEditors: limin
* @LastEditTime: 2025-08-06 00:56:24
* @FilePath: \gl_tape\utils\DBManager.js
* @LastEditTime: 2025-12-22 11:05:15
* @FilePath: \simgle_app\utils\DBManager.js
*/
import { SQLite } from '../lib'
/**
......@@ -34,23 +34,23 @@ class DBManager {
await this.db.init()
}
const isTableExists = await this.db.isTableExists(this.table_name)
console.log(isTableExists, 'isTableExists')
uni.$logger.info(`数据库是否存在isTableExists: ${isTableExists}`)
if (!isTableExists) {
await this.db.createTable(this.table_name, this.table_columns)
} else { //如果存在 判断需要新增的字段是否存在 不存在则添加
const isColumnExists = await this.db.isColumnExists(this.table_name, 'carBrand')
console.log(isColumnExists, 'isColumnExists')
uni.$logger.info(`字段是否存在isColumnExists: ${isColumnExists}`)
if (!isColumnExists) {
await this.db.addColumns(this.table_name, [
{ name: 'carBrand', definition: 'TEXT DEFAULT ""' },
{ name: 'carBrandId', definition: 'INTEGER DEFAULT 0' },
{ name: 'oneCarBrand', definition: 'TEXT DEFAULT ""' },
{ name: 'oneCarBrandId', definition: 'INTEGER DEFAULT 0' }
])
}
}
// else { //如果存在 判断需要新增的字段是否存在 不存在则添加
// const isColumnExists = await this.db.isColumnExists(this.table_name, 'carBrand')
// console.log(isColumnExists, 'isColumnExists')
// uni.$logger.info(`字段是否存在isColumnExists: ${isColumnExists}`)
// if (!isColumnExists) {
// await this.db.addColumns(this.table_name, [
// { name: 'carBrand', definition: 'TEXT DEFAULT ""' },
// { name: 'carBrandId', definition: 'INTEGER DEFAULT 0' },
// { name: 'oneCarBrand', definition: 'TEXT DEFAULT ""' },
// { name: 'oneCarBrandId', definition: 'INTEGER DEFAULT 0' }
// ])
// }
// }
return true
} catch (error) {
uni.$logger.error(`初始化数据库失败 error - > ${error.message}`)
......
......@@ -5,19 +5,19 @@ class LocalLog {
logger = null
constructor() {
this.logger = {}
// this.logger = new LogCat()
this.logger = new LogCat()
}
debug(msg) {
// this.logger.writeLog(LogLevel.DEBUG, msg)
this.logger.writeLog(LogLevel.DEBUG, msg)
}
info(msg) {
// this.logger.writeLog(LogLevel.INFO, msg)
this.logger.writeLog(LogLevel.INFO, msg)
}
warn(msg) {
// this.logger.writeLog(LogLevel.WARN, msg)
this.logger.writeLog(LogLevel.WARN, msg)
}
error(msg) {
// this.logger.writeLog(LogLevel.ERROR, msg)
this.logger.writeLog(LogLevel.ERROR, msg)
}
getFiles(beginDate, endDate) {
const logFiles = this.logger.getLogFileList()
......
......@@ -4,12 +4,12 @@
* @Author: limin
* @Date: 2024-12-04 18:17:23
* @LastEditors: limin
* @LastEditTime: 2025-01-06 18:50:33
* @FilePath: \gl_tape\utils\recordManager\AudioManager.js
* @LastEditTime: 2025-12-19 16:48:28
* @FilePath: \simgle_app\utils\recordManager\AudioManager.js
*/
class AudioManager {
startOptions = {
duration: 10 * 60 * 1000, //默认10分钟
duration: 1 * 60 * 1000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
}
......@@ -121,7 +121,6 @@ class AudioManager {
get counter() {
return this.__counter
}
onError(err) {}
/**
* 重置录音状态
......
......@@ -4,8 +4,8 @@
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2025-08-12 10:23:15
* @FilePath: \gl_tape\utils\recordManager\TempRecord.js
* @LastEditTime: 2025-12-19 19:07:49
* @FilePath: \simgle_app\utils\recordManager\TempRecord.js
*/
import utils from '../utils'
import helpler from './helpler'
......@@ -17,40 +17,90 @@ class TempRecord {
path = ''
newRecord = null
onTempRecordNumberChanged = null
/**
* 构造函数
* @param {Object} record - 新建接待记录的初始字段(如客户信息等)
* @param {Function} onTempRecordNumberChanged - 临时记录数量变化时的回调
*/
constructor(record, onTempRecordNumberChanged) {
this.newRecord = record
this.recordManager = uni.$dbTempRecord
this.dbManager = uni.$dbManager
this.onTempRecordNumberChanged = onTempRecordNumberChanged
}
/**
* 获取全部临时记录
* @returns {Array} 临时记录列表
*/
getRecords() {
return this.recordManager.getRecords()
}
/**
* 根据 id 获取单条临时记录
* @param {string} id - 临时记录的唯一标识
* @returns {Object|null} 找到则返回记录,否则返回 null
*/
getRecord(id) {
return this.recordManager.getRecordById(id)
}
/**
* 添加一条临时记录并触发数量变化通知
* @param {Object} [record=this.record] - 要添加的记录对象
* @returns {Promise<void>}
*/
async addRecord(record = this.record) {
await this.recordManager.addRecord(record)
uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id)
this.triggleRecordNumChanged()
}
/**
* 更新临时记录(部分字段)
* @param {Object} item - 需要更新的字段键值对
* @param {Object} where - 更新条件(一般为 { id })
* @returns {Promise<void>}
*/
updateRecord(item, where) {
return this.recordManager.updateRecord(item, where)
}
/**
* 删除一条临时记录并触发数量变化通知
* @param {string} id - 临时记录 id
* @returns {Promise<void>}
*/
async removeRecord(id) {
await this.recordManager.removeRecord(id)
uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id)
this.triggleRecordNumChanged()
}
/**
* 更新当前内存中的记录并同步到数据库(值未变则跳过)
* @param {string} key - 字段名
* @param {*} value - 字段值
* @returns {Promise<void>|undefined} 值未变化时返回 undefined
*/
async __update(key, value) {
if (this.record[key] === value) return
this.record[key] = value
return this.updateRecord({ [key]: value }, { id: this.record.id })
}
/**
* 获取客户端文件保存基础路径(带缓存)
* @returns {Promise<string>} 保存路径(例如 `_doc/`)
*/
async getFilePath() {
if (!this.path) {
this.path = await utils.getFileSaveFolderOnClient()
uni.$logger.local.info('〖接待记录Record〗 == 初始化文件保存路径 -> ' + this.path)
}
return this.path
}
/**
* 将当前临时记录持久化到正式记录表,并清理本地数据
* - 开始前会停止轮询
* - 会对过长的录音列表进行截断
* @param {Object} [record=this.record] - 要保存的记录
* @returns {Promise<void>}
*/
async save(record = this.record) {
try {
if (!record) throw new Error('记录对象为空')
......@@ -84,11 +134,14 @@ class TempRecord {
}
}
async clearLocalRecord(record = this.record) {
const { id, tempFilePath } = record
const { id, tempFilePath } = record || {}
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
await this.removeFile(tempFilePath)
await this.removeRecord(id)
record = null
if (id) {
await this.removeRecord(id)
}
this.record = null
this.path = ''
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
}
/**
......@@ -99,25 +152,33 @@ class TempRecord {
clearSavedFiles({ recordUrlList = [] } = this.record) {
// 遍历录音文件列表并删除每个文件
recordUrlList.forEach(item => {
uni.$logger.local.info('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file)
this.removeFile(item.file)
})
}
/**
* 将已保存的文件列表映射为上传列表(统一拼接基础保存路径)
* @param {Array} recordUrlList - 已保存文件路径列表(形如 { file })
* @returns {Promise<Array>} 规范化后的上传列表(形如 { status, file })
*/
async __analysisUrlList(recordUrlList) {
if (!recordUrlList?.length) return []
try {
const __path = await this.getFilePath()
const __list = recordUrlList.reduce((arr, item) => {
if (item?.file) {
arr.push({
const basePath = await this.getFilePath()
const list = []
for (const item of recordUrlList) {
const filePath = item?.file
if (typeof filePath === 'string' && filePath.length > 0) {
const baseName = filePath.split('/').pop()
list.push({
status: FileStatus.Waiting,
file: __path + item.file.replace(/.+\/(\d+\.mp3)/, '$1')
file: basePath + baseName
})
} else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
}
return arr
}, [])
return __list
}
return list
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message)
......@@ -125,6 +186,10 @@ class TempRecord {
}
/**
* 添加新的接待记录
* - 创建内存中的记录对象
* - 同步写入临时记录数据库
* - 启动音频处理流程
* @returns {Promise<void>}
*/
async add() {
// 创建一个新的记录对象
......@@ -134,6 +199,10 @@ class TempRecord {
// 添加音频资源
this.addAudio()
}
/**
* 构造一条新的接待记录的初始对象
* @returns {Object} 新记录对象(含 id、开始时间、空的录音列表等)
*/
__createNewRecord() {
return {
id: utils.uuid(),
......@@ -152,35 +221,117 @@ class TempRecord {
// Update the record with the new information
async addAudio() {
this.clearLoopTimer()
uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
//保存上一个临时文件
await this.saveLastAudio()
//删除上一个临时文件
await this.removeOldTempAudio()
//等待1秒
await helpler.sleep(1000)
//新增一个录音
await this.processPreviousAudio()
await helpler.sleep(1500)
await this.addNewAudioAndStartLoop()
}
/**
* 处理上一个临时文件
* 1. 持久化保存上一个临时文件并更新本地路径到数据库
* 2. 删除上一个临时文件
*/
async processPreviousAudio() {
try {
uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
await this.saveLastAudio()
await this.removeOldTempAudio()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 处理上一个录音失败' + e)
}
}
/**
* 添加新录音并启动保存循环
* 1. 添加新录音
* 2. 更新数据库路径
* 3. 启动保存循环
*/
async addNewAudioAndStartLoop() {
try {
await this.addNewAudioAndUpdate()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 添加/更新新录音失败' + e)
} finally {
this.startSaveAudioLoop()
}
}
/**
* 添加新录音并同步更新数据库
* - 在内存中成功添加临时路径后,调用 `updatePath` 持久化到临时表
* @returns {Promise<void>}
*/
async addNewAudioAndUpdate() {
await this.addNewAudio()
//更新临时录音文件
await this.updatePath()
//开启轮询保存临时录音文件
this.startSaveAudioLoop()
// 只有在内存中成功添加了录音路径,才去更新数据库
if (this.record.tempFilePath) {
await this.updatePath()
uni.$logger.local.info('〖接待记录Record〗 == 同步数据库路径成功 id: ' + this.record.id)
}
}
/**
* 读取最新的录音临时文件并尝试保存
* - 支持重试机制
* - 成功后更新内存状态与录音列表
* @returns {Promise<void>}
*/
async addNewAudio() {
const lastAudio = await helpler.getLatestAudioFilePath()
uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
this.record.tempFilePath = lastAudio
const __path = await this.saveFilePath(lastAudio)
this.record.recordUrlList.push({ file: __path })
try {
const lastAudio = await this.getLastAudioWithRetry()
if (!lastAudio) {
uni.$logger.local.warn('〖接待记录Record〗 == 未找到录音文件,跳过添加')
return
}
uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
const savedPath = await this.saveFilePath(lastAudio)
if (savedPath) {
this.record.tempFilePath = lastAudio
const last = this.record.recordUrlList[this.record.recordUrlList.length - 1]
if (last && last.file === savedPath) {
uni.$logger.local.warn('〖接待记录Record〗 == 录音未变化,跳过添加 -> ' + savedPath)
} else {
this.record.recordUrlList.push({ file: savedPath })
uni.$logger.local.info('〖接待记录Record〗 == 添加新录音成功:' + savedPath)
}
}
} catch (e) {
uni.$logger.error(`〖接待记录Record〗 == 添加一个新的录音失败' ${e.message} ${JSON.stringify(e)}`)
}
}
/**
* 重试读取最近一次录音临时文件路径
* @param {number} [maxRetries=3] - 最大重试次数
* @param {number} [delayMs=500] - 每次重试的等待毫秒数
* @returns {Promise<string>} 找到则返回路径,否则返回空字符串
*/
async getLastAudioWithRetry(maxRetries = 3, delayMs = 500) {
let lastAudio = ''
for (let i = 0; i < maxRetries; i++) {
lastAudio = await helpler.getLatestAudioFilePath()
if (lastAudio) break
await helpler.sleep(delayMs)
}
return lastAudio
}
removeOldTempAudio() {
/**
* 删除上一个临时录音文件并重置路径
* @returns {Promise<void>}
*/
async removeOldTempAudio() {
const { tempFilePath } = this.record
uni.$logger.local.info('〖接待记录Record〗 == 删除上一个临时文件 -> ' + tempFilePath)
return this.removeFile(tempFilePath)
await this.removeFile(tempFilePath)
// 删除文件后,显式置空路径,防止干扰后续逻辑
this.record.tempFilePath = ''
return
}
/**
* 将当前内存中的临时路径与录音列表同步到数据库临时表
* @returns {Promise<void>}
*/
updatePath() {
const { id, tempFilePath, recordUrlList } = this.record
return this.updateRecord({ tempFilePath, recordUrlList }, { id })
......@@ -191,7 +342,16 @@ class TempRecord {
* @returns - 返回保存后的文件路径
*/
async saveTempFile(record = this.record) {
const { tempFilePath, recordUrlList } = record
let { tempFilePath, recordUrlList } = record
if (!tempFilePath || recordUrlList.length === 0) {
if (!this.timer) {
uni.$logger.local.info('〖接待记录Record〗 == 无可保存的临时录音,当前未在轮询中,跳过自动补录')
return
}
uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,轮询中尝试添加新录音')
await this.addNewAudioAndUpdate()
return
}
const lastIndex = recordUrlList.length - 1
if (lastIndex < 0 || !tempFilePath) return
const { file } = recordUrlList[lastIndex]
......@@ -203,66 +363,146 @@ class TempRecord {
}
return saveResultPath
}
/**
* 将临时文件保存到持久化目录(兼容不同返回结构)
* @param {string} tempFilePath - 临时文件路径
* @returns {Promise<string|undefined>} 保存成功返回持久化路径,失败返回 undefined
*/
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
try {
const saveResult = await uni.saveFile({
tempFilePath
})
// 兼容 uni.saveFile 可能返回数组 [err, res] 或直接返回对象的情况
let saveResultPath = ''
if (Array.isArray(saveResult)) {
saveResultPath = saveResult[1]?.savedFilePath
} else {
saveResultPath = saveResult?.savedFilePath
}
if (!saveResultPath) {
uni.$logger.local.error('〖接待记录Record〗 == 保存文件失败,路径为空')
return
}
uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
return saveResultPath
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 保存文件异常: ' + e.message)
return
}
}
/**
* 删除文件(持久化路径使用 `uni.removeSavedFile`)
* @param {string} filePath - 要删除的文件路径(可能为 `_doc/...` 或其他)
* @returns {Promise<void>}
*/
removeFile(filePath) {
if (!filePath) return
return new Promise(resolve => {
uni.removeSavedFile({
filePath,
complete: resolve
})
try {
uni.removeSavedFile({ filePath, complete: resolve })
} catch (e) {
resolve()
}
})
}
/**
* 在轮询中保存最后一个临时录音并更新列表
* @returns {Promise<void>}
*/
async saveLastAudio() {
const __path = await this.saveTempFile()
__path && this.updateUrlList()
try {
const __path = await this.saveTempFile()
__path && this.updateUrlList()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 轮询保存异常: ' + e.message)
}
}
/**
* 将当前内存的 `recordUrlList` 写回数据库
* @returns {Promise<void>}
*/
updateUrlList() {
const { id, recordUrlList } = this.record
return this.updateRecord({ recordUrlList }, { id })
}
/**
* 启动保存临时录音的轮询
* - 若已启动则跳过
* @returns {void}
*/
startSaveAudioLoop() {
this.clearLoopTimer()
if (this.timer) {
uni.$logger.local.info('〖接待记录Record〗 == 轮询已启动,跳过')
return
}
uni.$logger.local.info('〖接待记录Record〗 == 启动轮询 ' + this.timer_interval + 'ms')
this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
}
/**
* 停止保存轮询并清理定时器句柄
* @returns {void}
*/
clearLoopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
this.timer = null
uni.$logger.local.info('〖接待记录Record〗 == 停止轮询')
}
/**
* 获取当前内存中的接待记录对象
* @returns {Object|null} 当前记录,可能为空
*/
get currentRecord() {
return this.record
}
/**
* 设置接待结束时间为当前时间并同步到数据库
* @returns {Promise<void>}
*/
setReceptionEndTime() {
return this.__update('receptionEndTime', this.getTimeNow())
}
/**
* 获取当前时间字符串(格式化)
* @returns {string} 形如 `YYYY/MM/DD HH:mm:ss`
*/
getTimeNow() {
return utils.convertDateTimeFormat(new Date(), '/')
}
/**
* 标记记录为错误结束原因
* @returns {Promise<void>}
*/
withError() {
return this.__update('endReasonType', 1)
}
/**
* 批量更新当前记录的多个预填字段
* @param {Object} items - 需要更新的键值对
* @returns {Promise<Object>} 返回更新后的记录对象
*/
async updatePreRecords(items) {
if (items) {
Object.keys(items).forEach(async key => await this.__update(key, items[key]))
for (const key of Object.keys(items)) {
await this.__update(key, items[key])
}
}
return this.record
}
/**
* 触发临时记录数量变化通知
* @returns {Promise<void>|void}
*/
async triggleRecordNumChanged() {
if (this.onTempRecordNumberChanged) {
this.onTempRecordNumberChanged()
uni.$logger.local.info('〖接待记录Record〗 == 通知临时记录数变化')
}
}
}
......
......@@ -5,8 +5,14 @@ import utils from '../utils'
* 此函数调用 `getAudioPathName` 获取文件名,并通过 `getAudioPath` 获取完整路径。
*/
async function getLatestAudioFilePath() {
const pathName = await __getAudioPathName()
return __getAudioPath(pathName)
try {
const pathName = await __getAudioPathName()
if (!pathName) return ''
return await __getAudioPath(pathName)
} catch (error) {
uni.$logger.local.warn('〖接待记录Record〗 == 获取最新录音路径异常: ' + error.message)
return ''
}
}
/**
......@@ -55,15 +61,27 @@ async function __getLatestFilePath(directoryPath) {
return latestFile ? directoryPath + '/' + latestFile.name : ''
}
/**
* 获取指定目录中修改时间最晚的文件
* 获取文件的元数据
*
* @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<object|null>} - 修改时间最晚的文件对象或 null
* @param {object} fileEntry - 文件条目
* @returns {Promise<object>} - 文件元数据
*/
async function __getLatestFile(directoryPath, prefix = '') {
return new Promise((resolve, reject) => {
// [测试注入] 模拟系统异常:劫持 API 强制失败
const originalResolve = plus.io.resolveLocalFileSystemURL
plus.io.resolveLocalFileSystemURL = function (path, success, fail) {
uni.$logger.local.info(`〖接待记录Record〗 == [测试模拟] 拦截目录读取: ${path}`)
setTimeout(() => {
fail && fail({ code: 12, message: 'Simulated Path Not Found' })
// 恢复 API,避免影响全局
plus.io.resolveLocalFileSystemURL = originalResolve
}, 0)
}
plus.io.resolveLocalFileSystemURL(
directoryPath,
e => {
......@@ -76,30 +94,17 @@ async function __getLatestFile(directoryPath, prefix = '') {
const latest = results.reduce((acc, current) => (current.modificationTime > acc.modificationTime ? current : acc), { modificationTime: 0 })
resolve(latest.name ? latest : null)
},
err => reject(err)
err => {
uni.$logger.local.warn(`〖接待记录Record〗 == 读取目录项失败: ${directoryPath}, err: ${JSON.stringify(err)} ${err.message}`)
resolve(null)
}
)
},
err => reject(err)
)
})
}
/**
* 获取文件的元数据
*
* @param {object} fileEntry - 文件条目
* @returns {Promise<object>} - 文件元数据
*/
async function __getFileMetadata(fileEntry) {
return new Promise((resolve, reject) => {
fileEntry.getMetadata(
metadata => {
resolve({
name: fileEntry.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
},
err => reject(err)
err => {
// 目录不存在或无法访问,视为无文件
uni.$logger.local.warn(`〖接待记录Record〗 == 目录不存在或无法访问: ${directoryPath} err: ${JSON.stringify(err)} ${err.message}`)
resolve(null)
}
)
})
}
......@@ -110,3 +115,4 @@ export default {
getLatestAudioFilePath,
sleep
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!