Commit 16ac2da7 by liimin Committed by chenwq1

feat: 重构录音管理及上传模块,增加WebSocket调试能力

- 新增 NativeRecorder 实现长录音直接保存,提升录音稳定性
- 重构上传管理器,支持 WebView 和 UniApp 双策略,优化大文件分片上传
- 增加 WebSocket 调试命令:实时日志流、SQL执行、文件浏览器
- 引入 Vuex 活跃状态插件,自动重置超时计时器
- 优化数据库结构,统一使用 $dbRecord 管理接待记录
- 修复组件引用空值问题,增强代码健壮性
1 parent 821e184a
Showing 96 changed files with 10955 additions and 1125 deletions
<!-- <!--
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-07 17:09:53 * @Date: 2024-04-07 17:09:53
* @LastEditors: 前端 qianduan01@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2025-01-14 11:27:04 * @LastEditTime: 2026-02-05 17:52:25
* @FilePath: \gl_tape\App.vue * @FilePath: \gl_tape\App.vue
* @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
--> -->
...@@ -11,6 +11,7 @@ const PATH = ['/pages/common/caseDetail'] ...@@ -11,6 +11,7 @@ const PATH = ['/pages/common/caseDetail']
const keepAlive = uni.requireNativePlugin('Ba-KeepAliveSuit') const keepAlive = uni.requireNativePlugin('Ba-KeepAliveSuit')
import { mapState } from 'vuex' import { mapState } from 'vuex'
import { Ws } from '@/ws/Ws.js' import { Ws } from '@/ws/Ws.js'
import { RecordSaveService, UploadService } from '@/utils/recordManager/index.js'
export default { export default {
computed: { computed: {
...mapState('audio', ['isEnd', 'isStart']) ...mapState('audio', ['isEnd', 'isStart'])
...@@ -58,6 +59,12 @@ export default { ...@@ -58,6 +59,12 @@ export default {
onShow: async function () { onShow: async function () {
this.$store.dispatch('setBackgroundState', false) this.$store.dispatch('setBackgroundState', false)
this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数 this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling()
uni.onMemoryWarning(function () {
console.log('onMemoryWarningReceive')
})
// const systemInfo = await uni.$api.systemApi.getMockData(); // const systemInfo = await uni.$api.systemApi.getMockData();
// if (systemInfo.isCheckedUpdate) { // if (systemInfo.isCheckedUpdate) {
// checkUpdate(); // checkUpdate();
...@@ -73,9 +80,35 @@ export default { ...@@ -73,9 +80,35 @@ export default {
}, },
onError: function (e) { onError: function (e) {
try { try {
uni.$logger?.error({ msg: e.message || '捕获全局异常', extra: { error: typeof e == 'string' ? e : JSON.stringify(e) } }) const msg = typeof e === 'string' ? e : e.message || '捕获全局异常'
const stack = typeof e === 'object' ? e.stack || JSON.stringify(e) : ''
uni.$logger?.error({
msg: `[全局异常] ${msg}`,
extra: {
stack,
raw: e,
url: this.$route?.path || 'unknown'
}
})
} catch (error) {
console.error('日志上报失败:', error)
}
},
onUnhandledRejection: function (res) {
try {
const reason = res.reason
const msg = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : '未处理的 Promise 拒绝'
const stack = reason instanceof Error ? reason.stack : JSON.stringify(reason)
uni.$logger?.error({
msg: `[UnhandledRejection] ${msg}`,
extra: {
stack,
reason: reason,
url: this.$route?.path || 'unknown'
}
})
} catch (error) { } catch (error) {
console.log(error) console.error('Promise 异常上报失败:', error)
} }
} }
} }
......
...@@ -35,6 +35,7 @@ class Request { ...@@ -35,6 +35,7 @@ class Request {
title: '网络异常', title: '网络异常',
icon: 'none' icon: 'none'
}) })
uni.$logger.locale.error('网络异常')
reject('网络异常') reject('网络异常')
return return
} }
...@@ -59,6 +60,41 @@ class Request { ...@@ -59,6 +60,41 @@ class Request {
responseType: 'text', responseType: 'text',
timeout: timeout || 60000, timeout: timeout || 60000,
success(response) { success(response) {
// /**业务代码 */
// let { data, statusCode } = response
// if (!data || statusCode != 200) {
// uni.hideLoading()
// let errMsg = ''
// if (!data) errMsg = '获取数据失败,请重试。'
// else errMsg = '服务器暂时不可用,请稍后再次尝试。'
// return reject(errMsg)
// }
// let { code, message } = data
// if (returnAll) {
// resolve(data)
// return
// }
// if (code == 20 || code == 21) {
// console.log(params.method)
// const pages = getCurrentPages(),
// currentPage = pages[pages.length - 1]
// uni.hideLoading()
// if (currentPage.route != 'pages/common/login')
// uni.reLaunch({
// url: '/pages/common/login'
// })
// } else {
// if (code == '0') {
// resolve(data.data)
// } else {
// uni.hideLoading()
// uni.showToast({
// title: message || '系统异常',
// icon: 'none'
// })
// }
// }
try {
/**业务代码 */ /**业务代码 */
let { data, statusCode } = response let { data, statusCode } = response
if (!data || statusCode != 200) { if (!data || statusCode != 200) {
...@@ -66,6 +102,7 @@ class Request { ...@@ -66,6 +102,7 @@ class Request {
let errMsg = '' let errMsg = ''
if (!data) errMsg = '获取数据失败,请重试。' if (!data) errMsg = '获取数据失败,请重试。'
else errMsg = '服务器暂时不可用,请稍后再次尝试。' else errMsg = '服务器暂时不可用,请稍后再次尝试。'
uni.$logger.error(`${params.method}接口异常:${errMsg}`)
return reject(errMsg) return reject(errMsg)
} }
let { code, message } = data let { code, message } = data
...@@ -74,7 +111,7 @@ class Request { ...@@ -74,7 +111,7 @@ class Request {
return return
} }
if (code == 20 || code == 21) { if (code == 20 || code == 21) {
console.log(params.method) uni.$logger.local.info(`触发系统登出-> ${params.method}:${message || '系统异常'} code:${code}`)
const pages = getCurrentPages(), const pages = getCurrentPages(),
currentPage = pages[pages.length - 1] currentPage = pages[pages.length - 1]
uni.hideLoading() uni.hideLoading()
...@@ -87,16 +124,23 @@ class Request { ...@@ -87,16 +124,23 @@ class Request {
resolve(data.data) resolve(data.data)
} else { } else {
uni.hideLoading() uni.hideLoading()
uni.$logger.error(`${params.method}接口异常:${message || '系统异常'}`)
uni.showToast({ uni.showToast({
title: message || '系统异常', title: message || '系统异常',
icon: 'none' icon: 'none'
}) })
reject(message || '系统异常')
} }
} }
} catch (error) {
uni.$logger.error(`${params.method}处理异常:${error.message}`)
reject(error)
}
}, },
fail(error) { fail(error) {
uni.hideLoading() uni.hideLoading()
console.error(`${params.method}接口异常:`, error) // console.error(`${params.method}接口异常:`, error)
uni.$logger.error(`${params.method}接口异常:${error.errMsg || error.message || JSON.stringify(error)}`)
uni.showToast({ uni.showToast({
title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常', title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常',
icon: 'error' icon: 'error'
......
...@@ -65,6 +65,11 @@ ...@@ -65,6 +65,11 @@
{{item.orderFinishFlag? '成交': '战败'}} {{item.orderFinishFlag? '成交': '战败'}}
</view> </view>
</template> </template>
<template v-else>
<view @click.stop="handleDelete(item)">
<uni-icons type="trash" :size="18" color="#999"></uni-icons>
</view>
</template>
<!-- <template v-else> <!-- <template v-else>
<view :class="[ <view :class="[
'status flex', 'status flex',
...@@ -239,7 +244,8 @@ export default { ...@@ -239,7 +244,8 @@ export default {
}, },
async getRecordNum () { async getRecordNum () {
let recordFailListAll = await uni.$dbManager.getRecords(); // let recordFailListAll = await uni.$dbManager.getRecords();
let recordFailListAll = await uni.$dbRecord.getCompletedRecords();
if (typeof recordFailListAll == 'string') { if (typeof recordFailListAll == 'string') {
recordFailListAll = JSON.parse(recordFailListAll || '[]') recordFailListAll = JSON.parse(recordFailListAll || '[]')
} }
...@@ -251,24 +257,34 @@ export default { ...@@ -251,24 +257,34 @@ export default {
}, },
async getPreRecordFail () { async getPreRecordFail () {
await this.getPreRecordNum() await this.getPreRecordNum()
this.list[0] = this.preRecordFailList.map(i => { // this.list[0] = this.preRecordFailList.map(i => {
// return Object.assign(i, {
// duration: 0,
// startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.')
// })
// })
const list = this.preRecordFailList.map(i => {
return Object.assign(i, { return Object.assign(i, {
duration: 0, duration: 0,
startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.') startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.')
}) })
}) })
this.$set(this.list, 0, list)
this.isPrePage = true this.isPrePage = true
this.flag = true this.flag = true
this.nothing = this.preRecordFailList.length ? true : false this.nothing = this.preRecordFailList.length ? true : false
}, },
async getPreRecordNum () { async getPreRecordNum () {
const preRecordList = await this.recorder.getRecords() // const preRecordList = await this.recorder.getRecords()
const preRecordList = await uni.$dbRecord.getTempRecords();
this.preRecordFailList = preRecordList.reverse() this.preRecordFailList = preRecordList.reverse()
}, },
getRecordFail () { async getRecordFail () {
this.getRecordNum() await this.getRecordNum()
this.list[0] = this.recordFailList.map(i => { // this.list[0] = this.recordFailList.map(i => {
const list = this.recordFailList.map(i => {
return { return {
id: i.id,
receptionStatus: i.receptionStatus, receptionStatus: i.receptionStatus,
phoneNumber: i.phoneNumber, phoneNumber: i.phoneNumber,
salesName: i.salesName, salesName: i.salesName,
...@@ -279,6 +295,7 @@ export default { ...@@ -279,6 +295,7 @@ export default {
endTime: i.receptionEndTime.replace(/\//g, '.') endTime: i.receptionEndTime.replace(/\//g, '.')
} }
}) })
this.$set(this.list, 0, list)
this.flag = true this.flag = true
this.isPrePage = false this.isPrePage = false
this.nothing = this.recordFailList.length ? true : false this.nothing = this.recordFailList.length ? true : false
...@@ -292,7 +309,8 @@ export default { ...@@ -292,7 +309,8 @@ export default {
await uni.$isNetWork() await uni.$isNetWork()
} catch (error) { } catch (error) {
const recordSuccessList = JSON.parse(uni.$storage.get("recordSuccessList") || "{}") const recordSuccessList = JSON.parse(uni.$storage.get("recordSuccessList") || "{}")
this.list[0] = recordSuccessList[this.tabIndex] || [] // this.list[0] = recordSuccessList[this.tabIndex] || []
this.$set(this.list, 0, recordSuccessList[this.tabIndex] || [])
this.flag = true this.flag = true
return return
} }
...@@ -370,29 +388,35 @@ export default { ...@@ -370,29 +388,35 @@ export default {
if (index == 0) this.getRecordFail() if (index == 0) this.getRecordFail()
else this.getPreRecordFail() else this.getPreRecordFail()
}, },
// async submitRecord (val) {
// this.flag = false
// delete val.duration
// delete val.startTime
// const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
// if (val.recordUrlList.length > maxUploadNum) {
// const userInfo = uni.$storage.get('userInfo')
// const { customerName, phoneNumber, carModel, salesName } = val || {}
// const { name } = userInfo || {}
// uni.$logger.error({
// msg: `员工: ${name}, 客户: ${customerName}`,
// extra: {
// '手机号: ': phoneNumber,
// '姓名: ': customerName,
// '销售: ': salesName,
// '车型: ': carModel,
// '原因: ': '录音文件过长,数量' + val.recordUrlList.length
// }
// })
// }
// val.recordUrlList = val.recordUrlList.slice(0, maxUploadNum)
// await this.recorder.save(val)
// this.getRecordNum()
// await this.getPreRecordFail()
// },
async submitRecord (val) { async submitRecord (val) {
this.flag = false this.flag = false
delete val.duration const {duration,startTime,...record} = val
delete val.startTime await this.recorder.saveInternal(record)
const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
if (val.recordUrlList.length > maxUploadNum) {
const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = val || {}
const { name } = userInfo || {}
uni.$logger.error({
msg: `员工: ${name}, 客户: ${customerName}`,
extra: {
'手机号: ': phoneNumber,
'姓名: ': customerName,
'销售: ': salesName,
'车型: ': carModel,
'原因: ': '录音文件过长,数量' + val.recordUrlList.length
}
})
}
val.recordUrlList = val.recordUrlList.slice(0, maxUploadNum)
await this.recorder.save(val)
this.getRecordNum()
await this.getPreRecordFail() await this.getPreRecordFail()
}, },
searchReceptionList ({ item }, name) { searchReceptionList ({ item }, name) {
...@@ -400,8 +424,27 @@ export default { ...@@ -400,8 +424,27 @@ export default {
this[name] = item.value this[name] = item.value
this.resetData() this.resetData()
this.getReceptionList() this.getReceptionList()
},
async handleDelete(item) {
uni.showModal({
title: '提示',
content: '确定要删除这条待提交记录吗?删除后将无法恢复。',
success: async (res) => {
if (res.confirm) {
try {
// 从数据库中删除记录
await this.recorder.deleteRecord(item)
// 刷新列表
await this.getPreRecordFail()
uni.showToast({ title: '删除成功', icon: 'success' })
} catch (error) {
uni.$logger.local.error('删除待提交记录失败:'+ error.message)
uni.showToast({ title: '删除失败', icon: 'none' })
} }
}
}
})
},
} }
} }
</script> </script>
......
<template> <template>
<view class="container" @click="handleTouchStart"> <view class="container" @click="handleTouchStart">
<view :class="['home', { show: !id && showHome }]"> <view :class="['home', { show: !id && showHome }]">
<left-side :userInfo="userInfo" :tabIndex.sync="tabIndex" ref="leftBox" @changeTab="changeTab" <left-side :userInfo="userInfo" :tabIndex.sync="tabIndex" ref="leftBox" @changeTab="changeTab" @stopAudio="stopAudio" @showReadCountTips="showReadCountTips" @closeTips="closeTips" @closeActivityCenter="closeActivityCenter" />
@stopAudio="stopAudio" @showReadCountTips="showReadCountTips" @closeTips="closeTips"
@closeActivityCenter="closeActivityCenter" />
<view class="tips-box" :style="tipsObject.style" @click.stop="closeTips">{{ tipsObject.text }}</view> <view class="tips-box" :style="tipsObject.style" @click.stop="closeTips">{{ tipsObject.text }}</view>
<view class="right-side"> <view class="right-side">
<view :class="['app-content-box right-content', { 'show-content-box': tabIndex == 0 }]"> <view :class="['app-content-box right-content', { 'show-content-box': tabIndex == 0 }]">
...@@ -21,9 +19,7 @@ ...@@ -21,9 +19,7 @@
<slot name="swiperCustom" /> <slot name="swiperCustom" />
</template> </template>
<template v-else> <template v-else>
<swiper-component :moduleList="moduleList" @click="swiperClick" :stopAutoPlay="previewOff" <swiper-component :moduleList="moduleList" @click="swiperClick" :stopAutoPlay="previewOff" :imgKey="bannerKey" :loadComplete="loadComplete" :noDataObject="swiperNoDataObject"></swiper-component>
:imgKey="bannerKey" :loadComplete="loadComplete"
:noDataObject="swiperNoDataObject"></swiper-component>
</template> </template>
</view> </view>
</view> </view>
...@@ -46,8 +42,7 @@ ...@@ -46,8 +42,7 @@
<component :is="'Point'" ref="pointRef" :userInfo="userInfo" @showPage="handleShowPage" /> <component :is="'Point'" ref="pointRef" :userInfo="userInfo" @showPage="handleShowPage" />
</view> </view>
<template v-if="tabIndex != 0 && tabIndex != 99"> <template v-if="tabIndex != 0 && tabIndex != 99">
<component :is="componentName" ref="pointRef" :userInfo="userInfo" @showPage="handleShowPage" <component :is="componentName" ref="pointRef" :userInfo="userInfo" @showPage="handleShowPage" :isPermissionFunction="isPermission" />
:isPermissionFunction="isPermission" />
</template> </template>
</view> </view>
<view class="store-addr" v-if="footerBox"> <view class="store-addr" v-if="footerBox">
...@@ -62,9 +57,7 @@ ...@@ -62,9 +57,7 @@
<component :is="pointComponentName" @backHome="backHome" @jump="jump" :transfer="transfer" /> <component :is="pointComponentName" @backHome="backHome" @jump="jump" :transfer="transfer" />
</view> </view>
<!-- 未点击开始接待,弹窗 --> <!-- 未点击开始接待,弹窗 -->
<MessageBox ref="previewRef" @confirm="previewHandler('preview', true)" :popupW="704" <MessageBox ref="previewRef" @confirm="previewHandler('preview', true)" :popupW="704" content="直接点击素材可进行预览,若面向车主展示,请点击「开始接待」" confirmBtnText="预览素材" @cancel="previewHandler('previewCancel')" @close="previewHandler('previewClose')"></MessageBox>
content="直接点击素材可进行预览,若面向车主展示,请点击「开始接待」" confirmBtnText="预览素材" @cancel="previewHandler('previewCancel')"
@close="previewHandler('previewClose')"></MessageBox>
<!-- 停留弹框 --> <!-- 停留弹框 -->
<!-- <MessageBox ref="tipBox" @cancel="tipCancel" @confirm="tipConfirm" content="系统检测到您在当前页面停留较久,是否仍在客户接待中?" cancelBtnText="否" confirmBtnText="是"></MessageBox> --> <!-- <MessageBox ref="tipBox" @cancel="tipCancel" @confirm="tipConfirm" content="系统检测到您在当前页面停留较久,是否仍在客户接待中?" cancelBtnText="否" confirmBtnText="是"></MessageBox> -->
<!-- 退出弹框 --> <!-- 退出弹框 -->
...@@ -88,7 +81,12 @@ ...@@ -88,7 +81,12 @@
<!-- 升级弹框 --> <!-- 升级弹框 -->
<update-box /> <update-box />
<slot name="content" /> <slot name="content" />
<web-view @message="handlerMessage" ref="webview" src="/hybrid/html/index.html"></web-view> <!-- <web-view
@message="handlerMessage"
ref="webview"
src="/hybrid/html/index.html"
></web-view> -->
<web-view ref="uploaderWebview" src="/hybrid/html/index.html" @message="handleUploadMessageNew" :webview-styles="webviewStyles"></web-view>
<!-- <web-view <!-- <web-view
ref="studyWebview" ref="studyWebview"
:src="jumpUrl" :src="jumpUrl"
...@@ -96,24 +94,17 @@ ...@@ -96,24 +94,17 @@
></web-view> --> ></web-view> -->
<!-- 学习中心 等级考试弹窗 --> <!-- 学习中心 等级考试弹窗 -->
<StudyPopup :show.sync="showStudyPopup" title="开始您的学习之旅" <StudyPopup :show.sync="showStudyPopup" title="开始您的学习之旅" :topImage="require('@/assets/images/common/study-center-bg.png')" :topImageWidth="848" :topImageHeight="248">
:topImage="require('@/assets/images/common/study-center-bg.png')" :topImageWidth="848" :topImageHeight="248"> <StudyPopupContent cardTitle="个性化学习路径" description="根据您当前的学习情况,我们将为您定制专属的学习计划,帮助您高效提升技能,实现职业突破。" :listItems="['基于当前能力水平评估', '结合岗位发展目标制定', '定期跟踪学习进度和效果']" tipText="true" :courseName="courseInfo.title" buttonText="开始测评" @cancel="handleStudyPopupCancel" @button-click="handleStartAssessment" />
<StudyPopupContent cardTitle="个性化学习路径" description="根据您当前的学习情况,我们将为您定制专属的学习计划,帮助您高效提升技能,实现职业突破。"
:listItems="['基于当前能力水平评估', '结合岗位发展目标制定', '定期跟踪学习进度和效果']" tipText="true" :courseName="courseInfo.title"
buttonText="开始测评" @cancel="handleStudyPopupCancel" @button-click="handleStartAssessment" />
</StudyPopup> </StudyPopup>
<!-- 考试提交确认弹窗 --> <!-- 考试提交确认弹窗 -->
<StudyPopup :show.sync="showExamPopup" title="" :width="848" :height="examPopInfo.isExamLoading ? 740 : 656" <StudyPopup :show.sync="showExamPopup" title="" :width="848" :height="examPopInfo.isExamLoading ? 740 : 656" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248">
:topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248"> <ExamSubmitPopup :isLoading="examPopInfo.isExamLoading" :showError="examPopInfo.showError" :confirmText="examPopInfo.confirmText" @cancel="handleExamCancel" @confirm="handleExamConfirm" />
<ExamSubmitPopup :isLoading="examPopInfo.isExamLoading" :showError="examPopInfo.showError"
:confirmText="examPopInfo.confirmText" @cancel="handleExamCancel" @confirm="handleExamConfirm" />
</StudyPopup> </StudyPopup>
<!-- 学习中心权限弹窗 --> <!-- 学习中心权限弹窗 -->
<StudyPopup :show.sync="showStudyPermissionPopup" title="" :width="848" :height="870" <StudyPopup :show.sync="showStudyPermissionPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden">
:topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248"
style="overflow: hidden">
<StudyCenterPermissionPopup :lockReason="lockReason" @confirm="handleStudyPermissionConfirm" /> <StudyCenterPermissionPopup :lockReason="lockReason" @confirm="handleStudyPermissionConfirm" />
</StudyPopup> </StudyPopup>
<activity-popup ref="activityPopup" @JumpActivityCenter="JumpActivityCenter"></activity-popup> <activity-popup ref="activityPopup" @JumpActivityCenter="JumpActivityCenter"></activity-popup>
...@@ -121,9 +112,7 @@ ...@@ -121,9 +112,7 @@
<uni-popup-message type="error" :message="errorMsg" :duration="1500"></uni-popup-message> <uni-popup-message type="error" :message="errorMsg" :duration="1500"></uni-popup-message>
</uni-popup> </uni-popup>
<!-- 异常订单锁单 --> <!-- 异常订单锁单 -->
<ErrorOrderPopup :show.sync="showErrorOrderPopup" title="" :width="848" :height="870" <ErrorOrderPopup :show.sync="showErrorOrderPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden">
:topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248"
style="overflow: hidden">
<view> <view>
<view class="error-order-title">异常订单提醒</view> <view class="error-order-title">异常订单提醒</view>
<view class="error-order-content">存在{{ abnormalOrderCount }} 条异常订单未处理,请尽快处理!</view> <view class="error-order-content">存在{{ abnormalOrderCount }} 条异常订单未处理,请尽快处理!</view>
...@@ -133,9 +122,7 @@ ...@@ -133,9 +122,7 @@
<!-- <view class="footer-btn cancel" @click="showErrorOrderPopup=false"> <!-- <view class="footer-btn cancel" @click="showErrorOrderPopup=false">
取消 取消
</view> --> </view> -->
<view class="footer-btn sure flex-1" @click="showErrorOrderPopup=false"> <view class="footer-btn sure flex-1" @click="showErrorOrderPopup = false">好的</view>
好的
</view>
</view> </view>
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
...@@ -176,8 +163,10 @@ import ExamSubmitPopup from '@/components/ExamSubmitPopup.vue' ...@@ -176,8 +163,10 @@ import ExamSubmitPopup from '@/components/ExamSubmitPopup.vue'
import StudyCenterPermissionPopup from '@/components/StudyCenterPermissionPopup.vue' import StudyCenterPermissionPopup from '@/components/StudyCenterPermissionPopup.vue'
import ActivityPopup from './components/ActivityPopup.vue' import ActivityPopup from './components/ActivityPopup.vue'
import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue' import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue'
import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js'
export default { export default {
mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin], // mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin],
mixins: [recorder, versionCheck, interceptionMixin],
components: { components: {
ReceptionCenter, ReceptionCenter,
StudyCenter, StudyCenter,
...@@ -254,6 +243,14 @@ export default { ...@@ -254,6 +243,14 @@ export default {
errorMsg: '', errorMsg: '',
showErrorOrderPopup: false, showErrorOrderPopup: false,
abnormalOrderCount: 0, abnormalOrderCount: 0,
webviewStyles: Object.freeze({
progress: false,
width: '10px',
height: '10px',
position: 'absolute',
top: '-1000px',
left: '-1000px'
})
} }
}, },
beforeDestroy() { beforeDestroy() {
...@@ -270,6 +267,10 @@ export default { ...@@ -270,6 +267,10 @@ export default {
}) })
const userInfo = uni.$storage.get('userInfo') || {} const userInfo = uni.$storage.get('userInfo') || {}
this.userInfo = userInfo this.userInfo = userInfo
FileUploadManager.init({
webviewRef: this.$refs.uploaderWebview,
vueContext: this
})
if (this.checkRecordAudio) permision.requestAndroidPermission('android.permission.RECORD_AUDIO') // 进入界面时检查权限 if (this.checkRecordAudio) permision.requestAndroidPermission('android.permission.RECORD_AUDIO') // 进入界面时检查权限
// 检查是否锁单 // 检查是否锁单
const { abnormalOrderNum } = await this.getAbnormalOrderLock() const { abnormalOrderNum } = await this.getAbnormalOrderLock()
...@@ -279,6 +280,10 @@ export default { ...@@ -279,6 +280,10 @@ export default {
return return
} }
}, },
beforeDestroy() {
// 清理 FileUploadManager 资源
FileUploadManager.destroy()
},
provide() { provide() {
return { return {
showPage: this.handleShowPage, showPage: this.handleShowPage,
...@@ -302,7 +307,7 @@ export default { ...@@ -302,7 +307,7 @@ export default {
}, },
activityWindowPopStatus() { activityWindowPopStatus() {
return this.$store.getters.activityWindowPopStatus return this.$store.getters.activityWindowPopStatus
}, }
}, },
watch: { watch: {
activityWindowPopStatus: { activityWindowPopStatus: {
...@@ -317,9 +322,9 @@ export default { ...@@ -317,9 +322,9 @@ export default {
created() { created() {
// 监听自定义事件 // 监听自定义事件
uni.$on('pageBack', () => { uni.$on('pageBack', () => {
this.$refs.leftBox.getMessageInfo(); this.$refs.leftBox.getMessageInfo()
this.$refs.messageRef.getMessageSummary() this.$refs.messageRef.getMessageSummary()
}); })
}, },
methods: { methods: {
// 处理开始测评(参考 detail.vue 的实现) // 处理开始测评(参考 detail.vue 的实现)
...@@ -726,14 +731,20 @@ export default { ...@@ -726,14 +731,20 @@ export default {
} }
this.$refs.leftBox.handleActivityCenter() this.$refs.leftBox.handleActivityCenter()
}, },
handleErrorOrderPopupSure(){ handleErrorOrderPopupSure() {
let pageName = { let pageName = {
0: 'equity', 0: 'equity',
1: 'boutique', 1: 'boutique'
}[this.sceneType] }[this.sceneType]
uni.navigateTo({ uni.navigateTo({
url: `/pages/${pageName}/tool/index?componentName=OrderManagement` url: `/pages/${pageName}/tool/index?componentName=OrderManagement`
}) })
},
handleUploadMessageNew(event) {
FileUploadManager.handleWebViewMessage(event)
},
handleTouchStart() {
uni.$emit('reset_timeout')
} }
} }
} }
...@@ -1022,7 +1033,7 @@ export default { ...@@ -1022,7 +1033,7 @@ export default {
margin-top: toRpx(64); margin-top: toRpx(64);
margin-bottom: toRpx(48); margin-bottom: toRpx(48);
width: 100%; width: 100%;
.cancel{ .cancel {
height: toRpx(88); height: toRpx(88);
border-radius: toRpx(64); border-radius: toRpx(64);
opacity: 1; opacity: 1;
...@@ -1034,7 +1045,7 @@ export default { ...@@ -1034,7 +1045,7 @@ export default {
font-size: toRpx(32); font-size: toRpx(32);
font-weight: 400; font-weight: 400;
} }
.sure{ .sure {
height: toRpx(88); height: toRpx(88);
border-radius: toRpx(64); border-radius: toRpx(64);
opacity: 1; opacity: 1;
......
<template> <template>
<view :class="['swiper-box',{'type-2':swiperType == 2}]"> <view :class="['swiper-box', { 'type-2': swiperType == 2 }]">
<template v-if="loadComplete"> <template v-if="loadComplete">
<template v-if="moduleList.length"> <template v-if="moduleList.length">
<movable-area <view
class="swiper-carousel" class="swiper-carousel"
@touchstart="starts" @touchstart="starts"
@touchmove="moves"
@touchend="ends" @touchend="ends"
> >
<template v-for="(item,index) in imagelist"> <template v-for="(item, index) in imagelist">
<movable-view <view
:key="index" :key="index"
:class="['carousel-block',item.class]" :class="['carousel-block', item.class]"
@click.stop="changeBlock(item)" @click.stop="changeBlock(item)"
direction="horizontal" :style="getItemStyle(item)"
@change="change"
:disabled="item.class != 'block-center' || moduleList.length == 1"
:x="item.class != 'block-center' ? 0 : viewX"
:data-index="item.isIndex"
v-if="item.imgUrl" v-if="item.imgUrl"
> >
<view class="transform-container">
<template v-if="custom"> <template v-if="custom">
<slot <slot :content="item" name="swiper"></slot>
:content="item"
name="swiper"
></slot>
</template> </template>
<template v-else> <template v-else>
<image <image
class="image-block" class="image-block"
:src="item.imgUrl" :src="item.imgUrl"
mode="aspectFill"
@load="item.hide = true" @load="item.hide = true"
/> />
<view <view class="bg" v-if="item.hide"></view>
class="bg" <view class="mask"></view>
v-if="item.hide"
></view>
</template> </template>
<!-- <view :class="['error-block',{hide:item.hide}]"> </view>
<uni-icons </view>
:type="icon"
:size="size"
color="#909399"
></uni-icons>
</view> -->
</movable-view>
</template> </template>
</movable-area> </view>
<view class="module-title flex"> <view class="module-title flex">
{{moduleTitle}} {{ moduleTitle }}
</view> </view>
<view class="module-dots flex"> <view class="module-dots flex">
<template v-for="(i,index) in moduleList"> <template v-for="(i, index) in moduleList">
<div <div
:class="['dot', {'active': index == currentIndex}]" :class="['dot', { active: index == currentIndex }]"
:key="index" :key="index"
> ></div>
</div>
</template> </template>
</view> </view>
</template> </template>
...@@ -68,22 +55,13 @@ ...@@ -68,22 +55,13 @@
:style="noDataObject.style" :style="noDataObject.style"
/> />
</template> </template>
{{noDataObject.text || '该场景尚未配置素材,请联系总部人员'}} {{ noDataObject.text || '该场景尚未配置素材,请联系总部人员' }}
</view> </view>
</template> </template>
</template> </template>
<template v-else> <template v-else>
<view class="loading flex"> <view class="loading flex">
<image <image class="gif" src="../assets/images/common/loadding.gif" />
class="gif"
src="../assets/images/common/loadding.gif"
/>
<!-- <uni-icons
class="icon"
type="refreshempty"
:size="120"
color="#3773f8"
></uni-icons> -->
</view> </view>
</template> </template>
</view> </view>
...@@ -164,6 +142,7 @@ export default { ...@@ -164,6 +142,7 @@ export default {
autoPlayTimer: null, autoPlayTimer: null,
endTimer: null, endTimer: null,
playStatus: true, playStatus: true,
isTouching: false,
style_object: Object.freeze([ style_object: Object.freeze([
{ index: 0, class: 'block-left' }, { index: 0, class: 'block-left' },
{ index: 1, class: 'block-center' }, { index: 1, class: 'block-center' },
...@@ -174,17 +153,59 @@ export default { ...@@ -174,17 +153,59 @@ export default {
} }
}, },
beforeDestroy () { beforeDestroy () {
// 组件销毁时清理自动播放定时器 this._isDestroyed = true
// 组件销毁时清理所有定时器
if (this.autoPlayTimer) { if (this.autoPlayTimer) {
clearTimeout(this.autoPlayTimer); clearTimeout(this.autoPlayTimer);
this.autoPlayTimer = null; this.autoPlayTimer = null;
} }
if (this.endTimer) {
clearTimeout(this.endTimer);
this.endTimer = null;
}
}, },
methods: { methods: {
getItemStyle(item) {
// 基础样式
let style = {}
// 3D 变换
let transform = ''
// 计算拖动时的实时偏移
let moveX = 0
if (this.isTouching) {
moveX = this.viewX
}
if (item.class === 'block-left') {
transform = `translateX(calc(-45% + ${moveX * 0.5}px)) translateZ(-100px) rotateY(25deg) scale(0.9)`
style.zIndex = 10
style.opacity = 0.8
} else if (item.class === 'block-right') {
transform = `translateX(calc(45% + ${moveX * 0.5}px)) translateZ(-100px) rotateY(-25deg) scale(0.9)`
style.zIndex = 10
style.opacity = 0.8
} else {
// block-center
transform = `translateX(${moveX}px) translateZ(0) rotateY(0deg) scale(1)`
style.zIndex = 20
style.opacity = 1
}
// 拖动时取消过渡动画,保证跟手性
if (this.isTouching) {
style.transition = 'none'
}
style.transform = transform
return style
},
getDatalist () { getDatalist () {
if (this.moduleList) { if (this.moduleList) {
this.currentIndex = 0 this.currentIndex = 0
this.datalist = JSON.parse(JSON.stringify(this.moduleList)) // 浅拷贝即可,避免昂贵的 JSON 序列化
this.datalist = [...this.moduleList]
let num = 3 let num = 3
let diff = num - this.moduleList.length let diff = num - this.moduleList.length
if (diff > 0) { if (diff > 0) {
...@@ -199,7 +220,9 @@ export default { ...@@ -199,7 +220,9 @@ export default {
}, },
getImagelist () { getImagelist () {
let { datalist, autoplay, style_object } = this let { datalist, autoplay, style_object } = this
this.imagelist = JSON.parse(JSON.stringify(style_object)) // 优化:使用 map 进行浅拷贝,避免 JSON.parse(JSON.stringify)
this.imagelist = style_object.map(item => ({ ...item }))
this.imagelist.forEach((item, index) => { this.imagelist.forEach((item, index) => {
const dataIndex = index - 1 < 0 ? datalist.length - 1 : index - 1 const dataIndex = index - 1 < 0 ? datalist.length - 1 : index - 1
item.isIndex = dataIndex item.isIndex = dataIndex
...@@ -211,6 +234,7 @@ export default { ...@@ -211,6 +234,7 @@ export default {
if (autoplay) this.autoPlayFunction() if (autoplay) this.autoPlayFunction()
}, },
autoPlayFunction () { autoPlayFunction () {
if (this._isDestroyed) return
if (!this.autoplay) return if (!this.autoplay) return
if (this.stopAutoPlay || !this.playStatus) { if (this.stopAutoPlay || !this.playStatus) {
if (this.autoPlayTimer) { if (this.autoPlayTimer) {
...@@ -221,6 +245,7 @@ export default { ...@@ -221,6 +245,7 @@ export default {
} }
// 设置新的自动播放定时器 // 设置新的自动播放定时器
this.autoPlayTimer = setTimeout(() => { this.autoPlayTimer = setTimeout(() => {
if (this._isDestroyed) return // 双重检查
// 再次检查是否需要停止播放 // 再次检查是否需要停止播放
if (this.stopAutoPlay || !this.playStatus) { if (this.stopAutoPlay || !this.playStatus) {
clearTimeout(this.autoPlayTimer); clearTimeout(this.autoPlayTimer);
...@@ -235,13 +260,13 @@ export default { ...@@ -235,13 +260,13 @@ export default {
updateCarouselPositions (direction = 'left') { updateCarouselPositions (direction = 'left') {
let { imagelist, datalist, moduleList } = this, let { imagelist, datalist, moduleList } = this,
len = datalist.length - 1, len = datalist.length - 1,
list = JSON.parse(JSON.stringify(this.style_object)) // 优化:浅拷贝 style_object
list = this.style_object
if (moduleList.length == 2) { if (moduleList.length == 2) {
this.imagelist.forEach((item, index) => { this.imagelist.forEach((item, index) => {
if (index != 0) { if (index != 0) {
let toor = item.isToor == 1 ? 2 : 1 let toor = item.isToor == 1 ? 2 : 1
item.isToor = toor item.isToor = toor
item.imgUrl = ''
item.class = list[toor].class item.class = list[toor].class
item.x = 0 item.x = 0
let isIndex = item.isIndex let isIndex = item.isIndex
...@@ -256,7 +281,6 @@ export default { ...@@ -256,7 +281,6 @@ export default {
(item.isToor - 1) < 0 ? imagelist.length - 1 : item.isToor - 1 (item.isToor - 1) < 0 ? imagelist.length - 1 : item.isToor - 1
: (item.isToor + 1) > imagelist.length - 1 ? 0 : item.isToor + 1 : (item.isToor + 1) > imagelist.length - 1 ? 0 : item.isToor + 1
item.isToor = toor item.isToor = toor
item.imgUrl = ''
item.class = list[toor].class item.class = list[toor].class
item.x = 0 item.x = 0
let isIndex = item.isIndex let isIndex = item.isIndex
...@@ -289,28 +313,40 @@ export default { ...@@ -289,28 +313,40 @@ export default {
starts (e) { starts (e) {
this.ismove = e.touches[0].pageX this.ismove = e.touches[0].pageX
this.playStatus = false this.playStatus = false
this.isTouching = true
this.viewX = 0
if (this.endTimer) { if (this.endTimer) {
clearTimeout(this.endTimer); clearTimeout(this.endTimer);
this.endTimer = null; this.endTimer = null;
return; }
if (this.autoPlayTimer) {
clearTimeout(this.autoPlayTimer)
this.autoPlayTimer = null
} }
}, },
moves (e) {
if (!this.isTouching) return
let pageX = e.touches[0].pageX
this.viewX = pageX - this.ismove
},
ends (e) { ends (e) {
this.isTouching = false
let { moduleList } = this let { moduleList } = this
if (moduleList.length == 1) return if (moduleList.length == 1) return
let { blockX, ismove } = this
let pageX = e.changedTouches[0].pageX let moveDistance = this.viewX
let nums = ismove - pageX this.viewX = 0 // 重置偏移量,让CSS transition接管回弹或切换动画
if (nums == 0) return
if (!(nums > 50 || blockX < -30) || !(nums < -50 || blockX > 30)) { // 阈值判断,超过 50px 或者快速滑动则切换
this.viewX = -10 if (moveDistance > 50) {
setTimeout(() => { this.updateCarouselPositions('right')
this.viewX = 0 } else if (moveDistance < -50) {
}, 16) this.updateCarouselPositions('left')
} }
if (nums > 50 || blockX < -30) this.updateCarouselPositions()
if (nums < -50 || blockX > 30) this.updateCarouselPositions('right') // 恢复自动播放
this.endTimer = setTimeout(() => { this.endTimer = setTimeout(() => {
if (this._isDestroyed) return
if (!this.playStatus) { if (!this.playStatus) {
this.playStatus = true this.playStatus = true
this.autoPlayFunction() this.autoPlayFunction()
...@@ -352,72 +388,58 @@ export default { ...@@ -352,72 +388,58 @@ export default {
width: 100%; width: 100%;
height: toRpx(440); height: toRpx(440);
position: relative; position: relative;
overflow: hidden; // overflow: hidden; // 移除 hidden 以显示 3D 效果
perspective: 1000px; // 添加透视
display: flex;
justify-content: center;
align-items: center;
.carousel-block { .carousel-block {
position: absolute; position: absolute;
border-radius: 10upx; width: toRpx(624);
overflow: hidden; height: toRpx(408);
box-shadow: 0 0 5px #0000001a;
transition: all 0.2s ease; /* 添加过渡 */
border: toRpx(2) solid #ffffffb3;
box-shadow: 0 toRpx(3) toRpx(12) 0 #5294ff33;
border-radius: toRpx(24); border-radius: toRpx(24);
.image-block { overflow: hidden;
position: absolute; background-color: #fff;
left: 0; box-shadow: 0 toRpx(8) toRpx(24) 0 rgba(0, 0, 0, 0.1);
top: 0; transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
transform-style: preserve-3d;
// 默认居中
left: 50%;
top: 50%;
margin-left: toRpx(-312); // width的一半
margin-top: toRpx(-204); // height的一半
.transform-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
background-size: 100% 100%; position: relative;
z-index: 5;
} }
.bg {
position: absolute; .image-block {
left: 0;
top: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
background: linear-gradient(180deg, #e6edff 0%, #f0f4ff 100%); border-radius: toRpx(24);
z-index: 4;
} }
.error-block {
.mask {
position: absolute; position: absolute;
left: 0;
top: 0; top: 0;
left: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: #f5f7fa; background: rgba(0,0,0,0.1); // 侧边遮罩
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
}
.hide {
opacity: 0; opacity: 0;
transition: opacity 0.5s;
pointer-events: none;
} }
&.block-left, &.block-right {
.mask {
opacity: 1;
} }
.block-left,
.block-right {
top: toRpx(68);
height: toRpx(306);
width: toRpx(468);
transition: all 0.1s;
}
.block-left {
left: toRpx(150);
z-index: 10;
}
.block-right {
left: toRpx(592);
z-index: 15;
} }
.block-center {
left: toRpx(294);
top: toRpx(16);
height: toRpx(408);
width: toRpx(624);
z-index: 20;
transition: all 0.3s;
} }
} }
.module-title { .module-title {
...@@ -466,7 +488,6 @@ export default { ...@@ -466,7 +488,6 @@ export default {
top: toRpx(68); top: toRpx(68);
height: toRpx(306); height: toRpx(306);
width: toRpx(604); width: toRpx(604);
transition: all 0.1s;
} }
.block-left { .block-left {
left: toRpx(88); left: toRpx(88);
......
...@@ -129,13 +129,24 @@ export default { ...@@ -129,13 +129,24 @@ export default {
border-radius: toRpx(16); border-radius: toRpx(16);
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
transition: all 0.05s;
overflow: hidden; overflow: hidden;
opacity: 0;
position: relative; position: relative;
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.95); // 增加不透明度,提升质感
visibility: hidden; backdrop-filter: blur(10px); // 添加毛玻璃效果,更高级
height: 0;
// 初始状态
max-height: 0;
opacity: 0;
transform: translateY(-20rpx) scale(0.95); // 稍微上移并缩小,制造弹出感
transform-origin: top center;
// 优化动画曲线:更干脆利落 (cubic-bezier)
// 缩短时间:0.4s -> 0.3s,更跟手不拖沓
transition:
max-height 0.3s cubic-bezier(0.215, 0.61, 0.355, 1),
opacity 0.2s linear,
transform 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
&::after { &::after {
position: absolute; position: absolute;
content: ''; content: '';
...@@ -144,9 +155,10 @@ export default { ...@@ -144,9 +155,10 @@ export default {
left: 0; left: 0;
right: 0; right: 0;
bottom: 0; bottom: 0;
filter: blur(toRpx(8)); // filter: blur(toRpx(8)); // 移除原来的模糊,改用 backdrop-filter
z-index: -1; z-index: -1;
} }
// ... 其他原有样式保持不变
.title { .title {
width: toRpx(120); width: toRpx(120);
height: toRpx(56); height: toRpx(56);
...@@ -161,6 +173,7 @@ export default { ...@@ -161,6 +173,7 @@ export default {
max-height: 60vh; max-height: 60vh;
overflow-y: auto; overflow-y: auto;
} }
// ... item 样式
.item { .item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -183,21 +196,17 @@ export default { ...@@ -183,21 +196,17 @@ export default {
} }
.showList { .showList {
display: flex; display: flex;
// 展开状态:给予足够大的max-height
max-height: toRpx(1000); // 预估一个足够大的值,或者使用 100vh
opacity: 1; opacity: 1;
transform: translateY(0) scale(1); // 恢复原位原大小
padding-bottom: toRpx(16); padding-bottom: toRpx(16);
animation: scale-up-top-right 0.4s; // 移除之前的 animation
visibility: visible; // animation: scale-up-top-right 0.4s;
height: auto; // visibility: visible; // 不需要 visibility,因为 height 0 已经隐藏了内容
} // height: auto; // 使用 max-height 做动画
@keyframes scale-up-top-right {
0% {
transform: scale(0.5);
transform-origin: top right;
}
100% {
transform: scale(1);
transform-origin: top right;
}
} }
// 移除之前的 keyframes
// @keyframes scale-up-top-right { ... }
} }
</style> </style>
\ No newline at end of file \ No newline at end of file
...@@ -47,6 +47,14 @@ ...@@ -47,6 +47,14 @@
<script src="js/OSSUpLoader.js"></script> <script src="js/OSSUpLoader.js"></script>
<script> <script>
// document.addEventListener('UniAppJSBridgeReady', function(){ // document.addEventListener('UniAppJSBridgeReady', function(){
document.addEventListener('UniAppJSBridgeReady', function() {
// 主动告知宿主环境,Webview 已准备就绪
uni.postMessage({
data: {
action: 'webview_ready'
}
});
});
/** /**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息 * 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID * @param {string} accessKeyId - OSS 访问密钥 ID
......
...@@ -122,17 +122,20 @@ class OSSUpLoader { ...@@ -122,17 +122,20 @@ class OSSUpLoader {
* @throws {Error} 如果文件路径转换失败,将抛出错误 * @throws {Error} 如果文件路径转换失败,将抛出错误
*/ */
_upload(fileName, file, callback) { _upload(fileName, file, callback) {
const partSize = this._getOptimalPartSize(file.size)
this.client this.client
.multipartUpload(this.ossFolder + fileName, file, { .multipartUpload(this.ossFolder + fileName, file, {
// 获取分片上传进度、断点和返回值。 // 获取分片上传进度、断点和返回值。
progress: (p, checkpoint, res) => { progress: (p, checkpoint, res) => {
this.currentCheckpoint = checkpoint
console.log(p) console.log(p)
this.currentCheckpoint = checkpoint
}, },
// 设置并发上传的分片数量。 // 设置并发上传的分片数量。
parallel: this.parallel, parallel: this.parallel,
//分片大小(kb) 最小为100kb 默认500kb //分片大小(kb) 最小为100kb 默认500kb
partSize: 1024 * this.partSize, // partSize: 1024 * this.partSize,
// 分片大小(bytes)
partSize: partSize,
timeout: this.timeout, timeout: this.timeout,
mime: this.mime mime: this.mime
}) })
...@@ -180,6 +183,41 @@ class OSSUpLoader { ...@@ -180,6 +183,41 @@ class OSSUpLoader {
}) })
} }
/**
* 根据文件大小计算最优分片大小
* 策略:文件越大,分片越大,以减少分片数量和请求开销
* @param {number} fileSize - 文件大小 (bytes)
* @returns {number} 分片大小 (bytes)
*/
_getOptimalPartSize(fileSize) {
const MB = 1024 * 1024
// 定义分片策略阶梯 (阈值 -> 分片大小)
// 注意:顺序从大到小排列,匹配即止
const strategies = [
// 优化后的分片策略 (平衡网络开销与失败重试成本)
// 1GB+: 10MB 分片 (约100+个请求,并发效率高)
{ threshold: 1 * 1024 * MB, size: 10 * MB },
// 100MB+: 5MB 分片 (20-200个请求,适中)
{ threshold: 100 * MB, size: 5 * MB },
// 50MB+: 2MB 分片 (25-50个请求)
{ threshold: 50 * MB, size: 2 * MB },
// 10MB+: 1MB 分片 (10-50个请求)
// 避免小文件分片过小导致 HTTP 握手开销占比过高
{ threshold: 10 * MB, size: 1 * MB }
// <10MB: 使用默认 partSize (通常 1MB)
]
for (const { threshold, size } of strategies) {
if (fileSize > threshold) {
return size
}
}
// 默认回退到配置的基础大小
return this.partSize * 1024
}
/** /**
* 将文件路径转换为可下载的文件对象 * 将文件路径转换为可下载的文件对象
* *
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-03 18:53:43 * @Date: 2025-01-03 18:53:43
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-01-07 15:34:10 * @LastEditTime: 2026-02-10 11:04:43
* @FilePath: \gl_tape\init.js * @FilePath: \gl_tape\init.js
*/ */
import { DBRecord } from './utils/recordManager/index' import { DBRecord } from './utils/recordManager/index'
...@@ -30,8 +30,8 @@ uni.$throttle = utils.throttle ...@@ -30,8 +30,8 @@ uni.$throttle = utils.throttle
uni.$isNetWork = utils.isNetWork uni.$isNetWork = utils.isNetWork
uni.$logger = logger uni.$logger = logger
// uni.$recordManager = RecordManager.getInstance() // uni.$recordManager = RecordManager.getInstance()
uni.$dbTempRecord = new DBRecord() // uni.$dbTempRecord = new DBRecord()
uni.$dbManager = new DBManager() // uni.$dbManager = new DBManager()
uni.$track = new Track() uni.$track = new Track()
console.log('init.js', HOST['eva']) console.log('init.js', HOST['eva'])
uni.signHttpConfig = { uni.signHttpConfig = {
...@@ -44,6 +44,10 @@ uni.signHttpConfig = { ...@@ -44,6 +44,10 @@ uni.signHttpConfig = {
sessionParamName: 'sessionId', sessionParamName: 'sessionId',
sessionId: _ => uni.$storage?.get('sessionId') sessionId: _ => uni.$storage?.get('sessionId')
}, },
sentry: {
enable: true, // 是否启用Sentry错误上报
dsn: 'https://cce6491788ff4b8899d8f912e6982a96@sentry.glsx.com.cn/42'
},
response: { response: {
code_key: 'code', code_key: 'code',
code_success_value: '0', code_success_value: '0',
...@@ -92,7 +96,24 @@ uni.signHttpConfig = { ...@@ -92,7 +96,24 @@ uni.signHttpConfig = {
} }
} }
!(async _ => { // !(async _ => {
await uni.$dbManager.init() // await uni.$dbManager.init()
await uni.$dbTempRecord.init() // await uni.$dbTempRecord.init()
})() // })()
if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord()
}
// 导出数据库初始化 Promise,供其他模块等待
if (!uni.$dbReady) {
uni.$dbReady = (async _ => {
try {
await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃
uni.$logger.local.info('数据库初始化完成')
return true
} catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message)
return false
}
})()
}
import TaskQueue from '../utils/TaskQueue'
import { PathUtils } from '../utils/recordManager/index'
class SQLite { class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size) { constructor(name, version, description, size) {
this.name = name this.name = name
this.version = version || '1.0' this.version = version || '1.0'
this.description = description || 'SQLite DB' this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null this.db = null
//注意:
this.dbPath = null // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
}
}
_enqueue(task) {
// 使用共享的队列实例
const queueInstance = SQLite._queues[this.name]
return queueInstance.enqueue(task)
} }
init() { async init() {
// 如果已经有路径,直接使用
if (this.dbPath) {
uni.$logger?.local?.info(`[SQLite] 使用已有路径: ${this.dbPath}`)
return this.openDatabase()
}
// 获取当前文档目录路径
const rootPath = await PathUtils.getFilePath()
this.dbPath = `${rootPath}${this.name}.db`
uni.$logger?.local?.info(`[SQLite] 数据库路径已确定: ${this.dbPath}`)
return this.openDatabase()
}
/**
* 打开数据库
*/
openDatabase() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.$logger?.local?.info(`[SQLite] 尝试打开数据库: path=${this.dbPath}`)
const isOpen = this.isOpen()
if (isOpen) {
uni.$logger?.local?.info(`[SQLite] 数据库已打开,跳过重复打开`)
resolve(true)
return
}
plus.sqlite.openDatabase({ plus.sqlite.openDatabase({
name: this.name, // 数据库名称 name: this.name,
path: `_doc/${this.name}.db`, // 数据库地址 path: this.dbPath,
success: resolve, // 直接使用 resolve success: e => {
fail: reject // 直接使用 reject uni.$logger?.local?.info(`[SQLite] ✅ 数据库打开成功`)
resolve(e)
},
fail: e => {
// 处理 -1402 错误 (Same Name Already Open),视为成功
if (e.code === -1402) {
uni.$logger?.local?.warn(`[SQLite] ⚠️ 数据库已打开 (Code -1402), 视为成功: ${this.name}`)
resolve(e)
return
}
uni.$logger?.local?.error(`[SQLite] ❌ 数据库打开失败: ${JSON.stringify(e)}`)
reject(e)
}
}) })
}) })
} }
selectSql(sql) { selectSql(sql) {
return new Promise((resolve, reject) => { return this._enqueue(
uni.$logger.local.info(`执行SQL语句: ${sql}`) () =>
new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({ plus.sqlite.selectSql({
name: this.name, name: this.name,
sql, sql,
...@@ -29,13 +82,16 @@ class SQLite { ...@@ -29,13 +82,16 @@ class SQLite {
const processedRows = result.map(row => const processedRows = result.map(row =>
Object.fromEntries( Object.fromEntries(
Object.entries(row).map(([key, value]) => { Object.entries(row).map(([key, value]) => {
// 优化:仅当 value 是字符串且以 { 或 [ 开头时才尝试解析
// 避免将普通数字字符串(如 "123")误解析为 Number 导致精度丢失
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try { try {
// 尝试将字符串解析为对象或数组
return [key, JSON.parse(value)] return [key, JSON.parse(value)]
} catch { } catch {
// 如果解析失败,保留原始值
return [key, value] return [key, value]
} }
}
return [key, value]
}) })
) )
) )
...@@ -44,11 +100,14 @@ class SQLite { ...@@ -44,11 +100,14 @@ class SQLite {
fail: reject fail: reject
}) })
}) })
)
} }
executeSql(sql) { executeSql(sql) {
return new Promise((resolve, reject) => { return this._enqueue(
uni.$logger.local.info(`执行SQL语句: ${sql}`) () =>
new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({ plus.sqlite.executeSql({
name: this.name, name: this.name,
sql, sql,
...@@ -56,6 +115,7 @@ class SQLite { ...@@ -56,6 +115,7 @@ class SQLite {
fail: reject fail: reject
}) })
}) })
)
} }
async isTableExists(tableName) { async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'` const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
...@@ -141,7 +201,7 @@ class SQLite { ...@@ -141,7 +201,7 @@ class SQLite {
isOpen() { isOpen() {
let isopen = plus.sqlite.isOpenDatabase({ let isopen = plus.sqlite.isOpenDatabase({
name: this.name, name: this.name,
path: `_doc/${this.name}.db` path: this.dbPath
}) })
return isopen return isopen
} }
...@@ -153,11 +213,18 @@ class SQLite { ...@@ -153,11 +213,18 @@ class SQLite {
} }
} }
drop(tabName) { drop(tabName) {
const sql = `DROP TABLE ${tabName}` const sql = `DROP TABLE IF EXISTS ${tabName}`
return this.executeSql(sql) return this.executeSql(sql)
} }
formatValue(value) { formatValue(value) {
return typeof value === 'object' && value !== null ? `'${JSON.stringify(value)}'` : `'${value}'` let strVal = ''
if (typeof value === 'object' && value !== null) {
strVal = JSON.stringify(value)
} else {
strVal = String(value)
}
// SQL 中转义单引号的方法是将 ' 替换为 ''
return `'${strVal.replace(/'/g, "''")}'`
} }
/** /**
......
...@@ -51,10 +51,10 @@ export default { ...@@ -51,10 +51,10 @@ export default {
cancelColor: '#292D33', cancelColor: '#292D33',
confirmText: modalInfo.confirmText, confirmText: modalInfo.confirmText,
confirmColor: '#347BFF', confirmColor: '#347BFF',
success: function (res) { success: (res) => {
// wx.__HAS_SHOW_MODAL = false; // wx.__HAS_SHOW_MODAL = false;
// if (res.cancel) _this.showNextModal(); // if (res.cancel) _this.showNextModal();
if (res.cancel) showNextModal() if (res.cancel) this.showNextModal()
modalInfo.eventCallback(res) modalInfo.eventCallback(res)
} }
}) })
......
...@@ -8,7 +8,8 @@ export default { ...@@ -8,7 +8,8 @@ export default {
let { useCarConfig, moduleList, media } = this, let { useCarConfig, moduleList, media } = this,
array = useCarConfig ? moduleList : media array = useCarConfig ? moduleList : media
let item = array.find(e => e.id == key), let item = array.find(e => e.id == key),
value = this.receptionTrack[key] // value = this.receptionTrack[key]
value = this.receptionTrack[key] ? { ...this.receptionTrack[key] } : null
if (value) { if (value) {
value.openCount += 1 value.openCount += 1
value.entryTime = Date.now() value.entryTime = Date.now()
...@@ -37,9 +38,14 @@ export default { ...@@ -37,9 +38,14 @@ export default {
receptionTrackLeave (keyName = 'id') { receptionTrackLeave (keyName = 'id') {
if (this.type == 'preview') return if (this.type == 'preview') return
let key = this[keyName], let key = this[keyName],
value = this.receptionTrack[key] // value = this.receptionTrack[key]
// value.stayDuration += Number(Date.now() - value.entryTime)
// this.$store.dispatch("setReceptionTrack", { key, value })
value = this.receptionTrack[key] ? { ...this.receptionTrack[key] } : null
if (value) {
value.stayDuration += Number(Date.now() - value.entryTime) value.stayDuration += Number(Date.now() - value.entryTime)
this.$store.dispatch("setReceptionTrack", { key, value }) this.$store.dispatch("setReceptionTrack", { key, value })
}
if (keyName == 'id' && key == 1) { //轻改才会触发 if (keyName == 'id' && key == 1) { //轻改才会触发
let [receptionRef] = this.$refs.media1 let [receptionRef] = this.$refs.media1
receptionRef.previewLeave && receptionRef.previewLeave(receptionRef.currentItem) receptionRef.previewLeave && receptionRef.previewLeave(receptionRef.currentItem)
......
/*
* @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
* @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 {
provide() {
return {
getRecorder: () => this.record
}
},
async mounted() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onError)
this.initDto()
this.record = new TempRecord(this.tempRecord, this.triggleTempNumber)
this.triggleTempNumber()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
// customerInfo: {
// handler(val) {
// this.handler(val, this.updateCustomerInfo)
// },
// deep: true
// },
customerKey: {
handler() {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
deep: true
},
booksList: {
handler(val) {
this.handler(val, this.updateBookList)
}
},
receptionStatus: {
handler(val) {
this.handler(val, this.updateReceptionStatus)
}
},
receptionKey: {
handler(val) {
this.handler(this.receptionTrack, this.updateMaterialPointList)
}
}
},
computed: {
...mapState(['user.customerInfo']),
...mapGetters(['customerInfo', 'receptionStatus', 'booksList', 'receptionTrack', 'receptionKey', 'customerKey'])
},
methods: {
...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),
initReception() {
this.setBooks([])
this.clearCustomerInfo()
this.setReceptionStatus('')
},
async onAudioStart() {
if (this.audioManager.counter === 0) {
await this.record.add()
} else {
this.record.addAudio()
}
},
async onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.info('〖接待管理Recorder〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.info('〖接待管理Recorder〗 == 断开录音! ')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
async stopAudio(isNotSave = false) {
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ')
this.stop()
await this.saveAndClearRecord(isNotSave)
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
uni.$logger.local.info('〖接待管理Recorder〗 == 不保存记录! ')
this.record.clearSavedFiles()
this.record.clearLocalRecord()
return
}
this.record.setReceptionEndTime() //设置接待结束时间
//如果不需要保存记录
await this.record.save()
},
stop() {
this.endWatchClick()
this.record.clearLoopTimer()
if (this.audioManager.isRecording) {
this.audioManager.stop()
}
},
handler(params, fn) {
if (this.audioManager.isRecording || this.record?.currentRecord?.endReasonType == 1) {
fn.call(this, params)
}
},
reset() {
this.audioManager = null
this.record = null
this.tempRecord = null
},
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo()
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType: channelType || 1 //1问界 2 比亚迪 3 其他
})
this.sceneType = sceneType
this.tempRecord = dto
},
updateCustomerInfo(customerInfo = {}) {
const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo
this.record.updatePreRecords({
customerName,
phoneNumber,
carModel,
salesUuid,
salesName,
carBrand,
carBrandId,
oneCarBrand,
oneCarBrandId
})
},
updateBookList(booksList) {
const receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
}
})
this.record.updatePreRecords({ receptionCustomerPaySourceList })
},
updateMaterialPointList(receptionTrack) {
const { merchantId, staffUuid, staffName } = this.tempRecord
let receptionCustomerMaterialPointList = []
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId,
staffUuid,
staffName,
businessScene: this.sceneType
})
})
this.record.updatePreRecords({ receptionCustomerMaterialPointList })
},
updateReceptionStatus(status) {
this.record.updatePreRecords({ receptionStatus: status })
},
getRecorder() {
return this.record
},
async triggleTempNumber() {
const _records = await this.record.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() {
this.stop()
this.reset()
}
}
...@@ -2,224 +2,44 @@ ...@@ -2,224 +2,44 @@
* @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: 2025-08-12 10:32:25 * @LastEditTime: 2026-01-21 19:07:13
* @FilePath: \gl_tape\mixin\record\recorder.js * @FilePath: \gl_tape\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'
import { mapMutations, mapState, mapGetters } from 'vuex' 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 { export default {
provide() { provide() {
return { return {
getRecorder: () => this.record getRecorder: () => this.recordService?.getRecorder()
} }
}, },
async mounted() { data() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onError) return {
this.initDto() recordService: null
this.record = new TempRecord(this.tempRecord, this.triggleTempNumber)
this.triggleTempNumber()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
// customerInfo: {
// handler(val) {
// this.handler(val, this.updateCustomerInfo)
// },
// deep: true
// },
customerKey: {
handler() {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
deep: true
},
booksList: {
handler(val) {
this.handler(val, this.updateBookList)
}
},
receptionStatus: {
handler(val) {
this.handler(val, this.updateReceptionStatus)
}
},
receptionKey: {
handler(val) {
this.handler(this.receptionTrack, this.updateMaterialPointList)
}
} }
}, },
computed: { async mounted() {
...mapState(['user.customerInfo']), // 获取 RecordService 单例 (已在构造函数中自动初始化)
...mapGetters(['customerInfo', 'receptionStatus', 'booksList', 'receptionTrack', 'receptionKey', 'customerKey']) this.recordService = RecordService.getInstance()
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setPerRecordNumber']), ...mapMutations('audio', ['setReceptionStatus', 'setBooks']),
...mapMutations(['clearCustomerInfo']),
//开始录音 //开始录音
startAudio: utils.throttle(async function (isInitData = true) { async startAudio(isInitData = true) {
const isPermission = await this.checkBeforeStart() return this.recordService.startAudio(isInitData)
if (!isPermission) return
uni.$logger.local.info('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime()
this.audioManager.start()
}, 300),
initReception() {
this.setBooks([])
this.clearCustomerInfo()
this.setReceptionStatus('')
},
async onAudioStart() {
if (this.audioManager.counter === 0) {
await this.record.add()
} else {
this.record.addAudio()
}
}, },
async onAudioStop() {
if (this.audioManager.isRecording) { //结束接待
uni.$logger.local.info('〖接待管理Recorder〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.info('〖接待管理Recorder〗 == 断开录音! ')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
async stopAudio(isNotSave = false) { async stopAudio(isNotSave = false) {
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ') return this.recordService.stopAudio(isNotSave)
this.stop()
await this.saveAndClearRecord(isNotSave)
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
uni.$logger.local.info('〖接待管理Recorder〗 == 不保存记录! ')
this.record.clearSavedFiles()
this.record.clearLocalRecord()
return
}
this.record.setReceptionEndTime() //设置接待结束时间
//如果不需要保存记录
await this.record.save()
}, },
stop() { stop() {
this.endWatchClick() this.recordService.stop()
this.record.clearLoopTimer()
if (this.audioManager.isRecording) {
this.audioManager.stop()
}
},
handler(params, fn) {
if (this.audioManager.isRecording || this.record?.currentRecord?.endReasonType == 1) {
fn.call(this, params)
}
},
reset() {
this.audioManager = null
this.record = null
this.tempRecord = null
},
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo()
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType: channelType || 1 //1问界 2 比亚迪 3 其他
})
this.sceneType = sceneType
this.tempRecord = dto
}, },
updateCustomerInfo(customerInfo = {}) { // 代理权限检查
const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo async isPermission(hintText) {
this.record.updatePreRecords({ return await this.recordService.isPermission(hintText)
customerName,
phoneNumber,
carModel,
salesUuid,
salesName,
carBrand,
carBrandId,
oneCarBrand,
oneCarBrandId
})
},
updateBookList(booksList) {
const receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
} }
})
this.record.updatePreRecords({ receptionCustomerPaySourceList })
},
updateMaterialPointList(receptionTrack) {
const { merchantId, staffUuid, staffName } = this.tempRecord
let receptionCustomerMaterialPointList = []
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId,
staffUuid,
staffName,
businessScene: this.sceneType
})
})
this.record.updatePreRecords({ receptionCustomerMaterialPointList })
},
updateReceptionStatus(status) {
this.record.updatePreRecords({ receptionStatus: status })
},
getRecorder() {
return this.record
},
async triggleTempNumber() {
const _records = await this.record.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() {
this.stop()
this.reset()
} }
} }
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js'
import OperationQueue from '@/utils/OperationQueue.js'
import { Command } from '../../ws/constants'
import { isInteger, deepClone } from '@/utils/utils.js'
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 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() {
try {
// 初始化 WebView
this.wv = await this.initWebview()
this.interval = UPLOAD_INTERVAL
// 初始化操作队列
this.operationQueue = new OperationQueue()
this.timeoutManager = new TimeoutManager()
// 开始轮询
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)
}
},
/**
* 订阅事件
* 这个函数用于订阅事件
* @returns {void} - 没有返回值
*/
on() {
// 订阅停止轮询事件
uni.$on(Command.StopPolling, this.stopPolling)
// 订阅开始轮询事件
uni.$on(Command.StartPolling, this.startPolling)
// 订阅设置轮询间隔事件
uni.$on(Command.SetPollingInterval, this.setInterval)
},
/**
* webview文件上传完成后执行的函数
* @param {*} data
*/
handlerMessage(data) {
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()
}
},
/**
* 保存文件信息并更新记录
* 这个函数用于保存文件信息并更新记录
* @param {Object} data - 包含文件信息的对象
* @returns {Promise<void>} - 一个 Promise,当文件信息保存并记录更新完成时解析,没有返回值
* @throws {Error} 如果在保存或更新过程中出现错误,将抛出错误
*/
async save(data) {
try {
const fileInfo = this.parseFileInfo(data)
uni.$logger.local.info(`【上传管理Uploader】 == 解析结果 -> ${JSON.stringify(fileInfo)}`)
if (!fileInfo || !fileInfo.recordId) {
uni.$logger.local.error(`【上传管理Uploader】 == 上传文件信息解析异常`)
return
}
const record = await uni.$dbManager.getRecordById(fileInfo.recordId)
const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord)
} 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()
}
},
/**
* 解析文件信息
* 这个函数用于解析文件信息
* @param {Object} data - 包含文件信息的对象
* @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)
return null
}
// 返回成功上传的文件信息
return { recordId, fileName, clientPath: filePath + fileName, serverPath: fileData.oss.res.requestUrls[0].split('?')[0], status: FileStatus.Uploaded }
},
/**
* 将文件路径更改为服务器路径
* 这个函数用于将接待记录中的文件路径更新为服务器路径
* @param {Object} record - 接待记录对象
* @param {Object} fileInfo - 文件信息对象
* @returns {Object} - 更新后的接待记录对象
*/
_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)}`)
// 如果是无文件状态,直接返回基础信息
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)}`)
return _record
}
// console.log(_record)
// 正常文件上传和文件丢失的记录执行此逻辑
_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)
})
if (item) {
let info2Update = {
status: fileInfo.status
}
if (info2Update.status === FileStatus.Uploaded) {
// 正常文件上传的数据才更新服务器文件和本地文件路径 后面删除本地文件的时候 现过滤出正常上传的文件然后再获取到对应的文件删除
Object.assign(info2Update, {
file: fileInfo.serverPath,
filePathOnClient: fileInfo.clientPath
})
}
Object.assign(item, info2Update)
uni.$logger.local.info(`【上传管理Uploader】 == 修改文件路径完成!!`)
} else {
uni.$logger.local.info(`【上传管理Uploader】 == 未找到记录 == fileInfo -> ${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}`)
throw new Error('【上传管理Uploader】 == 修改文件路径失败!!')
}
},
/**
* 报告错误
* 这个函数用于报告上传文件失败的错误
* @param {string} recordId - 记录ID
* @param {string} filePath - 文件路径
* @param {Object} res - 响应对象
* @param {string} message - 错误消息
* @returns {void} - 没有返回值
*/
async reportError(message, res, recordId, filePath) {
try {
const record = recordId ? await uni.$dbManager.getRecordById(recordId) : {}
const userInfo = this.userInfo //uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = record || {}
const { name } = userInfo || {}
const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
uni.$logger.error({
msg: `${now}-${message},员工: ${name}, 客户: ${customerName}`,
extra: {
'手机号: ': phoneNumber,
'员工: ': name,
'姓名: ': customerName,
'销售: ': salesName,
'车型: ': carModel,
'原因: ': serializeIfObject(res),
'文件路径: ': filePath
}
})
} catch (error) {
uni.$logger.error(`【上传管理Uploader】 == 报告错误时发生异常: ${error.message}`)
}
},
/**
* 初始化 WebView 的异步函数
* 这个函数返回一个 Promise,当初始化 WebView 完成时,它将解析为 WebView 对象。
* 在页面初始化调用时,这个函数会延迟 1 秒,以确保 WebView 对象已经创建。
*
* @async
* @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))
}
throw new Error('WebView initialization timeout')
} 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'
})
}
})
},
/**
* 入列操作
* 这个函数异步执行,目的是获取记录的快照并将其扁平化,以形成一个队列
* 通过调用 getRecordsSnapshotFlatten 获取快照数据
* 当所有数据准备好后,创建一个新的 Queue 实例,并将扁平化后的数据作为参数传入
* 这样,队列就被创建并且最初是满的,其中包含了已经获取到的记录快照
*
* @async
* @returns {Promise<void>} 一个 Promise,当初始化队列完成时解析,没有返回值
* @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误
*/
async enQueue() {
try {
const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot)
uni.$logger.local.info('【上传管理Uploader】 == 创建快照成功! 文件个数:' + this.snapshot.size)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 获取快照失败 error:${error.message}`, error.message)
}
},
/**
* 获取记录快照并展平数据
* 此函数异步获取记录快照,然后使用flattenData函数将这些记录转换为一个文件对象列表
* 每个文件对象都包含一个额外的recordId属性,用于指示它所属的记录
*
* @async
* @returns {Promise<Array>} 一个Promise,当获取并处理完记录时,返回一个文件对象列表
* @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
*/
async getRecordsSnapshotFlatten() {
const _records = await uni.$dbManager.getRecords()
const _snapshot = await this.flattenData(_records || [])
return _snapshot
},
/**
* 上传记录
* 这个函数用于上传文件
* @param {Object} record - 要上传的文件记录
* @returns {Promise<void>} - 一个 Promise,当文件上传完成时解析,没有返回值
* @throws {Error} 如果文件上传失败,将抛出错误
*/
async uploadRecord(record) {
// 如果文件状态是没有文件或者不存在,则直接保存记录
uni.$logger.local.info(`【上传管理Uploader】 == 开始上传文件!! record: ${JSON.stringify(record)}`)
if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) {
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,或文件不存在, 直接保存记录!!`)
this.save(record)
} 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}')`)
} catch (error) {
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
throw error
}
}
},
/**
* 从客户端删除文件
* 这个函数用于从客户端的本地存储中删除指定的文件
* @param {string} filePathOnClient - 要删除的文件在客户端的路径
* @returns {Promise<boolean>} - 一个 Promise,当文件删除成功时解析为 true,否则抛出错误
*/
_removeFileOnClient(filePathOnClient) {
uni.$logger.local.info(`【上传管理Uploader】 == 开始删除客户端的文件!! 路径-> ${filePathOnClient}`)
return new Promise((resolve, reject) => {
if (!filePathOnClient) {
uni.$logger.local.info(`【上传管理Uploader】 == 要删除的文件为空`)
resolve(true)
return
}
uni.removeSavedFile({
filePath: filePathOnClient,
complete: function (res) {
uni.$logger.local.info(`${filePathOnClient}->code:${res.code} msg:${res.errMsg}`)
resolve(res)
}
})
})
},
/**
* 异步保存或更新接待记录
* 这个函数用于保存或更新接待记录
* @param {Object} data - 要保存或更新的接待记录数据
* @throws {Error} 如果保存或更新接待记录失败,将抛出错误
*/
async _saveOrUpdate(data) {
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)
}
} else {
// 如果记录中还有未处理文件,记录日志并更新记录
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`)
// 更新接待记录
await uni.$dbManager.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
}
} catch (error) {
// 如果保存或更新接待记录失败,记录错误信息并抛出错误
this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data.id, data.filePath + data.fileName)
}
},
/**
* 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间
* @param {Array} recordUrlList - 包含文件URL的数组
* @param {string} receptionStartTime - 接待开始时间
* @returns {Promise<string>} - 一个 Promise,成功时解析为接待结束时间
*/
async _requestReceptionEndTime(recordUrlList, receptionStartTime) {
if (!recordUrlList || recordUrlList.length === 0) return receptionStartTime
try {
// 记录日志,显示正在向服务器请求结束接待时间,包括文件URL列表和接待开始时间
uni.$logger.local.info(`【上传管理Uploader】 == 向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`)
// 调用 uni.$api.commonApi.searchRecordingEndTime 方法,向服务器发送请求,获取接待结束时间
const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') })
// 记录日志,显示服务器返回的接待结束时间
uni.$logger.local.info(`【上传管理Uploader】 == 服务器返回结束接待时间: endTime ->${endTime}`)
// 返回接待结束时间,将日期格式中的连字符替换为斜杠,以保持一致性
return endTime.replace(/\-/g, '/')
} catch (error) {
// 如果请求失败,记录错误信息并抛出错误
this.reportError(`【上传管理Uploader】 == 向服务器获取结束接待时间异常: error ->${error.message}`, error.message)
}
},
/**
* 删除指定id的接待记录
* @param {string} recordId - 要删除的接待记录的id
* @throws {Error} 如果删除接待记录失败,将抛出错误
*/
async _removeRecordById(recordId) {
try {
await uni.$dbManager.removeRecord(recordId)
uni.$logger.local.info(`【上传管理Uploader】 == 删除接待记录成功: recordId ->${recordId}`)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
}
},
/**
* 异步删除接待记录中的文件
* @param {Array} fileArr - 要删除的文件数组
* @throws {Error} 如果删除文件失败,将抛出错误
*/
async _removeRecordFiles(fileArr) {
try {
while (fileArr.length > 0) {
const file = fileArr.shift()
await this._removeFileOnClient(file)
}
uni.$logger.local.info(`【上传管理Uploader】 == 删除接待文件完成!`)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr })
}
},
/**
* 扁平化数据
* 这个函数用于处理一个记录数组,检查每个记录的文件列表,并将文件信息扁平化
* 如果文件不存在或状态为已上传或已完成,则跳过该文件
* 如果文件存在,则将其状态设置为待上传,并将其添加到结果数组中
* 如果在处理文件过程中发生错误,则记录错误信息并继续处理下一个文件
*
* @param {Array} records - 要处理的记录数组
* @returns {Promise<Array>} - 返回一个 Promise,当所有记录处理完成时解析为包含所有处理后记录的数组
*/
async flattenData(records) {
const result = []
try {
for (const cur of records) {
const recordUrlList = this.urlListFilter(cur.recordUrlList)
if (recordUrlList.length == 0) {
// 如果记录中没有文件,则将其状态设置为 NoFile,并添加到结果数组中
result.push({ status: FileStatus.NoFile, recordId: cur.id })
this.reportError('【上传管理Uploader】 == 记录中不存在接待语音文件', { record: cur }, cur.id) //记录中不存在接待语音文件
continue
}
// 处理每个记录的文件列表
for (const file of recordUrlList) {
try {
// 如果文件状态为已上传或已完成,则跳过该文件
if (!file.status || file.status == FileStatus.Uploaded || file.status == FileStatus.Completed) continue
const aFullPath = file.file.split('/')
const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/'
const file2Up = { ...file, recordId: cur.id, fileName, filePath }
// 检查文件是否存在
const fileExists = await this.checkFileExists(file.file)
if (!fileExists) {
// 如果文件不存在,则将其状态设置为 NotExist,并记录错误信息
this.reportError('【上传管理Uploader】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file) //记录中语音文件不存在
file2Up.status = FileStatus.NotExist
}
result.push(file2Up)
} catch (error) {
// 如果在处理文件过程中发生错误,则记录错误信息并继续处理下一个文件
this.reportError(`【上传管理Uploader】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file })
continue
}
}
}
return result
} catch (error) {
throw new Error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
}
},
urlListFilter(urlList) {
if (!Array.isArray(urlList)) {
urlList = []
}
const __list = urlList.filter(item => item?.file)
return __list
},
/**
* 检查文件是否存在
* 这个函数用于检查指定文件路径是否存在
* 如果文件路径为空,则返回 false
* 如果文件路径不为空,则使用 uni.getFileInfo 方法获取文件信息
* 如果获取成功,则返回 true
* 如果获取失败,则返回 false
*/
async checkFileExists(filePath) {
return new Promise(resolve => {
if (!filePath || !this.isLegalFile(filePath)) {
resolve(false)
return
}
uni.getFileInfo({
filePath: filePath,
success: function (info) {
resolve(true)
},
fail: function (error) {
resolve(false)
}
})
})
},
isLegalFile(file) {
return file && file.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()
},
async wait(time = TIME_OUT_TIME) {
const msg = await this.timeoutManager.addTimeout(this.interval, time)
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 - 要处理的记录对象
* @returns {void} - 此函数不返回任何值
*/
async beginTask(record) {
// 将任务函数加入到操作队列中,并在任务完成后调用 polling 函数进行下一轮轮询
this.operationQueue.enqueue(() => this.task(record), `文件ID: ${record.recordId}@${record.fileName}`).finally(this.polling)
},
/**
* 处理单个记录的任务
* 这个函数用于处理单个记录的上传任务
* @param {Object} record - 要处理的记录对象
* @returns {Promise} - 当任务完成时解析的 Promise
*/
task(record) {
return new Promise(resolve => {
this.updateResolve = resolve
this.uploadRecord(record)
})
},
/**
* 结束任务
* 这个函数用于结束当前的任务
* 调用 resolve 方法来解决 Promise,标记任务完成
* @returns {void} - 此函数不返回任何值
*/
endTask() {
this.updateResolve && this.updateResolve(), (this.updateResolve = null)
},
/**
* 停止文件上传轮询并清除队列
* 这个方法会停止正在进行的轮询,并清除所有待处理的操作和快照数据
* 释放所有资源,确保没有任何后台任务在运行
*/
stopPolling() {
if (this.snapshot) {
this.snapshot.clear()
this.snapshot = null
}
if (this.operationQueue) {
this.operationQueue.clear() // 取消所有待处理的操作
}
this.canclePromises()
uni.$logger.local.info(`【上传管理Uploader】 == 停止文件上传轮询并清除队列`)
},
/**
* 设置轮询的时间间隔
* 这个方法用于设置文件上传轮询的时间间隔
* 如果 interval 不是整数,则会记录错误信息并返回
* 如果 isForce 为 true,则会强制重启轮询
* @param {number} interval - 轮询的时间间隔(秒)
* @param {boolean} [isForce=false] - 是否强制重启轮询
*/
setInterval(interval, isForce = false) {
if (!isInteger(interval)) {
const error = `【上传管理Uploader】 == 参数错误!interval 必需为数字! interval -> ${interval} `
uni.$logger.local.error(error)
return
}
this.interval = interval
if (isForce) {
this.startPolling(isForce)
}
uni.$logger.local.info(`【上传管理Uploader】 == 轮询间隔已设置为 ${interval} 秒`)
},
/**
* 启动文件上传轮询
* 这个方法用于启动文件上传轮询
* 如果 timer 已经存在且 isForce 为 false,则不会强制重启轮询
* 如果 isForce 为 true,则会强制重启轮询
* @param {boolean} [isForce=false] - 是否强制重启轮询
*/
async startPolling(isForce = false) {
if (this.timeoutManager.isProcessing || this.updateResolve) {
if (!isForce) {
uni.$logger.local.info(`【上传管理Uploader】 == 非强制模式下,不强制重启轮询`)
return
} else {
uni.$logger.local.info(`【上传管理Uploader】 == 强制模式下,立即完成promise,强制重启轮询`)
this.canclePromises()
}
}
setTimeout(async () => {
await this.enQueue()
this.polling()
}, 0)
// setTimeout(() => {
// this.startPolling(true)
// }, 1000)
uni.$logger.local.info(`【上传管理Uploader】 =========开始轮询========`)
},
/**
* 清除 timer
*/
canclePromises() {
this.timeoutManager?.cancelAllTasks()
this.endTask()
},
off() {
// 取消监听停止轮询事件
uni.$off(Command.StopPolling, this.stopPolling)
// 取消监听开始轮询事件
uni.$off(Command.StartPolling, this.startPolling)
// 取消监听设置轮询间隔事件
uni.$off(Command.SetPollingInterval, this.setInterval)
}
},
/**
* 组件销毁前执行的生命周期函数
* 这个函数会在组件销毁前被调用,用于执行一些清理工作
* 包括停止文件上传轮询、清除 WebView 组件、取消事件监听以及记录日志
*/
beforeDestroy() {
// 停止文件上传轮询并清除队列
this.stopPolling()
this.wv = null
this.off()
// 记录组件销毁前的日志信息
uni.$logger.local.info(`【上传管理Uploader】 == 组件销毁前执行的生命周期函数`)
}
}
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js' import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js' import Queue from '@/utils/Queue.js'
import OperationQueue from '@/utils/OperationQueue.js'
import { Command } from '../../ws/constants' import { Command } from '../../ws/constants'
import { isInteger, deepClone } from '@/utils/utils.js' import { isInteger, deepClone } from '@/utils/utils.js'
import { FileStatus } from '../../utils/common' import { FileStatus } from '../../utils/common'
import { serializeIfObject } from '../../utils/utils' import { serializeIfObject } from '../../utils/utils'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import TimeoutManager from '@/utils/TimeoutManager.js' const UPLOAD_INTERVAL = 0.5 * 60 * 1000
const UPLOAD_INTERVAL = 5 * 60 * 1000
const TIME_OUT_TIME = 15 * 60 * 1000 const TIME_OUT_TIME = 15 * 60 * 1000
export default { export default {
mounted() { mounted() {
this.init() this.init()
this.on() 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: { methods: {
async init() { async init() {
...@@ -44,14 +18,10 @@ export default { ...@@ -44,14 +18,10 @@ export default {
// 初始化 WebView // 初始化 WebView
this.wv = await this.initWebview() this.wv = await this.initWebview()
this.interval = UPLOAD_INTERVAL this.interval = UPLOAD_INTERVAL
// 初始化操作队列 this._pumpTimer = null
this.operationQueue = new OperationQueue() this._pumpRunning = false
this.timeoutManager = new TimeoutManager()
// 开始轮询 // 开始轮询
this.startPolling() 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) { } catch (error) {
this.reportError(`【上传管理Uploader】初始化失败 error:${error.message}`, error.message) this.reportError(`【上传管理Uploader】初始化失败 error:${error.message}`, error.message)
} }
...@@ -68,8 +38,15 @@ export default { ...@@ -68,8 +38,15 @@ export default {
uni.$on(Command.StartPolling, this.startPolling) uni.$on(Command.StartPolling, this.startPolling)
// 订阅设置轮询间隔事件 // 订阅设置轮询间隔事件
uni.$on(Command.SetPollingInterval, this.setInterval) uni.$on(Command.SetPollingInterval, this.setInterval)
// 监听网络状态变化
this._networkHandler = (res) => {
if (res.isConnected) {
uni.$logger.local.info(`【上传管理Uploader】 == 网络已恢复,唤醒上传任务`)
this.startPolling()
}
}
uni.onNetworkStatusChange(this._networkHandler)
}, },
/** /**
* webview文件上传完成后执行的函数 * webview文件上传完成后执行的函数
* @param {*} data * @param {*} data
...@@ -78,18 +55,11 @@ export default { ...@@ -78,18 +55,11 @@ export default {
uni.$logger.local.info(`【上传管理Uploader】 == 文件上传回调!`) uni.$logger.local.info(`【上传管理Uploader】 == 文件上传回调!`)
this.save(data) this.save(data)
}, },
/**
async checkDB() { * 生成任务唯一标识 Key
try { */
const isSuccess = uni.$dbManager.init() _getTaskKey(recordId, fileName) {
if (!isSuccess) { return `${recordId || ''}_${fileName || ''}`
this.toLogin()
return
}
} catch (error) {
uni.$logger.error(`【上传管理Uploader】 == 初始化数据库失败:${error.message}`)
this.toLogin()
}
}, },
/** /**
* 保存文件信息并更新记录 * 保存文件信息并更新记录
...@@ -101,20 +71,42 @@ export default { ...@@ -101,20 +71,42 @@ export default {
async save(data) { async save(data) {
try { try {
const fileInfo = this.parseFileInfo(data) const fileInfo = this.parseFileInfo(data)
uni.$logger.local.info(`【上传管理Uploader】 == 解析结果 -> ${JSON.stringify(fileInfo)}`) if (!fileInfo?.recordId) {
if (!fileInfo || !fileInfo.recordId) { // 仅记录警告,不抛出异常中断流程,由后续逻辑处理或忽略
uni.$logger.local.error(`【上传管理Uploader】 == 上传文件信息解析异常`) uni.$logger.local.warn(`【上传管理Uploader】 == 上传文件信息解析异常: recordId缺失, 本次任务结束`)
// 结束当前任务,让流程继续
this.endTask()
return return
} }
// 优化日志
uni.$logger.local.info(`【上传管理Uploader】 == 解析结果: recordId=${fileInfo.recordId}, status=${fileInfo.status}`)
// 竞态保护:判断回调是否属于当前任务
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 record = await uni.$dbManager.getRecordById(fileInfo.recordId)
if (!record) {
throw new Error(`未找到记录: ${fileInfo.recordId}`)
}
const modifiedRecord = this._changeFilePathToServer(record, fileInfo) const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord) await this._saveOrUpdate(modifiedRecord)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName) // 只有当前任务匹配时,才触发任务结束逻辑
} finally { if (isCurrentTask) {
uni.$logger.local.info('【上传管理Uploader】 == 本次任务完成,开启下一次上传任务!') uni.$logger.local.info('【上传管理Uploader】 == 本次任务完成,开启下一次上传任务!')
this.endTask() this.endTask()
} }
} catch (error) {
this.reportError(`【上传管理Uploader】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask() // 发生异常时也尝试结束任务,防止阻塞
}
}, },
/** /**
* 解析文件信息 * 解析文件信息
...@@ -123,25 +115,71 @@ export default { ...@@ -123,25 +115,71 @@ export default {
* @returns {Object} - 解析后的文件信息对象 * @returns {Object} - 解析后的文件信息对象
*/ */
parseFileInfo(data) { parseFileInfo(data) {
uni.$logger.local.info(`【上传管理Uploader】 == 开始文件信息解析-> ${JSON.stringify(data)}`) try {
// 如果是无文件状态,直接返回基础信息 const input = serializeIfObject(data)
if ([FileStatus.NoFile, FileStatus.NotExist].includes(data.status)) { uni.$logger.local.info(`【上传管理Uploader】 == 开始文件信息解析-> ${input}`)
let { recordId, filePath, fileName, status } = data if (!data) return null
status = status == FileStatus.NotExist ? FileStatus.Completed : FileStatus.NoFile //Completed NoFile 状态用于区分 正常上传的Uploaded状态.后续获取服务器文件路径过滤 const { status } = data
return { recordId, clientPath: filePath + fileName, serverPath: null, fileName, status } // 1. 处理无文件或文件不存在的特殊状态
} if ([FileStatus.NoFile, FileStatus.NotExist].includes(status)) {
// 获取上传结果,如果失败直接返回 null return this._parseNoFileStatus(data)
const { recordId, fileName, filePath, code, data: fileData, message } = data.detail.data[0] }
if (code !== 0) { // 2. 处理正常上传回调
const __message = `【上传管理Uploader】 == 文件上传回调,解析异常: code->${code} message->${message}` return this._parseUploadedFile(data)
uni.$logger.local.error(__message) } catch (error) {
this.reportError(__message, data, recordId, filePath + fileName) uni.$logger.local.error(`【上传管理Uploader】 == 解析文件信息异常: ${error.message}`)
return null return null
} }
// 返回成功上传的文件信息
return { recordId, fileName, clientPath: filePath + fileName, serverPath: fileData.oss.res.requestUrls[0].split('?')[0], status: FileStatus.Uploaded }
}, },
_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
}
// 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,49 +189,47 @@ export default { ...@@ -151,49 +189,47 @@ export default {
*/ */
_changeFilePathToServer(record, fileInfo) { _changeFilePathToServer(record, fileInfo) {
try { try {
// record = Array.isArray(record) ? record[0] : record // sqlite 返回数组
// 深度克隆记录对象,以避免修改原始数据
const _record = deepClone(record) const _record = deepClone(record)
uni.$logger.local.info(`【上传管理Uploader】 == 开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(_record.recordUrlList)}`) uni.$logger.local.info(`【上传管理Uploader】 == 开始更新文件路径, recordId: ${_record.id}`)
// 如果是无文件状态,直接返回基础信息
// 场景1: 无文件状态 (NoFile)
if (fileInfo.status === FileStatus.NoFile) { if (fileInfo.status === FileStatus.NoFile) {
_record.status = FileStatus.NoFile _record.status = FileStatus.NoFile
// 如果接待结束时间不存在,则设置为接待开始时间
_record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime _record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime
_record.recordUrlList = [] _record.recordUrlList = []
uni.$logger.local.info(`【上传管理Uploader】 == 当前记录没有接待语音文件,已将状态设置为无文件状态: ${JSON.stringify(_record)}`) uni.$logger.local.info(`【上传管理Uploader】 == 记录被标记为无文件状态`)
return _record return _record
} }
// console.log(_record)
// 正常文件上传和文件丢失的记录执行此逻辑 // 场景2: 正常更新文件状态
_record.recordUrlList = this.urlListFilter(_record.recordUrlList) _record.recordUrlList = this.urlListFilter(_record.recordUrlList)
const item = _record.recordUrlList.find(item => { const targetFile = _record.recordUrlList.find(item => this._isTargetFile(item, fileInfo))
const isLegal = this.isLegalFile(fileInfo.fileName)
return isLegal ? item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName) : !this.isLegalFile(item.file) if (targetFile) {
}) this._updateFileStatus(targetFile, fileInfo)
if (item) {
let info2Update = {
status: fileInfo.status
}
if (info2Update.status === FileStatus.Uploaded) {
// 正常文件上传的数据才更新服务器文件和本地文件路径 后面删除本地文件的时候 现过滤出正常上传的文件然后再获取到对应的文件删除
Object.assign(info2Update, {
file: fileInfo.serverPath,
filePathOnClient: fileInfo.clientPath
})
}
Object.assign(item, info2Update)
uni.$logger.local.info(`【上传管理Uploader】 == 修改文件路径完成!!`)
} else { } 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 return _record
} catch (error) { } catch (error) {
uni.$logger.error(`【上传管理Uploader】 == 修改文件路径失败!! error-> ${error.message}`) uni.$logger.error(`【上传管理Uploader】 == 修改文件路径失败: ${error.message}`)
throw new Error('【上传管理Uploader】 == 修改文件路径失败!!') throw new Error('【上传管理Uploader】 == 修改文件路径失败!!')
} }
}, },
_isTargetFile(item, fileInfo) {
// 匹配逻辑: 优先匹配绝对路径,其次匹配文件名后缀
if (!this.isLegalFile(fileInfo.fileName)) return !this.isLegalFile(item.file)
return item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName)
},
_updateFileStatus(targetFile, fileInfo) {
targetFile.status = fileInfo.status
// 仅当上传成功时,才回填服务器路径
if (fileInfo.status === FileStatus.Uploaded) {
targetFile.file = fileInfo.serverPath
targetFile.filePathOnClient = fileInfo.clientPath
}
uni.$logger.local.info(`【上传管理Uploader】 == 文件状态已更新: ${fileInfo.fileName} -> ${fileInfo.status}`)
},
/** /**
* 报告错误 * 报告错误
* 这个函数用于报告上传文件失败的错误 * 这个函数用于报告上传文件失败的错误
...@@ -235,37 +271,21 @@ export default { ...@@ -235,37 +271,21 @@ export default {
* @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。 * @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。
*/ */
async initWebview() { async initWebview() {
const MAX_RETRIES = 500 // 最多尝试500次,每次间隔100ms,总共50秒
const INTERVAL = 100
try { try {
const currentWebview = this.$parent.$scope.$getAppWebview() uni.$logger.local.warn('【上传管理Uploader】 == 初始化 WebView 开始...')
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) { const currentWebview = this.$parent?.$scope?.$getAppWebview()
const wv = currentWebview.children()[0] const wv = currentWebview?.children()?.[0]
if (wv) { if (wv) {
wv.setStyle({ top: '100%', height: 300 }) wv.setStyle({ top: '100%', height: 300 })
uni.$logger.local.warn('【上传管理Uploader】 == 初始化 WebView 成功!')
return wv return wv
} }
await new Promise(resolve => setTimeout(resolve, INTERVAL)) uni.$logger.local.warn('【上传管理Uploader】 == 初始化 WebView 失败!')
} return null
throw new Error('WebView initialization timeout')
} catch (error) { } catch (error) {
this.reportError(`初始化Webview失败 error:${error.message}`, error.message) this.reportError(`初始化Webview失败 error:${error.message}`, error.message)
// this.toLogin() return null
throw error
}
},
toLogin() {
uni.hideLoading()
uni.showModal({
title: '错误',
content: '初始化失败,请重新登录系统',
showCancel: false,
success(res) {
uni.reLaunch({
url: '/pages/common/login'
})
} }
})
}, },
/** /**
* 入列操作 * 入列操作
...@@ -282,9 +302,12 @@ export default { ...@@ -282,9 +302,12 @@ export default {
try { try {
const _snapshot = await this.getRecordsSnapshotFlatten() const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot) this.snapshot = new Queue(_snapshot)
uni.$logger.local.info('【上传管理Uploader】 == 创建快照成功! 文件个数:' + this.snapshot.size) uni.$logger.local.warn(`【上传管理Uploader】 == 创建快照成功! ${JSON.stringify(this.snapshot.items)} 快照数: ${this.snapshot.size} `)
} catch (error) { } catch (error) {
this.reportError(`【上传管理Uploader】 == 获取快照失败 error:${error.message}`, error.message) this.reportError(`【上传管理Uploader】 == 获取快照失败 error:${error.message}`, error.message)
if (!this.snapshot) {
this.snapshot = new Queue([])
}
} }
}, },
/** /**
...@@ -317,15 +340,22 @@ export default { ...@@ -317,15 +340,22 @@ export default {
} else { } else {
try { try {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken() const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
uni.$logger.local.info(`【上传管理Uploader】 == 获取Token成功!!', lsaccessKeySecret: ${lsaccessKeySecret}`) this._safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, record.fileName, record.filePath, record.recordId)
// 通过WebView的evalJS方法,将密钥和ID等信息传递给WebView中的JavaScript代码 执行文件上传
this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
} catch (error) { } catch (error) {
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message) this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
this.endTask()
throw error 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)
},
/** /**
* 从客户端删除文件 * 从客户端删除文件
* 这个函数用于从客户端的本地存储中删除指定的文件 * 这个函数用于从客户端的本地存储中删除指定的文件
...@@ -333,7 +363,6 @@ export default { ...@@ -333,7 +363,6 @@ export default {
* @returns {Promise<boolean>} - 一个 Promise,当文件删除成功时解析为 true,否则抛出错误 * @returns {Promise<boolean>} - 一个 Promise,当文件删除成功时解析为 true,否则抛出错误
*/ */
_removeFileOnClient(filePathOnClient) { _removeFileOnClient(filePathOnClient) {
uni.$logger.local.info(`【上传管理Uploader】 == 开始删除客户端的文件!! 路径-> ${filePathOnClient}`)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!filePathOnClient) { if (!filePathOnClient) {
uni.$logger.local.info(`【上传管理Uploader】 == 要删除的文件为空`) uni.$logger.local.info(`【上传管理Uploader】 == 要删除的文件为空`)
...@@ -343,13 +372,12 @@ export default { ...@@ -343,13 +372,12 @@ export default {
uni.removeSavedFile({ uni.removeSavedFile({
filePath: filePathOnClient, filePath: filePathOnClient,
complete: function (res) { complete: function (res) {
uni.$logger.local.info(`${filePathOnClient}->code:${res.code} msg:${res.errMsg}`) uni.$logger.local.info(`删除 ${filePathOnClient}-> ${res.errMsg}`)
resolve(res) resolve(res)
} }
}) })
}) })
}, },
/** /**
* 异步保存或更新接待记录 * 异步保存或更新接待记录
* 这个函数用于保存或更新接待记录 * 这个函数用于保存或更新接待记录
...@@ -360,45 +388,50 @@ export default { ...@@ -360,45 +388,50 @@ export default {
uni.$logger.local.info(`【上传管理Uploader】 == 开始保存或更新接待记录!!`) uni.$logger.local.info(`【上传管理Uploader】 == 开始保存或更新接待记录!!`)
try { try {
const { status, ...record } = data const { status, ...record } = data
const fileList = record.recordUrlList const fileList = Array.isArray(record.recordUrlList) ? record.recordUrlList : []
// 判断接待记录的状态,如果是没有文件或者所有文件都已经上传或完成 const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))
if (status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))) { if (isAllCompleted) {
// 过滤出状态为已上传的文件,提取其文件路径 并更新记录的 recordUrlList await this._handleCompletedRecord(record, fileList)
const updatedFile = fileList.filter(file => file.status == FileStatus.Uploaded) } else {
const pathArr = updatedFile.map(i => i.file) await this._handleIncompleteRecord(record)
// 过滤出存在本地文件路径的文件,提取其本地文件路径 以便记录保存完成后 删除 }
const originalFileArr = updatedFile.map(i => i.filePathOnClient) //正常上传的文件才删除本地文件 } catch (error) {
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】 == 本条接待所有文件已经上传和处理完毕!!`)
uni.$logger.local.info(`【上传管理Uploader】 == 已上传的文件: ${JSON.stringify(pathArr)}`) // uni.$logger.local.info(`【上传管理Uploader】 == 已上传的文件: ${JSON.stringify(serverPaths)}`)
uni.$logger.local.info(`【上传管理Uploader】 == 本地文件: ${JSON.stringify(originalFileArr)}`) // 2. 准备提交参数
const params = Object.assign(record, { recordUrlList: pathArr }) const params = { ...record, recordUrlList: serverPaths }
// 如果接待结束时间不存在,则向服务器请求接待结束时间
if (!params.receptionEndTime) { if (!params.receptionEndTime) {
params.receptionEndTime = await this._requestReceptionEndTime(pathArr, params.receptionStartTime) params.receptionEndTime = await this._requestReceptionEndTime(serverPaths, params.receptionStartTime)
} }
// 3. 提交到服务器
uni.$logger.local.info(`【上传管理Uploader】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`) uni.$logger.local.info(`【上传管理Uploader】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
//向服务器发送请求,保存接待记录
const res = await uni.$api.commonApi.saveRecCustomer(params) const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.info(`【上传管理Uploader】 == 服务器返回结果: ${JSON.stringify(res)}`) uni.$logger.local.warn(`【上传管理Uploader】 == 服务器返回结果: ${JSON.stringify(res)}`)
// 如果服务器返回结果成功 // 4. 清理本地数据
if (res) { if (res) {
// 移除本地文件 uni.$logger.local.info(`【上传管理Uploader】 == 开始删除客户端的文件!!`)
await this._removeRecordFiles(originalFileArr) await this._removeRecordFiles(localPaths)
// 从记录管理器中移除记录
await this._removeRecordById(record.id) await this._removeRecordById(record.id)
} }
} else { },
// 如果记录中还有未处理文件,记录日志并更新记录 /**
* 处理未完成的记录(仅更新本地状态)
*/
async _handleIncompleteRecord(record) {
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`) uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`)
// 更新接待记录
await uni.$dbManager.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id }) await uni.$dbManager.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
}
} catch (error) {
// 如果保存或更新接待记录失败,记录错误信息并抛出错误
this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data.id, data.filePath + data.fileName)
}
}, },
/** /**
* 向服务器请求接待结束时间 * 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间 * 这个函数用于向服务器请求接待结束时间
...@@ -435,7 +468,6 @@ export default { ...@@ -435,7 +468,6 @@ export default {
this.reportError(`【上传管理Uploader】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId }) this.reportError(`【上传管理Uploader】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
} }
}, },
/** /**
* 异步删除接待记录中的文件 * 异步删除接待记录中的文件
* @param {Array} fileArr - 要删除的文件数组 * @param {Array} fileArr - 要删除的文件数组
...@@ -452,7 +484,6 @@ export default { ...@@ -452,7 +484,6 @@ export default {
this.reportError(`【上传管理Uploader】 == 删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr }) this.reportError(`【上传管理Uploader】 == 删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr })
} }
}, },
/** /**
* 扁平化数据 * 扁平化数据
* 这个函数用于处理一个记录数组,检查每个记录的文件列表,并将文件信息扁平化 * 这个函数用于处理一个记录数组,检查每个记录的文件列表,并将文件信息扁平化
...@@ -478,7 +509,7 @@ export default { ...@@ -478,7 +509,7 @@ export default {
for (const file of recordUrlList) { for (const file of recordUrlList) {
try { 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 aFullPath = file.file.split('/')
const fileName = aFullPath.pop() const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
...@@ -500,10 +531,11 @@ export default { ...@@ -500,10 +531,11 @@ export default {
} }
return result return result
} catch (error) { } catch (error) {
throw new Error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`) // throw new Error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
uni.$logger.local.error(`【上传管理Uploader】 == 处理文件列表异常: ${error.message}`)
return result
} }
}, },
urlListFilter(urlList) { urlListFilter(urlList) {
if (!Array.isArray(urlList)) { if (!Array.isArray(urlList)) {
urlList = [] urlList = []
...@@ -511,7 +543,6 @@ export default { ...@@ -511,7 +543,6 @@ export default {
const __list = urlList.filter(item => item?.file) const __list = urlList.filter(item => item?.file)
return __list return __list
}, },
/** /**
* 检查文件是否存在 * 检查文件是否存在
* 这个函数用于检查指定文件路径是否存在 * 这个函数用于检查指定文件路径是否存在
...@@ -537,65 +568,13 @@ export default { ...@@ -537,65 +568,13 @@ export default {
}) })
}) })
}, },
isLegalFile(file) { isLegalFile(file) {
return file && file.endsWith('.mp3') return file && String(file).toLowerCase().endsWith('.mp3')
}, },
waitting(ms = this.interval) {
/** uni.$logger.local.info(ms + 'ms后开始下一轮尝试!')
* 轮询函数 this._scheduleNext(ms)
* 这个函数会检查网络连接状态,如果网络在线,则执行上传操作
* 如果网络不在线,则记录错误信息并在指定的时间间隔后重试
*/
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()
},
async wait(time = TIME_OUT_TIME) {
const msg = await this.timeoutManager.addTimeout(this.interval, time)
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)
}
},
/** /**
* 开始处理任务 * 开始处理任务
* 这个函数用于将一个任务加入到操作队列中,并在任务完成后进行轮询 * 这个函数用于将一个任务加入到操作队列中,并在任务完成后进行轮询
...@@ -603,10 +582,11 @@ export default { ...@@ -603,10 +582,11 @@ export default {
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
async beginTask(record) { 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))
await this.task(record)
}, },
/** /**
* 处理单个记录的任务 * 处理单个记录的任务
* 这个函数用于处理单个记录的上传任务 * 这个函数用于处理单个记录的上传任务
...@@ -615,18 +595,47 @@ export default { ...@@ -615,18 +595,47 @@ export default {
*/ */
task(record) { task(record) {
return new Promise(resolve => { return new Promise(resolve => {
this.updateResolve = resolve // 启动看门狗
this.uploadRecord(record) const timeoutId = this._startWatchdog()
this.updateResolve = () => {
clearTimeout(timeoutId) // 清除定时器
resolve()
}
this._taskStartTime = Date.now() // 记录任务开始时间
this._currentKey = this._getTaskKey(record.recordId, record.fileName)
this.uploadRecord(record).catch(err => {
uni.$logger.local.error(`【上传管理Uploader】 == 任务执行异常: ${err.message}`)
// 确保异常也能结束任务,释放锁
this.endTask()
})
}) })
}, },
/** /**
* 启动任务看门狗
* 防止任务执行时间过长导致死锁
* @returns {number} 定时器ID
*/
_startWatchdog() {
const TIMEOUT_THRESHOLD = 5 * 60 * 1000 // 5分钟
return setTimeout(() => {
if (this.updateResolve) {
uni.$logger.local.error('【上传管理Uploader】 == 看门狗检测到任务卡死超过5分钟,强制结束当前任务!')
this.endTask()
}
}, TIMEOUT_THRESHOLD)
},
/**
* 结束任务 * 结束任务
* 这个函数用于结束当前的任务 * 这个函数用于结束当前的任务
* 调用 resolve 方法来解决 Promise,标记任务完成 * 调用 resolve 方法来解决 Promise,标记任务完成
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
endTask() { endTask() {
this.updateResolve && this.updateResolve(), (this.updateResolve = null) this.updateResolve && this.updateResolve()
this.updateResolve = null
this._taskStartTime = null
}, },
/** /**
* 停止文件上传轮询并清除队列 * 停止文件上传轮询并清除队列
...@@ -638,8 +647,9 @@ export default { ...@@ -638,8 +647,9 @@ export default {
this.snapshot.clear() this.snapshot.clear()
this.snapshot = null this.snapshot = null
} }
if (this.operationQueue) { if (this._pumpTimer) {
this.operationQueue.clear() // 取消所有待处理的操作 clearTimeout(this._pumpTimer)
this._pumpTimer = null
} }
this.canclePromises() this.canclePromises()
uni.$logger.local.info(`【上传管理Uploader】 == 停止文件上传轮询并清除队列`) uni.$logger.local.info(`【上传管理Uploader】 == 停止文件上传轮询并清除队列`)
...@@ -653,16 +663,16 @@ export default { ...@@ -653,16 +663,16 @@ export default {
* @param {boolean} [isForce=false] - 是否强制重启轮询 * @param {boolean} [isForce=false] - 是否强制重启轮询
*/ */
setInterval(interval, isForce = false) { setInterval(interval, isForce = false) {
if (!isInteger(interval)) { // if (!isInteger(interval)) {
const error = `【上传管理Uploader】 == 参数错误!interval 必需为数字! interval -> ${interval} ` // const error = `【上传管理Uploader】 == 参数错误!interval 必需为数字! interval -> ${interval} `
uni.$logger.local.error(error) // uni.$logger.local.error(error)
return // return
} // }
this.interval = interval // this.interval = interval
if (isForce) { // if (isForce) {
this.startPolling(isForce) // this.startPolling(isForce)
} // }
uni.$logger.local.info(`【上传管理Uploader】 == 轮询间隔已设置为 ${interval} 秒`) // uni.$logger.local.info(`【上传管理Uploader】 == 轮询间隔已设置为 ${interval} 秒`)
}, },
/** /**
* 启动文件上传轮询 * 启动文件上传轮询
...@@ -672,7 +682,7 @@ export default { ...@@ -672,7 +682,7 @@ export default {
* @param {boolean} [isForce=false] - 是否强制重启轮询 * @param {boolean} [isForce=false] - 是否强制重启轮询
*/ */
async startPolling(isForce = false) { async startPolling(isForce = false) {
if (this.timeoutManager.isProcessing || this.updateResolve) { if (this._pumpRunning || this.updateResolve) {
if (!isForce) { if (!isForce) {
uni.$logger.local.info(`【上传管理Uploader】 == 非强制模式下,不强制重启轮询`) uni.$logger.local.info(`【上传管理Uploader】 == 非强制模式下,不强制重启轮询`)
return return
...@@ -682,21 +692,118 @@ export default { ...@@ -682,21 +692,118 @@ export default {
} }
} }
setTimeout(async () => { setTimeout(async () => {
// 清除之前的定时器,防止双重调度
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
await this.enQueue() await this.enQueue()
this.polling() this._scheduleNext(0)
}, 0) }, 0)
// setTimeout(() => {
// this.startPolling(true)
// }, 1000)
uni.$logger.local.info(`【上传管理Uploader】 =========开始轮询========`) uni.$logger.local.info(`【上传管理Uploader】 =========开始轮询========`)
}, },
/** /**
* 清除 timer * 清除 timer
*/ */
canclePromises() { canclePromises() {
this.timeoutManager?.cancelAllTasks() // this.timeoutManager?.cancelAllTasks() // 已移除
this.endTask() this.endTask()
}, },
async _schedulerPump() {
if (this._pumpRunning) return
this._pumpRunning = true
try {
// 1. 检查 WebView 是否就绪 (懒加载重试)
if (!this.wv) {
uni.$logger.local.warn('【上传管理Uploader】 == WebView未就绪,尝试重新初始化...')
this.wv = await this.initWebview()
if (!this.wv) {
uni.$logger.local.warn('【上传管理Uploader】 == WebView 初始化失败,稍后重试')
this.waitting() // 不再 await,直接调度下次重试
return
}
}
// 2. 检查是否满足停止条件
const stopReason = await this._checkStopConditions()
if (stopReason) {
uni.$logger.local.info(`【上传管理Uploader】 == ${stopReason}, 停止轮询`)
return
}
// 3. 执行任务
const record = this.snapshot.dequeue()
await this.beginTask(record) // 等待任务执行完成
// 成功执行后,重置重试计数器
this._retryCount = 0
// 4. 任务完成后,立即调度下一个(不需要等待 interval)
this._scheduleNext(0)
} catch (error) {
this.reportError(`【上传管理Uploader】 == 异常,error->${error.message}`)
// 指数退避策略
this._retryCount = (this._retryCount || 0) + 1
const maxDelay = 15 * 60 * 1000 // 最大延迟 15分钟
const delay = Math.min(this.interval * Math.pow(2, this._retryCount - 1), maxDelay)
uni.$logger.local.warn(`【上传管理Uploader】 == 发生异常,第 ${this._retryCount} 次重试,将在 ${delay}ms 后执行`)
this.waitting(delay)
} finally {
this._pumpRunning = false
}
},
/**
* 检查是否满足停止轮询的条件
* 如果满足,返回停止原因(字符串),否则返回 null
*/
async _checkStopConditions() {
// 1. 检查是否在后台
if (this.$store.getters.isInBackgound) {
return 'APP在后台运行,不进行文件上传'
}
// 2. 检查网络状态
const isOnline = await uni.$isNetWork()
if (!isOnline) {
return '网络异常,等待网络恢复'
}
// 3. 检查当前是否已有任务在执行
if (this.updateResolve) {
return '任务正在执行中'
}
// 4. 检查队列是否为空
if (!this.snapshot || this.snapshot.size === 0) {
await this.enQueue()
}
// 再次检查队列
if (!this.snapshot || this.snapshot.size === 0) {
return '队列为空,等待新任务唤醒'
}
return null
},
_scheduleNext(ms = 0) {
if(this.snapshot === null) return
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(
() => {
// this._checkTaskTimeout() // 已在 task 内部实现
this._schedulerPump()
},
Math.max(0, ms)
)
},
/**
* 看门狗:检查当前任务是否超时
* 防止异常情况下任务永久卡死导致队列阻塞
*/
_checkTaskTimeout() {
// 已在 task 内部实现,保留此方法为空或直接移除
},
off() { off() {
// 取消监听停止轮询事件 // 取消监听停止轮询事件
uni.$off(Command.StopPolling, this.stopPolling) uni.$off(Command.StopPolling, this.stopPolling)
...@@ -704,6 +811,11 @@ export default { ...@@ -704,6 +811,11 @@ export default {
uni.$off(Command.StartPolling, this.startPolling) uni.$off(Command.StartPolling, this.startPolling)
// 取消监听设置轮询间隔事件 // 取消监听设置轮询间隔事件
uni.$off(Command.SetPollingInterval, this.setInterval) uni.$off(Command.SetPollingInterval, this.setInterval)
// 取消网络监听
if (this._networkHandler) {
uni.offNetworkStatusChange(this._networkHandler)
this._networkHandler = null
}
} }
}, },
/** /**
......
/* /*
* @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: yangming@didihu.com.cn yangming@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2025-05-21 15:17:55 * @LastEditTime: 2026-01-21 15:56:43
* @FilePath: \gl_tape\mixin\timeout.js * @FilePath: \gl_tape\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 TIMEOUT = 40 // 40分钟
const TIMER_INTERVAL = 1 * 60 * 1000 //1分钟检一次 const Miniute = 60 * 1000
const TIMER_TIMEOUT = TIMER_DURATION / TIMER_INTERVAL const TIMER_DURATION = TIMEOUT * Miniute
const CHECK_INTERVAL = 1 * Miniute // 1分钟检查一次
import utils from '@/utils/utils'
export default { export default {
data() {
return {
__timerId: null,
_lastActiveTime: 0
}
},
methods: { methods: {
//结束提示 // 结束提示
stopRecorder() { async stopRecorder() {
this.setReceptionStatus(0) this.setReceptionStatus(0)
this.record.withError() await this.recordService.getRecorder().withError()
this.stop() await this.stop()
uni.$logger.local.info('== 长时间未触碰平板断开录音 ==')
}, },
//监听点击事件 // 初始化或启动监听
initTime() { initTime() {
uni.$logger.local.info('== 触碰平板开始计时 ==') // 1. 无论是否已启动,先更新活跃时间
this.endWatchClick() this._lastActiveTime = Date.now()
this.__timer = setInterval(() => { // 2. 如果定时器已在运行,直接返回,避免重复创建
if (this.__counter >= TIMER_TIMEOUT) { // 这是相比原方案最大的优化:全周期只有一个 setInterval 实例
//关闭录音 if (this.__timerId) return
uni.$logger.local.info('== 长时间未触碰平板 == __timer:' + this.__timer + '__counter:' + this.__counter + '分钟') // 3. 启动周期性检查
this.endWatchClick() this.__watchStart()
this.stopRecorder() },
return
__watchStart() {
this.__timerId = setInterval(async () => {
const now = Date.now()
// 直接计算时间差,比维护 counter 计数器更准确、更简单
if (now - this._lastActiveTime >= TIMER_DURATION) {
await this.__watchStop()
if (!this.__timerId) uni.$logger.local.info(`== 检测到${ TIMEOUT }分钟闲置未操作,自动停止录音 ==`)
} }
this.__counter++ }, CHECK_INTERVAL)
uni.$logger.local.info('== 未触碰平板计时 ==' + this.__counter + '分钟' + '== __timer:' + this.__timer) if (this.__timerId) uni.$logger.local.info('== 开启闲置检测 ==')
}, TIMER_INTERVAL) },
async __watchStop() {
await this.stopRecorder()
this.endWatchClick()
}, },
// 停止监听
endWatchClick() { endWatchClick() {
if (this.__timer) { if (this.__timerId) {
clearInterval(this.__timer) clearInterval(this.__timerId)
this.__timer = null this.__timerId = null
this.__counter = 0
uni.$logger.local.info('== 停止监听未触碰平板事件 == __timer:' + this.__timer + ' __counter:' + this.__counter)
} }
this._lastActiveTime = null
uni.$logger.local.info('== 停止闲置检测 ==')
}, },
handleTouchStart() {
if (this.__counter > 0) { // 响应触摸事件
uni.$logger.local.info(`== ${this.__counter}分钟后触碰平板,重置计数器 == __timer:${this.__timer}`) // 使用 debounce 包装:在连续触摸过程中(如滑动屏幕)不更新,
} // 只有用户停止操作 1秒后,才更新一次时间戳
this.__counter = 0 handleTouchStart: utils.debounce(function() {
} this._lastActiveTime = Date.now()
}, 1500),
},
created() {
uni.$on('reset_timeout', this.handleTouchStart)
}, },
beforeDestroy() { beforeDestroy() {
if (this.__timer) { uni.$off('reset_timeout', this.handleTouchStart)
clearInterval(this.__timer) this.endWatchClick()
}
} }
} }
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
* @Description: * @Description:
* @Author: huyue * @Author: huyue
* @Date: 2024-04-08 11:30:30 * @Date: 2024-04-08 11:30:30
* @LastEditors: 前端 qianduan01@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2024-12-25 18:52:46 * @LastEditTime: 2026-01-07 19:23:33
--> -->
<template> <template>
<view <view
...@@ -25,14 +25,23 @@ ...@@ -25,14 +25,23 @@
></uni-icons> ></uni-icons>
</view> </view>
</view> </view>
<template v-for="(item, index) in (useCarConfig ? moduleList :media)"> <template v-for="(item, index) in renderList">
<!-- 极端性能优化:只渲染当前页及其左右邻居的空壳容器,更远的直接移除 DOM -->
<view <view
v-if="shouldRender(index)"
:class="['view', { showView: id == item.id }, modeName]" :class="['view', { showView: id == item.id }, modeName]"
:key="index" :key="item.id"
:style="getViewStyle(item.id)"
@touchstart.stop="touchStart" @touchstart.stop="touchStart"
@touchmove.stop="touchMove"
@touchend.stop="touchEnd" @touchend.stop="touchEnd"
> >
<view class="component-wrapper">
<!-- 核心内容:只有在 isComponentLoaded 为 true 时才真正渲染子组件 -->
<!-- 并且增加 v-if="shouldRenderContent(index)" 双重保险,确保非邻居页的重组件彻底销毁 -->
<component <component
class="fade-in-component"
v-if="isComponentLoaded(index) && shouldRenderContent(index)"
@full="handleFull" @full="handleFull"
:detail="item" :detail="item"
:is="item.componentName" :is="item.componentName"
...@@ -52,6 +61,7 @@ ...@@ -52,6 +61,7 @@
:aitoCarModelIds="aitoCarModelIds" :aitoCarModelIds="aitoCarModelIds"
/> />
</view> </view>
</view>
</template> </template>
<template v-if="type != 'preview'"> <template v-if="type != 'preview'">
<template v-if="backZindex"> <template v-if="backZindex">
...@@ -141,7 +151,10 @@ export default { ...@@ -141,7 +151,10 @@ export default {
moduleList: [], moduleList: [],
useCarConfig: false, useCarConfig: false,
dateilKey: Date.now(), dateilKey: Date.now(),
currentMediaId: '' currentMediaId: '',
touchDiffX: 0,
isTouching: false,
loadedIndexes: [] // 记录已加载组件的索引
} }
}, },
computed: { computed: {
...@@ -190,17 +203,67 @@ export default { ...@@ -190,17 +203,67 @@ export default {
}, },
viewKey () { viewKey () {
return this.$store.state.user.viewKey return this.$store.state.user.viewKey
},
// 缓存当前渲染列表,避免在 template 中重复计算三元表达式
renderList() {
return this.useCarConfig ? this.moduleList : this.media
},
// 缓存当前 ID 的索引,避免在 v-if 中重复查找
currentIndex() {
// 优化查找性能,如果列表很大,findIndex 可能会慢
// 但由于我们已经按需渲染了,这里通常不会是瓶颈
// 为了极致性能,可以考虑维护一个 map 或直接缓存 index
if (!this.renderList || !this.renderList.length) return -1
return this.renderList.findIndex(i => i.id == this.id)
} }
}, },
watch: { watch: {
// 监听 currentIndex 变化,处理预加载逻辑
currentIndex: {
immediate: true,
handler(newVal) {
if (newVal === -1) return
// 1. 立即加载当前页
this.addLoadedIndex(newVal)
// 2. 延迟预加载前后页(防抖处理)
if (this.preloadTimer) {
clearTimeout(this.preloadTimer)
this.preloadTimer = null
}
// 只有当用户停止滑动 300ms 后才开始预加载,避免滑动过程中的无效计算
this.preloadTimer = setTimeout(() => {
if (this._isDestroyed) return // 增加销毁判断
if (!this.renderList) return
const len = this.renderList.length
if (len === 0) return
const prev = newVal === 0 ? len - 1 : newVal - 1
const next = newVal === len - 1 ? 0 : newVal + 1
// 使用 requestAnimationFrame 或 $nextTick 分批执行,降低主线程压力
this.$nextTick(() => {
this.addLoadedIndex(prev)
this.$nextTick(() => {
this.addLoadedIndex(next)
})
})
}, 300)
}
},
watchStatus: { watchStatus: {
immediate: true, immediate: true,
handler (newval) { handler (newval) {
if (newval) {
this.useCarConfig = false this.useCarConfig = false
this.dateilKey = Date.now() this.dateilKey = Date.now()
this.pageToolList = this.toolList this.pageToolList = this.toolList
this.currentMediaId = this.mediaId this.currentMediaId = this.mediaId
if (newval) this.drawStatus = false this.drawStatus = false
}
} }
}, },
viewKey: { viewKey: {
...@@ -226,6 +289,21 @@ export default { ...@@ -226,6 +289,21 @@ export default {
const systemInfo = uni.getSystemInfoSync() const systemInfo = uni.getSystemInfoSync()
this.screenWidth = systemInfo.screenWidth this.screenWidth = systemInfo.screenWidth
}, },
beforeDestroy() {
// 1. 清理所有定时器
if (this.preloadTimer) clearTimeout(this.preloadTimer)
if (this.rafId) clearTimeout(this.rafId) // 兼容 raf
// 2. 深度清理数据引用,帮助 GC 快速回收
// 将大对象置为 null,切断引用链
this.moduleList = null
this.pageToolList = null
this.scaleValueObject = null
this.loadedIndexes = null
// 3. 手动触发组件销毁(虽然 Vue 会自动做,但显式重置有助于避免闭包内存泄漏)
this.currentMediaId = null
},
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus']), ...mapMutations('audio', ['setReceptionStatus']),
open () { open () {
...@@ -264,44 +342,133 @@ export default { ...@@ -264,44 +342,133 @@ export default {
// dbClick () { // dbClick () {
// if (!this.isPreview) this.drawStatus = !this.drawStatus // if (!this.isPreview) this.drawStatus = !this.drawStatus
// }, // },
getViewStyle(itemId) {
if (this.id !== itemId) return {}
// 回弹动画
if (!this.isTouching && this.touchDiffX !== 0) {
return {
transform: `translateX(0px)`,
transition: 'transform 0.4s cubic-bezier(0.25, 0.8, 0.25, 1)' // 丝滑回弹
}
}
// 拖动中
if (this.isTouching) {
// 增加阻尼感:滑动距离越大,阻力越大
// 使用 log 函数或衰减系数来模拟阻尼
// 调整阻尼系数,让滑动更轻松
// 1.0 = 1:1 跟手,没有任何阻力,感觉最轻盈
const damping = 1.0 // 0.8 -> 1.0,完全跟手
const dampedX = this.touchDiffX * damping
return {
transform: `translateX(${dampedX}px)`,
transition: 'none'
}
}
return {}
},
touchStart (e) { touchStart (e) {
if (!this.drawStatus && e.changedTouches?.length) { if (!this.drawStatus && e.changedTouches?.length) {
this.startX = e.changedTouches[0].pageX this.startX = e.changedTouches[0].pageX
this.startY = e.changedTouches[0].pageY this.startY = e.changedTouches[0].pageY
this.isTouching = true
this.touchDiffX = 0
this.startTime = Date.now()
}
},
touchMove (e) {
if (!this.isTouching || this.drawStatus) return
// 使用 requestAnimationFrame 优化滑动性能
// 注意:uniapp 环境下可能需要使用 wxs 或者模拟 raf
if (this.rafId) return
this.rafId = setTimeout(() => {
const touch = e.changedTouches[0]
// 垂直滑动不触发水平拖动
if (Math.abs(touch.pageY - this.startY) > Math.abs(touch.pageX - this.startX)) {
this.rafId = null
return
} }
this.touchDiffX = touch.pageX - this.startX
this.rafId = null
}, 1000 / 60) // 限制在 60fps
}, },
touchEnd (e) { touchEnd (e) {
this.isTouching = false
if (this.modeName) return if (this.modeName) return
try { try {
let { pageToolList, drawStatus, startX, screenWidth, id, scaleValueObject, productModelStatus } = this let { pageToolList, drawStatus, startX, screenWidth, id, scaleValueObject, productModelStatus } = this
if (!e || !e.changedTouches || drawStatus || pageToolList.length == 0 || e.changedTouches.length === 0) return
let halfScreenWidth = screenWidth / 2, // 如果没有触摸事件数据,重置并返回
touch = e.changedTouches[0], if (!e || !e.changedTouches || drawStatus || pageToolList.length == 0 || e.changedTouches.length === 0) {
isDistanceSignificant = Math.abs(touch.pageX - startX) > screenWidth / 6, // 这里不需要手动重置 touchDiffX 为 0,因为 isTouching=false 后,getViewStyle 会自动处理回弹
index = pageToolList.findIndex(item => item.id == id) // 只需要在动画结束后清理状态即可
if (Math.abs(this.startY - touch.pageY) > 150) return setTimeout(() => { this.touchDiffX = 0 }, 400)
return
}
const touch = e.changedTouches[0]
const endX = touch.pageX
const diffX = endX - startX
// 垂直滑动距离过大
if (Math.abs(this.startY - touch.pageY) > 100) {
// 触发回弹
setTimeout(() => { this.touchDiffX = 0 }, 400)
return
}
// 滑动距离阈值
// 降低阈值:screenWidth / 6 -> screenWidth / 8
// 让用户不需要滑太远就能触发切换
const isDistanceSignificant = Math.abs(diffX) > screenWidth / 8
const index = pageToolList.findIndex(item => item.id == id)
if (!scaleValueObject[id]) scaleValueObject[id] = 1 if (!scaleValueObject[id]) scaleValueObject[id] = 1
if (isDistanceSignificant && index != -1 && scaleValueObject[id] == 1 && !productModelStatus) { if (isDistanceSignificant && index != -1 && scaleValueObject[id] == 1 && !productModelStatus) {
const { nextId, modeName, title } = this.getNextId(index, pageToolList, startX, halfScreenWidth) const { nextId, modeName, title } = this.getNextId(index, pageToolList, diffX)
this.modeName = modeName this.modeName = modeName
this.receptionTrackLeave() this.receptionTrackLeave()
this.$emit('update:id', nextId) this.$emit('update:id', nextId)
uni.$logger.local.info(`预览${title}`) uni.$logger.local.info(`预览${title}`)
// 切换成功,不需要回弹动画,直接重置
this.touchDiffX = 0
setTimeout(() => { setTimeout(() => {
this.modeName = '' this.modeName = ''
}, 500) }, 500)
} else {
// 未触发切换,触发回弹
// getViewStyle 会处理回弹动画
// 动画结束后重置数据
setTimeout(() => {
this.touchDiffX = 0
}, 400)
} }
} catch (error) { } catch (error) {
console.log(error) console.log(error)
this.touchDiffX = 0
} }
}, },
getNextId (index, pageToolList, startX, halfScreenWidth) { getNextId (index, pageToolList, diffX) {
let nextItem = {}, let nextItem = {},
modeName = '' modeName = ''
if (startX > halfScreenWidth) {
if (diffX < 0) {
// 向左滑动 (diffX < 0),表示想看右边的内容(下一个)
// 动画效果应该是内容从右边进来 (to-right) 或者当前内容向左移出
// 假设 to-right 是新页面从右侧滑入
nextItem = index === pageToolList.length - 1 ? pageToolList[0] : pageToolList[index + 1] nextItem = index === pageToolList.length - 1 ? pageToolList[0] : pageToolList[index + 1]
modeName = 'to-right' modeName = 'to-right'
} else { } else {
// 向右滑动 (diffX > 0),表示想看左边的内容(上一个)
// 动画效果应该是内容从左边进来 (to-left)
nextItem = index === 0 ? pageToolList[pageToolList.length - 1] : pageToolList[index - 1] nextItem = index === 0 ? pageToolList[pageToolList.length - 1] : pageToolList[index - 1]
modeName = 'to-left' modeName = 'to-left'
} }
...@@ -346,16 +513,57 @@ export default { ...@@ -346,16 +513,57 @@ export default {
{ id, moduleList, toolList } = data { id, moduleList, toolList } = data
let { useCarConfig, moduleList: pageModuleList, media: pageMedia } = this, let { useCarConfig, moduleList: pageModuleList, media: pageMedia } = this,
array = useCarConfig ? pageModuleList : pageMedia, array = useCarConfig ? pageModuleList : pageMedia,
{ detailTitle } = array.find(item => item.id == pageId) { detailTitle } = array.find(item => item.id == pageId) || {} // 防止未找到报错
this.receptionTrackLeave() this.receptionTrackLeave()
this.moduleList = moduleList // 使用 Object.freeze 冻结大对象,提升性能
this.pageToolList = toolList this.moduleList = Object.freeze(moduleList)
this.pageToolList = Object.freeze(toolList)
this.useCarConfig = true this.useCarConfig = true
if (id != currentMediaId) { if (id != currentMediaId) {
let jumpItem = moduleList.find(e => e.detailTitle == detailTitle) let jumpItem = moduleList.find(e => e.detailTitle == detailTitle)
this.$emit('update:id', jumpItem ? jumpItem.id : moduleList[0].id) this.$emit('update:id', jumpItem ? jumpItem.id : moduleList[0].id)
} }
this.currentMediaId = id this.currentMediaId = id
},
shouldRender(index) {
const len = this.renderList.length
const current = this.currentIndex
// 异常情况保护:如果找不到当前索引,或者列表为空,默认渲染第一项或全部
if (current === -1 || len === 0) return index === 0
// 基础范围:当前页的前后一页
if (Math.abs(index - current) <= 1) return true
// 循环边界处理
if (current === 0 && index === len - 1) return true
if (current === len - 1 && index === 0) return true
return false
},
// 进一步限制内容渲染范围:只保留当前页和左右各1页的内容
// 即使 loadedIndexes 里有,如果距离太远,也要销毁内容以释放内存
shouldRenderContent(index) {
const current = this.currentIndex
const len = this.renderList.length
// 基础范围:当前页的前后一页
if (Math.abs(index - current) <= 1) return true
// 循环边界处理
if (current === 0 && index === len - 1) return true
if (current === len - 1 && index === 0) return true
return false
},
// 判断组件是否应该实际渲染(配合 v-if)
isComponentLoaded(index) {
return this.loadedIndexes.includes(index)
},
addLoadedIndex(index) {
if (!this.loadedIndexes.includes(index)) {
this.loadedIndexes.push(index)
}
} }
} }
} }
...@@ -407,32 +615,54 @@ export default { ...@@ -407,32 +615,54 @@ export default {
top: 0; top: 0;
left: 0; left: 0;
visibility: hidden; visibility: hidden;
} will-change: transform; // 提前告知浏览器该元素会变化,优化渲染
}
.component-wrapper {
width: 100%;
height: 100%;
// 强制开启硬件加速,避免组件渲染引起的重排
transform: translateZ(0);
}
.showView { .showView {
position: absolute; position: absolute;
z-index: 1; z-index: 1;
visibility: visible; visibility: visible;
} }
.to-left { .to-left {
animation: to-left 0.25s forwards; animation: to-left 0.4s cubic-bezier(0.25, 1, 0.5, 1) forwards;
} }
.to-right { .to-right {
animation: to-right 0.25s forwards; animation: to-right 0.4s cubic-bezier(0.25, 1, 0.5, 1) forwards;
} }
@keyframes to-left { @keyframes to-left {
0% { 0% {
left: -100%; transform: translateX(-100%) scale(0.95);
opacity: 0.8;
} }
100% { 100% {
left: 0; transform: translateX(0) scale(1);
opacity: 1;
} }
} }
@keyframes to-right { @keyframes to-right {
0% { 0% {
left: 100%; transform: translateX(100%) scale(0.95);
opacity: 0.8;
} }
100% { 100% {
left: 0; transform: translateX(0) scale(1);
opacity: 1;
}
}
.fade-in-component {
animation: fadeIn 0.3s ease-out forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
} }
} }
</style> </style>
...@@ -48,12 +48,14 @@ export default { ...@@ -48,12 +48,14 @@ export default {
}) })
return return
} }
this.$refs.home.updateApp() // this.$refs.home.updateApp()
this.$refs.home?.updateApp()
this.init() this.init()
}, },
methods: { methods: {
init () { init () {
this.$refs.home.$refs.leftBox.getMessageInfo() // this.$refs.home.$refs.leftBox.getMessageInfo()
this.$refs.home?.$refs?.leftBox?.getMessageInfo()
}, },
} }
} }
......
...@@ -15,6 +15,7 @@ import update from './modules/update' ...@@ -15,6 +15,7 @@ import update from './modules/update'
import sys from './modules/sys' import sys from './modules/sys'
import point from './modules/point' import point from './modules/point'
import boutique from './modules/boutique' import boutique from './modules/boutique'
import createActivityTracker from './plugins/activityTracker'
Vue.use(Vuex) Vue.use(Vuex)
const store = new Vuex.Store({ const store = new Vuex.Store({
...@@ -26,7 +27,15 @@ const store = new Vuex.Store({ ...@@ -26,7 +27,15 @@ const store = new Vuex.Store({
point, point,
boutique boutique
}, },
getters getters,
plugins: [
createActivityTracker([
// 'setCustomerInfo',
'setReceptionTrack',
// 'setPaymentType',
// 'setCurrentCarInfo'
])
]
}) })
// Vue.prototype.$store = store; // Vue.prototype.$store = store;
......
...@@ -51,6 +51,26 @@ export default { ...@@ -51,6 +51,26 @@ export default {
state.customerInfo = data state.customerInfo = data
state.customerKey = Date.now() state.customerKey = Date.now()
}, },
setReceptionTrack (state, { key, value }) {
state.receptionTrack[key] = value
state.receptionKey = Date.now()
},
clearReceptionTrack (state) {
state.receptionTrack = {}
state.receptionKey = Date.now()
},
updateViewKey (state) {
state.viewKey = Date.now();
},
setPaymentType (state, value) {
state.paymentType = value;
},
setCarBrandsList (state, value) {
state.carBrands = value;
},
setEmployeeList (state, value) {
state.employeeList = value;
},
setCurrentCarInfo (state, data = {}) { setCurrentCarInfo (state, data = {}) {
state.currentCarInfo = data; state.currentCarInfo = data;
}, },
...@@ -80,7 +100,7 @@ export default { ...@@ -80,7 +100,7 @@ export default {
return state.customerInfo; return state.customerInfo;
}, },
setCustomerInfo ({ commit }, value) { setCustomerInfo ({ commit }, value) {
uni.$logger.local.info(`当前接待客户信息: ${JSON.stringify(value)}`) // uni.$logger.local.info(`当前接待客户信息: ${JSON.stringify(value)}`)
commit("setCustomerInfo", value); commit("setCustomerInfo", value);
}, },
clearCustomerInfo ({ commit }) { clearCustomerInfo ({ commit }) {
...@@ -89,26 +109,23 @@ export default { ...@@ -89,26 +109,23 @@ export default {
clearHistory ({ state }) { clearHistory ({ state }) {
state.historyStatus = Date.now(); state.historyStatus = Date.now();
}, },
setPaymentType ({ state }, value) { setPaymentType ({ commit }, value) {
state.paymentType = value; commit('setPaymentType', value)
}, },
setCarBrandsList ({ state }, value) { setCarBrandsList ({ commit }, value) {
state.carBrands = value; commit('setCarBrandsList', value)
}, },
setEmployeeList ({ state }, value) { setEmployeeList ({ commit }, value) {
state.employeeList = value; commit('setEmployeeList', value)
}, },
setReceptionTrack ({ state }, { key, value }) { setReceptionTrack ({ commit }, { key, value }) {
state.receptionTrack[key] = value commit('setReceptionTrack', { key, value })
state.receptionKey = Date.now()
}, },
clearReceptionTrack ({ state }) { clearReceptionTrack ({ commit }) {
state.receptionTrack = {} commit('clearReceptionTrack')
state.receptionKey = Date.now()
}, },
updateViewKey ({ state }) { updateViewKey ({ commit }) {
state.viewKey = Date.now(); commit('updateViewKey')
}, },
setCurrentCarInfo ({ commit }, value) { setCurrentCarInfo ({ commit }, value) {
commit("setCurrentCarInfo", value); commit("setCurrentCarInfo", value);
......
// store/plugins/activityTracker.js
import utils from '@/utils/utils'
/**
* 自动监听用户活跃状态的 Vuex 插件
* 当指定的 mutation 发生时,触发 reset_timeout 事件
*/
export default function createActivityTracker(mutationsToWatch = []) {
// 使用 utils.throttle 限制触发频率,避免高频 mutation 导致过多 emit
const notifyActivity = utils.throttle(() => {
uni.$emit('reset_timeout')
}, 1000)
return store => {
store.subscribe((mutation, state) => {
// 如果 mutation 在监控列表中,则触发活跃通知
if (mutationsToWatch.includes(mutation.type)) {
notifyActivity()
}
})
}
}
/*
* @Descripttion: 通用任务队列类实现了串行执行、超时控制、异常隔离等功能
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 12:03:27
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:45:20
* @FilePath: \gl_tape\utils\TaskQueue.js
*/
export default class TaskQueue {
constructor(name = 'TaskQueue') {
this.name = name
this.queue = Promise.resolve()
}
/**
* 将任务加入队列
* @param {Function} task - 返回 Promise 的任务函数
* @param {number} timeout - 超时时间(ms),默认 20000
* @returns {Promise}
*/
enqueue(task, timeout = 20000) {
const taskWithTimeout = () => this._withTimeout(task, timeout)
// 将任务追加到队列末尾
const next = this.queue.then(taskWithTimeout).catch(err => {
// 队列自身的错误不应中断后续任务,但这里的 err 已经被 taskWithTimeout 内部捕获并处理了
// 这里再次抛出是为了让调用者能捕获到错误
throw err
})
// 更新队列指针,确保队列始终指向最新的 Promise,且永远是 resolved 状态(catch 了错误)
// 这样后续任务不会因为前一个任务失败而无法执行
this.queue = next.catch(() => {})
return next
}
/**
* 带超时控制的任务执行器
* @private
*/
_withTimeout(task, timeout) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
const error = new Error(`${this.name}操作超时(${timeout}ms)`)
uni.$logger.local.error(error.message)
reject(error)
}, timeout)
// 使用 Promise.resolve().then(task) 确保即使 task() 同步抛错也能被捕获并进入 finally
Promise.resolve().then(task)
.then(resolve)
.catch(reject)
.finally(() => clearTimeout(timeoutId))
})
}
}
\ No newline at end of file \ No newline at end of file
...@@ -5,6 +5,7 @@ class LocalLog { ...@@ -5,6 +5,7 @@ class LocalLog {
logger = null logger = null
constructor() { constructor() {
this.logger = new LogCat() this.logger = new LogCat()
this.removeOverDays(90)
} }
debug(msg) { debug(msg) {
this.logger.writeLog(LogLevel.DEBUG, msg) this.logger.writeLog(LogLevel.DEBUG, msg)
...@@ -36,15 +37,16 @@ class LocalLog { ...@@ -36,15 +37,16 @@ class LocalLog {
return fileList return fileList
} }
removeOverDays(day = 7) { removeOverDays(day = 7) {
const logFiles = this.logger.getLogFileList() this.logger._cleanOldLogs(day)
if (!logFiles.length) return // const logFiles = this.logger.getLogFileList()
const today = getTime('YYYY-MM-DD') // if (!logFiles.length) return
logFiles.forEach(({ name, path }) => { // const today = getTime('YYYY-MM-DD')
const fileDate = name.split('.').shift() // logFiles.forEach(({ name, path }) => {
if (daysBetween(fileDate, today) > day) { // const fileDate = name.split('.').shift()
this.logger.removeLogFile(path) // if (daysBetween(fileDate, today) > day) {
} // this.logger.removeLogFile(path)
}) // }
// })
} }
} }
export default LocalLog export default LocalLog
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-09-03 13:48:51
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:49:25
* @FilePath: \gl_tape\utils\logger\LogCat.js
*/
import { getTime } from './util' import { getTime } from './util'
import { serializeIfObject } from '../utils' import { serializeIfObject } from '../utils'
import TaskQueue from '../TaskQueue'
class LogCat { class LogCat {
main = plus.android.runtimeMainActivity() main = plus.android.runtimeMainActivity()
File = plus.android.importClass('java.io.File') File = plus.android.importClass('java.io.File')
...@@ -11,145 +22,224 @@ class LogCat { ...@@ -11,145 +22,224 @@ class LogCat {
// FileInputStream = plus.android.importClass('java.io.FileInputStream') // FileInputStream = plus.android.importClass('java.io.FileInputStream')
// InputStreamReader = plus.android.importClass('java.io.InputStreamReader') // InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
LogPath = '' LogPath = ''
// 日志写入队列,确保串行写入
taskQueue = new TaskQueue('LogCat')
// 记录上一次检查清理的日期,用于跨天触发清理
lastCleanDate = ''
// 流复用相关变量
currentWriter = null // 当前 BufferedWriter
currentFos = null // 当前 FileOutputStream
currentLogFile = '' // 当前打开的日志文件路径
closeTimer = null // 自动关闭流的定时器
constructor(folderName = '_zyzs_log') { constructor(folderName = '_zyzs_log') {
try {
let file = null
if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) { if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName file = this.main.getExternalFilesDir(null)
}
if (file) {
this.LogPath = file.getPath() + folderName
} else { } else {
this.LogPath = this.main.getFilesDir().getPath() + folderName this.LogPath = this.main.getFilesDir().getPath() + folderName
} }
// 初始化日志目录对象,避免每次写入都 new
this.logDirFile = new this.File(this.LogPath)
// 启动自动清理(清理7天前的日志)this.lastCleanDate = getTime('YYYY-MM-DD')
} catch (e) {
console.error('LogCat init error:', e)
this.LogPath = ''
}
console.log('日志文件存放路径->', this.LogPath) console.log('日志文件存放路径->', this.LogPath)
} }
writeLog(tag, messages) { writeLog(tag, messages) {
let msg = serializeIfObject(messages) // 将写入任务加入队列
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
// 延迟一小段时间执行,避免阻塞 UI 渲染
setTimeout(() => {
this._doWriteLog(tag, messages)
resolve()
}, 0)
})
})
}
// 真正的写入逻辑(私有方法)
_doWriteLog(tag, messages) {
// 如果路径初始化失败,直接放弃写入,避免报错
if (!this.LogPath) return
let msg = ''
try {
if (messages instanceof Error) {
msg = messages.stack || messages.message
} else if (messages === undefined) {
msg = 'undefined'
} else {
msg = serializeIfObject(messages)
}
} catch (e) {
msg = String(messages)
}
let date = getTime('YYYY-MM-DD') let date = getTime('YYYY-MM-DD')
// 检查跨天:如果当前日期与上次清理日期不同,触发一次清理
if (this.lastCleanDate && date !== this.lastCleanDate) {
this.lastCleanDate = date
}
let datetime = getTime() let datetime = getTime()
//文件名 //文件名
let fileName = this.LogPath + '/' + date + '.txt' let fileName = this.LogPath + '/' + date + '.txt'
//写入的内容 //写入的内容
let content = `${datetime} [${tag}] : ${msg}\n` let content = `${datetime} [${tag}] : ${msg}\n`
console.log(content.replace(/\n/g, ''))
let path = new this.File(this.LogPath) // 使用对应的 console 方法输出
if (!path.exists()) { const logFunc = console[tag] || console.log
path.mkdirs() //创建父路径 logFunc(content.replace(/\n/g, ''))
// 移除重复的目录检查,仅在必要时(如目录被意外删除)才尝试重建
// let path = new this.File(this.LogPath)
// if (!path.exists()) {
// path.mkdirs()
// }
// 双重保险:虽然构造函数里创建了,但防止运行时目录被误删
if (this.logDirFile && !this.logDirFile.exists()) {
this.logDirFile.mkdirs()
} }
let fos = null
let bw = null
try { try {
fos = new this.FileOutputStream(fileName, true) // 1. 如果当前没有流,或者文件名变了(跨天),则重新打开
bw = new this.BufferedWriter(new this.OutputStreamWriter(fos)) if (!this.currentWriter || this.currentLogFile !== fileName) {
//bw.write(log); this._closeStream() // 关闭旧流
bw.append(content)
this.currentFos = new this.FileOutputStream(fileName, true)
this.currentWriter = new this.BufferedWriter(new this.OutputStreamWriter(this.currentFos))
this.currentLogFile = fileName
}
// 2. 写入内容
this.currentWriter.append(content)
// 3. 刷新缓冲区,确保内容真正写入磁盘(虽然有性能损耗,但防止崩溃丢日志)
// 也可以选择积累一定量再 flush,这里为了安全选择每次 flush
this.currentWriter.flush()
// 4. 重置自动关闭定时器 (5秒后无操作自动关闭)
if (this.closeTimer) {
clearTimeout(this.closeTimer)
}
this.closeTimer = setTimeout(() => {
this._closeStream()
}, 5000)
} catch (e) { } catch (e) {
console.log('e->', e) console.log('日志写入失败:', e)
} finally { // 发生异常时尝试关闭流,以便下次重试
this._closeStream()
}
}
// 关闭当前流
_closeStream() {
try { try {
if (bw != null) { if (this.closeTimer) {
bw.close() //关闭缓冲流 clearTimeout(this.closeTimer)
fos.close() //关闭文件输出流 this.closeTimer = null
} }
} catch (closeEx) {
console.log('closeEx->', closeEx) if (this.currentWriter != null) {
this.currentWriter.close()
this.currentWriter = null
} }
// BufferedWriter 关闭时会自动关闭底层的 FileOutputStream,
// 但为了保险起见,如果 writer 创建失败导致 fos 悬空,这里单独检查一下
if (this.currentFos != null) {
// 如果 writer 已经关闭了 fos,再次关闭也不会报错
this.currentFos.close()
this.currentFos = null
}
this.currentLogFile = ''
} catch (e) {
console.log('关闭日志流失败:', e)
} }
} }
// 自动清理旧日志
_cleanOldLogs(daysToKeep) {
// 放入队列异步执行,不影响启动速度
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
setTimeout(() => {
try {
const list = this.getLogFileList()
const now = new Date().getTime()
const oneDay = 24 * 60 * 60 * 1000
list.forEach(file => {
// 文件名格式:YYYY-MM-DD.txt
const match = file.name.match(/^(\d{4}-\d{2}-\d{2})\.txt$/)
if (match) {
const fileDate = new Date(match[1]).getTime()
// 如果文件日期早于 (当前时间 - 保留天数),则删除
if (now - fileDate > daysToKeep * oneDay) {
this.removeLogFile(file.path)
}
}
})
} catch (e) {
console.error('清理旧日志失败:', e)
} finally {
resolve()
}
}, 1000) // 延迟1秒执行,避开App启动高峰
})
})
}
// 删除日志 // 删除日志
removeLogFile(fileName) { removeLogFile(fileName) {
try {
let file = new this.File(fileName) let file = new this.File(fileName)
let fos = new this.FileOutputStream(fileName, true) if (file.exists()) {
fos.close()
file.delete() file.delete()
console.log('删除------' + fileName) console.log('删除------' + fileName)
} }
} catch (e) {
console.error('删除日志失败:', e)
}
}
// 获取所有日志文件列表 // 获取所有日志文件列表
getLogFileList() { getLogFileList() {
try {
if (!this.LogPath) return []
let file = new this.File(this.LogPath) let file = new this.File(this.LogPath)
if (!file.exists()) return []
let tempList = file.listFiles() let tempList = file.listFiles()
if (!tempList || tempList.length === 0) return [] if (!tempList || tempList.length === 0) return []
const list = tempList.map(file => {
return { // 注意:Java数组在NativeJS中可能没有map方法,建议使用循环
name: file.getName(), const list = []
path: file.getPath() for (let i = 0; i < tempList.length; i++) {
} const f = tempList[i]
list.push({
name: f.getName(),
path: f.getPath()
}) })
}
return list return list
} catch (e) {
console.error('获取日志列表失败:', e)
return []
}
} }
} }
export default LogCat export default LogCat
\ No newline at end of file \ No newline at end of file
// import { getTime } from './util'
// import { serializeIfObject } from '../utils'
// class LogCat {
// // main = plus.android.runtimeMainActivity()
// // File = plus.android.importClass('java.io.File')
// // Environment = plus.android.importClass('android.os.Environment')
// // BufferedWriter = plus.android.importClass('java.io.BufferedWriter')
// // FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
// // OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')
// // BufferedReader = plus.android.importClass('java.io.BufferedReader')
// // FileInputStream = plus.android.importClass('java.io.FileInputStream')
// // InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
// LogPath = ''
// constructor(folderName = '_zyzs_log') {
// // if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
// // this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName
// // } else {
// // this.LogPath = this.main.getFilesDir().getPath() + folderName
// // }
// // console.log('日志文件存放路径->', this.LogPath)
// }
// writeLog(tag, messages) {
// return
// let msg = serializeIfObject(messages)
// let date = getTime('YYYY-MM-DD')
// let datetime = getTime()
// //文件名
// let fileName = this.LogPath + '/' + date + '.txt'
// //写入的内容
// let content = `${datetime} [${tag}] : ${msg}\n`
// console.log(content.replace(/\n/g, ''))
// let path = new this.File(this.LogPath)
// if (!path.exists()) {
// path.mkdirs() //创建父路径
// }
// let fos = null
// let bw = null
// try {
// fos = new this.FileOutputStream(fileName, true)
// bw = new this.BufferedWriter(new this.OutputStreamWriter(fos))
// //bw.write(log);
// bw.append(content)
// } catch (e) {
// console.log('e->', e)
// } finally {
// try {
// if (bw != null) {
// bw.close() //关闭缓冲流
// fos.close() //关闭文件输出流
// }
// } catch (closeEx) {
// console.log('closeEx->', closeEx)
// }
// }
// }
// // 删除日志
// removeLogFile(fileName) {
// let file = new this.File(fileName)
// let fos = new this.FileOutputStream(fileName, true)
// fos.close()
// file.delete()
// console.log('删除------' + fileName)
// }
// // 获取所有日志文件列表
// getLogFileList() {
// let file = new this.File(this.LogPath)
// let tempList = file.listFiles()
// if (!tempList || tempList.length === 0) return []
// const list = tempList.map(file => {
// return {
// name: file.getName(),
// path: file.getPath()
// }
// })
// return list
// }
// }
// export default LogCat
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-09-03 14:22:52
* @LastEditors: limin
* @LastEditTime: 2026-01-22 16:21:17
* @FilePath: \gl_tape\utils\logger\RemoteLog.js
*/
import sentryInit from '@/utils/sentryConfig/sentryInit' import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel , RemoteExtraDataKey} from './constants' import { LogLevel , RemoteExtraDataKey} from './constants'
class RemoteLog { class RemoteLog {
...@@ -20,10 +29,43 @@ class RemoteLog { ...@@ -20,10 +29,43 @@ class RemoteLog {
} }
send(level, { extra = {}, msg, tag = { key: '', value: '' } }) { send(level, { extra = {}, msg, tag = { key: '', value: '' } }) {
this.sentry.withScope(scope => { this.sentry.withScope(scope => {
scope.setTags(tag.key, tag.value) // 1. 设置 Tag
scope.setExtra(RemoteExtraDataKey, extra) if (tag && tag.key) {
scope.setTag(tag.key, tag.value)
}
// 2. 自动补充环境信息到 Extra
const systemInfo = uni.getSystemInfoSync()
const enhancedExtra = {
...extra,
device_brand: systemInfo.brand,
device_model: systemInfo.model,
os_name: systemInfo.osName, // uni-app x 支持,或用 platform
os_version: systemInfo.osVersion,
uni_platform: systemInfo.uniPlatform,
app_version: systemInfo.appVersion,
network_type: 'unknown' // 可选:尝试获取网络状态
}
// 尝试获取网络状态(如果允许异步)
// uni.getNetworkType({ success: (res) => enhancedExtra.network_type = res.networkType })
scope.setExtra(RemoteExtraDataKey, enhancedExtra)
// 3. 设置级别
scope.setLevel(level) scope.setLevel(level)
this.sentry.captureException(new Error(msg))
// 4. 上报 (区分 Error 对象和普通消息)
// 如果 msg 本身就是 Error 对象,直接上报以保留堆栈信息
// 如果是字符串,则包装成 Error
if (msg instanceof Error) {
this.sentry.captureException(msg)
} else {
// 将字符串消息作为 Error 的 message,这样在 Sentry 面板中更直观
const error = new Error(String(msg))
// 可以手动尝试附加调用栈(虽然 new Error 已经有了)
this.sentry.captureException(error)
}
}) })
} }
} }
......
...@@ -8,6 +8,7 @@ class Logger { ...@@ -8,6 +8,7 @@ class Logger {
remote = null remote = null
local = null local = null
fields = [] fields = []
logListener = null
constructor(fields = []) { constructor(fields = []) {
this.fields = fields this.fields = fields
this.init() this.init()
...@@ -17,6 +18,9 @@ class Logger { ...@@ -17,6 +18,9 @@ class Logger {
this.remote = new RemoteLog(user) this.remote = new RemoteLog(user)
this.local = new LocalLog() this.local = new LocalLog()
} }
setLogListener(listener) {
this.logListener = listener
}
debug(info) { debug(info) {
this.write(LogLevel.DEBUG, info) this.write(LogLevel.DEBUG, info)
} }
...@@ -32,6 +36,13 @@ class Logger { ...@@ -32,6 +36,13 @@ class Logger {
write(level, info) { write(level, info) {
this.remote[level](info) this.remote[level](info)
this.local[level](info) this.local[level](info)
if (this.logListener) {
try {
this.logListener(level, info)
} catch (e) {
console.error('Log listener error', e)
}
}
} }
getUserInfo() { getUserInfo() {
const userInfo = storageApi.getUserInfo() const userInfo = storageApi.getUserInfo()
......
/*
* @Descripttion:
* @version: 1.0.0
* @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
*/
class AudioManager {
startOptions = {
duration: 10 * 60 * 1000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
}
__isRecording = false
__counter = 0
events = {}
/**
* AudioManager类的构造函数
* 负责初始化音频管理器实例,包括音频录制的开始、停止和错误处理
* @param {Function} onStart - 音频录制开始时的回调函数
* @param {Function} onStop - 音频录制停止时的回调函数
* @param {Function} onError - 音频录制遇到错误时的回调函数
*/
constructor(onStart, onStop, onError) {
this.on()
this.events = {
onStart,
onStop,
onError
}
}
on() {
this.recorderManager = uni.getRecorderManager()
this.recorderManager.onStart(this.onStart.bind(this))
this.recorderManager.onStop(this.onStop.bind(this))
this.recorderManager.onError(this.onError.bind(this))
}
/**
* 启动录音管理器开始录音
* 此方法用于初始化录音过程,它将配置参数应用到录音管理器,并开始录音
*/
start() {
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音 ')
this.recorderManager.start(this.startOptions)
}
/**
* 异步处理录音开始时的回调函数
*
* 此函数在录音开始时被调用,主要用于执行一些初始化操作和状态更新
* 它首先记录了一条信息到日志,然后执行事件的onStart方法,
* 并且更新内部计数器和录音状态标志
*/
async onStart() {
// 记录录音开始的信息到日志
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 ')
// 等待事件的onStart方法执行完成
await this.events.onStart()
// 内部计数器增加,用于跟踪录音开始的次数
this.__counter++
// 设置录音状态标志为true,表示当前正在录音
this.__isRecording = true
}
/**
* 停止录音功能
*
* 此方法用于停止当前正在进行的录音操作它首先记录了停止录音的信息,
* 然后重置了当前的录音状态,最后通过调用RecorderManager的stop方法来停止录音
*/
stop() {
// 记录停止录音的信息
uni.$logger.local.info('〖录音管理Audio〗 == 停止录音 ')
// 重置录音状态
this.reset()
// 调用RecorderManager的stop方法来停止录音
this.recorderManager.stop()
}
/**
* 异步处理停止录音的回调函数
* @param {Object} res - 停止录音的回调结果对象
*
* 此函数用于在录音停止时执行相应的逻辑它接收一个回调结果对象作为参数,
* 该对象包含有关停止录音的信息它首先记录了一条信息表示录音已停止,
* 然后调用events对象上的onStop方法处理具体的停止录音逻辑
*/
async onStop(res) {
uni.$logger.local.info('〖录音管理Audio〗 == 停止录音回调 ')
await this.events.onStop(res)
}
/**
* 异步处理错误的方法
*
* 当遇到错误时,此方法会被调用,它将等待错误事件处理完成
* 主要作用是将错误传递给注册在this.events上的错误事件处理器
*
* @param {Error} err - 发生的错误对象
*/
async onError(err) {
await this.events.onError(err)
}
/**
* 获取当前是否正在录音的状态
*
* 此方法用于获取实例当前的录音状态它返回一个布尔值,表示是否正在录音
* 该方法没有参数
*
* @returns {boolean} 当前是否正在录音true表示正在录音,false表示未在录音
*/
get isRecording() {
return this.__isRecording
}
/**
* 获取当前计数器的值
*
* 此方法作为属性访问器,用于获取内部私有属性 __counter 的值
* 它没有参数
* 返回值为当前计数器的值
*/
get counter() {
return this.__counter
}
onError(err) {}
/**
* 重置录音状态
*
* 此方法用于将录音管理器的状态重置为初始状态,即不是正在录音,且计数器清零
* 它主要用于准备开始新的录音过程或取消当前录音过程时,清理所有录音相关状态
*/
reset() {
// 记录重置录音状态的日志信息
uni.$logger.local.info('〖录音管理Audio〗 == 重置录音状态 ')
// 设置__isRecording属性为false,表示当前不处于录音状态
this.__isRecording = false
// 将__counter计数器重置为0,此计数器可能用于记录录音过程中的某些度量,如录音时间
this.__counter = 0
}
}
export default AudioManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 14:48:44
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:35:40
* @FilePath: \gl_tape\utils\recordManager\RecordDto.js
*/
export default class RecordDto {
staffUuid = ''
staffName = ''
serviceMerchantId = ''
carModel = ''
endReasonType = 1 //原因 1.异常 0.正常
customerName = ''
phoneNumber = ''
appCode = ''
loginPhone = ''
salesName = ''
salesUuid = ''
receptionStatus = '' //接待结果 1.成交 0.战败
receptionStartTime = ''
receptionEndTime = ''
receptionCustomerPaySourceList = [] //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
merchantId = ''
merchantName = ''
bussinessType = 0 // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType = 1 //1问界 2 比亚迪 3 其他
receptionCustomerMaterialPointList = []
carBrand = ''
carBrandId = ''
oneCarBrand = ''
oneCarBrandId = ''
constructor(options) {
Object.assign(this, options)
}
}
/*
* @Descripttion:
* @version: 1.0.0
* @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
*/
import utils from '../utils'
import helpler from './helpler'
import { FileStatus } from '../common/constants'
class TempRecord {
timer = null
timer_interval = 30 * 1000
record = null
path = ''
newRecord = null
onTempRecordNumberChanged = null
constructor(record, onTempRecordNumberChanged) {
this.newRecord = record
this.recordManager = uni.$dbTempRecord
this.dbManager = uni.$dbManager
this.onTempRecordNumberChanged = onTempRecordNumberChanged
}
getRecords() {
return this.recordManager.getRecords()
}
getRecord(id) {
return this.recordManager.getRecordById(id)
}
async addRecord(record = this.record) {
await this.recordManager.addRecord(record)
this.triggleRecordNumChanged()
}
updateRecord(item, where) {
return this.recordManager.updateRecord(item, where)
}
async removeRecord(id) {
await this.recordManager.removeRecord(id)
this.triggleRecordNumChanged()
}
async __update(key, value) {
if (this.record[key] === value) return
this.record[key] = value
return this.updateRecord({ [key]: value }, { id: this.record.id })
}
async getFilePath() {
if (!this.path) {
this.path = await utils.getFileSaveFolderOnClient()
}
return this.path
}
async save(record = this.record) {
try {
if (!record) throw new Error('记录对象为空')
uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
this.clearLoopTimer()
await this.saveTempFile(record)
const { recordUrlList, tempFilePath, ...__record } = record
const recordLongList = await this.__analysisUrlList(recordUrlList)
const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
if (recordLongList.length > maxUploadNum) {
const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = record || {}
const { name } = userInfo || {}
uni.$logger.error({
msg: `员工: ${name}, 客户: ${customerName}`,
extra: {
'手机号: ': phoneNumber,
'姓名: ': customerName,
'销售: ': salesName,
'车型: ': carModel,
'原因: ': '录音文件过长,数量' + recordLongList.length
}
})
}
__record.recordUrlList = recordLongList.slice(0, maxUploadNum)
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
await this.dbManager.addRecord(__record)
await this.clearLocalRecord(record)
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
}
}
async clearLocalRecord(record = this.record) {
const { id, tempFilePath } = record
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
await this.removeFile(tempFilePath)
await this.removeRecord(id)
record = null
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
}
/**
* 清除已保存的录音文件
* @param {Object} options - 配置参数
* @param {Array} options.recordUrlList - 录音文件列表,默认为当前记录的recordUrlList
*/
clearSavedFiles({ recordUrlList = [] } = this.record) {
// 遍历录音文件列表并删除每个文件
recordUrlList.forEach(item => {
this.removeFile(item.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({
status: FileStatus.Waiting,
file: __path + item.file.replace(/.+\/(\d+\.mp3)/, '$1')
})
} else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
}
return arr
}, [])
return __list
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message)
}
}
/**
* 添加新的接待记录
*/
async add() {
// 创建一个新的记录对象
this.record = this.__createNewRecord()
// 异步添加新创建的记录对象
await this.addRecord(this.record)
// 添加音频资源
this.addAudio()
}
__createNewRecord() {
return {
id: utils.uuid(),
...this.newRecord,
receptionStartTime: this.getTimeNow(),
receptionEndTime: '',
recordUrlList: []
}
}
/**
* 添加音频
* @param {Object} isUpdate - 是否更新音频
* @returns {void}
*/
// 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.addNewAudio()
//更新临时录音文件
await this.updatePath()
//开启轮询保存临时录音文件
this.startSaveAudioLoop()
}
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 })
}
removeOldTempAudio() {
const { tempFilePath } = this.record
uni.$logger.local.info('〖接待记录Record〗 == 删除上一个临时文件 -> ' + tempFilePath)
return this.removeFile(tempFilePath)
}
updatePath() {
const { id, tempFilePath, recordUrlList } = this.record
return this.updateRecord({ tempFilePath, recordUrlList }, { id })
}
/**
* 保存文件
* @param {Object} record - 接待记录对象
* @returns - 返回保存后的文件路径
*/
async saveTempFile(record = this.record) {
const { tempFilePath, recordUrlList } = record
const lastIndex = recordUrlList.length - 1
if (lastIndex < 0 || !tempFilePath) return
const { file } = recordUrlList[lastIndex]
const saveResultPath = await this.saveFilePath(tempFilePath)
if (saveResultPath) {
uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
await this.removeFile(file)
record.recordUrlList[lastIndex].file = saveResultPath
}
return saveResultPath
}
async saveFilePath(tempFilePath) {
uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
if (!tempFilePath) return
const saveResult = await uni.saveFile({
tempFilePath
})
let saveResultPath = saveResult[1]?.savedFilePath
uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
return saveResultPath
}
removeFile(filePath) {
if (!filePath) return
return new Promise(resolve => {
uni.removeSavedFile({
filePath,
complete: resolve
})
})
}
async saveLastAudio() {
const __path = await this.saveTempFile()
__path && this.updateUrlList()
}
updateUrlList() {
const { id, recordUrlList } = this.record
return this.updateRecord({ recordUrlList }, { id })
}
startSaveAudioLoop() {
this.clearLoopTimer()
this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
}
clearLoopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
get currentRecord() {
return this.record
}
setReceptionEndTime() {
return this.__update('receptionEndTime', this.getTimeNow())
}
getTimeNow() {
return utils.convertDateTimeFormat(new Date(), '/')
}
withError() {
return this.__update('endReasonType', 1)
}
async updatePreRecords(items) {
if (items) {
Object.keys(items).forEach(async key => await this.__update(key, items[key]))
}
return this.record
}
async triggleRecordNumChanged() {
if (this.onTempRecordNumberChanged) {
this.onTempRecordNumberChanged()
}
}
}
export default TempRecord
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:34:39
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:36:04
* @FilePath: \gl_tape\utils\recordManager\dbRecord.js
*/
import DBManager from '../DBManager.js'
class DBRecord {
table_columns = [
`id TEXT PRIMARY KEY`,
`staffUuid TEXT`,
`staffName TEXT`,
`serviceMerchantId INTEGER`,
'carModel TEXT',
'endReasonType INTEGER',
'customerName TEXT',
'phoneNumber TEXT',
'appCode TEXT',
'loginPhone TEXT',
'salesName TEXT',
'salesUuid TEXT',
'receptionStatus INTEGER',
'receptionStartTime TEXT',
'receptionEndTime TEXT',
'receptionCustomerPaySourceList TEXT',
'merchantId INTEGER',
'merchantName TEXT',
'bussinessType INTEGER',
'channelType INTEGER',
'receptionCustomerMaterialPointList TEXT',
'recordUrlList TEXT',
'tempFilePath TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER'
]
table_name = 'temp_records'
constructor() {
this.db = new DBManager(this.table_name, this.table_columns)
return this.db
}
}
export default DBRecord
import utils from '../utils'
/**
* 内部方法,用于获取完整的音频文件路径
*
* 此函数调用 `getAudioPathName` 获取文件名,并通过 `getAudioPath` 获取完整路径。
*/
async function getLatestAudioFilePath() {
const pathName = await __getAudioPathName()
return __getAudioPath(pathName)
}
/**
* 异步获取音频文件路径名称
*
* 此函数用于查找特定目录中所有以 'uniapp_temp' 开头的文件,并返回修改时间最晚的文件名。
* 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。
*/
async function __getAudioPathName() {
const path = await utils.getAudioFilePath()
return __getLatestFileName(path, 'uniapp_temp')
}
/**
* 异步获取指定名称的音频文件路径
*
* 此函数用于根据给定的文件名查找其完整路径,并返回修改时间最晚的文件路径。
* 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。
* @param {string} name - 文件名(不包含扩展名)
*/
async function __getAudioPath(name) {
const path = await utils.getAudioFilePath(name + '/recorder')
return __getLatestFilePath(path)
}
/**
* 获取指定目录中修改时间最晚的文件名
*
* @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<string>} - 修改时间最晚的文件名
*/
async function __getLatestFileName(directoryPath, prefix = '') {
const latestFile = await __getLatestFile(directoryPath, prefix)
return latestFile ? latestFile.name : ''
}
/**
* 获取指定目录中修改时间最晚的文件路径
*
* @param {string} directoryPath - 目录路径
* @returns {Promise<string>} - 修改时间最晚的文件路径
*/
async function __getLatestFilePath(directoryPath) {
const latestFile = await __getLatestFile(directoryPath)
return latestFile ? directoryPath + '/' + latestFile.name : ''
}
/**
* 获取指定目录中修改时间最晚的文件
*
* @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<object|null>} - 修改时间最晚的文件对象或 null
*/
async function __getLatestFile(directoryPath, prefix = '') {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
directoryPath,
e => {
const dirR = e.createReader()
dirR.readEntries(
async entries => {
const files = entries.filter(item => (prefix ? item.name.startsWith(prefix) : true))
const filePromises = files.map(item => __getFileMetadata(item))
const results = await Promise.all(filePromises)
const latest = results.reduce((acc, current) => (current.modificationTime > acc.modificationTime ? current : acc), { modificationTime: 0 })
resolve(latest.name ? latest : null)
},
err => reject(err)
)
},
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)
)
})
}
async function sleep(time){
return new Promise(resolve => setTimeout(resolve, time))
}
export default {
getLatestAudioFilePath,
sleep
}
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-06-28 17:12:39
* @LastEditors: limin
* @LastEditTime: 2025-03-11 18:07:04
* @FilePath: \gl_tape\utils\recordManager\index.js
*/
// import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js'
import DBRecord from './dbRecord.js'
// import Record from './Record.js'
import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js'
import helpler from './helpler.js'
// const SingleDBTempRecord = singleton(TempRecord)
module.exports = { AudioManager, DBRecord, RecordDto, TempRecord, helpler }
...@@ -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: 2025-01-06 18:50:33 * @LastEditTime: 2026-01-20 09:23:27
* @FilePath: \gl_tape\utils\recordManager\AudioManager.js * @FilePath: \gl_tape\utils\recordManager\AudioManager.js
*/ */
import StrategyFactory from './strategies'
class AudioManager { class AudioManager {
startOptions = { startOptions = {
duration: 10 * 60 * 1000, //默认10分钟 duration: 10 * 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,表示当前正在录音
...@@ -121,7 +128,10 @@ class AudioManager { ...@@ -121,7 +128,10 @@ class AudioManager {
get counter() { get counter() {
return this.__counter return this.__counter
} }
onError(err) {}
setCounter(val) {
this.__counter = val
}
/** /**
* 重置录音状态 * 重置录音状态
......
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-11-22 08:18:23
* @LastEditors: limin
* @LastEditTime: 2026-01-13 19:02:14
* @FilePath: \gl_tape\utils\recordManager\DBManager.js
*/
import { SQLite } from '../../lib'
/**
* 记录管理器类
* 用于管理记录列表
*/
class DBManager {
db = null
db_name = 'zyzs'
db_version = '1.0'
db_table_name = 'records'
db_description = 'zyzs db'
db_size = 50 * 1024 * 1024
sqlite = null
isTableExists = false
constructor(table_name, table_columns) {
this.table_name = table_name || this.db_table_name
this.table_columns = table_columns
this.db = new SQLite(this.db_name, this.db_version, this.db_description, this.db_size)
}
async init() {
try {
const isOpen = await this.db.isOpen()
if (!isOpen) {
await this.db.init()
}
const isTableExists = await this.db.isTableExists(this.table_name)
uni.$logger.warn(`数据库是否存在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' }
// ])
// }
// }
return true
} catch (error) {
uni.$logger.error(`初始化数据库失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
async openDB() {}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
await this.db.insert(this.table_name, record)
}
/**
* 移除一个ID对应的记录
*
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord(id) {
return this.db.delete(this.table_name, { id })
}
/**
* 根据给定的 ID 获取一条记录
*
* @param {number} id - 要获取的记录的 ID
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*
*/
async getRecordById(id) {
const records = await this.db.select(this.table_name, { id })
return Array.isArray(records) ? records[0] : records // sqlite 返回数组
}
/**
* 根据条件获取记录列表
* @param {Object} where - 查询条件
* @returns {Array} - 记录列表
*/
async getRecordsByWhere(where) {
return this.db.select(this.table_name, where)
}
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
async getRecords() {
return this.db.select(this.table_name)
}
/**
* 设置记录列表
*
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
async setRecords(records) {
return records.forEach(async record => {
this.addRecord(record)
})
}
/**
* 更新记录数组中的记录
* 这个函数用于更新给定记录数组中的特定记录
* 它接受一个参数 record,该参数是要更新的记录对象
*
* @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/
async updateRecord(setData, where) {
const { id, ...record } = setData
if (!where) {
where = { id }
}
return this.db.update(this.table_name, record, where)
}
async isOpen() {
return this.db.isOpen()
}
async isTableExists() {
return this.db.isTableExists(this.table_name)
}
/**
* 清除所有记录
*
* @returns {void} - 此函数不返回任何值
*/
async clearRecords() {
this.db.delete(this.table_name)
}
async drop() {
this.db.drop(this.table_name)
}
}
export default DBManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 20:48:08
* @LastEditors: limin
* @LastEditTime: 2026-01-30 19:10:32
* @FilePath: \gl_tape\utils\recordManager\FileUploadManager.js
*/
import { getUploadManager } from '@/utils/uploadManager'
import { FileStatus } from '@/utils/common'
// import { decryptAES } from '@/lib/aes.js'
/**
* 文件上传管理器
* @description: 基于新的 UploadManager,支持两种上传策略(UniAppStrategy、WebViewStrategy)
* @feature: oss-upload-refactor
* @purpose: 为 UploadService 提供新的上传能力,同时保持接口兼容
*
* 特点:
* 1. 基于新的 UploadManager,支持两种上传策略
* 2. 适配 UploadService 的接口,无缝集成
* 3. 自动处理 OSS Token 获取和解密
* 4. 模拟 WebView 回调格式,兼容现有逻辑
*
* 使用示例:
* ```javascript
* import FileUploadManager from '@/utils/recordManager/FileUploadManager.js'
*
* const fileUploadManager = FileUploadManager.getInstance()
*
* // 初始化(在 HomeFrame 中调用)
* await fileUploadManager.init({
* webviewRef: this.$refs.uploaderWebview,
* vueContext: this
* })
*
* // 上传文件
* await fileUploadManager.uploadRecord(record, (result) => {
* // 处理上传结果
* })
* ```
*/
class FileUploadManager {
static instance = null
constructor() {
/**
* UploadManager 实例
* @type {UploadManager}
*/
this.uploadManager = null
/**
* 初始化完成的 Promise
* @type {Promise<void>}
* @private
*/
this._initPromise = null
/**
* 初始化完成的 resolve 函数
* @type {Function|null}
* @private
*/
this._initResolve = null
// 创建初始化 Promise
this._initPromise = new Promise((resolve) => {
this._initResolve = resolve
})
}
/**
* 获取单例实例
* @returns {FileUploadManager}
*/
static getInstance() {
if (!FileUploadManager.instance) {
FileUploadManager.instance = new FileUploadManager()
}
return FileUploadManager.instance
}
/**
* 初始化上传管理器
*
* @param {Object} options - 初始化选项
* @param {Object} [options.webviewRef] - WebView 组件引用(可选)
* @param {Object} [options.vueContext] - Vue 组件实例(可选)
*/
async init(options = {}) {
try {
// 防止重复初始化
if (this.uploadManager) {
uni.$logger.local.debug('[FileUploadManager] 已初始化,跳过重复初始化')
// 如果传入了新的 WebView 配置,更新配置
if (options.webviewRef && options.vueContext) {
this.uploadManager.setWebViewConfig(options.webviewRef, options.vueContext)
uni.$logger.local.info('[FileUploadManager] WebView 配置已更新')
}
return
}
// 获取 UploadManager 实例,传入 WebView 配置
// UploadManager 会自动初始化 WebView 策略
this.uploadManager = getUploadManager({
webview: options.webviewRef && options.vueContext ? {
webviewRef: options.webviewRef,
vueContext: options.vueContext
} : null
})
uni.$logger.local.info('[FileUploadManager] 初始化成功')
// 解析初始化 Promise
if (this._initResolve) {
this._initResolve()
this._initResolve = null
}
} catch (error) {
uni.$logger.local.error(`[FileUploadManager] 初始化失败: ${error.message}`)
throw error
}
}
/**
* 等待初始化完成
*
* @returns {Promise<void>}
*/
async waitForInit() {
if (this.uploadManager) {
return
}
return this._initPromise
}
/**
* 处理来自 WebView 的消息
*
* @param {Object} event - WebView message 事件
*/
handleWebViewMessage(event) {
if (!event?.detail?.data?.[0]) {
return
}
// 直接转发给 UploadManager 处理
// UploadManager 会自动处理 webview_ready 信号和上传回调
if (this.uploadManager) {
this.uploadManager.handleWebViewMessage(event)
} else {
uni.$logger.local.warn('[FileUploadManager] uploadManager 未初始化,无法处理 WebView 消息')
}
}
/**
* 获取最后一次上传使用的策略
*
* 注意:这是最后一次上传实际使用的策略
* 系统会根据文件大小和就绪状态自动选择策略
*
* @returns {string} 策略名称
*/
getCurrentStrategy() {
if (!this.uploadManager) {
return 'unknown'
}
return this.uploadManager.getCurrentStrategyName()
}
/**
* 上传文件记录
*
* 适配 UploadService 的接口,处理上传并返回 WebView 格式的结果
*
* @param {Object} record - 文件记录
* @param {string} record.recordId - 记录 ID
* @param {string} record.fileName - 文件名
* @param {string} record.filePath - 文件路径
* @param {number} record.status - 文件状态
* @param {Function} callback - 上传完成回调
* @returns {Promise<void>}
*/
async uploadRecord(record, callback) {
try {
uni.$logger.local.info(`[FileUploadManager] 开始上传文件: ${record.fileName}`)
// 处理无文件或文件不存在的情况
if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) {
uni.$logger.local.info('[FileUploadManager] 文件不存在,直接返回')
// 构造结果,模拟 WebView 回调格式
const result = {
detail: {
data: [{
code: 0,
message: 'no file',
recordId: record.recordId,
fileName: record.fileName,
filePath: record.filePath,
status: record.status
}]
}
}
callback && callback(result)
return
}
// 获取 OSS Token
const token = await uni.$api.commonApi.getToken({})
// const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await uni.$api.commonApi.getToken({})
let { lsaccessKeySecret, securityToken, lsaccessKeyId, bucketName='', region='' } = token || {}
// 解密配置
// bucketName = await this._tryDecrypt(bucketName, 'Bucket')
// region = await this._tryDecrypt(region, 'Region')
// lsaccessKeySecret = await this._tryDecrypt(lsaccessKeySecret, 'AccessKeySecret')
// lsaccessKeyId = await this._tryDecrypt(lsaccessKeyId, 'AccessKeyId')
// 获取文件大小
const filePath = record.filePath + record.fileName
let fileSize = 0
try {
const fileInfo = await this._getFileInfo(filePath)
fileSize = fileInfo.size
uni.$logger.local.info(`[FileUploadManager] 文件大小: ${fileSize} bytes`)
} catch (error) {
uni.$logger.local.warn(`[FileUploadManager] 无法获取文件大小: ${error.message},使用默认值 0`)
}
// 构造文件对象
const file = {
path: filePath,
name: record.fileName,
size: fileSize
}
// 构造 OSS 配置
const ossConfig = {
accessKeyId: lsaccessKeyId,
accessKeySecret: lsaccessKeySecret,
stsToken: securityToken,
bucket: bucketName,
region: region
}
// 使用 UploadManager 上传
// UploadManager 会根据策略优先级自动选择已就绪的策略
const url = await this.uploadManager.upload(file, {
ossConfig,
onProgress: (percent) => {
// uni.$logger.local.debug(`[FileUploadManager] 上传进度: ${percent}%`)
},
onSuccess: (url, metadata) => {
// 记录实际使用的策略
// const usedStrategy = this.uploadManager.getCurrentStrategyName()
// uni.$logger.local.info(`[FileUploadManager] 上传成功: ${url}, 使用策略: ${usedStrategy}`)
},
onFailure: (error) => {
uni.$logger.local.error(`[FileUploadManager] 上传失败: ${error.message}`)
}
})
// 构造上传结果,模拟 WebView 回调格式
const uploadResult = {
detail: {
data: [{
code: 0,
message: 'success',
recordId: record.recordId,
fileName: record.fileName,
filePath: record.filePath,
data: {
oss: {
res: {
requestUrls: [url]
}
}
}
}]
}
}
// 调用回调
callback && callback(uploadResult)
} catch (error) {
uni.$logger.local.error(`[FileUploadManager] 上传失败: ${error.message}`)
// 构造错误结果
const errorResult = {
detail: {
data: [{
code: -1,
message: error.message,
recordId: record.recordId,
fileName: record.fileName,
filePath: record.filePath
}]
}
}
callback && callback(errorResult)
return
}
}
/**
* 解密字符串
* @private
*/
async _tryDecrypt(str, label) {
if (str && (str.includes('=') || str.length > 50)) {
let decrypted =str //await decryptAES(str)
if (decrypted) {
if (label == 'Region' && decrypted.includes('.')) {
decrypted = decrypted.split('.')[0]
}
}
return decrypted
}
return str
}
/**
* 获取文件信息
* @private
* @param {string} filePath - 文件路径
* @returns {Promise<Object>} 文件信息 { size, ... }
*/
async _getFileInfo(filePath) {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
plus.io.getFileInfo({
filePath: filePath,
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(new Error(err.errMsg || 'Failed to get file info'))
}
})
// #endif
// #ifdef H5
// H5 环境无法直接获取文件大小,返回默认值
resolve({ size: 0 })
// #endif
})
}
/**
* 取消正在进行的上传
*/
cancel() {
if (this.uploadManager) {
this.uploadManager.cancel()
uni.$logger.local.info('[FileUploadManager] 取消上传')
}
}
/**
* 销毁实例,清理资源
*/
destroy() {
// 清理引用
// this.uploadManager = null
// uni.$logger.local.info('[FileUploadManager] 实例已销毁')
}
/**
* 获取所有支持的策略
*
* @returns {Array<string>} 策略名称数组
*/
getSupportedStrategies() {
if (!this.uploadManager) {
return []
}
return this.uploadManager.getSupportedStrategies()
}
}
// 导出单例
export default FileUploadManager.getInstance()
/*
* @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' // 录音中
}
// 默认配置
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: []
}
// 缓存 Java 类
this._JavaFile = null
this._JavaMediaRecorder = null
// 绑定上下文,防止调用时 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) {
uni.$logger.local.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
}
/**
* 延迟加载 Java 类
*/
_loadJavaClasses() {
// #ifdef APP-PLUS
if (!this._JavaFile) {
this._JavaFile = plus.android.importClass('java.io.File')
}
if (!this._JavaMediaRecorder) {
this._JavaMediaRecorder = plus.android.importClass('android.media.MediaRecorder')
}
// #endif
}
/**
* 确保保存目录存在 (带缓存)
* @param {string} dirPath - 相对路径,如 _doc/uniapp_save/
* @returns {Promise<string>} - 绝对路径 (Java File 使用)
*/
async _ensureSaveDir(dirPath) {
if (this._cachedDir?.path === dirPath && this._cachedDir.absPath) {
return this._cachedDir.absPath
}
const absPath = await PathUtils.ensureDir(dirPath)
this._cachedDir = { path: dirPath, absPath: absPath }
return absPath
}
/**
* 开始录音
* @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) {
uni.$logger.local.warn('[NativeRecorder] Already recording, stopping first...')
await this.stop()
}
// 设置为准备状态,加锁
// 注意:虽然没有显式的 PREPARING 状态,但 RECORDING 状态配合下面的检查点逻辑
// 已经实现了"准备中"的并发控制
this._state = RecorderState.RECORDING
try {
// #ifdef APP-PLUS
// 1. 导入必要的 Android 类
this._loadJavaClasses()
const MediaRecorder = this._JavaMediaRecorder
const File = this._JavaFile
// 2. 准备路径
// 使用 TempRecord 统一管理的路径逻辑,避免多处硬编码
// 这里的 options.path 如果未提供,使用 DEFAULT_CONFIG.basePath
const basePath = options.path || DEFAULT_CONFIG.basePath
// _ensureSaveDir 负责将相对路径转换为绝对路径
// 【关键点】这里是异步操作,期间可能会被 stop() 中断
const saveDirAbsPath = await this._ensureSaveDir(basePath)
// 【检查点】如果异步期间状态变回 '' (IDLE)(说明被 stop 打断),则终止
if (this._state !== RecorderState.RECORDING) {
uni.$logger.local.warn('[NativeRecorder] Start cancelled during preparation')
return
}
// 使用 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. 更新状态
// 此时状态应该已经是 RECORDING,无需再次设置,但为了保险确认一下
if (this._state !== RecorderState.RECORDING) return
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) {
// 已经是空闲,无需操作
return
}
// 无论 MediaRecorder 是否初始化,stop 的意图都是结束录音
// 如果 _mediaRecorder 为空,说明还在准备阶段,直接清理即可
if (!this._mediaRecorder) {
uni.$logger.local.warn('[NativeRecorder] Stopping while preparing (no mediaRecorder instance)')
this._cleanup()
return
}
try {
// #ifdef APP-PLUS
// 停止录音
// 注意: 如果录音时间极短(小于1s),stop() 可能会抛出 RuntimeException
try {
// 在 stop 之前先重置错误监听器,防止 stop 抛出的异常被误判
// 但 Java 侧异常需要捕获
this._mediaRecorder.stop()
} catch (stopErr) {
// 常见错误:RuntimeException: stop failed.
// 原因:录音时间太短(通常小于 1 秒)或尚未开始
uni.$logger.local.warn('[NativeRecorder] Stop exception (likely too short):', stopErr)
// 这种情况下,文件可能无效或未生成,需要检查文件是否存在
}
uni.$logger.local.info(`[NativeRecorder] Stopped`)
// 检查文件是否存在且大小 > 0
this._loadJavaClasses()
const File = this._JavaFile
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 {
uni.$logger.local.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) {
uni.$logger.local.error(`[NativeRecorder] ${context}:`+ error.message)
// 清理资源,直接重置为 IDLE
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
}
/**
* 是否正在录音
*/
isRecording() {
return this._state === RecorderState.RECORDING
}
/**
* 显式释放资源 (供页面销毁时调用)
*/
release() {
this.stop()
this._cleanup()
}
}
// 导出单例
export default new NativeRecorder()
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-21 10:52:09
*/
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: ' + audio?.fileName)
// 创建一个新的记录对象
const recordUrlList = audio && audio.fileName ? [{ file: audio.fileName }] : []
// 调用基类通用流程
await super.add(recordUrlList)
}
}
export default NativeSave
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-16 14:48:27
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:47:12
* @FilePath: \gl_tape\utils\recordManager\PathUtils.js
*/
/**
* 路径处理工具类
*/
class PathUtils {
static _basePath = null
// 默认保存文件夹名称
static SAVE_DIR_NAME = 'uniapp_save'
// 默认文件保存路径 (相对于 _doc/)
static DEFAULT_SAVE_PATH = `_doc/${this.SAVE_DIR_NAME}/`
static CACHED_ROOT_PATH = null
// 本地缓存键名
static ROOT_PATH_CACHE_KEY = 'sqlite_root_path_cache'
/**
* 路径拼接工具
* @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() {
// 1. 优先使用内存缓存,性能最高
if (this.CACHED_ROOT_PATH) {
uni.$logger?.local?.info(`[PathUtils] 命中内存缓存,根路径: ${this.CACHED_ROOT_PATH}`);
return Promise.resolve(this.CACHED_ROOT_PATH);
}
// 2. 尝试读取持久化缓存
const storageCache = uni.getStorageSync(this.ROOT_PATH_CACHE_KEY);
if (storageCache) {
uni.$logger?.local?.info(`[PathUtils] 命中本地缓存,根路径: ${storageCache}`);
// 同步到内存缓存
this.CACHED_ROOT_PATH = storageCache;
return Promise.resolve(this.CACHED_ROOT_PATH);
}
// 3. 无缓存,请求原生文件系统API
return new Promise((resolve, reject) => {
if (!plus) {
reject(new Error('plus runtime 未初始化'));
return;
}
plus.io.requestFileSystem(
plus.io.PRIVATE_DOC,
(fs) => {
const fullPath = fs.root.fullPath;
uni.$logger?.local?.info(`[PathUtils] 请求原生API获取根路径: ${fullPath}`);
// 写入两级缓存
this.CACHED_ROOT_PATH = fullPath;
uni.setStorageSync(this.ROOT_PATH_CACHE_KEY, fullPath);
resolve(fullPath);
},
(error) => {
reject(new Error(`[PathUtils] 获取文件系统失败: ${JSON.stringify(error)}`));
}
);
});
}
/**
* 获取客户端文件保存基础路径
*/
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
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-15 19:20:33
*/
import utils from '../utils'
import helpler from './helpler'
import PathUtils from './PathUtils'
import { FileStatus } from '../common/constants'
import UploadService from './UploadService.js'
import TempRecord from './TempRecord'
class PollingSave extends TempRecord {
constructor(record, onTempRecordNumberChanged, attributesProvider) {
super(record, onTempRecordNumberChanged, attributesProvider)
}
/**
* 添加新的接待记录
* - 创建内存中的记录对象
* - 同步写入临时记录数据库
* - 启动音频处理流程
* @returns {Promise<void>}
*/
async add() {
// 调用基类通用流程(创建记录+入库)
await super.add([])
// 添加音频资源
await this.addAudio()
}
/**
* 添加音频
* @param {Object} isUpdate - 是否更新音频
* @returns {void}
*/
async addAudio() {
this.clearLoopTimer()
// 0. 记录旧路径到实例属性,供底层查找时排除
this._excludePath = this.record?.tempFilePath || ''
// 1. 处理旧录音,并获取清理任务 (只更新内存,不更新数据库)
let cleanupTask
try {
cleanupTask = await this.processPreviousAudio()
if (this.record) this.record.tempFilePath = ''
// 2. 获取新录音并统一提交数据库更新
await this.addNewAudioAndUpdate()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == addAudio 流程异常: ' + e.message)
} finally {
// 4. 启动轮询
this.startSaveAudioLoop()
// 5. 执行错峰清理
if (cleanupTask) await cleanupTask()
this._excludePath = ''
}
}
/**
* 处理上一个临时文件
* 1. 持久化保存上一个临时文件并更新本地路径到数据库
* 2. 返回一个执行删除操作的函数(闭包),无旧文件时返回 null
*/
async processPreviousAudio() {
try {
// uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
// 直接调用原子保存方法,只更新内存,不涉及数据库操作
await this.saveTempFile()
const oldPath = this.record?.tempFilePath
// 返回清理闭包,封装删除逻辑
return oldPath ? () => this.removeOldTempAudio(oldPath) : null
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 处理上一个录音失败' + e)
return null
}
}
/**
* 添加新录音并同步更新数据库
* - 在内存中成功添加临时路径后,调用 `updatePath` 持久化到临时表
* @returns {Promise<void>}
*/
async addNewAudioAndUpdate() {
await this.addNewAudio()
// 只要有记录对象,就强制更新一次数据库,确保:
// 1. 如果有新文件,更新 tempFilePath 和 recordUrlList
// 2. 如果没新文件(添加失败),也要把可能存在的旧文件归档变更持久化
if (this.record) {
await this.updatePath()
// uni.$logger.local.info('〖接待记录Record〗 == 同步数据库路径成功 id: ' + this.record.id)
}
}
/**
* 读取最新的录音临时文件并尝试保存
* - 支持重试机制
* - 成功后更新内存状态与录音列表
* @returns {Promise<void>}
*/
async addNewAudio() {
try {
// 直接使用实例属性 _excludePath
const lastAudio = await this.getLastAudioWithRetry(10, 100)
if (!lastAudio) {
uni.$logger.local.warn('〖接待记录Record〗 == 未找到录音文件,跳过添加')
return
}
// uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
const savedPath = await this.saveFilePath(lastAudio)
if (savedPath && this.record) {
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)}`)
}
}
/**
* 停止保存轮询并清理定时器句柄
* @returns {void}
*/
clearLoopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
/**
* 重试读取最近一次录音临时文件路径
* @param {number} [maxRetries=10] - 最大重试次数 (降低到10次)
* @param {number} [baseDelay=100] - 基础等待毫秒数 (指数退避)
* @returns {Promise<string>} 找到则返回路径,否则返回空字符串
*/
async getLastAudioWithRetry(maxRetries = 10, baseDelay = 100) {
let lastAudio = ''
// 使用实例属性作为排除路径,默认为空
const excludePath = this._excludePath || ''
for (let i = 0; i < maxRetries; i++) {
// 如果实例已销毁,立即中断重试
if (this._isDestroyed) {
uni.$logger.local.warn('〖接待记录Record〗 == 实例已销毁,终止寻找录音文件')
return ''
}
// 传入 excludePath 让底层去过滤
const currentAudio = await helpler.getLatestAudioFilePath(excludePath)
// 只要找到文件,就一定是有效的(excludePath 已经在底层被排除)
if (currentAudio && currentAudio !== excludePath) {
lastAudio = currentAudio
break
}
// if (i % 3 === 0) {
// uni.$logger.local.info(`〖接待记录Record〗 == 正在寻找新录音文件 (排除: ${excludePath})...`)
// }
// 指数退避:每次等待时间增加,避免频繁轮询
// 100ms, 150ms, 225ms... 上限 500ms
const delay = Math.min(baseDelay * Math.pow(1.5, i), 500)
await helpler.sleep(delay)
}
if (!lastAudio) {
uni.$logger.local.warn(`〖接待记录Record〗 == 重试 ${maxRetries} 次后仍未找到新录音文件`)
}
return lastAudio
}
/**
* 删除指定路径的临时录音文件
* @param {string} path - 要删除的文件路径
* @returns {Promise<void>}
*/
async removeOldTempAudio(path) {
if (!path) return
// uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件 -> ' + path)
await this.removeFile(path)
}
/**
* 将当前内存中的临时路径与录音列表同步到数据库临时表
* @returns {Promise<void>}
*/
updatePath() {
const { id, tempFilePath, recordUrlList } = this.record
return this.updateRecord({ tempFilePath, recordUrlList }, { id })
}
/**
* 保存文件
* @param {Object} record - 接待记录对象
* @returns - 返回保存后的文件路径
*/
async saveTempFile(record = this.record) {
if (!record) {
uni.$logger.local.warn('〖接待记录Record〗 == saveTempFile 记录为空,跳过')
return
}
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]
const saveResultPath = await this.saveFilePath(tempFilePath)
if (saveResultPath) {
// uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
await this.removeFile(file)
record.recordUrlList[lastIndex].file = saveResultPath
}
return saveResultPath
}
/**
* 将临时文件保存到持久化目录(兼容不同返回结构)
* @param {string} tempFilePath - 临时文件路径
* @returns {Promise<string|undefined>} 保存成功返回持久化路径,失败返回 undefined
*/
async saveFilePath(tempFilePath) {
// uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
if (!tempFilePath) return
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
}
}
/**
* 在轮询中保存最后一个临时录音并更新列表
* @returns {Promise<void>}
*/
async saveLastAudio() {
if (this._isDestroyed) return // 双重保险
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() {
if (this.timer) {
uni.$logger.local.info('〖接待记录Record〗 == 轮询已启动,跳过')
return
}
if (this._isDestroyed) {
uni.$logger.local.warn('〖接待记录Record〗 == 组件已销毁,忽略 startSaveAudioLoop')
return
}
uni.$logger.local.info('〖接待记录Record〗 == 启动轮询 ' + this.timer_interval + 'ms')
this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
}
async beforeSave(record) {
this.clearLoopTimer()
await this.saveTempFile(record)
}
}
export default PollingSave
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 14:30:10
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:47:06
* @FilePath: \gl_tape\utils\recordManager\RecordCacheManager.js
*/
/**
* 缓存配置表
* 用于定义哪些字段需要走 LocalStorage 暂存策略
*/
const CACHE_CONFIG = {
MATERIAL_POINTS: {
keyPrefix: 'MATERIAL_POINTS_', // Storage Key 前缀
targetField: 'receptionCustomerMaterialPointList' // 对应的 Record 字段名
}
}
/**
* 记录缓存管理器
* 统一管理大字段的暂存、合并与清理
*/
const RecordCacheManager = {
/**
* 暂存数据
* @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG)
* @param {any} data - 数据
*/
set(recordId, type, data) {
if (!recordId || !CACHE_CONFIG[type]) return
try {
const config = CACHE_CONFIG[type]
uni.setStorageSync(config.keyPrefix + recordId, data)
} catch (e) {
uni.$logger.local.error(`RecordCacheManager: Set ${type} failed: ${e.message}`)
}
},
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {Object} record - 记录对象 (仅用于获取ID)
* @returns {Object} 从缓存恢复的数据对象
*/
consumeAll(record) {
if (!record || !record.id) return {}
const restoredData = {}
Object.values(CACHE_CONFIG).forEach(config => {
try {
const key = config.keyPrefix + record.id
const data = uni.getStorageSync(key)
if (data) {
restoredData[config.targetField] = data
uni.removeStorageSync(key) // 消费即焚
}
} catch (e) {
uni.$logger.local.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${e.message}`)
}
})
return restoredData
},
/**
* 清理指定记录的所有缓存
* @param {string} recordId
*/
clearAll(recordId) {
if (!recordId) return
Object.values(CACHE_CONFIG).forEach(config => {
try {
uni.removeStorageSync(config.keyPrefix + recordId)
} catch (e) {}
})
}
}
export default RecordCacheManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 20:57:12
* @LastEditors: limin
* @LastEditTime: 2026-01-30 19:34:30
* @FilePath: \gl_tape\utils\recordManager\RecordSaveService.js
*/
import Queue from '@/utils/Queue.js'
import { deepClone, serializeIfObject } from '@/utils/utils.js'
import { FileStatus } from '@/utils/common'
import dayjs from 'dayjs'
import store from '@/store'
import FileUploadManager from './FileUploadManager.js'
const UPLOAD_INTERVAL = 0.5 * 60 * 1000
/**
* 接待记录保存服务
*
* 职责:
* 1. 管理接待记录的上传队列
* 2. 处理文件上传结果
* 3. 保存接待记录到服务器
* 4. 清理本地文件和记录
*
* 特点:
* - 使用 FileUploadManager 处理文件上传
* - 自动轮询上传队列
* - 支持网络恢复后自动重试
* - 黑名单机制防止死循环
*/
class RecordSaveService {
static instance = null
constructor() {
this.interval = UPLOAD_INTERVAL
this._pumpTimer = null
this._pumpRunning = false
this.snapshot = null
this._currentKey = null
this.updateResolve = null
this._taskStartTime = null
this._networkHandler = null
this._blackList = new Set()
// Bind methods to ensure 'this' context
this.stopPolling = this.stopPolling.bind(this)
this.startPolling = this.startPolling.bind(this)
this.setInterval = this.setInterval.bind(this)
}
static getInstance() {
if (!RecordSaveService.instance) {
RecordSaveService.instance = new RecordSaveService()
}
return RecordSaveService.instance
}
async init() {
try {
// 监听网络状态变化
this._networkHandler = res => {
if (res.isConnected) {
uni.$logger.local.info(`【接待记录保存服务】 == 网络已恢复,唤醒上传任务`)
this.startPolling()
}
}
uni.onNetworkStatusChange(this._networkHandler)
uni.$logger.local.info('【接待记录保存服务】初始化成功')
} catch (error) {
this.reportError(`【接待记录保存服务】初始化失败 error:${error.message}`, error.message)
}
}
/**
* 处理文件上传结果
* @param {Object} data - 上传结果数据
*/
async handleUploadResult(data) {
uni.$logger.local.info(`【接待记录保存服务】 == 文件上传回调!`)
this.save(data)
}
/**
* 生成任务唯一标识 Key
*/
_getTaskKey(recordId, fileName) {
return `${recordId || ''}_${fileName || ''}`
}
/**
* 保存上传结果
*/
async save(data) {
try {
const fileInfo = this.parseFileInfo(data)
if (fileInfo?.error) {
// uni.$logger.local.error(`【接待记录保存服务】 == 上传文件信息解析异常: ${fileInfo.error}`)
// this.reportError(
// `【接待记录保存服务】 == 上传文件信息解析异常: ${fileInfo.error}`,
// fileInfo.data,
// fileInfo.recordId,
// fileInfo.filePath
// )
throw new Error(`上传文件信息解析异常: ${fileInfo.error}`)
}
uni.$logger.local.info(`【接待记录保存服务】 == 解析结果: recordId=${fileInfo.recordId}, status=${fileInfo.status}`)
const callbackKey = this._getTaskKey(fileInfo.recordId, fileInfo.fileName)
const isCurrentTask = this._currentKey && callbackKey === this._currentKey
if (!isCurrentTask) {
uni.$logger.local.warn(`【接待记录保存服务】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态`)
}
const record = await uni.$dbRecord.getRecordById(fileInfo.recordId)
if (!record) {
throw new Error(`未找到记录: ${fileInfo.recordId}`)
}
const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord)
if (isCurrentTask) {
uni.$logger.local.info('【接待记录保存服务】 == 本次任务完成,开启下一次上传任务!')
this.endTask()
}
} catch (error) {
if (this._currentKey) {
this._addToBlackList(this._currentKey.split('_')[0], `Save failed: ${error.message}`)
}
this.reportError(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask()
}
}
/**
* 解析文件信息
*/
parseFileInfo(data) {
// 1. 尝试从回调结构中提取 payload
const payload = data?.detail?.data?.[0]
// CASE 1: 上传回调
if (payload) {
const { data: d, ...o } = payload
const input = serializeIfObject(o)
uni.$logger.local.warn(`【接待记录保存服务】 == 开始文件信息解析-> ${input}`)
return this._parseUploadedFile(data)
}
// CASE 2: 直接调用 (data 是 record 对象)
if (data && (data.status === FileStatus.NoFile || data.status === FileStatus.NotExist)) {
return this._parseNoFileStatus(data)
}
return { error: '【接待记录保存服务】 == 未知文件状态', data, filePath: (data.filePath || '') + (data.fileName || '') }
}
_parseNoFileStatus(data) {
const { recordId, fileName, filePath, status } = data
const clientPath = (filePath || '') + (fileName || '')
if (!recordId) {
return { error: '【接待记录保存服务】 == 缺少记录ID', data, filePath: clientPath }
}
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 || '')
if (!payload || typeof payload !== 'object') {
return { error: '回调数据格式错误', data, recordId: data?.recordId, filePath: clientPath }
}
if (!recordId) {
return { error: '文件上传回调,缺少recordId', data, filePath: clientPath }
}
const { code, message, data: fileData } = payload
const serverUrl = fileData?.oss?.res?.requestUrls?.[0]
if (code !== 0 || !serverUrl) {
return { error: `解析异常: code->${code} message->${message}`, data, recordId, filePath: clientPath }
}
return {
recordId,
fileName,
clientPath,
serverPath: String(serverUrl).split('?')[0],
status: FileStatus.Uploaded
}
}
_reportParseError(msg, data, recordId, filePath) {
const fullMsg = `【接待记录保存服务】 == ${msg}`
uni.$logger.local.error(fullMsg)
this.reportError(fullMsg, data, recordId, filePath)
}
_changeFilePathToServer(record, fileInfo) {
const _record = deepClone(record)
uni.$logger.local.info(`【接待记录保存服务】 == 开始更新文件路径, recordId: ${_record.id}`)
if (fileInfo.status === FileStatus.NoFile) {
_record.status = FileStatus.NoFile
_record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime
_record.recordUrlList = []
uni.$logger.local.info(`【接待记录保存服务】 == 记录被标记为无文件状态`)
return _record
}
_record.recordUrlList = this.urlListFilter(_record.recordUrlList)
const targetFile = _record.recordUrlList.find(item => this._isTargetFile(item, fileInfo))
if (targetFile) {
this._updateFileStatus(targetFile, fileInfo)
} else {
uni.$logger.local.warn(`【接待记录保存服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`)
}
return _record
}
_isTargetFile(item, fileInfo) {
if (!this.isLegalFile(fileInfo.fileName)) return !this.isLegalFile(item.file)
return item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName)
}
_updateFileStatus(targetFile, fileInfo) {
targetFile.status = fileInfo.status
if (fileInfo.status === FileStatus.Uploaded) {
targetFile.file = fileInfo.serverPath
targetFile.filePathOnClient = fileInfo.clientPath
}
uni.$logger.local.info(`【接待记录保存服务】 == 文件状态已更新: ${fileInfo.fileName} -> ${fileInfo.status}`)
}
async reportError(message, res, recordId, filePath) {
try {
const record = recordId ? await uni.$dbRecord.getRecordById(recordId) : {}
const userInfo = uni.$storage.get('userInfo') || {}
const { customerName, customerPhone, carType } = record || {}
const { user: { userName } = {} } = userInfo
const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
uni.$logger.error({
msg: `${now}-${message},员工: ${userName}, 客户: ${customerName}`,
extra: {
'员工: ': userName,
'客户姓名: ': customerName,
'客户手机号: ': customerPhone,
'车型: ': carType,
'原因: ': serializeIfObject(res),
'文件路径: ': filePath
}
})
} catch (error) {
uni.$logger.error(`【接待记录保存服务】 == 报告错误时发生异常: ${error.message}`)
}
}
async enQueue() {
try {
const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot)
uni.$logger.local.warn(`【接待记录保存服务】 == 创建快照成功! ${JSON.stringify(this.snapshot.items)} 快照数: ${this.snapshot.size} `)
} catch (error) {
this.reportError(`【接待记录保存服务】 == 获取快照失败 error:${error.message}`, error.message)
if (!this.snapshot) {
this.snapshot = new Queue([])
}
}
}
async getRecordsSnapshotFlatten() {
await uni.$dbReady
let _records = await uni.$dbRecord.getCompletedRecords()
return await this.flattenData(_records || [])
}
/**
* 上传文件记录
* 使用 FileUploadManager 处理文件上传
*/
async uploadRecord(record) {
uni.$logger.local.info(`【接待记录保存服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`)
try {
// 使用 FileUploadManager 上传文件
await FileUploadManager.uploadRecord(record, (result) => {
// 处理上传结果
this.handleUploadResult(result)
})
} catch (error) {
uni.$logger.local.error(`【接待记录保存服务】 == 上传失败: ${error.message}`)
// 构造错误结果
const errorResult = {
detail: {
data: [{
code: -1,
message: error.message,
recordId: record.recordId,
fileName: record.fileName,
filePath: record.filePath
}]
}
}
this.handleUploadResult(errorResult)
}
}
_removeFileOnClient(filePathOnClient) {
return new Promise((resolve, reject) => {
if (!filePathOnClient) {
uni.$logger.local.info(`【接待记录保存服务】 == 要删除的文件为空`)
resolve(true)
return
}
uni.removeSavedFile({
filePath: filePathOnClient,
complete: function (res) {
uni.$logger.local.info(`删除 ${filePathOnClient}-> ${res.errMsg}`)
resolve(res)
}
})
})
}
async _saveOrUpdate(data) {
uni.$logger.local.info(`【接待记录保存服务】 == 开始保存或更新接待记录!!`)
const { status, tempFilePath, receptionStatus, ...record } = data
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 {
await this._handleIncompleteRecord(record)
}
}
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.warn(`【接待记录保存服务】 == 本条接待所有文件已经上传和处理完毕!!`)
// uni.$logger.local.info(`【接待记录保存服务】 == 已上传的文件: ${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(`【接待记录保存服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.warn(`【接待记录保存服务】 == 服务器返回结果: ${JSON.stringify(res)}`)
// 4. 清理本地数据
if (res) {
uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`)
await this._removeRecordFiles(localPaths)
await this._removeRecordById(record.id)
}
}
/**
* 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间
* @param {Array} recordUrlList - 包含文件URL的数组
* @param {string} receptionStartTime - 接待开始时间
* @returns {Promise<string>} - 一个 Promise,成功时解析为接待结束时间
*/
async _requestReceptionEndTime(recordUrlList, receptionStartTime) {
if (!recordUrlList || recordUrlList.length === 0) return receptionStartTime
// 记录日志,显示正在向服务器请求结束接待时间,包括文件URL列表和接待开始时间
uni.$logger.local.info(`【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`)
// 调用 uni.$api.commonApi.searchRecordingEndTime 方法,向服务器发送请求,获取接待结束时间
const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') })
// 记录日志,显示服务器返回的接待结束时间
uni.$logger.local.info(`【上传服务】 == 服务器返回结束接待时间: endTime ->${endTime}`)
// 返回接待结束时间,将日期格式中的连字符替换为斜杠,以保持一致性
return endTime.replace(/\-/g, '/')
}
async _handleIncompleteRecord(record) {
uni.$logger.local.info(`【接待记录保存服务】 == 记录中有未上传文件,开始更新记录!!`)
await uni.$dbRecord.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
}
async _removeRecordById(recordId) {
try {
await uni.$dbRecord.removeRecord(recordId)
uni.$logger.local.info(`【接待记录保存服务】 == 删除接待记录成功: recordId ->${recordId}`)
} catch (error) {
this.reportError(`【接待记录保存服务】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
}
}
async _removeRecordFiles(fileArr) {
try {
while (fileArr.length > 0) {
const file = fileArr.shift()
await this._removeFileOnClient(file)
}
uni.$logger.local.info(`【接待记录保存服务】 == 删除接待文件完成!`)
} catch (error) {
this.reportError(`【接待记录保存服务】 == 删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr })
}
}
/**
* 将任务添加到黑名单
*/
_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) {
const result = []
try {
for (const cur of records) {
const recordUrlList = this.urlListFilter(cur.recordUrlList)
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
if (this._isInBlackList(cur.id)) {
continue
}
if (recordUrlList.length == 0) {
result.push({ status: FileStatus.NoFile, recordId: cur.id })
this.reportError('【接待记录保存服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id)
continue
}
for (const file of recordUrlList) {
try {
if (file.status === FileStatus.Uploaded || file.status === FileStatus.Completed) continue
const aFullPath = file.file.split('/')
const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/'
const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file)
if (!fileExists) {
this.reportError('【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file)
file2Up.status = FileStatus.NotExist
}
result.push(file2Up)
} catch (error) {
this.reportError(`【接待记录保存服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file })
this._addToBlackList(cur.id, `Parse error: ${error.message}`)
continue
}
}
}
return result
} catch (error) {
uni.$logger.local.error(`【接待记录保存服务】 == 处理文件列表异常: ${error.message}`)
return result
}
}
urlListFilter(urlList) {
if (!Array.isArray(urlList)) {
urlList = []
}
const __list = urlList.filter(item => item?.file)
return __list
}
async checkFileExists(filePath) {
return new Promise(resolve => {
if (!filePath || !this.isLegalFile(filePath)) {
resolve(false)
return
}
uni.getFileInfo({
filePath: filePath,
success: function (info) {
resolve(true)
},
fail: function (error) {
resolve(false)
}
})
})
}
isLegalFile(file) {
return file && String(file).toLowerCase().endsWith('.mp3')
}
waitting(ms = this.interval) {
uni.$logger.local.info(ms + 'ms后开始下一轮尝试!')
this._scheduleNext(ms)
}
async beginTask(record) {
await this.task(record)
}
task(record) {
return new Promise(async resolve => {
const timeoutId = this._startWatchdog()
this.updateResolve = () => {
clearTimeout(timeoutId)
resolve()
}
this._taskStartTime = Date.now()
this._currentKey = this._getTaskKey(record.recordId, record.fileName)
try {
if (this._isInBlackList(record.recordId)) {
uni.$logger.local.warn(`【接待记录保存服务】 == 任务在黑名单中,跳过: ${this._currentKey}`)
this.endTask()
return
}
await this.uploadRecord(record)
} catch (error) {
this._addToBlackList(record.recordId, `上传文件时发生异常(uploadRecord): ${error.message}`)
this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
this.endTask()
}
})
}
_startWatchdog() {
const TIMEOUT_THRESHOLD = 10 * 60 * 1000
return setTimeout(() => {
if (this.updateResolve) {
uni.$logger.local.error('【接待记录保存服务】 == 看门狗检测到任务卡死超过10分钟,强制结束当前任务!')
this.endTask()
}
}, TIMEOUT_THRESHOLD)
}
endTask() {
this.updateResolve && this.updateResolve()
this.updateResolve = null
this._taskStartTime = null
}
stopPolling() {
if (this.snapshot) {
this.snapshot.clear()
this.snapshot = null
}
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this.canclePromises()
uni.$logger.local.info(`【接待记录保存服务】 == 停止文件上传轮询并清除队列`)
}
setInterval(interval, isForce = false) {
// 保留接口,暂不实现动态调整
}
async startPolling(isForce = false) {
await uni.$dbReady
await this._ensureInitialized()
this._blackList.clear()
if (this._pumpRunning || this.updateResolve) {
if (!isForce) {
uni.$logger.local.info(`【接待记录保存服务】 == 非强制模式下,不强制重启轮询`)
return
} else {
uni.$logger.local.info(`【接待记录保存服务】 == 强制模式下,立即完成promise,强制重启轮询`)
this.canclePromises()
}
}
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(() => {
this._schedulerPump()
}, 0)
uni.$logger.local.info(`【接待记录保存服务】 =========开启上传服务========`)
}
/**
* 确保已初始化
* 使用 Promise 等待 FileUploadManager 被初始化(由 HomeFrame 负责初始化)
* @private
*/
async _ensureInitialized() {
// 如果已经初始化,直接返回
if (FileUploadManager.uploadManager) {
return
}
// 等待 FileUploadManager 被初始化(由 HomeFrame.mounted 负责)
await FileUploadManager.waitForInit()
// 等待策略就绪
await FileUploadManager.uploadManager.ready()
}
canclePromises() {
this.endTask()
}
async _schedulerPump() {
if (this._pumpRunning) return
this._pumpRunning = true
let record = null
try {
const stopReason = await this._checkStopConditions()
if (stopReason) {
uni.$logger.local.info(`【接待记录保存服务】 == ${stopReason}, 暂停上传服务 ,等待唤醒`)
return
}
// 从队列取出任务
record = this.snapshot.dequeue()
// 执行任务
await this.beginTask(record)
// 成功:立即处理下一个任务
this._scheduleNext(0)
} catch (error) {
this.reportError(`【接待记录保存服务】 == 异常,error->${error.message}`, error.message, record?.recordId)
// 如果任务已经 dequeue,将其加入黑名单防止死循环
if (record?.recordId) {
this._addToBlackList(record.recordId, `Scheduler error: ${error.message}`)
}
// 发生异常,等待后继续处理下一个任务
uni.$logger.local.warn(`【接待记录保存服务】 == 发生异常,将在 ${this.interval}ms 后继续处理下一个任务`)
this.waitting(this.interval)
} finally {
this._pumpRunning = false
}
}
async _checkStopConditions() {
let isInBackgound = false
try {
if (store && store.getters) {
isInBackgound = store.getters.isInBackgound
}
} catch (e) {}
if (isInBackgound) {
return 'APP在后台运行,不进行文件上传'
}
const isOnline = await uni.$isNetWork()
if (!isOnline) {
return '网络异常,等待网络恢复'
}
if (this.updateResolve) {
return '任务正在执行中'
}
if (!this.snapshot || this.snapshot.size === 0) {
await this.enQueue()
}
if (!this.snapshot || this.snapshot.size === 0) {
return '队列为空'
}
return null
}
_scheduleNext(ms = 0) {
if (this.snapshot === null) return
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(
() => {
this._schedulerPump()
},
Math.max(0, ms)
)
}
off() {
if (this._networkHandler) {
uni.offNetworkStatusChange(this._networkHandler)
this._networkHandler = null
}
}
}
export default RecordSaveService.getInstance()
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 16:22:23
* @LastEditors: limin
* @LastEditTime: 2026-01-27 17:22:43
* @FilePath: \gl_tape\utils\recordManager\RecordService.js
*/
import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js'
import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js'
import store from '@/store'
class RecordService {
static instance = null
constructor() {
this.audioManager = null
this.record = null
this.tempRecord = null
this.debounceTimers = {}
this._startAudioPromise = null
this.timeoutService = null
// 初始化 (单例模式下只执行一次)
this.init()
}
static getInstance() {
if (!RecordService.instance) {
RecordService.instance = new RecordService()
}
return RecordService.instance
}
init() {
try {
uni.$logger.local.info('【录音服务RecordService】 == 初始化')
this.audioManager = new AudioManager(this.onAudioStart.bind(this), this.onAudioStop.bind(this), this.onAudioError.bind(this))
this.initDto()
// attributesProvider 需要绑定 this,因为 getBussinessType 依赖实例方法
this.record = StrategyFactory.getSaveStrategy(this.tempRecord, this.triggleTempNumber.bind(this), this.attributesProvider.bind(this))
this.timeoutService = new TimeoutService(this.onTimeOut.bind(this))
this.triggleTempNumber()
// 启动状态监听
// this.startStateListener()
this.initWatchers()
} catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == 初始化异常: ${e.message}`)
}
}
initWatchers() {
// 监听 customerKey
this.unwatchCustomer = store.watch(
(state, getters) => getters.customerKey,
() => {
const customerInfo = store.getters.customerInfo
this.handler(customerInfo, this.updateCustomerInfo, 1000)
},
{ immediate: true }
)
// 监听 receptionStatus
this.unwatchStatus = store.watch(
(state, getters) => getters.receptionStatus,
val => {
this.handler(val, this.updateReceptionStatus, 200)
},
{ immediate: true }
)
this.unwatchBookList = store.watch(
(state, getters) => getters.booksList,
val => {
this.handler(val, this.updateBookList, 1500)
},
{ immediate: true }
)
this.unwatchReceptionKey = store.watch(
(state, getters) => getters.receptionKey,
() => {
const receptionTrack = store.getters.receptionTrack
this.handler(receptionTrack, this.updateMaterialPointList, 1000)
},
{ immediate: true }
)
}
// --- 业务逻辑 (从 recorder.js 迁移) ---
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('【录音服务RecordService】 == 开始接待 ')
if (isInitData) {
this.initReception()
}
this.audioManager.start()
this.timeoutService.start()
return true // 返回 true 表示成功启动
} catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}`)
} finally {
this._startAudioPromise = null
}
})()
return this._startAudioPromise
}
getBussinessType(sceneType) {
return sceneType == 0 ? 1 : 2 // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
}
attributesProvider() {
const { sceneType } = uni.$storage.get('userInfo') || {}
const dynamicAttrs = {
bussinessType: this.getBussinessType(sceneType)
}
// uni.$logger.local.warn(`【录音服务RecordService】 == 创建新记录,注入动态属性: ${JSON.stringify(dynamicAttrs)}`)
return dynamicAttrs
}
initReception() {
store.commit('audio/setBooks', [])
store.commit('clearCustomerInfo')
store.commit('audio/setReceptionStatus', '')
}
async onAudioStart(res) {
try {
if (this.audioManager.counter === 0) {
uni.$logger.local.info('〖RecordService〗 == First audio segment, adding record...')
await this.record.add(res)
uni.$logger.local.info('〖RecordService〗 == Record added successfully.')
} else {
this.record.addAudio(res)
}
} catch (e) {
uni.$logger.local.error('〖RecordService〗 == onAudioStart error: ' + e.message)
}
}
async onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.info('【录音服务RecordService】 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.info('【录音服务RecordService】 == 断开录音! ')
}
}
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
}
async stopAudio(isNotSave = false) {
if (!this.isReceptioning()) {
uni.$logger.local.warn('【录音服务RecordService】 == 未开始接待,不能结束接待! ')
return
}
uni.$logger.local.info('【录音服务RecordService】 == 结束接待! ')
this.stop()
try {
await this.saveAndClearRecord(isNotSave)
} catch (error) {
uni.$logger.local.error(`【录音服务RecordService】 == 结束接待保存失败: ${error.message}`)
this.reportError('结束接待保存失败', error.message)
}
}
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
//如果不需要保存记录
uni.$logger.local.info('【录音服务RecordService】 == 不保存记录! ')
await this.record.clearSavedFiles()
await this.record.clearLocalRecord()
return
}
await this.record.setReceptionEndTime() //设置接待结束时间
await this.record.save()
}
stop() {
this.record?.clearLoopTimer()
this.stopAudioRecord()
}
onTimeOut() {
store.commit('audio/setReceptionStatus', 0)
this.record.withError()
this.stopAudioRecord()
}
stopAudioRecord() {
this.audioManager?.stop()
this.timeoutService?.stop()
}
handler(params, fn, delay = 0) {
if (this.isReceptioning()) {
if (delay > 0) {
// 使用函数名作为防抖的 key
// 注意:这里 fn.name 在压缩混淆后可能会变,但在 Service 内部引用是固定的
this.debounce(fn.name, () => fn.call(this, params), delay)
} else {
fn.call(this, params)
}
}
}
isReceptioning() {
return this.audioManager?.isRecording || this.record?.currentRecord?.endReasonType == 1
}
reset() {
this.flushAllDebounceTimers()
this.audioManager = null
this.record = null
this.tempRecord = null
}
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo() || {}
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: this.getBussinessType(sceneType),
channelType: channelType || 1 //1问界 2 比亚迪 3 其他
})
this.tempRecord = dto
}
debounce(key, fn, delay) {
if (this.debounceTimers[key]) {
clearTimeout(this.debounceTimers[key].timer)
}
this.debounceTimers[key] = {
fn,
timer: setTimeout(() => {
fn()
delete this.debounceTimers[key]
}, delay)
}
}
flushAllDebounceTimers() {
if (this.debounceTimers) {
Object.keys(this.debounceTimers).forEach(key => {
const item = this.debounceTimers[key]
if (item) {
clearTimeout(item.timer)
try {
item.fn()
uni.$logger.local.info(`【录音服务RecordService】 == 强制执行防抖任务: ${key}`)
} catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == 强制执行防抖任务失败: ${key}, error: ${e.message}`)
}
}
})
this.debounceTimers = {}
}
}
updateCustomerInfo(customerInfo = {}) {
const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo
this.record.updatePreRecords({
customerName,
phoneNumber,
carModel,
salesUuid,
salesName,
carBrand,
carBrandId,
oneCarBrand,
oneCarBrandId
})
}
updateBookList(booksList) {
const receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
}
})
this.record.updatePreRecords({ receptionCustomerPaySourceList })
}
updateMaterialPointList(receptionTrack) {
const { merchantId, staffUuid, staffName } = this.tempRecord || {}
const { sceneType } = uni.$storage.get('userInfo') || {}
let receptionCustomerMaterialPointList = []
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId,
staffUuid,
staffName,
businessScene: sceneType
})
})
// 优化:将高频更新的物料点数据存入 LocalStorage
if (this.record) {
this.record.cacheMaterialPoints(receptionCustomerMaterialPointList)
}
}
updateReceptionStatus(status) {
this.record.updatePreRecords({ receptionStatus: status })
}
getRecorder() {
return this.record
}
async triggleTempNumber() {
if (!this.record) return
const _records = await this.record.getRecords()
store.commit('audio/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
}
reportError(msg, errorMsg) {
uni.$logger.local.error(`【录音服务RecordService】 == ${msg}`)
// TODO: 如果有统一的上报机制,可以在这里调用
}
destroy() {
this.unWatch()
this.record?.destroy()
this.stop()
this.reset()
}
unWatch() {
this.unwatchBookList?.()
this.unwatchCustomer?.()
this.unwatchReceptionKey?.()
this.unwatchStatus?.()
}
}
export default RecordService
...@@ -4,12 +4,12 @@ ...@@ -4,12 +4,12 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:49:17 * @Date: 2025-01-02 18:49:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-08-12 10:23:15 * @LastEditTime: 2026-01-30 03:19:33
* @FilePath: \gl_tape\utils\recordManager\TempRecord.js * @FilePath: \gl_tape\utils\recordManager\TempRecord.js
*/ */
import utils from '../utils' import utils from '../utils'
import helpler from './helpler'
import { FileStatus } from '../common/constants' import { FileStatus } from '../common/constants'
import { RecordCacheManager, PathUtils, UploadService,RecordSaveService } from './index.js'
class TempRecord { class TempRecord {
timer = null timer = null
timer_interval = 30 * 1000 timer_interval = 30 * 1000
...@@ -17,224 +17,261 @@ class TempRecord { ...@@ -17,224 +17,261 @@ class TempRecord {
path = '' path = ''
newRecord = null newRecord = null
onTempRecordNumberChanged = null onTempRecordNumberChanged = null
constructor(record, onTempRecordNumberChanged) { _isDestroyed = false // 新增销毁标志位
constructor(record, onTempRecordNumberChanged, attributesProvider) {
this.newRecord = record this.newRecord = record
this.recordManager = uni.$dbTempRecord // this.dbRecord = uni.$dbRecord // 延迟获取,避免初始化顺序问题
this.dbManager = uni.$dbManager
this.onTempRecordNumberChanged = onTempRecordNumberChanged this.onTempRecordNumberChanged = onTempRecordNumberChanged
this.attributesProvider = attributesProvider
} }
getRecords() {
return this.recordManager.getRecords() get dbRecord() {
return uni.$dbRecord
} }
/**
* 获取全部临时记录
* @returns {Array} 临时记录列表
*/
async getRecords() {
return this.dbRecord.getTempRecords()
}
/**
* 根据 id 获取单条临时记录
* @param {string} id - 临时记录的唯一标识
* @returns {Object|null} 找到则返回记录,否则返回 null
*/
getRecord(id) { getRecord(id) {
return this.recordManager.getRecordById(id) return this.dbRecord.getRecordById(id)
} }
/**
* 添加一条临时记录并触发数量变化通知
* @param {Object} [record=this.record] - 要添加的记录对象
* @returns {Promise<void>}
*/
async addRecord(record = this.record) { async addRecord(record = this.record) {
await this.recordManager.addRecord(record) try {
this.triggleRecordNumChanged() await this.dbRecord.addRecord(record)
} uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id)
updateRecord(item, where) {
return this.recordManager.updateRecord(item, where)
}
async removeRecord(id) {
await this.recordManager.removeRecord(id)
this.triggleRecordNumChanged() this.triggleRecordNumChanged()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 新增临时记录失败: ' + e.message)
} }
async __update(key, value) {
if (this.record[key] === value) return
this.record[key] = value
return this.updateRecord({ [key]: value }, { id: this.record.id })
} }
async getFilePath() {
if (!this.path) { /**
this.path = await utils.getFileSaveFolderOnClient() * 更新临时记录(部分字段)
} * @param {Object} item - 需要更新的字段键值对
return this.path * @param {Object} where - 更新条件(一般为 { id })
* @returns {Promise<void>}
*/
updateRecord(item, where) {
return this.dbRecord.updateRecord(item, where)
} }
async save(record = this.record) {
async __saveData(toUpdateData = {}, record) {
try { try {
if (!record) throw new Error('记录对象为空') if (!record) throw new Error('记录对象为空')
uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record)) uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
this.clearLoopTimer() // const { recordUrlList } = record
await this.saveTempFile(record)
const { recordUrlList, tempFilePath, ...__record } = record // // 调用保存前钩子
const recordLongList = await this.__analysisUrlList(recordUrlList) // await this.beforeSave(record)
const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
if (recordLongList.length > maxUploadNum) { // const recordLongList = await this.analysisUrlList(recordUrlList)
const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = record || {} // // 从缓存恢复大字段数据
const { name } = userInfo || {} // const restoredData = RecordCacheManager.consumeAll(record)
uni.$logger.error({ // // 构造仅需更新的字段,避免全量更新导致性能浪费
msg: `员工: ${name}, 客户: ${customerName}`, // const updateData = {
extra: { // ...toUpdateData, // 确保合并所有字段
'手机号: ': phoneNumber, // recordStatus: 1,
'姓名: ': customerName, // recordUrlList: recordLongList,
'销售: ': salesName, // ...restoredData // 合并恢复的大字段数据
'车型: ': carModel, // }
'原因: ': '录音文件过长,数量' + recordLongList.length
}
})
}
__record.recordUrlList = recordLongList.slice(0, maxUploadNum)
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!') uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
await this.dbManager.addRecord(__record) // 直接更新原记录,不再插入新记录
await this.clearLocalRecord(record) await this.dbRecord.updateRecord(toUpdateData, { id: record.id })
// 删除本地临时文件 (不再删除数据库记录,因为已经转正)
await this.clearLocalRecord(record, false) // 传入 false 表示不删除数据库记录
this.triggleRecordNumChanged()
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling()
} catch (error) { } catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message) uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
} }
} }
async clearLocalRecord(record = this.record) {
const { id, tempFilePath } = record saveInternal(record) {
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath) if (!record || !record.id) return
await this.removeFile(tempFilePath) const { id, recordUrlList, tempFilePath, ...__record } = record
await this.removeRecord(id) return this.__save(record, __record)
record = null
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
} }
async save(record = this.record) {
await this.beforeSave(record)
return this.__save(record, {})
}
/** /**
* 清除已保存的录音文件 * 将当前临时记录持久化到正式记录表,并清理本地数据
* @param {Object} options - 配置参数 * - 开始前会停止轮询
* @param {Array} options.recordUrlList - 录音文件列表,默认为当前记录的recordUrlList * - 会对过长的录音列表进行截断
* @param {Object} [record=this.record] - 要保存的记录
* @returns {Promise<void>}
*/ */
clearSavedFiles({ recordUrlList = [] } = this.record) { async __save(record, toUpdateData) {
// 遍历录音文件列表并删除每个文件 try {
recordUrlList.forEach(item => { const { recordUrlList } = record
this.removeFile(item.file) // 从缓存恢复大字段数据
}) const restoredData = RecordCacheManager.consumeAll(record)
const recordLongList = await this.analysisUrlList(recordUrlList)
const updateData = {
...toUpdateData,
recordStatus: 1,
recordUrlList: recordLongList,
...restoredData // 合并恢复的大字段数据
}
return this.__saveData(updateData, record)
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
} }
async __analysisUrlList(recordUrlList) { }
/**
* 将已保存的文件列表映射为上传列表(统一拼接基础保存路径)
* @param {Array} recordUrlList - 已保存文件路径列表(形如 { file })
* @returns {Promise<Array>} 规范化后的上传列表(形如 { status, file })
*/
async analysisUrlList(recordUrlList) {
if (!recordUrlList?.length) return [] if (!recordUrlList?.length) return []
try { try {
const __path = await this.getFilePath() const basePath = await PathUtils.getBasePath()
const __list = recordUrlList.reduce((arr, item) => { const list = []
if (item?.file) { for (const item of recordUrlList) {
arr.push({ const filePath = item?.file
if (typeof filePath === 'string' && filePath.length > 0) {
const baseName = filePath.split('/').pop()
list.push({
status: FileStatus.Waiting, status: FileStatus.Waiting,
file: __path + item.file.replace(/.+\/(\d+\.mp3)/, '$1') file: PathUtils.join(basePath, baseName)
}) })
} else { } else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==') uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
} }
return arr }
}, []) return list
return __list
} catch (error) { } catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message) uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message) throw new Error(error.message)
} }
} }
/** /**
* 添加新的接待记录 * 删除一条临时记录并触发数量变化通知
* @param {string} id - 临时记录 id
* @returns {Promise<void>}
*/ */
async add() { async removeRecord(id) {
// 创建一个新的记录对象 await this.dbRecord.removeRecord(id)
this.record = this.__createNewRecord() uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id)
// 异步添加新创建的记录对象 this.triggleRecordNumChanged()
await this.addRecord(this.record)
// 添加音频资源
this.addAudio()
} }
__createNewRecord() {
return { /**
id: utils.uuid(), * 更新当前内存中的记录并同步到数据库(值未变则跳过)
...this.newRecord, * @param {Object} items - 包含多个字段的对象 { key: value, ... }
receptionStartTime: this.getTimeNow(), * @returns {Promise<void>|undefined} 值未变化时返回 undefined
receptionEndTime: '', */
recordUrlList: [] async __update(items) {
if (!this.record || !items || typeof items !== 'object') return
const updates = Object.fromEntries(Object.entries(items).filter(([k, v]) => !utils.nullValues.includes(v) && this.record[k] !== v))
if (Object.keys(updates).length) {
Object.assign(this.record, updates)
return this.updateRecord(updates, { id: this.record.id })
} }
} }
/** /**
* 添加音频 * 彻底删除一条接待记录
* @param {Object} isUpdate - 是否更新音频 * @param {Object} record - 要删除的记录对象
* @returns {void} * @returns {Promise<void>}
*/ */
// Update the record with the new information async deleteRecord(record) {
async addAudio() { if (!record) return
this.clearLoopTimer() uni.$logger.local.warn('〖接待记录Record〗 == 开始彻底删除记录 id: ' + record.id)
uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!') if (record.recordUrlList?.length) {
//保存上一个临时文件 await this.clearSavedFiles(record)
await this.saveLastAudio()
//删除上一个临时文件
await this.removeOldTempAudio()
//等待1秒
await helpler.sleep(1000)
//新增一个录音
await this.addNewAudio()
//更新临时录音文件
await this.updatePath()
//开启轮询保存临时录音文件
this.startSaveAudioLoop()
} }
await this.clearLocalRecord(record, true)
async addNewAudio() { uni.$logger.local.warn('〖接待记录Record〗 == 记录彻底删除完成')
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 })
} }
removeOldTempAudio() { async clearLocalRecord(record = this.record, removeDbRecord = true) {
const { tempFilePath } = this.record const { id, tempFilePath } = record || {}
uni.$logger.local.info('〖接待记录Record〗 == 删除上一个临时文件 -> ' + tempFilePath) uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
return this.removeFile(tempFilePath) await this.removeFile(tempFilePath)
if (id && removeDbRecord) {
await this.removeRecord(id)
}
RecordCacheManager.clearAll(id)
this.record = null
this.path = ''
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
} }
updatePath() { /**
const { id, tempFilePath, recordUrlList } = this.record * 清除已保存的录音文件
return this.updateRecord({ tempFilePath, recordUrlList }, { id }) * @param {Object} options - 配置参数
* @param {Array} options.recordUrlList - 录音文件列表,默认为当前记录的recordUrlList
*/
async clearSavedFiles({ recordUrlList = [] } = this.record) {
for (const item of recordUrlList) {
uni.$logger.local.info('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file)
await this.removeFile(item.file)
}
} }
/** /**
* 保存文件 * 缓存物料点数据
* @param {Object} record - 接待记录对象 * @param {Array} list
* @returns - 返回保存后的文件路径
*/ */
async saveTempFile(record = this.record) { cacheMaterialPoints(list) {
const { tempFilePath, recordUrlList } = record if (this.record && this.record.id) {
const lastIndex = recordUrlList.length - 1 RecordCacheManager.set(this.record.id, 'MATERIAL_POINTS', list)
if (lastIndex < 0 || !tempFilePath) return }
const { file } = recordUrlList[lastIndex]
const saveResultPath = await this.saveFilePath(tempFilePath)
if (saveResultPath) {
uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
await this.removeFile(file)
record.recordUrlList[lastIndex].file = saveResultPath
}
return saveResultPath
}
async saveFilePath(tempFilePath) {
uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
if (!tempFilePath) return
const saveResult = await uni.saveFile({
tempFilePath
})
let saveResultPath = saveResult[1]?.savedFilePath
uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
return saveResultPath
} }
removeFile(filePath) {
/**
* 删除文件(持久化路径使用 `uni.removeSavedFile`)
* @param {string} filePath - 要删除的文件路径(可能为 `_doc/...` 或其他)
* @returns {Promise<void>}
*/
async removeFile(filePath) {
if (!filePath) return if (!filePath) return
let file = filePath
// 若非 file:// 开头的绝对路径,则补全为本地存储目录下的绝对路径
if (!filePath.startsWith('file://')) {
// 优化:使用 getBasePath() 利用缓存,减少 Native Bridge 调用
const saveDir = await PathUtils.getBasePath()
// 仅保留文件名,防止 _doc/ 等相对路径前缀干扰
file = PathUtils.join(saveDir, filePath.split('/').pop())
}
return new Promise(resolve => { return new Promise(resolve => {
uni.removeSavedFile({ try {
filePath, uni.removeSavedFile({ filePath: file, complete: resolve })
complete: resolve } catch (e) {
}) resolve()
})
} }
async saveLastAudio() { })
const __path = await this.saveTempFile()
__path && this.updateUrlList()
} }
updateUrlList() { /**
const { id, recordUrlList } = this.record * 停止保存轮询并清理定时器句柄
return this.updateRecord({ recordUrlList }, { id }) * @returns {void}
} */
startSaveAudioLoop() {
this.clearLoopTimer()
this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
}
clearLoopTimer() { clearLoopTimer() {
if (this.timer) { if (this.timer) {
clearInterval(this.timer) clearInterval(this.timer)
...@@ -242,28 +279,102 @@ class TempRecord { ...@@ -242,28 +279,102 @@ class TempRecord {
} }
} }
async destroy() {
this._isDestroyed = true
this.clearLoopTimer()
uni.$logger.local.info('〖接待记录Record〗 == TempRecord 实例已销毁')
}
/**
* 获取当前内存中的接待记录对象
* @returns {Object|null} 当前记录,可能为空
*/
get currentRecord() { get currentRecord() {
return this.record return this.record
} }
/**
* 设置接待结束时间为当前时间并同步到数据库
* @returns {Promise<void>}
*/
setReceptionEndTime() { setReceptionEndTime() {
return this.__update('receptionEndTime', this.getTimeNow()) return this.__update({ receptionEndTime: this.getTimeNow() })
} }
/**
* 获取当前时间字符串(格式化)
* @returns {string} 形如 `YYYY/MM/DD HH:mm:ss`
*/
getTimeNow() { getTimeNow() {
return utils.convertDateTimeFormat(new Date(), '/') return utils.convertDateTimeFormat(new Date(), '/')
} }
/**
* 标记记录为错误结束原因
* @returns {Promise<void>}
*/
withError() { withError() {
return this.__update('endReasonType', 1) return this.__update({ endReasonType: 1 })
} }
/**
* 批量更新当前记录的多个预填字段
* @param {Object} items - 需要更新的键值对
* @returns {Promise<Object>} 返回更新后的记录对象
*/
async updatePreRecords(items) { async updatePreRecords(items) {
if (items) { await this.__update(items)
Object.keys(items).forEach(async key => await this.__update(key, items[key]))
}
return this.record return this.record
} }
/**
* 通用添加记录流程
* - 创建内存中的记录对象
* - 同步写入临时记录数据库
* @param {Array} initialUrlList - 初始文件列表
* @returns {Promise<void>}
*/
async add(initialUrlList = []) {
this.record = this.__createNewRecord(initialUrlList)
await this.addRecord(this.record)
}
/**
* 构造一条新的接待记录的初始对象
* @param {Array} initialUrlList - 初始的文件列表
* @returns {Object} 新记录对象
*/
__createNewRecord(initialUrlList = []) {
const dynamicAttributes = this.attributesProvider ? this.attributesProvider() : {}
return {
id: utils.uuid(),
...this.newRecord,
...dynamicAttributes,
receptionStartTime: this.getTimeNow(),
receptionEndTime: '',
recordUrlList: initialUrlList,
recordStatus: 0
}
}
/**
* 保存前的钩子函数 (子类可覆盖)
* @param {Object} record
* @returns {Promise<void>}
*/
async beforeSave(record) {
// 默认不做任何事
}
/**
* 触发临时记录数量变化通知
* @returns {Promise<void>|void}
*/
async triggleRecordNumChanged() { async triggleRecordNumChanged() {
if (this.onTempRecordNumberChanged) { if (this.onTempRecordNumberChanged) {
this.onTempRecordNumberChanged() this.onTempRecordNumberChanged()
} }
} }
} }
export default TempRecord export default TempRecord
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-06 10:13:02
* @LastEditors: limin
* @LastEditTime: 2026-01-23 19:37:59
* @FilePath: \gl_tape\utils\recordManager\TimeoutService.js
*/
class TimeoutService {
TIMEOUT = 720000// 40分钟
Miniute = 60 * 1000
TIMER_DURATION = this.TIMEOUT * this.Miniute
CHECK_INTERVAL = 1 * this.Miniute // 1分钟检查一次
onStop = null
__timerId = null
_lastActiveTime = 0
constructor(onStop) {
this.onStop = onStop
}
start() {
uni.$on('reset_timeout', this.handleTouchStart)
this.watch()
}
async stopRecorder() {
return this.onStop()
}
// 初始化或启动监听
watch() {
// 1. 无论是否已启动,先更新活跃时间
this._lastActiveTime = Date.now()
// 2. 如果定时器已在运行,直接返回,避免重复创建
// 这是相比原方案最大的优化:全周期只有一个 setInterval 实例
if (this.__timerId) return
// 3. 启动周期性检查
this.__watchStart()
}
__watchStart() {
this.__timerId = setInterval(async () => {
const now = Date.now()
// 直接计算时间差,比维护 counter 计数器更准确、更简单
if (now - this._lastActiveTime >= this.TIMER_DURATION) {
await this.__watchStop()
if (!this.__timerId) uni.$logger.local.info(`== 检测到${this.TIMEOUT}分钟闲置未操作,自动停止录音 ==`)
}
}, this.CHECK_INTERVAL)
if (this.__timerId) uni.$logger.local.info('== 开启闲置检测 ==')
}
async __watchStop() {
await this.stopRecorder()
this.endWatchClick()
}
endWatchClick() {
if (this.__timerId) {
clearInterval(this.__timerId)
this.__timerId = null
}
this._lastActiveTime = null
uni.$logger.local.info('== 停止闲置检测 ==')
}
handleTouchStart() {
//实现防抖
if (this._debounceTimer) clearTimeout(this._debounceTimer)
this._debounceTimer = setTimeout(() => {
this._lastActiveTime = Date.now()
}, 1000)
}
stop() {
uni.$off('reset_timeout', this.handleTouchStart)
this.endWatchClick()
}
}
export default TimeoutService
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-13 16:30:09
* @LastEditors: limin
* @LastEditTime: 2026-01-29 16:07:00
* @FilePath: \gl_tape\utils\recordManager\UploadService.js
*/
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js'
import { Command } from '@/ws/constants'
import { isInteger, deepClone, serializeIfObject, getWebviewInstance } from '@/utils/utils.js'
import { FileStatus } from '@/utils/common'
import dayjs from 'dayjs'
// import { decryptAES } from '@/lib/aes.js'
import store from '@/store'
import { USE_NATIVE_RECORDER } from './strategies'
const UPLOAD_INTERVAL = 0.5 * 60 * 1000
class UploadService {
constructor() {
this.wv = null
this.interval = UPLOAD_INTERVAL
this._pumpTimer = null
this._pumpRunning = false
this.snapshot = null
this._retryCount = 0
this._currentKey = null
this.updateResolve = null
this._taskStartTime = null
this._networkHandler = null
this._blackList = new Set()
// Bind methods to ensure 'this' context
this.stopPolling = this.stopPolling.bind(this)
this.startPolling = this.startPolling.bind(this)
this.setInterval = this.setInterval.bind(this)
}
static getInstance() {
if (!UploadService.instance) {
UploadService.instance = new UploadService()
}
return UploadService.instance
}
async init() {
try {
// 监听网络状态变化
this._networkHandler = res => {
if (res.isConnected) {
uni.$logger.local.info(`【上传服务】 == 网络已恢复,唤醒上传任务`)
this.startPolling()
}
}
uni.onNetworkStatusChange(this._networkHandler)
} catch (error) {
this.reportError(`【上传服务】初始化失败 error:${error.message}`, error.message)
}
}
/**
* 内部方法:设置并激活 Webview
* @param {Object} wv - 原生 Webview 对象
* @param {Object} refInfo - 引用信息 { component, context }
* @returns {boolean} 是否设置成功
*/
_setupWebview(wv, refInfo) {
if (wv) {
if (typeof wv.setStyle === 'function') {
wv.setStyle({ top: '-1000px', left: '-1000px', width: '10px', height: '10px' })
}
this.wv = wv
if (refInfo) {
this._webviewRef = refInfo
}
return true
}
return false
}
/**
* 设置 Webview 实例(由 UI 组件注入)
* @param {Object} webviewComponent - Vue 组件引用 ($refs.uploaderWebview)
* @param {Object} vueContext - Vue 实例上下文 (this)
*/
async setWebviewContext(webviewComponent, vueContext) {
// #ifdef APP-PLUS
// 尝试获取实例,带有重试机制 (封装在 getWebviewInstance 中)
const wv = await getWebviewInstance(webviewComponent, vueContext)
// 保存引用以便后续轮询中自动恢复
const refInfo = { component: webviewComponent, context: vueContext }
if (this._setupWebview(wv, refInfo)) {
uni.$logger.local.info('【上传服务】Webview Context 已注入')
// Webview 就绪,正式启动轮询
if (!this._pumpRunning) {
this.startPolling()
}
} else {
// 即使第一次没成功,也保存引用,以便后续自动恢复
this._webviewRef = refInfo
uni.$logger.local.warn('【上传服务】Webview 初始化未就绪,将在轮询中自动恢复')
}
// #endif
}
/**
* webview文件上传完成后执行的函数
* @param {*} data
*/
handlerMessage(data) {
uni.$logger.local.info(`【上传服务】 == 文件上传回调!`)
// 这里的 data 结构需要适配 parseFileInfo
// 原来的 data 来自 @message 事件,结构是 { detail: { data: [payload] } }
// 我们在 _setupWebview 中构造了相同的结构
this.save(data)
}
/**
* 生成任务唯一标识 Key
*/
_getTaskKey(recordId, fileName) {
return `${recordId || ''}_${fileName || ''}`
}
async save(data) {
try {
const fileInfo = this.parseFileInfo(data)
if (!fileInfo?.recordId) {
uni.$logger.local.error(`【上传服务】 == 上传文件信息解析异常`)
throw new Error('上传文件信息解析异常,强制结束当前任务')
}
uni.$logger.local.info(`【上传服务】 == 解析结果: recordId=${fileInfo.recordId}, status=${fileInfo.status}`)
const callbackKey = this._getTaskKey(fileInfo.recordId, fileInfo.fileName)
const isCurrentTask = this._currentKey && callbackKey === this._currentKey
if (!isCurrentTask) {
uni.$logger.local.warn(`【上传服务】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态`)
}
const record = await uni.$dbRecord.getRecordById(fileInfo.recordId)
if (!record) {
throw new Error(`未找到记录: ${fileInfo.recordId}`)
}
const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord)
if (isCurrentTask) {
uni.$logger.local.info('【上传服务】 == 本次任务完成,开启下一次上传任务!')
this.endTask()
}
} catch (error) {
if (this._currentKey) {
this._addToBlackList(this._currentKey.split('_')[0], `Save failed: ${error.message}`)
}
this.reportError(`【上传服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask()
}
}
parseFileInfo(data) {
try {
// 1. 尝试从 Webview 回调结构中提取 payload
const payload = data?.detail?.data?.[0]
// CASE 1: Webview 回调
if (payload) {
const { data: d, ...o } = payload
const input = serializeIfObject(o)
uni.$logger.local.warn(`【上传服务】 == 开始文件信息解析-> ${input}`)
return this._parseUploadedFile(data)
}
// CASE 2: 直接调用 (data 是 record 对象)
// 检查是否包含特定状态 (NoFile / NotExist)
if (data && (data.status === FileStatus.NoFile || data.status === FileStatus.NotExist)) {
return this._parseNoFileStatus(data)
}
return null
} catch (error) {
uni.$logger.local.error(`【上传服务】 == 解析文件信息异常: ${error.message}`)
return null
}
}
_parseNoFileStatus(data) {
const { recordId, fileName, filePath, status } = data
const clientPath = (filePath || '') + (fileName || '')
if (!recordId) {
this.reportError('【上传服务】 == 缺少记录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 || '')
if (!payload || typeof payload !== 'object') {
this._reportParseError('回调数据格式错误', data, data?.recordId, clientPath)
return null
}
if (!recordId) {
this._reportParseError('文件上传回调,缺少recordId', data, undefined, clientPath)
return null
}
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 = `【上传服务】 == ${msg}`
uni.$logger.local.error(fullMsg)
this.reportError(fullMsg, data, recordId, filePath)
}
_changeFilePathToServer(record, fileInfo) {
const _record = deepClone(record)
uni.$logger.local.info(`【上传服务】 == 开始更新文件路径, recordId: ${_record.id}`)
if (fileInfo.status === FileStatus.NoFile) {
_record.status = FileStatus.NoFile
_record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime
_record.recordUrlList = []
uni.$logger.local.info(`【上传服务】 == 记录被标记为无文件状态`)
return _record
}
_record.recordUrlList = this.urlListFilter(_record.recordUrlList)
const targetFile = _record.recordUrlList.find(item => this._isTargetFile(item, fileInfo))
if (targetFile) {
this._updateFileStatus(targetFile, fileInfo)
} else {
uni.$logger.local.warn(`【上传服务】 == 未找到匹配的文件记录: ${JSON.stringify(fileInfo)}`)
}
return _record
}
_isTargetFile(item, fileInfo) {
if (!this.isLegalFile(fileInfo.fileName)) return !this.isLegalFile(item.file)
return item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName)
}
_updateFileStatus(targetFile, fileInfo) {
targetFile.status = fileInfo.status
if (fileInfo.status === FileStatus.Uploaded) {
targetFile.file = fileInfo.serverPath
targetFile.filePathOnClient = fileInfo.clientPath
}
uni.$logger.local.info(`【上传服务】 == 文件状态已更新: ${fileInfo.fileName} -> ${fileInfo.status}`)
}
async reportError(message, res, recordId, filePath) {
try {
const record = recordId ? await uni.$dbRecord.getRecordById(recordId) : {}
const userInfo = uni.$storage.get('userInfo') || {}
const { customerName, customerPhone, carType } = record || {}
const { user: { userName } = {} } = userInfo
const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
uni.$logger.error({
msg: `${now}-${message},员工: ${userName}, 客户: ${customerName}`,
extra: {
'员工: ': userName,
'客户姓名: ': customerName,
'客户手机号: ': customerPhone,
'车型: ': carType,
'原因: ': serializeIfObject(res),
'文件路径: ': filePath
}
})
} catch (error) {
uni.$logger.error(`【上传服务】 == 报告错误时发生异常: ${error.message}`)
}
}
async enQueue() {
try {
const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot)
uni.$logger.local.warn(`【上传服务】 == 创建快照成功! ${JSON.stringify(this.snapshot.items)} 快照数: ${this.snapshot.size} `)
} catch (error) {
this.reportError(`【上传服务】 == 获取快照失败 error:${error.message}`, error.message)
if (!this.snapshot) {
this.snapshot = new Queue([])
}
}
}
async getRecordsSnapshotFlatten() {
await uni.$dbReady // 双重保险
let _records = await uni.$dbRecord.getCompletedRecords()
return await this.flattenData(_records || [])
}
async uploadRecord(record) {
// 如果文件状态是没有文件或者不存在,则直接保存记录
uni.$logger.local.info(`【上传服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`)
if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) {
uni.$logger.local.info(`【上传服务】 == 记录中有未上传文件,或文件不存在, 直接保存记录!!`)
await this.save(record)
} else {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
this._safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, record.fileName, record.filePath, record.recordId)
}
}
_safeEvalUpload(lsaccessKeyId, lsaccessKeySecret, securityToken, fileName, filePath, recordId, options = {}) {
if (!this.wv) {
throw new Error('【上传服务】 == WebView 未就绪,无法执行上传脚本')
}
const args = [lsaccessKeyId, lsaccessKeySecret, securityToken, fileName, filePath, recordId].map(v => JSON.stringify(String(v || '')))
// 处理 options 对象,确保它是 JSON 字符串
const optionsStr = JSON.stringify(options || {})
args.push(optionsStr)
const script = `msgFromUniapp(${args.join(',')})`
this.wv.evalJS(script)
}
_removeFileOnClient(filePathOnClient) {
return new Promise((resolve, reject) => {
if (!filePathOnClient) {
uni.$logger.local.info(`【上传服务】 == 要删除的文件为空`)
resolve(true)
return
}
uni.removeSavedFile({
filePath: filePathOnClient,
complete: function (res) {
uni.$logger.local.info(`删除 ${filePathOnClient}-> ${res.errMsg}`)
resolve(res)
}
})
})
}
async _saveOrUpdate(data) {
uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`)
const { status, tempFilePath, recordStatus, ...record } = data
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 {
await this._handleIncompleteRecord(record)
}
}
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(`【上传服务】 == 本条接待所有文件已经上传和处理完毕!!`)
// uni.$logger.local.info(`【上传服务】 == 已上传的文件: ${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(`【上传服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.warn(`【上传服务】 == 服务器返回结果: ${JSON.stringify(res)}`)
// 4. 清理本地数据
if (res) {
uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`)
await this._removeRecordFiles(localPaths)
await this._removeRecordById(record.id)
}
}
/**
* 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间
* @param {Array} recordUrlList - 包含文件URL的数组
* @param {string} receptionStartTime - 接待开始时间
* @returns {Promise<string>} - 一个 Promise,成功时解析为接待结束时间
*/
async _requestReceptionEndTime(recordUrlList, receptionStartTime) {
if (!recordUrlList || recordUrlList.length === 0) return receptionStartTime
// 记录日志,显示正在向服务器请求结束接待时间,包括文件URL列表和接待开始时间
uni.$logger.local.info(`【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`)
// 调用 uni.$api.commonApi.searchRecordingEndTime 方法,向服务器发送请求,获取接待结束时间
const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') })
// 记录日志,显示服务器返回的接待结束时间
uni.$logger.local.info(`【上传服务】 == 服务器返回结束接待时间: endTime ->${endTime}`)
// 返回接待结束时间,将日期格式中的连字符替换为斜杠,以保持一致性
return endTime.replace(/\-/g, '/')
}
async _handleIncompleteRecord(record) {
uni.$logger.local.info(`【上传服务】 == 记录中有未上传文件,开始更新记录!!`)
await uni.$dbRecord.updateRecord({ recordUrlList: record.recordUrlList }, { id: record.id })
}
async _removeRecordById(recordId) {
try {
await uni.$dbRecord.removeRecord(recordId)
uni.$logger.local.info(`【上传服务】 == 删除接待记录成功: recordId ->${recordId}`)
} catch (error) {
this.reportError(`【上传服务】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
}
}
async _removeRecordFiles(fileArr) {
try {
while (fileArr.length > 0) {
const file = fileArr.shift()
await this._removeFileOnClient(file)
}
uni.$logger.local.info(`【上传服务】 == 删除接待文件完成!`)
} catch (error) {
this.reportError(`【上传服务】 == 删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr })
}
}
/**
* 将任务添加到黑名单
* @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) {
const result = []
try {
for (const cur of records) {
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
if (this._isInBlackList(cur.id)) {
continue
}
const recordUrlList = this.urlListFilter(cur.recordUrlList)
if (recordUrlList.length == 0) {
result.push({ status: FileStatus.NoFile, recordId: cur.id })
// 仅在第一次遇到时上报错误
// 注意:不要加入黑名单,因为 NoFile 状态也是需要提交到服务器的(作为无录音记录)
// 如果加入黑名单,下一次轮询就会跳过它,导致永远无法触发 _handleCompletedRecord
this.reportError('【上传服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id)
// this._addToBlackList(cur.id, 'No audio files found')
continue
}
for (const file of recordUrlList) {
try {
if (file.status === FileStatus.Uploaded || file.status === FileStatus.Completed) continue
const aFullPath = file.file.split('/')
const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/'
// 2. 文件任务级别的黑名单检查
// const taskKey = this._getTaskKey(cur.id, fileName)
// if (this._isInBlackList(taskKey)) {
// continue
// }
const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file)
if (!fileExists) {
this.reportError('【上传服务】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file)
file2Up.status = FileStatus.NotExist
// 文件不存在,加入黑名单
// this._addToBlackList(taskKey, 'File not exist on disk')
}
result.push(file2Up)
} catch (error) {
this.reportError(`【上传服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file })
// 解析异常,尝试加入黑名单避免死循环
// const errorKey = this._getTaskKey(cur.id, file?.file)
this._addToBlackList(cur.id, `Parse error: ${error.message}`)
continue
}
}
}
return result
} catch (error) {
uni.$logger.local.error(`【上传服务】 == 处理文件列表异常: ${error.message}`)
return result
}
}
urlListFilter(urlList) {
if (!Array.isArray(urlList)) {
urlList = []
}
const __list = urlList.filter(item => item?.file)
return __list
}
async checkFileExists(filePath) {
return new Promise(resolve => {
if (!filePath || !this.isLegalFile(filePath)) {
resolve(false)
return
}
uni.getFileInfo({
filePath: filePath,
success: function (info) {
resolve(true)
},
fail: function (error) {
resolve(false)
}
})
})
}
isLegalFile(file) {
return file && String(file).toLowerCase().endsWith('.mp3')
}
waitting(ms = this.interval) {
uni.$logger.local.info(ms + 'ms后开始下一轮尝试!')
this._scheduleNext(ms)
}
async beginTask(record) {
await this.task(record)
}
task(record) {
return new Promise(async resolve => {
const timeoutId = this._startWatchdog()
this.updateResolve = () => {
clearTimeout(timeoutId)
resolve()
}
this._taskStartTime = Date.now()
this._currentKey = this._getTaskKey(record.recordId, record.fileName)
try {
if (this._isInBlackList(this._currentKey)) {
uni.$logger.local.warn(`【上传服务】 == 任务在黑名单中,跳过: ${taskKey}`)
this.endTask()
return
}
await this.uploadRecord(record)
} catch (error) {
const message = `上传文件时发生异常(uploadRecord): ${error.message}`
this._addToBlackList(record.recordId, message)
this.reportError(message, error.message)
this.endTask()
}
})
}
_startWatchdog() {
const TIMEOUT_THRESHOLD = 10 * 60 * 1000
return setTimeout(() => {
if (this.updateResolve) {
uni.$logger.local.error('【上传服务】 == 看门狗检测到任务卡死超过10分钟,强制结束当前任务!')
this.endTask()
}
}, TIMEOUT_THRESHOLD)
}
endTask() {
this.updateResolve && this.updateResolve()
this.updateResolve = null
this._taskStartTime = null
}
stopPolling() {
if (this.snapshot) {
this.snapshot.clear()
this.snapshot = null
}
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this.canclePromises()
uni.$logger.local.info(`【上传服务】 == 停止文件上传轮询并清除队列`)
}
setInterval(interval, isForce = false) {
// 保留接口,暂不实现动态调整
}
async startPolling(isForce = false) {
// 确保数据库已初始化
await uni.$dbReady
// 每次启动新一轮轮询时,清空黑名单,允许重试之前的失败任务
this._blackList.clear()
if (this._pumpRunning || this.updateResolve) {
if (!isForce) {
uni.$logger.local.info(`【上传服务】 == 非强制模式下,不强制重启轮询`)
return
} else {
uni.$logger.local.info(`【上传服务】 == 强制模式下,立即完成promise,强制重启轮询`)
this.canclePromises()
}
}
// 防止重复启动的定时器
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(() => {
this._schedulerPump()
}, 0)
uni.$logger.local.info(`【上传服务】 =========开启上传服务========`)
}
canclePromises() {
this.endTask()
}
/**
* 尝试恢复 Webview 实例
* @returns {Promise<boolean>} 是否恢复成功
*/
async _tryRecoverWebview() {
// 尝试自动恢复
if (this._webviewRef && this._webviewRef.component) {
const wv = await getWebviewInstance(this._webviewRef.component, this._webviewRef.context)
if (this._setupWebview(wv)) {
uni.$logger.local.info('【上传服务】 == WebView 自动恢复成功!')
return true
}
}
return false
}
async _schedulerPump() {
if (this._pumpRunning) return
this._pumpRunning = true
try {
const stopReason = await this._checkStopConditions()
if (stopReason) {
uni.$logger.local.info(`【上传服务】 == ${stopReason}, 暂停上传服务 ,等待唤醒`)
return
}
const record = this.snapshot.dequeue()
await this.beginTask(record)
this._scheduleNext(0)
} catch (error) {
this.reportError(`【上传服务】 == 异常,error->${error.message}`)
this._retryCount = (this._retryCount || 0) + 1
const maxDelay = 15 * 60 * 1000
const delay = Math.min(this.interval * Math.pow(2, this._retryCount - 1), maxDelay)
uni.$logger.local.warn(`【上传服务】 == 发生异常,第 ${this._retryCount} 次重试,将在 ${delay}ms 后执行`)
this.waitting(delay)
} finally {
this._pumpRunning = false
}
}
async _checkStopConditions() {
let isInBackgound = false
try {
if (store && store.getters) {
isInBackgound = store.getters.isInBackgound
}
} catch (e) {}
if (isInBackgound) {
return 'APP在后台运行,不进行文件上传'
}
const isOnline = await uni.$isNetWork()
if (!isOnline) {
return '网络异常,等待网络恢复'
}
if (!this.wv) {
const isReady = await this._tryRecoverWebview()
if (!isReady) {
return 'Webview未就绪'
}
}
if (this.updateResolve) {
return '任务正在执行中'
}
if (!this.snapshot || this.snapshot.size === 0) {
await this.enQueue()
}
if (!this.snapshot || this.snapshot.size === 0) {
return '队列为空'
}
return null
}
_scheduleNext(ms = 0) {
if (this.snapshot === null) return
if (this._pumpTimer) {
clearTimeout(this._pumpTimer)
this._pumpTimer = null
}
this._pumpTimer = setTimeout(
() => {
this._schedulerPump()
},
Math.max(0, ms)
)
}
off() {
if (this._networkHandler) {
uni.offNetworkStatusChange(this._networkHandler)
this._networkHandler = null
}
}
}
export default UploadService.getInstance()
...@@ -4,12 +4,14 @@ ...@@ -4,12 +4,14 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-02 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-01-06 09:36:04 * @LastEditTime: 2026-01-22 15:58:34
* @FilePath: \gl_tape\utils\recordManager\dbRecord.js * @FilePath: \gl_tape\utils\recordManager\dbRecord.js
*/ */
import DBManager from '../DBManager.js' import DBManager from './DBManager.js'
class DBRecord { class DBRecord extends DBManager {
table_columns = [ constructor() {
const table_name = 'records'
const table_columns = [
`id TEXT PRIMARY KEY`, `id TEXT PRIMARY KEY`,
`staffUuid TEXT`, `staffUuid TEXT`,
`staffName TEXT`, `staffName TEXT`,
...@@ -32,16 +34,112 @@ class DBRecord { ...@@ -32,16 +34,112 @@ class DBRecord {
'channelType INTEGER', 'channelType INTEGER',
'receptionCustomerMaterialPointList TEXT', 'receptionCustomerMaterialPointList TEXT',
'recordUrlList TEXT', 'recordUrlList TEXT',
'tempFilePath TEXT',
'carBrand TEXT', 'carBrand TEXT',
'carBrandId INTEGER', 'carBrandId INTEGER',
'oneCarBrand TEXT', 'oneCarBrand TEXT',
'oneCarBrandId INTEGER' 'oneCarBrandId INTEGER',
'tempFilePath TEXT',
'recordStatus INTEGER DEFAULT 1' // 0: recording, 1: completed
] ]
table_name = 'temp_records' super(table_name, table_columns)
constructor() { this._initPromise = null
this.db = new DBManager(this.table_name, this.table_columns) }
return this.db
async init() {
if (this._initPromise) return this._initPromise
this._initPromise = (async () => {
try {
await super.init()
await this.ensureColumns()
await this.migrateTempRecords()
return true
} catch (e) {
uni.$logger.local.error('DBRecord: init failed ' + e.message)
throw e
}
})()
return this._initPromise
}
/**
* 确保表字段存在(用于版本升级)
*/
async ensureColumns() {
try {
// 优化:只查询一次表结构
const columnInfo = await this.db.selectSql(`PRAGMA table_info(${this.table_name})`)
const existingColumns = columnInfo.map(col => col.name)
const columnsToAdd = this.table_columns.reduce((acc, colDef) => {
const [name, ...def] = colDef.trim().split(/\s+/)
if (name && !existingColumns.includes(name)) {
acc.push({ name, definition: def.join(' ') })
}
return acc
}, [])
if (columnsToAdd.length > 0) {
await this.db.addColumns(this.table_name, columnsToAdd)
uni.$logger.local.info(`DBRecord: Added columns ${columnsToAdd.map(c => c.name).join(', ')}`)
}
} catch (e) {
uni.$logger.local.error('DBRecord: ensureColumns failed ' + e.message)
}
}
/**
* 将旧的临时表数据迁移到正式表
*/
async migrateTempRecords() {
const tempTableName = 'temp_records'
try {
const exists = await this.db.isTableExists(tempTableName)
if (!exists) return
uni.$logger.local.warn('DBRecord: Found temp_records table, starting migration...')
// 获取所有临时记录
const tempRecords = await this.db.selectSql(`SELECT * FROM ${tempTableName}`)
if (tempRecords && tempRecords.length > 0) {
for (const record of tempRecords) {
if (!record.id) continue
// 标记为进行中
record.recordStatus = 0
// 检查是否已存在
const existing = await this.getRecordById(record.id)
if (existing) {
// 如果存在,说明正式表已有记录,temp_records 中的是残留数据,直接跳过
uni.$logger.local.warn(`DBRecord: Temp record ${record.id} already exists in records, skipping migration.`)
} else {
// 如果不存在,插入它
await this.addRecord(record)
uni.$logger.local.info(`DBRecord: Migrated temp record ${record.id}`)
}
}
}
// 迁移完成后删除旧表
await this.db.drop(tempTableName)
uni.$logger.local.warn('DBRecord: Migration completed, temp_records table dropped.')
} catch (e) {
uni.$logger.local.error('DBRecord: Migration failed ' + e.message)
}
}
/**
* 获取已完成的接待记录 (recordStatus = 1)
*/
async getCompletedRecords() {
return this.getRecordsByWhere({ recordStatus: 1 })
}
/**
* 获取进行中/临时的接待记录 (recordStatus = 0)
*/
async getTempRecords() {
return this.getRecordsByWhere({ recordStatus: 0 })
} }
} }
export default DBRecord export default DBRecord
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-06 14:07:42
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:47:34
* @FilePath: \gl_tape\utils\recordManager\helpler.js
*/
import utils from '../utils' import utils from '../utils'
import PathUtils from './PathUtils'
/** /**
* 内部方法,用于获取完整的音频文件路径 * 内部方法,用于获取完整的音频文件路径
* *
* 此函数调用 `getAudioPathName` 获取文件名,并通过 `getAudioPath` 获取完整路径。 * 此函数调用 `getAudioPathName` 获取文件名,并通过 `getAudioPath` 获取完整路径。
* @param {string} excludePath - 需要排除的文件路径(完整路径)
*/ */
async function getLatestAudioFilePath() { async function getLatestAudioFilePath(excludePath = '') {
const pathName = await __getAudioPathName() try {
return __getAudioPath(pathName) // 从完整路径中提取文件名,用于底层过滤
} let excludeName = ''
if (excludePath) {
excludeName = excludePath.split('/').pop()
}
const pathName = await __getAudioPathName(excludeName)
if (!pathName) return ''
return await __getAudioPath(pathName)
} catch (error) {
uni.$logger.local.warn('〖接待记录Record〗 == 获取最新录音路径异常: ' + error.message)
return ''
}
}
/** /**
* 异步获取音频文件路径名称 * 异步获取音频文件路径名称
* *
* 此函数用于查找特定目录中所有以 'uniapp_temp' 开头的文件,并返回修改时间最晚的文件名。 * 此函数用于查找特定目录中所有以 'uniapp_temp' 开头的文件,并返回修改时间最晚的文件名。
* 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。 * 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。
* @param {string} excludeName - 需要排除的文件名
*/ */
async function __getAudioPathName() { async function __getAudioPathName(excludeName = '') {
const path = await utils.getAudioFilePath() const path = await PathUtils.getAudioFilePath()
return __getLatestFileName(path, 'uniapp_temp') return __getLatestFileName(path, 'uniapp_temp', excludeName)
} }
/** /**
* 异步获取指定名称的音频文件路径 * 异步获取指定名称的音频文件路径
* *
...@@ -28,22 +50,21 @@ async function __getAudioPathName() { ...@@ -28,22 +50,21 @@ async function __getAudioPathName() {
* @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)
} }
/** /**
* 获取指定目录中修改时间最晚的文件名 * 获取指定目录中修改时间最晚的文件名
* *
* @param {string} directoryPath - 目录路径 * @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选) * @param {string} prefix - 文件名前缀(可选)
* @param {string} excludeName - 需要排除的文件名(可选)
* @returns {Promise<string>} - 修改时间最晚的文件名 * @returns {Promise<string>} - 修改时间最晚的文件名
*/ */
async function __getLatestFileName(directoryPath, prefix = '') { async function __getLatestFileName(directoryPath, prefix = '', excludeName = '') {
const latestFile = await __getLatestFile(directoryPath, prefix) const latestFile = await __getLatestFile(directoryPath, prefix, excludeName)
return latestFile ? latestFile.name : '' return latestFile ? latestFile.name : ''
} }
/** /**
* 获取指定目录中修改时间最晚的文件路径 * 获取指定目录中修改时间最晚的文件路径
* *
...@@ -54,58 +75,109 @@ async function __getLatestFilePath(directoryPath) { ...@@ -54,58 +75,109 @@ async function __getLatestFilePath(directoryPath) {
const latestFile = await __getLatestFile(directoryPath) const latestFile = await __getLatestFile(directoryPath)
return latestFile ? directoryPath + '/' + latestFile.name : '' return latestFile ? directoryPath + '/' + latestFile.name : ''
} }
/** /**
* 获取指定目录中修改时间最晚的文件 * 获取文件的元数据
*
* @param {object} fileEntry - 文件条目
* @returns {Promise<object>} - 文件元数据
*/
function __getFileMetadata(fileEntry) {
return new Promise(resolve => {
fileEntry.getMetadata(
metadata => {
resolve({
name: fileEntry.name,
modificationTime: metadata.modificationTime.getTime()
})
},
e => {
uni.$logger.local.warn(`〖接待记录Record〗 == 获取文件元数据失败: ${fileEntry.name} ${e.message}`)
resolve({
name: fileEntry.name,
modificationTime: 0
})
}
)
})
}
/**
* 获取指定目录中修改时间最晚的文件信息
* *
* @param {string} directoryPath - 目录路径 * @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选) * @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<object|null>} - 修改时间最晚的文件对象或 null * @param {string} excludeName - 需要排除的文件名(可选)
* @returns {Promise<object|null>} - 文件对象 {name, modificationTime} 或 null
*/ */
async function __getLatestFile(directoryPath, prefix = '') { async function __getLatestFile(directoryPath, prefix = '', excludeName = '') {
return new Promise((resolve, reject) => { 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( plus.io.resolveLocalFileSystemURL(
directoryPath, directoryPath,
e => { e => {
const dirR = e.createReader() const dirR = e.createReader()
dirR.readEntries( dirR.readEntries(
async entries => { async entries => {
const files = entries.filter(item => (prefix ? item.name.startsWith(prefix) : true)) try {
// 先根据前缀和排除名单进行过滤
const files = entries.filter(item => {
if (prefix && !item.name.startsWith(prefix)) return false
if (excludeName && item.name === excludeName) return false
return true
})
const filePromises = files.map(item => __getFileMetadata(item)) const filePromises = files.map(item => __getFileMetadata(item))
const results = await Promise.all(filePromises) const results = await Promise.all(filePromises)
const latest = results.reduce((acc, current) => (current.modificationTime > acc.modificationTime ? current : acc), { modificationTime: 0 }) const latest = results.reduce((acc, current) => {
// 优先尝试从文件名解析时间戳 (假设文件名是时间戳或包含时间戳)
// 例如: 1767921591256.mp3 -> 1767921591256
const getTimestamp = (name) => {
if (!name) return 0
const match = name.match(/(\d{13})/) // 匹配13位毫秒时间戳
return match ? parseInt(match[1]) : 0
}
const accTs = getTimestamp(acc.name)
const currTs = getTimestamp(current.name)
if (accTs > 0 && currTs > 0) {
return currTs > accTs ? current : acc
}
// 回退到修改时间
return (current.modificationTime > acc.modificationTime ? current : acc)
}, { name: '', modificationTime: 0 })
resolve(latest.name ? latest : null) resolve(latest.name ? latest : null)
} catch (error) {
uni.$logger.local.error(`〖接待记录Record〗 == 处理目录项异常: ${error.message}`)
resolve(null)
}
}, },
err => reject(err) err => {
uni.$logger.local.warn(`〖接待记录Record〗 == 读取目录项失败: ${directoryPath}, err: ${JSON.stringify(err)} ${err.message}`)
resolve(null)
}
) )
}, },
err => reject(err) err => {
) // 目录不存在或无法访问,视为无文件
}) uni.$logger.local.warn(`〖接待记录Record〗 == 目录不存在或无法访问: ${directoryPath} err: ${JSON.stringify(err)} ${err.message}`)
} resolve(null)
}
/**
* 获取文件的元数据
*
* @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)
) )
}) })
} }
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
......
...@@ -4,15 +4,24 @@ ...@@ -4,15 +4,24 @@
* @Author: limin * @Author: limin
* @Date: 2024-06-28 17:12:39 * @Date: 2024-06-28 17:12:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-03-11 18:07:04 * @LastEditTime: 2026-01-30 03:31:12
* @FilePath: \gl_tape\utils\recordManager\index.js * @FilePath: \gl_tape\utils\recordManager\index.js
*/ */
// import { singleton } from '../utils.js' // import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js' import AudioManager from './AudioManager.js'
// import DBTempRecord from './dbTempRecord.js' // 已废弃
import DBRecord from './dbRecord.js' import DBRecord from './dbRecord.js'
import DBManager from './DBManager.js'
// import Record from './Record.js' // import Record from './Record.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'
// const SingleDBTempRecord = singleton(TempRecord) import StrategyFactory from './strategies.js'
module.exports = { AudioManager, DBRecord, RecordDto, TempRecord, helpler } import RecordCacheManager from './RecordCacheManager.js'
import PathUtils from './PathUtils.js'
import UploadService from './UploadService.js'
import TimeoutService from './TimeoutService.js'
import RecordSaveService from './RecordSaveService.js'
import FileUploadManager from './FileUploadManager.js'
export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory, RecordCacheManager, PathUtils, UploadService,TimeoutService, RecordSaveService, FileUploadManager }
export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory, RecordCacheManager, PathUtils, UploadService,TimeoutService, RecordSaveService, FileUploadManager }
/*
* @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 {
/**
* 获取录音器策略
* @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(...args) {
let StrategyClass = PollingSave
// #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
StrategyClass = NativeSave
}
// #endif
return new StrategyClass(...args)
}
}
export default StrategyFactory
/*
* @Description: WebView 策略调试工具
* @Usage: 在上传前调用 debugWebViewStrategy() 查看详细状态
*/
import { getUploadManager } from '@/utils/uploadManager/UploadManager.js'
/**
* 调试 WebView 策略状态
*
* 在上传前调用此方法,查看 WebView 策略的详细状态
*/
export function debugWebViewStrategy() {
console.log('========== WebView 策略调试信息 ==========')
const uploadManager = getUploadManager()
// 1. 检查 UploadManager
if (!uploadManager) {
console.error('❌ UploadManager 未初始化')
return
}
console.log('✅ UploadManager 已初始化')
// 2. 检查文件大小阈值
const threshold = uploadManager.getFileSizeThreshold()
const thresholdMB = (threshold / 1024 / 1024).toFixed(2)
console.log(`📏 文件大小阈值: ${thresholdMB} MB`)
console.log(` - < ${thresholdMB} MB: 优先使用 UniApp`)
console.log(` - >= ${thresholdMB} MB: 优先使用 WebView`)
// 3. 检查 WebView 策略
const webviewStrategy = uploadManager.strategySelector.getStrategy(STRATEGY_NAMES.WEBVIEW)
if (!webviewStrategy) {
console.error('❌ WebView 策略未注册')
return
}
console.log('✅ WebView 策略已注册')
// 4. 检查 WebView 支持
const isSupported = webviewStrategy.isSupported()
console.log(`${isSupported ? '✅' : '❌'} WebView 支持: ${isSupported}`)
// 5. 检查 WebView 就绪
const isReady = webviewStrategy.isReady()
console.log(`${isReady ? '✅' : '❌'} WebView 就绪: ${isReady}`)
if (!isReady) {
console.warn('⚠️ WebView 未就绪,可能原因:')
console.warn(' 1. WebView 未初始化')
console.warn(' 2. 未收到 webview_ready 信号')
console.warn(' 3. WebView 加载失败')
}
// 6. 检查 UniApp 策略
const uniappStrategy = uploadManager.strategySelector.getStrategy(STRATEGY_NAMES.UNIAPP)
if (uniappStrategy) {
const uniappSupported = uniappStrategy.isSupported()
const uniappReady = uniappStrategy.isReady()
console.log(`${uniappSupported ? '✅' : '❌'} UniApp 支持: ${uniappSupported}`)
console.log(`${uniappReady ? '✅' : '❌'} UniApp 就绪: ${uniappReady}`)
}
// 7. 检查所有可用策略
const supportedStrategies = uploadManager.getSupportedStrategies()
console.log(`📋 支持的策略: [${supportedStrategies.join(', ')}]`)
// 8. 模拟策略选择
console.log('\n========== 模拟策略选择 ==========')
// 小文件
const smallFileSize = 10 * 1024 * 1024 // 10MB
const smallFilePriority = uploadManager._getStrategyPriorityByFileSize(smallFileSize)
console.log(`📄 小文件 (10 MB):`)
console.log(` 策略优先级: [${smallFilePriority.join(', ')}]`)
// 大文件
const largeFileSize = 100 * 1024 * 1024 // 100MB
const largeFilePriority = uploadManager._getStrategyPriorityByFileSize(largeFileSize)
console.log(`📄 大文件 (100 MB):`)
console.log(` 策略优先级: [${largeFilePriority.join(', ')}]`)
// 9. 预测上传策略
console.log('\n========== 预测上传策略 ==========')
function predictStrategy(fileSize) {
const priority = uploadManager._getStrategyPriorityByFileSize(fileSize)
const fileSizeMB = (fileSize / 1024 / 1024).toFixed(2)
console.log(`📄 文件大小: ${fileSizeMB} MB`)
console.log(` 策略优先级: [${priority.join(', ')}]`)
for (const strategyName of priority) {
const strategy = uploadManager.strategySelector.getStrategy(strategyName)
if (strategy && strategy.isSupported() && strategy.isReady()) {
console.log(` ✅ 将使用: ${strategyName}`)
return strategyName
} else {
const reason = !strategy ? '未注册' : !strategy.isSupported() ? '不支持' : '未就绪'
console.log(` ❌ ${strategyName}: ${reason}`)
}
}
console.log(' ❌ 无可用策略')
return null
}
// 测试不同文件大小
predictStrategy(10 * 1024 * 1024) // 10MB
console.log('')
predictStrategy(100 * 1024 * 1024) // 100MB
console.log('\n========== 调试信息结束 ==========')
}
/**
* 强制启用 WebView 测试模式
*/
export function forceEnableWebView() {
console.log('🔥 强制启用 WebView 测试模式')
const uploadManager = getUploadManager()
if (!uploadManager) {
console.error('❌ UploadManager 未初始化')
return false
}
// 设置阈值为 0
uploadManager.setFileSizeThreshold(0)
console.log('✅ 阈值已设置为 0 MB')
console.log('✅ 所有文件都将优先使用 WebView 策略')
// 再次检查
debugWebViewStrategy()
return true
}
/**
* 等待 WebView 就绪
*
* @param {number} timeout - 超时时间(毫秒)
* @param {number} interval - 检查间隔(毫秒)
* @returns {Promise<boolean>} 是否就绪
*/
export function waitForWebViewReady(timeout = 10000, interval = 500) {
return new Promise((resolve) => {
const startTime = Date.now()
const check = () => {
const uploadManager = getUploadManager()
const webviewStrategy = uploadManager?.strategySelector?.getStrategy(STRATEGY_NAMES.WEBVIEW)
if (webviewStrategy && webviewStrategy.isReady()) {
console.log('✅ WebView 已就绪')
resolve(true)
return
}
const elapsed = Date.now() - startTime
if (elapsed >= timeout) {
console.error(`❌ WebView 未就绪(超时 ${timeout}ms)`)
resolve(false)
return
}
console.log(`⏳ 等待 WebView 就绪... (${elapsed}ms / ${timeout}ms)`)
setTimeout(check, interval)
}
check()
})
}
export default {
debugWebViewStrategy,
forceEnableWebView,
waitForWebViewReady
}
# UploadManager - OSS 文件上传管理器
基于策略模式的 OSS 文件上传管理器,支持多种上传策略和自动降级。
## 快速开始
### 1. 初始化
```javascript
import { getUploadManager } from '@/utils/uploadManager'
// 获取单例实例
const uploadManager = getUploadManager({
webview: {
webviewRef: this.$refs.uploaderWebview,
vueContext: this
}
})
// 等待所有策略就绪
await uploadManager.ready()
```
### 2. 上传文件
```javascript
const file = {
path: '/path/to/file.mp3',
name: 'file.mp3',
size: 1024000 // 字节
}
const url = await uploadManager.upload(file, {
ossConfig: {
accessKeyId: 'xxx',
accessKeySecret: 'xxx',
stsToken: 'xxx',
bucket: 'my-bucket',
region: 'oss-cn-hangzhou'
},
onProgress: (percent) => {
console.log(`上传进度: ${percent}%`)
},
onSuccess: (url) => {
console.log(`上传成功: ${url}`)
},
onFailure: (error) => {
console.error(`上传失败: ${error.message}`)
}
})
```
## 核心特性
### 自动策略选择
根据文件大小自动选择最优策略:
- **文件 < 50MB**:优先使用 UniAppStrategy(表单上传)
- **文件 >= 50MB**:优先使用 WebViewStrategy(OSS SDK 分片上传)
### 自动降级
如果首选策略失败或未就绪,自动降级到下一个可用策略:
1. 尝试第一个策略
2. 失败则尝试第二个策略
3. 所有策略都失败则抛出异常
### Promise-based 就绪机制
```javascript
// 等待所有策略就绪
await uploadManager.ready()
// 检查是否已就绪(同步)
if (uploadManager.isReady()) {
console.log('所有策略已就绪')
}
```
## 支持的策略
### WebViewStrategy
- 使用阿里云 OSS SDK
- 支持分片上传
- 适合大文件(>= 50MB)
- 需要 WebView 环境
### UniAppStrategy
- 使用 `uni.uploadFile` API
- 表单上传
- 适合小文件(< 50MB)
- 跨平台支持
## API 文档
### UploadManager
#### 构造函数
```javascript
new UploadManager(options)
```
**参数:**
- `options.webview` - WebView 配置(可选)
- `webviewRef` - WebView 组件引用
- `vueContext` - Vue 组件实例
#### upload(file, options)
上传文件到 OSS
**参数:**
- `file` - 文件对象
- `path` - 文件路径
- `name` - 文件名
- `size` - 文件大小(字节)
- `options` - 上传选项
- `ossConfig` - OSS 配置
- `onProgress` - 进度回调
- `onSuccess` - 成功回调
- `onFailure` - 失败回调
**返回:** `Promise<string>` - OSS 文件 URL
#### ready()
等待所有策略就绪
**返回:** `Promise<void>`
#### isReady()
检查是否已就绪(同步)
**返回:** `boolean`
#### cancel()
取消正在进行的上传
#### handleWebViewMessage(event)
处理来自 WebView 的消息
**参数:**
- `event` - WebView message 事件
**返回:** `boolean` - 是否处理了消息
## 配置
### 文件大小阈值
```javascript
// 设置阈值(默认 50MB)
uploadManager.setFileSizeThreshold(100 * 1024 * 1024) // 100MB
// 获取阈值
const threshold = uploadManager.getFileSizeThreshold()
```
## 调试
### 启用调试日志
日志会自动输出到 `uni.$logger`,包括:
- 策略注册信息
- 文件大小和策略选择
- 上传进度和结果
- 错误信息
### 常见问题
#### WebView 策略未就绪
- 检查 WebView 是否加载完成
- 检查是否收到 `webview_ready` 信号
- 使用 `await uploadManager.ready()` 等待就绪
#### 上传失败
- 检查 OSS 配置是否正确
- 检查文件路径是否存在
- 检查网络连接
- 查看日志中的错误信息
## 架构设计
### 策略模式
- `UploadStrategy`:策略基类
- `WebViewStrategy`:WebView 上传策略
- `UniAppStrategy`:UniApp 上传策略
### 职责分离
- `UploadManager`:上传管理器(门面)
- `StrategySelector`:策略选择器
- `UploadStrategy`:策略实现
## 文档
- **快速开始**:`QUICK_START.md`
- **历史文档归档**:`docs/ARCHIVE.md`
- **代码注释**:查看各个模块的代码注释
---
**最后更新:** 2026-01-30
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:39:31
* @LastEditors: limin
* @LastEditTime: 2026-01-30 19:42:20
* @FilePath: \gl_tape\utils\uploadManager\UploadManager.js
*/
import WebViewStrategy from './strategies/WebViewStrategy.js'
import UniAppStrategy from './strategies/UniAppStrategy.js'
import StrategySelector from './components/StrategySelector.js'
import { STRATEGY_NAMES, FILE_SIZE_THRESHOLD } from './constants.js'
/**
* 上传管理器 - 文件上传的主门面
*
* 功能:
* 1. 管理两种上传策略(WebView、UniApp)
* 2. 根据文件大小自动选择最优策略
* 3. 自动降级到备用策略
* 4. 统一的上传接口
* 5. 完整的日志记录
*
* 使用示例:
* ```javascript
* const uploadManager = new UploadManager()
*
* // 上传文件(自动选择策略)
* await uploadManager.upload(file, {
* onProgress: (percent) => console.log(`进度: ${percent}%`),
* onSuccess: (url) => console.log(`成功: ${url}`),
* onFailure: (error) => console.error(`失败: ${error.message}`)
* })
* ```
*/
class UploadManager {
/**
* yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
*/
region = 'oss-cn-shenzhen'
/**
* 填写Bucket名称。
*/
bucket = 'glsk-oss'
constructor(options = {}) {
/**
* 策略选择器
* @type {StrategySelector}
*/
this.strategySelector = new StrategySelector()
/**
* 日志记录器
* @type {Object}
*/
this.logger = uni.$logger || console
/**
* 文件大小阈值(字节)
* 小于此大小使用 UniAppStrategy(表单上传)
* 大于等于此大小使用 WebViewStrategy(OSS SDK 分片上传)
*
* 默认:50MB
*
* @type {number}
*/
this.fileSizeThreshold = FILE_SIZE_THRESHOLD.SMALL_FILE
/**
* 最后一次上传使用的策略名称
* @type {string}
*/
this.lastUsedStrategy = STRATEGY_NAMES.NONE
/**
* 就绪状态 Promise
* @type {Promise<void>}
* @private
*/
this._readyPromise = null
/**
* 就绪状态 resolve 函数
* @type {Function|null}
* @private
*/
this._readyResolve = null
/**
* 是否已就绪
* @type {boolean}
* @private
*/
this._isReady = false
/**
* WebView 配置
* @type {Object|null}
* @private
*/
this._webviewConfig = options.webview || null
// 注册所有策略
this._registerStrategies()
// 初始化就绪 Promise
this._initReadyPromise()
// 如果传入了 WebView 配置,初始化 WebView 策略
if (this._webviewConfig) {
this._initializeWebViewStrategy()
}
}
/**
* 初始化就绪 Promise
* @private
*/
_initReadyPromise() {
this._readyPromise = new Promise((resolve) => {
this._readyResolve = resolve
})
}
/**
* 初始化 WebView 策略
* @private
*/
_initializeWebViewStrategy() {
const { webviewRef, vueContext } = this._webviewConfig
if (!webviewRef || !vueContext) {
this.logger.local?.warn('[UploadManager] WebView 配置不完整,跳过 WebView 策略初始化')
return
}
try {
const webviewStrategy = this.strategySelector.getStrategy(STRATEGY_NAMES.WEBVIEW)
if (webviewStrategy) {
webviewStrategy.initialize(webviewRef, vueContext)
this.logger.local?.info('[UploadManager] WebView 策略已初始化')
}
} catch (error) {
this.logger.local?.error(`[UploadManager] WebView 策略初始化失败: ${error.message}`)
}
}
/**
* 设置 WebView 配置(延迟初始化)
*
* 如果在构造时没有传入 WebView 配置,可以稍后设置
*
* @param {Object} webviewRef - WebView 组件引用
* @param {Object} vueContext - Vue 组件实例
*/
setWebViewConfig(webviewRef, vueContext) {
this._webviewConfig = { webviewRef, vueContext }
this._initializeWebViewStrategy()
}
/**
* 注册所有上传策略
* @private
*/
_registerStrategies() {
this.strategySelector.register(new WebViewStrategy())
this.strategySelector.register(new UniAppStrategy())
this.logger.local?.info(`[UploadManager] Strategies registered: ${STRATEGY_NAMES.WEBVIEW}, ${STRATEGY_NAMES.UNIAPP}`)
}
/**
* 上传文件到 OSS
*
* 策略选择逻辑:
* 1. 根据文件大小动态选择策略:
* - 文件 < 50MB:优先使用 UniAppStrategy(表单上传,简单快速)
* - 文件 >= 50MB:优先使用 WebViewStrategy(OSS SDK,支持分片)
* 2. 如果首选策略未就绪,按优先级降级
* 3. 支持策略级降级(第一个策略失败立即尝试下一个)
* 4. 所有策略都失败则抛出异常
*
* @param {Object} file - 文件对象
* @param {string} file.path - 文件路径
* @param {string} file.name - 文件名
* @param {number} file.size - 文件大小(字节)
*
* @param {Object} options - 上传选项
* @param {Function} [options.onProgress] - 进度回调 (percent: 0-100)
* @param {Function} [options.onSuccess] - 成功回调 (url, metadata)
* @param {Function} [options.onFailure] - 失败回调 (error)
* @param {Object} [options.ossConfig] - OSS 配置
*
* @returns {Promise<string>} OSS 文件 URL
* @throws {Error} 上传失败时抛出错误
*/
async upload(file, options = {}) {
const startTime = Date.now()
// 1. 获取策略优先级
const strategyPriority = this._getStrategyPriorityByFileSize(file.size)
// this._logFileInfo(file, strategyPriority)
// 2. 查找可用策略
const readyStrategies = this._findReadyStrategies(strategyPriority)
// 3. 补充 OSS 配置
this._ensureOSSConfig(options)
// 4. 依次尝试策略
return await this._tryStrategies(readyStrategies, file, options, startTime)
}
/**
* 记录文件信息
* @private
*/
_logFileInfo(file, strategyPriority) {
this.logger.local?.info(`[UploadManager] File size: ${file.size} bytes (${(file.size / 1024 / 1024).toFixed(2)} MB)`)
this.logger.local?.info(`[UploadManager] Strategy priority: [${strategyPriority.join(', ')}]`)
}
/**
* 查找已就绪的策略
* @private
*/
_findReadyStrategies(strategyPriority) {
const readyStrategies = []
const notReadyStrategies = []
const unsupportedStrategies = []
for (const strategyName of strategyPriority) {
const strategy = this.strategySelector.getStrategy(strategyName)
if (!strategy) continue
if (!strategy.isSupported()) {
unsupportedStrategies.push(strategyName)
continue
}
if (strategy.isReady()) {
readyStrategies.push({ name: strategyName, strategy })
} else {
notReadyStrategies.push(strategyName)
}
}
// 如果没有可用策略,抛出错误
if (readyStrategies.length === 0) {
this._throwNoStrategyError(notReadyStrategies, unsupportedStrategies)
}
// this.logger.local?.info(`[UploadManager] Available strategies: [${readyStrategies.map(s => s.name).join(', ')}]`)
return readyStrategies
}
/**
* 抛出无可用策略错误
* @private
*/
_throwNoStrategyError(notReadyStrategies, unsupportedStrategies) {
let errorMsg = '无可用的上传策略。'
if (notReadyStrategies.length > 0) {
errorMsg += ` 未就绪: [${notReadyStrategies.join(', ')}]。`
if (notReadyStrategies.includes(STRATEGY_NAMES.WEBVIEW)) {
errorMsg += ' WebView 策略需要等待初始化完成,请稍后重试。'
}
}
if (unsupportedStrategies.length > 0) {
errorMsg += ` 不支持: [${unsupportedStrategies.join(', ')}]。`
}
if (notReadyStrategies.length === 0 && unsupportedStrategies.length === 0) {
errorMsg += ' 未找到任何上传策略。'
}
this.logger.local?.error(`[UploadManager] ${errorMsg}`)
throw new Error(errorMsg)
}
/**
* 确保 OSS 配置完整
* @private
*/
_ensureOSSConfig(options={}) {
options.ossConfig = options.ossConfig || {}
const { ossConfig } = options
// 使用默认值填充空缺配置
ossConfig.bucket = ossConfig.bucket || this.bucket
ossConfig.region = ossConfig.region || this.region
// 自动生成 endpoint
if (!ossConfig.endpoint && ossConfig.bucket && ossConfig.region) {
ossConfig.endpoint = `https://${ossConfig.bucket}.${ossConfig.region}.aliyuncs.com`
}
}
/**
* 依次尝试策略上传(使用 Promise 链式调用)
* @private
*/
async _tryStrategies(readyStrategies, file, options, startTime) {
return readyStrategies.reduce((promise, { name: strategyName, strategy }, index) => {
return promise.catch(async (previousError) => {
// 如果不是第一个策略,说明前面的策略失败了
if (index > 0) {
this.logger.local?.warn(
`[UploadManager] Strategy ${readyStrategies[index - 1].name} failed: ${previousError.message}, trying next strategy...`
)
}
this.logger.local?.info(`[UploadManager] Trying strategy ${index + 1}/${readyStrategies.length}: ${strategyName}`)
try {
const result = await this._uploadWithStrategy(strategy, strategyName, file, options, startTime)
// 上传成功
this.lastUsedStrategy = strategyName
return result
} catch (error) {
// 如果是最后一个策略,记录错误并抛出
if (index === readyStrategies.length - 1) {
this.logger.local?.error(`[UploadManager] All strategies failed, last error: ${error.message}`)
}
throw error
}
})
}, Promise.reject(new Error('No strategies available')))
}
/**
* 使用指定策略上传
* @private
*/
async _uploadWithStrategy(strategy, strategyName, file, options, startTime) {
const wrappedOptions = {
...options,
onProgress: options.onProgress,
onSuccess: (url, metadata) => {
const duration = Date.now() - startTime
this.logger.local?.info(`[UploadManager] Upload success: ${url} (${duration}ms) using ${strategyName}`)
options.onSuccess?.(url, metadata)
},
onFailure: (error) => {
const duration = Date.now() - startTime
this.logger.local?.error(`[UploadManager] Upload failed: ${error.message} (${duration}ms)`)
options.onFailure?.(error)
}
}
return await strategy.upload(file, wrappedOptions)
}
/**
* 根据文件大小获取策略优先级
*
* 策略:
* - 文件 < 50MB:[STRATEGY_NAMES.UNIAPP, STRATEGY_NAMES.WEBVIEW](优先表单上传)
* - 文件 >= 50MB:[STRATEGY_NAMES.WEBVIEW, STRATEGY_NAMES.UNIAPP](优先 OSS SDK)
*
* @param {number} fileSize - 文件大小(字节)
* @returns {Array<string>} 策略优先级数组
* @private
*/
_getStrategyPriorityByFileSize(fileSize) {
if (fileSize < this.fileSizeThreshold) {
// 小文件:优先使用 UniAppStrategy(表单上传)
return [STRATEGY_NAMES.UNIAPP, STRATEGY_NAMES.WEBVIEW]
} else {
// 大文件:优先使用 WebViewStrategy(OSS SDK 分片上传)
return [STRATEGY_NAMES.WEBVIEW, STRATEGY_NAMES.UNIAPP]
}
}
/**
* 设置文件大小阈值
*
* @param {number} threshold - 阈值(字节)
*/
setFileSizeThreshold(threshold) {
this.fileSizeThreshold = threshold
this.logger.local?.info(`[UploadManager] File size threshold set to: ${threshold} bytes (${(threshold / 1024 / 1024).toFixed(2)} MB)`)
}
/**
* 获取文件大小阈值
*
* @returns {number} 阈值(字节)
*/
getFileSizeThreshold() {
return this.fileSizeThreshold
}
/**
* 取消正在进行的上传
*
* 注意:取消功能依赖于各个策略的实现
*/
cancel() {
this.logger.local?.info('[UploadManager] Cancel requested')
// 尝试取消所有策略(因为不知道哪个策略正在上传)
this.strategySelector.getAllStrategies().forEach(strategy => {
try {
strategy.cancel()
} catch (error) {
// 忽略取消错误
}
})
}
/**
* 获取最后一次上传使用的策略名称
*
* @returns {string} 策略名称
*/
getCurrentStrategyName() {
return this.lastUsedStrategy
}
/**
* 初始化 WebView 策略
*
* 必须在使用 WebView 策略前调用
* 会自动监听 webview_ready 信号
*
* @deprecated 使用构造函数的 webview 选项或 setWebViewConfig() 方法
* @param {Object} webviewRef - WebView 组件引用
* @param {Object} vueContext - Vue 组件实例
*/
initializeWebViewStrategy(webviewRef, vueContext) {
this.logger.local?.warn('[UploadManager] initializeWebViewStrategy() 已废弃,请使用构造函数的 webview 选项或 setWebViewConfig() 方法')
this.setWebViewConfig(webviewRef, vueContext)
}
/**
* 处理来自 WebView 的消息
*
* 自动处理 webview_ready 信号和上传回调
*
* @param {Object} event - WebView message 事件
* @returns {boolean} 是否处理了消息
*/
handleWebViewMessage(event) {
const data = event?.detail?.data?.[0]
if (!data) {
this.logger.local?.warn('[UploadManager] WebView 消息数据为空')
return false
}
const webviewStrategy = this.strategySelector.getStrategy(STRATEGY_NAMES.WEBVIEW)
if (!webviewStrategy) {
this.logger.local?.error('[UploadManager] WebView 策略未找到')
return false
}
// 处理消息
webviewStrategy.handleMessage(data)
// 如果是 webview_ready 信号,检查是否所有策略都已就绪
if (data.action === 'webview_ready') {
this._checkAndResolveReady()
}
return true
}
/**
* 检查并解析就绪状态
* @private
*/
_checkAndResolveReady() {
// 如果已经就绪,不再重复处理
if (this._isReady) {
return
}
// 检查所有策略是否都已就绪
if (this.areAllStrategiesReady()) {
this._isReady = true
// 解析 Promise
if (this._readyResolve) {
this._readyResolve()
}
}
}
/**
* 等待所有策略就绪
*
* 返回一个 Promise,当所有策略都就绪时 resolve
* 如果已经就绪,立即 resolve
*
* @returns {Promise<void>}
*
* @example
* // 使用 await
* await uploadManager.ready()
* console.log('所有策略已就绪')
*
* @example
* // 使用 then
* uploadManager.ready().then(() => {
* console.log('所有策略已就绪')
* })
*/
ready() {
return this._readyPromise
}
/**
* 检查所有策略是否已就绪
*
* @returns {boolean} 是否所有支持的策略都已就绪
*/
areAllStrategiesReady() {
const allStrategies = this.strategySelector.getAllStrategies()
return allStrategies.every(strategy => {
const isSupported = strategy.isSupported()
const isReady = strategy.isReady()
// 不支持的策略不影响就绪状态
if (!isSupported) {
return true
}
return isReady
})
}
/**
* 检查是否已就绪(同步方法)
*
* @returns {boolean} 是否已就绪
*/
isReady() {
return this._isReady
}
}
// 导出单例
let instance = null
/**
* 获取 UploadManager 单例
*
* @param {Object} options - 初始化选项
* @param {Object} [options.webview] - WebView 配置
* @param {Object} [options.webview.webviewRef] - WebView 组件引用
* @param {Object} [options.webview.vueContext] - Vue 组件实例
* @returns {UploadManager}
*/
export function getUploadManager(options = {}) {
if (!instance) {
instance = new UploadManager(options)
} else if (options.webview) {
// 如果已经有实例,但传入了新的 WebView 配置,更新配置
instance.setWebViewConfig(options.webview.webviewRef, options.webview.vueContext)
}
return instance
}
export default UploadManager
/*
* @Author: AI Assistant
* @Date: 2025-01-28
* @Description: 分片管理器 - 处理大文件分片上传和断点续传
* @Feature: oss-upload-refactor
*/
/**
* ChunkManager - 分片上传和断点续传管理器
*
* 注意:当前未使用此管理器
*
* 原因:
* 1. OSS 表单上传(PostObject)不支持分片上传
* 2. uni.uploadFile 只能上传完整文件,不能上传文件的一部分
* 3. 真正的分片上传需要使用 OSS SDK 或 REST API
*
* 如果需要分片上传,请使用 WebViewStrategy(OSS SDK)
*
* 功能(保留用于未来扩展):
* 1. 判断文件是否需要分片上传
* 2. 根据文件大小动态计算最优分片大小
* 3. 执行分片上传流程
* 4. 保存和恢复上传检查点(断点续传)
* 5. 清理过期检查点
*
* 设计原则:
* - 所有上传策略共享此逻辑,避免代码重复
* - 使用 LocalStorage 持久化检查点数据
* - 支持断点续传,提高大文件上传可靠性
*/
class ChunkManager {
constructor() {
/**
* 基础分片大小(用作降级)
* @type {number}
*/
this.basePartSize = 1024 // 1KB
/**
* 大文件阈值(超过此大小使用分片上传)
* @type {number}
*
* 注意:当前禁用分片上传
*
* 原因:
* - OSS 表单上传(PostObject)不支持分片上传
* - uni.uploadFile 只能上传完整文件
* - 真正的分片上传需要使用 OSS SDK(WebViewStrategy)
*
* 配置说明:
* - Infinity:禁用分片上传(当前配置)
* - 10 * 1024 * 1024:10MB 阈值(如果启用分片)
* - 100 * 1024:100KB 阈值(测试用)
*/
this.largeFileThreshold = Infinity // 禁用分片上传
/**
* LocalStorage 中存储检查点的键名
* @type {string}
*/
this.checkpointStorage = 'upload_checkpoints'
}
/**
* 判断文件是否应该使用分片上传
*
* @param {Object} file - 文件对象
* @param {number} file.size - 文件大小(字节)
* @returns {boolean} true 表示需要分片上传
*/
shouldUseChunkedUpload(file) {
return file.size > this.largeFileThreshold
}
/**
* 根据文件大小计算最优分片大小
*
* 策略:文件越大,分片越大,减少请求次数
*
* 分片策略(测试环境):
* - > 1MB → 100KB 分片
* - > 500KB → 50KB 分片
* - > 100KB → 20KB 分片
* - 其他 → 20KB 分片(降级)
*
* 分片策略(生产环境):
* - > 1GB → 10MB 分片
* - > 100MB → 5MB 分片
* - > 50MB → 2MB 分片
* - > 10MB → 1MB 分片
* - 其他 → 1MB 分片(降级)
*
* @param {number} fileSize - 文件大小(字节)
* @returns {number} 最优分片大小(字节)
*/
getOptimalPartSize(fileSize) {
const KB = 1024
const MB = 1024 * 1024
// 测试环境:小分片策略
const testStrategies = [
{ threshold: 1 * MB, size: 100 * KB }, // > 1MB → 100KB 分片
{ threshold: 500 * KB, size: 50 * KB }, // > 500KB → 50KB 分片
{ threshold: 100 * KB, size: 20 * KB } // > 100KB → 20KB 分片
]
// 生产环境:大分片策略
const prodStrategies = [
{ threshold: 1 * 1024 * MB, size: 10 * MB }, // > 1GB → 10MB 分片
{ threshold: 100 * MB, size: 5 * MB }, // > 100MB → 5MB 分片
{ threshold: 50 * MB, size: 2 * MB }, // > 50MB → 2MB 分片
{ threshold: 10 * MB, size: 1 * MB } // > 10MB → 1MB 分片
]
// 根据阈值选择策略(100KB 阈值表示测试环境)
const strategies = this.largeFileThreshold === 100 * KB ? testStrategies : prodStrategies
const defaultSize = this.largeFileThreshold === 100 * KB ? 20 * KB : 1 * MB
// 找到第一个匹配的策略
for (const { threshold, size } of strategies) {
if (fileSize > threshold) {
return size
}
}
// 降级到默认分片大小
return defaultSize
return this.basePartSize * 1024
}
/**
* 计算文件的分片信息
*
* @param {Object} file - 文件对象
* @param {number} file.size - 文件大小(字节)
* @returns {Array<Object>} 分片信息数组
*
* 返回格式:
* [{
* chunkNumber: 1, // 分片编号(从 1 开始)
* start: 0, // 起始字节位置
* end: 5242880, // 结束字节位置
* size: 5242880, // 分片大小
* totalChunks: 10, // 总分片数
* chunkSize: 5242880 // 分片大小(用于参考)
* }, ...]
*/
calculateChunks(file) {
const chunkSize = this.getOptimalPartSize(file.size)
const totalChunks = Math.ceil(file.size / chunkSize)
const chunks = []
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize
const end = Math.min(start + chunkSize, file.size)
chunks.push({
chunkNumber: i + 1,
start,
end,
size: end - start,
totalChunks,
chunkSize
})
}
return chunks
}
/**
* 获取分片上传的上下文信息
*
* 用于策略自己实现分片上传逻辑
*
* @param {Object} file - 文件对象
* @returns {Object} 分片上传上下文
*
* 返回格式:
* {
* uploadId: string, // 唯一的上传 ID
* chunks: Array<Object>, // 分片信息数组
* checkpoint: Object|null, // 已有检查点(如果存在)
* uploadedChunks: Array<number>, // 已上传的分片编号
* uploadedParts: Array<Object> // 已上传的分片信息
* }
*/
async getChunkedUploadContext(file) {
const uploadId = this.generateUploadId(file)
const chunks = this.calculateChunks(file)
// 加载已有检查点(断点续传)
const checkpoint = await this.loadCheckpoint(uploadId)
const uploadedChunks = checkpoint?.uploadedChunks || []
const uploadedParts = checkpoint?.uploadedParts || []
return {
uploadId,
chunks,
checkpoint,
uploadedChunks,
uploadedParts
}
}
/**
* 更新分片上传进度
*
* 由策略在每个分片上传完成后调用
*
* @param {string} uploadId - 上传 ID
* @param {Object} file - 文件对象
* @param {number} chunkNumber - 分片编号
* @param {string} eTag - 分片 ETag
* @param {Array<number>} uploadedChunks - 已上传的分片编号数组
* @param {Array<Object>} uploadedParts - 已上传的分片信息数组
* @param {number} totalChunks - 总分片数
*/
async updateChunkProgress(uploadId, file, chunkNumber, eTag, uploadedChunks, uploadedParts, totalChunks) {
// 保存检查点(用于断点续传)
await this.saveCheckpoint(uploadId, {
uploadId,
fileName: file.name,
uploadedChunks,
uploadedParts,
totalChunks
})
}
/**
* 生成唯一的上传 ID
*
* 格式:{fileName}_{fileSize}_{timestamp}_{random}
*
* @param {Object} file - 文件对象
* @param {string} file.name - 文件名
* @param {number} file.size - 文件大小
* @returns {string} 唯一的上传 ID
*/
generateUploadId(file) {
const timestamp = Date.now()
const random = Math.random().toString(36).substr(2, 9)
return `${file.name}_${file.size}_${timestamp}_${random}`
}
/**
* 保存检查点到 LocalStorage
*
* @param {string} uploadId - 上传 ID
* @param {Object} checkpoint - 检查点数据
* @param {string} checkpoint.uploadId - 上传 ID
* @param {string} checkpoint.fileName - 文件名
* @param {Array<number>} checkpoint.uploadedChunks - 已上传的分片编号
* @param {Array<Object>} checkpoint.uploadedParts - 已上传的分片信息
* @param {number} checkpoint.totalChunks - 总分片数
*/
async saveCheckpoint(uploadId, checkpoint) {
try {
const checkpoints = this.loadAllCheckpoints()
checkpoints[uploadId] = {
...checkpoint,
timestamp: Date.now()
}
uni.setStorageSync(this.checkpointStorage, JSON.stringify(checkpoints))
} catch (error) {
console.warn('[ChunkManager] Failed to save checkpoint:', error)
}
}
/**
* 从 LocalStorage 加载检查点
*
* @param {string} uploadId - 上传 ID
* @returns {Object|null} 检查点数据,不存在时返回 null
*/
async loadCheckpoint(uploadId) {
try {
const checkpoints = this.loadAllCheckpoints()
return checkpoints[uploadId] || null
} catch (error) {
console.warn('[ChunkManager] Failed to load checkpoint:', error)
return null
}
}
/**
* 加载所有检查点
*
* @returns {Object} 所有检查点数据(键为 uploadId)
*/
loadAllCheckpoints() {
try {
const data = uni.getStorageSync(this.checkpointStorage)
return data ? JSON.parse(data) : {}
} catch (error) {
return {}
}
}
/**
* 清除检查点
*
* @param {string} uploadId - 上传 ID
*/
async clearCheckpoint(uploadId) {
try {
const checkpoints = this.loadAllCheckpoints()
delete checkpoints[uploadId]
uni.setStorageSync(this.checkpointStorage, JSON.stringify(checkpoints))
} catch (error) {
console.warn('[ChunkManager] Failed to clear checkpoint:', error)
}
}
/**
* 完成分片上传
*
* 注意:OSS 表单上传(PostObject)不支持真正的分片上传
* 当前实现的"分片"只是逻辑分片,用于:
* 1. 显示上传进度
* 2. 支持断点续传(重新上传时跳过已上传的分片)
*
* 如果需要真正的 OSS 分片上传(Multipart Upload),需要:
* 1. 使用 OSS SDK(在 WebView 中)
* 2. 或者调用 OSS REST API(需要复杂的签名)
*
* @param {string} uploadId - 上传 ID
* @param {Object} file - 文件对象
* @param {Array<Object>} parts - 已上传的分片信息
* @param {Object} ossConfig - OSS 配置
* @returns {Promise<string>} 文件 URL
*/
async completeChunkedUpload(uploadId, file, parts, ossConfig) {
// 对于表单上传,每个分片都是独立上传的完整文件
// 这里只需要返回最后一个分片的 URL
// 实际上,所有分片都上传到同一个 OSS key,后面的会覆盖前面的
// 构造文件 URL
const ossKey = parts[0]?.ossKey || `uploads/${file.name}`
const fileUrl = `${ossConfig.endpoint}/${ossKey}`
uni.$logger?.local?.info(`[ChunkManager] All chunks uploaded, file URL: ${fileUrl}`)
return fileUrl
}
/**
* 清理过期检查点(超过 24 小时)
*
* 建议在应用启动时调用一次
*/
async cleanupOldCheckpoints() {
try {
const checkpoints = this.loadAllCheckpoints()
const now = Date.now()
const maxAge = 24 * 60 * 60 * 1000 // 24 小时
Object.keys(checkpoints).forEach(uploadId => {
const checkpoint = checkpoints[uploadId]
if (now - checkpoint.timestamp > maxAge) {
delete checkpoints[uploadId]
}
})
uni.setStorageSync(this.checkpointStorage, JSON.stringify(checkpoints))
} catch (error) {
console.warn('[ChunkManager] Failed to cleanup checkpoints:', error)
}
}
}
// 导出单例
export default ChunkManager
/*
* @Author: AI Assistant
* @Date: 2025-01-28
* @Description: 配置管理器 - 管理上传策略配置(简化版)
* @Feature: oss-upload-refactor
*/
/**
* 配置管理器(简化版)
*
* 功能:
* 1. 管理上传配置
* 2. 支持运行时配置更新
*
* 简化说明:
* - 移除了复杂的 LocalStorage 持久化
* - 移除了未使用的方法
* - 使用内存配置,简单高效
*/
class ConfigurationManager {
constructor() {
/**
* 当前配置
* @type {Object}
*/
this.config = {
strategyPriority: [STRATEGY_NAMES.UNIAPP, STRATEGY_NAMES.WEBVIEW], // 策略优先级
retryConfig: {
maxRetries: 3, // 最大重试次数
retryDelay: 1000 // 重试延迟(毫秒)
}
}
}
/**
* 获取当前配置
*
* @returns {Object} 配置对象
*/
getCurrentConfig() {
return this.config
}
/**
* 更新配置
*
* @param {Object} newConfig - 新配置(部分或全部)
*/
async updateConfig(newConfig) {
this.config = {
...this.config,
...newConfig
}
uni.$logger?.local?.info('[ConfigurationManager] Config updated')
}
/**
* 获取首选上传策略
*
* @returns {Promise<string>} 策略名称
*/
async getPreferredStrategy() {
return this.config.strategyPriority[0]
}
}
// 导出管理器类
export default ConfigurationManager
/*
* @Author: AI Assistant
* @Date: 2025-01-28
* @Description: 重试管理器 - 处理上传失败的自动重试逻辑
* @Feature: oss-upload-refactor
*/
/**
* 重试管理器
*
* 功能:
* 1. 执行带重试逻辑的异步函数
* 2. 支持指数退避策略
* 3. 支持自定义重试条件
* 4. 支持重试回调
*
* 设计原则:
* - 通用性:可用于任何异步函数的重试
* - 灵活性:支持自定义重试策略和条件
*/
class RetryManager {
/**
* 执行带重试逻辑的函数
*
* @param {Function} fn - 要执行的异步函数
* @param {Object} options - 重试选项
* @param {number} [options.maxRetries=3] - 最大重试次数
* @param {Function|number} [options.retryDelay] - 重试延迟(毫秒)或延迟计算函数
* @param {Function} [options.shouldRetry] - 判断是否应该重试的函数
* @param {Function} [options.onRetry] - 重试时的回调函数
* @returns {Promise} 函数执行结果
* @throws {Error} 所有重试都失败后抛出最后一次的错误
*
* @example
* // 基本用法
* await retryManager.executeWithRetry(
* () => uploadFile(file),
* { maxRetries: 3 }
* )
*
* @example
* // 自定义重试策略
* await retryManager.executeWithRetry(
* () => uploadFile(file),
* {
* maxRetries: 3,
* retryDelay: (attempt) => Math.pow(2, attempt) * 1000, // 指数退避
* shouldRetry: (error) => !error.message.includes('cancelled'),
* onRetry: (attempt, error) => console.log(`Retry ${attempt}: ${error.message}`)
* }
* )
*/
async executeWithRetry(fn, options = {}) {
const {
maxRetries = 3,
retryDelay = (attempt) => attempt * 1000,
shouldRetry = () => true,
onRetry = () => {}
} = options
let lastError
// 尝试执行函数(初次 + 重试)
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
// 执行函数
const result = await fn()
// 成功,返回结果
if (attempt > 0) {
uni.$logger?.local?.info(`[RetryManager] Success after ${attempt} retries`)
}
return result
} catch (error) {
lastError = error
// 判断是否应该重试
const isLastAttempt = attempt >= maxRetries
const canRetry = shouldRetry(error)
if (!isLastAttempt && canRetry) {
// 计算延迟时间
const delay = typeof retryDelay === 'function'
? retryDelay(attempt)
: retryDelay
// 调用重试回调
onRetry(attempt + 1, error)
uni.$logger?.local?.warn(`[RetryManager] Retry ${attempt + 1}/${maxRetries} after ${delay}ms: ${error.message}`)
// 等待后重试
await this.sleep(delay)
} else {
// 不再重试,跳出循环
if (isLastAttempt) {
uni.$logger?.local?.error(`[RetryManager] All ${maxRetries} retries exhausted`)
} else {
uni.$logger?.local?.error(`[RetryManager] Retry skipped: ${error.message}`)
}
break
}
}
}
// 所有重试都失败,抛出最后一次的错误
throw lastError
}
/**
* 延迟执行
*
* @param {number} ms - 延迟时间(毫秒)
* @returns {Promise<void>}
*/
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* 创建指数退避延迟函数
*
* @param {number} baseDelay - 基础延迟时间(毫秒)
* @param {number} maxDelay - 最大延迟时间(毫秒)
* @returns {Function} 延迟计算函数
*
* @example
* const retryDelay = RetryManager.createExponentialBackoff(1000, 10000)
* // attempt 0: 1000ms
* // attempt 1: 2000ms
* // attempt 2: 4000ms
* // attempt 3: 8000ms
* // attempt 4: 10000ms (capped)
*/
static createExponentialBackoff(baseDelay = 1000, maxDelay = 60000) {
return (attempt) => {
const delay = baseDelay * Math.pow(2, attempt)
return Math.min(delay, maxDelay)
}
}
/**
* 创建线性延迟函数
*
* @param {number} baseDelay - 基础延迟时间(毫秒)
* @returns {Function} 延迟计算函数
*
* @example
* const retryDelay = RetryManager.createLinearBackoff(1000)
* // attempt 0: 1000ms
* // attempt 1: 2000ms
* // attempt 2: 3000ms
*/
static createLinearBackoff(baseDelay = 1000) {
return (attempt) => baseDelay * (attempt + 1)
}
/**
* 创建固定延迟函数
*
* @param {number} delay - 固定延迟时间(毫秒)
* @returns {Function} 延迟计算函数
*
* @example
* const retryDelay = RetryManager.createFixedDelay(2000)
* // 每次重试都延迟 2000ms
*/
static createFixedDelay(delay = 1000) {
return () => delay
}
}
// 导出管理器类
export default RetryManager
/*
* @Author: AI Assistant
* @Date: 2025-01-28
* @Description: 策略选择器 - 管理上传策略的注册和选择(简化版)
* @Feature: oss-upload-refactor
*/
import UploadStrategy from '../strategies/UploadStrategy.js'
/**
* 策略选择器(简化版)
*
* 功能:
* 1. 注册上传策略
* 2. 根据名称获取策略
* 3. 获取所有已注册的策略
*
* 简化说明:
* - 移除了未使用的方法
* - 保留核心功能
*/
class StrategySelector {
constructor() {
/**
* 策略 Map
* key: 策略名称, value: 策略实例
* @type {Map<string, UploadStrategy>}
*/
this.strategies = new Map()
}
/**
* 注册策略
*
* @param {UploadStrategy} strategy - 策略实例
* @throws {Error} 如果策略不是 UploadStrategy 的实例
*/
register(strategy) {
if (!(strategy instanceof UploadStrategy)) {
throw new Error('Strategy must extend UploadStrategy')
}
const name = strategy.getName()
this.strategies.set(name, strategy)
}
/**
* 根据名称获取策略
*
* @param {string} name - 策略名称 ('webview', 'uniapp')
* @returns {UploadStrategy|null} 策略实例,不存在时返回 null
*/
getStrategy(name) {
return this.strategies.get(name) || null
}
/**
* 获取所有已注册的策略
*
* @returns {Array<UploadStrategy>} 策略实例数组
*/
getAllStrategies() {
return Array.from(this.strategies.values())
}
}
// 导出选择器类
export default StrategySelector
/*
* @Descripttion: 上传管理器常量定义
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-30
*/
/**
* 上传策略名称常量
*
* 统一管理所有策略名称,避免硬编码导致的不一致问题
*/
export const STRATEGY_NAMES = Object.freeze({
/**
* WebView 策略
* 使用 WebView 加载 H5 页面,调用 aliyun-oss-sdk 上传
*/
WEBVIEW: '[webview.oss.sdk]',
/**
* UniApp 策略
* 使用 uni.uploadFile API 进行表单上传
*/
UNIAPP: '[uniapp.uni.uploadFile]',
/**
* 无策略
*/
NONE: 'none'
})
/**
* 文件大小阈值(字节)
*/
export const FILE_SIZE_THRESHOLD = Object.freeze({
/**
* 小文件阈值:50MB
* 小于此大小使用 UniAppStrategy(表单上传)
* 大于等于此大小使用 WebViewStrategy(OSS SDK 分片上传)
*/
SMALL_FILE: 50 * 1024 * 1024 // 50MB
})
/**
* 上传状态常量
*/
export const UPLOAD_STATUS = Object.freeze({
/**
* 等待中
*/
PENDING: 'pending',
/**
* 上传中
*/
UPLOADING: 'uploading',
/**
* 上传成功
*/
SUCCESS: 'success',
/**
* 上传失败
*/
FAILED: 'failed',
/**
* 已取消
*/
CANCELLED: 'cancelled'
})
/**
* WebView 消息类型
*/
export const WEBVIEW_MESSAGE_TYPE = Object.freeze({
/**
* WebView 就绪信号
*/
READY: 'webview_ready',
/**
* 上传进度
*/
PROGRESS: 'upload_progress',
/**
* 上传成功
*/
SUCCESS: 'upload_success',
/**
* 上传失败
*/
ERROR: 'upload_error'
})
/**
* 默认配置
*/
export const DEFAULT_CONFIG = Object.freeze({
/**
* 默认文件大小阈值
*/
FILE_SIZE_THRESHOLD: FILE_SIZE_THRESHOLD.SMALL_FILE,
/**
* 默认超时时间(毫秒)
*/
TIMEOUT: 10 * 60 * 1000, // 10 分钟
/**
* 默认重试次数
*/
MAX_RETRIES: 3,
/**
* 默认分片大小(字节)
*/
CHUNK_SIZE: 5 * 1024 * 1024 // 5MB
})
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:40:13
* @LastEditors: limin
* @LastEditTime: 2026-01-30 01:47:38
* @FilePath: \simgle_app\utils\uploadManager\index.js
*/
import UploadManager, { getUploadManager } from './UploadManager.js'
import WebViewStrategy from './strategies/WebViewStrategy.js'
import UniAppStrategy from './strategies/UniAppStrategy.js'
import UploadStrategy from './strategies/UploadStrategy.js'
import { STRATEGY_NAMES, FILE_SIZE_THRESHOLD, UPLOAD_STATUS, WEBVIEW_MESSAGE_TYPE, DEFAULT_CONFIG } from './constants.js'
// 导出主要类和函数
export {
UploadManager,
getUploadManager,
WebViewStrategy,
UniAppStrategy,
UploadStrategy,
STRATEGY_NAMES,
FILE_SIZE_THRESHOLD,
UPLOAD_STATUS,
WEBVIEW_MESSAGE_TYPE,
DEFAULT_CONFIG
}
// 默认导出单例获取函数
export default getUploadManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:36:49
* @LastEditors: limin
* @LastEditTime: 2026-01-30 01:46:21
* @FilePath: \simgle_app\utils\uploadManager\strategies\NativeStrategy.js
*/
import UploadStrategy from './UploadStrategy.js'
/**
* 原生 Android OSS SDK 上传策略(高性能方案)
*
* 特点:
* 1. 直接调用 Android 原生 OSS SDK
* 2. 性能最优,内存占用最小
* 3. 支持 OSS SDK 内置的 multipart upload 和断点续传
* 4. 仅支持 Android 平台
*
* 依赖:
* - com.aliyun.dpa:oss-android-sdk:2.9.13
*
* 权限:
* - android.permission.INTERNET
* - android.permission.ACCESS_NETWORK_STATE
* - android.permission.READ_EXTERNAL_STORAGE
* - android.permission.WRITE_EXTERNAL_STORAGE
*/
class NativeStrategy extends UploadStrategy {
constructor() {
super()
/**
* OSS 客户端实例
* @type {Object|null}
*/
this.ossClient = null
/**
* 当前上传任务
* @type {Object|null}
*/
this.currentUpload = null
}
/**
* 上传文件
*
* 自动判断是否使用 multipart upload:
* - 小文件(< 10MB):直接上传
* - 大文件(>= 10MB):使用 multipart upload(带断点续传)
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async upload(file, options) {
// 确保 OSS 客户端已初始化
if (!this.ossClient) {
await this.initializeOSSClient(options)
}
// 检查是否需要使用 multipart upload
// 注意:Native SDK 内部处理分片,不使用 ChunkManager
if (this.chunkManager && this.chunkManager.shouldUseChunkedUpload(file)) {
uni.$logger?.local?.info(`[NativeStrategy] Using multipart upload for large file: ${file.name} (${file.size} bytes)`)
return this.uploadMultipart(file, options)
}
// 小文件直接上传
return this.uploadDirect(file, options)
}
/**
* 直接上传文件(小文件)
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async uploadDirect(file, options) {
return new Promise(async (resolve, reject) => {
// #ifdef APP-PLUS
try {
uni.$logger?.local?.info(`[NativeStrategy] Starting direct upload: ${file.name}, size: ${file.size}, path: ${file.path}`)
// 转换文件路径:file:// -> 绝对路径
let filePath = file.path
if (filePath.startsWith('file://')) {
// 移除 file:// 前缀,得到绝对路径
filePath = filePath.replace('file://', '')
uni.$logger?.local?.info(`[NativeStrategy] Converted file path: ${filePath}`)
}
// 验证文件是否存在
const fileExists = await this._checkFileExists(filePath)
if (!fileExists) {
const error = `File not found: ${filePath}`
uni.$logger?.local?.error(`[NativeStrategy] ${error}`)
reject(new Error(error))
return
}
uni.$logger?.local?.info(`[NativeStrategy] File exists, proceeding with upload`)
// 导入 Android 类
const PutObjectRequest = plus.android.importClass('com.alibaba.sdk.android.oss.model.PutObjectRequest')
const OSSProgressCallback = plus.android.importClass('com.alibaba.sdk.android.oss.callback.OSSProgressCallback')
const OSSCompletedCallback = plus.android.importClass('com.alibaba.sdk.android.oss.callback.OSSCompletedCallback')
// 生成 OSS 文件路径
const ossKey = this.generateOSSKey(file.name, options)
uni.$logger?.local?.info(`[NativeStrategy] OSS key: ${ossKey}, bucket: ${options.ossConfig.bucket}`)
// 创建上传请求
const request = new PutObjectRequest(
options.ossConfig.bucket,
ossKey,
filePath // 使用转换后的路径
)
uni.$logger?.local?.info(`[NativeStrategy] Upload request created with path: ${filePath}`)
// 设置进度回调
request.setProgressCallback(
plus.android.implements(OSSProgressCallback, {
onProgress: (request, currentSize, totalSize) => {
const percent = Math.round((currentSize / totalSize) * 100)
uni.$logger?.local?.debug(`[NativeStrategy] Upload progress: ${percent}% (${currentSize}/${totalSize})`)
options.onProgress?.(percent)
}
})
)
uni.$logger?.local?.info(`[NativeStrategy] Starting asyncPutObject...`)
// 添加超时机制(30秒)
const uploadTimeout = setTimeout(() => {
uni.$logger?.local?.error(`[NativeStrategy] Upload timeout after 30 seconds`)
reject(new Error('Upload timeout'))
this.currentUpload = null
}, 30000)
// 执行上传
this.currentUpload = this.ossClient.asyncPutObject(
request,
plus.android.implements(OSSCompletedCallback, {
onSuccess: (request, result) => {
clearTimeout(uploadTimeout) // 清除超时定时器
uni.$logger?.local?.info(`[NativeStrategy] onSuccess callback triggered`)
const fileUrl = `${options.ossConfig.endpoint}/${ossKey}`
const metadata = {
size: file.size,
name: file.name
}
options.onSuccess?.(fileUrl, metadata)
resolve(fileUrl)
this.currentUpload = null
uni.$logger?.local?.info(`[NativeStrategy] Upload success: ${fileUrl}`)
},
onFailure: (request, clientException, serviceException) => {
clearTimeout(uploadTimeout) // 清除超时定时器
uni.$logger?.local?.error(`[NativeStrategy] onFailure callback triggered`)
let errorMessage = 'Upload failed'
let errorCode = 'UNKNOWN_ERROR'
if (clientException) {
const clientMsg = clientException.getMessage()
errorMessage = clientMsg || errorMessage
errorCode = 'CLIENT_ERROR'
uni.$logger?.local?.error(`[NativeStrategy] Client exception: ${clientMsg}`)
}
if (serviceException) {
const serviceMsg = serviceException.getMessage()
const statusCode = serviceException.getStatusCode()
errorMessage = serviceMsg || errorMessage
errorCode = statusCode || errorCode
uni.$logger?.local?.error(`[NativeStrategy] Service exception: ${serviceMsg}, status: ${statusCode}`)
}
const error = {
code: errorCode,
message: errorMessage
}
options.onFailure?.(error)
reject(new Error(error.message))
this.currentUpload = null
}
})
)
uni.$logger?.local?.info(`[NativeStrategy] asyncPutObject called, waiting for callback...`)
} catch (e) {
uni.$logger?.local?.error(`[NativeStrategy] Exception in uploadDirect: ${e.message}`)
uni.$logger?.local?.error(`[NativeStrategy] Stack: ${e.stack}`)
reject(new Error(`Native upload failed: ${e.message}`))
}
// #endif
// #ifndef APP-PLUS
reject(new Error('Native strategy only supported on APP-PLUS'))
// #endif
})
}
/**
* Multipart 上传(大文件,带断点续传)
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async uploadMultipart(file, options) {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
try {
// 导入 Android 类
const MultipartUploadRequest = plus.android.importClass('com.alibaba.sdk.android.oss.model.MultipartUploadRequest')
const OSSProgressCallback = plus.android.importClass('com.alibaba.sdk.android.oss.callback.OSSProgressCallback')
const OSSCompletedCallback = plus.android.importClass('com.alibaba.sdk.android.oss.callback.OSSCompletedCallback')
// 生成 OSS 文件路径
const ossKey = this.generateOSSKey(file.name, options)
// 创建 multipart 上传请求
const request = new MultipartUploadRequest(
options.ossConfig.bucket,
ossKey,
file.path
)
// 设置分片大小(5MB)- 匹配 ChunkManager 的策略
request.setPartSize(5 * 1024 * 1024)
// 启用断点续传(checkpoint 文件用于恢复)
const checkpointDir = plus.io.convertLocalFileSystemURL('_doc/oss_checkpoint/')
request.setCheckpointDir(checkpointDir)
// 设置进度回调
request.setProgressCallback(
plus.android.implements(OSSProgressCallback, {
onProgress: (request, currentSize, totalSize) => {
const percent = Math.round((currentSize / totalSize) * 100)
options.onProgress?.(percent)
}
})
)
// 执行 multipart 上传
this.currentUpload = this.ossClient.asyncMultipartUpload(
request,
plus.android.implements(OSSCompletedCallback, {
onSuccess: (request, result) => {
const fileUrl = `${options.ossConfig.endpoint}/${ossKey}`
const metadata = {
size: file.size,
name: file.name
}
options.onSuccess?.(fileUrl, metadata)
resolve(fileUrl)
this.currentUpload = null
uni.$logger?.local?.info(`[NativeStrategy] Multipart upload success: ${fileUrl}`)
},
onFailure: (request, clientException, serviceException) => {
const error = {
code: serviceException?.getStatusCode() || 'CLIENT_ERROR',
message: serviceException?.getMessage() || clientException?.getMessage() || 'Multipart upload failed'
}
options.onFailure?.(error)
reject(new Error(error.message))
this.currentUpload = null
uni.$logger?.local?.error(`[NativeStrategy] Multipart upload failed: ${error.message}`)
}
})
)
} catch (e) {
reject(new Error(`Native multipart upload failed: ${e.message}`))
}
// #endif
// #ifndef APP-PLUS
reject(new Error('Native strategy only supported on APP-PLUS'))
// #endif
})
}
/**
* 上传分片(Native 策略不使用)
*
* Native 策略使用 OSS SDK 内置的 multipart upload
* 此方法不应被调用
*
* @throws {Error} 不支持此方法
*/
async uploadChunk(file, chunkInfo, options) {
throw new Error('NativeStrategy uses built-in multipart upload, uploadChunk should not be called directly')
}
/**
* 初始化 OSS 客户端
*
* @param {Object} options - 上传选项
*/
async initializeOSSClient(options) {
// #ifdef APP-PLUS
try {
// 导入 Android 类
const OSSClient = plus.android.importClass('com.alibaba.sdk.android.oss.OSSClient')
const ClientConfiguration = plus.android.importClass('com.alibaba.sdk.android.oss.ClientConfiguration')
const OSSPlainTextAKSKCredentialProvider = plus.android.importClass('com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider')
// 获取 OSS 配置
const config = await this.getOSSConfig(options)
// 创建凭证提供者
const credentialProvider = new OSSPlainTextAKSKCredentialProvider(
config.accessKeyId,
config.accessKeySecret
)
// 创建客户端配置
const clientConfig = new ClientConfiguration()
clientConfig.setConnectionTimeout(15000) // 连接超时 15 秒
clientConfig.setSocketTimeout(15000) // Socket 超时 15 秒
clientConfig.setMaxConcurrentRequest(5) // 最大并发请求数
clientConfig.setMaxErrorRetry(2) // 最大错误重试次数
// 创建 OSS 客户端
this.ossClient = new OSSClient(
plus.android.runtimeMainActivity(),
config.endpoint,
credentialProvider,
clientConfig
)
uni.$logger?.local?.info('[NativeStrategy] OSS client initialized')
} catch (e) {
uni.$logger?.local?.error(`[NativeStrategy] Failed to initialize OSS client: ${e.message}`)
throw new Error(`Failed to initialize OSS client: ${e.message}`)
}
// #endif
// #ifndef APP-PLUS
throw new Error('Native strategy only supported on APP-PLUS')
// #endif
}
/**
* 检查文件是否存在
* @private
* @param {string} filePath - 文件路径
* @returns {Promise<boolean>}
*/
async _checkFileExists(filePath) {
return new Promise((resolve) => {
// #ifdef APP-PLUS
try {
plus.io.resolveLocalFileSystemURL(
filePath,
() => resolve(true),
() => resolve(false)
)
} catch (e) {
resolve(false)
}
// #endif
// #ifndef APP-PLUS
resolve(false)
// #endif
})
}
/**
* 获取 OSS 配置
*
* @param {Object} options - 上传选项
* @returns {Promise<Object>} OSS 配置
*/
async getOSSConfig(options) {
// 如果 options 中已提供 ossConfig,直接使用
if (options.ossConfig) {
return options.ossConfig
}
// 否则从后端获取
return new Promise((resolve, reject) => {
uni.request({
url: '/api/oss/config',
method: 'GET',
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(new Error('Failed to get OSS config'))
}
},
fail: (err) => {
reject(new Error(err.errMsg))
}
})
})
}
/**
* 取消上传
*/
cancel() {
if (this.currentUpload) {
// #ifdef APP-PLUS
try {
this.currentUpload.cancel()
uni.$logger?.local?.info('[NativeStrategy] Upload cancelled')
} catch (e) {
uni.$logger?.local?.warn(`[NativeStrategy] Failed to cancel upload: ${e.message}`)
}
// #endif
this.currentUpload = null
}
}
/**
* 检查是否支持
*
* 仅在 Android 平台且 OSS SDK 可用时支持
*
* @returns {boolean} 是否支持
*/
isSupported() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
try {
// 尝试导入 OSS SDK 类
plus.android.importClass('com.alibaba.sdk.android.oss.OSSClient')
return true
} catch (e) {
uni.$logger?.local?.warn('[NativeStrategy] OSS SDK not available')
return false
}
}
// #endif
return false
}
/**
* 获取策略名称
*
* @returns {string} 'native'
*/
getName() {
return 'native'
}
/**
* 生成 OSS 文件路径
*
* 直接使用传入的文件名(已做唯一处理)
* 格式:uploads/{fileName}
*
* @param {string} fileName - 文件名(已做唯一处理)
* @param {Object} options - 上传选项
* @returns {string} OSS 文件路径
*/
generateOSSKey(fileName, options) {
const folder = options.ossFolder || 'uploads'
return `${folder}/${fileName}`
}
}
// 导出策略类
export default NativeStrategy
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:36:49
* @LastEditors: limin
* @LastEditTime: 2026-02-06 19:07:55
* @FilePath: \gl_tape\utils\uploadManager\strategies\UniAppStrategy.js
*/
import UploadStrategy from './UploadStrategy.js'
// 导入加密库(只加载一次)
const base64 = require('@/utils/ossUploadFile/base64.js')
const Crypto = require('@/utils/ossUploadFile/crypto.js')
import { STRATEGY_NAMES } from '../constants.js'
/**
* UniApp 上传策略(推荐方案)
*
* 特点:
* 1. 使用 uni.uploadFile API 直接上传到 OSS
* 2. 无需 WebView,性能更好,内存占用更小
* 3. 支持进度回调
* 4. 统一的分片上传流程(小文件分片数为 1)
* 5. 支持取消上传
*/
class UniAppStrategy extends UploadStrategy {
ossFolder = 'quality/'
constructor() {
super()
/**
* 当前上传任务
* @type {Object|null}
*/
this.uploadTask = null
}
/**
* 上传文件
*
* 使用 uni.uploadFile + OSS 表单上传(PostObject)
*
* 注意:OSS 表单上传不支持分片上传,每次上传整个文件
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async upload(file, options) {
const { ossConfig } = options
if (!ossConfig) {
throw new Error('OSS config not provided')
}
// 生成 OSS 文件路径
const ossKey = this.generateOSSKey(file.name, options)
const fileUrl = `${ossConfig.endpoint}/${ossKey}`
// uni.$logger?.local?.info(`[UniAppStrategy] Starting upload: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB) to ${ossKey}`)
// 直接上传整个文件
return this.uploadFile(file, ossKey, fileUrl, ossConfig, options)
}
/**
* 上传文件到 OSS
*
* 使用 uni.uploadFile + OSS 表单上传(PostObject)
*
* @param {Object} file - 文件对象
* @param {string} ossKey - OSS 文件路径
* @param {string} fileUrl - 完整文件 URL
* @param {Object} ossConfig - OSS 配置
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async uploadFile(file, ossKey, fileUrl, ossConfig, options) {
return new Promise((resolve, reject) => {
// 生成 policy 和 signature
const { policy, signature } = this._generatePolicy(ossKey, ossConfig)
// 构造上传表单数据
const formData = {
key: ossKey,
OSSAccessKeyId: ossConfig.accessKeyId,
policy: policy,
signature: signature,
'success_action_status': '200'
}
// 如果有 STS Token,添加到表单
if (ossConfig.stsToken) {
formData['x-oss-security-token'] = ossConfig.stsToken
}
console.log('formData', formData,ossConfig)
// 创建上传任务
this.uploadTask = uni.uploadFile({
url: ossConfig.endpoint,
filePath: file.path,
name: 'file',
formData: formData,
success: (res) => {
if (res.statusCode === 200 || res.statusCode === 204) {
// uni.$logger?.local?.info(`[UniAppStrategy] Upload success: ${fileUrl}`)
options.onSuccess?.(fileUrl, { size: file.size, name: file.name })
resolve(fileUrl)
} else {
const error = new Error(`Upload failed with status ${res.statusCode}`)
uni.$logger?.local?.error(`[UniAppStrategy] ${error.message}`)
options.onFailure?.(error)
reject(error)
}
},
fail: (err) => {
const error = new Error(err.errMsg || 'Upload failed')
uni.$logger?.local?.error(`[UniAppStrategy] ${error.message}`)
options.onFailure?.(error)
reject(error)
}
})
// 监听上传进度
this.uploadTask.onProgressUpdate((res) => {
options.onProgress?.(res.progress)
})
})
}
/**
* 生成 OSS Policy 和 Signature
*
* OSS PostObject 表单上传的安全验证机制:
* 1. Policy:定义上传权限和限制(过期时间、文件大小、bucket 等)
* 2. Signature:使用 AccessKeySecret 对 policy 进行 HMAC-SHA1 签名
* 3. OSS 服务器验证签名,确保请求来自授权用户
*
* @param {string} ossKey - OSS 文件路径
* @param {Object} ossConfig - OSS 配置
* @returns {Object} { policy, signature }
* @private
*/
_generatePolicy(ossKey, ossConfig) {
// 生成过期时间(1小时后)
const expiration = new Date(Date.now() + 3600 * 1000).toISOString()
// 构造 policy(定义上传规则)
const policyObj = {
expiration: expiration,
conditions: [
{ bucket: ossConfig.bucket },
['eq', '$key', ossKey],
['content-length-range', 0, 1048576000] // 最大 1GB
]
}
// Base64 编码 policy
const policyBase64 = base64.encode(JSON.stringify(policyObj))
// HMAC-SHA1 签名(使用 AccessKeySecret)
const bytes = Crypto.HmacSHA1(policyBase64, ossConfig.accessKeySecret)
const signature = Crypto.enc.Base64.stringify(bytes)
return {
policy: policyBase64,
signature: signature
}
}
/**
* 生成 OSS 文件路径
*
* 直接使用传入的文件名(已做唯一处理)
* 格式:uploads/{fileName}
*
* @param {string} fileName - 文件名(已做唯一处理)
* @param {Object} options - 上传选项
* @returns {string} OSS 文件路径
*/
generateOSSKey(fileName, options) {
const folder = options.ossFolder || this.ossFolder
return `${folder}/${fileName}`
}
/**
* 取消上传
*/
cancel() {
if (this.uploadTask) {
this.uploadTask.abort()
this.uploadTask = null
uni.$logger?.local?.info('[UniAppStrategy] Upload cancelled')
}
}
/**
* 检查是否支持
*
* @returns {boolean} 是否支持
*/
isSupported() {
return typeof uni !== 'undefined' && typeof uni.uploadFile === 'function'
}
/**
* 获取策略名称
*
* @returns {string} 'uniapp'
*/
getName() {
return STRATEGY_NAMES.UNIAPP
}
}
// 导出策略类
export default UniAppStrategy
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:33:18
* @LastEditors: limin
* @LastEditTime: 2026-01-30 19:24:17
* @FilePath: \gl_tape\utils\uploadManager\strategies\UploadStrategy.js
*/
/**
* 上传策略基类
* 所有具体的上传策略(WebView、UniApp)都必须继承此类并实现其抽象方法
*
* 设计原则:
* 1. 开闭原则:对扩展开放,对修改关闭
* 2. 依赖倒置:依赖抽象而非具体实现
* 3. 接口隔离:提供最小化的接口定义
*/
class UploadStrategy {
constructor() {
// 策略基类不需要额外的属性
}
/**
* 上传文件到 OSS
*
* @param {Object} file - 文件对象
* @param {string} file.path - 文件路径 (例如: 'file:///storage/...')
* @param {string} file.name - 文件名 (例如: 'audio.mp3')
* @param {number} file.size - 文件大小(字节)
* @param {string} [file.type] - MIME 类型(可选)
*
* @param {Object} options - 上传选项
* @param {Function} options.onProgress - 进度回调 (percent: 0-100)
* @param {Function} options.onSuccess - 成功回调 (url: string, metadata: Object)
* @param {Function} options.onFailure - 失败回调 (error: Object)
* @param {Object} [options.ossConfig] - OSS 配置(策略特定)
* @param {string} [options.ossConfig.bucket] - OSS bucket 名称
* @param {string} [options.ossConfig.endpoint] - OSS endpoint
* @param {string} [options.ossConfig.accessKeyId] - OSS AccessKeyId
* @param {string} [options.ossConfig.accessKeySecret] - OSS AccessKeySecret
* @param {string} [options.ossConfig.stsToken] - OSS STS Token(可选)
*
* @returns {Promise<string>} OSS 文件 URL
* @throws {Error} 子类必须实现此方法
*/
async upload(file, options) {
throw new Error(`upload() must be implemented by ${this.constructor.name}`)
}
/**
* 取消正在进行的上传
*
* 实现要求:
* 1. 立即停止上传操作
* 2. 清理相关资源(uploadTask、pending promises 等)
* 3. 调用 onFailure 回调,传入取消错误
*
* @throws {Error} 子类必须实现此方法
*/
cancel() {
throw new Error(`cancel() must be implemented by ${this.constructor.name}`)
}
/**
* 检查当前环境是否支持该策略
*
* 示例:
* - WebViewStrategy: 总是返回 true(作为兜底方案)
* - UniAppStrategy: 检查 uni.uploadFile 是否可用
*
* @returns {boolean} true 表示支持,false 表示不支持
* @throws {Error} 子类必须实现此方法
*/
isSupported() {
throw new Error(`isSupported() must be implemented by ${this.constructor.name}`)
}
/**
* 检查策略是否已就绪(可以立即执行上传)
*
* 示例:
* - WebViewStrategy: 检查 WebView 是否已收到 webview_ready 信号
* - UniAppStrategy: 总是返回 true(无需初始化)
*
* @returns {boolean} true 表示已就绪,false 表示未就绪
*/
isReady() {
// 默认实现:支持即就绪
return this.isSupported()
}
/**
* 获取策略名称(用于日志记录和配置)
*
* 标准名称:
* - STRATEGY_NAMES.WEBVIEW: WebView 策略
* - STRATEGY_NAMES.UNIAPP: UniApp 策略
*
* @returns {string} 策略名称
* @throws {Error} 子类必须实现此方法
*/
getName() {
throw new Error(`getName() must be implemented by ${this.constructor.name}`)
}
}
// 导出基类
export default UploadStrategy
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-28 15:35:18
* @LastEditors: limin
* @LastEditTime: 2026-01-30 01:47:11
* @FilePath: \simgle_app\utils\uploadManager\strategies\WebViewStrategy.js
*/
import UploadStrategy from './UploadStrategy.js'
import { getWebviewInstance } from '@/utils/utils.js'
import { STRATEGY_NAMES } from '../constants.js'
/**
* WebView 上传策略(遗留方案)
*
* 特点:
* 1. 使用 WebView 加载 H5 页面,调用 aliyun-oss-sdk 上传
* 2. 通过 evalJS 和 postMessage 与 WebView 通信
* 3. OSS SDK 内置 multipart upload,支持大文件分片上传
* 4. 作为最终兜底方案,总是可用
*
* 通信流程:
* 1. WebView 加载完成后发送 'webview_ready' 信号
* 2. Native 调用 evalJS 执行 msgFromUniapp 函数
* 3. WebView 上传完成后通过 postMessage 返回结果
*/
class WebViewStrategy extends UploadStrategy {
constructor() {
super()
/**
* WebView 组件引用
* @type {Object|null}
*/
this.webviewRef = null
/**
* 待处理的上传任务 Map
* key: uploadId, value: { resolve, reject, onProgress, onSuccess, onFailure }
* @type {Map<string, Object>}
*/
this.pendingUploads = new Map()
/**
* WebView 是否已就绪
* @type {boolean}
*/
this.isWebViewReady = false
/**
* 当前上传 ID
* @type {string|null}
*/
this.currentUploadId = null
/**
* Vue 组件上下文
* @type {Object|null}
*/
this.vueContext = null
}
/**
* 初始化 WebView 上下文
*
* @param {Object} webviewRef - WebView 组件引用 ($refs.uploaderWebview)
* @param {Object} vueContext - Vue 组件实例 (this)
*/
initialize(webviewRef, vueContext) {
this.webviewRef = webviewRef
this.vueContext = vueContext
}
/**
* 上传文件
*
* 注意:WebView 策略使用 OSS SDK 内置的 multipart upload
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async upload(file, options) {
return this.uploadDirect(file, options)
}
/**
* 直接上传文件(通过 WebView)
*
* @param {Object} file - 文件对象
* @param {Object} options - 上传选项
* @returns {Promise<string>} 文件 URL
*/
async uploadDirect(file, options) {
if (!this.isWebViewReady) {
throw new Error('WebView not ready')
}
if (!this.webviewRef) {
throw new Error('WebView reference not set, call initialize() first')
}
const uploadId = this.generateUploadId()
this.currentUploadId = uploadId
return new Promise(async (resolve, reject) => {
// 保存回调
this.pendingUploads.set(uploadId, {
resolve,
reject,
onProgress: options.onProgress,
onSuccess: options.onSuccess,
onFailure: options.onFailure
})
// 🔥 修复:从完整路径中提取目录路径
// file.path 是完整路径:file:///path/to/file.mp3
// msgFromUniapp 需要:
// - fileName: file.mp3
// - filePath: file:///path/to/
let filePath = file.path
let fileName = file.name
// 如果 file.path 包含文件名,提取目录路径
if (filePath.endsWith(fileName)) {
// 移除文件名,保留目录路径
filePath = filePath.substring(0, filePath.length - fileName.length)
} else if (filePath.includes('/')) {
// 如果路径不以文件名结尾,但包含 /,确保以 / 结尾
if (!filePath.endsWith('/')) {
filePath = filePath + '/'
}
}
// 调用 WebView 函数上传文件
// 匹配现有的 msgFromUniapp 函数签名
await this.callWebViewFunction(
'msgFromUniapp',
options.ossConfig.accessKeyId,
options.ossConfig.accessKeySecret,
options.ossConfig.stsToken,
fileName,
filePath,
uploadId, // 使用 uploadId 作为 recordId
options.ossConfig.bucket,
options.ossConfig.region,
{
// 可选参数
partSize: options.partSize || 500, // 默认 500KB
parallel: options.parallel || 4, // 并发数
timeout: options.timeout || 60000, // 超时时间
ossFolder: options.ossFolder || 'quality/' // OSS 文件夹
}
)
})
}
/**
* 上传分片(WebView 策略不使用)
*
* WebView 策略使用 OSS SDK 内置的 multipart upload
* 此方法不应被调用
*
* @throws {Error} 不支持此方法
*/
async uploadChunk() {
throw new Error('WebViewStrategy uses OSS SDK built-in multipart upload, uploadChunk should not be called directly')
}
/**
* 取消上传
*
* 注意:WebView OSS SDK 不支持通过消息取消上传
* 只能拒绝 pending promise
*/
cancel() {
if (this.currentUploadId) {
const upload = this.pendingUploads.get(this.currentUploadId)
if (upload) {
const error = new Error('Upload cancelled by user')
upload.onFailure?.({ code: 'CANCELLED', message: error.message })
upload.reject(error)
this.pendingUploads.delete(this.currentUploadId)
}
this.currentUploadId = null
uni.$logger?.local?.info('[WebViewStrategy] Upload cancelled')
}
}
/**
* 检查是否支持
*
* WebView 总是可用(作为兜底方案)
*
* @returns {boolean} 总是返回 true
*/
isSupported() {
return true
}
/**
* 检查是否已就绪
*
* WebView 需要等待 webview_ready 信号
*
* @returns {boolean} 是否已就绪
*/
isReady() {
return this.isWebViewReady
}
/**
* 获取策略名称
*
* @returns {string} 'webview'
*/
getName() {
return STRATEGY_NAMES.WEBVIEW
}
/**
* 调用 WebView 中的函数
*
* @param {string} functionName - 函数名
* @param {...any} args - 函数参数
*/
async callWebViewFunction(functionName, ...args) {
if (!this.vueContext) {
throw new Error('Vue context not set')
}
// 将参数转换为字符串
const argsStr = args.map(arg => {
if (typeof arg === 'object') {
return JSON.stringify(arg)
} else if (typeof arg === 'string') {
return `'${arg}'`
}
return arg
}).join(',')
// 执行 WebView 中的 JavaScript 函数
const jsCode = `window.${functionName}(${argsStr})`
try {
// 使用项目的 getWebviewInstance 工具函数获取 WebView 实例
const webviewComponent = this.vueContext.$refs.uploaderWebview
const nativeWebview = await getWebviewInstance(webviewComponent, this.vueContext)
if (!nativeWebview) {
throw new Error('Failed to get WebView instance')
}
// 调用 evalJS
if (typeof nativeWebview.evalJS === 'function') {
nativeWebview.evalJS(jsCode)
} else {
throw new Error('WebView evalJS method not found')
}
} catch (error) {
uni.$logger?.local?.error(`[WebViewStrategy] Failed to call WebView function: ${error.message}`)
throw error
}
}
/**
* 处理来自 WebView 的消息
*
* 消息格式:
* - webview_ready: { action: 'webview_ready' }
* - 上传结果: { code, message, fileName, recordId, filePath, data: { oss } }
*
* @param {Object} data - 消息数据
*/
handleMessage(data) {
// 处理 webview_ready 信号
if (data.action === 'webview_ready') {
this.isWebViewReady = true
return
}
// 处理上传响应
const uploadId = data.recordId
const upload = this.pendingUploads.get(uploadId)
if (!upload) {
uni.$logger?.local?.warn(`[WebViewStrategy] No pending upload found for: ${uploadId}`)
return
}
if (data.code === 0) {
// 上传成功
const fileUrl = data.data?.oss?.res?.requestUrls?.[0] || ''
const metadata = {
size: data.data?.oss?.res?.size || 0,
name: data.fileName
}
upload.onSuccess?.(fileUrl, metadata)
upload.resolve(fileUrl)
// uni.$logger?.local?.info(`[WebViewStrategy] Upload success: ${fileUrl}`)
} else {
// 上传失败
const error = {
code: data.code,
message: data.message || 'Upload failed'
}
upload.onFailure?.(error)
upload.reject(new Error(error.message))
uni.$logger?.local?.error(`[WebViewStrategy] Upload failed: ${error.message}`)
}
// 清理
this.pendingUploads.delete(uploadId)
if (this.currentUploadId === uploadId) {
this.currentUploadId = null
}
}
/**
* 生成上传 ID
*
* @returns {string} 唯一的上传 ID
*/
generateUploadId() {
return `upload_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
}
/**
* 重置策略状态
*
* 用于清理所有待处理的上传任务
*/
reset() {
this.pendingUploads.clear()
this.currentUploadId = null
this.isWebViewReady = false
uni.$logger?.local?.info('[WebViewStrategy] Strategy reset')
}
}
// 导出策略类
export default WebViewStrategy
...@@ -187,16 +187,19 @@ async function getAudioFilePath(path = '') { ...@@ -187,16 +187,19 @@ async function getAudioFilePath(path = '') {
const rootPath = await getFilePath() const rootPath = await getFilePath()
return `file://${rootPath}${path}` return `file://${rootPath}${path}`
} }
export function serializeIfObject(msg) { export function serializeIfObject(value) {
return typeof msg === 'object' ? JSON.stringify(msg) : msg.toString() if (value && typeof value === 'object') {
} return JSON.stringify(value)
export function isInteger(value) {
if (typeof value === 'number') {
return Number.isInteger(value)
} else if (typeof value === 'string') {
return /^-?\d+$/.test(value)
} }
return false return value
}
/**
* 获取 Webview 实例的工具方法
* @param {Object} webviewComponent - Vue 组件引用
* @param {Object} vueContext - Vue 实例上下文
*/
export function isInteger(obj) {
return typeof obj === 'number' && obj % 1 === 0
} }
export function singleton(className) { export function singleton(className) {
let ins = null let ins = null
...@@ -287,6 +290,8 @@ function validateVIN(vin) { ...@@ -287,6 +290,8 @@ function validateVIN(vin) {
return checkDigit === vin[8]; return checkDigit === vin[8];
} }
const nullValues = [undefined,'undefined',null,'null']
export default { export default {
compareVersions, compareVersions,
convertDateTimeFormat, convertDateTimeFormat,
...@@ -308,5 +313,71 @@ export default { ...@@ -308,5 +313,71 @@ export default {
setCopyData, setCopyData,
refreshPageData, refreshPageData,
filterValue, filterValue,
validateVIN validateVIN,
nullValues,
isInteger,
getWebviewInstance
}
/**
* 获取 Webview 实例 (增强版)
* @param {Object} component - Vue 组件引用
* @param {Object} context - Vue 上下文
*/
export function getWebviewInstance(component, context) {
return new Promise((resolve) => {
// 1. 尝试直接获取
if (component && typeof component.$getAppWebview === 'function') {
const wv = component.$getAppWebview()
if (wv) {
resolve(wv)
return
}
}
// 2. 尝试通过页面查找 (解决组件未挂载完全时的获取问题)
const tryFind = () => {
try {
let pageWebview = null
if (context && context.$scope && typeof context.$scope.$getAppWebview === 'function') {
pageWebview = context.$scope.$getAppWebview()
} else if (context && context.$parent && context.$parent.$scope && typeof context.$parent.$scope.$getAppWebview === 'function') {
pageWebview = context.$parent.$scope.$getAppWebview()
}
if (pageWebview && typeof pageWebview.children === 'function') {
const children = pageWebview.children()
for (let i = 0; i < children.length; i++) {
const child = children[i]
const url = child.getURL ? child.getURL() : ''
if (url && url.indexOf('hybrid/html/index.html') > -1) {
return child
}
}
}
} catch (e) {
console.warn('getWebviewInstance error:', e)
}
return null
}
const wv = tryFind()
if (wv) {
resolve(wv)
return
}
// 3. 异步重试 (处理渲染延迟)
let retries = 0
const timer = setInterval(() => {
retries++
const wv = tryFind()
if (wv) {
clearInterval(timer)
resolve(wv)
} else if (retries >= 10) {
clearInterval(timer)
resolve(null)
}
}, 200)
})
} }
import WorkerFactory from './WorkerFactory'
export default class CommandFactory {
store = new Map()
static instance = null
constructor() {
if (this.instance) {
return this.instance
}
this.instance = this
}
static getInstance() {
if (!CommandFactory.instance) {
CommandFactory.instance = new CommandFactory()
}
return CommandFactory.instance
}
dispatch(cmd) {
const Worker = WorkerFactory.create(cmd)
if (!Worker) {
throw new Error('未找到对应的Worker')
}
// if (!this.store.has(Worker.name)) {
// this.store.set(Worker.name, new Worker())
// }
// return this.store.get(Worker.name)
return new Worker()
}
clear() {
this.store.clear()
this.instance = null
}
}
import LogsWorker from './workers/LogsWorker'
import CommonWorker from './workers/CommonWorker'
import MessageWorker from './workers/MessageWorker'
import StorageWorker from './workers/StorageWorker'
import RecordsWorker from './workers/RecordsWorker'
import RemoveLogWorker from './workers/RemoveLogWorker'
import GetLogListWorker from './workers/GetLogListWorker'
import StopPollingWorker from './workers/StopPollingWorker'
import RemoveRecordWorker from './workers/RemoveRecordWorker'
import StartPollingWorker from './workers/StartPollingWorker'
import SetPollingIntervalWorker from './workers/SetPollingIntervalWorker'
import TempRecordsWorker from './workers/TempRecordsWorker'
import RemoveTempRecordWorker from './workers/RemoveTempRecordWorker'
import AddTempRecordWorker from './workers/AddTempRecordWorker'
import AddRecordWorker from './workers/AddRecordWorker'
import { Command } from './constants'
const Workers = {
[Command.GetLog]: LogsWorker,
[Command.Records]: RecordsWorker,
[Command.Message]: MessageWorker,
[Command.RemoveLog]: RemoveLogWorker,
[Command.GetStorage]: StorageWorker,
[Command.GetLogList]: GetLogListWorker,
[Command.StopPolling]: StopPollingWorker,
[Command.RemoveRecord]: RemoveRecordWorker,
[Command.StartPolling]: StartPollingWorker,
[Command.SetPollingInterval]: SetPollingIntervalWorker,
[Command.TempRecords]: TempRecordsWorker,
[Command.RemoveTempRecord]: RemoveTempRecordWorker,
[Command.AddTempRecord]: AddTempRecordWorker,
[Command.AddRecord]: AddRecordWorker
}
export default {
create: cmd => Workers[cmd] || CommonWorker
}
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import { WsTyps } from '../utils/common'
import CommandFactory from './CommandFactory'
import config from '@/config.js'
import { serializeIfObject,deepClone } from '@/utils/utils.js'
// const WsTyps = common.constants.WsTyps
export class Ws {
wsAddress
loginAddress
token
deviceId
onMessage
ws
constructor() {
this.wsAddress = config.SOCKET_SERVER
this.loginAddress =`${config.HTTP_SERVER}/login`
}
async connect() {
const { code, data, o } = await this.login()
if (code == 200) {
this.deviceId = data.id
this.token = data.token
this.ws = io(this.wsAddress, {
path:'/websocket/',
auth: { token: this.token, deviceId: this.deviceId },
transports: ['websocket'],
timeout: 5000
})
this.subscribe()
} else {
uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`)
}
}
async login(retryCount = 3, retryDelay = 2000) {
const tryLogin = async (attemptCount) => {
try {
const sysInfo = uni.getSystemInfoSync()
if (!sysInfo?.deviceId) {
throw new Error('未获取到系统设备信息')
}
// sysInfo.deviceId = '4DF8801064461802495A2452CCD04EE4'
uni.$logger.local.info(`========WS,用户登录(第${attemptCount}次尝试) ${JSON.stringify({deviceId:sysInfo.deviceId})}========`)
return new Promise((resolve, reject) => {
uni.request({
url: this.loginAddress,
data: { sn: sysInfo.deviceId },
method: 'POST',
dataType: 'json',
success(response) {
resolve(response.data)
},
fail(err) {
reject(err)
}
})
})
} catch (error) {
throw error
}
}
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
return await tryLogin(attempt)
} catch (err) {
if (attempt === retryCount) {
uni.$logger.local.error(`登录失败(已重试${retryCount}次), 请检查网络或联系管理员! err->${serializeIfObject(err)}`)
throw err
}
uni.$logger.local.warn(`登录失败(第${attempt}次), ${retryDelay/1000}秒后重试... err->${serializeIfObject(err)}`)
await new Promise(resolve => setTimeout(resolve, retryDelay))
}
}
}
subscribe() {
this.ws.on(WsTyps.Connected, () => {
uni.$logger.local.info('========WebSocket 连接成功========')
})
this.ws.on(
WsTyps.MessageTypes.Private,
function (data) {
uni.$logger.local.info(`WebSocket 收到消息 -> ${JSON.stringify(data)}`)
if (data.errorCode && data.errorCode == 907) return this.connect()
const _data = deepClone(data)
const worker = CommandFactory.getInstance().dispatch(_data.command)
worker.work(this.deviceId, _data, this)
this.onMessage && this.onMessage(_data)
}.bind(this)
)
this.ws.on(WsTyps.MessageTypes.System, function (data) {
uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`)
})
this.ws.on(WsTyps.Disconnected, () => {
CommandFactory.getInstance().clear()
uni.$logger.local.info(`========WebSocket 断开连接 device_id->${this.deviceId}========`)
})
this.ws.on(WsTyps.Eroor, msg => {
CommandFactory.getInstance().clear()
uni.$logger.error(`========WebSocket 异常 device_id->${this.deviceId} msg ->${serializeIfObject(msg)}========`)
})
}
send(data, type = WsTyps.MessageTypes.Private) {
this.ws.emit(type, { device_id: this.deviceId, ...data })
}
}
const Command = {
GetLog: 'getLog',
GetStorage: 'getStorage',
Message: 'message',
GetLogList: 'getLogList',
RemoveLog: 'removeLog',
RemoveRecord: 'removeRecord',
StopPolling: 'stopPolling',
StartPolling: 'startPolling',
SetPollingInterval: 'setPollingInterval',
Records: 'records',
TempRecords: 'tempRecords',
RemoveTempRecord: 'removeTempRecord',
AddTempRecord: 'addTempRecord',
AddRecord: 'addRecord'
}
export { Command }
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2025-01-14 16:49:00
* @LastEditors: limin
* @LastEditTime: 2025-01-20 17:31:12
* @FilePath: \gl_tape\ws\workers\AddRecordWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { RecordDto } from '@/utils/recordManager/index'
export default class AddRecordWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const record = data.data
if (!record) {
throw new Error(`数据格式错误,请提供 record 数据`)
}
const keys = Object.keys(record)
const dto = new RecordDto({})
const existKeys = ['id', 'recordUrlList']
keys.forEach(key => {
if (!existKeys.includes(key) && !dto.hasOwnProperty(key)) {
throw new Error(`数据格式错误,表中没有 ${key} 字段`)
}
})
await uni.$dbManager.addRecord(record)
const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待上传记录成功', data: record })
} catch (error) {
const msg = `写入待上传记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
import { RecordDto } from '@/utils/recordManager/index'
export default class AddTempRecordWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const record = data.data
if (!record) {
throw new Error(`数据格式错误,请提供 record 数据`)
}
const keys = Object.keys(record)
const dto = new RecordDto({})
const existKeys = ['id', 'recordUrlList','tempFilePath']
keys.forEach(key => {
if (!existKeys.includes(key) && !dto.hasOwnProperty(key)) {
throw new Error(`数据格式错误,表中没有 ${key} 字段`)
}
})
await uni.$dbTempRecord.addRecord(record)
const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待提交记录成功', data:record })
} catch (error) {
const msg = `写入待提交记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
import { serializeIfObject } from '@/utils/utils.js'
export default class CommonWorker {
constructor() {}
work(deviceId, data) {
uni.$logger.local.info(`收到WebSocket 消息: deviceId->${deviceId}, data->${serializeIfObject(data)}`)
// console.log(`收到WebSocket 消息: deviceId->${deviceId}, data->${typeof data ==='[object Object]'?JSON.stringify(data):data}`)
}
}
import { serializeIfObject } from '@/utils/utils.js'
export default class GetLogListWorker {
constructor() {}
work(deviceId, data, ws) {
try {
const beginDate = data.beginDate
const endDate = data.endDate
const LogList = uni.$logger.local.getFiles(beginDate, endDate)
uni.$logger.local.info(`获取日志列表成功! beginDate ->${beginDate} endDate-> ${endDate} res->${serializeIfObject(LogList)}`)
ws.send({ LogList })
} catch (error) {
uni.$logger.local.error(`获取日志列表失败! beginDate ->${beginDate} endDate-> ${endDate} error->${serializeIfObject(error.message)}`)
}
}
}
import config from '@/config.js'
import { serializeIfObject,deepClone } from '@/utils/utils.js'
export default class LogsWorker {
logFile = null
constructor() {
this.logFile = uni.$logger.local.logger
this.isUploading = false
this.files = []
}
getLogFileList() {
return this.logFile.getLogFileList()
}
upload(deviceId, data) {
if (this.isUploading) {
const msg = `日志上传中,请稍后再试!`
uni.$logger.local.info(msg)
this.ws.send(msg)
return
}
this.isUploading = true
const files = this.getLogFileList()
this.files = JSON.stringify(files)
if (files?.length) {
files.sort((a, b) => a.name.localeCompare(b.name))
this.process(files, deviceId)
}
}
async process(files, deviceId) {
if (files.length > 0) {
const file = files.shift()
await this.post(file, deviceId)
setTimeout(() => this.process(files, deviceId), 500)
} else {
this.ws.send({ code: 200, msg: `日志上传完成 logs -> ${this.files}`})
this.isUploading = false
this.files=[]
}
}
post({ name, path }, deviceId) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: `${config.HTTP_SERVER}/${config.FILE_UPLOAD_URL}`,
filePath: path,
name: 'file',
header: {
'Content-Type': 'multipart/form-data'
},
formData: {
deviceId,
type: 'log'
},
success: res => {
uni.$logger.local.info(`文件上传成功! res->${serializeIfObject(res)} filePath->${path}`)
resolve()
},
fail: res => {
uni.$logger.local.error(`文件上传失败! res->${serializeIfObject(res)} filePath->${path} .`)
resolve()
}
})
})
}
work(deviceId, data, ws) {
this.ws = ws
this.upload(deviceId, data)
}
}
import { serializeIfObject } from '@/utils/utils.js'
export default class MessageWorker {
constructor() {}
work(deviceId, data) {
uni.$logger.local.info(`收到WebSocket 消息: deviceId->${deviceId}, data->${serializeIfObject(data)}`)
// console.log(`收到WebSocket 消息: deviceId->${deviceId}, data->${typeof data ==='[object Object]'?JSON.stringify(data):data}`)
}
}
import { serializeIfObject } from '@/utils/utils.js'
export default class RecordsWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const records = await uni.$dbManager.getRecords()
const msg = `记录获取成功 records -> ${JSON.stringify(records)}`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg: '获取记录成功', data:records })
} catch (error) {
const msg = `获取记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
import { isInteger } from '@/utils/utils.js'
export default class RemoveLogWorker {
constructor() {}
work(deviceId, data, ws) {
//参数可以不传,默认7天
const days = data.days
if (!isInteger(days) || days==0) {
const error = `RemoveLogWorker -> 删除日志: 参数错误!days 必需为数字! days -> ${days} `
ws.send({ error, data })
uni.$logger.local.error(error)
return
}
uni.$logger.local.removeOverDays(days)
const msg = `删除${days}天前的日志成功!`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg: msg, data })
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 20:45:05
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-06 09:42:35
* @FilePath: \gl-tape\ws\workers\RemoveRecordWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { serializeIfObject } from '@/utils/utils.js'
export default class RemoveRecordWorker {
constructor() {}
async work(deviceId, data, ws) {
const recordId = data.id
if (!recordId) {
const msg = `删除接待记录,缺少记录id`
uni.$logger.local.info(msg)
ws.send({ error: msg })
return
}
try {
const record = await uni.$dbManager.getRecordById(recordId)
if (!record) {
const msg = `记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg)
ws.send({ error: msg })
return
}
await uni.$dbManager.removeRecord(recordId)
const msg = `记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg })
} catch (error) {
const msg = `记录删除异常 id -> ${recordId} error -> ${serializeIfObject(error.message)}`
uni.$logger.local.error(msg)
ws.send({ error: error, recordId })
}
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 20:45:05
* @LastEditors: limin
* @LastEditTime: 2025-01-13 20:24:34
* @FilePath: \gl_tape\ws\workers\RemoveTempRecordWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { serializeIfObject } from '@/utils/utils.js'
export default class RemoveTempRecordWorker {
constructor() {}
async work(deviceId, data, ws) {
const recordId = data.id
if (!recordId) {
const msg = `删除接待待提交记录,缺少记录id`
uni.$logger.local.info(msg)
ws.send({ error: msg })
return
}
try {
const record = await uni.$dbTempRecord.getRecordById(recordId)
if (!record) {
const msg = `待提交记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg)
ws.send({ error: msg })
return
}
await uni.$dbTempRecord.removeRecord(recordId)
const msg = `待提交记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg })
} catch (error) {
const msg = `待提交记录删除异常 id -> ${recordId} error -> ${serializeIfObject(error.message)}`
uni.$logger.local.error(msg)
ws.send({ error: error, recordId })
}
}
}
import { isInteger } from '@/utils/utils.js'
export default class SetPollingIntervalWorker {
constructor() {}
work(deviceId, data, ws) {
const interval = data.interval
const isForce = !!data.force
if (!isInteger(interval)) {
const error = `SetPollingIntervalWorker -> 设置轮询时间间隔: 参数错误!interval 必需为数字! interval -> ${interval} `
ws.send({ error, data })
uni.$logger.local.error(error)
return
}
uni.$emit(data.command, interval,isForce)
ws.send({ code: 200, msg: `设置轮询间隔时间成功!当前间隔时间为 -> ${interval} s`, data })
}
}
export default class StartPollingWorker {
constructor() {}
work(deviceId, data, ws) {
const isForce = !!data.force
uni.$emit(data.command, isForce)
const msg = `启动轮询指令下发并执行成功!`
ws.send({ code: 200, msg, data })
}
}
export default class StopPollingWorker {
constructor() {}
work(deviceId, data, ws) {
uni.$emit(data.command)
const msg = `终止轮询指令下发并执行成功!`
ws.send({ code: 200, msg, data })
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 20:45:05
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2025-01-22 15:33:03
* @FilePath: \gl_tape\ws\workers\StorageWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { constData } from '../../utils/cache'
import { serializeIfObject } from '@/utils/utils.js'
export default class StorageWorker {
constructor() {}
async work(deviceId, data, ws) {
let key = data.key
if (!constData.STORAGE_OBJECTKEY[key]) {
uni.$logger.local.error(`不存在的 Storage Key->${key}. data->${serializeIfObject(data)}`)
return
}
let value = uni.$storage.get(key)
if (key == 'recordList') {
value = await uni.$dbManager.getRecords()
}
const msg = `获取本地缓存! key->${key} value->${serializeIfObject(value)}`
uni.$logger.local.info(msg)
ws.send({ [key]: value })
}
}
export default class TempRecordsWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const records = await uni.$dbTempRecord.getRecords()
const msg = `记录获取待提交记录成功 temp records -> ${JSON.stringify(records)}`
uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '获取待提交记录成功', data:records })
} catch (error) {
const msg = `获取待提交记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
...@@ -13,6 +13,9 @@ import TempRecordsWorker from './workers/TempRecordsWorker' ...@@ -13,6 +13,9 @@ import TempRecordsWorker from './workers/TempRecordsWorker'
import RemoveTempRecordWorker from './workers/RemoveTempRecordWorker' import RemoveTempRecordWorker from './workers/RemoveTempRecordWorker'
import AddTempRecordWorker from './workers/AddTempRecordWorker' import AddTempRecordWorker from './workers/AddTempRecordWorker'
import AddRecordWorker from './workers/AddRecordWorker' import AddRecordWorker from './workers/AddRecordWorker'
import SqlWorker from './workers/SqlWorker'
import LiveLogWorker from './workers/LiveLogWorker'
import FileExplorerWorker from './workers/FileExplorerWorker'
import { Command } from './constants' import { Command } from './constants'
const Workers = { const Workers = {
[Command.GetLog]: LogsWorker, [Command.GetLog]: LogsWorker,
...@@ -28,7 +31,10 @@ const Workers = { ...@@ -28,7 +31,10 @@ const Workers = {
[Command.TempRecords]: TempRecordsWorker, [Command.TempRecords]: TempRecordsWorker,
[Command.RemoveTempRecord]: RemoveTempRecordWorker, [Command.RemoveTempRecord]: RemoveTempRecordWorker,
[Command.AddTempRecord]: AddTempRecordWorker, [Command.AddTempRecord]: AddTempRecordWorker,
[Command.AddRecord]: AddRecordWorker [Command.AddRecord]: AddRecordWorker,
[Command.ExecuteSql]: SqlWorker,
[Command.LiveLog]: LiveLogWorker,
[Command.FileExplorer]: FileExplorerWorker
} }
export default { export default {
create: cmd => Workers[cmd] || CommonWorker create: cmd => Workers[cmd] || CommonWorker
......
...@@ -76,25 +76,28 @@ export class Ws { ...@@ -76,25 +76,28 @@ export class Ws {
} }
subscribe() { subscribe() {
this.ws.on(WsTyps.Connected, () => { this.ws.on(WsTyps.Connected, () => {
uni.$logger.local.info('========WebSocket 连接成功========') uni.$logger.local.warn('========WebSocket 连接成功========')
}) })
this.ws.on( this.ws.on(
WsTyps.MessageTypes.Private, WsTyps.MessageTypes.Private,
function (data) { function (data) {
uni.$logger.local.info(`WebSocket 收到消息 -> ${JSON.stringify(data)}`) uni.$logger.local.info(`WebSocket 收到消息 -> ${JSON.stringify(data)}`)
if (data.errorCode && data.errorCode == 907) return this.connect() if (data.errorCode && data.errorCode == 907) {
uni.$logger.local.warn('WebSocket Token过期,尝试重连...')
return this.connect()
}
const _data = deepClone(data) const _data = deepClone(data)
const worker = CommandFactory.getInstance().dispatch(_data.command) const worker = CommandFactory.getInstance().dispatch(_data.command)
worker.work(this.deviceId, _data, this) worker.work(this.deviceId, _data, this)
this.onMessage && this.onMessage(_data) this.onMessage && this.onMessage(_data)
}.bind(this) }.bind(this)
) )
this.ws.on(WsTyps.MessageTypes.System, function (data) { // this.ws.on(WsTyps.MessageTypes.System, function (data) {
uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`) // uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`)
}) // })
this.ws.on(WsTyps.Disconnected, () => { this.ws.on(WsTyps.Disconnected, () => {
CommandFactory.getInstance().clear() CommandFactory.getInstance().clear()
uni.$logger.local.info(`========WebSocket 断开连接 device_id->${this.deviceId}========`) uni.$logger.local.warn(`========WebSocket 断开连接 device_id->${this.deviceId}========`)
}) })
this.ws.on(WsTyps.Eroor, msg => { this.ws.on(WsTyps.Eroor, msg => {
CommandFactory.getInstance().clear() CommandFactory.getInstance().clear()
......
...@@ -12,6 +12,9 @@ const Command = { ...@@ -12,6 +12,9 @@ const Command = {
TempRecords: 'tempRecords', TempRecords: 'tempRecords',
RemoveTempRecord: 'removeTempRecord', RemoveTempRecord: 'removeTempRecord',
AddTempRecord: 'addTempRecord', AddTempRecord: 'addTempRecord',
AddRecord: 'addRecord' AddRecord: 'addRecord',
ExecuteSql: 'executeSql',
LiveLog: 'liveLog',
FileExplorer: 'fileExplorer'
} }
export { Command } export { Command }
...@@ -23,7 +23,8 @@ export default class AddRecordWorker { ...@@ -23,7 +23,8 @@ export default class AddRecordWorker {
throw new Error(`数据格式错误,表中没有 ${key} 字段`) throw new Error(`数据格式错误,表中没有 ${key} 字段`)
} }
}) })
await uni.$dbManager.addRecord(record) record.recordStatus = 1
await uni.$dbRecord.addRecord(record)
const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}` const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待上传记录成功', data: record }) ws.send({ code: 200,msg: '写入待上传记录成功', data: record })
......
...@@ -15,7 +15,9 @@ export default class AddTempRecordWorker { ...@@ -15,7 +15,9 @@ export default class AddTempRecordWorker {
throw new Error(`数据格式错误,表中没有 ${key} 字段`) throw new Error(`数据格式错误,表中没有 ${key} 字段`)
} }
}) })
await uni.$dbTempRecord.addRecord(record) // 标记为接待中
record.recordStatus = 0
await uni.$dbRecord.addRecord(record)
const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}` const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待提交记录成功', data:record }) ws.send({ code: 200,msg: '写入待提交记录成功', data:record })
......
import { serializeIfObject } from '@/utils/utils.js'
export default class FileExplorerWorker {
constructor() {}
work(deviceId, data, ws) {
const { path } = data
// 默认路径:_doc/ (应用私有文档目录)
const targetPath = path || '_doc/'
uni.$logger.local.info(`[FileExplorerWorker] 浏览目录: ${targetPath}`)
// 检查是否在 App 环境
// #ifndef APP-PLUS
ws.send({ error: '文件浏览仅支持 App 环境' })
return
// #endif
// #ifdef APP-PLUS
plus.io.resolveLocalFileSystemURL(
targetPath,
(entry) => {
if (entry.isDirectory) {
// 如果是目录,读取目录内容
const directoryReader = entry.createReader()
directoryReader.readEntries(
(entries) => {
const fileList = entries.map((itm) => ({
name: itm.name,
fullPath: itm.fullPath,
isFile: itm.isFile,
isDirectory: itm.isDirectory,
// 注意:getMetadata 需要异步获取,这里为了简单只返回基本信息
// 如果需要大小和时间,需要遍历调用 getMetadata,会比较慢
}))
// 排序:目录在前,文件在后
fileList.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1
if (!a.isDirectory && b.isDirectory) return 1
return a.name.localeCompare(b.name)
})
ws.send({
code: 200,
msg: '获取目录成功',
data: {
currentPath: entry.fullPath,
files: fileList
}
})
},
(e) => {
const msg = `读取目录失败: ${e.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
)
} else {
// 如果是文件,获取文件信息
entry.getMetadata(
(metadata) => {
ws.send({
code: 200,
msg: '获取文件信息成功',
data: {
isFile: true,
name: entry.name,
fullPath: entry.fullPath,
size: metadata.size,
modificationTime: metadata.modificationTime,
directory: false
}
})
},
(e) => {
const msg = `获取文件信息失败: ${e.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
)
}
},
(e) => {
const msg = `路径解析失败: ${targetPath}, error: ${e.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
)
// #endif
}
}
import { serializeIfObject } from '@/utils/utils.js'
export default class LiveLogWorker {
constructor() {}
work(deviceId, data, ws) {
const { action } = data // 'start' | 'stop'
if (action === 'start') {
uni.$logger.local.info('[LiveLogWorker] 开启实时日志流')
// 设置监听器
uni.$logger.setLogListener((level, info) => {
// 防止死循环:这里发送 WS 消息,如果 WS 发送失败导致 logger.error,会再次触发监听器
// 简单处理:只发送非 WS 相关的日志,或者信任 WS 库不会在 send 时狂打日志
// 这里直接发送
try {
// 构造日志消息对象
const logMsg = {
type: 'liveLog',
level,
info: typeof info === 'object' ? serializeIfObject(info) : info,
timestamp: Date.now()
}
// 直接调用底层的 ws 发送,跳过 logging 避免循环
// 注意:ws 是 Ws.js 中的实例,ws.ws 是 socket.io 实例
if (ws && ws.ws && ws.ws.connected) {
ws.ws.emit('message', logMsg)
}
} catch (e) {
// 忽略发送错误,避免死循环
console.error('Live log send failed', e)
}
})
ws.send({ code: 200, msg: '实时日志已开启' })
} else if (action === 'stop') {
uni.$logger.setLogListener(null)
uni.$logger.local.info('[LiveLogWorker] 关闭实时日志流')
ws.send({ code: 200, msg: '实时日志已关闭' })
} else {
ws.send({ error: '未知动作: ' + action })
}
}
}
...@@ -3,7 +3,7 @@ export default class RecordsWorker { ...@@ -3,7 +3,7 @@ export default class RecordsWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const records = await uni.$dbManager.getRecords() const records = await uni.$dbRecord.getCompletedRecords()
const msg = `记录获取成功 records -> ${JSON.stringify(records)}` const msg = `记录获取成功 records -> ${JSON.stringify(records)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg: '获取记录成功', data:records }) ws.send({ code: 200, msg: '获取记录成功', data:records })
......
...@@ -18,14 +18,14 @@ export default class RemoveRecordWorker { ...@@ -18,14 +18,14 @@ export default class RemoveRecordWorker {
return return
} }
try { try {
const record = await uni.$dbManager.getRecordById(recordId) const record = await uni.$dbRecord.getRecordById(recordId)
if (!record) { if (!record) {
const msg = `记录不存在 id -> ${recordId}` const msg = `记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ error: msg }) ws.send({ error: msg })
return return
} }
await uni.$dbManager.removeRecord(recordId) await uni.$dbRecord.removeRecord(recordId)
const msg = `记录删除成功 id -> ${recordId}` const msg = `记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg }) ws.send({ code: 200, msg })
......
...@@ -18,14 +18,14 @@ export default class RemoveTempRecordWorker { ...@@ -18,14 +18,14 @@ export default class RemoveTempRecordWorker {
return return
} }
try { try {
const record = await uni.$dbTempRecord.getRecordById(recordId) const record = await uni.$dbRecord.getRecordById(recordId)
if (!record) { if (!record) {
const msg = `待提交记录不存在 id -> ${recordId}` const msg = `待提交记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ error: msg }) ws.send({ error: msg })
return return
} }
await uni.$dbTempRecord.removeRecord(recordId) await uni.$dbRecord.removeRecord(recordId)
const msg = `待提交记录删除成功 id -> ${recordId}` const msg = `待提交记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg }) ws.send({ code: 200, msg })
......
import { serializeIfObject } from '@/utils/utils.js'
export default class SqlWorker {
constructor() {}
async work(deviceId, data, ws) {
const { sql } = data
if (!sql) {
ws.send({ error: 'SQL语句不能为空', requestData: data })
return
}
try {
// 假设 uni.$dbRecord 已经初始化且 db 属性可用
// 使用 selectSql 执行查询。注意:对于非查询语句(如 UPDATE/DELETE),selectSql 可能也适用,
// 或者需要检查 lib/sqlite.js 是否支持 executeSql
// 根据之前的 SearchCodebase 结果,lib/sqlite.js 只有 selectSql 和 executeSql (未在 context 中显示但通常有)
// 但 DBManager 中似乎只用了 insert/delete/select 等封装方法。
// 不过 lib/sqlite.js 显示了 selectSql 方法。
uni.$logger.local.info(`[SqlWorker] 执行SQL: ${sql}`)
const result = await uni.$dbRecord.db.selectSql(sql)
ws.send({
code: 200,
msg: 'SQL执行成功',
data: result,
requestData: data
})
} catch (error) {
const msg = `SQL执行失败: ${error.message}`
uni.$logger.local.error(msg)
ws.send({
code: 500,
error: msg,
requestData: data
})
}
}
}
...@@ -18,7 +18,7 @@ export default class StorageWorker { ...@@ -18,7 +18,7 @@ export default class StorageWorker {
} }
let value = uni.$storage.get(key) let value = uni.$storage.get(key)
if (key == 'recordList') { if (key == 'recordList') {
value = await uni.$dbManager.getRecords() value = await uni.$dbRecord.getRecords()
} }
const msg = `获取本地缓存! key->${key} value->${serializeIfObject(value)}` const msg = `获取本地缓存! key->${key} value->${serializeIfObject(value)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
......
...@@ -2,10 +2,10 @@ export default class TempRecordsWorker { ...@@ -2,10 +2,10 @@ export default class TempRecordsWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const records = await uni.$dbTempRecord.getRecords() const tempRecords = await uni.$dbRecord.getTempRecords()
const msg = `记录获取待提交记录成功 temp records -> ${JSON.stringify(records)}` const msg = `记录获取待提交记录成功 temp records -> ${JSON.stringify(tempRecords)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '获取待提交记录成功', data:records }) ws.send({ code: 200,msg: '获取待提交记录成功', data:tempRecords })
} catch (error) { } catch (error) {
const msg = `获取待提交记录失败 error -> ${error.message}` const msg = `获取待提交记录失败 error -> ${error.message}`
uni.$logger.local.error(msg) uni.$logger.local.error(msg)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!