RecordService.js
8.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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'
import store from '@/store'
class RecordService {
static instance = null
constructor() {
this.audioManager = null
this.recorder = null
this.tempRecord = null
this._startAudioPromise = null
// init 是 async,但构造函数不能 await;用 Promise 让外部在 start 前等待初始化完成
this._initPromise = null
this.timeoutService = null
// 初始化
this._initPromise = this.init()
}
static getInstance() {
if (!RecordService.instance) {
RecordService.instance = new RecordService()
}
return RecordService.instance
}
async init() {
if (this.audioManager) return // 避免重复初始化
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.timeoutService = new TimeoutService(this.onTimeOut.bind(this))
this.triggleTempNumber()
this.initWatchers()
}
initWatchers() {
// 监听 customerKey
this.unwatchCustomer = store.watch(
(state, getters) => getters.customerKey,
() => {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
{ immediate: true }
)
// 监听 receptionStatus
this.unwatchStatus = store.watch(
(state, getters) => getters.receptionStatus,
val => {
this.handler(val, this.updateReceptionStatus)
},
{ immediate: true }
)
}
handler(params, fn) {
if (this.isReceptioning()) {
fn.call(this, params)
}
}
// --- 状态与属性 Getter ---
get getters() {
return store.getters
}
// 模拟 mixin 中的 computed 映射
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
}
// 模拟 mixin 中的 mutations
commit(type, payload) {
store.commit(type, payload)
}
setReceptionStatus(status) {
this.commit('audio/setReceptionStatus', status)
}
setPerRecordNumber(number) {
this.commit('audio/setPerRecordNumber', number)
}
clearCustomerInfo() {
this.commit('clearCustomerInfo')
}
// --- 核心业务逻辑 ---
async initDto() {
const userInfo = storageApi.getUserInfo() || {}
const { userId, userName } = userInfo
const machineCode = await utils.getOAID()
const dto = new RecordDto({
userId,
userName,
machineCode
})
this.tempRecord = dto
}
/**
* 获取动态属性,用于 TempRecord 创建新记录时回调
*/
attributesProvider() {
const typeItem = uni.$storage.get('typeItem') || {}
const dynamicAttrs = {
typeCode: typeItem.typeCode || '',
materialId: this.materialId || ''
}
uni.$logger.local.warn(`〖RecordService〗 == 创建新记录,注入动态属性: ${JSON.stringify(dynamicAttrs)}`)
return dynamicAttrs
}
initReception() {
this.clearCustomerInfo()
}
// --- 音频回调处理 ---
async onAudioStart(res) {
try {
if (this.audioManager.counter === 0) {
uni.$logger.local.info('〖RecordService〗 == First audio segment, adding record...')
await this.recorder.add(res)
uni.$logger.local.info('〖RecordService〗 == Record added successfully.')
} else {
this.recorder.addAudio(res)
}
} catch (e) {
uni.$logger.local.error('〖RecordService〗 == onAudioStart error: ' + e.message)
}
}
async onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.warn('〖RecordService〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.warn('〖RecordService〗 == 断开录音! ')
}
}
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
}
reportError(title, message) {
// 这里需要根据实际情况实现错误上报,或者通过事件通知外部
uni.$logger.local.error(`${title}: ${message}`)
// 如果有全局的错误处理机制,可以在这里调用
}
// --- 录音控制 ---
async startAudio(isInitData = true) {
// 确保 init 完成后再启动计时/录音
await this._initPromise
if (this._startAudioPromise) return this._startAudioPromise
this._startAudioPromise = (async () => {
try {
const isPermission = await this.checkBeforeStart()
if (!isPermission) return false // 返回 false 表示未成功启动
uni.$logger.local.warn('〖RecordService〗 == 开始接待 ')
isInitData && this.initReception()
this.audioManager.start()
this.timeoutService.start()
return true // 返回 true 表示成功启动
} finally {
this._startAudioPromise = null
}
})()
return this._startAudioPromise
}
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.warn('〖RecordService〗 == 不保存记录! ')
await this.recorder.clearSavedFiles()
await this.recorder.clearLocalRecord()
return
}
await this.recorder.setReceptionEndTime() // 设置接待结束时间
// 如果不需要保存记录
await this.recorder.save()
}
stop() {
this.recorder?.clearLoopTimer()
this.stopAudioRecord()
}
onTimeOut() {
store.commit('audio/setReceptionStatus', 0)
this.recorder.withError()
this.stopAudioRecord()
}
stopAudioRecord() {
this.audioManager?.stop()
this.timeoutService?.stop()
}
isReceptioning() {
return this.audioManager?.isRecording || this.recorder?.currentRecord?.endReasonType == 1
}
reset() {
this.audioManager = null
this.recorder = null
this.tempRecord = null
this.timeoutService = null
}
destroy() {
this.unwatchCustomer?.()
this.unwatchStatus?.()
this.recorder?.destroy()
this.stop()
this.reset()
}
// --- 数据更新 ---
updateCustomerInfo(customerInfo = {}) {
const { customerName, customerPhone, customerType, carType } = customerInfo
const params = {
customerName,
customerPhone,
customerType,
carType
}
this.recorder?.updatePreRecords(params)
}
updateReceptionStatus(status) {
this.recorder?.updatePreRecords({ result: status })
}
// --- 权限检查 ---
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
}
// --- 辅助方法 ---
async triggleTempNumber(records) {
if (!this.recorder) return
const _records = records || (await this.recorder.getRecords())
this.setPerRecordNumber(_records.length)
}
getRecorder() {
return this.recorder
}
}
export default RecordService