Commit 4fb8957b by liimin

refactor(record-manager): 重构录音管理模块,引入策略模式优化录音和保存逻辑

重构录音管理模块,主要变更包括:
1. 引入策略模式,通过 StrategyFactory 动态选择录音和保存策略
2. 新增 NativeRecorder 和 NativeSave 策略实现原生录音功能
3. 提取 PathUtils 统一处理文件路径相关操作
4. 优化 RecordService 作为统一入口管理录音生命周期
5. 改进错误处理和日志记录

相关组件和混入代码同步更新以适应新的录音管理架构
1 parent d924d038
...@@ -422,9 +422,8 @@ export default { ...@@ -422,9 +422,8 @@ export default {
this.loadData() this.loadData()
}, },
async submitRecord (val) { async submitRecord (val) {
delete val.duration const { duration,tempFilePath,...r } = val
// delete val.startTime await this.recorder.save(r)
await this.recorder.recoverRecord(val)
this.loadRecords() this.loadRecords()
await this.getTempRecords() await this.getTempRecords()
}, },
......
...@@ -2,63 +2,39 @@ ...@@ -2,63 +2,39 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54 * @Date: 2024-12-26 10:03:54
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-13 16:10:54 * @LastEditTime: 2026-01-16 19:20:26
* @FilePath: \simgle_app\mixin\record\recorder.js * @FilePath: \simgle_app\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @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 RecordService from '../../utils/recordManager/RecordService.js'
import { mapMutations, mapState, mapGetters } from 'vuex' import { mapMutations, mapState, mapGetters } from 'vuex'
import { storageApi } from '@/utils/cache'
import utils from '@/utils/utils'
import permision from '@/js_sdk/wa-permission/permission.js'
export default { export default {
provide() { provide() {
return { return {
getRecorder: () => this.recorder getRecorder: () => this.recordService?.getRecorder()
} }
}, },
async mounted() { data() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onAudioError) return {
await this.initDto() recordService: null,
this.recorder = new TempRecord(this.tempRecord, this.triggleTempNumber, this.attributesProvider) interruptedRecord: null
// 优化:只查询一次数据库,然后分发给 recoverIfNeeded 和 triggleTempNumber
// await this.recoverIfNeeded()
this.triggleTempNumber()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
customerKey: {
handler() {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
deep: true
},
receptionStatus: {
handler(val) {
this.handler(val, this.updateReceptionStatus)
}
} }
}, },
computed: { async mounted() {
...mapState(['user.customerInfo']), this.recordService = RecordService.getInstance()
...mapGetters(['customerInfo', 'receptionStatus', 'receptionTrack', 'receptionKey', 'customerKey', 'typeCode', 'materialId']) await this.recordService.init()
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus', 'setPerRecordNumber']),
...mapMutations(['clearCustomerInfo']),
/** /**
* 尝试恢复异常中断的录音现场 * 尝试恢复异常中断的录音现场
* @param {Array} [records] - 可选,传入已查询的记录列表,避免重复查询 * @param {Array} [records] - 可选,传入已查询的记录列表,避免重复查询
*/ */
async recoverIfNeeded() { async recoverIfNeeded() {
try { try {
const _records = await this.recorder.getRecords() const _records = await this.getRecorder().getRecords()
// 查找最近一条未正常结束的记录(没有结束时间) // 查找最近一条未正常结束的记录(没有结束时间)
const interruptedRecord = _records.find(r => !r.endTime && r.userId == this.tempRecord.userId) const interruptedRecord = _records.find(r => !r.endTime && r.userId == this.recordService.tempRecord.userId)
if (interruptedRecord) { if (interruptedRecord) {
uni.$logger.local.warn('〖接待管理Recorder〗 == 发现未完成的接待记录,尝试恢复现场:', interruptedRecord) uni.$logger.local.warn('〖接待管理Recorder〗 == 发现未完成的接待记录,尝试恢复现场:', interruptedRecord)
...@@ -85,7 +61,7 @@ export default { ...@@ -85,7 +61,7 @@ export default {
if (this.interruptedRecord && this.interruptedRecord.id) { if (this.interruptedRecord && this.interruptedRecord.id) {
try { try {
// 删除该条未完成的记录,避免下次再次提示 // 删除该条未完成的记录,避免下次再次提示
await this.recorder.deleteRecord(this.interruptedRecord) await this.getRecorder().deleteRecord(this.interruptedRecord)
uni.$logger.local.info('〖接待管理Recorder〗 == 已删除未完成记录:' + this.interruptedRecord.id) uni.$logger.local.info('〖接待管理Recorder〗 == 已删除未完成记录:' + this.interruptedRecord.id)
} catch (e) { } catch (e) {
uni.$logger.local.error('〖接待管理Recorder〗 == 删除未完成记录失败:' + e) uni.$logger.local.error('〖接待管理Recorder〗 == 删除未完成记录失败:' + e)
...@@ -103,10 +79,10 @@ export default { ...@@ -103,10 +79,10 @@ export default {
// 1. 设置 counter 为 urlList 的数量(至少为1,确保不走新建逻辑),用于 onAudioStart 判断 // 1. 设置 counter 为 urlList 的数量(至少为1,确保不走新建逻辑),用于 onAudioStart 判断
const count = record.urlList?.length || 1 const count = record.urlList?.length || 1
this.audioManager.setCounter(count) this.recordService.audioManager.setCounter(count)
// 2. 恢复内存对象 // 2. 恢复内存对象
this.recorder.record = record this.recordService.recorder.record = record
// 3. 尝试恢复 UI 状态 (Vuex) // 3. 尝试恢复 UI 状态 (Vuex)
if (record.customerName || record.customerPhone) { if (record.customerName || record.customerPhone) {
...@@ -124,173 +100,40 @@ export default { ...@@ -124,173 +100,40 @@ export default {
// 4. 调用页面 开始接待 按钮 启动录音 // 4. 调用页面 开始接待 按钮 启动录音
await this.start() await this.start()
// 5. 恢复轮询(如果需要继续上传临时文件) // // 5. 恢复轮询(如果需要继续上传临时文件)
this.recorder.clearLoopTimer() // this.recordService.recorder.clearLoopTimer()
this.recorder.startSaveAudioLoop() // this.recordService.recorder.startSaveAudioLoop()
}, },
//开始录音 //开始录音
async startAudio(isInitData = true) { async startAudio(isInitData = true) {
if (this._startAudioPromise) return this._startAudioPromise const isSuccess = await this.recordService.startAudio(isInitData)
this._startAudioPromise = (async () => { if (isSuccess) {
try {
const isPermission = await this.checkBeforeStart()
if (!isPermission) return
uni.$logger.local.warn('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime() this.initTime()
this.audioManager.start()
} finally {
this._startAudioPromise = null
} }
})() return isSuccess
return this._startAudioPromise
}, },
/** /**
* 获取动态属性,用于 TempRecord 创建新记录时回调
* @returns {Object} 包含 typeCode 和 materialId 的对象
*/
attributesProvider() {
const typeItem = uni.$storage.get('typeItem') || {}
const dynamicAttrs = {
typeCode: typeItem.typeCode || '',
materialId: this.materialId || ''
}
uni.$logger.local.warn(`〖接待管理Recorder〗 == 创建新记录,注入动态属性: ${JSON.stringify(dynamicAttrs)}`)
return dynamicAttrs
},
initReception() {
// this.setBooks([])
this.clearCustomerInfo()
// this.setReceptionStatus('')
},
async onAudioStart() {
if (this.audioManager.counter === 0) {
await this.recorder.add()
} else {
this.recorder.addAudio()
}
},
async onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.warn('〖接待管理Recorder〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.warn('〖接待管理Recorder〗 == 断开录音! ')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
/**
* 结束接待 * 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音 * @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void} * @returns {void}
*/ */
async stopAudio(isNotSave = false) { async stopAudio(isNotSave = false) {
if (!this.isReceptioning()) { await this.recordService.stopAudio(isNotSave)
uni.$logger.local.warn('〖接待管理Recorder〗 == 未开始接待,不能结束接待! ')
return
}
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ')
this.stop() this.stop()
try {
await this.saveAndClearRecord(isNotSave)
} catch (error) {
uni.$logger.local.error(`〖接待管理Recorder〗 == 结束接待保存失败: ${error.message}`)
this.reportError('结束接待保存失败', error.message)
}
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
uni.$logger.local.warn('〖接待管理Recorder〗 == 不保存记录! ')
this.recorder.clearSavedFiles()
this.recorder.clearLocalRecord()
return
}
this.recorder.setReceptionEndTime() //设置接待结束时间
//如果不需要保存记录
await this.recorder.save()
}, },
stop() { stop() {
this.endWatchClick?.() this.endWatchClick?.()
this.recorder?.clearLoopTimer()
this.audioManager?.stop()
},
handler(params, fn) {
if (this.isReceptioning()) {
fn.call(this, params)
}
},
isReceptioning() {
return this.audioManager?.isRecording || this.recorder?.currentRecord?.endReasonType == 1
},
reset() {
this.audioManager = null
this.recorder = null
this.tempRecord = null
},
async initDto() {
const userInfo = storageApi.getUserInfo() || {}
const {
user: { userId, userName, deptId }
} = userInfo
const machineCode = await utils.getOAID()
const dto = new RecordDto({
userId,
userName,
merchantId: deptId,
machineCode
})
// this.sceneType = sceneType
this.tempRecord = dto
},
updateCustomerInfo(customerInfo = {}) {
const { customerName, customerPhone, customerType, carType } = customerInfo
const params = {
customerName,
customerPhone,
customerType,
carType
}
this.recorder.updatePreRecords(params)
},
updateReceptionStatus(status) {
this.recorder.updatePreRecords({ result: status })
}, },
getRecorder() { getRecorder() {
return this.recorder return this.recordService.getRecorder()
}, },
async triggleTempNumber(records) { async isPermission() {
if (!this.recorder) return return this.recordService.isPermission()
const _records = records || await this.recorder.getRecords()
this.setPerRecordNumber(_records.length)
},
async isPermission(hintText = '为了记录语音通话,请打开录音权限') {
const result = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
await helpler.sleep(0)
if (result !== 1) {
uni.showToast({
title: hintText,
icon: 'none'
})
}
return result === 1
},
async checkBeforeStart() {
const isPermission = await this.isPermission()
const isRecording = this.audioManager.isRecording
return isPermission && !isRecording
} }
}, },
beforeDestroy() { beforeDestroy() {
this.recorder?.destroy() this.recordService?.destroy()
this.stop()
this.reset()
} }
} }
...@@ -2,13 +2,14 @@ ...@@ -2,13 +2,14 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48 * @Date: 2024-04-08 11:28:48
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-13 18:13:46 * @LastEditTime: 2026-01-16 13:12:27
* @FilePath: \simgle_app\mixin\timeout.js * @FilePath: \simgle_app\mixin\timeout.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
const TIMER_DURATION = 40 * 60 * 1000 //40分钟 const TIMER_DURATION = 40 * 60 * 1000 //40分钟
const TIMER_INTERVAL = 1 * 60 * 1000 //1分钟检一次 const TIMER_INTERVAL = 1 * 60 * 1000 //1分钟检一次
const TIMER_TIMEOUT = TIMER_DURATION / TIMER_INTERVAL const TIMER_TIMEOUT = TIMER_DURATION / TIMER_INTERVAL
import RecordService from '../utils/recordManager/RecordService'
export default { export default {
methods: { methods: {
//结束提示 //结束提示
...@@ -16,9 +17,7 @@ export default { ...@@ -16,9 +17,7 @@ export default {
if (typeof this.setReceptionStatus === 'function') { if (typeof this.setReceptionStatus === 'function') {
this.setReceptionStatus(0) this.setReceptionStatus(0)
} }
if (this.record && typeof this.record.withError === 'function') { RecordService.getRecorder().withError()
this.record.withError()
}
if (typeof this.stop === 'function') { if (typeof this.stop === 'function') {
this.stop() this.stop()
} }
......
...@@ -4,9 +4,11 @@ ...@@ -4,9 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2024-12-04 18:17:23 * @Date: 2024-12-04 18:17:23
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-09 19:00:13 * @LastEditTime: 2026-01-15 16:37:41
* @FilePath: \simgle_app\utils\recordManager\AudioManager.js * @FilePath: \simgle_app\utils\recordManager\AudioManager.js
*/ */
import StrategyFactory from './strategies'
class AudioManager { class AudioManager {
startOptions = { startOptions = {
duration: 1 * 60 * 1000, //默认10分钟 duration: 1 * 60 * 1000, //默认10分钟
...@@ -33,7 +35,12 @@ class AudioManager { ...@@ -33,7 +35,12 @@ class AudioManager {
} }
} }
on() { on() {
this.recorderManager = uni.getRecorderManager() // 使用策略工厂获取录音管理器实例
this.recorderManager = StrategyFactory.getRecorderStrategy()
// 统一日志输出,利用多态特性,不再需要 if 判断
uni.$logger.local.info(`AudioManager: Using ${this.recorderManager.name}`)
this.recorderManager.onStart(this.onStart.bind(this)) this.recorderManager.onStart(this.onStart.bind(this))
this.recorderManager.onStop(this.onStop.bind(this)) this.recorderManager.onStop(this.onStop.bind(this))
this.recorderManager.onError(this.onError.bind(this)) this.recorderManager.onError(this.onError.bind(this))
...@@ -53,11 +60,11 @@ class AudioManager { ...@@ -53,11 +60,11 @@ class AudioManager {
* 它首先记录了一条信息到日志,然后执行事件的onStart方法, * 它首先记录了一条信息到日志,然后执行事件的onStart方法,
* 并且更新内部计数器和录音状态标志 * 并且更新内部计数器和录音状态标志
*/ */
async onStart() { async onStart(res) {
// 记录录音开始的信息到日志 // 记录录音开始的信息到日志
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 ') uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 '+JSON.stringify(res))
// 等待事件的onStart方法执行完成 // 等待事件的onStart方法执行完成
await this.events.onStart() await this.events.onStart(res)
// 内部计数器增加,用于跟踪录音开始的次数 // 内部计数器增加,用于跟踪录音开始的次数
this.__counter++ this.__counter++
// 设置录音状态标志为true,表示当前正在录音 // 设置录音状态标志为true,表示当前正在录音
......
/*
* @Author: limin
* @Date: 2025-01-15
* @Description: Android原生录音管理器 (Systematic Design)
* @Purpose: 提供高性能、长时稳定的录音功能,替代 uni.getRecorderManager 在复杂场景下的不足
* @DesignPattern: Singleton + State Machine + Observer
*/
import utils from '../utils.js'
import PathUtils from './PathUtils.js'
// 录音状态枚举
const RecorderState = {
IDLE: 'idle', // 空闲
RECORDING: 'recording', // 录音中
PAUSED: 'paused', // 暂停 (暂未实现,预留)
ERROR: 'error' // 错误状态
}
// 默认配置
const DEFAULT_CONFIG = {
sampleRate: 16000,
numberOfChannels: 1,
encodeBitRate: 96000,
format: 'aac', // 对应 mpeg_4 容器 + aac 编码
basePath: PathUtils.DEFAULT_SAVE_PATH // 默认持久化保存路径
}
class NativeRecorder {
static _instance = null
constructor() {
if (NativeRecorder._instance) {
return NativeRecorder._instance
}
this._state = RecorderState.IDLE
this._mediaRecorder = null
this._currentFilePath = ''
this._listeners = {
start: [],
stop: [],
error: []
}
// 绑定上下文,防止调用时 this 丢失
this.start = this.start.bind(this)
this.stop = this.stop.bind(this)
this.name = 'NativeRecorder (Android)' // 策略名称
NativeRecorder._instance = this
}
/**
* 获取单例实例
*/
static getInstance() {
if (!NativeRecorder._instance) {
NativeRecorder._instance = new NativeRecorder()
}
return NativeRecorder._instance
}
/**
* 注册事件监听 (兼容 uni.getRecorderManager 接口)
*/
onStart(callback) { this._addListener('start', callback) }
onStop(callback) { this._addListener('stop', callback) }
onError(callback) { this._addListener('error', callback) }
/**
* 内部添加监听器
*/
_addListener(event, callback) {
if (typeof callback === 'function') {
this._listeners[event].push(callback)
}
}
/**
* 触发事件
*/
_emit(event, data) {
// 异步触发,避免阻塞主线程
setTimeout(() => {
this._listeners[event].forEach(cb => {
try {
cb(data)
} catch (e) {
console.error(`[NativeRecorder] Event handler error (${event}):`, e)
}
})
}, 0)
}
/**
* 检查当前环境是否支持
*/
_checkEnvironment() {
// #ifndef APP-PLUS
return false
// #endif
// #ifdef APP-PLUS
if (plus.os.name !== 'Android') {
return false
}
return true
// #endif
}
/**
* 确保保存目录存在
* @param {string} dirPath - 相对路径,如 _doc/uniapp_save/
* @returns {Promise<string>} - 绝对路径 (Java File 使用)
*/
_ensureSaveDir(dirPath) {
return PathUtils.ensureDir(dirPath)
}
/**
* 开始录音
* @param {Object} options - 配置项 { sampleRate, numberOfChannels, encodeBitRate, path }
*/
async start(options = {}) {
if (!this._checkEnvironment()) {
this._emit('error', { errMsg: 'Environment not supported (Android App only)' })
return
}
// 防止重复启动
if (this._state === RecorderState.RECORDING) {
console.warn('[NativeRecorder] Already recording, stopping first...')
await this.stop()
}
try {
// #ifdef APP-PLUS
// 1. 导入必要的 Android 类
const MediaRecorder = plus.android.importClass('android.media.MediaRecorder')
const File = plus.android.importClass('java.io.File')
// 2. 准备路径
// 使用 TempRecord 统一管理的路径逻辑,避免多处硬编码
// 这里的 options.path 如果未提供,使用 DEFAULT_CONFIG.basePath
const basePath = options.path || DEFAULT_CONFIG.basePath
// _ensureSaveDir 负责将相对路径转换为绝对路径
const saveDirAbsPath = await this._ensureSaveDir(basePath)
// 使用 UUID + 时间戳 确保文件名唯一性,防止多用户并发上传到 OSS 时文件名冲突
// 格式: {uuid}_{timestamp}.mp3
const uuidStr = utils.uuid(8, 16) // 生成8位长度的UUID,基数为16
const fileName = `${Date.now()}_${uuidStr}.mp3`
const saveFile = new File(saveDirAbsPath, fileName)
// 确保文件不存在,避免覆盖(虽然时间戳几乎不可能重复)
if (saveFile.exists()) {
saveFile.delete()
}
this._currentFilePath = saveFile.getAbsolutePath()
// 3. 初始化 MediaRecorder
this._mediaRecorder = new MediaRecorder()
// 4. 配置参数 (严格顺序: AudioSource -> OutputFormat -> AudioEncoder)
this._mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
this._mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
this._mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
// 应用自定义配置或默认配置
const sampleRate = options.sampleRate || DEFAULT_CONFIG.sampleRate
const channels = options.numberOfChannels || DEFAULT_CONFIG.numberOfChannels
const bitRate = options.encodeBitRate || DEFAULT_CONFIG.encodeBitRate
this._mediaRecorder.setAudioSamplingRate(sampleRate)
this._mediaRecorder.setAudioChannels(channels)
this._mediaRecorder.setAudioEncodingBitRate(bitRate)
this._mediaRecorder.setOutputFile(this._currentFilePath)
// 5. 准备并启动
// prepare() 可能会因为硬件占用或权限问题抛出 IOException
try {
this._mediaRecorder.prepare()
this._mediaRecorder.start()
} catch (prepareErr) {
throw new Error(`MediaRecorder prepare/start failed: ${prepareErr.message}`)
}
// 6. 更新状态
this._state = RecorderState.RECORDING
uni.$logger.local.info(`[NativeRecorder] Started: ${this._currentFilePath}`)
const fileUrl = 'file://' + this._currentFilePath
this._emit('start', {
filePath: this._currentFilePath,
fullPath: fileUrl,
fileName: fileName,
basePath: basePath
})
// #endif
} catch (e) {
this._handleError('Start failed', e)
}
}
/**
* 停止录音
*/
stop() {
if (!this._checkEnvironment()) return
if (this._state !== RecorderState.RECORDING || !this._mediaRecorder) {
console.warn('[NativeRecorder] Not recording or recorder not initialized')
return
}
try {
// #ifdef APP-PLUS
// 停止录音
// 注意: 如果录音时间极短(小于1s),stop() 可能会抛出 RuntimeException
try {
// 在 stop 之前先重置错误监听器,防止 stop 抛出的异常被误判
// 但 Java 侧异常需要捕获
this._mediaRecorder.stop()
} catch (stopErr) {
// 常见错误:RuntimeException: stop failed.
// 原因:录音时间太短(通常小于 1 秒)或尚未开始
console.warn('[NativeRecorder] Stop exception (likely too short):', stopErr)
// 这种情况下,文件可能无效或未生成,需要检查文件是否存在
}
uni.$logger.local.info(`[NativeRecorder] Stopped`)
// 检查文件是否存在且大小 > 0
const File = plus.android.importClass('java.io.File')
const file = new File(this._currentFilePath)
if (file.exists() && file.length() > 0) {
// 转换为 uni-app 可用的 file:// 路径
const fileUrl = 'file://' + this._currentFilePath
this._emit('stop', {
filePath: fileUrl
})
} else {
console.warn('[NativeRecorder] Recorded file invalid (empty or missing)')
// 可以选择是否抛出 error,或者静默失败
// this._emit('error', { errMsg: 'Recorded file invalid' })
}
// #endif
} catch (e) {
this._handleError('Stop failed', e)
} finally {
this._cleanup()
}
}
/**
* 内部错误处理
*/
_handleError(context, error) {
console.error(`[NativeRecorder] ${context}:`, error)
this._state = RecorderState.ERROR
this._cleanup()
this._emit('error', { errMsg: `${context}: ${error.message}` })
}
/**
* 资源清理
*/
_cleanup() {
if (this._mediaRecorder) {
try {
// #ifdef APP-PLUS
this._mediaRecorder.release()
// #endif
} catch (e) {
// ignore
}
this._mediaRecorder = null
}
this._state = RecorderState.IDLE
// 注意:不清除 _currentFilePath,因为 stop 回调可能需要它
}
/**
* 获取当前状态
*/
getState() {
return this._state
}
}
// 导出单例
export default new NativeRecorder()
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-16 10:02:57
*/
import TempRecord from './TempRecord'
class NativeSave extends TempRecord {
constructor(record, onTempRecordNumberChanged, attributesProvider) {
super(record, onTempRecordNumberChanged, attributesProvider)
}
/**
* 添加新的接待记录
* - 创建内存中的记录对象
* - 同步写入临时记录数据库
* - 启动音频处理流程
* @returns {Promise<void>}
*/
async add(audio) {
uni.$logger.local.info('〖NativeSave〗 == add called with: ' + JSON.stringify(audio))
// 创建一个新的记录对象
const urlList = audio && audio.fileName ? [{ file: audio.fileName }] : []
// 调用基类通用流程
await super.add(urlList)
}
}
export default NativeSave
/**
* 路径处理工具类
*/
class PathUtils {
static _basePath = null
// 默认保存文件夹名称
static SAVE_DIR_NAME = 'uniapp_save'
// 默认文件保存路径 (相对于 _doc/)
static DEFAULT_SAVE_PATH = `_doc/${this.SAVE_DIR_NAME}/`
/**
* 路径拼接工具
* @param {...string} args 路径片段
* @returns {string}
*/
static join(...args) {
if (args.length === 0) return ''
const parts = args.map((part, index) => {
if (!part) return ''
let str = String(part)
if (index !== 0) {
str = str.replace(/^\/+/, '') // 去除开头的斜杠
}
if (index !== args.length - 1) {
str = str.replace(/\/+$/, '') // 去除结尾的斜杠
}
return str
}).filter(p => p.length > 0)
return parts.join('/')
}
/**
* 获取基础保存路径 (带缓存)
*/
static async getBasePath() {
if (this._basePath) return this._basePath
this._basePath = await this.getFileSaveFolderOnClient()
return this._basePath
}
/**
* 获取文件系统根目录的完整路径
* @returns {Promise<string>}
*/
static getFilePath() {
return new Promise(resolve => {
// #ifdef APP-PLUS
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
resolve(fs.root.fullPath)
})
// #endif
// #ifndef APP-PLUS
resolve('')
// #endif
})
}
/**
* 获取客户端文件保存基础路径
*/
static async getFileSaveFolderOnClient() {
const rootPath = await this.getFilePath()
const path = this.join(rootPath, this.SAVE_DIR_NAME)
return `file://${path}/`
}
/**
* 获取音频文件基础路径
*/
static async getAudioFilePath(path = '') {
const rootPath = await this.getFilePath()
const fullPath = this.join(rootPath, path)
return `file://${fullPath}`
}
/**
* 获取绝对路径
* @param {string} relativePath 相对路径或文件名
*/
static async getAbsolutePath(relativePath) {
if (!relativePath) return ''
if (relativePath.startsWith('file://') || relativePath.startsWith('/')) {
return relativePath
}
const base = await this.getBasePath()
// 避免重复斜杠
if (base.endsWith('/') && relativePath.startsWith('/')) {
return base + relativePath.substring(1)
}
if (!base.endsWith('/') && !relativePath.startsWith('/')) {
return base + '/' + relativePath
}
return base + relativePath
}
/**
* 确保目录存在 (递归创建)
* @param {string} dirPath 目录路径
*/
static ensureDir(dirPath) {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
plus.io.resolveLocalFileSystemURL(dirPath, entry => {
resolve(entry.fullPath)
}, () => {
// 目录不存在,尝试创建
// NativeRecorder 传的是 "_doc/uniapp_save/"
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, fs => {
const root = fs.root
let path = dirPath
if (path.startsWith('_doc/')) path = path.substring(5)
const createDir = (entry, folders) => {
if (folders.length === 0) {
resolve(entry.fullPath)
return
}
entry.getDirectory(folders[0], { create: true }, dirEntry => {
createDir(dirEntry, folders.slice(1))
}, err => {
reject(new Error('创建目录失败: ' + err.message))
})
}
createDir(root, path.split('/').filter(p => p))
}, err => reject(err))
})
// #endif
// #ifndef APP-PLUS
resolve(dirPath)
// #endif
})
}
}
export default PathUtils
...@@ -2,6 +2,7 @@ import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js' ...@@ -2,6 +2,7 @@ import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js' import Queue from '@/utils/Queue.js'
import { Command } from '@/ws/constants' import { Command } from '@/ws/constants'
import { isInteger, deepClone, serializeIfObject, getWebviewInstance } from '@/utils/utils.js' import { isInteger, deepClone, serializeIfObject, getWebviewInstance } from '@/utils/utils.js'
import PathUtils from './PathUtils.js'
import { FileStatus } from '@/utils/common' import { FileStatus } from '@/utils/common'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { decryptAES } from '@/lib/aes.js' import { decryptAES } from '@/lib/aes.js'
...@@ -136,7 +137,7 @@ class UploadService { ...@@ -136,7 +137,7 @@ class UploadService {
} }
} catch (error) { } catch (error) {
if (this._currentKey) { if (this._currentKey) {
this._blackList.add(this._currentKey) this._addToBlackList(this._currentKey, `Save failed: ${error.message}`)
} }
this.reportError(`【上传服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName) this.reportError(`【上传服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask() this.endTask()
...@@ -308,7 +309,7 @@ class UploadService { ...@@ -308,7 +309,7 @@ class UploadService {
async uploadRecord(record) { async uploadRecord(record) {
// 任务开始前,再次检查黑名单(防止队列滞后) // 任务开始前,再次检查黑名单(防止队列滞后)
const taskKey = this._getTaskKey(record.recordId, record.fileName) const taskKey = this._getTaskKey(record.recordId, record.fileName)
if (this._blackList.has(taskKey)) { if (this._isInBlackList(taskKey)) {
uni.$logger.local.warn(`【上传服务】 == 任务在黑名单中,跳过: ${taskKey}`) uni.$logger.local.warn(`【上传服务】 == 任务在黑名单中,跳过: ${taskKey}`)
this.endTask() this.endTask()
return return
...@@ -346,7 +347,7 @@ class UploadService { ...@@ -346,7 +347,7 @@ class UploadService {
return decrypted return decrypted
} }
} catch (e) { } catch (e) {
uni.$logger.error(`${label} decryption error`+ e.message) uni.$logger.error(`${label} decryption error` + e.message)
} }
return str return str
} }
...@@ -381,7 +382,7 @@ class UploadService { ...@@ -381,7 +382,7 @@ class UploadService {
async _saveOrUpdate(data) { async _saveOrUpdate(data) {
uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`) uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`)
try { try {
const { status,tempFilePath,receptionStatus, ...record } = data const { status, tempFilePath, receptionStatus, ...record } = data
const fileList = Array.isArray(record.urlList) ? record.urlList : [] const fileList = Array.isArray(record.urlList) ? record.urlList : []
const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status)) const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))
if (isAllCompleted) { if (isAllCompleted) {
...@@ -390,7 +391,8 @@ class UploadService { ...@@ -390,7 +391,8 @@ class UploadService {
await this._handleIncompleteRecord(record) await this._handleIncompleteRecord(record)
} }
} catch (error) { } catch (error) {
this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data?.id) uni.$logger.error(`【上传服务】 == 上传接待记录异常,error:${error.message}`)
this._addToBlackList(this._currentKey, `Upload record failed: ${JSON.stringify(error.message)}`)
} }
} }
...@@ -407,11 +409,12 @@ class UploadService { ...@@ -407,11 +409,12 @@ class UploadService {
uni.$logger.local.info(`【上传服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`) uni.$logger.local.info(`【上传服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
const res = await uni.$api.reception.save(params) const res = await uni.$api.reception.save(params)
uni.$logger.local.warn(`【上传服务】 == 服务器返回结果: ${JSON.stringify(res)}`) uni.$logger.local.warn(`【上传服务】 == 服务器返回结果: ${JSON.stringify(res)}`)
if (res?.code == 200) { if (res?.code == 200) {
uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`) uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`)
await this._removeRecordFiles(localPaths) await this._removeRecordFiles(localPaths)
await this._removeRecordById(record.id) await this._removeRecordById(record.id)
} else {
throw new Error(`【上传服务】 == 服务器保存接待记录失败: ${JSON.stringify(res)}`)
} }
} }
...@@ -441,14 +444,40 @@ class UploadService { ...@@ -441,14 +444,40 @@ class UploadService {
} }
} }
/**
* 将任务添加到黑名单
* @param {string} key - 任务 Key (recordId_fileName 或 recordId)
* @param {string} reason - 原因
*/
_addToBlackList(key, reason = 'unknown') {
if (!key) return
if (!this._blackList.has(key)) {
this._blackList.add(key)
uni.$logger.local.warn(`【上传服务】 == 加入黑名单 [${key}]: ${reason}`)
}
}
/**
* 检查是否在黑名单中
*/
_isInBlackList(key) {
return key && this._blackList.has(key)
}
async flattenData(records) { async flattenData(records) {
const result = [] const result = []
try { try {
for (const cur of records) { for (const cur of records) {
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
if (this._isInBlackList(cur.id)) {
continue
}
const urlList = this.urlListFilter(cur.urlList) const urlList = this.urlListFilter(cur.urlList)
if (urlList.length == 0) { if (urlList.length == 0) {
result.push({ status: FileStatus.NoFile, recordId: cur.id }) result.push({ status: FileStatus.NoFile, recordId: cur.id })
// 仅在第一次遇到时上报错误,并加入黑名单防止刷屏
this.reportError('【上传服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id) this.reportError('【上传服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id)
// this._addToBlackList(cur.id, 'No audio files found')
continue continue
} }
for (const file of urlList) { for (const file of urlList) {
...@@ -458,24 +487,26 @@ class UploadService { ...@@ -458,24 +487,26 @@ class UploadService {
const fileName = aFullPath.pop() const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
// [关键修复] 在处理文件前优先检查黑名单,避免无效检查和日志刷屏 // 2. 文件任务级别的黑名单检查
const taskKey = this._getTaskKey(cur.id, fileName) const taskKey = this._getTaskKey(cur.id, fileName)
if (this._blackList.has(taskKey)) { if (this._isInBlackList(taskKey)) {
// uni.$logger.local.info(`【上传服务】 == 快照生成时过滤黑名单任务: ${taskKey}`)
continue continue
} }
const file2Up = { ...file, recordId: cur.id, fileName, filePath } const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file) const fileExists = await this.checkFileExists(file.file)
if (!fileExists) { if (!fileExists) {
// 尝试使用 PathUtils 获取绝对路径再次检查
this.reportError('【上传服务】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file) this.reportError('【上传服务】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file)
file2Up.status = FileStatus.NotExist file2Up.status = FileStatus.NotExist
this._blackList.add(taskKey) // 文件不存在,加入黑名单
// this._addToBlackList(taskKey, 'File not exist on disk')
} }
result.push(file2Up) result.push(file2Up)
} catch (error) { } catch (error) {
this.reportError(`【上传服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file }) this.reportError(`【上传服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file })
// 解析异常,尝试加入黑名单避免死循环
const errorKey = this._getTaskKey(cur.id, file?.file)
this._addToBlackList(errorKey, `Parse error: ${error.message}`)
continue continue
} }
} }
......
import utils from '../utils' import utils from '../utils'
import PathUtils from './PathUtils'
/** /**
* 内部方法,用于获取完整的音频文件路径 * 内部方法,用于获取完整的音频文件路径
* *
...@@ -29,7 +30,7 @@ async function getLatestAudioFilePath(excludePath = '') { ...@@ -29,7 +30,7 @@ async function getLatestAudioFilePath(excludePath = '') {
* @param {string} excludeName - 需要排除的文件名 * @param {string} excludeName - 需要排除的文件名
*/ */
async function __getAudioPathName(excludeName = '') { async function __getAudioPathName(excludeName = '') {
const path = await utils.getAudioFilePath() const path = await PathUtils.getAudioFilePath()
return __getLatestFileName(path, 'uniapp_temp', excludeName) return __getLatestFileName(path, 'uniapp_temp', excludeName)
} }
/** /**
...@@ -40,7 +41,7 @@ async function __getAudioPathName(excludeName = '') { ...@@ -40,7 +41,7 @@ async function __getAudioPathName(excludeName = '') {
* @param {string} name - 文件名(不包含扩展名) * @param {string} name - 文件名(不包含扩展名)
*/ */
async function __getAudioPath(name) { async function __getAudioPath(name) {
const path = await utils.getAudioFilePath(name + '/recorder') const path = await PathUtils.getAudioFilePath(name + '/recorder')
return __getLatestFilePath(path) return __getLatestFilePath(path)
} }
/** /**
...@@ -167,6 +168,7 @@ async function __getLatestFile(directoryPath, prefix = '', excludeName = '') { ...@@ -167,6 +168,7 @@ async function __getLatestFile(directoryPath, prefix = '', excludeName = '') {
async function sleep(time) { async function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time)) return new Promise(resolve => setTimeout(resolve, time))
} }
export default { export default {
getLatestAudioFilePath, getLatestAudioFilePath,
sleep sleep
......
...@@ -16,5 +16,7 @@ import DBManager from './DBManager.js' ...@@ -16,5 +16,7 @@ import DBManager from './DBManager.js'
import RecordDto from './RecordDto.js' import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js' import TempRecord from './TempRecord.js'
import helpler from './helpler.js' import helpler from './helpler.js'
import StrategyFactory from './strategies.js'
// const SingleDBTempRecord = singleton(TempRecord) // const SingleDBTempRecord = singleton(TempRecord)
module.exports = { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler } export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory }
export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory }
/*
* @Author: limin
* @Date: 2025-01-15
* @Description: 录音管理策略工厂 (Strategy Pattern)
*/
import NativeRecorder from './NativeRecorder'
import NativeSave from './NativeSave'
import PollingSave from './PollingSave'
// 录音模式配置
// true: 使用 NativeRecorder (长录音,直接保存文件)
// false: 使用 uni.getRecorderManager + 30s 轮询保存逻辑
export const USE_NATIVE_RECORDER = true
// --- Recorder Strategies (录音器策略) ---
/**
* UniApp 原生录音策略
* 封装 uni.getRecorderManager()
*/
class UniRecorderStrategy {
constructor() {
this.manager = uni.getRecorderManager()
this.name = 'uni.getRecorderManager'
}
start(options) {
this.manager.start(options)
}
stop() {
this.manager.stop()
}
onStart(cb) {
this.manager.onStart(cb)
}
onStop(cb) {
this.manager.onStop(cb)
}
onError(cb) {
this.manager.onError(cb)
}
}
// NativeRecorder 已经实现了相同的接口,直接作为策略使用
// --- Strategy Factory (策略工厂) ---
class StrategyFactory {
// constructor(record,onTempRecordNumberChanged,attributesProvider) {
// this.record = record
// this.onTempRecordNumberChanged = onTempRecordNumberChanged
// this.attributesProvider = attributesProvider
// }
/**
* 获取录音器策略
* @returns {Object} 录音器实例 (Strategy)
*/
static getRecorderStrategy() {
// #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
return NativeRecorder
}
// #endif
return new UniRecorderStrategy()
}
/**
* 获取保存策略
* @param {Object} context 上下文 (通常是 TempRecord 实例需要的参数)
* @returns {Object} 保存策略实例
*/
static getSaveStrategy(record, onTempRecordNumberChanged, attributesProvider) {
// #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
// 实例化 NativeSaveStrategy,并传入上下文
return new NativeSave(record, onTempRecordNumberChanged, attributesProvider)
}
// #endif
// 实例化 PollingSaveStrategy,并传入上下文
return new PollingSave(record, onTempRecordNumberChanged, attributesProvider)
}
}
export default StrategyFactory
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 17:16:46 * @Date: 2024-04-08 17:16:46
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-12 16:59:04 * @LastEditTime: 2026-01-16 09:31:06
* @FilePath: \simgle_app\utils\utils.js * @FilePath: \simgle_app\utils\utils.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -146,20 +146,6 @@ var uuid = function (len, radix) { ...@@ -146,20 +146,6 @@ var uuid = function (len, radix) {
return uuid.join('') return uuid.join('')
} }
/**
* 获取文件系统根目录的完整路径
* 这个函数使用 HTML5 的 plus.io.requestFileSystem API 在私有文档目录中请求文件系统访问权限
* 当文件系统访问权限被授予后,使用 resolve 方法返回根目录的完整路径
* 这个 Promise 风格的函数可以被其他代码使用,以异步方式获取文件系统的根路径
* @returns {Promise<string>} 一个 Promise,当获取到文件系统根目录的完整路径时兑现,并返回根目录的路径作为字符串
*/
function getFilePath() {
return new Promise(resolve => {
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
resolve(fs.root.fullPath)
})
})
}
/** 比较版本号的大小 /** 比较版本号的大小
**/ **/
function compareVersions(version1, version2) { function compareVersions(version1, version2) {
...@@ -179,14 +165,6 @@ function compareVersions(version1, version2) { ...@@ -179,14 +165,6 @@ function compareVersions(version1, version2) {
// 如果版本号1 等于版本号2,则输出0 // 如果版本号1 等于版本号2,则输出0
return 0 return 0
} }
async function getFileSaveFolderOnClient() {
const rootPath = await getFilePath()
return `file://${rootPath}uniapp_save/`
}
async function getAudioFilePath(path = '') {
const rootPath = await getFilePath()
return `file://${rootPath}${path}`
}
export function serializeIfObject(value) { export function serializeIfObject(value) {
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
return JSON.stringify(value) return JSON.stringify(value)
...@@ -314,10 +292,7 @@ export default { ...@@ -314,10 +292,7 @@ export default {
throttle, throttle,
isNetWork, isNetWork,
uuid, uuid,
getFilePath,
getFileSaveFolderOnClient,
serializeIfObject, serializeIfObject,
getAudioFilePath,
calcAdd, calcAdd,
getViewInfo, getViewInfo,
setPrice, setPrice,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!