Commit 45724665 by liimin

feat(record): 增加录音超时自动停止功能并优化闲置检测

refactor(timeout): 重构闲置检测逻辑为独立服务
fix(upload): 修复OSS分片上传大小计算问题
feat(utils): 添加nullValues常量用于空值判断
style: 更新多个文件的最后编辑时间和注释
1 parent 934c020b
......@@ -21,29 +21,13 @@
<MessageBox ref="previewRef" @confirm="previewHandler('preview', true)" :popupW="704" content="直接点击素材可进行预览,若面向车主展示,请点击「开始接待」" confirmBtnText="预览素材" @cancel="previewHandler('previewCancel')" @close="previewHandler('previewClose')"></MessageBox>
<finish-reception-dialog ref="finish" @confirm="$emit('openStep')" @cancel="$emit('backHome')" />
<!-- 恢复接待弹窗 -->
<MessageBox
ref="resumePopup"
title="恢复接待"
content="检测到您有上次未完成的接待,是否继续接待?"
confirmBtnText="继续接待"
cancelBtnText="开始新的"
:showCancelBtn="true"
:popupW="704"
@confirm="resumeConfirm"
@cancel="resumeCancel"
@close="resumeCancel"
/>
<MessageBox ref="resumePopup" title="恢复接待" content="检测到您有上次未完成的接待,是否继续接待?" confirmBtnText="继续接待" cancelBtnText="开始新的" :showCancelBtn="true" :popupW="704" @confirm="resumeConfirm" @cancel="resumeCancel" @close="resumeCancel" />
<!-- 升级弹框 -->
<update-box />
<slot name="content" />
<!-- 隐形 Webview (声明式) -->
<!-- 使用 webview-styles 控制原生层级位置 -->
<web-view
ref="uploaderWebview"
src="/hybrid/html/index.html"
@message="handleUploadMessage"
:webview-styles="webviewStyles"
></web-view>
<web-view ref="uploaderWebview" src="/hybrid/html/index.html" @message="handleUploadMessage" :webview-styles="webviewStyles"></web-view>
<!-- <web-view
ref="studyWebview"
:src="jumpUrl"
......@@ -69,7 +53,7 @@ const TAB_COMPONENTS = {
2: 'Order'
}
export default {
mixins: [recorder, timeout, versionCheck],
mixins: [recorder, versionCheck],
components: { LeftSide, Material, ReceptionCenter, FinishReceptionDialog, StoreAddress, HomeSlot, Order },
props: {
activeDetailId: [String, Number],
......@@ -121,7 +105,7 @@ export default {
this.userInfo = userInfo
this.currentType = uni.$storage.get('typeItem')
// if (this.checkRecordAudio) permision.requestAndroidPermission('android.permission.RECORD_AUDIO') // 进入界面时检查权限
// 初始化上传相关逻辑
this.initUploader()
},
......@@ -136,7 +120,7 @@ export default {
return this.$refs.finish
},
componentName() {
return TAB_COMPONENTS[this.tabIndex] || ''
return TAB_COMPONENTS[this.tabIndex] || ''
}
},
methods: {
......@@ -179,14 +163,14 @@ export default {
this.$emit('changeType')
},
handleUploadMessage(event) {
// 接收来自 Webview 的消息,并转发给 UploadService
const data = event.detail.data[0]
if (data) {
// 构造 Service 需要的格式 { detail: { data: [payload] } }
// 或者直接让 Service 接收 payload
// 目前 Service.handlerMessage 期望的是 { detail: { data: [...] } }
UploadService.handlerMessage(event)
}
// 接收来自 Webview 的消息,并转发给 UploadService
const data = event.detail.data[0]
if (data) {
// 构造 Service 需要的格式 { detail: { data: [payload] } }
// 或者直接让 Service 接收 payload
// 目前 Service.handlerMessage 期望的是 { detail: { data: [...] } }
UploadService.handlerMessage(event)
}
},
initUploader() {
// 初始化上传服务 (移除 init 调用,交由 App.vue 统一管理)
......@@ -194,13 +178,16 @@ export default {
// 注入 Webview 实例
this.injectWebview()
},
injectWebview() {
// 恢复:通过 $refs 获取模板中声明的 Webview 实例
// 注意:需要等待 mounted 后一段时间确保 webview 已经渲染
this.$nextTick(() => {
UploadService.setWebviewContext(this.$refs.uploaderWebview, this)
})
}
injectWebview() {
// 恢复:通过 $refs 获取模板中声明的 Webview 实例
// 注意:需要等待 mounted 后一段时间确保 webview 已经渲染
this.$nextTick(() => {
UploadService.setWebviewContext(this.$refs.uploaderWebview, this)
})
},
handleTouchStart() {
uni.$emit('reset_timeout')
}
}
}
</script>
......@@ -237,7 +224,7 @@ export default {
z-index: 1;
}
.home {
.home {
position: fixed;
width: 100%;
height: 100%;
......@@ -247,9 +234,9 @@ export default {
visibility: hidden;
opacity: 0;
will-change: opacity, visibility; // 提示浏览器提前优化
// 使用3D加速,避免重绘
transform: translateZ(0);
transform: translateZ(0);
}
.detail {
......@@ -261,14 +248,16 @@ export default {
z-index: -1;
visibility: hidden;
transform: translateX(100%);
transition: transform 0.5s cubic-bezier(0.19, 1, 0.22, 1), visibility 0.5s;
transition:
transform 0.5s cubic-bezier(0.19, 1, 0.22, 1),
visibility 0.5s;
will-change: transform, visibility; // 提示浏览器提前优化
&.show {
z-index: 2;
visibility: visible;
transform: translateX(0);
will-change: transform;
will-change: transform;
}
}
......
......@@ -38,7 +38,7 @@ class OSSUpLoader {
/**
* 每个上传分片的大小(字节)。默认500kb。
*/
partSize = 1024
partSize = 500
/**
* 最小文件大小
*/
......@@ -90,7 +90,7 @@ class OSSUpLoader {
region,
bucket,
accessKeyId,
accessKeySecret,
accessKeySecret
// stsToken,
})
}
......@@ -134,6 +134,7 @@ class OSSUpLoader {
* @throws {Error} 如果文件路径转换失败,将抛出错误
*/
_upload(fileName, file, callback) {
const partSize = this._getOptimalPartSize(file.size)
this.client
.multipartUpload(this.ossFolder + fileName, file, {
// 获取分片上传进度、断点和返回值。
......@@ -145,8 +146,8 @@ class OSSUpLoader {
},
// 设置并发上传的分片数量。
parallel: this.parallel,
//分片大小(kb) 最小为100kb 默认500kb
partSize: 1024 * this.partSize,
//分片大小
partSize: partSize,
timeout: this.timeout,
mime: this.mime
})
......@@ -196,6 +197,33 @@ class OSSUpLoader {
}
/**
* 根据文件大小计算最优分片大小
* 策略:文件越大,分片越大,以减少分片数量和请求开销
* @param {number} fileSize - 文件大小 (bytes)
* @returns {number} 分片大小 (bytes)
*/
_getOptimalPartSize(fileSize) {
const MB = 1024 * 1024
// 定义分片策略阶梯 (阈值 -> 分片大小)
// 注意:顺序从大到小排列,匹配即止
const strategies = [
{ 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
]
for (const { threshold, size } of strategies) {
if (fileSize > threshold) {
return size
}
}
// 默认回退到配置的基础大小
return this.partSize * 1024
}
/**
* 将文件路径转换为可下载的文件对象
*
* @param {string} filePath - 文件的路径
......
......@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54
* @LastEditors: limin
* @LastEditTime: 2026-01-20 11:03:00
* @LastEditTime: 2026-01-21 17:13:07
* @FilePath: \simgle_app\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
......@@ -107,11 +107,7 @@ export default {
//开始录音
async startAudio(isInitData = true) {
const isSuccess = await this.recordService.startAudio(isInitData)
if (isSuccess) {
this.initTime()
}
return isSuccess
return this.recordService.startAudio(isInitData)
},
/**
......@@ -120,11 +116,9 @@ export default {
* @returns {void}
*/
async stopAudio(isNotSave = false) {
this.endWatchClick?.()
await this.recordService.stopAudio(isNotSave)
return this.recordService.stopAudio(isNotSave)
},
stop() {
this.endWatchClick?.()
this.recordService.stop()
},
getRecorder() {
......
......@@ -2,64 +2,80 @@
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48
* @LastEditors: limin
* @LastEditTime: 2026-01-20 10:58:35
* @LastEditTime: 2026-01-21 14:23:03
* @FilePath: \simgle_app\mixin\timeout.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
const TIMER_DURATION = 40 * 60 * 1000 //40分钟
const TIMER_INTERVAL = 1 * 60 * 1000 //1分钟检一次
const TIMER_TIMEOUT = TIMER_DURATION / TIMER_INTERVAL
const TIMEOUT = 40 // 40分钟
const Miniute = 60 * 1000
const TIMER_DURATION = TIMEOUT * Miniute
const CHECK_INTERVAL = 1 * Miniute // 1分钟检查一次
import utils from '@/utils/utils'
export default {
data() {
return {
__timerId: null,
_lastActiveTime: 0
}
},
methods: {
//结束提示
stopRecorder() {
// 结束提示
async stopRecorder() {
// if (typeof this.setReceptionStatus === 'function') {
// this.setReceptionStatus(0)
// }
this.recordService.getRecorder().withError()
this.stop()
uni.$logger.local.info(`==${TIMER_DURATION / 60000} 分钟未触碰平板断开录音 ==`)
},
//监听点击事件
initTime() {
uni.$logger.local.info('== 触碰平板开始计时 ==')
this.endWatchClick()
this.__counter = 0
this.__timer = null
this.__timer = setInterval(() => {
if (this.__counter >= TIMER_TIMEOUT) {
//关闭录音
uni.$logger.local.info(`== ${TIMER_DURATION / 60000} 分钟未触碰平板 == __timer:${this.__timer} __counter:${this.__counter}分钟`)
this.endWatchClick()
this.stopRecorder()
return
}
this.__counter++
if (this.__counter % 10 === 0) {
uni.$logger.local.info('== 未触碰平板计时 ==' + this.__counter + '分钟' + '== __timer:' + this.__timer)
// 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 >= TIMER_DURATION) {
await this.__watchStop()
if (!this.__timerId) uni.$logger.local.info(`== 检测到${TIMEOUT}分钟闲置未操作,自动停止录音 ==`)
}
}, TIMER_INTERVAL)
}, CHECK_INTERVAL)
if (this.__timerId) uni.$logger.local.info('== 开启闲置检测 ==')
},
async __watchStop() {
await this.stopRecorder()
this.endWatchClick()
},
// 停止监听
endWatchClick() {
if (this.__timer) {
clearInterval(this.__timer)
uni.$logger.local.info('== 停止监听未触碰平板事件 == __timer:' + this.__timer + ' __counter:' + this.__counter)
if (this.__timerId) {
clearInterval(this.__timerId)
this.__timerId = null
}
this.__timer = null
this.__counter = 0
this._lastActiveTime = null
uni.$logger.local.info('== 停止闲置检测 ==')
},
handleTouchStart() {
if (this.__counter > 0) {
uni.$logger.local.info(`== ${this.__counter}分钟后触碰平板,重置计数器 == __timer:${this.__timer}`)
}
this.__counter = 0
}
// 响应触摸事件
// 使用 debounce 包装:在连续触摸过程中(如滑动屏幕)不更新,
// 只有用户停止操作 1秒后,才更新一次时间戳
handleTouchStart: utils.debounce(function () {
this._lastActiveTime = Date.now()
}, 1500)
},
created() {
uni.$on('reset_timeout', this.handleTouchStart)
},
beforeDestroy() {
if (this.__timer) {
clearInterval(this.__timer)
}
this.__timer = null
this.__counter = 0
uni.$off('reset_timeout', this.handleTouchStart)
this.endWatchClick()
}
}
import { AudioManager, RecordDto, helpler, StrategyFactory } from './index.js'
import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js'
import { storageApi } from '@/utils/cache'
import utils from '@/utils/utils'
import permision from '@/js_sdk/wa-permission/permission.js'
......@@ -12,7 +12,7 @@ class RecordService {
this.recorder = null
this.tempRecord = null
this._startAudioPromise = null
this.timeoutService = null
// 初始化
// this.init() // 不在构造函数中自动初始化,留给外部调用或 getInstance
}
......@@ -27,17 +27,10 @@ class RecordService {
async init() {
if (this.audioManager) return // 避免重复初始化
this.audioManager = new AudioManager(
this.onAudioStart.bind(this),
this.onAudioStop.bind(this),
this.onAudioError.bind(this)
)
this.audioManager = new AudioManager(this.onAudioStart.bind(this), this.onAudioStop.bind(this), this.onAudioError.bind(this))
await this.initDto()
this.recorder = StrategyFactory.getSaveStrategy(
this.tempRecord,
this.triggleTempNumber.bind(this),
this.attributesProvider.bind(this)
)
this.recorder = StrategyFactory.getSaveStrategy(this.tempRecord, this.triggleTempNumber.bind(this), this.attributesProvider.bind(this))
this.timeoutService = new TimeoutService(this.onTimeOut.bind(this))
this.triggleTempNumber()
this.initWatchers()
}
......@@ -49,16 +42,16 @@ class RecordService {
() => {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
{ immediate: true}
{ immediate: true }
)
// 监听 receptionStatus
this.unwatchStatus = store.watch(
(state, getters) => getters.receptionStatus,
(val) => {
val => {
this.handler(val, this.updateReceptionStatus)
},
{ immediate: true}
{ immediate: true }
)
}
......@@ -75,13 +68,23 @@ class RecordService {
}
// 模拟 mixin 中的 computed 映射
get customerInfo() { return this.getters.customerInfo }
get receptionStatus() { return this.getters.receptionStatus }
get customerInfo() {
return this.getters.customerInfo
}
get receptionStatus() {
return this.getters.receptionStatus
}
// get receptionTrack() { return this.getters.receptionTrack }
// get receptionKey() { return this.getters.receptionKey }
get customerKey() { return this.getters.customerKey }
get typeCode() { return this.getters.typeCode }
get materialId() { return this.getters.materialId }
get customerKey() {
return this.getters.customerKey
}
get typeCode() {
return this.getters.typeCode
}
get materialId() {
return this.getters.materialId
}
// 模拟 mixin 中的 mutations
commit(type, payload) {
......@@ -181,8 +184,8 @@ class RecordService {
uni.$logger.local.warn('〖RecordService〗 == 开始接待 ')
isInitData && this.initReception()
// this.initTime() // 移交给调用方处理
this.audioManager.start()
this.timeoutService.start()
return true // 返回 true 表示成功启动
} finally {
this._startAudioPromise = null
......@@ -220,9 +223,17 @@ class RecordService {
}
stop() {
// this.endWatchClick?.() // 这是 Vue 组件的方法,这里无法直接调用
this.recorder?.clearLoopTimer()
this.stopAudioRecord()
}
onTimeOut() {
store.commit('audio/setReceptionStatus', 0)
this.recorder.withError()
this.stopAudioRecord()
}
stopAudioRecord() {
this.audioManager?.stop()
this.timeoutService?.stop()
}
isReceptioning() {
......@@ -284,7 +295,7 @@ class RecordService {
async triggleTempNumber(records) {
if (!this.recorder) return
const _records = records || await this.recorder.getRecords()
const _records = records || (await this.recorder.getRecords())
this.setPerRecordNumber(_records.length)
}
......
......@@ -4,7 +4,7 @@
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-20 12:28:56
* @LastEditTime: 2026-01-21 14:52:37
* @FilePath: \simgle_app\utils\recordManager\TempRecord.js
*/
import utils from '../utils'
......@@ -212,7 +212,7 @@ class TempRecord {
*/
async __update(items) {
if (!this.record || !items || typeof items !== 'object') return
const updates = Object.fromEntries(Object.entries(items).filter(([k, v]) => this.record[k] !== v))
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 })
......
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-06 10:13:02
* @LastEditors: limin
* @LastEditTime: 2026-01-21 17:02:23
* @FilePath: \gl_tape\utils\recordManager\TimeoutService.js
*/
class TimeoutService {
TIMEOUT = 40 // 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(() => {
console.log("🚀 ~ TimeoutService ~ handleTouchStart ~ this._debounceTimer:")
this._lastActiveTime = Date.now()
}, 1000)
}
stop() {
uni.$off('reset_timeout', this.handleTouchStart)
this.endWatchClick()
}
}
export default TimeoutService
......@@ -573,10 +573,10 @@ class UploadService {
}
_startWatchdog() {
const TIMEOUT_THRESHOLD = 5 * 60 * 1000
const TIMEOUT_THRESHOLD = 10 * 60 * 1000
return setTimeout(() => {
if (this.updateResolve) {
uni.$logger.local.error('【上传服务】 == 看门狗检测到任务卡死超过5分钟,强制结束当前任务!')
uni.$logger.local.error('【上传服务】 == 看门狗检测到任务卡死超过10分钟,强制结束当前任务!')
this.endTask()
}
}, TIMEOUT_THRESHOLD)
......
......@@ -17,6 +17,7 @@ import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js'
import helpler from './helpler.js'
import StrategyFactory from './strategies.js'
import TimeoutService from './TimeoutService.js'
// const SingleDBTempRecord = singleton(TempRecord)
export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory }
export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory }
export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService }
export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService }
......@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 17:16:46
* @LastEditors: limin
* @LastEditTime: 2026-01-16 09:31:06
* @LastEditTime: 2026-01-21 15:02:24
* @FilePath: \simgle_app\utils\utils.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
......@@ -283,6 +283,8 @@ const getOAID = () => {
})
}
const nullValues = [undefined,'undefined',null,'null']
export default {
compareVersions,
convertDateTimeFormat,
......@@ -300,5 +302,6 @@ export default {
showNoAccess,
setCopyData,
refreshPageData,
getOAID
getOAID,
nullValues
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!