Commit d0891af7 by 岑成威

Merge remote-tracking branch 'origin/bug' into saas+v5.9.0

2 parents a02d0b87 a7f52ad5
Showing 55 changed files with 3750 additions and 49 deletions
...@@ -5,6 +5,11 @@ ...@@ -5,6 +5,11 @@
import { Ws } from '@/ws/Ws.js' import { Ws } from '@/ws/Ws.js'
import { RecordSaveService, UploadService } from '@/utils/recordManager/index.js' import { RecordSaveService, UploadService } from '@/utils/recordManager/index.js'
import appCacheApi from '@/utils/clearAppCache.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 { export default {
computed: { computed: {
...mapState('audio', ['isEnd', 'isStart']) ...mapState('audio', ['isEnd', 'isStart'])
...@@ -13,6 +18,27 @@ ...@@ -13,6 +18,27 @@
userInfo: uni.getStorageSync('release_userInfo') userInfo: uni.getStorageSync('release_userInfo')
}, },
onLaunch: async function () { 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.onKeep()
// this.setAPPVersion() // this.setAPPVersion()
setTimeout(() => { setTimeout(() => {
...@@ -52,21 +78,10 @@ ...@@ -52,21 +78,10 @@
appCacheApi.clearAppCache() appCacheApi.clearAppCache()
this.$store.dispatch('setBackgroundState', false) this.$store.dispatch('setBackgroundState', false)
this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数 this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling() RecordSaveService.startPolling()
uni.onMemoryWarning(function () { uni.onMemoryWarning(function () {
console.log('onMemoryWarningReceive') 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 () { onHide: function () {
this.$store.dispatch('setBackgroundState', true) this.$store.dispatch('setBackgroundState', true)
...@@ -168,4 +183,3 @@ ...@@ -168,4 +183,3 @@
left: 0rpx; left: 0rpx;
} }
</style> </style>
\ No newline at end of file \ No newline at end of file
...@@ -21,6 +21,11 @@ const getMockData = async (immediate = false) => { ...@@ -21,6 +21,11 @@ const getMockData = async (immediate = false) => {
const MOCKDATA = uni.$storage.get('mock_data') const MOCKDATA = uni.$storage.get('mock_data')
try { try {
if (!immediate && MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) { 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) return Promise.resolve(MOCKDATA)
} else { } else {
if (!serverConfig.mockRequestCount || immediate) { if (!serverConfig.mockRequestCount || immediate) {
...@@ -30,6 +35,11 @@ const getMockData = async (immediate = false) => { ...@@ -30,6 +35,11 @@ const getMockData = async (immediate = false) => {
data.createTime = Date.now() data.createTime = Date.now()
serverConfig.mockCache = data serverConfig.mockCache = data
uni.$storage.set('mock_data', data) uni.$storage.set('mock_data', data)
try {
require('@/utils/logger/FloatLogConfig.js').default.applyFromMockData(data)
} catch (e) {
/* ignore */
}
return Promise.resolve(data) return Promise.resolve(data)
} else { } else {
const key = Date.now() const key = Date.now()
......
<template>
<!-- #ifdef APP-PLUS -->
<view class="audio-demo-root">
<view
class="audio-demo-fab"
:class="{ running: isRunning }"
@tap.stop="onFabClick"
>
<text class="fab-label">{{ fabText }}</text>
<text class="fab-sub">PCM</text>
</view>
<view v-if="panelVisible" class="audio-demo-mask" @tap="panelVisible = false">
<view class="audio-demo-panel" @tap.stop>
<view class="panel-head">
<text class="panel-title">录音 / WS Demo</text>
<text class="panel-status">{{ statusText }}</text>
<view class="panel-actions">
<text class="act" @tap.stop="clearLogs">清空</text>
<text class="act danger" @tap.stop="panelVisible = false">关闭</text>
</view>
</view>
<scroll-view class="panel-scroll" scroll-y :scroll-into-view="scrollIntoView">
<view
v-for="(line, idx) in logs"
:key="line.time + '_' + idx"
:id="'demo-log-' + idx"
:class="['log-line', 'lv-' + line.level]"
>
<text class="log-text">{{ line.text }}</text>
</view>
<view v-if="!logs.length" class="log-empty">点击悬浮按钮开始:录音 5s → WS 上传</view>
</scroll-view>
<view class="panel-foot">
<text class="hint">日志同步至 uni.$logger 与悬浮「日志」球(若已开启)</text>
</view>
</view>
</view>
</view>
<!-- #endif -->
</template>
<script>
// #ifdef APP-PLUS
import AudioStreamDemoRunner from '@/utils/audioStream/AudioStreamDemoRunner.js'
// #endif
const STATUS_MAP = {
idle: '待命',
connecting: '连接 WS…',
recording: '录音中(5s)',
uploading: '上传中…',
done: '完成'
}
export default {
name: 'AudioStreamDemo',
data() {
return {
panelVisible: false,
status: 'idle',
logs: [],
scrollIntoView: '',
// #ifdef APP-PLUS
runner: null
// #endif
}
},
computed: {
isRunning() {
return this.status === 'connecting' || this.status === 'recording' || this.status === 'uploading'
},
fabText() {
if (this.status === 'recording') return '录'
if (this.status === 'uploading') return '传'
return '测'
},
statusText() {
return STATUS_MAP[this.status] || this.status
}
},
created() {
// #ifdef APP-PLUS
this.runner = new AudioStreamDemoRunner({
onLog: (entry) => this.appendLog(entry),
onStatus: (s) => {
this.status = s
}
})
// #endif
},
beforeDestroy() {
// #ifdef APP-PLUS
this.runner?.cancel()
// #endif
},
methods: {
onFabClick() {
// #ifndef APP-PLUS
uni.showToast({ title: '仅 App 端', icon: 'none' })
return
// #endif
this.panelVisible = true
if (this.isRunning) return
this.startDemo()
},
async startDemo() {
// #ifdef APP-PLUS
this.appendLog({ level: 'info', text: '[AudioDemo] 点击开始', time: Date.now() })
const ok = await this.runner.start()
if (!ok && this.status === 'idle') {
uni.showToast({ title: '启动失败,看日志', icon: 'none' })
}
// #endif
},
appendLog(entry) {
this.logs.push(entry)
if (this.logs.length > 300) {
this.logs.splice(0, this.logs.length - 300)
}
this.$nextTick(() => {
this.scrollIntoView = 'demo-log-' + (this.logs.length - 1)
})
},
clearLogs() {
this.logs = []
}
}
}
</script>
<style lang="scss" scoped>
/* 全屏占位但不挡点击,仅悬浮钮可点(与 FloatLogPanel 同模式) */
.audio-demo-root {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 100010;
pointer-events: none;
}
.audio-demo-fab {
position: fixed;
left: 24rpx;
top: 120rpx;
pointer-events: auto;
width: 112rpx;
height: 112rpx;
border-radius: 56rpx;
background: linear-gradient(135deg, #3b82f6, #2563eb);
box-shadow: 0 8rpx 24rpx rgba(37, 99, 235, 0.55);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
&.running {
background: linear-gradient(135deg, #ef4444, #dc2626);
animation: pulse 1s ease-in-out infinite;
}
}
.fab-label {
color: #fff;
font-size: 34rpx;
font-weight: 600;
line-height: 1.1;
}
.fab-sub {
color: rgba(255, 255, 255, 0.85);
font-size: 18rpx;
margin-top: 4rpx;
}
@keyframes pulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.06);
}
}
.audio-demo-mask {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
pointer-events: auto;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: flex-end;
}
.audio-demo-panel {
width: 100%;
max-height: 70vh;
background: #1e1e1e;
border-radius: 24rpx 24rpx 0 0;
display: flex;
flex-direction: column;
}
.panel-head {
padding: 24rpx 28rpx 16rpx;
border-bottom: 1px solid #333;
}
.panel-title {
color: #f5f5f5;
font-size: 30rpx;
font-weight: 600;
}
.panel-status {
display: block;
margin-top: 8rpx;
color: #93c5fd;
font-size: 24rpx;
}
.panel-actions {
margin-top: 16rpx;
display: flex;
gap: 24rpx;
}
.act {
color: #60a5fa;
font-size: 26rpx;
&.danger {
color: #f87171;
}
}
.panel-scroll {
flex: 1;
max-height: 50vh;
padding: 16rpx 24rpx;
box-sizing: border-box;
}
.log-line {
margin-bottom: 12rpx;
font-size: 22rpx;
line-height: 1.45;
word-break: break-all;
}
.log-text {
color: #d4d4d4;
}
.lv-warn .log-text {
color: #fbbf24;
}
.lv-error .log-text {
color: #f87171;
}
.lv-debug .log-text {
color: #9ca3af;
}
.log-empty {
color: #6b7280;
font-size: 24rpx;
padding: 40rpx 0;
text-align: center;
}
.panel-foot {
padding: 16rpx 24rpx 32rpx;
border-top: 1px solid #333;
}
.hint {
color: #6b7280;
font-size: 22rpx;
}
</style>
...@@ -126,9 +126,18 @@ ...@@ -126,9 +126,18 @@
</view> </view>
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
<!-- #ifdef APP-PLUS -->
<AudioStreamDemo />
<!-- #endif -->
<FloatLogPanel v-if="showFloatLog" />
</view> </view>
</template> </template>
<script> <script>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
// #ifdef APP-PLUS
import AudioStreamDemo from '@/components/AudioStreamDemo/AudioStreamDemo.vue'
// #endif
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import ReceptionCenter from './components/ReceptionCenter/index.vue' import ReceptionCenter from './components/ReceptionCenter/index.vue'
import SceneMarket from './components/SceneMarket/index.vue' import SceneMarket from './components/SceneMarket/index.vue'
// import myClick from '@/mixin/click' // import myClick from '@/mixin/click'
...@@ -147,7 +156,7 @@ import Ranking from './components/Point/Ranking.vue' ...@@ -147,7 +156,7 @@ import Ranking from './components/Point/Ranking.vue'
import Calendar from './components/Income/Calendar.vue' import Calendar from './components/Income/Calendar.vue'
import Promotion from './components/Income/Promotion.vue' import Promotion from './components/Income/Promotion.vue'
import History from './components/Income/History.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 MessageDetail from './components/Message/MessageDetail.vue'
import SwiperComponent from '../SwiperComponent.vue' import SwiperComponent from '../SwiperComponent.vue'
import StudyCenter from './components/StudyCenter.vue' import StudyCenter from './components/StudyCenter.vue'
...@@ -166,8 +175,12 @@ import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue' ...@@ -166,8 +175,12 @@ import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue'
import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js' import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js'
export default { export default {
// mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin], // mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin],
mixins: [recorder, versionCheck, interceptionMixin], mixins: [ recorder, versionCheck, interceptionMixin, merge],
components: { components: {
FloatLogPanel,
// #ifdef APP-PLUS
AudioStreamDemo,
// #endif
ReceptionCenter, ReceptionCenter,
StudyCenter, StudyCenter,
SceneMarket, SceneMarket,
...@@ -216,6 +229,7 @@ export default { ...@@ -216,6 +229,7 @@ export default {
}, },
data() { data() {
return { return {
showFloatLog: false,
studyUrl: '', studyUrl: '',
jumpUrl: '', jumpUrl: '',
transfer: '', transfer: '',
...@@ -254,12 +268,17 @@ export default { ...@@ -254,12 +268,17 @@ export default {
} }
}, },
beforeDestroy() { beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
// 组件销毁前移除监听 // 组件销毁前移除监听
uni.$logger.local.info('levelStudyPopup 移除监听') uni.$logger.local.info('levelStudyPopup 移除监听')
uni.$off('levelStudyPopup') uni.$off('levelStudyPopup')
uni.$off('pageBack') uni.$off('pageBack')
}, },
async mounted() { async mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
uni.$logger.local.info('levelStudyPopup 开始监听mounted') uni.$logger.local.info('levelStudyPopup 开始监听mounted')
uni.$on('levelStudyPopup', obj => { uni.$on('levelStudyPopup', obj => {
uni.$logger.local.info('接收到学习弹窗事件', obj) uni.$logger.local.info('接收到学习弹窗事件', obj)
...@@ -327,6 +346,9 @@ export default { ...@@ -327,6 +346,9 @@ export default {
}) })
}, },
methods: { methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
},
// 处理开始测评(参考 detail.vue 的实现) // 处理开始测评(参考 detail.vue 的实现)
async handleStartAssessment() { async handleStartAssessment() {
this.showStudyPopup = false this.showStudyPopup = false
......
...@@ -19,13 +19,18 @@ ...@@ -19,13 +19,18 @@
{{ title }} {{ title }}
</view> </view>
<slot></slot> <slot></slot>
<FloatLogPanel v-if="showFloatLog" />
</view> </view>
</template> </template>
<script type='text/ecmascript-6'> <script type='text/ecmascript-6'>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
export default { export default {
components: { FloatLogPanel },
props: { props: {
pageStyle:{ pageStyle: {
type: String, type: String,
default: '' default: ''
}, },
...@@ -49,14 +54,24 @@ export default { ...@@ -49,14 +54,24 @@ export default {
default: '' default: ''
} }
}, },
name: '', data() {
data () {
return { return {
showFloatLog: false
} }
}, },
mounted () { mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
},
beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
}, },
methods: { methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
}
} }
} }
</script> </script>
......
...@@ -2,7 +2,7 @@ module.exports = { ...@@ -2,7 +2,7 @@ module.exports = {
// 请求域名 格式:https://xxx.xxx.com // 请求域名 格式:https://xxx.xxx.com
HTTP_REQUEST_URL: 'http://127.0.0.1:8000/api', 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_DOMAIN: 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com',
// 文件直传到阿里云oss时需用到 // 文件直传到阿里云oss时需用到
......
const target = ['ip', 'dev', 'uat', 'prod', 'beta'] const target = ['ip', 'dev', 'uat', 'prod', 'beta']
const index = 3 const index = 2
/** /**
* *
0本地 0本地
......
...@@ -103,13 +103,16 @@ uni.signHttpConfig = { ...@@ -103,13 +103,16 @@ uni.signHttpConfig = {
if (!uni.$dbRecord) { if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord() uni.$dbRecord = new DBRecord()
} }
uni.$storageMergeDone = new Promise(resolve => {
uni.$resolveStorageMerge = resolve
})
// 导出数据库初始化 Promise,供其他模块等待 // 导出数据库初始化 Promise,供其他模块等待
if (!uni.$dbReady) { if (!uni.$dbReady) {
uni.$dbReady = (async _ => { uni.$dbReady = (async _ => {
try { try {
await uni.$dbRecord.init() await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃 await uni.$storageMergeDone
uni.$logger.local.info('数据库初始化完成') uni.$logger.local.info('数据库初始化与路径合并已完成')
return true return true
} catch (e) { } catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message) uni.$logger.local.error('数据库初始化失败: ' + e.message)
......
...@@ -3,15 +3,13 @@ import { PathUtils } from '../utils/recordManager/index' ...@@ -3,15 +3,13 @@ import { PathUtils } from '../utils/recordManager/index'
class SQLite { class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例 static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size) { constructor(name, version, description, size, dbPath) {
this.name = name this.name = name
this.version = version || '1.0' this.version = version || '1.0'
this.description = description || 'SQLite DB' this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null this.db = null
//注意: this.dbPath = dbPath || `_doc/${name}.db`
this.dbPath = `_doc/${name}.db` // 存储数据库的完整路径
this.dbPath = `_doc/${name}.db` // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在) // 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) { if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`) SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
...@@ -207,11 +205,34 @@ class SQLite { ...@@ -207,11 +205,34 @@ class SQLite {
return isopen return isopen
} }
close() { close() {
if (this.db) { return this.closeDatabase()
this.db.close() }
this.db = null
console.log('数据库连接已关闭') /** 关闭 plus.sqlite 连接(与 openDatabase 配对) */
closeDatabase() {
return this._enqueue(
() =>
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) { drop(tabName) {
const sql = `DROP TABLE IF EXISTS ${tabName}` const sql = `DROP TABLE IF EXISTS ${tabName}`
......
import { storageApi } from '@/utils/cache' 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 { export default {
mounted() { mounted() {
// this.mergeRecord() // this.mergeRecord()
...@@ -60,8 +71,10 @@ export default { ...@@ -60,8 +71,10 @@ export default {
processNextEntry() // 处理下一个条目 processNextEntry() // 处理下一个条目
}, },
function (e) { function (e) {
console.log('文件删除失败:', e.message) // 文件占用/无权限时常见,避免刷屏
uni.$logger.local.info(`文件删除失败: ->${entry.fullPath} ->${e.message}`) uni.$logger?.local?.debug?.(
`清理跳过文件:${entry.fullPath} -> ${e.message || e}`
)
deleteCount++ deleteCount++
processNextEntry() // 处理下一个条目 processNextEntry() // 处理下一个条目
} }
...@@ -102,24 +115,32 @@ export default { ...@@ -102,24 +115,32 @@ export default {
) )
}, },
clearPrevFile() { clearPrevFile() {
let version = plus.runtime.version if (typeof plus === 'undefined') return
let clearVersion = uni.$storage.get('clearVersion') if (this._clearPrevFileRunning) return
if (clearVersion != version) { const version = plus.runtime.version
const wwwPath = plus.io.convertLocalFileSystemURL('doc') const clearVersion = uni.$storage.get('clearVersion')
// const filesPath = wwwPath.replace(/apps.+/, 'apps/') if (clearVersion === version) return
// console.log(filesPath)
const filesPath = wwwPath.replace(/gltap.+/, 'gltap/') const docPath = plus.io.convertLocalFileSystemURL('_doc')
this.getDirectoryContents(filesPath) const filesPath = resolvePackageRootFromDocUrl(docPath)
if (!filesPath) {
uni.$storage.set('clearVersion', version)
return
} }
setTimeout(() => {
// 立即标记,避免 HomeFrame 反复挂载时在 5s 内重复整目录清理
uni.$storage.set('clearVersion', version) uni.$storage.set('clearVersion', version)
}, 5000) this._clearPrevFileRunning = true
uni.$logger?.local?.info?.(`版本升级清理包根目录:${filesPath}`)
this.getDirectoryContents(filesPath)
}, },
getDirectoryContents(dirPath) { getDirectoryContents(dirPath) {
// 解析目录路径 // 解析目录路径
const _this = this const _this = this
const excludeFile = ['databases'] // 切勿删除 apps / databases,否则会扫到正在使用的 doc、库文件并报「不允许读」
const excludeFile = ['databases', 'apps', 'cache', 'files']
plus.io.resolveLocalFileSystemURL( plus.io.resolveLocalFileSystemURL(
dirPath, dirPath,
function (entry) { function (entry) {
...@@ -132,10 +153,10 @@ export default { ...@@ -132,10 +153,10 @@ export default {
console.log('目录内容读取成功:') console.log('目录内容读取成功:')
_this.directoryList = entries _this.directoryList = entries
entries.forEach(function (entry) { entries.forEach(function (entry) {
console.log('文件路径:', entry.fullPath) const name = entry.name || ''
if (!excludeFile.includes(entry.name)) { if (excludeFile.includes(name)) return
if (entry.isFile && /\.db$/i.test(name)) return
_this.deleteDirectory(entry.fullPath) _this.deleteDirectory(entry.fullPath)
}
}) })
}, },
function (e) { function (e) {
......
...@@ -43,6 +43,10 @@ export default { ...@@ -43,6 +43,10 @@ export default {
}, },
updateCustomerInfo(data){ updateCustomerInfo(data){
this.recordService.updateCustomerInfo(data) this.recordService.updateCustomerInfo(data)
},
/** 订阅接待中的实时 PCM 音频帧 */
onAudioStreamChunk(callback) {
return this.recordService?.getAudioStreamService()?.onChunk(callback) || (() => {})
} }
} }
} }
## 1.0.0
- Android AudioRecord PCM 实时采集
- 支持 onPcmFrame 帧回调(base64)
{
"id": "gl-pcm-capture",
"displayName": "gl-pcm-capture",
"version": "1.0.0",
"description": "Android PCM 实时采集,通过回调输出音频帧(base64)",
"keywords": ["pcm", "audio", "record", "stream"],
"repository": "",
"engines": {
"HBuilderX": "^3.94"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": { "price": "0.00" },
"sourcecode": { "price": "0.00" }
},
"contact": { "qq": "" },
"declaration": {
"ads": "无",
"data": "插件不采集任何数据,仅在本地回调 PCM 帧",
"permissions": "android.permission.RECORD_AUDIO"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": { "tcb": "n", "aliyun": "n" },
"client": {
"Vue": { "vue2": "y", "vue3": "y" },
"App": {
"app-android": { "minVersion": "21" },
"app-ios": "n"
},
"H5-mobile": {
"Safari": "n",
"Android Browser": "n",
"微信浏览器(Android)": "n",
"QQ浏览器(Android)": "n"
},
"H5-pc": {
"Chrome": "n",
"IE": "n",
"Edge": "n",
"Firefox": "n",
"Safari": "n"
},
"小程序": {
"微信": "n",
"阿里": "n",
"百度": "n",
"字节跳动": "n",
"QQ": "n",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": { "华为": "n", "联盟": "n" }
}
}
}
}
# gl-pcm-capture
Android 端 PCM 实时采集 UTS 插件。通过 `AudioRecord` 在后台线程读取音频帧,以 base64 形式回调给 JS 层。
## 使用
```javascript
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
onPcmFrame((frame) => {
console.log('pcm frame', frame.seq, frame.byteLength)
})
startPcmCapture({
sampleRate: 16000,
frameSize: 4096,
success: () => console.log('started'),
fail: (err) => console.error(err)
})
// 停止
stopPcmCapture()
offPcmFrame()
```
推荐通过 `utils/audioStream/AudioStreamService.js` 封装使用。
## 注意
- 仅支持 Android App 自定义基座 / 正式包
- 需要 `RECORD_AUDIO` 权限
- 与 `MediaRecorder` 同时占用 MIC 时,部分机型可能冲突,后续将统一采集层
package uts.sdk.modules.glPcmCapture
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Base64
/**
* PCM 读帧结果(供 UTS 层回调 JS)
*/
class PcmFrameData(
val base64: String,
val byteLength: Int
)
object PcmCaptureNative {
@JvmStatic
fun getMinBufferSize(sampleRate: Int): Int {
return AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
)
}
@JvmStatic
fun createRecorder(sampleRate: Int, bufferSize: Int): AudioRecord {
return AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize
)
}
@JvmStatic
fun readFrame(recorder: AudioRecord, frameSize: Int): PcmFrameData? {
val buffer = ByteArray(frameSize)
val readLen = recorder.read(buffer, 0, frameSize)
if (readLen <= 0) {
return null
}
val base64 = Base64.encodeToString(buffer, 0, readLen, Base64.NO_WRAP)
return PcmFrameData(base64, readLen)
}
}
import AudioRecord from 'android.media.AudioRecord'
import Thread from 'java.lang.Thread'
import Runnable from 'java.lang.Runnable'
import { PcmCaptureNative } from 'uts.sdk.modules.glPcmCapture'
import {
StartPcmCaptureOptions,
StartPcmCaptureSuccess,
PcmFrameResult,
StopPcmCaptureOptions,
StopPcmCaptureSuccess
} from '../interface.uts'
import { PcmCaptureFailImpl } from '../unierror.uts'
let audioRecord : AudioRecord | null = null
let captureThread : Thread | null = null
let isRunning = false
let seqCounter : Int = 0
let frameCallback : ((res : PcmFrameResult) => void) | null = null
let currentSampleRate : Int = 16000
let currentFrameSize : Int = 4096
export function onPcmFrame(callback : (res : PcmFrameResult) => void) : void {
frameCallback = callback
}
export function offPcmFrame() : void {
frameCallback = null
}
function dispatchFrame(frame : PcmFrameResult) : void {
const cb = frameCallback
if (cb == null) {
return
}
const activity = UTSAndroid.getUniActivity()
if (activity != null) {
const uiRunnable = new (class implements Runnable {
override run() : void {
cb(frame)
}
})
activity.runOnUiThread(uiRunnable)
} else {
cb(frame)
}
}
export function startPcmCapture(options : StartPcmCaptureOptions) : void {
if (isRunning) {
const err = new PcmCaptureFailImpl(1400003)
options.fail?.(err)
options.complete?.(err)
return
}
const sampleRateInt = (options.sampleRate ?? 16000).toInt()
const frameSizeInt = (options.frameSize ?? 4096).toInt()
currentSampleRate = sampleRateInt
currentFrameSize = frameSizeInt
const minBufferSize = PcmCaptureNative.getMinBufferSize(sampleRateInt)
if (minBufferSize <= 0) {
const err = new PcmCaptureFailImpl(1400001)
options.fail?.(err)
options.complete?.(err)
return
}
const bufferSizeInt = Math.max(minBufferSize, frameSizeInt * 2).toInt()
try {
const recorder = PcmCaptureNative.createRecorder(sampleRateInt, bufferSizeInt)
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
recorder.release()
const err = new PcmCaptureFailImpl(1400002)
options.fail?.(err)
options.complete?.(err)
return
}
audioRecord = recorder
isRunning = true
seqCounter = 0
recorder.startRecording()
const runnable = new (class implements Runnable {
override run() : void {
while (isRunning && audioRecord != null) {
const frameData = PcmCaptureNative.readFrame(audioRecord!, currentFrameSize)
if (frameData != null) {
const frame : PcmFrameResult = {
base64: frameData.base64,
byteLength: frameData.byteLength,
seq: seqCounter,
timestamp: Date.now(),
sampleRate: currentSampleRate,
channels: 1,
bitDepth: 16
}
seqCounter++
dispatchFrame(frame)
} else {
// read 返回 0 或负数时短暂让出 CPU,避免空转
Thread.sleep(10)
}
}
}
})
const thread = new Thread(runnable)
captureThread = thread
thread.start()
const success : StartPcmCaptureSuccess = { errMsg: 'startPcmCapture:ok' }
options.success?.(success)
options.complete?.(success)
} catch (e : Exception) {
isRunning = false
audioRecord = null
const err = new PcmCaptureFailImpl(1400001)
err.errMsg = 'startPcmCapture fail: ' + e.message
options.fail?.(err)
options.complete?.(err)
}
}
export function stopPcmCapture(options ?: StopPcmCaptureOptions) : void {
isRunning = false
const recorder = audioRecord
if (recorder != null) {
try {
recorder.stop()
} catch (e : Exception) {
// 录音过短时 stop 可能抛异常,忽略
}
try {
recorder.release()
} catch (e : Exception) {
// ignore
}
audioRecord = null
}
captureThread = null
seqCounter = 0
const success : StopPcmCaptureSuccess = { errMsg: 'stopPcmCapture:ok' }
options?.success?.(success)
options?.complete?.(success)
}
export type PcmFrameResult = {
base64: string
byteLength: number
seq: number
timestamp: number
sampleRate: number
channels: number
bitDepth: number
}
export type StartPcmCaptureOptions = {
sampleRate?: number
frameSize?: number
success?: (res: { errMsg: string }) => void
fail?: (err: { errCode: number; errMsg: string }) => void
complete?: (res: any) => void
}
export type StopPcmCaptureOptions = {
success?: (res: { errMsg: string }) => void
complete?: (res: any) => void
}
export declare function startPcmCapture(options: StartPcmCaptureOptions): void
export declare function stopPcmCapture(options?: StopPcmCaptureOptions): void
export declare function onPcmFrame(callback: (res: PcmFrameResult) => void): void
export declare function offPcmFrame(): void
export type PcmFrameResult = {
base64 : string
byteLength : number
seq : number
timestamp : number
sampleRate : number
channels : number
bitDepth : number
}
export type StartPcmCaptureSuccess = {
errMsg : string
}
export type StopPcmCaptureSuccess = {
errMsg : string
}
export type PcmCaptureErrorCode = 1400001 | 1400002 | 1400003
export interface PcmCaptureFail extends IUniError {
errCode : PcmCaptureErrorCode
}
export type PcmCaptureFailCallback = (err : PcmCaptureFail) => void
export type StartPcmCaptureSuccessCallback = (res : StartPcmCaptureSuccess) => void
export type StopPcmCaptureSuccessCallback = (res : StopPcmCaptureSuccess) => void
export type PcmCaptureCompleteCallback = (res : any) => void
export type PcmFrameCallback = (res : PcmFrameResult) => void
export type StartPcmCaptureOptions = {
sampleRate ?: number
frameSize ?: number
success ?: StartPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StopPcmCaptureOptions = {
success ?: StopPcmCaptureSuccessCallback | null
fail ?: PcmCaptureFailCallback | null
complete ?: PcmCaptureCompleteCallback | null
}
export type StartPcmCapture = (options : StartPcmCaptureOptions) => void
export type StopPcmCapture = (options ?: StopPcmCaptureOptions) => void
export type OnPcmFrame = (callback : PcmFrameCallback) => void
export type OffPcmFrame = () => void
import { PcmCaptureErrorCode, PcmCaptureFail } from "./interface.uts"
export const UniErrorSubject = 'gl-pcm-capture'
export const UniErrors : Map<PcmCaptureErrorCode, string> = new Map([
[1400001, 'AudioRecord init or read failed'],
[1400002, 'AudioRecord not initialized'],
[1400003, 'Already capturing'],
])
export class PcmCaptureFailImpl extends UniError implements PcmCaptureFail {
constructor(errCode : PcmCaptureErrorCode) {
super()
this.errSubject = UniErrorSubject
this.errCode = errCode
this.errMsg = UniErrors[errCode] ?? ""
}
}
/*
* @Description: 首页录音 + WebSocket 边录边传 Demo(NativeWsClient)
*/
import AudioStreamService from './AudioStreamService.js'
import { demoLog } from './demoLog.js'
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import permision from '@/js_sdk/wa-permission/permission.js'
const DEMO_RECORD_MS = 5000
const PCM_START_TIMEOUT_MS = 8000
export default class AudioStreamDemoRunner {
constructor(hooks = {}) {
this._onLog = hooks.onLog || (() => {})
this._onStatus = hooks.onStatus || (() => {})
this._frames = []
this._chunkHandler = null
this._timer = null
this._running = false
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
}
get isRunning() {
return this._running
}
async start() {
// #ifndef APP-PLUS
this._log('warn', '仅 App 端支持')
return false
// #endif
// #ifdef APP-PLUS
if (this._running) {
this._log('warn', 'Demo 进行中')
return false
}
if (plus.os.name !== 'Android') {
this._log('warn', '当前 Demo 仅支持 Android PCM')
return false
}
const permitted = await this._ensureRecordPermission()
if (!permitted) {
this._log('error', '无录音权限')
return false
}
this._running = true
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
this._setStatus('connecting')
this._ws = NativeWsClient.getInstance()
this._prevOnMessage = this._ws.onMessage
this._ws.onMessage = (data) => {
this._log('info', `[WS] 收到 <= ${JSON.stringify(data || {}).slice(0, 240)}`)
this._prevOnMessage && this._prevOnMessage(data)
}
if (!this._ws.isConnected) {
this._log('info', '连接原生 WebSocket(uni.connectSocket)…')
try {
await this._ws.connect()
this._ownsWs = true
} catch (e) {
this._log('error', `WebSocket 连接失败: ${e.message || e}`)
this._cleanup(false)
return false
}
} else {
this._log('info', '复用已有 NativeWs 连接')
}
const stream = AudioStreamService.getInstance()
if (stream.isRunning) {
this._log('warn', 'PCM 采集中(可能接待录音占用麦克风),先停止再试')
stream.stop()
}
this._chunkHandler = (frame) => this._onPcmChunk(frame)
stream.onChunk(this._chunkHandler)
let started = false
try {
started = await Promise.race([
stream.start({ debugLog: true }),
new Promise((_, reject) => {
setTimeout(() => reject(new Error('PCM 启动超时,检查 gl-pcm-capture 插件与麦克风占用')), PCM_START_TIMEOUT_MS)
})
])
} catch (e) {
this._log('error', e.message || String(e))
started = false
}
if (!started) {
this._log('error', 'PCM 采集启动失败(插件未生效或麦克风被占用)')
this._cleanup(false)
return false
}
this._setStatus('recording')
this._log('info', `PCM 已启动,边录边传 ${DEMO_RECORD_MS / 1000}s 后结束`)
this._timer = setTimeout(() => {
this.stopAndUpload()
}, DEMO_RECORD_MS)
return true
// #endif
}
_onPcmChunk(frame) {
this._frames.push({
seq: frame.seq,
base64: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
})
if (frame.seq % 8 === 0) {
this._log('info', `采集中 帧#${frame.seq} ${frame.byteLength}B,已缓存 ${this._frames.length} 帧,已发送 ${this._sentCount} 帧`)
}
const ws = this._ws
if (!ws?.isConnected) return
this._sendChain = this._sendChain
.then(() => this._sendPcmFrame(frame))
.catch((e) => {
this._log('warn', `发送帧#${frame.seq} 失败: ${e.message || e}`)
})
}
async _sendPcmFrame(frame) {
const ws = this._ws
if (!ws?.isConnected) return
if (!this._streamStarted) {
const ok = await ws.send({
command: 'audioStreamStart',
data: {
sampleRate: 16000,
channels: 1,
bitDepth: 16,
format: 'pcm',
demo: true
}
})
if (!ok) {
throw new Error('audioStreamStart 发送失败')
}
this._streamStarted = true
this._log('info', '已发送 audioStreamStart,开始上传 PCM 帧')
}
const ok = await ws.send({
command: 'audioStream',
data: {
seq: frame.seq,
chunk: frame.base64,
byteLength: frame.byteLength,
timestamp: frame.timestamp
}
})
if (!ok) {
throw new Error(`audioStream seq=${frame.seq} 发送失败`)
}
this._sentCount++
if (this._sentCount % 10 === 0) {
this._log('info', `实时上传 ${this._sentCount} 帧`)
}
}
async stopAndUpload() {
if (!this._running) return
clearTimeout(this._timer)
this._timer = null
this._setStatus('uploading')
this._log('info', '停止录音…')
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
await this._sendChain.catch(() => {})
const total = this._frames.length
const bytes = this._frames.reduce((sum, f) => sum + (f.byteLength || 0), 0)
this._log('info', `录音结束:采集 ${total} 帧 / 已发送 ${this._sentCount} 帧,约 ${(bytes / 1024).toFixed(1)} KB`)
const ws = this._ws
if (ws?.isConnected && this._streamStarted) {
try {
await ws.send({
command: 'audioStreamEnd',
data: { total, sent: this._sentCount, bytes }
})
this._log('info', `已发送 audioStreamEnd sent=${this._sentCount}`)
} catch (e) {
this._log('error', `audioStreamEnd 失败: ${e.message || e}`)
}
} else if (total === 0) {
this._log('warn', '未采集到 PCM 数据,未向服务端发送音频')
} else if (!this._streamStarted) {
this._log('warn', '未发送 audioStreamStart,跳过 audioStreamEnd')
}
this._cleanup(true)
}
cancel() {
clearTimeout(this._timer)
this._timer = null
const stream = AudioStreamService.getInstance()
if (this._chunkHandler) {
stream.offChunk(this._chunkHandler)
this._chunkHandler = null
}
stream.stop()
this._cleanup(false)
this._log('warn', 'Demo 已取消')
}
async _ensureRecordPermission() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
const code = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
return code === 1
}
// #endif
return true
}
_cleanup(done) {
this._running = false
this._frames = []
this._streamStarted = false
this._sentCount = 0
this._sendChain = Promise.resolve()
if (this._ws) {
this._ws.onMessage = this._prevOnMessage
}
if (this._ownsWs && this._ws) {
this._ws.close().catch(() => {})
NativeWsClient.resetInstance()
}
this._ws = null
this._prevOnMessage = null
this._ownsWs = false
this._setStatus(done ? 'done' : 'idle')
}
_log(level, msg) {
const entry = demoLog(level, msg)
this._onLog(entry)
}
_setStatus(status) {
this._onStatus(status)
}
}
/*
* @Description: PCM 实时流服务(Android UTS 插件封装)
* 用法:
* const stream = AudioStreamService.getInstance()
* stream.onChunk((frame) => { ... })
* stream.start() / stream.stop()
*/
import { DEFAULT_FRAME_SIZE, DEFAULT_SAMPLE_RATE } from './constants.js'
import { normalizePcmFrame } from './pcmUtils.js'
// #ifdef APP-PLUS
import {
startPcmCapture,
stopPcmCapture,
onPcmFrame,
offPcmFrame
} from '@/uni_modules/gl-pcm-capture'
// #endif
class AudioStreamService {
static _instance = null
constructor() {
this._listeners = new Set()
this._running = false
this._frameHandler = null
this._logEveryN = 50
this._frameCount = 0
}
static getInstance() {
if (!AudioStreamService._instance) {
AudioStreamService._instance = new AudioStreamService()
}
return AudioStreamService._instance
}
/**
* 订阅 PCM 帧
* @param {(frame: object) => void} callback frame 含 base64、buffer(ArrayBuffer)、seq 等
* @returns {() => void} 取消订阅
*/
onChunk(callback) {
if (typeof callback !== 'function') {
return () => {}
}
this._listeners.add(callback)
return () => this._listeners.delete(callback)
}
offChunk(callback) {
this._listeners.delete(callback)
}
get isRunning() {
return this._running
}
/**
* @param {object} [options]
* @param {number} [options.sampleRate]
* @param {number} [options.frameSize]
* @param {boolean} [options.debugLog] 是否打印采样日志
*/
start(options = {}) {
// #ifndef APP-PLUS
uni.$logger?.local?.warn('[AudioStream] 仅 App 端支持')
return Promise.resolve(false)
// #endif
// #ifdef APP-PLUS
if (plus.os.name !== 'Android') {
uni.$logger?.local?.warn('[AudioStream] 当前仅实现 Android PCM 采集')
return Promise.resolve(false)
}
if (typeof startPcmCapture !== 'function') {
uni.$logger?.local?.error(
'[AudioStream] gl-pcm-capture 未加载,请使用含 UTS 插件的自定义基座/正式包'
)
return Promise.resolve(false)
}
if (this._running) {
return Promise.resolve(true)
}
const sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE
const frameSize = options.frameSize || DEFAULT_FRAME_SIZE
const debugLog = options.debugLog !== false
this._frameHandler = (frame) => {
const normalized = normalizePcmFrame(frame)
this._frameCount++
if (debugLog && this._frameCount % this._logEveryN === 1) {
uni.$logger?.local?.info(
`[AudioStream] frame#${normalized.seq} bytes=${normalized.byteLength} ts=${normalized.timestamp}`
)
}
this._listeners.forEach((cb) => {
try {
cb(normalized)
} catch (e) {
uni.$logger?.local?.error(`[AudioStream] listener error: ${e.message}`)
}
})
}
onPcmFrame(this._frameHandler)
return new Promise((resolve) => {
startPcmCapture({
sampleRate,
frameSize,
success: () => {
this._running = true
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已启动')
resolve(true)
},
fail: (err) => {
offPcmFrame()
this._frameHandler = null
uni.$logger?.local?.error(`[AudioStream] 启动失败: ${JSON.stringify(err)}`)
resolve(false)
}
})
})
// #endif
}
stop() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
stopPcmCapture()
offPcmFrame()
}
// #endif
this._running = false
this._frameHandler = null
this._frameCount = 0
uni.$logger?.local?.info('[AudioStream] PCM 采集已停止')
}
}
export default AudioStreamService
/** 接待录音时是否同步启动 PCM 流采集(Android) */
export const ENABLE_PCM_STREAM = true
/** 默认采样率,与接待录音一致 */
export const DEFAULT_SAMPLE_RATE = 16000
/** 每帧字节数,约 128ms @ 16kHz mono 16bit */
export const DEFAULT_FRAME_SIZE = 4096
import FloatLogBus from '@/utils/logger/FloatLogBus.js'
const DEMO_TAG = '[AudioDemo]'
export function demoLog(level, msg) {
const text = `${DEMO_TAG} ${msg}`
const logger = uni.$logger?.local
// 只走 logger;若已 install FloatLogBus,logger 监听器会同步到悬浮窗,避免重复打两条
if (logger?.[level]) {
logger[level](text)
} else {
console.log(text)
try {
if (!FloatLogBus.isInstalled()) {
FloatLogBus.install()
}
FloatLogBus.push(level, text)
} catch (_) {
/* ignore */
}
}
return { level, text, time: Date.now() }
}
import AudioStreamService from './AudioStreamService.js'
import AudioStreamDemoRunner from './AudioStreamDemoRunner.js'
import { ENABLE_PCM_STREAM, DEFAULT_SAMPLE_RATE, DEFAULT_FRAME_SIZE } from './constants.js'
import { base64ToArrayBuffer, normalizePcmFrame } from './pcmUtils.js'
import { demoLog } from './demoLog.js'
export {
AudioStreamService,
AudioStreamDemoRunner,
ENABLE_PCM_STREAM,
DEFAULT_SAMPLE_RATE,
DEFAULT_FRAME_SIZE,
base64ToArrayBuffer,
normalizePcmFrame,
demoLog
}
export default AudioStreamService
/**
* base64 PCM → ArrayBuffer
* @param {string} base64
* @returns {ArrayBuffer}
*/
export function base64ToArrayBuffer(base64) {
if (typeof uni !== 'undefined' && typeof uni.base64ToArrayBuffer === 'function') {
return uni.base64ToArrayBuffer(base64)
}
const binary = atob(base64)
const len = binary.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes.buffer
}
/**
* 将插件帧数据标准化,附带 ArrayBuffer
* @param {object} frame
* @returns {object}
*/
export function normalizePcmFrame(frame) {
return {
...frame,
buffer: base64ToArrayBuffer(frame.base64)
}
}
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 @@ ...@@ -8,8 +8,25 @@
* 可以输入预定的版权声明、个性签名、空行等 * 可以输入预定的版权声明、个性签名、空行等
*/ */
import LogCat from './LogCat' import LogCat from './LogCat'
import FloatLogBus from './FloatLogBus.js'
import { LogLevel } from './constants' import { LogLevel } from './constants'
import { getTime, withinSpliter, daysBetween } from './util' 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 { class LocalLog {
logger = null logger = null
logListener = null logListener = null
...@@ -22,6 +39,7 @@ class LocalLog { ...@@ -22,6 +39,7 @@ class LocalLog {
} }
_write(level, msg) { _write(level, msg) {
this.logger.writeLog(level, msg) this.logger.writeLog(level, msg)
mirrorToConsole(level, msg)
if (this.logListener) { if (this.logListener) {
try { try {
this.logListener(level, msg) this.logListener(level, msg)
......
...@@ -91,6 +91,17 @@ class RecordSaveService { ...@@ -91,6 +91,17 @@ class RecordSaveService {
return `${recordId || ''}_${fileName || ''}` 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 { ...@@ -130,8 +141,11 @@ class RecordSaveService {
this.endTask() this.endTask()
} }
} catch (error) { } catch (error) {
if (this._currentKey) { const failRecordId = data?.detail?.data?.[0]?.recordId || data?.recordId
this._addToBlackList(this._currentKey.split('_')[0], `Save failed: ${error.message}`) 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.reportError(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
this.endTask() this.endTask()
...@@ -150,6 +164,19 @@ class RecordSaveService { ...@@ -150,6 +164,19 @@ class RecordSaveService {
const { data: d, ...o } = payload const { data: d, ...o } = payload
const input = serializeIfObject(o) const input = serializeIfObject(o)
uni.$logger.local.warn(`【接待记录保存服务】 == 开始文件信息解析-> ${input}`) 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) return this._parseUploadedFile(data)
} }
...@@ -445,8 +472,8 @@ class RecordSaveService { ...@@ -445,8 +472,8 @@ class RecordSaveService {
continue continue
} }
if (recordUrlList.length == 0) { if (recordUrlList.length == 0) {
this._addToBlackList(cur.id, '无语音文件')
result.push({ status: FileStatus.NoFile, recordId: cur.id }) result.push({ status: FileStatus.NoFile, recordId: cur.id })
this.reportError('【接待记录保存服务】 == 记录中不存在接待语音文件', { record: cur }, cur.id)
continue continue
} }
for (const file of recordUrlList) { for (const file of recordUrlList) {
......
...@@ -11,6 +11,7 @@ import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } fro ...@@ -11,6 +11,7 @@ import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } fro
import { storageApi } from '@/utils/cache' import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js' import permision from '@/js_sdk/wa-permission/permission.js'
import store from '@/store' import store from '@/store'
import AudioStreamService, { ENABLE_PCM_STREAM } from '@/utils/audioStream'
class RecordService { class RecordService {
static instance = null static instance = null
...@@ -99,6 +100,7 @@ class RecordService { ...@@ -99,6 +100,7 @@ class RecordService {
} }
this.audioManager.start() this.audioManager.start()
this.timeoutService.start() this.timeoutService.start()
await this.startPcmStream()
return true // 返回 true 表示成功启动 return true // 返回 true 表示成功启动
} catch (e) { } catch (e) {
uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}`) uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}`)
...@@ -200,10 +202,26 @@ class RecordService { ...@@ -200,10 +202,26 @@ class RecordService {
this.stopAudioRecord() this.stopAudioRecord()
} }
stopAudioRecord() { stopAudioRecord() {
this.stopPcmStream()
this.audioManager?.stop() this.audioManager?.stop()
this.timeoutService?.stop() this.timeoutService?.stop()
} }
/** 获取 PCM 流服务,业务侧通过 onChunk 监听实时音频帧 */
getAudioStreamService() {
return AudioStreamService.getInstance()
}
async startPcmStream() {
if (!ENABLE_PCM_STREAM) return
await AudioStreamService.getInstance().start()
}
stopPcmStream() {
if (!ENABLE_PCM_STREAM) return
AudioStreamService.getInstance().stop()
}
handler(params, fn, delay = 0) { handler(params, fn, delay = 0) {
if (this.isReceptioning()) { if (this.isReceptioning()) {
// if (delay > 0) { // if (delay > 0) {
......
/*
* 原生 WebSocket 客户端(SocketTask)
* 协议对齐 venus uniapp-x-tape/ws/Ws.uts
* API 对齐 https://uniapp.dcloud.net.cn/api/request/websocket.html
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import {
buildAuthenticatedWsUrl,
getNativeWsBase,
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
}
get isConnected() {
return this._connected && this.socketTask != null
}
async connect() {
this._manualClose = false
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)
}
const packet =
typeof data === 'string'
? data
: 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
this.connect().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
/*
* socket.io 客户端封装(与 ws/Ws.js 同协议,供 Demo / 业务推流使用)
* 注意:项目服务端是 socket.io,不能用 uni.connectSocket 直连
*/
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import config from '@/config.js'
import { WsTyps } from '@/utils/common'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
class SocketIoClient {
constructor(options = {}) {
this._tag = options.logTag || 'SocketIo'
this._ws = null
this._deviceId = null
this._token = null
this._onMessage = null
this._connected = false
}
get isConnected() {
return this._connected && this._ws != null
}
get deviceId() {
return this._deviceId
}
onMessage(handler) {
this._onMessage = typeof handler === 'function' ? handler : null
}
/**
* 登录并连接 socket.io(与 Ws.js 相同 path / auth)
*/
async connect() {
if (this.isConnected) {
return true
}
const { code, data } = await loginDevice()
if (code != 200) {
throw new Error(`WS 登录失败 code=${code}`)
}
this._deviceId = data.id
this._token = data.token
this._log('info', `登录成功 deviceId=${this._deviceId}`)
return new Promise((resolve, reject) => {
const socket = io(config.SOCKET_SERVER, {
path: '/websocket/',
auth: { token: this._token, deviceId: this._deviceId },
transports: ['websocket'],
timeout: 5000
})
const timer = setTimeout(() => {
cleanup()
reject(new Error('socket.io 连接超时'))
}, 8000)
const onConnect = () => {
cleanup()
this._ws = socket
this._connected = true
this._log('info', 'socket.io 已连接')
this._bindMessage()
resolve(true)
}
const onError = (err) => {
cleanup()
this._log('error', `socket.io 错误 ${serializeIfObject(err)}`)
reject(err || new Error('socket.io error'))
}
const onDisconnect = () => {
this._connected = false
this._log('warn', 'socket.io 已断开')
}
const cleanup = () => {
clearTimeout(timer)
socket.off(WsTyps.Connected, onConnect)
socket.off(WsTyps.Eroor, onError)
}
socket.on(WsTyps.Connected, onConnect)
socket.on(WsTyps.Eroor, onError)
socket.on(WsTyps.Disconnected, onDisconnect)
this._log('info', `连接 socket.io -> ${config.SOCKET_SERVER}/websocket/`)
})
}
_bindMessage() {
if (!this._ws || !this._onMessage) return
this._ws.on(WsTyps.MessageTypes.Private, (data) => {
this._onMessage(data)
})
}
/**
* 发送消息(默认 private 频道,自动带 device_id)
* @param {object} data
*/
send(data, type = WsTyps.MessageTypes.Private) {
if (!this.isConnected) {
return Promise.reject(new Error('socket.io 未连接'))
}
const payload = { device_id: this._deviceId, ...data }
this._log('debug', `发送 => ${serializeIfObject(data).slice(0, 200)}`)
this._ws.emit(type, payload)
return Promise.resolve({ errMsg: 'emit:ok' })
}
disconnect() {
this._connected = false
if (this._ws) {
try {
this._ws.disconnect()
} catch (_) {
/* ignore */
}
this._ws = null
}
this._onMessage = null
this._log('info', 'socket.io 已关闭')
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
uni.$logger?.local?.[level]?.(text) || console.log(text)
}
}
export default SocketIoClient
/*
* uni.connectSocket 官方说明:
* https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - 至少传入 success / fail / complete 之一 → 同步返回 SocketTask
* - 不传上述回调 → 返回封装后的 Promise<SocketTask>
*
* 统一使用 SocketTask(onOpen / onMessage / send / close),
* 不使用已废弃的全局 uni.onSocketOpen / uni.sendSocketMessage 等。
*/
export function isSocketTask(task) {
return task != null && typeof task.onOpen === 'function'
}
/**
* 文档推荐写法:传入 complete,同步拿到 SocketTask
* @param {{ url: string, header?: object, protocols?: string[], fail?: Function }} options
* @returns {object} SocketTask
*/
export function createSocketTask(options) {
const { url, header, protocols, fail } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const socketTask = uni.connectSocket({
url,
header: header || {},
protocols: protocols || [],
fail,
complete: () => {}
})
if (!isSocketTask(socketTask)) {
throw new Error('connectSocket 未返回 SocketTask,需传入 success / fail / complete 之一')
}
return socketTask
}
/**
* 兼容 Promise 封装:不传 success/fail/complete 时 await
* @param {{ url: string, header?: object, protocols?: string[] }} options
* @returns {Promise<object>} SocketTask
*/
export async function connectSocketTask(options) {
const { url, header, protocols } = options
if (!url) {
throw new Error('connectSocket 缺少 url')
}
const result = uni.connectSocket({
url,
header: header || {},
protocols: protocols || []
})
if (isSocketTask(result)) {
return result
}
if (result != null && typeof result.then === 'function') {
const task = await result
if (!isSocketTask(task)) {
throw new Error('connectSocket Promise 未解析为 SocketTask')
}
return task
}
return createSocketTask(options)
}
/** WebSocket 连接状态 */
export const SocketState = {
IDLE: 'idle',
CONNECTING: 'connecting',
OPEN: 'open',
CLOSING: 'closing',
CLOSED: 'closed'
}
export const DEFAULT_OPTIONS = {
/** 断线后是否自动重连 */
reconnect: true,
/** 重连间隔(ms) */
reconnectInterval: 3000,
/** 最大重连次数,-1 表示不限 */
reconnectMaxRetries: -1,
/** 未连接时是否缓存 send 队列 */
enableSendQueue: true,
/** send 队列上限 */
sendQueueMax: 100,
/** 收到文本消息时尝试 JSON.parse */
autoParseJson: true,
/** 日志标签 */
logTag: 'SocketClient'
}
import SocketClient from './SocketClient.js'
import NativeWsClient from './NativeWsClient.js'
import { createSocketTask, connectSocketTask, isSocketTask } from './connectSocketTask.js'
import { SocketState, DEFAULT_OPTIONS } from './constants.js'
import {
WS_NATIVE_PATH,
NATIVE_WS_BASE,
setNativeWsBase,
getNativeWsBase,
normalizeWsUrl,
buildAuthenticatedWsUrl,
pickLoginWsUrl
} from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js'
import { loginDevice } from './wsAuth.js'
export {
SocketClient,
NativeWsClient,
createSocketTask,
connectSocketTask,
isSocketTask,
SocketState,
DEFAULT_OPTIONS,
WS_NATIVE_PATH,
NATIVE_WS_BASE,
setNativeWsBase,
getNativeWsBase,
normalizeWsUrl,
buildAuthenticatedWsUrl,
pickLoginWsUrl,
normalizeWsPayload,
loginDevice
}
export default SocketClient
/*
* 设备 WS 登录:POST {HTTP_SERVER}/login,body { sn: deviceId }
* 对齐 venus uniapp-x-tape/ws/Ws.uts login()
*
* 使用方:
* - utils/socket/NativeWsClient(原生 SocketTask / 音频 Demo)
* 不使用方:
* - ws/Ws.js 主业务 socket.io(自带 login(),未引用本文件)
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
function assertLoginResponse(body, loginAddress) {
if (body == null || typeof body !== 'object' || Array.isArray(body)) {
const preview = typeof body === 'string' ? body.slice(0, 80) : serializeIfObject(body)
throw new Error(`登录返回非 JSON,HTTP_SERVER 可能配错: ${loginAddress} -> ${preview}`)
}
if (body.code == null && body.data == null) {
throw new Error(
`登录返回无 code(多为前端 HTML 或地址错误): ${loginAddress}`
)
}
}
/**
* @param {number} retryCount
* @param {number} retryDelay
* @returns {Promise<object>}
*/
export async function loginDevice(retryCount = 3, retryDelay = 2000) {
const loginAddress = `${config.HTTP_SERVER}/login`
const tryLogin = async (attemptCount) => {
const sysInfo = uni.getSystemInfoSync()
if (!sysInfo?.deviceId) {
throw new Error('未获取到系统设备信息')
}
uni.$logger?.local?.info(
`WS登录(第${attemptCount}次) ${loginAddress} ${JSON.stringify({ deviceId: sysInfo.deviceId })}`
)
return new Promise((resolve, reject) => {
uni.request({
url: loginAddress,
data: { sn: sysInfo.deviceId },
method: 'POST',
dataType: 'json',
success: (response) => {
try {
assertLoginResponse(response.data, loginAddress)
resolve(response.data)
} catch (e) {
reject(e)
}
},
fail: reject
})
})
}
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
return await tryLogin(attempt)
} catch (err) {
if (attempt === retryCount) {
uni.$logger?.local?.error(
`WS登录失败(已重试${retryCount}次) err->${serializeIfObject(err)}`
)
throw err
}
uni.$logger?.local?.warn(
`WS登录失败(第${attempt}次), ${retryDelay / 1000}s后重试...`
)
await new Promise((r) => setTimeout(r, retryDelay))
}
}
}
/*
* 原生 WebSocket 地址(对齐 uniapp-x-tape/ws/Ws.uts)
* 连接格式: ws://host:port/path?token=xxx&deviceId=xxx
*
* WebSocket 与 HTTP 共用同一套服务,地址由服务端提供后填到 NATIVE_WS_BASE。
* 不修改 config.js / env.js。
*/
import config from '@/config.js'
/** SOCKET_SERVER 仅为域名时自动拼接的路径 */
export const WS_NATIVE_PATH = '/ws-native'
/**
* 原生 WS 完整 base(不含 ?token=),服务端提供后填写,例如:
* ws://host:8081/ws-native
*/
export let NATIVE_WS_BASE = 'wss://echo.websocket.org'
export function setNativeWsBase(url) {
NATIVE_WS_BASE = (url || '').trim()
}
export function getNativeWsBase() {
return NATIVE_WS_BASE
}
/**
* @param {string} url
* @returns {string}
*/
export function normalizeWsUrl(url) {
if (!url) return ''
const trimmed = url.trim()
if (/^wss?:\/\//i.test(trimmed)) {
return trimmed.replace(/\/+$/, '')
}
if (trimmed.startsWith('https://')) {
return `wss://${trimmed.slice(8)}`.replace(/\/+$/, '')
}
if (trimmed.startsWith('http://')) {
return `ws://${trimmed.slice(7)}`.replace(/\/+$/, '')
}
return trimmed
}
/**
* 从登录 data 中取服务端下发的 ws 地址(若有)
* @param {object} data
*/
export function pickLoginWsUrl(data) {
if (!data) return ''
return (
data.wsUrl ||
data.ws_url ||
data.socketUrl ||
data.socket_url ||
data.wsAddress ||
data.ws_address ||
''
)
}
/**
* 拼带鉴权 query 的完整 ws 地址
* @param {string} base SOCKET_SERVER 或登录返回的 wsUrl
* @param {string} token
* @param {string|number} deviceId
*/
export function buildAuthenticatedWsUrl(base, token, deviceId) {
const configured = NATIVE_WS_BASE.trim()
let root = configured ? normalizeWsUrl(configured) : normalizeWsUrl(base)
if (!configured) {
const path = WS_NATIVE_PATH.startsWith('/') ? WS_NATIVE_PATH : `/${WS_NATIVE_PATH}`
const hasPath = /^wss?:\/\/[^/]+\/.+/.test(root)
if (!hasPath) {
root = `${root.replace(/\/+$/, '')}${path}`
}
}
const encodedToken = encodeURIComponent(token)
const encodedDeviceId = encodeURIComponent(String(deviceId))
return `${root}?token=${encodedToken}&deviceId=${encodedDeviceId}`
}
/*
* 原生 WebSocket 消息解析(对齐 uniapp-x-tape/ws/Ws.uts normalizePayload)
*/
/**
* @param {string|ArrayBuffer|object} raw
* @returns {object}
*/
export function normalizeWsPayload(raw) {
if (raw == null) {
return { command: 'message', data: null }
}
let parsed = null
if (typeof raw === 'string') {
try {
parsed = JSON.parse(raw.trim())
} catch {
return { command: 'message', raw }
}
} else if (raw instanceof ArrayBuffer) {
try {
const text = uni.arrayBufferToBase64
? decodeArrayBuffer(raw)
: String(raw)
parsed = JSON.parse(text)
} catch {
return { command: 'message', raw: '[ArrayBuffer]' }
}
} else if (typeof raw === 'object') {
parsed = raw
} else {
return { command: 'message', raw: String(raw) }
}
// { event: "private", data: { command: "xxx" } }
if (parsed.event != null && parsed.data != null) {
return typeof parsed.data === 'object' ? parsed.data : { data: parsed.data }
}
// { code: 200, data: { event, data: { command } } }
if (parsed.code != null && parsed.data != null) {
const outer = parsed.data
if (outer && outer.data != null) {
return typeof outer.data === 'object' ? outer.data : { data: outer.data }
}
return typeof outer === 'object' ? outer : { data: outer }
}
return parsed
}
function decodeArrayBuffer(buffer) {
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder('utf-8').decode(buffer)
}
const bytes = new Uint8Array(buffer)
let s = ''
for (let i = 0; i < bytes.length; i++) {
s += String.fromCharCode(bytes[i])
}
return s
}
/**
* targetSdk>=29 时 plus.io 无法以绝对路径读写 /data/data、/data/user;
* 本应用沙箱内可用 Java File 复制(与 DCloud 文档说明一致)。
*/
function normalizeAbs(path) {
if (!path) return ''
return String(path)
.replace(/^file:\/\//, '')
.trim()
}
export function isInternalSandboxAbsPath(path) {
const p = normalizeAbs(path)
return p.startsWith('/data/data/') || p.startsWith('/data/user/')
}
export function resolvePlusAbsolutePath(relativeOrUrl) {
if (!relativeOrUrl || typeof plus === 'undefined') return ''
try {
return normalizeAbs(plus.io.convertLocalFileSystemURL(relativeOrUrl))
} catch (_) {
return normalizeAbs(relativeOrUrl)
}
}
export function fileExistsByAndroid(absPath) {
const p = normalizeAbs(absPath)
if (!p || typeof plus === 'undefined') return false
try {
const File = plus.android.importClass('java.io.File')
const f = plus.android.newObject('java.io.File', p)
return !!f.exists() && f.isFile()
} catch (_) {
return false
}
}
export function copyFileByAndroid(srcAbs, destAbs) {
const srcPath = normalizeAbs(srcAbs)
const destPath = normalizeAbs(destAbs)
if (!srcPath || !destPath) {
return Promise.reject(new Error('copyFileByAndroid: 路径为空'))
}
return new Promise((resolve, reject) => {
try {
const File = plus.android.importClass('java.io.File')
const FileInputStream = plus.android.importClass('java.io.FileInputStream')
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
const srcFile = plus.android.newObject('java.io.File', srcPath)
if (!srcFile.exists()) {
reject(new Error(`源文件不存在:${srcPath}`))
return
}
const destFile = plus.android.newObject('java.io.File', destPath)
const parent = destFile.getParentFile()
if (parent && !parent.exists() && !parent.mkdirs()) {
reject(new Error(`无法创建目标目录:${parent.getAbsolutePath()}`))
return
}
const inputStream = plus.android.newObject('java.io.FileInputStream', srcFile)
const outputStream = plus.android.newObject('java.io.FileOutputStream', destFile)
const buffer = plus.android.newObject('byte[]', 8192)
let length = plus.android.invoke(inputStream, 'read', buffer)
while (length > 0) {
plus.android.invoke(outputStream, 'write', buffer, 0, length)
length = plus.android.invoke(inputStream, 'read', buffer)
}
plus.android.invoke(outputStream, 'flush')
plus.android.invoke(inputStream, 'close')
plus.android.invoke(outputStream, 'close')
if (!destFile.exists()) {
reject(new Error(`复制后目标不存在:${destPath}`))
return
}
resolve(destPath)
} catch (e) {
reject(new Error(e?.message || String(e)))
}
})
}
export const PATH_CACHE_KEY = 'zyzs_storage_path_cache'
/** 记录「当前包根 + 已处理过的 alternate 包根」,避免未切换时每次启动重复扫库 */
export const MERGE_STATE_KEY = 'zyzs_storage_merge_state'
export const DB_FILE = 'zyzs.db'
export const TEMP_DB_FILE = '_zyzs_temp_.db'
export const MAIN_DB_NAME = 'zyzs'
export const TEMP_DB_NAME = 'zyzs_temp_merge'
/** 正式发包 Android 包名;自定义基座运行时为 io.dcloud.HBuilder 等 */
export const RELEASE_PACKAGE_NAME = 'uni.gltap'
/** @deprecated 使用 RELEASE_PACKAGE_NAME */
export const PACKAGE_NAME = RELEASE_PACKAGE_NAME
export const TABLE_NAME = 'records'
export const MAIN_DB_PATH = `_doc/${DB_FILE}`
export const TEMP_DB_PATH = `_doc/${TEMP_DB_FILE}`
/** 与 PathUtils.SAVE_DIR_NAME 一致 */
export const UNIAPP_SAVE_DIR = 'uniapp_save'
/** 是否检测当前包根下扁平 zyzs.db(包根/zyzs.db,非 apps/.../doc) */
export const ENABLE_LEGACY_FLAT_DB_MERGE = false
import SQLite from '@/lib/sqlite.js'
import { TEMP_DB_NAME, TEMP_DB_PATH, TABLE_NAME } from './constants.js'
import { logStep, logStepFail } from './log.js'
const STAGE = '归并·数据库'
/** 合并用临时库(路径 _doc/_zyzs_temp_.db,与主库 zyzs 区分) */
const tempSqlite = new SQLite(TEMP_DB_NAME, '1.0', 'path merge temp', 50 * 1024 * 1024, TEMP_DB_PATH)
export async function openTempDb() {
try {
await tempSqlite.init()
logStep(STAGE, 'SQLite 临时库 init 成功', { 逻辑名: TEMP_DB_NAME, 路径: TEMP_DB_PATH })
return true
} catch (e) {
logStepFail(STAGE, 'SQLite 临时库 init 失败', { 错误: e?.message || String(e) })
throw e
}
}
export async function closeTempDb() {
try {
if (tempSqlite.isOpen()) {
await tempSqlite.closeDatabase()
logStep(STAGE, 'SQLite 临时库已关闭', { 逻辑名: TEMP_DB_NAME })
} else {
logStep(STAGE, 'SQLite 临时库本就未打开,无需关闭')
}
} catch (e) {
logStepFail(STAGE, 'SQLite 临时库关闭失败', { 错误: e?.message || String(e) })
}
}
export async function selectTempRecords() {
logStep(STAGE, `检查临时库是否存在表 ${TABLE_NAME}`)
const exists = await tempSqlite.isTableExists(TABLE_NAME)
if (!exists) {
logStep(STAGE, `临时库无 ${TABLE_NAME} 表,视为 0 条`)
return []
}
logStep(STAGE, `执行 SELECT * FROM ${TABLE_NAME}`)
const rows = await tempSqlite.selectSql(`SELECT * FROM ${TABLE_NAME}`)
logStep(STAGE, '临时库查询完成', { 条数: rows?.length || 0 })
return rows
}
function getDbRecord() {
const dbRecord = uni.$dbRecord
if (!dbRecord) {
throw new Error('uni.$dbRecord 未就绪,请先执行 init()')
}
return dbRecord
}
/** 依赖 uni.$dbRecord.init() 已建表,直接向主库插入 */
export async function mergeRecordsToMain(rows, meta = {}) {
const total = rows?.length || 0
logStep(STAGE, '逐条合并到主库', { 待处理: total, ...meta })
const dbRecord = getDbRecord()
let merged = 0
let skipped = 0
let failed = 0
for (const record of rows) {
if (!record || !record.id) {
skipped++
logStepFail(STAGE, '跳过无效记录(无 id)', { 记录: record })
continue
}
try {
const exists = await dbRecord.getRecordById(record.id)
if (exists) {
skipped++
logStep(STAGE, `主库已存在,跳过 id=${record.id}`)
continue
}
await dbRecord.addRecord(record)
merged++
} catch (e) {
failed++
logStepFail(STAGE, `插入主库失败 id=${record.id}`, {
错误: e?.message || String(e),
已成功: merged,
已跳过: skipped
})
logStepFail(STAGE, '合并中止,返回失败', { 来源: meta.来源 })
return false
}
}
logStep(STAGE, '主库合并统计', {
待处理: total,
新插入: merged,
跳过已存在或无效: skipped,
失败: failed,
...meta
})
if (failed > 0) {
return false
}
return true
}
import { UNIAPP_SAVE_DIR } from './constants.js'
import { normalizePath } from './pathCache.js'
export function resolveUniappSaveDir(packageRoot, appId) {
const root = normalizePath(packageRoot)
return `${root}/apps/${appId}/doc/${UNIAPP_SAVE_DIR}`
}
export function resolveDocRootFromPackageRoot(packageRoot, appId) {
const root = normalizePath(packageRoot)
return `${root}/apps/${appId}/doc`
}
import { isRestrictedInternalPath } from './pathAccess.js'
import { UNIAPP_SAVE_DIR } from './constants.js'
import { getRuntimePackageName } from './packageName.js'
import {
copyFileByAndroid,
fileExistsByAndroid,
isInternalSandboxAbsPath,
resolvePlusAbsolutePath
} from './androidFileCopy.js'
import { logStep, logStepFail } from './log.js'
const STAGE = '归并·文件'
function toFileUrl(path) {
if (!path) return path
const p = String(path).trim()
if (p.startsWith('file://')) return p
if (p.startsWith('_')) return p
if (p.startsWith('/')) return `file://${p}`
return `file:///${p}`
}
export async function fileExists(path) {
if (!path || typeof plus === 'undefined') return false
const p = String(path)
.trim()
.replace(/^file:\/\//, '')
if (isInternalSandboxAbsPath(p) && fileExistsByAndroid(p)) {
return true
}
return new Promise(resolve => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
() => resolve(true),
() => resolve(false)
)
})
}
function copyEntryToDocDir(srcEntry, docRelativeDir, destFileName) {
const docDir = docRelativeDir.endsWith('/') ? docRelativeDir : `${docRelativeDir}/`
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
docDir.startsWith('_doc') ? docDir : `_doc/${docDir}`,
dirEntry => {
srcEntry.copyTo(
dirEntry,
destFileName,
entry => resolve(entry.fullPath),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
function copyFileToDocByPlusIo(sourceAbsolutePath, destFileName) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(sourceAbsolutePath),
srcEntry => {
copyEntryToDocDir(srcEntry, '_doc/', destFileName).then(resolve).catch(reject)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
export async function copyFileToDoc(sourceAbsolutePath, destFileName) {
const pkg = getRuntimePackageName()
if (isRestrictedInternalPath(sourceAbsolutePath, pkg)) {
const err = new Error('无法访问非本应用的内部路径,仅合并当前应用沙箱内的库文件')
logStepFail(STAGE, '拒绝复制:非本应用内部路径', { 来源: sourceAbsolutePath })
return Promise.reject(err)
}
const src = String(sourceAbsolutePath).trim()
const destRel = destFileName.startsWith('_doc/') ? destFileName : `_doc/${destFileName}`
const destAbs = resolvePlusAbsolutePath(destRel)
logStep(STAGE, '开始复制到 _doc', { 来源: src, 目标相对: destRel, 目标绝对: destAbs })
if (isInternalSandboxAbsPath(src)) {
logStep(STAGE, '内部沙箱路径,使用 Java File API', { 来源: src })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, 'File API 复制成功', { 目标: out })
return out
} catch (e) {
logStepFail(STAGE, 'File API 复制失败', { 来源: src, 错误: e?.message || String(e) })
throw e
}
}
logStep(STAGE, '外置/可访问路径,尝试 plus.io 复制')
try {
const out = await copyFileToDocByPlusIo(src, destFileName)
logStep(STAGE, 'plus.io 复制成功', { 结果: out })
return out
} catch (e) {
const msg = e?.message || String(e)
if (isInternalSandboxAbsPath(src) || /36199|不支持当前路径|targetSdk/i.test(msg)) {
logStep(STAGE, 'plus.io 失败,降级 File API', { 原因: msg })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '降级 File API 复制成功', { 目标: out })
return out
} catch (e2) {
logStepFail(STAGE, '降级 File API 仍失败', { 错误: e2?.message || String(e2) })
throw e2
}
}
logStepFail(STAGE, 'plus.io 复制失败', { 来源: src, 错误: msg })
throw e
}
}
/** 复制到 _doc/uniapp_save/(目录不存在时由 plus 创建父级需先 ensure) */
async function copyIntoDocSaveDirByPlusIo(sourceAbsolutePath, destFileName) {
return new Promise((resolve, reject) => {
const ensureThenCopy = () => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(sourceAbsolutePath),
srcEntry => {
plus.io.resolveLocalFileSystemURL(
`_doc/${UNIAPP_SAVE_DIR}/`,
dirEntry => {
srcEntry.copyTo(
dirEntry,
destFileName,
entry => resolve(entry.fullPath),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
() => {
plus.io.resolveLocalFileSystemURL(
'_doc/',
docEntry => {
docEntry.getDirectory(
UNIAPP_SAVE_DIR,
{ create: true },
saveDir => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(sourceAbsolutePath),
src2 =>
src2
.copyTo(
saveDir,
destFileName,
entry => resolve(entry.fullPath),
e => reject(new Error(e?.message || JSON.stringify(e)))
),
e => reject(new Error(e?.message || JSON.stringify(e)))
)
},
e => reject(new Error(e?.message || JSON.stringify(e)))
)
},
e => reject(new Error(e?.message || JSON.stringify(e)))
)
}
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
}
ensureThenCopy()
})
}
export async function copyFileIntoDocSaveDir(sourceAbsolutePath, destFileName) {
const pkg = getRuntimePackageName()
if (isRestrictedInternalPath(sourceAbsolutePath, pkg)) {
logStepFail(STAGE, '拒绝复制录音:非本应用内部路径', { 来源: sourceAbsolutePath })
return Promise.reject(new Error('无法从非本应用内部路径复制录音文件'))
}
const src = String(sourceAbsolutePath).trim()
const destAbs = resolvePlusAbsolutePath(`_doc/${UNIAPP_SAVE_DIR}/${destFileName}`)
logStep(STAGE, '开始复制录音到 uniapp_save', {
来源: src,
文件名: destFileName,
目标: destAbs
})
if (isInternalSandboxAbsPath(src)) {
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '录音 File API 复制成功', { 目标: out })
return out
} catch (e) {
logStepFail(STAGE, '录音 File API 复制失败', { 错误: e?.message || String(e) })
throw e
}
}
try {
const out = await copyIntoDocSaveDirByPlusIo(src, destFileName)
logStep(STAGE, '录音 plus.io 复制成功', { 结果: out })
return out
} catch (e) {
const msg = e?.message || String(e)
if (/36199|不支持当前路径|targetSdk/i.test(msg)) {
logStep(STAGE, '录音 plus.io 失败,降级 File API', { 原因: msg })
try {
const out = await copyFileByAndroid(src, destAbs)
logStep(STAGE, '录音降级复制成功', { 目标: out })
return out
} catch (e2) {
logStepFail(STAGE, '录音降级复制失败', { 错误: e2?.message || String(e2) })
throw e2
}
}
logStepFail(STAGE, '录音 plus.io 复制失败', { 错误: msg })
throw e
}
}
export function removeFile(path) {
logStep(STAGE, '尝试删除文件', { 路径: path })
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
entry => {
entry.remove(
() => {
logStep(STAGE, '文件删除成功', { 路径: path })
resolve(true)
},
err => {
const msg = err?.message || JSON.stringify(err)
logStepFail(STAGE, '文件删除失败', { 路径: path, 错误: msg })
reject(new Error(msg))
}
)
},
() => {
logStep(STAGE, '删除跳过:路径无法解析', { 路径: path })
resolve(false)
}
)
})
}
export function removeDocRelative(relativePath) {
const path = relativePath.startsWith('_doc/') ? relativePath : `_doc/${relativePath}`
return removeFile(path).catch(() => false)
}
import StoragePathMerge from './StoragePathMerge.js'
export default StoragePathMerge
export { StoragePathMerge }
import FloatLogBus from '@/utils/logger/FloatLogBus.js'
import LogCat from '@/utils/logger/LogCat.js'
import { LogLevel } from '@/utils/logger/constants.js'
export const MERGE_LOG_TAG = 'StoragePathMerge'
const MERGE_LOG_STORAGE_KEY = 'zyzs_storage_merge_log_history'
/** 与业务 LocalLog 同目录,避免再建一套 logger 封装导致悬浮窗/落盘不同步 */
let mergeLogCat = null
function getMergeLogCat() {
if (!mergeLogCat) {
mergeLogCat = new LogCat('_zyzs_log')
}
return mergeLogCat
}
function formatLine(msg, extra) {
return extra !== undefined ? `${msg} ${JSON.stringify(extra)}` : msg
}
function formatFull(level, msg, extra) {
return `[${MERGE_LOG_TAG}] ${formatLine(msg, extra)}`
}
function persistMergeLog(full) {
try {
let raw = uni.getStorageSync(MERGE_LOG_STORAGE_KEY)
let arr = []
if (raw) {
arr = typeof raw === 'string' ? JSON.parse(raw) : raw
}
if (!Array.isArray(arr)) arr = []
const d = new Date()
const pad = n => (n < 10 ? '0' + n : String(n))
const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
arr.push({ time, level: 'info', text: full, id: `persist_${Date.now()}` })
if (arr.length > 80) arr = arr.slice(-80)
uni.setStorageSync(MERGE_LOG_STORAGE_KEY, JSON.stringify(arr))
} catch (_) {
/* ignore */
}
}
/**
* 路径合并专用日志(与业务日志系统对齐):
* - FloatLogBus:悬浮窗 / getMergeLines(始终 push,带 [StoragePathMerge])
* - LogCat:与 uni.$logger.local 相同 _zyzs_log 落盘
* 不经过 storageMerge 单独通道,避免 install 前后悬浮窗漏日志
*/
function emit(level, msg, extra) {
const full = formatFull(level, msg, extra)
const busLevel = level === 'error' ? 'error' : 'info'
const catLevel = level === 'error' ? LogLevel.ERROR : LogLevel.INFO
try {
FloatLogBus.push(busLevel, full)
} catch (_) {
/* ignore */
}
try {
getMergeLogCat().writeLog(catLevel, full)
} catch (_) {
/* ignore */
}
const oc = FloatLogBus.getOriginalConsole?.()
if (level === 'error') {
;(oc?.error || console.error)(full)
} else {
;(oc?.log || console.log)(full)
}
persistMergeLog(full)
}
export function logInfo(msg, extra) {
emit('info', msg, extra)
}
export function logError(msg, extra) {
emit('error', msg, extra)
}
/** 归并流程分阶段步骤(info) */
export function logStep(stage, msg, extra) {
emit('info', `[${stage}] ${msg}`, extra)
}
/** 归并流程分阶段失败(error) */
export function logStepFail(stage, msg, extra) {
emit('error', `[${stage}] ${msg}`, extra)
}
export function loadPersistedMergeLogs() {
try {
const raw = uni.getStorageSync(MERGE_LOG_STORAGE_KEY)
if (!raw) return []
const arr = typeof raw === 'string' ? JSON.parse(raw) : raw
return Array.isArray(arr) ? arr : []
} catch (_) {
return []
}
}
export function waitForPlus(timeoutMs = 5000) {
return new Promise(resolve => {
if (typeof plus !== 'undefined') {
resolve(plus)
return
}
let settled = false
const done = p => {
if (settled) return
settled = true
resolve(p || null)
}
if (typeof document !== 'undefined') {
document.addEventListener('plusready', () => done(typeof plus !== 'undefined' ? plus : null), {
once: true
})
}
setTimeout(() => done(typeof plus !== 'undefined' ? plus : null), timeoutMs)
})
}
import { MERGE_STATE_KEY } from './constants.js'
import { normalizePath } from './pathCache.js'
function emptyState() {
return { anchoredRoot: '', handledAlternates: [] }
}
export function loadMergeState() {
try {
const raw = uni.getStorageSync(MERGE_STATE_KEY)
if (!raw) return emptyState()
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (!parsed || typeof parsed !== 'object') return emptyState()
return {
anchoredRoot: normalizePath(parsed.anchoredRoot || ''),
handledAlternates: (parsed.handledAlternates || [])
.map(normalizePath)
.filter(Boolean)
}
} catch (_) {
return emptyState()
}
}
function saveMergeState(state) {
uni.setStorageSync(MERGE_STATE_KEY, JSON.stringify(state))
}
/** 强制归并时清空「已处理 alternate」,便于重新扫描 */
export function resetAlternateHandledForForce(currentRoot) {
const root = normalizePath(currentRoot)
saveMergeState({ anchoredRoot: root, handledAlternates: [] })
}
/**
* 包根切换 → 清空已处理列表;未切换且全部 alternate 已处理 → 可跳过扫描
* @param {string} currentRoot 当前运行包根
* @param {{ path: string }[]} nonCurrentItems getNonCurrentPaths 结果
* @param {boolean} force 手动强制归并
*/
export function planAlternateScan(currentRoot, nonCurrentItems, force) {
const root = normalizePath(currentRoot)
const all = (nonCurrentItems || []).map(item => normalizePath(item.path)).filter(Boolean)
if (force) {
return {
skip: false,
paths: all,
reason: '手动强制归并,重新扫描全部 alternate 包根'
}
}
if (!root || all.length === 0) {
return { skip: true, paths: [], reason: '无 alternate 包根需扫描' }
}
let state = loadMergeState()
const anchored = normalizePath(state.anchoredRoot)
if (anchored !== root) {
state = { anchoredRoot: root, handledAlternates: [] }
saveMergeState(state)
return {
skip: false,
paths: all,
reason: '包根已切换,重新扫描 alternate',
previousRoot: anchored || '(无)'
}
}
const handledSet = new Set(state.handledAlternates)
const pending = all.filter(p => !handledSet.has(p))
if (pending.length === 0) {
return {
skip: true,
paths: [],
reason: '当前包根未切换,本应用 alternate 包根均已处理过',
anchoredRoot: root,
handledAlternates: [...handledSet]
}
}
return {
skip: false,
paths: pending,
reason: '存在尚未处理的 alternate 包根',
pending,
handledAlternates: [...handledSet]
}
}
/** 探测/合并结束且无硬错误时,标记该 alternate 包根已处理(仅针对当前 anchoredRoot) */
export function markAlternateRootHandled(currentRoot, alternateRoot) {
const root = normalizePath(currentRoot)
const alt = normalizePath(alternateRoot)
if (!root || !alt || root === alt) return
let state = loadMergeState()
if (normalizePath(state.anchoredRoot) !== root) {
state = { anchoredRoot: root, handledAlternates: [] }
}
const set = new Set(state.handledAlternates)
set.add(alt)
state.handledAlternates = [...set]
saveMergeState(state)
}
import { RELEASE_PACKAGE_NAME } from './constants.js'
import { getSameAppPackageRoots } from './pathAccess.js'
/**
* 当前安装包名(自定义基座多为 io.dcloud.HBuilder,正式包为 uni.gltap)
*/
export function getRuntimePackageName() {
try {
if (typeof plus !== 'undefined') {
const osName = plus.os?.name
if (osName === 'Android' || osName === 'android') {
const main = plus.android.runtimeMainActivity()
const pkg = main?.getPackageName?.()
if (pkg) return String(pkg)
}
}
} catch (_) {
/* ignore */
}
return RELEASE_PACKAGE_NAME
}
/** 仅当前运行包(不扫描其它应用 / 正式包遗留目录) */
export function getPackageNamesForMerge() {
const runtime = getRuntimePackageName()
return runtime ? [runtime] : []
}
/**
* 当前应用可能出现的包根(外置 emulated + /data/user/N + /data/data)
* @param {string} [hintRoot] 当前包根,用于解析 /data/user/N
*/
export function getDefaultPackageRoots(hintRoot) {
const pkg = getRuntimePackageName()
if (!pkg) return []
return getSameAppPackageRoots(pkg, hintRoot)
}
/**
* 同一安装包在 Android 上可能出现的多套私有根路径(外置 /data/user /data/data)。
* 仅处理当前运行包名,不扫描其它应用。
*/
function normalizeAccessPath(path) {
if (!path) return ''
return String(path)
.replace(/^file:\/\//, '')
.trim()
.replace(/\/+$/, '')
}
function escapeRegExp(str) {
return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/** 从包根或 doc 路径解析 Android 多用户 id,默认 0 */
export function parseAndroidUserIdFromPath(path) {
const p = normalizeAccessPath(path)
const m = p.match(/^\/data\/user\/(\d+)\//)
return m ? m[1] : '0'
}
/**
* 当前应用(单包名)在设备上可能出现的包根目录
* @param {string} packageName 当前运行包名
* @param {string} [hintRoot] 当前 doc 反推的包根,用于带上实际 /data/user/N
*/
export function getSameAppPackageRoots(packageName, hintRoot) {
if (!packageName) return []
const seen = new Set()
const roots = []
const add = path => {
const n = normalizeAccessPath(path)
if (!n || seen.has(n)) return
seen.add(n)
roots.push(n)
}
add(`/storage/emulated/0/Android/data/${packageName}`)
add(`/data/data/${packageName}`)
const userIds = new Set(['0'])
if (hintRoot) userIds.add(parseAndroidUserIdFromPath(hintRoot))
for (const uid of userIds) {
add(`/data/user/${uid}/${packageName}`)
}
return roots
}
/**
* 是否属于当前应用(单包名)的存储根(外置或内部)
*/
export function isOwnAppStoragePath(path, packageName) {
const p = normalizeAccessPath(path)
if (!p || !packageName) return false
return getSameAppPackageRoots(packageName).some(
root => p === root || p.startsWith(`${root}/`)
)
}
/** @deprecated 使用 isOwnAppStoragePath */
export function isOwnAppDataPath(path, packageNames) {
const pkg = Array.isArray(packageNames) ? packageNames[0] : packageNames
return isOwnAppStoragePath(path, pkg)
}
/**
* 是否应跳过:内部路径且不属于当前应用
*/
export function isRestrictedInternalPath(path, packageName) {
const p = normalizeAccessPath(path)
if (!p.startsWith('/data/data/') && !p.startsWith('/data/user/')) return false
if (packageName && isOwnAppStoragePath(path, packageName)) return false
return true
}
export function isExternalAppDataRoot(path) {
if (!path) return false
return normalizeAccessPath(path).includes('/Android/data/')
}
/** @deprecated 使用 getSameAppPackageRoots */
export function getInternalPackageRoots(packageNames) {
const pkg = Array.isArray(packageNames) ? packageNames[0] : packageNames
return getSameAppPackageRoots(pkg).filter(
r => r.startsWith('/data/data/') || r.startsWith('/data/user/')
)
}
/** @deprecated 使用 getSameAppPackageRoots */
export function getMergeAccessiblePackageRoots(getPackageNamesForMerge) {
const names = typeof getPackageNamesForMerge === 'function' ? getPackageNamesForMerge() : []
const pkg = names[0]
if (!pkg) return []
return getSameAppPackageRoots(pkg).filter(r => r.includes('/Android/data/'))
}
import { PATH_CACHE_KEY } from './constants.js'
import { getDefaultPackageRoots, getRuntimePackageName } from './packageName.js'
import { isRestrictedInternalPath } from './pathAccess.js'
export function normalizePath(path) {
if (!path) return ''
let p = String(path).trim()
if (p.startsWith('file://')) {
p = p.replace(/^file:\/\//, '')
}
return p.replace(/\/+$/, '')
}
export function loadPathCache() {
try {
const raw = uni.getStorageSync(PATH_CACHE_KEY)
if (!raw) return null
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (!Array.isArray(parsed)) return null
const pkg = getRuntimePackageName()
return parsed
.filter(item => item && item.path && !isRestrictedInternalPath(item.path, pkg))
.map(item => ({
path: normalizePath(item.path),
isCurrent: !!item.isCurrent
}))
} catch (e) {
return null
}
}
export function savePathCache(cache) {
uni.setStorageSync(PATH_CACHE_KEY, JSON.stringify(cache))
}
export function createDefaultCache(currentRoot) {
const roots = getDefaultPackageRoots(currentRoot)
const normalizedCurrent = normalizePath(currentRoot)
const seen = new Set()
const cache = []
for (const path of roots) {
const normalized = normalizePath(path)
if (!normalized || seen.has(normalized)) continue
seen.add(normalized)
cache.push({
path: normalized,
isCurrent: normalized === normalizedCurrent
})
}
if (normalizedCurrent && !seen.has(normalizedCurrent)) {
cache.push({ path: normalizedCurrent, isCurrent: true })
cache.forEach(item => {
if (item.path !== normalizedCurrent) item.isCurrent = false
})
}
if (!cache.some(item => item.isCurrent) && cache.length > 0) {
const match = cache.find(item => item.path === normalizedCurrent)
if (match) {
match.isCurrent = true
} else if (normalizedCurrent) {
cache.push({ path: normalizedCurrent, isCurrent: true })
cache.forEach(item => {
if (item.path !== normalizedCurrent) item.isCurrent = false
})
} else {
cache[0].isCurrent = true
}
}
return cache
}
/**
* 同步 CurrentPath 与 PathCache 的 isCurrent 标记
*/
export function syncCurrentFlag(cache, currentRoot) {
const normalizedCurrent = normalizePath(currentRoot)
if (!normalizedCurrent) return cache
let list = Array.isArray(cache) ? [...cache] : []
const existing = list.find(item => normalizePath(item.path) === normalizedCurrent)
if (existing) {
list = list.map(item => ({
...item,
path: normalizePath(item.path),
isCurrent: normalizePath(item.path) === normalizedCurrent
}))
} else {
list = list.map(item => ({
...item,
path: normalizePath(item.path),
isCurrent: false
}))
list.push({ path: normalizedCurrent, isCurrent: true })
}
return list
}
export function getNonCurrentPaths(cache) {
const pkg = getRuntimePackageName()
return (cache || []).filter(
item => !item.isCurrent && item.path && !isRestrictedInternalPath(item.path, pkg)
)
}
/**
* 将默认包根补进已有缓存(切换自定义基座 / 正式包后仍能扫到遗留路径)
*/
export function ensureDefaultRootsInCache(cache, currentRoot) {
const normalizedCurrent = normalizePath(currentRoot)
let list = Array.isArray(cache) ? cache.map(item => ({ ...item })) : []
const pathSet = new Set(list.map(item => normalizePath(item.path)))
for (const path of getDefaultPackageRoots(currentRoot)) {
const normalized = normalizePath(path)
if (!normalized || pathSet.has(normalized)) continue
pathSet.add(normalized)
list.push({
path: normalized,
isCurrent: normalized === normalizedCurrent
})
}
return syncCurrentFlag(list, currentRoot)
}
import { PathUtils } from '@/utils/recordManager/index.js'
import { DB_FILE } from './constants.js'
import { normalizePath } from './pathCache.js'
import { fileExists } from './fileIo.js'
import { getDefaultPackageRoots } from './packageName.js'
import { logStep } from './log.js'
const STAGE = '归并·路径'
export { getDefaultPackageRoots, getRuntimePackageName, getPackageNamesForMerge } from './packageName.js'
export function getAppId() {
if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.appid) {
return plus.runtime.appid
}
return '__UNI__D3BD3DF'
}
/**
* 从 doc 目录 fullPath 推导包根目录
*/
export function derivePackageRootFromDocPath(docPath) {
const normalized = normalizePath(docPath)
if (!normalized) return ''
const appId = getAppId()
const docSuffix = `/apps/${appId}/doc`
if (normalized.endsWith(docSuffix)) {
return normalized.substring(0, normalized.length - docSuffix.length)
}
const appsMarker = '/apps/'
const appsIdx = normalized.indexOf(appsMarker)
if (appsIdx > 0) {
return normalized.substring(0, appsIdx)
}
if (normalized.endsWith('/doc')) {
return normalized.substring(0, normalized.length - 4)
}
return normalized
}
export async function getCurrentPackageRoot() {
const docPath = await PathUtils.getFilePath()
const root = derivePackageRootFromDocPath(docPath)
logStep(STAGE, '由 doc 路径推导包根', { doc: normalizePath(docPath), 包根: root })
return root
}
/**
* 包根下 zyzs.db 的候选绝对路径(无 file:// 前缀)
*/
export function resolveDbFilePaths(packageRoot) {
const root = normalizePath(packageRoot)
const appId = getAppId()
return [
`${root}/${DB_FILE}`,
`${root}/apps/${appId}/doc/${DB_FILE}`
]
}
export async function findDbInPackageRoot(packageRoot) {
const candidates = resolveDbFilePaths(packageRoot)
logStep(STAGE, '开始探测数据库候选路径', { 包根: packageRoot, 候选数: candidates.length })
for (let i = 0; i < candidates.length; i++) {
const path = candidates[i]
const exists = await fileExists(path)
logStep(STAGE, `候选 (${i + 1}/${candidates.length})`, { 路径: path, 存在: exists })
if (exists) {
logStep(STAGE, '命中数据库文件', { 路径: path, 包根: packageRoot })
return path
}
}
logStep(STAGE, '未命中任何候选库', { 包根: packageRoot })
return null
}
import { TABLE_NAME, UNIAPP_SAVE_DIR } from './constants.js'
import { normalizePath } from './pathCache.js'
import { fileExists, copyFileIntoDocSaveDir } from './fileIo.js'
import { logStep, logStepFail } from './log.js'
const STAGE = '归并·媒体'
/** 与 UploadService.checkFileExists 一致:按表内路径用 uni.getFileInfo 判断可读 */
export function checkMediaFileExists(filePath) {
return new Promise(resolve => {
if (!filePath || !String(filePath).toLowerCase().endsWith('.mp3')) {
resolve(false)
return
}
uni.getFileInfo({
filePath,
success: () => resolve(true),
fail: () => resolve(false)
})
})
}
export function extractFileNameFromMediaPath(filePath) {
if (!filePath) return ''
const p = String(filePath).replace(/\\/g, '/')
const parts = p.split('/')
return parts[parts.length - 1] || ''
}
export function buildMediaFilePathForCurrentDoc(currentDocPath, fileName) {
const root = normalizePath(currentDocPath)
if (!root || !fileName) return ''
const base = root.endsWith('/') ? root : `${root}/`
return `file://${base}${UNIAPP_SAVE_DIR}/${fileName}`
}
function parseRecordUrlList(raw) {
if (!raw) return []
try {
const list = typeof raw === 'string' ? JSON.parse(raw) : raw
return Array.isArray(list) ? list : []
} catch (_) {
return []
}
}
/**
* 合并完成后:按表内路径校验;仅当 uni.getFileInfo 失败时从 alternate 目录拷文件并改路径
*/
export async function verifyAndRepairRecordMediaPaths(currentDocPath, alternateSaveDirs) {
const dbRecord = uni.$dbRecord
if (!dbRecord) {
logStepFail(STAGE, '跳过:uni.$dbRecord 未就绪')
return { okCount: 0, missingCount: 0, repairedCount: 0 }
}
const altDirs = (alternateSaveDirs || []).map(d => normalizePath(d)).filter(Boolean)
const curDoc = normalizePath(currentDocPath)
logStep(STAGE, '读取主库 records 用于媒体校验', {
doc根: curDoc,
备用录音目录数: altDirs.length,
备用目录: altDirs
})
try {
const rows = await dbRecord.db.selectSql(`SELECT id, recordUrlList, tempFilePath FROM ${TABLE_NAME}`)
const rowCount = rows?.length || 0
logStep(STAGE, '主库 records 读取完成', { 记录数: rowCount })
if (rowCount === 0) {
logStep(STAGE, '无记录需校验媒体,结束')
return { okCount: 0, missingCount: 0, repairedCount: 0 }
}
let okCount = 0
let missingCount = 0
let repairedCount = 0
let idx = 0
for (const row of rows || []) {
idx++
if (!row?.id) {
logStepFail(STAGE, `记录 (${idx}/${rowCount}) 无 id,跳过`)
continue
}
const list = parseRecordUrlList(row.recordUrlList)
let listChanged = false
let tempFilePath = row.tempFilePath
let recordOk = 0
let recordMissing = 0
let recordRepaired = 0
logStep(STAGE, `校验记录 (${idx}/${rowCount})`, {
recordId: row.id,
片段数: list.length,
有tempFilePath: !!tempFilePath
})
for (const item of list) {
if (!item?.file) continue
const path = item.file
const exists = await checkMediaFileExists(path)
if (exists) {
okCount++
recordOk++
continue
}
missingCount++
recordMissing++
const fileName = extractFileNameFromMediaPath(path)
if (!fileName) {
logStepFail(STAGE, `不可读且无法解析文件名 recordId=${row.id}`, { 路径: path })
continue
}
logStep(STAGE, `片段不可读,尝试从备用目录修复 recordId=${row.id}`, {
表内路径: path,
文件名: fileName
})
let repaired = false
for (const altDir of altDirs) {
const candidate = `${altDir}/${fileName}`
const altExists = await fileExists(candidate)
logStep(STAGE, `检查备用副本 recordId=${row.id}`, {
候选: candidate,
存在: altExists
})
if (!altExists) continue
try {
await copyFileIntoDocSaveDir(candidate, fileName)
item.file = buildMediaFilePathForCurrentDoc(curDoc, fileName)
listChanged = true
repaired = true
repairedCount++
recordRepaired++
logStep(STAGE, `片段修复成功 recordId=${row.id}`, {
来源: candidate,
新路径: item.file
})
break
} catch (e) {
logStepFail(STAGE, `片段从备用目录复制失败 recordId=${row.id}`, {
候选: candidate,
错误: e?.message || String(e)
})
}
}
if (!repaired) {
logStepFail(STAGE, `片段不可读且未找到可用备用副本 recordId=${row.id}`, {
表内路径: path,
文件名: fileName
})
}
}
if (tempFilePath) {
const tempOk = await checkMediaFileExists(tempFilePath)
if (tempOk) {
okCount++
recordOk++
} else {
missingCount++
recordMissing++
const fileName = extractFileNameFromMediaPath(tempFilePath)
logStep(STAGE, `tempFilePath 不可读 recordId=${row.id}`, {
路径: tempFilePath,
文件名: fileName
})
let tempRepaired = false
for (const altDir of altDirs) {
const candidate = `${altDir}/${fileName}`
if (!(await fileExists(candidate))) continue
try {
await copyFileIntoDocSaveDir(candidate, fileName)
tempFilePath = buildMediaFilePathForCurrentDoc(curDoc, fileName)
listChanged = true
repairedCount++
recordRepaired++
tempRepaired = true
logStep(STAGE, `tempFilePath 修复成功 recordId=${row.id}`, { 新路径: tempFilePath })
break
} catch (e) {
logStepFail(STAGE, `tempFilePath 复制失败 recordId=${row.id}`, {
候选: candidate,
错误: e?.message || String(e)
})
}
}
if (!tempRepaired && fileName) {
logStepFail(STAGE, `tempFilePath 未修复 recordId=${row.id}`, { 原路径: row.tempFilePath })
}
}
}
if (listChanged) {
logStep(STAGE, `回写主库路径 recordId=${row.id}`)
try {
await dbRecord.updateRecord(
{
recordUrlList: JSON.stringify(list),
tempFilePath
},
{ id: row.id }
)
logStep(STAGE, `主库路径已更新 recordId=${row.id}`)
} catch (e) {
logStepFail(STAGE, `主库路径更新失败 recordId=${row.id}`, {
错误: e?.message || String(e)
})
}
}
logStep(STAGE, `记录 (${idx}/${rowCount}) 校验小结`, {
recordId: row.id,
可读片段: recordOk,
不可读: recordMissing,
已修复: recordRepaired,
是否更新表: listChanged
})
}
logStep(STAGE, '媒体校验汇总', {
记录数: rowCount,
可读片段累计: okCount,
不可读累计: missingCount,
已修复累计: repairedCount
})
return { okCount, missingCount, repairedCount }
} catch (e) {
logStepFail(STAGE, '媒体校验 SQL 或流程失败', { 错误: e?.message || String(e) })
return { okCount: 0, missingCount: 0, repairedCount: 0 }
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!