Commit 0f5a6103 by 岑成威

Merge branch 'saas+v5.9.0' into saas+v5.8.3

2 parents 02540f16 219c6421
Showing 115 changed files with 3377 additions and 1036 deletions
......@@ -5,6 +5,11 @@
import { Ws } from '@/ws/Ws.js'
import { RecordSaveService, UploadService } from '@/utils/recordManager/index.js'
import appCacheApi from '@/utils/clearAppCache.js'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
// #ifdef APP-PLUS
import StoragePathMerge from '@/utils/storageMerge/StoragePathMerge.js'
import { logStep as mergeLogStep, logStepFail as mergeLogStepFail } from '@/utils/storageMerge/log.js'
// #endif
export default {
computed: {
...mapState('audio', ['isEnd', 'isStart'])
......@@ -13,6 +18,27 @@
userInfo: uni.getStorageSync('release_userInfo')
},
onLaunch: async function () {
// 先拉取/应用悬浮窗配置并 install,再合并,避免启动日志丢失
try {
await FloatLogConfig.refreshFromServer(true)
} catch (_) {
/* ignore */
}
// #ifdef APP-PLUS
try {
await uni.$dbRecord.init()
mergeLogStep('归并·启动', 'App onLaunch:主库 init 完成,调用 StoragePathMerge.run()')
await StoragePathMerge.run()
} catch (e) {
mergeLogStepFail('归并·启动', '启动数据库/合并异常', { 错误: e?.message || String(e) })
} finally {
uni.$resolveStorageMerge?.()
mergeLogStep('归并·启动', 'App onLaunch:归并流程结束(uni.$resolveStorageMerge 已触发)')
}
// #endif
// #ifndef APP-PLUS
uni.$resolveStorageMerge?.()
// #endif
this.onKeep()
// this.setAPPVersion()
setTimeout(() => {
......@@ -52,21 +78,10 @@
appCacheApi.clearAppCache()
this.$store.dispatch('setBackgroundState', false)
this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling()
uni.onMemoryWarning(function () {
console.log('onMemoryWarningReceive')
})
// const systemInfo = await uni.$api.systemApi.getMockData();
// if (systemInfo.isCheckedUpdate) {
// checkUpdate();
// }
// let version = plus.runtime.version;
// uni.$api.commonApi.getAPPVersion().then((res) => {
// if (res != version && !systemInfo.isCheckedUpdate)
// this.$store.dispatch("openUpdateModal");
// });
},
onHide: function () {
this.$store.dispatch('setBackgroundState', true)
......@@ -168,4 +183,3 @@
left: 0rpx;
}
</style>
\ No newline at end of file
......@@ -21,6 +21,11 @@ const getMockData = async (immediate = false) => {
const MOCKDATA = uni.$storage.get('mock_data')
try {
if (!immediate && MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) {
try {
require('@/utils/logger/FloatLogConfig.js').default.applyFromMockData(MOCKDATA)
} catch (e) {
/* ignore */
}
return Promise.resolve(MOCKDATA)
} else {
if (!serverConfig.mockRequestCount || immediate) {
......@@ -30,6 +35,11 @@ const getMockData = async (immediate = false) => {
data.createTime = Date.now()
serverConfig.mockCache = data
uni.$storage.set('mock_data', data)
try {
require('@/utils/logger/FloatLogConfig.js').default.applyFromMockData(data)
} catch (e) {
/* ignore */
}
return Promise.resolve(data)
} else {
const key = Date.now()
......
......@@ -143,15 +143,21 @@
</view>
</template>
</ErrorOrderPopup>
<!-- #ifdef APP-PLUS -->
<AiAssistantBall :visible="showAiAssistant" />
<!-- #endif -->
<FloatLogPanel v-if="showFloatLog" />
</view>
</template>
<script>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
// #ifdef APP-PLUS
import AiAssistantBall from '@/components/AiAssistantBall/AiAssistantBall.vue'
// #endif
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import ReceptionCenter from './components/ReceptionCenter/index.vue'
import SceneMarket from './components/SceneMarket/index.vue'
// import myClick from '@/mixin/click'
import timeout from '@/mixin/timeout'
import recorder from '@/mixin/record/recorder'
import uploader from '@/mixin/record/uploader.js'
import versionCheck from '@/mixin/versionCheck.js'
import LeftSide from './components/LeftSide.vue'
import Point from './components/Point.vue'
......@@ -164,7 +170,7 @@ import Ranking from './components/Point/Ranking.vue'
import Calendar from './components/Income/Calendar.vue'
import Promotion from './components/Income/Promotion.vue'
import History from './components/Income/History.vue'
// import merge from '@/mixin/record/merge.js'
import merge from '@/mixin/record/merge.js'
import MessageDetail from './components/Message/MessageDetail.vue'
import SwiperComponent from '../SwiperComponent.vue'
import StudyCenter from './components/StudyCenter.vue'
......@@ -180,11 +186,15 @@ import ExamSubmitPopup from '@/components/ExamSubmitPopup.vue'
import StudyCenterPermissionPopup from '@/components/StudyCenterPermissionPopup.vue'
import ActivityPopup from './components/ActivityPopup.vue'
import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue'
import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js'
import { FileUploadManager } from '@/utils/recordManager/index.js'
export default {
// mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin],
mixins: [recorder, versionCheck, interceptionMixin],
mixins: [ recorder, versionCheck, interceptionMixin, merge],
components: {
FloatLogPanel,
// #ifdef APP-PLUS
AiAssistantBall,
// #endif
ReceptionCenter,
StudyCenter,
SceneMarket,
......@@ -229,10 +239,16 @@ export default {
type: Boolean,
default: true
},
swiperCustom: Boolean
swiperCustom: Boolean,
/** 接待详情页展示 AI 悬浮球 */
showAiAssistant: {
type: Boolean,
default: false
}
},
data() {
return {
showFloatLog: false,
studyUrl: '',
jumpUrl: '',
transfer: '',
......@@ -271,12 +287,17 @@ export default {
}
},
beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
// 组件销毁前移除监听
uni.$logger.local.info('levelStudyPopup 移除监听')
uni.$off('levelStudyPopup')
uni.$off('pageBack')
},
async mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
uni.$logger.local.info('levelStudyPopup 开始监听mounted')
uni.$on('levelStudyPopup', obj => {
uni.$logger.local.info('接收到学习弹窗事件', obj)
......@@ -352,6 +373,9 @@ export default {
this.getStoreBaseSceneCodeList()
},
methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
},
// 处理开始测评(参考 detail.vue 的实现)
async handleStartAssessment() {
this.showStudyPopup = false
......
......@@ -19,13 +19,18 @@
{{ title }}
</view>
<slot></slot>
<FloatLogPanel v-if="showFloatLog" />
</view>
</template>
<script type='text/ecmascript-6'>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
export default {
components: { FloatLogPanel },
props: {
pageStyle:{
pageStyle: {
type: String,
default: ''
},
......@@ -49,14 +54,24 @@ export default {
default: ''
}
},
name: '',
data () {
data() {
return {
showFloatLog: false
}
},
mounted () {
mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
},
beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
},
methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
}
}
}
</script>
......@@ -91,4 +106,4 @@ export default {
}
}
}
</style>
\ No newline at end of file
</style>
......@@ -2,7 +2,7 @@ module.exports = {
// 请求域名 格式:https://xxx.xxx.com
HTTP_REQUEST_URL: 'http://127.0.0.1:8000/api',
// 阿里云oss域名 格式:https://xxx.oss-cn-xxx.aliyuncs.com
// 阿里云oss域名 格式:https://xxx.oss-cn-shenzhen.aliyuncs.com
OSS_DOMAIN: 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com',
// 文件直传到阿里云oss时需用到
......
......@@ -103,13 +103,16 @@ uni.signHttpConfig = {
if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord()
}
uni.$storageMergeDone = new Promise(resolve => {
uni.$resolveStorageMerge = resolve
})
// 导出数据库初始化 Promise,供其他模块等待
if (!uni.$dbReady) {
uni.$dbReady = (async _ => {
try {
await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃
uni.$logger.local.info('数据库初始化完成')
await uni.$storageMergeDone
uni.$logger.local.info('数据库初始化与路径合并已完成')
return true
} catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message)
......
import TaskQueue from '../utils/TaskQueue'
import { PathUtils } from '../utils/recordManager/index'
// import TaskQueue from '../utils/TaskQueue'
// import { PathUtils } from '../utils/recordManager/index'
class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size) {
constructor(name, version, description, size, dbPath) {
this.name = name
this.version = version || '1.0'
this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null
//注意:
this.dbPath = `_doc/${name}.db` // 存储数据库的完整路径
this.dbPath = `_doc/${name}.db` // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
}
this.dbPath = dbPath || `_doc/${name}.db`
}
_enqueue(task) {
......@@ -25,16 +19,8 @@ class SQLite {
}
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()
uni.$logger?.local?.info(`[SQLite] 使用已有路径: ${this.dbPath}`)
return this.openDatabase()
}
/**
......@@ -71,52 +57,46 @@ class SQLite {
}
selectSql(sql) {
return this._enqueue(
() =>
new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
// 处理查询结果,尝试还原数组或对象字符串
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
// 优化:仅当 value 是字符串且以 { 或 [ 开头时才尝试解析
// 避免将普通数字字符串(如 "123")误解析为 Number 导致精度丢失
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try {
return [key, JSON.parse(value)]
} catch {
return [key, value]
}
}
return new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
// 处理查询结果,尝试还原数组或对象字符串
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
// 优化:仅当 value 是字符串且以 { 或 [ 开头时才尝试解析
// 避免将普通数字字符串(如 "123")误解析为 Number 导致精度丢失
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try {
return [key, JSON.parse(value)]
} catch {
return [key, value]
})
)
)
resolve(processedRows)
},
fail: reject
})
})
)
}
}
return [key, value]
})
)
)
resolve(processedRows)
},
fail: reject
})
})
}
executeSql(sql) {
return this._enqueue(
() =>
new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
)
return new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
}
async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
......@@ -207,11 +187,31 @@ class SQLite {
return isopen
}
close() {
if (this.db) {
this.db.close()
this.db = null
console.log('数据库连接已关闭')
}
return this.closeDatabase()
}
/** 关闭 plus.sqlite 连接(与 openDatabase 配对) */
closeDatabase() {
return new Promise((resolve, reject) => {
if (!this.isOpen()) {
resolve()
return
}
plus.sqlite.closeDatabase({
name: this.name,
success: () => {
uni.$logger?.local?.info(`[SQLite] 数据库已关闭: ${this.name}`)
resolve()
},
fail: err => {
if (err && err.code === -1402) {
resolve()
return
}
reject(err)
}
})
})
}
drop(tabName) {
const sql = `DROP TABLE IF EXISTS ${tabName}`
......
......@@ -31,7 +31,6 @@
/* 模块配置 */
"modules" : {
"Camera" : {},
"Record" : {},
"VideoPlayer" : {},
"AudioPlayer" : {},
"SQLite" : {},
......@@ -90,6 +89,13 @@
"xhdpi" : "static/96.png",
"xxhdpi" : "static/144.png"
}
},
"plugins" : {
"audio" : {
"mp3" : {
"description" : "Android平台录音支持MP3格式文件"
}
}
}
},
"nativePlugins" : {
......
import { storageApi } from '@/utils/cache'
/** 从 doc 绝对路径推导包根目录(兼容 uni.gltap / io.dcloud.HBuilder) */
function resolvePackageRootFromDocUrl(docUrl) {
if (!docUrl) return ''
const normalized = String(docUrl).replace(/^file:\/\//, '').replace(/\/+$/, '')
const match = normalized.match(/^(.+?)\/apps\/[^/]+\/doc$/)
if (match) return `${match[1]}/`
const gltap = normalized.replace(/gltap.+/, 'gltap/')
return gltap !== normalized ? gltap : ''
}
export default {
mounted() {
// this.mergeRecord()
......@@ -60,8 +71,10 @@ export default {
processNextEntry() // 处理下一个条目
},
function (e) {
console.log('文件删除失败:', e.message)
uni.$logger.local.info(`文件删除失败: ->${entry.fullPath} ->${e.message}`)
// 文件占用/无权限时常见,避免刷屏
uni.$logger?.local?.debug?.(
`清理跳过文件:${entry.fullPath} -> ${e.message || e}`
)
deleteCount++
processNextEntry() // 处理下一个条目
}
......@@ -102,24 +115,32 @@ export default {
)
},
clearPrevFile() {
let version = plus.runtime.version
let clearVersion = uni.$storage.get('clearVersion')
if (typeof plus === 'undefined') return
if (this._clearPrevFileRunning) return
if (clearVersion != version) {
const wwwPath = plus.io.convertLocalFileSystemURL('doc')
// const filesPath = wwwPath.replace(/apps.+/, 'apps/')
// console.log(filesPath)
const filesPath = wwwPath.replace(/gltap.+/, 'gltap/')
this.getDirectoryContents(filesPath)
}
setTimeout(() => {
const version = plus.runtime.version
const clearVersion = uni.$storage.get('clearVersion')
if (clearVersion === version) return
const docPath = plus.io.convertLocalFileSystemURL('_doc')
const filesPath = resolvePackageRootFromDocUrl(docPath)
if (!filesPath) {
uni.$storage.set('clearVersion', version)
}, 5000)
return
}
// 立即标记,避免 HomeFrame 反复挂载时在 5s 内重复整目录清理
uni.$storage.set('clearVersion', version)
this._clearPrevFileRunning = true
uni.$logger?.local?.info?.(`版本升级清理包根目录:${filesPath}`)
this.getDirectoryContents(filesPath)
},
getDirectoryContents(dirPath) {
// 解析目录路径
const _this = this
const excludeFile = ['databases']
// 切勿删除 apps / databases,否则会扫到正在使用的 doc、库文件并报「不允许读」
const excludeFile = ['databases', 'apps', 'cache', 'files']
plus.io.resolveLocalFileSystemURL(
dirPath,
function (entry) {
......@@ -132,10 +153,10 @@ export default {
console.log('目录内容读取成功:')
_this.directoryList = entries
entries.forEach(function (entry) {
console.log('文件路径:', entry.fullPath)
if (!excludeFile.includes(entry.name)) {
_this.deleteDirectory(entry.fullPath)
}
const name = entry.name || ''
if (excludeFile.includes(name)) return
if (entry.isFile && /\.db$/i.test(name)) return
_this.deleteDirectory(entry.fullPath)
})
},
function (e) {
......
/*
* @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()
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54
* @LastEditors: cenchengwei@foreverht.com
* @LastEditTime: 2026-04-08 15:23:08
* @FilePath: /gl_tape/mixin/record/recorder.js
* @LastEditors: limin
* @LastEditTime: 2026-06-11 17:25:43
* @FilePath: \gl_tape\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import RecordService from '../../utils/recordManager/RecordService'
import { mapMutations, mapState, mapGetters } from 'vuex'
import { mapMutations } from 'vuex'
export default {
provide() {
return {
......
......@@ -4,6 +4,7 @@
@start="$refs.customerTypeRef.open()"
ref="home"
:id="id"
:show-ai-assistant="recording && !!id"
@openStep="openStep"
@backHome="backHome"
finishDoneText="下一步"
......
......@@ -5,6 +5,7 @@
@start="start"
ref="home"
:id="id"
:show-ai-assistant="recording && !!id"
@openStep="openStep"
@backHome="backHome"
@changeTab="changeTab"
......
No preview for this file type
## 为减小组件包的大小,默认组件包中不包含编辑、latex 公式等扩展功能,需要使用扩展功能的请参考下方的 插件扩展 栏的说明
## 功能介绍
- 全端支持(含 `v3、NVUE`)
- 支持丰富的标签(包括 `table`、`video`、`svg` 等)
- 支持丰富的事件效果(自动预览图片、链接处理等)
- 支持设置占位图(加载中、出错时、预览时)
- 支持锚点跳转、长按复制等丰富功能
- 支持大部分 *html* 实体
- 丰富的插件(关键词搜索、内容编辑、`latex` 公式等)
- 效率高、容错性强且轻量化
查看 [功能介绍](https://jin-yufeng.github.io/mp-html/#/overview/feature) 了解更多
## 使用方法
- `uni_modules` 方式
1. 点击右上角的 `使用 HBuilder X 导入插件` 按钮直接导入项目或点击 `下载插件 ZIP` 按钮下载插件包并解压到项目的 `uni_modules/mp-html` 目录下
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<!-- 不需要引入,可直接使用 -->
<mp-html :content="html" />
```
```javascript
export default {
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时在 `HBuilder X` 中右键 `uni_modules/mp-html` 目录选择 `从插件市场更新` 即可
- 源码方式
1. 从 [github](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 或 [gitee](https://gitee.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 下载源码
插件市场的 **非 uni_modules 版本** 无法更新,不建议从插件市场获取
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from '@/components/mp-html/mp-html'
export default {
// HBuilderX 2.5.5+ 可以通过 easycom 自动引入
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
- npm 方式
1. 在项目根目录下执行
```bash
npm install mp-html
```
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html'
export default {
// 不可省略
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时执行以下命令即可
```bash
npm update mp-html
```
使用 *cli* 方式运行的项目,通过 *npm* 方式引入时,需要在 *vue.config.js* 中配置 *transpileDependencies*,详情可见 [#330](https://github.com/jin-yufeng/mp-html/issues/330#issuecomment-913617687)
如果在 **nvue** 中使用还要将 `dist/uni-app/static` 目录下的内容拷贝到项目的 `static` 目录下,否则无法运行
查看 [快速开始](https://jin-yufeng.github.io/mp-html/#/overview/quickstart) 了解更多
## 组件属性
| 属性 | 类型 | 默认值 | 说明 |
|:---:|:---:|:---:|---|
| container-style | String | | 容器的样式([2.1.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v210)) |
| content | String | | 用于渲染的 html 字符串 |
| copy-link | Boolean | true | 是否允许外部链接被点击时自动复制 |
| domain | String | | 主域名(用于链接拼接) |
| error-img | String | | 图片出错时的占位图链接 |
| lazy-load | Boolean | false | 是否开启图片懒加载 |
| loading-img | String | | 图片加载过程中的占位图链接 |
| pause-video | Boolean | true | 是否在播放一个视频时自动暂停其他视频 |
| preview-img | Boolean | true | 是否允许图片被点击时自动预览 |
| scroll-table | Boolean | false | 是否给每个表格添加一个滚动层使其能单独横向滚动 |
| selectable | Boolean | false | 是否开启文本长按复制 |
| set-title | Boolean | true | 是否将 title 标签的内容设置到页面标题 |
| show-img-menu | Boolean | true | 是否允许图片被长按时显示菜单 |
| tag-style | Object | | 设置标签的默认样式 |
| use-anchor | Boolean | false | 是否使用锚点链接 |
查看 [属性](https://jin-yufeng.github.io/mp-html/#/basic/prop) 了解更多
## 组件事件
| 名称 | 触发时机 |
|:---:|---|
| load | dom 树加载完毕时 |
| ready | 图片加载完毕时 |
| error | 发生渲染错误时 |
| imgtap | 图片被点击时 |
| linktap | 链接被点击时 |
| play | 音视频播放时 |
查看 [事件](https://jin-yufeng.github.io/mp-html/#/basic/event) 了解更多
## api
组件实例上提供了一些 `api` 方法可供调用
| 名称 | 作用 |
|:---:|---|
| in | 将锚点跳转的范围限定在一个 scroll-view 内 |
| navigateTo | 锚点跳转 |
| getText | 获取文本内容 |
| getRect | 获取富文本内容的位置和大小 |
| setContent | 设置富文本内容 |
| imgList | 获取所有图片的数组 |
| pauseMedia | 暂停播放音视频([2.2.2+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v222)) |
| setPlaybackRate | 设置音视频播放速率([2.4.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v240)) |
查看 [api](https://jin-yufeng.github.io/mp-html/#/advanced/api) 了解更多
## 插件扩展
除基本功能外,本组件还提供了丰富的扩展,可按照需要选用
| 名称 | 作用 |
|:---:|---|
| audio | 音乐播放器 |
| editable | 富文本 **编辑**([示例项目](https://mp-html.oss-cn-hangzhou.aliyuncs.com/editable.zip)) |
| emoji | 解析 emoji |
| highlight | 代码块高亮显示 |
| markdown | 渲染 markdown |
| search | 关键词搜索 |
| style | 匹配 style 标签中的样式 |
| txv-video | 使用腾讯视频 |
| img-cache | 图片缓存 by [@PentaTea](https://github.com/PentaTea) |
| latex | 渲染 latex 公式 by [@Zeng-J](https://github.com/Zeng-J) |
从插件市场导入的包中 **不含有** 扩展插件,使用插件需通过微信小程序 `富文本插件` 获取或参考以下方法进行打包:
1. 获取完整组件包
```bash
npm install mp-html
```
2. 编辑 `tools/config.js` 中的 `plugins` 项,选择需要的插件
3. 生成新的组件包
在 `node_modules/mp-html` 目录下执行
```bash
npm install
npm run build:uni-app
```
4. 拷贝 `dist/uni-app` 中的内容到项目根目录
查看 [插件](https://jin-yufeng.github.io/mp-html/#/advanced/plugin) 了解更多
## 关于 nvue
`nvue` 使用原生渲染,不支持部分 `css` 样式,为实现和 `html` 相同的效果,组件内部通过 `web-view` 进行渲染,性能上差于原生,根据 `weex` 官方建议,`web` 标签仅应用在非常规的降级场景。因此,如果通过原生的方式(如 `richtext`)能够满足需要,则不建议使用本组件,如果有较多的富文本内容,则可以直接使用 `vue` 页面
由于渲染方式与其他端不同,有以下限制:
1. 不支持 `lazy-load` 属性
2. 视频不支持全屏播放
3. 如果在 `flex-direction: row` 的容器中使用,需要给组件设置宽度或设置 `flex: 1` 占满剩余宽度
纯 `nvue` 模式下,[此问题](https://ask.dcloud.net.cn/question/119678) 修复前,不支持通过 `uni_modules` 引入,需要本地引入(将 [dist/uni-app](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 中的内容拷贝到项目根目录下)
## 问题反馈
遇到问题时,请先查阅 [常见问题](https://jin-yufeng.github.io/mp-html/#/question/faq) 和 [issue](https://github.com/jin-yufeng/mp-html/issues) 中是否已有相同的问题
可通过 [issue](https://github.com/jin-yufeng/mp-html/issues/new/choose) 、插件问答或发送邮件到 [mp_html@126.com](mailto:mp_html@126.com) 提问,不建议在评论区提问(不方便回复)
提问请严格按照 [issue 模板](https://github.com/jin-yufeng/mp-html/issues/new/choose) ,描述清楚使用环境、`html` 内容或可复现的 `demo` 项目以及复现方式,对于 **描述不清**、**无法复现** 或重复的问题将不予回复
欢迎加入 `QQ` 交流群:
群1(已满):`699734691`
群2(已满):`778239129`
群3:`960265313`
查看 [问题反馈](https://jin-yufeng.github.io/mp-html/#/question/feedback) 了解更多
// marked v16+ 依赖 at(),App 端部分 JS 引擎未实现
if (!String.prototype.at) {
// eslint-disable-next-line no-extend-native
String.prototype.at = function (index) {
index = Math.trunc(index) || 0
if (index < 0) index += this.length
if (index < 0 || index >= this.length) return undefined
return this.charAt(index)
}
}
if (!Array.prototype.at) {
// eslint-disable-next-line no-extend-native
Array.prototype.at = function (index) {
index = Math.trunc(index) || 0
if (index < 0) index += this.length
if (index < 0 || index >= this.length) return undefined
return this[index]
}
}
/**
* @fileoverview markdown 插件
* Include marked (https://github.com/markedjs/marked)
* Include github-markdown-css (https://github.com/sindresorhus/github-markdown-css)
*/
import './at-polyfill.js'
import { marked } from './marked.min'
let index = 0
function Markdown (vm) {
this.vm = vm
vm._ids = {}
}
Markdown.prototype.onUpdate = function (content) {
if (this.vm.markdown) {
// 解决中文标点符号后粗体失效的问题,增加零宽空格
content = content.replace(/\*\*([^*]+)\*\*([,。!?;:])/g, '**$1**&#8203;$2')
return marked(content)
}
}
Markdown.prototype.onParse = function (node, vm) {
if (vm.options.markdown) {
// 中文 id 需要转换,否则无法跳转
if (vm.options.useAnchor && node.attrs && /[\u4e00-\u9fa5]/.test(node.attrs.id)) {
const id = 't' + index++
this.vm._ids[node.attrs.id] = id
node.attrs.id = id
}
if (node.name === 'p' || node.name === 'table' || node.name === 'tr' || node.name === 'th' || node.name === 'td' || node.name === 'blockquote' || node.name === 'pre' || node.name === 'code') {
node.attrs.class = `md-${node.name} ${node.attrs.class || ''}`
}
}
}
export default Markdown
{
"id": "mp-html",
"displayName": "mp-html 富文本组件【全端支持,支持编辑、latex等扩展】",
"version": "v2.5.2",
"description": "一个强大的富文本组件,高效轻量,功能丰富",
"keywords": [
"富文本",
"编辑器",
"html",
"rich-text",
"editor"
],
"repository": "https://github.com/jin-yufeng/mp-html",
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/mp-html",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"platforms": {
"cloud": {
"tcb": "√",
"aliyun": "√",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "√",
"android": "√",
"ios": "√",
"harmony": "-"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "-",
"baidu": "√",
"kuaishou": "-",
"jd": "-",
"harmony": "-",
"qq": "√",
"lark": "√"
},
"quickapp": {
"huawei": "-",
"union": "-"
}
},
"uni-app-x": {
"web": {
"safari": "-",
"chrome": "-"
},
"app": {
"android": "-",
"ios": "-",
"harmony": "-"
},
"mp": {
"weixin": "-"
}
}
}
}
},
"engines": {
"HBuilderX": "^3.1.0",
"uni-app": "^3.6.15",
"uni-app-x": ""
}
}
\ No newline at end of file
"use strict";function t(t){for(var e=Object.create(null),n=t.attributes.length;n--;)e[t.attributes[n].name]=t.attributes[n].value;return e}function e(){a[1]&&(this.src=a[1],this.onerror=null),this.onclick=null,this.ontouchstart=null,uni.postMessage({data:{action:"onError",source:"img",attrs:t(this)}})}function n(){window.unloadimgs-=1,0===window.unloadimgs&&uni.postMessage({data:{action:"onReady"}})}function o(r,s,c){for(var d=0;d<r.length;d++)!function(){var u,l=r[d];if(l.type&&"node"!==l.type)u=document.createTextNode(l.text.replace(/&amp;/g,"&"));else{var g=l.name;"svg"===g&&(c="http://www.w3.org/2000/svg"),"html"!==g&&"body"!==g||(g="div"),u=c?document.createElementNS(c,g):document.createElement(g);for(var p in l.attrs)u.setAttribute(p,l.attrs[p]);if(l.children&&o(l.children,u,c),"img"===g){if(window.unloadimgs+=1,u.onload=n,u.onerror=n,!u.src&&u.getAttribute("data-src")&&(u.src=u.getAttribute("data-src")),l.attrs.ignore||(u.onclick=function(e){e.stopPropagation(),uni.postMessage({data:{action:"onImgTap",attrs:t(this)}})}),a[2]){var h=new Image;h.src=u.src,u.src=a[2],h.onload=function(){u.src=this.src},h.onerror=function(){u.onerror()}}u.onerror=e}else if("a"===g)u.addEventListener("click",function(e){e.stopPropagation(),e.preventDefault();var n,o=this.getAttribute("href");o&&"#"===o[0]&&(n=(document.getElementById(o.substr(1))||{}).offsetTop),uni.postMessage({data:{action:"onLinkTap",attrs:t(this),offset:n}})},!0);else if("video"===g||"audio"===g)i.push(u),l.attrs.autoplay||l.attrs.controls||u.setAttribute("controls","true"),u.onplay=function(){if(uni.postMessage({data:{action:"onPlay"}}),a[3])for(var t=0;t<i.length;t++)i[t]!==this&&i[t].pause()},u.onerror=function(){uni.postMessage({data:{action:"onError",source:g,attrs:t(this)}})};else if("table"===g&&a[4]&&!u.style.cssText.includes("inline")){var f=document.createElement("div");f.style.overflow="auto",f.appendChild(u),u=f}else"svg"===g&&(c=void 0)}s.appendChild(u)}()}document.addEventListener("UniAppJSBridgeReady",function(){document.body.onclick=function(){return uni.postMessage({data:{action:"onClick"}})},uni.postMessage({data:{action:"onJSBridgeReady"}})});var a,i=[];window.setContent=function(t,e,n){var r=document.getElementById("content");e[0]&&(document.body.style.cssText=e[0]),e[5]||(r.style.userSelect="none"),n||(r.innerHTML="",i=[]),a=e,window.unloadimgs=0;var s=document.createDocumentFragment();o(t,s),r.appendChild(s);var c=r.scrollHeight;uni.postMessage({data:{action:"onLoad",height:c}}),window.unloadimgs||uni.postMessage({data:{action:"onReady",height:c}}),clearInterval(window.timer),window.timer=setInterval(function(){r.scrollHeight!==c&&(c=r.scrollHeight,uni.postMessage({data:{action:"onHeightChange",height:c}}))},350)},window.onunload=function(){clearInterval(window.timer)};
\ No newline at end of file
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function t(e,t){return n.call(e,t)}var i=[],a=function(e,n){var t={options:{timestamp:+new Date},name:e,arg:n};if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){if("postMessage"===e){var a={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(a):window.__dcloud_weex_.postMessage(JSON.stringify(a))}var o={type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(o):window.__dcloud_weex_.postMessageToService(JSON.stringify(o))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:t,pageId:""},"*");if(0===i.length){var r=plus.webview.currentWebview();if(!r)throw new Error("plus.webview.currentWebview() is undefined");var d=r.parent(),s="";s=d?d.id:r.id,i.push(s)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}},"__uniapp__service");else{var w=JSON.stringify(t);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(w,",").concat(JSON.stringify(i),");"))}},o={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;a("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("redirectTo",{url:encodeURI(n)})},getEnv:function(e){window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a("postMessage",e.data||{})}},r=/uni-app/i.test(navigator.userAgent),d=/Html5Plus/i.test(navigator.userAgent),s=/complete|loaded|interactive/;var w=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var u=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var g=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var v=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);for(var l,_=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},f=[function(e){if(r||d)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&s.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),o},function(e){if(v)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(w){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(u)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){return document.addEventListener("DOMContentLoaded",e),o}],m=0;m<f.length&&!(l=f[m](_));m++);l||(l={});var E="undefined"!=typeof uni?uni:{};if(!E.navigateTo)for(var b in l)t(l,b)&&(E[b]=l[b]);return E.webView=l,E}));
\ No newline at end of file
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>body,html{width:100%;height:100%;overflow-x:scroll;overflow-y:hidden}body{margin:0}video{width:300px;height:225px}img{max-width:100%;-webkit-touch-callout:none}</style></head><body><div id="content" style="overflow:hidden"></div><script type="text/javascript" src="./js/uni.webview.min.js"></script><script type="text/javascript" src="./js/handler.js"></script></body>
\ No newline at end of file
{
"id": "uni-recorder-x",
"displayName": "uni-recorder-x 录音",
"version": "1.0.0",
"description": "基于 getRecorderManager API 实现的录音插件,支持 onFrameRecorded 实时音频流回调",
"keywords": [
"recorder",
"录音",
"uts"
],
"repository": "",
"engines": {
"HBuilderX": "^4.01",
"uni-app": "^4.34",
"uni-app-x": "^4.61"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": {
"price": "0.00"
}
},
"contact": {},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"app": {
"vue": "√",
"nvue": "√",
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
}
},
"uni-app-x": {
"app": {
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
}
}
}
}
}
}
# uni-getRecorderManager
实现录音管理功能。
[API规范文档](https://doc.dcloud.net.cn/uni-app-x/api/get-recorder-manager.html)
## uts 语言介绍
uts,全称 uni type script,是一门跨平台的、高性能的、强类型的现代编程语言。
它可以被编译为不同平台的编程语言,如:
Android平台:编译为Kotlin
iOS平台:编译Swift
鸿蒙OS平台:编译为ArkTS
web平台/小程序:编译为JavaScript
uts 采用了与 ts 基本一致的语法规范,支持绝大部分 ES6 API。
但为了跨端,uts进行了一些约束和特定平台的增补。
过去在js引擎下运行支持的语法,大部分在uts的处理下也可以平滑的在kotlin和swift中使用。但有一些无法抹平,需要使用条件编译。
和uni-app的条件编译类似,uts也支持条件编译。写在条件编译里的,可以调用平台特有的扩展语法。
## uts 插件介绍
UTS 插件是一种特定的 uni_modules 插件,其核心目的是允许 uni-app/uni-app x 开发者使用 UTS 语法来调用扩展 API(封装原生系统的API或三方SDK)。
UTS 插件的实现代码主要位于 utssdk 目录下,并按平台进行分离和组织:
| 目录/文件 | 目标平台 | 实现语言 | 作用描述 |
| -- | -- | -- | -- |
|utssdk/app-android|Android|UTS, Kotlin, Java|存放 UTS 插件在 Android 平台上的具体实现源码|
|utssdk/app-ios|iOS|UTS, Swift|存放 UTS 插件在 iOS 平台上的具体实现源码|
|utssdk/app-harmony|HarmonyOS (鸿蒙)|UTS, ArkTS|存放 UTS 插件在 HarmonyOS 平台上的具体实现源码|
|utssdk/*.uts|多平台共用|UTS|存放使用 UTS 语言编写的、可供 所有平台 共用的实现源码|
## 参考文档
- [uts 语言介绍](https://doc.dcloud.net.cn/uni-app-x/uts/)
- [uts 和 ts 的差异](https://doc.dcloud.net.cn/uni-app-x/uts/uts_diff_ts.html)
- [uts 插件开发文档](https://doc.dcloud.net.cn/uni-app-x/plugin/uts-plugin.html)
- [uts 插件原生语言混编开发文档](https://doc.dcloud.net.cn/uni-app-x/plugin/uts-plugin-hybrid.html)
- [uts 插件 Android 平台开发注意事项](https://doc.dcloud.net.cn/uni-app-x/plugin/uts-for-android.html)
- [uts 插件 iOS 平台开发注意事项](https://doc.dcloud.net.cn/uni-app-x/plugin/uts-for-ios.html)
- [uts 插件 HarmonyOS 平台开发注意事项](https://doc.dcloud.net.cn/uni-app-x/plugin/uts-for-ios.html)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application>
</application>
</manifest>
\ No newline at end of file
package uts.sdk.modules.uniRecorder
import android.util.Log
/**
* 运行时由 manifest plugins.audio.mp3 注入 SimpleLame;
* 编译期不 import、不打包 audio-mp3aac aar,避免 Dex 重复。
*/
object SimpleLameBridge {
private const val TAG = "SimpleLameBridge"
private const val CLASS_NAME = "io.dcloud.feature.audio.mp3.SimpleLame"
private var lameClass: Class<*>? = null
private fun clazz(): Class<*> {
if (lameClass == null) {
lameClass = Class.forName(CLASS_NAME)
}
return lameClass!!
}
fun init(inSampleRate: Int, channelCount: Int, outSampleRate: Int, bitrateKbps: Int, quality: Int) {
val method = clazz().getMethod(
"init",
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType
)
method.invoke(null, inSampleRate, channelCount, outSampleRate, bitrateKbps, quality)
}
fun encode(bufferL: ShortArray, bufferR: ShortArray, samples: Int, mp3buf: ByteArray): Int {
val method = clazz().getMethod(
"encode",
ShortArray::class.java,
ShortArray::class.java,
Int::class.javaPrimitiveType,
ByteArray::class.java
)
return method.invoke(null, bufferL, bufferR, samples, mp3buf) as Int
}
fun flush(mp3buf: ByteArray): Int {
val method = clazz().getMethod("flush", ByteArray::class.java)
return method.invoke(null, mp3buf) as Int
}
fun close() {
try {
val method = clazz().getMethod("close")
method.invoke(null)
} catch (e: Exception) {
Log.w(TAG, "SimpleLame.close failed: ${e.message}")
}
}
}
import { API_GET_RECORDER_MANAGER } from '../protocol.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail, OnFrameRecordedResult } from '../interface.uts';
import { createFile } from './utils.uts';
import LogSelfV2 from "io.dcloud.uts.log.LogSelfV2";
import { RecorderManagerFailImpl, RecorderManagerUniErrors } from '../unierror.uts';
import { AudioRecorder, RecordingListener, AudioDataListener, RecordingFormat } from "uts.sdk.modules.uniRecorder";
import Base64 from "android.util.Base64";
export { RecorderManagerFailImpl }
// NOTE 避免被 vue Proxy 污染
const DEFAULT_DURATION = 1000 * 60
const MAX_DURATION = DEFAULT_DURATION * 10
const DEFAULT_FORMAT = 'aac'
class RecorderManagerImpl implements RecorderManager, RecordingListener, AudioDataListener {
manager : AudioRecorder
constructor() {
this.manager = new AudioRecorder()
}
override start(options : RecorderManagerStartOptions) : void {
UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, ["android.permission.RECORD_AUDIO"], (allRight : boolean, grantedList : Array<string>) => {
this.innerStart(options)
}, (allRight : boolean, grantedList : Array<string>) => {
this.onRecordingError(1107601, "")
})
}
innerStart(options : RecorderManagerStartOptions) : void {
if (options.format == null) options.format = DEFAULT_FORMAT
if (options.duration == null) {
options.duration = DEFAULT_DURATION
}
if (options.duration! > MAX_DURATION) {
options.duration = MAX_DURATION
} else if (options.duration! < 0) {
options.duration = DEFAULT_DURATION
}
if(options.sampleRate == null) {
options.sampleRate = 8000
}
if(options.numberOfChannels == null) {
options.numberOfChannels = 2
}
if(options.encodeBitRate == null) {
options.encodeBitRate = 48000
}
this.manager.setAudioParams(options.sampleRate!.toInt(), options.numberOfChannels!.toInt(), options.encodeBitRate!.toInt())
this.manager.setSaveToFile(true)
var format = RecordingFormat.AAC
switch (options.format) {
case 'aac': {
format = RecordingFormat.AAC
break
}
case 'mp3': {
format = RecordingFormat.MP3
break
}
case 'pcm': {
format = RecordingFormat.PCM
break
}
case 'wav': {
format = RecordingFormat.WAV
break
}
default: {
format = RecordingFormat.AAC
break
}
}
this.manager.setRecordingListener(this)
this.manager.setAudioDataListener(this)
this.manager.setMaxRecordingDuration(options.duration!.toLong())
this.manager.startRecording(format, createFile(options.format! as string, options.saveDir))
}
// override pause() : void {
// this.manager.pauseRecording()
// }
// override resume() : void {
// this.manager.resumeRecording()
// }
override stop() {
this.manager.stopRecording()
}
startCallback : ((result : RecorderManagerOnStartResult) => void) | null = null
override onStart(options : (result : RecorderManagerOnStartResult) => void) : void {
this.startCallback = options
}
// override offStart() : void {
// this.startCallback = null
// }
// pauseCallback : ((result : any) => void) | null = null
// override onPause(options : (result : any) => void) : void {
// this.pauseCallback = options
// }
// override offPause() : void {
// this.pauseCallback = null
// }
stopCallback : ((result : RecorderManagerOnStopResult) => void) | null = null
override onStop(options : (result : RecorderManagerOnStopResult) => void) : void {
this.stopCallback = options
}
// override offStop() : void {
// this.stopCallback = null
// }
frameRecordedCallback : ((result : OnFrameRecordedResult) => void) | null = null
override onFrameRecorded(options : (result : OnFrameRecordedResult) => void) : void {
this.frameRecordedCallback = options
}
override offFrameRecorded() : void {
this.frameRecordedCallback = null
}
errorCallback : ((result : IRecorderManagerFail) => void) | null = null
override onError(options : (result : IRecorderManagerFail) => void) : void {
this.errorCallback = options
}
// override offError() : void {
// this.errorCallback = null
// }
// resumeCallback : ((result : any) => void) | null = null
// override onResume(options : (result : any) => void) : void {
// this.resumeCallback = options
// }
// override offResume() : void {
// this.resumeCallback = null
// }
// beginCallback : ((result : any) => void) | null = null
// override onInterruptionBegin(options : (result : any) => void) : void {
// this.beginCallback = options
// }
// override offInterruptionBegin() : void {
// this.beginCallback = null
// }
// endCallback : ((result : any) => void) | null = null
// override onInterruptionEnd(options : (result : any) => void) : void {
// this.endCallback = options
// }
// override offInterruptionEnd() : void {
// this.endCallback = null
// }
override onRecordingStarted() {
let res = new RecorderManagerOnStartResultCallback(this.manager.getFilePath()!)
this.startCallback?.(res)
}
override onRecordingStopped() {
this.stopCallback?.(new RecorderManagerOnStopResultCallback(this.manager.getFilePath()!))
}
override onRecordingPaused() {
// this.pauseCallback?.("")
}
override onRecordingResumed() {
// this.resumeCallback?.("")
}
override onRecordingError(errorCode : Int, errorMessage : String) {
var error : IRecorderManagerFail
if ([1107601, 1107602, 1107603, 1107604, 1107605, 1107606, 1107607, 1107608].indexOf(errorCode) >= 0) {
error = new RecorderManagerFailImpl(errorCode, RecorderManagerUniErrors[errorCode]!)
} else {
error = new RecorderManagerFailImpl(1107606, RecorderManagerUniErrors[1107606]!)
}
this.errorCallback?.(error)
}
// AudioDataListener 回调:实时返回 PCM 音频帧数据
override onAudioData(data : ByteArray, size : Int) {
if (this.frameRecordedCallback == null) return
var base64Str = Base64.encodeToString(data, 0, size, Base64.NO_WRAP)
this.frameRecordedCallback!(new OnFrameRecordedResultCallback(base64Str, false))
}
override onAudioError(errorCode : Int, errorMessage : String) {
// 音频数据错误通过 onError 统一处理
this.onRecordingError(errorCode, errorMessage)
}
}
class RecorderManagerOnStartResultCallback implements RecorderManagerOnStartResult, IJSONStringify, LogSelfV2 {
override filePath : string = ""
constructor(filePath : string) {
this.filePath = filePath
}
override toJSON() : Any {
var result : UTSJSONObject = new UTSJSONObject()
result.set("filePath", this.filePath)
return result
}
override toLogMap() : Map<String, Any> {
var map : Map<String, Any> = new Map<String, Any>()
map.set("filePath", this.filePath)
return map
}
}
class RecorderManagerOnStopResultCallback implements RecorderManagerOnStopResult, IJSONStringify, LogSelfV2 {
override tempFilePath : string = ""
constructor(filePath : string) {
this.tempFilePath = filePath
}
override toJSON() : Any {
var result : UTSJSONObject = new UTSJSONObject()
result.set("tempFilePath", this.tempFilePath)
return result
}
override toLogMap() : Map<String, Any> {
var map : Map<String, Any> = new Map<String, Any>()
map.set("tempFilePath", this.tempFilePath)
return map
}
}
class OnFrameRecordedResultCallback implements OnFrameRecordedResult, IJSONStringify, LogSelfV2 {
override base64 : string = ""
override isLastFrame : boolean = false
constructor(base64 : string, isLastFrame : boolean) {
this.base64 = base64
this.isLastFrame = isLastFrame
}
override toJSON() : Any {
var result : UTSJSONObject = new UTSJSONObject()
result.set("base64", this.base64)
result.set("isLastFrame", this.isLastFrame)
return result
}
override toLogMap() : Map<String, Any> {
var map : Map<String, Any> = new Map<String, Any>()
map.set("base64", this.base64)
map.set("isLastFrame", this.isLastFrame)
return map
}
}
var recordManager : RecorderManagerImpl | null = null
export const getRecorderManagerX : GetRecorderManager = function () : RecorderManager {
if (recordManager == null)
recordManager = new RecorderManagerImpl()
return recordManager!
}
import { RecorderManagerOnStopResult } from '../interface.uts';
import File from 'java.io.File';
import UUID from 'java.util.UUID';
export type RecorderState = 'pause' | 'resume' | 'start' | 'stop' | 'error' | 'frameRecorded' | 'interruptionBegin' | 'interruptionEnd'
export interface StateChangeRes extends RecorderManagerOnStopResult {
errMsg ?: string
frameBuffer ?: ArrayBuffer
isLastFrame ?: boolean
}
export function onRecorderStateChange(state : RecorderState, res ?: StateChangeRes) : void {
}
export function createFile( format : string, saveDir ?: string | null) : string {
var dirPath : string
if (saveDir != null && saveDir!.length > 0) {
dirPath = saveDir!
} else {
let context = UTSAndroid.getAppContext()
var parentPath = UTSAndroid.getAppCachePath()
if (context != null) {
let filesDir = context.getExternalFilesDir(null)
if (filesDir != null) {
parentPath = filesDir.path
}
}
dirPath = parentPath!
}
const fileDir = `${dirPath}/records`
let dir = new File(fileDir)
if (!dir.exists()) {
dir.mkdirs()
}
const random = UUID.randomUUID().toString().replace(/-/g, '').substring(0, 8)
const fileName = `${Date.now()}_${random}.${format.toLocaleLowerCase()}`
return `${dir.path}/${fileName}`
}
export const supportFormats = ['aac']
import { BusinessError } from '@kit.BasicServicesKit';
import media from '@ohos.multimedia.media'
import { fileIo } from '@kit.CoreFileKit';
import { RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import { createFile, onRecorderStateChange, StateChangeRes, transformErrorCode } from './utils.uts';
import { RecorderManagerFailImpl } from '../unierror.uts'
export type SupportFormat = 'aac' | 'mp3' | 'm4a' | 'wav'
export const supportFormats: Array<SupportFormat> = ['aac', 'mp3', 'm4a', 'wav']
function getAudioCodec(format: SupportFormat): media.CodecMimeType {
switch (format) {
case 'aac':
return media.CodecMimeType.AUDIO_AAC
case 'mp3':
return media.CodecMimeType.AUDIO_MP3
case 'm4a':
return media.CodecMimeType.AUDIO_AAC
case 'wav':
return media.CodecMimeType.AUDIO_G711MU
/* case 'pcm':
return media.CodecMimeType.AUDIO_G711MU */
default:
return media.CodecMimeType.AUDIO_AAC
}
}
function getFileFormat(format: SupportFormat): media.ContainerFormatType {
switch (format) {
case 'aac':
return media.ContainerFormatType.CFT_MPEG_4A
case 'mp3':
return media.ContainerFormatType.CFT_MP3
case 'm4a':
return media.ContainerFormatType.CFT_MPEG_4A
case 'wav':
return media.ContainerFormatType.CFT_WAV
/* case 'pcm':
return media.ContainerFormatType.CFT_MPEG_4A */
default:
return media.ContainerFormatType.CFT_MPEG_4A
}
}
const DEFAULT_DURATION = 1000 * 60
export default class AVRecorder {
private avRecorder?: media.AVRecorder
private isFirstStart: boolean = true
constructor() { }
private onStateChange(file: fileIo.File) {
if (this.avRecorder) {
this.avRecorder.on('stateChange', async (state, reason) => {
switch (state) {
case 'idle':
// 调用rest接口后触发idle状态;create后也在idle状态
this.isFirstStart = true
break
case 'started':
if (this.isFirstStart) {
this.isFirstStart = false
onRecorderStateChange('start', { tempFilePath: file.path } as StateChangeRes)
} else {
if (reason === media.StateChangeReason.BACKGROUND) {
onRecorderStateChange('interruptionEnd')
}
onRecorderStateChange('resume')
}
break
case 'paused':
if (reason === media.StateChangeReason.BACKGROUND) {
onRecorderStateChange('interruptionBegin')
}
onRecorderStateChange('pause')
break
case 'stopped':
onRecorderStateChange('stop', { tempFilePath: file.path } as StateChangeRes)
fileIo.closeSync(file)
break
}
})
this.avRecorder.on('error', (err: BusinessError) => {
onRecorderStateChange('error', new RecorderManagerFailImpl(transformErrorCode(err.code), err.message) as IRecorderManagerFail)
})
}
}
private async release() {
if (this.avRecorder !== undefined) {
await this.avRecorder.reset();
await this.avRecorder.release();
this.avRecorder = undefined;
}
}
async start(options: RecorderManagerStartOptions): Promise<void> {
if (this.avRecorder !== undefined) {
await this.release();
}
// 1.创建录制实例
this.avRecorder = await media.createAVRecorder();
const { sampleRate = 8000, numberOfChannels = 2, encodeBitRate = 48000, duration, format = 'aac' } = options
const file = createFile(supportFormats, format!, 'aac')
this.onStateChange(file);
const audioProfile: media.AVRecorderProfile = {
audioBitrate: format === 'wav' ? 64000 : encodeBitRate!,
audioChannels: format === 'wav' ? 1 : numberOfChannels!,
audioCodec: getAudioCodec(format! as SupportFormat),
audioSampleRate: format === 'wav' ? 8000 : sampleRate!,
fileFormat: getFileFormat(format! as SupportFormat),
}
const audioConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
profile: audioProfile,
url: 'fd://' + file.fd // 文件需先由调用者创建,赋予读写权限,将文件fd传给此参数,eg.fd://45
}
return new Promise((resolve, reject) => {
UTSHarmony.requestSystemPermission(['ohos.permission.MICROPHONE'], async (allRight: boolean) => {
if (allRight) {
await this.avRecorder?.prepare(audioConfig)
await this.avRecorder?.start()
if (duration && duration > 0) {
setTimeout(async () => {
await this.avRecorder?.stop()
}, duration)
}
resolve()
} else {
onRecorderStateChange('error', new RecorderManagerFailImpl(1107601) as IRecorderManagerFail)
reject()
}
}, (doNotAskAgain: boolean) => {
onRecorderStateChange('error', new RecorderManagerFailImpl(1107601) as IRecorderManagerFail)
reject()
})
})
}
async pause(): Promise<void> {
if (this.avRecorder !== undefined && this.avRecorder.state === 'started') {
// 仅在started状态下调用pause为合理状态切换
await this.avRecorder.pause();
}
}
async resume(): Promise<void> {
if (this.avRecorder !== undefined && this.avRecorder.state === 'paused') { // 仅在paused状态下调用resume为合理状态切换
await this.avRecorder.resume();
}
}
async stop(): Promise<void> {
if (this.avRecorder !== undefined && (this.avRecorder.state === 'started' || this.avRecorder.state === 'paused')) { // 仅在started或者paused状态下调用stop为合理状态切换
await this.avRecorder.stop();
await this.release();
this.isFirstStart = true
}
}
}
import { API_GET_RECORDER_MANAGER } from '../protocol.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import AVRecorder, { supportFormats as avRecorderSupportFormats, SupportFormat } from './AVRecorder.uts';
import { onRecorderStateChange, setRecordStateCallback, deleteRecordStateCallback } from './utils.uts';
import { RecorderManagerFailImpl } from '../unierror.uts'
// NOTE 避免被 vue Proxy 污染
let RECORDER_MANAGER: AVRecorder | null = null
const DEFAULT_FORMAT = 'aac'
class RecorderManagerImpl implements RecorderManager {
__v_skip: boolean = true
start(options: RecorderManagerStartOptions | null = null): void {
if (options == null) options = {} as RecorderManagerStartOptions
if (!options.format) options.format = DEFAULT_FORMAT
if (avRecorderSupportFormats.includes((options.format ?? '') as SupportFormat)) {
RECORDER_MANAGER = new AVRecorder()
}
if (RECORDER_MANAGER) {
RECORDER_MANAGER.start(options)
} else {
onRecorderStateChange('error', new RecorderManagerFailImpl(1107605))
}
}
// pause(): void {
// if (RECORDER_MANAGER) RECORDER_MANAGER.pause()
// }
// resume(): void {
// if (RECORDER_MANAGER) RECORDER_MANAGER.resume()
// }
async stop() {
if (RECORDER_MANAGER) {
try {
await RECORDER_MANAGER.stop()
} catch (error) { }
RECORDER_MANAGER = null
}
}
onStart(options: (result: RecorderManagerOnStartResult) => void): void {
setRecordStateCallback('start', options)
}
// onPause(options: (result: any) => void): void {
// setRecordStateCallback('pause', options)
// }
onStop(options: (result: RecorderManagerOnStopResult) => void): void {
setRecordStateCallback('stop', options)
}
// onFrameRecorded(options: (result: any) => void): void {
// setRecordStateCallback('frameRecorded', options)
// }
onError(options: (result: IRecorderManagerFail) => void): void {
setRecordStateCallback('error', options)
}
// onResume(options: (result: any) => void): void {
// setRecordStateCallback('resume', options)
// }
// onInterruptionBegin(options: (result: any) => void): void {
// setRecordStateCallback('interruptionBegin', options)
// }
// onInterruptionEnd(options: (result: any) => void): void {
// setRecordStateCallback('interruptionEnd', options)
// }
// offStart(): void {
// deleteRecordStateCallback('start')
// }
// offPause(): void {
// deleteRecordStateCallback('pause')
// }
// offStop(): void {
// deleteRecordStateCallback('stop')
// }
// offFrameRecorded(): void {
// deleteRecordStateCallback('frameRecorded')
// }
// offError(): void {
// deleteRecordStateCallback('error')
// }
// offResume(): void {
// deleteRecordStateCallback('resume')
// }
// offInterruptionBegin(): void {
// deleteRecordStateCallback('interruptionBegin')
// }
// offInterruptionEnd(): void {
// deleteRecordStateCallback('interruptionEnd')
// }
}
let recorderManager: RecorderManager | null = null
export const getRecorderManagerX: GetRecorderManager = defineSyncApi<RecorderManager>(
API_GET_RECORDER_MANAGER,
(): RecorderManager => {
if (recorderManager) return recorderManager
else recorderManager = new RecorderManagerImpl()
return recorderManager
}
) as GetRecorderManager
export {
GetRecorderManager,
IRecorderManagerFail,
RecorderManager,
RecorderManagerErrorCode,
RecorderManagerOnStopResult,
RecorderManagerStartOptions
} from '../interface.uts'
import { getAbilityContext } from '@dcloudio/uni-runtime';
import common from '@ohos.app.ability.common';
import { fileIo } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';
import { RecorderManagerOnStopResult, RecorderManagerErrorCode, IRecorderManagerFail } from '../interface.uts';
export type RecorderState = 'pause' | 'resume' | 'start' | 'stop' | 'error' | 'frameRecorded' | 'interruptionBegin' | 'interruptionEnd'
type ErrorCb = (result: IRecorderManagerFail) => void
interface Callbacks {
pause?: Function | null
resume?: Function | null
start?: Function | null
stop?: Function | null
error?: ErrorCb | null
frameRecorded?: Function | null
interruptionBegin?: Function | null
interruptionEnd?: Function | null
}
const callbacks: Callbacks = {
pause: null,
resume: null,
start: null,
stop: null,
error: null,
frameRecorded: null,
interruptionBegin: null,
interruptionEnd: null
}
export function setRecordStateCallback(state: RecorderState, cb: Function | ErrorCb | null = null) {
switch (state) {
case 'pause':
callbacks.pause = cb
break
case 'resume':
callbacks.resume = cb
break
case 'start':
callbacks.start = cb
break
case 'stop':
callbacks.stop = cb
break
case 'error':
callbacks.error = cb as ErrorCb
break
case 'frameRecorded':
callbacks.frameRecorded = cb
break
case 'interruptionBegin':
callbacks.interruptionBegin = cb
break
case 'interruptionEnd':
callbacks.interruptionEnd = cb
break
}
}
export function deleteRecordStateCallback(state: RecorderState) {
setRecordStateCallback(state)
}
export interface StateChangeRes extends RecorderManagerOnStopResult {
errMsg?: string
frameBuffer?: ArrayBuffer
isLastFrame?: boolean
doNotAskAgain?: boolean
}
export function onRecorderStateChange(state: RecorderState, res?: StateChangeRes | IRecorderManagerFail): void {
switch (state) {
case 'pause':
return callbacks.pause?.(res)
case 'resume':
return callbacks.resume?.(res)
case 'start':
return callbacks.start?.(res)
case 'stop':
return callbacks.stop?.(res)
case 'error':
return callbacks.error?.(res as IRecorderManagerFail)
case 'frameRecorded':
return callbacks.frameRecorded?.(res)
case 'interruptionBegin':
return callbacks.interruptionBegin?.(res)
case 'interruptionEnd':
return callbacks.interruptionEnd?.(res)
}
}
export function createFile(supportFormats: string[], format: string, defaultExt: string) {
const context = getAbilityContext() as common.UIAbilityContext;
const filePath = `${context.filesDir}/record/`
if (!fileIo.accessSync(filePath)) {
fileIo.mkdirSync(filePath, true)
}
const random = util.generateRandomUUID(true).replace(/-/g, '').substring(0, 8);
const fileName = `${Date.now()}_${random}.${supportFormats.includes(format ?? '') ? format?.toLocaleLowerCase() : defaultExt}`
const file: fileIo.File = fileIo.openSync(`${filePath}${fileName}`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
return file
}
export function transformErrorCode(errCode: number): RecorderManagerErrorCode {
switch (errCode) {
case 201:
return 1107601
case 401:
return 1107606
case 5400106:
return 1107605
case 5400107:
return 1107607
}
return errCode as RecorderManagerErrorCode
}
{
"deploymentTarget": "12.0"
}
\ No newline at end of file
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
export { RecorderManagerFailImpl } from '../unierror.uts'
export const getRecorderManagerX : GetRecorderManager = function () : RecorderManager {
let recorderManager = new UniAudioRecorderManager.shared
return recorderManager
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSMicrophoneUsageDescription</key>
<string>APP需要您的同意,才能使用麦克风,以便于录制音频</string>
</dict>
</plist>
\ No newline at end of file
// 平台条件编译:自动导入对应平台的实现
// #ifdef APP-ANDROID
import { getRecorderManagerX } from './app-android/index.uts'
export { getRecorderManagerX as getRecorderManager }
// #endif
// #ifdef APP-IOS
import { getRecorderManagerX } from './app-ios/index.uts'
export { getRecorderManagerX as getRecorderManager }
// #endif
// #ifdef APP-HARMONY
import { getRecorderManagerX } from './app-harmony/index.uts'
export { getRecorderManagerX as getRecorderManager }
// #endif
// 类型导出
export {
GetRecorderManager,
RecorderManager,
RecorderManagerStartOptions,
RecorderManagerOnStartResult,
RecorderManagerOnStopResult,
OnFrameRecordedResult,
IRecorderManagerFail
} from './interface.uts'
export interface Uni {
getRecorderManagerX() : RecorderManager
}
export type GetRecorderManager = () => RecorderManager;
export type RecorderManagerStartOptions = {
duration ?: number | null,
sampleRate ?: number | null,
numberOfChannels ?: number | null,
encodeBitRate ?: number | null,
format ?:
'aac' |
'mp3' |
'pcm' |
'wav' |
'm4a' | null,
frameSize ?: number | null,
saveDir ?: string | null
};
export interface RecorderManagerOnStopResult {
tempFilePath : string
};
export interface RecorderManagerOnStartResult {
filePath : string
};
export interface OnFrameRecordedResult {
base64 : string;
isLastFrame : boolean;
};
export interface RecorderManager {
start(options : RecorderManagerStartOptions) : void;
stop() : void;
onStart(options : (result : RecorderManagerOnStartResult) => void) : void;
onStop(options : (result : RecorderManagerOnStopResult) => void) : void;
onError(options: (result: IRecorderManagerFail) => void): void;
onFrameRecorded(options: (result: OnFrameRecordedResult) => void): void;
offFrameRecorded(): void;
}
export type RecorderManagerErrorCode =
1107601 |
1107602 |
1107603 |
1107604 |
1107605 |
1107606 |
1107607 |
1107608;
export interface IRecorderManagerFail extends IUniError {
errCode : RecorderManagerErrorCode
};
export const API_GET_RECORDER_MANAGER = 'getRecorderManagerX'
import { RecorderManagerErrorCode, IRecorderManagerFail } from "./interface.uts"
/**
* 错误主题
*/
export const RecorderManagerUniErrorSubject = 'uni-recorder';
/**
* 错误码
* @UniError
*/
export const RecorderManagerUniErrors : Map<RecorderManagerErrorCode, string> = new Map([
/**
* 没有麦克风权限
*/
[1107601, 'No microphone permissions.'],
/**
* 不支持该采样率
*/
[1107602, 'This sample rate is not supported.'],
/**
* 采样率是和编码码率不匹配
*/
[1107603, 'The sample rate does not match the encoding bitrate.'],
/**
* 启动失败
*/
[1107604, 'Failed to start.'],
/**
* 不支持该音频格式
*/
[1107605, 'This audio format is not supported.'],
/**
* 其他错误
*/
[1107606, 'Other errors.'],
/**
* 被打断
*/
[1107607, 'Audio interrupted.'],
/**
* 正在录音中,请稍后再试
*/
[1107608, 'Audio is recording.']
]);
export class RecorderManagerFailImpl extends UniError implements IRecorderManagerFail {
// #ifdef APP-HARMONY
override errCode: RecorderManagerErrorCode
// #endif
constructor(errCode : RecorderManagerErrorCode, errMsg: string = '') {
super();
this.errSubject = RecorderManagerUniErrorSubject;
this.errCode = errCode;
this.errMsg = errMsg != "" ? errMsg : (RecorderManagerUniErrors.get(errCode) ?? errMsg);
}
}
const SKIP_MENU_KEY = 'ai_assistant_skip_menu'
const GUIDE_DATE_KEY = 'ai_assistant_guide_date'
function todayKey() {
const d = new Date()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${d.getFullYear()}-${m}-${day}`
}
export function getSkipMenu() {
return !!uni.getStorageSync(SKIP_MENU_KEY)
}
export function setSkipMenu(value) {
uni.setStorageSync(SKIP_MENU_KEY, !!value)
}
/** 是否应在今日展示引导气泡(每天首次) */
export function shouldShowDailyGuide() {
const last = uni.getStorageSync(GUIDE_DATE_KEY)
return last !== todayKey()
}
export function markDailyGuideShown() {
uni.setStorageSync(GUIDE_DATE_KEY, todayKey())
}
/*
* 接待场景 AI 对话 WebSocket(跟随接待会话建连/断连)
*/
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import { getNativeWsBase } from '@/utils/socket'
class AiChatWsService {
static _instance = null
constructor() {
this._connectPromise = null
/** 是否由接待会话托管(仅此种情况在 stopAudio 时断开) */
this._receptionBound = false
/** 只有明确配置了该 url 才会发起 WebSocket 连接 */
this._wsUrl = ''
}
static getInstance() {
if (!AiChatWsService._instance) {
AiChatWsService._instance = new AiChatWsService()
}
return AiChatWsService._instance
}
getClient() {
return NativeWsClient.getInstance()
}
/** 显式设置 AI 对话 WS 地址;未设置时不会自动连接 */
setWsUrl(url) {
this._wsUrl = url || ''
}
isConnected() {
return this.getClient().isConnected
}
/**
* 建立 AI 对话 WS
* @param {{ fromReception?: boolean }} [options] fromReception=true 时跟随接待生命周期断连
*/
connectForReception(options = {}) {
// #ifndef APP-PLUS
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
const wsUrl = (getNativeWsBase() || '').trim()
if (!wsUrl) {
// 未配置 WS 地址时直接跳过(本项目可纯 HTTP 模式运行)
return Promise.resolve(false)
}
if (options.fromReception) {
this._receptionBound = true
}
if (this.isConnected()) {
return Promise.resolve(true)
}
if (this._connectPromise) {
return this._connectPromise
}
this._connectPromise = (async () => {
try {
uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${wsUrl}`)
await this.getClient().connectDirect(wsUrl)
return true
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 连接失败: ${e.message || e}`)
return false
} finally {
this._connectPromise = null
}
})()
return this._connectPromise
// #endif
}
/** 结束接待:断开并停止自动重连 */
async disconnectReception() {
// #ifndef APP-PLUS
return
// #endif
// #ifdef APP-PLUS
if (!this._receptionBound) {
return
}
this._receptionBound = false
this._connectPromise = null
const client = this.getClient()
try {
uni.$logger?.local?.info('[AiChatWs] 接待结束,断开 WS')
await client.close(1000, 'reception end', true)
} catch (e) {
uni.$logger?.local?.warn(`[AiChatWs] 断开异常: ${e.message || e}`)
}
// #endif
}
/** 求助前确保已连接(接待开始时通常已连好,此处作兜底) */
async ensureConnected() {
if (this.isConnected()) {
return true
}
return this.connectForReception()
}
}
export default AiChatWsService
import { DEMO_STREAM_MARKDOWN } from './demoStreamMarkdown.js'
import {
USE_AI_STREAM_MOCK,
STREAM_MOCK_CHARS_PER_TICK,
STREAM_MOCK_INTERVAL_MS,
STREAM_WAIT_TIMEOUT_MS
} from './constants.js'
import AiChatWsService from './AiChatWsService.js'
const STREAM_DELTA_TYPES = new Set([
'text',
'delta',
'chunk',
'markdown',
'content',
'message',
'answer'
])
const STREAM_DONE_TYPES = new Set(['done', 'end', 'complete', 'finished', 'stop'])
function extractDelta(data) {
if (!data || typeof data !== 'object') return ''
if (STREAM_DONE_TYPES.has(data.type)) return null
if (data.type === 'receiving' || data.type === 'processing') return ''
if (STREAM_DELTA_TYPES.has(data.type)) {
return data.content ?? data.text ?? data.delta ?? data.markdown ?? data.message ?? ''
}
if (typeof data.content === 'string' && data.type !== 'error') {
return data.content
}
return ''
}
function isDoneMessage(data) {
return data && STREAM_DONE_TYPES.has(data.type)
}
function isErrorMessage(data) {
return data && (data.type === 'error' || data.error)
}
class AiStreamSession {
constructor() {
this._active = false
this._markdown = ''
this._callbacks = null
this._prevOnMessage = null
this._mockTimer = null
this._timeoutTimer = null
this._mockIndex = 0
this._useMock = false
}
get isActive() {
return this._active
}
get markdown() {
return this._markdown
}
/**
* @param {{ onUpdate?: Function, onDone?: Function, onError?: Function, useMock?: boolean }} callbacks
*/
start(callbacks = {}) {
this.cancel()
this._active = true
this._markdown = ''
this._callbacks = callbacks
this._useMock = callbacks.useMock ?? USE_AI_STREAM_MOCK
if (this._useMock) {
this._startMockStream(DEMO_STREAM_MARKDOWN)
} else {
this._bindWsListener()
this._timeoutTimer = setTimeout(() => {
if (this._active) {
this._finish(new Error('等待 AI 回复超时'))
}
}, STREAM_WAIT_TIMEOUT_MS)
}
return this
}
cancel() {
this._active = false
this._unbindWsListener()
this._clearTimers()
this._callbacks = null
this._mockIndex = 0
}
handleWsMessage(data) {
if (!this._active) return
if (isErrorMessage(data)) {
const msg = data.message || data.content || data.error || 'AI 返回错误'
this._finish(new Error(msg))
return
}
if (isDoneMessage(data)) {
this._finish()
return
}
const delta = extractDelta(data)
if (delta === null) {
this._finish()
return
}
if (delta) {
this._append(delta)
}
}
_append(chunk) {
if (!chunk) return
this._markdown += chunk
this._callbacks?.onUpdate?.({
markdown: this._markdown,
delta: chunk
})
}
_finish(err) {
if (!this._active) return
this._active = false
this._clearTimers()
this._unbindWsListener()
if (err) {
this._callbacks?.onError?.(err)
} else {
this._callbacks?.onDone?.({
markdown: this._markdown
})
}
this._callbacks = null
}
_bindWsListener() {
const client = AiChatWsService.getInstance().getClient()
this._prevOnMessage = client.onMessage
client.onMessage = (data) => {
this.handleWsMessage(data)
this._prevOnMessage && this._prevOnMessage(data)
}
}
_unbindWsListener() {
const client = AiChatWsService.getInstance().getClient()
if (client.onMessage && this._prevOnMessage !== undefined) {
client.onMessage = this._prevOnMessage
}
this._prevOnMessage = null
}
_clearTimers() {
if (this._mockTimer) {
clearInterval(this._mockTimer)
this._mockTimer = null
}
if (this._timeoutTimer) {
clearTimeout(this._timeoutTimer)
this._timeoutTimer = null
}
}
_startMockStream(fullText) {
this._mockIndex = 0
this._mockTimer = setInterval(() => {
if (!this._active) return
if (this._mockIndex >= fullText.length) {
this._finish()
return
}
const chunk = fullText.slice(this._mockIndex, this._mockIndex + STREAM_MOCK_CHARS_PER_TICK)
this._mockIndex += STREAM_MOCK_CHARS_PER_TICK
this._append(chunk)
}, STREAM_MOCK_INTERVAL_MS)
}
}
let _instance = null
export function getAiStreamSession() {
if (!_instance) {
_instance = new AiStreamSession()
}
return _instance
}
export default AiStreamSession
/** true:音频仍走真实 WS 上传,回复用本地 markdown 模拟流式输出;联调通过后改为 false */
export const USE_AI_STREAM_MOCK = true
/** 模拟流式:每 tick 追加字符数(越小越像逐字输出) */
export const STREAM_MOCK_CHARS_PER_TICK = 12
export const STREAM_MOCK_INTERVAL_MS = 25
export const STREAM_WAIT_TIMEOUT_MS = 120000
/**
* 流式渲染演示用 Markdown(iOS __uniConfig 白屏问题记录)
* 联调真实 AI 后可将 USE_AI_STREAM_MOCK 设为 false
*/
export const DEMO_STREAM_MARKDOWN = `# iOS 26.x 切后台白屏(\`__uniConfig\` 丢失)问题记录
> 版本:2.26.6 · 框架:uni-app Vue2 · 设备:iPadOS 26.4+(App Store 审核复现)
> 涉及文件:\`utils/ensureUniConfig.js\`、\`main.js\`、\`App.vue\`
---
## 1. 问题现象
### 触发条件
- App 切到后台一段时间后,再切回前台
- 低版本 iOS 难以复现,**iPadOS 26.4 / 26.5** 高概率出现
- \`pages.json\` 注册路由较多(本项目约 **52 条**)时更容易触发
### 控制台典型日志
\`\`\`
【==== 切出 ====】 APP
(uView、init.js 再次打印,说明 main.js 被重新执行)
ReferenceError: Can't find variable: __uniConfig
TypeError: r[t] is not a function
TypeError: undefined is not an object (evaluating 'r.addVData')
【==== 切回 ====】 APP
(若不处理,页面白屏,业务无法继续)
\`\`\`
### 用户侧表现
- 屏幕空白,无法操作
- 有时底层 WS、SQLite 仍在跑,但页面已无法渲染
---
## 2. 根因分析
| 层级 | 说明 |
|------|------|
| **直接原因** | 切回前台时 uni-app 运行时未正确重新注入 \`__uniConfig\`,或 JS 上下文被整包重跑,内部路由/页面注册对象(\`addVData\`、\`r[t]\`)处于损坏状态 |
| **表现** | \`main.js\`、\`init.js\` 再次执行(与冷启动类似),但引擎状态不完整 |
| **诱因** | iOS 26.x 对 WebView / JS 上下文管理变化 + 路由表过大,使该问题在审核设备上稳定复现 |
| **框架层** | 属于 DCloud 引擎侧问题,业务代码无法「修复注入」,只能 **检测 + 兜底恢复** |
---
## 4. 最终方案
### 4.1 思路
> **不试图在业务层「修好」uni 引擎,而是:可靠检出损坏 → 放弃当前页面栈 → \`reLaunch\` 登录页,让用户重新进入可用状态。**
代价:切回白屏时用户需 **重新登录**;收益:避免无限白屏,通过 App Store 审核。
### 4.2 核心机制
#### (1)损坏检测(多路并行)
\`\`\`
onHide
└─ 写入 ZY_BG_AT(时间戳)+ ZY_WAS_BACKGROUND
main.js 加载时(同进程 JS 重跑)
├─ syncProcessStartupFlags():对比 launchLoadedTime,新进程则清 BG 标记
├─ detectMainJsReEntry():
│ ├─ getApp() 仍能拿到实例 → 损坏
│ └─ ZY_BG_AT 在 2 分钟内 → 损坏(切回核心条件)
└─ ensureUniConfig():__uniConfig 缺失则从 storage 恢复,并标记损坏
\`\`\`
匹配关键字:\`__uniConfig\`、\`addVData\`、\`r[t] is not a function\`
#### (2)粘性恢复标记 \`_recoverRequired\`
一旦判定损坏,置 \`_recoverRequired = true\`:
- **不会因为** 从 backup 恢复了 \`__uniConfig\` 变量就清除
- **不会因为** \`onLaunch\` 里看到 config 存在就清除
- 仅在 \`reLaunch\` 登录页成功后清除
---
## 8. 总结
1. **问题本质**:uni-app 在 iOS 26.x 切回时 JS 上下文异常重建,\`__uniConfig\` 及页面注册体系损坏,导致白屏。
2. **业务无法根治**:备份 \`__uniConfig\` 只能补变量,无法修复引擎内部对象。
3. **有效手段**:\`ZY_BG_AT\` 2 分钟 + \`main.js\` 重跑检测 + \`_recoverRequired\` 粘性标记 + 强制 \`reLaunch\` 登录。
4. **关键踩坑**:切回时 \`onLaunch\` 仍会执行,若在此时因 \`__uniConfig\` 存在就清除损坏标记,会导致 **检测到损坏却不跳转**。
5. **当前状态**:切回白屏可恢复至登录页;杀进程冷启动不误判。方案已在审核设备验证可用。
---
*以上内容由 AI 流式模拟输出,使用 [mp-html](https://ext.dcloud.net.cn/plugin?id=805) 渲染。*
`
import { LogLevel } from './constants'
import { serializeIfObject } from '../utils'
import FloatLogConfig from './FloatLogConfig.js'
const MAX_LINES = 400
const PIN_TAG = '[StoragePathMerge]'
const MAX_PINNED_LINES = 60
function trimLines() {
if (lines.length <= MAX_LINES) return
const pinned = lines.filter(l => l.text.includes(PIN_TAG))
const normal = lines.filter(l => !l.text.includes(PIN_TAG))
const pinnedKeep = pinned.slice(-MAX_PINNED_LINES)
const normalBudget = Math.max(0, MAX_LINES - pinnedKeep.length)
const normalKeep = normal.slice(-normalBudget)
lines = [...normalKeep, ...pinnedKeep]
lines.sort((a, b) => {
const ta = parseInt(String(a.id).split('_')[0], 10) || 0
const tb = parseInt(String(b.id).split('_')[0], 10) || 0
return ta - tb
})
}
let lines = []
/** 路径合并等启动期日志,单独保留,避免被后续刷屏挤掉 */
let mergeLines = []
let listeners = new Set()
let installed = false
let originalConsole = null
function pad(n) {
return n < 10 ? '0' + n : String(n)
}
function nowTime() {
const d = new Date()
const ms = String(d.getMilliseconds())
const ms3 = ms.length >= 3 ? ms : ('00' + ms).slice(-3)
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms3}`
}
function normalizeLevel(level) {
const l = String(level || 'info').toLowerCase()
if (l === LogLevel.DEBUG || l === 'debug') return 'debug'
if (l === LogLevel.WARN || l === 'warn') return 'warn'
if (l === LogLevel.ERROR || l === 'error') return 'error'
return 'info'
}
function formatPayload(payload) {
if (payload == null) return ''
if (typeof payload === 'string') return payload
if (payload instanceof Error) {
return payload.stack || payload.message || String(payload)
}
if (typeof payload === 'object') {
if (payload.msg != null) {
const extra = payload.extra != null ? ` ${serializeIfObject(payload.extra)}` : ''
return String(payload.msg) + extra
}
try {
return serializeIfObject(payload)
} catch (e) {
return String(payload)
}
}
return String(payload)
}
function joinArgs(args) {
return args.map(a => formatPayload(a)).filter(Boolean).join(' ')
}
function pushLine(level, text) {
const msg = formatPayload(text)
if (!msg) return
const line = {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
time: nowTime(),
level: normalizeLevel(level),
text: msg
}
lines.push(line)
if (msg.includes(PIN_TAG)) {
mergeLines.push(line)
if (mergeLines.length > MAX_PINNED_LINES) {
mergeLines = mergeLines.slice(mergeLines.length - MAX_PINNED_LINES)
}
}
trimLines()
listeners.forEach(fn => {
try {
fn(line)
} catch (e) {
/* ignore */
}
})
}
function patchConsole() {
if (originalConsole) return
originalConsole = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
debug: console.debug.bind(console)
}
console.log = (...args) => {
originalConsole.log(...args)
pushLine('info', joinArgs(args))
}
console.info = (...args) => {
originalConsole.info(...args)
pushLine('info', joinArgs(args))
}
console.warn = (...args) => {
originalConsole.warn(...args)
pushLine('warn', joinArgs(args))
}
console.error = (...args) => {
originalConsole.error(...args)
pushLine('error', joinArgs(args))
}
console.debug = (...args) => {
originalConsole.debug(...args)
pushLine('debug', joinArgs(args))
}
}
const FloatLogBus = {
isInstalled() {
return installed
},
getOriginalConsole() {
return originalConsole
},
install() {
if (installed) return
installed = true
patchConsole()
if (uni.$logger && typeof uni.$logger.setLogListener === 'function') {
uni.$logger.setLogListener((level, info) => {
pushLine(level, info)
})
}
pushLine('info', '[FloatLogBus] 日志悬浮窗已就绪')
},
isFloatLogEnabled() {
return FloatLogConfig.isLogBallVisible()
},
push(level, text) {
pushLine(level, text)
},
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
getLineCount() {
return lines.length
},
getLines() {
return lines.slice()
},
/** 仅路径合并相关日志(冷启动后仍可在悬浮窗看到) */
getMergeLines() {
return mergeLines.slice()
},
/** 取尾部日志,避免面板一次性拷贝/渲染过多 */
getRecentLines(limit = 200) {
if (!limit || lines.length <= limit) return lines.slice()
return lines.slice(lines.length - limit)
},
clearLines() {
lines = []
mergeLines = []
listeners.forEach(fn => {
try {
fn(null)
} catch (e) {
/* ignore */
}
})
}
}
export default FloatLogBus
import { index as envIndex } from '@/env'
const listeners = new Set()
let configLoaded = false
let serverAllows = false
function isNonProduction() {
return envIndex !== 3
}
/**
* app-tape 配置 isShowLogBall:仅显式 true 时展示,未配置/false 均隐藏
*/
export function parseIsShowLogBall(mockData) {
if (!mockData || mockData.isShowLogBall == null) return false
const v = mockData.isShowLogBall
if (v === true || v === 1) return true
if (typeof v === 'string') return v.toLowerCase() === 'true'
return false
}
function computeVisible() {
return isNonProduction() && serverAllows
}
function notify() {
const visible = computeVisible()
listeners.forEach(fn => {
try {
fn(visible)
} catch (e) {
/* ignore */
}
})
return visible
}
const FloatLogConfig = {
isNonProduction,
isLogBallVisible() {
return computeVisible()
},
isConfigLoaded() {
return configLoaded
},
applyFromMockData(mockData) {
if (!isNonProduction()) {
serverAllows = false
} else {
serverAllows = parseIsShowLogBall(mockData)
}
configLoaded = true
const visible = notify()
if (visible) {
const FloatLogBus = require('./FloatLogBus.js').default
FloatLogBus.install()
}
return visible
},
/**
* 拉取配置中心 app-tape 并更新悬浮球(uni.$api.systemApi.getMockData)
* 例: https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=app-tape&env=test
* 字段 isShowLogBall;生产环境不展示
*/
async refreshFromServer(immediate = false) {
if (!isNonProduction()) {
serverAllows = false
configLoaded = true
return notify()
}
const cached = uni.$storage?.get?.('mock_data')
if (cached) {
this.applyFromMockData(cached)
}
try {
if (uni.$api?.systemApi?.getMockData) {
const data = await uni.$api.systemApi.getMockData(immediate)
return this.applyFromMockData(data)
}
serverAllows = false
} catch (e) {
uni.$logger?.local?.warn?.(`[FloatLogConfig] 读取 app-tape 配置失败: ${e?.message || e}`)
serverAllows = false
}
configLoaded = true
return notify()
},
subscribe(fn) {
listeners.add(fn)
fn(computeVisible())
return () => listeners.delete(fn)
}
}
export default FloatLogConfig
......@@ -8,8 +8,25 @@
* 可以输入预定的版权声明、个性签名、空行等
*/
import LogCat from './LogCat'
import FloatLogBus from './FloatLogBus.js'
import { LogLevel } from './constants'
import { getTime, withinSpliter, daysBetween } from './util'
function mirrorToConsole(level, msg) {
const text = msg == null ? '' : typeof msg === 'string' ? msg : String(msg)
if (!text) return
const oc = FloatLogBus.getOriginalConsole?.()
if (level === LogLevel.ERROR) {
;(oc?.error || console.error)(text)
} else if (level === LogLevel.WARN) {
;(oc?.warn || console.warn)(text)
} else if (level === LogLevel.DEBUG) {
;(oc?.debug || console.debug)(text)
} else {
;(oc?.log || console.log)(text)
}
}
class LocalLog {
logger = null
logListener = null
......@@ -25,6 +42,7 @@ class LocalLog {
_write (level, msg) {
// #ifdef APP-PLUS
this.logger.writeLog(level, msg)
mirrorToConsole(level, msg)
if (this.logListener) {
try {
this.logListener(level, msg)
......
/*
* @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 }
/*
* 音频帧缓冲池
* 维护最近 N 秒的 PCM 音频帧,支持截取上传
*/
const DEFAULT_SAMPLE_RATE = 16000
const DEFAULT_CHANNELS = 1
const DEFAULT_BITS_PER_SAMPLE = 16
const WAV_HEADER_SIZE = 44
// 格式配置:format -> { contentType, needHeader }
const FORMAT_CONFIG = {
wav: { contentType: 'audio/wav', needHeader: true },
pcm: { contentType: 'application/octet-stream', needHeader: false }
}
export default class AudioFramePool {
/**
* @param {Object} options
* @param {number} options.maxSeconds - 最大保留秒数,默认 60
* @param {number} options.sampleRate - 采样率,默认 16000
* @param {number} options.channels - 声道数,默认 1
* @param {number} options.bitsPerSample - 位深,默认 16
*/
constructor(options = {}) {
this.sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
this.channels = options.channels || DEFAULT_CHANNELS
this.bitsPerSample = options.bitsPerSample || DEFAULT_BITS_PER_SAMPLE
this.maxSeconds = options.maxSeconds || 60
// 每秒字节数: sampleRate * channels * (bitsPerSample / 8)
this.bytesPerSecond = this.sampleRate * this.channels * (this.bitsPerSample / 8)
this.maxBytes = this.bytesPerSecond * this.maxSeconds
// 帧队列: Uint8Array[]
this.frames = []
this.totalBytes = 0
}
/**
* 推入一帧音频数据
* @param {string} base64 - base64 编码的 PCM 数据
*/
push(base64) {
if (!base64 || typeof base64 !== 'string') return
let buffer
try {
// uni-app 内置 API,全平台可用
buffer = uni.base64ToArrayBuffer(base64)
} catch (e) {
uni.$logger?.local?.error(`AudioFramePool: base64解码失败 ${e.message}`)
return
}
const bytes = new Uint8Array(buffer)
this.frames.push(bytes)
this.totalBytes += bytes.byteLength
// 淘汰旧帧
this._evict()
}
/**
* 淘汰超出上限的旧帧
*/
_evict() {
while (this.totalBytes > this.maxBytes && this.frames.length > 0) {
const removed = this.frames.shift()
this.totalBytes -= removed.byteLength
}
}
/**
* 获取当前缓冲池中的音频时长(秒)
*/
getDuration() {
return this.totalBytes / this.bytesPerSecond
}
/**
* 截取当前缓冲池中的音频
* @param {number} [seconds] - 截取最近多少秒,不传则截取全部
* @param {string} [format='pcm'] - 输出格式:'pcm'(纯 PCM)
* @returns {ArrayBuffer|null} ArrayBuffer
*/
capture(seconds, format = 'pcm') {
if (this.frames.length === 0) {
uni.$logger?.local?.warn('AudioFramePool: 缓冲池为空')
return null
}
let targetBytes = this.totalBytes
if (seconds && seconds > 0) {
targetBytes = Math.min(seconds * this.bytesPerSecond, this.totalBytes)
}
// 从末尾向前取帧
const selected = []
let selectedBytes = 0
for (let i = this.frames.length - 1; i >= 0; i--) {
selected.unshift(this.frames[i])
selectedBytes += this.frames[i].byteLength
if (selectedBytes >= targetBytes) break
}
// 拼接所有选中帧
const pcmData = new Uint8Array(selectedBytes)
let offset = 0
for (const frame of selected) {
pcmData.set(frame, offset)
offset += frame.byteLength
}
// 如果取出的字节超过目标,裁剪头部多余部分
const trimmed = selectedBytes > targetBytes
? pcmData.slice(selectedBytes - targetBytes)
: pcmData
// 根据格式决定是否添加 WAV 头
return FORMAT_CONFIG[format].needHeader ? this._addWavHeader(trimmed) : trimmed.buffer
}
/**
* 截取并上传
* @param {Object} options
* @param {string} options.url - 上传接口地址
* @param {number} [options.seconds] - 截取最近多少秒
* @param {string} [options.format='pcm'] - 音频格式:'wav' 或 'pcm'
* @param {Object} [options.header] - 请求头(如 Authorization)
* @returns {Promise<Object>}
*/
async upload(options) {
const { url, seconds, format = 'pcm', header = {} } = options
// if (!url) {
// throw new Error('上传 URL 不能为空')
// }
const audioBuffer = this.capture(seconds, format)
if (!audioBuffer) {
throw new Error('缓冲池为空,无数据可上传')
}
// const pcmSize = FORMAT_CONFIG[format].needHeader ? (audioBuffer.byteLength - WAV_HEADER_SIZE) : audioBuffer.byteLength
// const actualDuration = Math.round(pcmSize / this.bytesPerSecond * 1000) / 1000
// const fileName = `clip_${Date.now()}_${actualDuration}s.${format}`
const contentType = FORMAT_CONFIG[format].contentType
// #ifdef H5
return this._uploadH5(url, audioBuffer, contentType, header)
// #endif
// #ifdef APP-PLUS
return this._uploadApp(url, audioBuffer, contentType, header)
// #endif
}
/**
* H5 平台上传
*/
_uploadH5(url, arrayBuffer, contentType, header = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
xhr.setRequestHeader('Content-Type', contentType)
// 应用额外请求头
Object.entries(header).forEach(([key, value]) => {
xhr.setRequestHeader(key, value)
})
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else {
reject(new Error(`上传失败: ${xhr.status}`))
}
}
xhr.onerror = () => reject(new Error('网络错误'))
xhr.send(arrayBuffer)
})
}
/**
* App 平台上传:直接 ArrayBuffer 通过 uni.request 发送
*/
async _uploadApp(url, arrayBuffer, contentType, header = {}) {
return new Promise((resolve, reject) => {
uni.request({
url,
method: 'POST',
header: {
...header,
'Content-Type': contentType
},
data: arrayBuffer,
success: (res) => resolve(res.data),
fail: (err) => reject(new Error(err.errMsg))
})
})
}
/**
* 用原生 API 写二进制文件(Android/iOS 通用)
*/
async _writeBinaryFile(absPath, arrayBuffer) {
const base64 = uni.arrayBufferToBase64(arrayBuffer)
// #ifdef APP-ANDROID
const Base64 = plus.android.importClass('android.util.Base64')
const javaBytes = Base64.decode(base64, 0)
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
const fos = new FileOutputStream(absPath)
fos.write(javaBytes)
fos.close()
// #endif
// #ifdef APP-IOS
const NSData = plus.ios.importClass('NSData')
const data = NSData.alloc().initWithBase64EncodedStringOptions(base64, 0)
data.writeToFileAtomically(absPath, true)
plus.ios.deleteObject(data)
// #endif
}
/**
* 为 PCM 数据添加 WAV 文件头
* @param {Uint8Array} pcmData - 原始 PCM 数据
* @returns {ArrayBuffer}
*/
_addWavHeader(pcmData) {
const dataSize = pcmData.byteLength
const buffer = new ArrayBuffer(WAV_HEADER_SIZE + dataSize)
const view = new DataView(buffer)
// RIFF header
this._writeString(view, 0, 'RIFF')
view.setUint32(4, 36 + dataSize, true)
this._writeString(view, 8, 'WAVE')
// fmt chunk
this._writeString(view, 12, 'fmt ')
view.setUint32(16, 16, true)
view.setUint16(20, 1, true) // PCM format
view.setUint16(22, this.channels, true)
view.setUint32(24, this.sampleRate, true)
view.setUint32(28, this.bytesPerSecond, true)
view.setUint16(32, this.channels * (this.bitsPerSample / 8), true)
view.setUint16(34, this.bitsPerSample, true)
// data chunk
this._writeString(view, 36, 'data')
view.setUint32(40, dataSize, true)
// 拼接 PCM 数据
const wav = new Uint8Array(buffer)
wav.set(pcmData, WAV_HEADER_SIZE)
return buffer
}
_writeString(view, offset, str) {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i))
}
}
/**
* 清空缓冲池
*/
reset() {
this.frames = []
this.totalBytes = 0
}
/**
* 获取缓冲池状态
*/
getStatus() {
return {
frameCount: this.frames.length,
totalBytes: this.totalBytes,
duration: this.getDuration().toFixed(2) + 's',
maxSeconds: this.maxSeconds
}
}
}
......@@ -4,16 +4,17 @@
* @Author: limin
* @Date: 2024-12-04 18:17:23
* @LastEditors: limin
* @LastEditTime: 2026-01-20 09:23:27
* @LastEditTime: 2026-06-11 16:20:54
* @FilePath: \gl_tape\utils\recordManager\AudioManager.js
*/
import StrategyFactory from './strategies'
class AudioManager {
startOptions = {
duration: 10 * 60 * 1000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
numberOfChannels: 1,
format: 'mp3', // 默认mp3格式
saveDir: null,
}
__isRecording = false
__counter = 0
......@@ -22,25 +23,31 @@ class AudioManager {
/**
* AudioManager类的构造函数
* 负责初始化音频管理器实例,包括音频录制的开始、停止和错误处理
* @param {Function} onFrameRecorded - 实时音频帧记录时的回调函数
* @param {Function} onFrameRecordedEnd - 实时音频帧记录结束时的回调函数
* @param {Function} onStart - 音频录制开始时的回调函数
* @param {Function} onStop - 音频录制停止时的回调函数
* @param {Function} onError - 音频录制遇到错误时的回调函数
*/
constructor(onStart, onStop, onError) {
constructor(onStart, onStop, onError, onFrameRecorded, onFrameRecordedEnd, saveDir = null) {
this.on()
this.events = {
onStart,
onStop,
onError
onError,
onFrameRecorded,
onFrameRecordedEnd,
}
this.startOptions.saveDir = saveDir
}
on() {
// 使用策略工厂获取录音管理器实例
this.recorderManager = StrategyFactory.getRecorderStrategy()
// 统一日志输出,利用多态特性,不再需要 if 判断
uni.$logger.local.info(`AudioManager: Using ${this.recorderManager.name}`)
// 只注册 onFrameRecorded,它会收到所有帧数据(包括 isLastFrame 标记)
this.recorderManager.onFrameRecorded(this.onFrameRecorded.bind(this))
this.recorderManager.onStart(this.onStart.bind(this))
this.recorderManager.onStop(this.onStop.bind(this))
this.recorderManager.onError(this.onError.bind(this))
......@@ -97,6 +104,14 @@ class AudioManager {
await this.events.onStop(res)
}
/**
* 实时音频帧回调
* 接收录音器的帧数据并转发给 this.events.onFrameRecorded
* @param {Object} data - 帧数据,包含 base64 和 isLastFrame
*/
onFrameRecorded(data) {
this.events.onFrameRecorded(data)
}
/**
* 异步处理错误的方法
*
* 当遇到错误时,此方法会被调用,它将等待错误事件处理完成
......@@ -105,6 +120,7 @@ class AudioManager {
* @param {Error} err - 发生的错误对象
*/
async onError(err) {
uni.$logger.local.info('〖录音管理Audio〗 == 录音错误回调 '+JSON.stringify(err))
await this.events.onError(err)
}
/**
......
......@@ -4,7 +4,7 @@
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-21 10:52:09
* @LastEditTime: 2026-06-11 16:21:22
*/
import TempRecord from './TempRecord'
......@@ -20,9 +20,9 @@ class NativeSave extends TempRecord {
* @returns {Promise<void>}
*/
async add(audio) {
uni.$logger.local.info('〖NativeSave〗 == add called with: ' + audio?.fileName)
uni.$logger.local.info('〖NativeSave〗 == add called with: ' + audio?.filePath)
// 创建一个新的记录对象
const recordUrlList = audio && audio.fileName ? [{ file: audio.fileName }] : []
const recordUrlList = audio && audio.filePath ? [{ file: audio.filePath }] : []
// 调用基类通用流程
await super.add(recordUrlList)
}
......
......@@ -91,6 +91,17 @@ class RecordSaveService {
return `${recordId || ''}_${fileName || ''}`
}
_recordIdFromTaskKey(taskKey) {
if (!taskKey) return ''
const idx = String(taskKey).lastIndexOf('_')
if (idx <= 0) return String(taskKey)
const maybeName = taskKey.slice(idx + 1)
if (maybeName && /\.(mp3|wav|m4a)$/i.test(maybeName)) {
return taskKey.slice(0, idx)
}
return String(taskKey)
}
/**
* 保存上传结果
*/
......@@ -130,8 +141,11 @@ class RecordSaveService {
this.endTask()
}
} catch (error) {
if (this._currentKey) {
this._addToBlackList(this._currentKey.split('_')[0], `Save failed: ${error.message}`)
const failRecordId = data?.detail?.data?.[0]?.recordId || data?.recordId
if (failRecordId) {
this._addToBlackList(String(failRecordId), `Save failed: ${error.message}`)
} else if (this._currentKey) {
this._addToBlackList(this._recordIdFromTaskKey(this._currentKey), `Save failed: ${error.message}`)
}
this.reportError(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask()
......@@ -150,6 +164,19 @@ class RecordSaveService {
const { data: d, ...o } = payload
const input = serializeIfObject(o)
uni.$logger.local.warn(`【接待记录保存服务】 == 开始文件信息解析-> ${input}`)
if (
payload.code === 0 &&
(payload.message === 'no file' ||
payload.status === FileStatus.NoFile ||
payload.status === FileStatus.NotExist)
) {
return this._parseNoFileStatus({
recordId: payload.recordId,
fileName: payload.fileName,
filePath: payload.filePath,
status: payload.status ?? FileStatus.NoFile
})
}
return this._parseUploadedFile(data)
}
......@@ -445,8 +472,8 @@ class RecordSaveService {
continue
}
if (recordUrlList.length == 0) {
this._addToBlackList(cur.id, '无语音文件')
result.push({ status: FileStatus.NoFile, recordId: cur.id })
this.reportError('【接待记录保存服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id)
continue
}
for (const file of recordUrlList) {
......
......@@ -4,7 +4,7 @@
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-30 03:19:33
* @LastEditTime: 2026-06-11 16:29:07
* @FilePath: \gl_tape\utils\recordManager\TempRecord.js
*/
import utils from '../utils'
......@@ -56,7 +56,7 @@ class TempRecord {
try {
await this.dbRecord.addRecord(record)
uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id)
this.triggleRecordNumChanged()
this.triggerRecordNumChanged()
} catch (e) {
uni.$logger.local.error('〖接待记录Record〗 == 新增临时记录失败: ' + e.message)
}
......@@ -76,30 +76,13 @@ class TempRecord {
try {
if (!record) throw new Error('记录对象为空')
uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
// const { recordUrlList } = record
// // 调用保存前钩子
// await this.beforeSave(record)
// const recordLongList = await this.analysisUrlList(recordUrlList)
// // 从缓存恢复大字段数据
// const restoredData = RecordCacheManager.consumeAll(record)
// // 构造仅需更新的字段,避免全量更新导致性能浪费
// const updateData = {
// ...toUpdateData, // 确保合并所有字段
// recordStatus: 1,
// recordUrlList: recordLongList,
// ...restoredData // 合并恢复的大字段数据
// }
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
// 直接更新原记录,不再插入新记录
await this.dbRecord.updateRecord(toUpdateData, { id: record.id })
// 删除本地临时文件 (不再删除数据库记录,因为已经转正)
await this.clearLocalRecord(record, false) // 传入 false 表示不删除数据库记录
this.triggleRecordNumChanged()
this.triggerRecordNumChanged()
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling()
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
......@@ -126,14 +109,14 @@ class TempRecord {
*/
async __save(record, toUpdateData) {
try {
const { recordUrlList } = record
// const { recordUrlList } = record
// 从缓存恢复大字段数据
const restoredData = RecordCacheManager.consumeAll(record)
const recordLongList = await this.analysisUrlList(recordUrlList)
// const recordLongList = await this.analysisUrlList(recordUrlList)
const updateData = {
...toUpdateData,
recordStatus: 1,
recordUrlList: recordLongList,
// recordUrlList: recordLongList,
...restoredData // 合并恢复的大字段数据
}
return this.__saveData(updateData, record)
......@@ -147,29 +130,29 @@ class TempRecord {
* @param {Array} recordUrlList - 已保存文件路径列表(形如 { file })
* @returns {Promise<Array>} 规范化后的上传列表(形如 { status, file })
*/
async analysisUrlList(recordUrlList) {
if (!recordUrlList?.length) return []
try {
const basePath = await PathUtils.getBasePath()
const list = []
for (const item of recordUrlList) {
const filePath = item?.file
if (typeof filePath === 'string' && filePath.length > 0) {
const baseName = filePath.split('/').pop()
list.push({
status: FileStatus.Waiting,
file: PathUtils.join(basePath, baseName)
})
} else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
}
}
return list
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message)
}
}
// async analysisUrlList(recordUrlList) {
// if (!recordUrlList?.length) return []
// try {
// const basePath = await PathUtils.getBasePath()
// const list = []
// for (const item of recordUrlList) {
// const filePath = item?.file
// if (typeof filePath === 'string' && filePath.length > 0) {
// const baseName = filePath.split('/').pop()
// list.push({
// status: FileStatus.Waiting,
// file: PathUtils.join(basePath, baseName)
// })
// } else {
// uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
// }
// }
// return list
// } catch (error) {
// uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
// throw new Error(error.message)
// }
// }
/**
* 删除一条临时记录并触发数量变化通知
* @param {string} id - 临时记录 id
......@@ -178,7 +161,7 @@ class TempRecord {
async removeRecord(id) {
await this.dbRecord.removeRecord(id)
uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id)
this.triggleRecordNumChanged()
this.triggerRecordNumChanged()
}
/**
......@@ -370,7 +353,7 @@ class TempRecord {
* 触发临时记录数量变化通知
* @returns {Promise<void>|void}
*/
async triggleRecordNumChanged() {
async triggerRecordNumChanged() {
if (this.onTempRecordNumberChanged) {
this.onTempRecordNumberChanged()
}
......
......@@ -8,14 +8,87 @@ import NativeRecorder from './NativeRecorder'
import NativeSave from './NativeSave'
import PollingSave from './PollingSave'
// #ifdef APP-PLUS
import { getRecorderManagerX } from '@/uni_modules/uni-recorder-x'
// #endif
// 录音模式配置
// true: 使用 NativeRecorder (长录音,直接保存文件)
// false: 使用 uni.getRecorderManager + 30s 轮询保存逻辑
export const USE_NATIVE_RECORDER = true
// 'x' : 使用 uni-recorder-x (默认,支持 onFrameRecorded 实时流回调)
// 'native' : 使用 NativeRecorder (Android Java 原生长录音)
// 'uni' : 使用 uni.getRecorderManager (基础)
export const RECORDER_MODE = 'x'
// --- Recorder Strategies (录音器策略) ---
/**
* uni-recorder-x 策略
* 支持 onFrameRecorded 实时音频流回调,跨平台
*/
class UniRecorderXStrategy {
constructor() {
// #ifdef APP-PLUS
this.manager = getRecorderManagerX()
// #endif
// #ifndef APP-PLUS
this.manager = uni.getRecorderManager()
// #endif
this.name = 'uni-recorder-x'
}
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)
}
/**
* 实时音频帧回调 (仅 APP-PLUS 平台有效)
* @param {Function} cb - 回调函数,参数: { base64, isLastFrame }
*/
onFrameRecorded(cb) {
// #ifdef APP-PLUS
if (this.manager.onFrameRecorded) {
this.manager.onFrameRecorded(cb)
}
// #endif
}
/**
* 实时音频帧结束回调 (仅 APP-PLUS 平台有效)
* @param {Function} cb - 回调函数,参数: { base64, isLastFrame }
*/
onFrameRecordedEnd(cb) {
// #ifdef APP-PLUS
if (this.manager.onFrameRecordedEnd) {
this.manager.onFrameRecordedEnd(cb)
}
// #endif
}
offFrameRecorded() {
// #ifdef APP-PLUS
if (this.manager.offFrameRecorded) {
this.manager.offFrameRecorded()
}
// #endif
}
}
/**
* UniApp 原生录音策略
* 封装 uni.getRecorderManager()
*/
......@@ -56,11 +129,23 @@ class StrategyFactory {
* @returns {Object} 录音器实例 (Strategy)
*/
static getRecorderStrategy() {
// 优先使用 uni-recorder-x (默认)
if (RECORDER_MODE === 'x') {
// #ifdef APP-PLUS
if (plus.os.name === 'Android' || plus.os.name === 'iOS') {
return new UniRecorderXStrategy()
}
// #endif
// 非 APP 平台降级为 uni.getRecorderManager
return new UniRecorderStrategy()
}
// #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
if (RECORDER_MODE === 'native' && plus.os.name === 'Android') {
return NativeRecorder
}
// #endif
return new UniRecorderStrategy()
}
......@@ -72,9 +157,7 @@ class StrategyFactory {
static getSaveStrategy(...args) {
let StrategyClass = PollingSave
// #ifdef APP-PLUS
if (USE_NATIVE_RECORDER && plus.os.name === 'Android') {
StrategyClass = NativeSave
}
StrategyClass = NativeSave
// #endif
return new StrategyClass(...args)
}
......
/*
* 统一通道客户端:构造时选择 http / websocket,对外 API 一致
*
* const client = new NativeChannelClient({ transport: 'websocket' })
* const client = new NativeChannelClient({ transport: 'http', sendPath: '/message', auth: true })
*/
import { TransportType } from './constants.js'
import NativeWsClient from './NativeWsClient.js'
import NativeHttpClient from './NativeHttpClient.js'
class NativeChannelClient {
/**
* @param {object} [options]
* @param {'http'|'websocket'} [options.transport='websocket']
* @param {string} [options.baseUrl] HTTP 根地址(http 模式)
* @param {string} [options.sendPath] HTTP send 路径(http 模式)
* @param {string} [options.wsUrl] WebSocket 地址覆盖(websocket 模式,写入 NATIVE_WS_BASE 逻辑由 ws 客户端处理)
* @param {Function} [options.onMessage]
*/
constructor(options = {}) {
const transport = options.transport || TransportType.WEBSOCKET
this.transport = transport
if (transport === TransportType.HTTP) {
this._impl = new NativeHttpClient(options)
} else {
this._impl = new NativeWsClient()
if (options.wsUrl) {
this._impl.wsAddress = options.wsUrl
}
}
if (typeof options.onMessage === 'function') {
this._impl.onMessage = options.onMessage
}
}
get isConnected() {
return this._impl.isConnected
}
get deviceId() {
return this._impl.deviceId
}
get token() {
return this._impl.token
}
get onMessage() {
return this._impl.onMessage
}
set onMessage(handler) {
this._impl.onMessage = handler
}
connect() {
return this._impl.connect()
}
connectDirect(url) {
if (this.transport !== TransportType.WEBSOCKET) {
return Promise.reject(new Error('connectDirect 仅支持 websocket 模式'))
}
return this._impl.connectDirect(url)
}
send(data, type) {
return this._impl.send(data, type)
}
sendJson(obj) {
if (typeof this._impl.sendJson === 'function') {
return this._impl.sendJson(obj)
}
return this._impl.send(obj)
}
close(...args) {
return this._impl.close(...args)
}
waitUntilConnected(timeoutMs) {
return this._impl.waitUntilConnected(timeoutMs)
}
/** 仅 http 模式:底层 uni.request */
request(options) {
if (this.transport !== TransportType.HTTP) {
return Promise.reject(new Error('request 仅支持 http 模式'))
}
return this._impl.request(options)
}
}
export default NativeChannelClient
/*
* 原生 HTTP 客户端(uni.request)
* - 默认不鉴权:request()/send() 直接可用,不需要 connect()
* - auth=true 时:connect() 会调用 /login 拿 token/deviceId,并在请求中自动附加
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import { normalizeWsPayload } from './wsMessage.js'
import { DEFAULT_HTTP_OPTIONS } from './constants.js'
const DEFAULT_TYPE = 'private'
class NativeHttpClient {
/**
* @param {object} [options]
* @param {string} [options.baseUrl] HTTP 根地址,默认 config.HTTP_SERVER
* @param {string} [options.sendPath] send 请求路径,默认 /message
* @param {string} [options.method] 默认 POST
* @param {object} [options.header] 额外请求头
* @param {number} [options.timeout]
*/
constructor(options = {}) {
this.baseUrl = (options.baseUrl || config.HTTP_SERVER || '').replace(/\/+$/, '')
this.sendPath = options.sendPath || DEFAULT_HTTP_OPTIONS.sendPath
this.method = (options.method || DEFAULT_HTTP_OPTIONS.method).toUpperCase()
this.header = { 'Content-Type': 'application/json', ...(options.header || {}) }
this.timeout = options.timeout ?? DEFAULT_HTTP_OPTIONS.timeout
this.dataType = options.dataType || DEFAULT_HTTP_OPTIONS.dataType
this.auth = options.auth === true || (options.auth && options.auth.enabled === true)
this.token = ''
this.deviceId = ''
this.onMessage = null
// HTTP 无“连接”概念;仅在启用 auth 时,connect() 用于拉取 token/deviceId
this._tag = options.logTag || DEFAULT_HTTP_OPTIONS.logTag
}
get isConnected() {
// HTTP 默认认为可用;若启用鉴权,则以 token 是否存在作为“已连接/已就绪”
return this.auth ? !!this.token : true
}
async connect() {
if (!this.auth) {
return
}
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
this._log('info', `HTTP 已登录 deviceId=${this.deviceId}`)
}
/**
* 通用 uni.request 封装(相对路径自动拼 baseUrl)
* @param {object} options uni.request 参数,url 可为相对路径
*/
request(options = {}) {
const url = this._resolveUrl(options.url)
if (!url) {
return Promise.reject(new Error('request 缺少 url'))
}
const header = { ...this.header, ...(options.header || {}) }
if (this.auth && this.token && !header.token) {
header.token = this.token
}
return new Promise((resolve, reject) => {
uni.request({
timeout: this.timeout,
dataType: this.dataType,
...options,
url,
header,
success: (res) => resolve(res),
fail: (err) => reject(err)
})
})
}
send(data, type = DEFAULT_TYPE) {
if (this.auth && !this.token) {
this._log('warn', 'HTTP 需要鉴权:请先 connect() 获取 token/deviceId')
return Promise.resolve(false)
}
let body
if (typeof data === 'string') {
try {
body = JSON.parse(data)
} catch {
body = { raw: data }
}
} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
this._log('warn', 'HTTP 模式暂不支持 ArrayBuffer,请使用 JSON')
return Promise.resolve(false)
} else {
body = {
...data,
...(this.auth && this.deviceId ? { device_id: this.deviceId } : {}),
...(data.type != null ? { type: data.type } : this.auth ? { type } : {})
}
}
const url = this._resolveUrl(this.sendPath)
return new Promise((resolve) => {
uni.request({
url,
method: this.method,
header: this.auth && this.token ? { ...this.header, token: this.token } : { ...this.header },
data: body,
timeout: this.timeout,
dataType: this.dataType,
success: (res) => {
const ok = res.statusCode >= 200 && res.statusCode < 300
if (!ok) {
this._log('warn', `send 非 2xx status=${res.statusCode} ${serializeIfObject(res.data)}`)
resolve(false)
return
}
const parsed = normalizeWsPayload(res.data)
this._log('info', `收到 <= ${JSON.stringify(parsed).slice(0, 240)}`)
this.onMessage && this.onMessage(parsed)
resolve(true)
},
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
sendJson(obj) {
return this.send(obj)
}
async close() {
this.token = ''
this.deviceId = ''
this._log('info', '会话已关闭')
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
_resolveUrl(path) {
if (!path) return ''
if (/^https?:\/\//i.test(path)) return path
const p = path.startsWith('/') ? path : `/${path}`
return `${this.baseUrl}${p}`
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
export default NativeHttpClient
/*
* 原生 WebSocket 客户端(SocketTask)
* 协议对齐 venus uniapp-x-tape/ws/Ws.uts
* API 对齐 https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - connect(): 走 /login 拿 token/deviceId,然后按 `NATIVE_WS_BASE`(若设置)或 `SOCKET_SERVER + WS_NATIVE_PATH` 连接
* - connectDirect(url): 不登录,直接连接指定 url(用于独立服务)
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import {
buildAuthenticatedWsUrl,
getNativeWsBase,
normalizeWsUrl,
pickLoginWsUrl
} from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js'
import { createSocketTask } from './connectSocketTask.js'
const DEFAULT_TYPE = 'private'
function formatSocketErr(err) {
if (!err) return 'unknown'
if (typeof err === 'string') return err
if (err.errMsg) return err.errMsg
if (err.message) return err.message
const raw = serializeIfObject(err)
return raw === '{}' ? 'WebSocket 连接失败(请确认 utils/socket/wsConfig.js 中 NATIVE_WS_BASE)' : raw
}
class NativeWsClient {
constructor() {
this.wsAddress = getNativeWsBase() || config.SOCKET_SERVER
this.token = ''
this.deviceId = ''
this.onMessage = null
this.socketTask = null
this._connected = false
this._manualClose = false
this._reconnectTimer = null
this._reconnectCount = 0
this._isReconnecting = false
this._directUrl = ''
}
get isConnected() {
return this._connected && this.socketTask != null
}
/** 直连指定 ws 地址(无登录鉴权,用于音频对话等独立服务) */
async connectDirect(url) {
const target = normalizeWsUrl(url)
if (!target) {
throw new Error('connectDirect 缺少 url')
}
this._manualClose = false
this._directUrl = target
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
try {
await this._connectSocketByUrl(target)
} catch (e) {
this._log('error', `connectDirect 失败: ${e.message}`)
throw e
}
}
/** 发送纯 JSON 字符串,不附加 device_id 等字段 */
sendJson(obj) {
return this.send(JSON.stringify(obj))
}
async connect() {
this._manualClose = false
this._directUrl = ''
try {
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
const wsFromLogin = pickLoginWsUrl(data)
if (wsFromLogin) {
this.wsAddress = wsFromLogin
}
await this._createSocket()
} catch (e) {
this._log('error', `connect 失败: ${e.message}`)
this._scheduleReconnect()
throw e
}
}
send(data, type = DEFAULT_TYPE) {
if (!this.isConnected) {
this._log('warn', '未连接,send 忽略')
return Promise.resolve(false)
}
let packet
if (typeof data === 'string') {
packet = data
} else if (data instanceof ArrayBuffer) {
packet = data
} else if (ArrayBuffer.isView(data)) {
packet = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
} else {
packet = JSON.stringify({
...data,
device_id: this.deviceId,
type: data.type || type
})
}
return new Promise((resolve) => {
this.socketTask.send({
data: packet,
success: () => resolve(true),
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
async close(code = 1000, reason = 'manual close', manual = true) {
this._manualClose = manual
this._clearReconnectTimer()
this._connected = false
const task = this.socketTask
this.socketTask = null
if (!task) return
await new Promise((resolve) => {
task.close({ code, reason, complete: () => resolve() })
})
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
async _createSocket() {
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
const url = buildAuthenticatedWsUrl(this.wsAddress, this.token, this.deviceId)
await this._connectSocketByUrl(url)
}
_connectSocketByUrl(targetUrl) {
this._log(
'info',
`连接地址 ${targetUrl}(login=${config.HTTP_SERVER})`
)
return new Promise((resolve, reject) => {
let opened = false
let settled = false
const timer = setTimeout(() => {
if (settled) return
settled = true
reject(new Error(`连接超时: ${targetUrl}`))
}, 8000)
const finishOpen = () => {
if (settled) return
opened = true
settled = true
clearTimeout(timer)
this._reconnectCount = 0
this._isReconnecting = false
this._connected = true
this._log('warn', '连接成功')
resolve()
}
const failEarly = (err) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(new Error(err?.message || serializeIfObject(err)))
}
let socketTask
try {
socketTask = createSocketTask({
url: targetUrl,
fail: (err) => failEarly(err)
})
} catch (e) {
failEarly(e)
return
}
this.socketTask = socketTask
socketTask.onOpen(() => finishOpen())
socketTask.onMessage((event) => this._handleMessage(event?.data))
socketTask.onError((err) => {
this._log('error', `异常 ${formatSocketErr(err)}`)
if (!opened && !settled) {
failEarly(new Error(`onError: ${formatSocketErr(err)}`))
} else if (opened && !this._manualClose) {
this._scheduleReconnect()
}
})
socketTask.onClose((res) => {
this._connected = false
this.socketTask = null
this._log('warn', `断开 ${serializeIfObject(res)}`)
if (!opened && !settled) {
const closeHint = res?.code === 1006 || !res?.code
? '(握手失败,常见原因:路径 404 或服务端仅支持 socket.io)'
: ''
failEarly(new Error(`onClose before open: ${serializeIfObject(res)}${closeHint}`))
return
}
if (!this._manualClose) {
this._scheduleReconnect()
}
})
})
}
_handleMessage(raw) {
const data = normalizeWsPayload(raw)
this._log('info', `收到 <= ${JSON.stringify(data).slice(0, 240)}`)
if (data.errorCode && data.errorCode == 907) {
this._log('warn', 'Token 过期,准备重连')
this._scheduleReconnect(true)
return
}
this.onMessage && this.onMessage(data)
}
_scheduleReconnect(force = false) {
if (this._manualClose) return
if (this._isReconnecting && !force) return
this._isReconnecting = true
this._clearReconnectTimer()
this._reconnectCount += 1
const delay = Math.min(30000, this._reconnectCount * 2000)
this._log('warn', `${delay}ms 后第 ${this._reconnectCount} 次重连`)
this._reconnectTimer = setTimeout(() => {
this._reconnectTimer = null
const reconnect = this._directUrl
? () => this.connectDirect(this._directUrl)
: () => this.connect()
reconnect().catch(() => {})
}, delay)
}
_clearReconnectTimer() {
if (this._reconnectTimer != null) {
clearTimeout(this._reconnectTimer)
this._reconnectTimer = null
}
}
_log(level, msg) {
const text = `[NativeWs] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
let _instance = null
NativeWsClient.getInstance = function getInstance() {
if (!_instance) {
_instance = new NativeWsClient()
}
return _instance
}
NativeWsClient.resetInstance = function resetInstance() {
if (_instance) {
_instance.close().catch(() => {})
_instance = null
}
}
export default NativeWsClient
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!