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)
},
......
/*
* @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) {}
/**
* 重置录音状态
......
......@@ -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!