StoragePathMerge.js
11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { TEMP_DB_FILE, DB_FILE, ENABLE_LEGACY_FLAT_DB_MERGE } from './constants.js'
import { normalizePath } from './pathCache.js'
import {
loadPathCache,
savePathCache,
createDefaultCache,
ensureDefaultRootsInCache,
getNonCurrentPaths
} from './pathCache.js'
import {
getCurrentPackageRoot,
findDbInPackageRoot,
getRuntimePackageName,
getAppId
} from './pathResolver.js'
import { PathUtils } from '@/utils/recordManager/index.js'
import { copyFileToDoc, removeFile, removeDocRelative, fileExists } from './fileIo.js'
import {
openTempDb,
closeTempDb,
selectTempRecords,
mergeRecordsToMain
} from './dbMerge.js'
import { isRestrictedInternalPath, isOwnAppStoragePath } from './pathAccess.js'
import { resolveUniappSaveDir, resolveRecordDir } from './docMediaMerge.js'
import { verifyAndRepairRecordMediaPaths } from './recordMediaVerify.js'
import {
planAlternateScan,
markAlternateRootHandled,
resetAlternateHandledForForce
} from './mergeState.js'
import { logStep, logStepFail, waitForPlus } from './log.js'
const STAGE = {
RUN: '归并·总流程',
DB: '归并·数据库',
PATH: '归并·路径',
MEDIA: '归并·媒体'
}
function previewList(arr, limit = 4) {
if (!Array.isArray(arr)) return { count: 0, preview: [] }
if (arr.length <= limit) return { count: arr.length, preview: arr.slice() }
return { count: arr.length, preview: arr.slice(0, limit), more: arr.length - limit }
}
function isAndroidApp(plusRef) {
const osName = plusRef?.os?.name
return !!plusRef && (osName === 'Android' || osName === 'android')
}
async function safeRemoveDocRelative(relativePath, label) {
const ok = await removeDocRelative(relativePath)
// 仅在真正删除成功时记录,避免刷屏(不存在属于常态)
if (ok) logStep(STAGE.DB, `临时文件已删除:${relativePath}`, label ? { 说明: label } : undefined)
return ok
}
/** @returns {'restricted'|'copy_failed'|'empty'|'merged'|'merge_failed'|'error'} */
async function mergeFromDbFile(dbPath, label, mergePkg) {
const tag = label || dbPath
if (!dbPath) {
logStepFail(STAGE.DB, '跳过:数据库路径为空', { 标签: tag })
return 'error'
}
if (isRestrictedInternalPath(dbPath, mergePkg)) {
logStepFail(STAGE.DB, '跳过:非本应用内部路径', { 路径: dbPath, 标签: tag })
return 'restricted'
}
const hint = isOwnAppStoragePath(dbPath, mergePkg) ? '本应用' : '其它'
logStep(STAGE.DB, '处理来源库', { 来源: dbPath, 标签: tag, 归属: hint })
await safeRemoveDocRelative(TEMP_DB_FILE, '合并前清理旧临时库')
try {
await copyFileToDoc(dbPath, TEMP_DB_FILE)
} catch (e) {
logStepFail(STAGE.DB, '复制来源库到临时库失败', {
来源: dbPath,
错误: e?.message || String(e)
})
return 'copy_failed'
}
try {
await openTempDb()
const rows = await selectTempRecords()
const count = rows?.length || 0
logStep(STAGE.DB, '临时库 records 读取完成', { 条数: count, 来源: dbPath })
if (!rows || count === 0) {
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '无数据清理临时库')
return 'empty'
}
const ok = await mergeRecordsToMain(rows, { 来源: dbPath })
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '合并后清理临时库')
if (ok) {
logStep(STAGE.DB, '记录已写入主库', { 来源: dbPath, 条数: count })
try {
const removed = await removeFile(dbPath)
if (removed) {
logStep(STAGE.DB, '来源库已删除', { 路径: dbPath })
} else {
logStepFail(STAGE.DB, '来源库删除失败:文件未找到或无法解析', { 路径: dbPath })
}
} catch (e) {
logStepFail(STAGE.DB, '来源库删除异常', {
路径: dbPath,
错误: e?.message || String(e)
})
}
return 'merged'
}
logStepFail(STAGE.DB, '写入主库未完全成功,保留来源库', { 来源: dbPath, 条数: count, 标签: tag })
return 'merge_failed'
} catch (e) {
logStepFail(STAGE.DB, '处理来源库异常', {
来源: dbPath,
标签: tag,
错误: e?.message || String(e)
})
try {
await closeTempDb()
} catch (closeErr) {
logStepFail(STAGE.DB, '异常后关闭临时库失败', { 错误: closeErr?.message || closeErr })
}
try {
await safeRemoveDocRelative(TEMP_DB_FILE, '异常后清理临时库')
} catch (_) {
/* ignore */
}
return 'error'
}
}
async function processPath(packageRoot, mergePkg, currentRoot, index, total) {
logStep(STAGE.PATH, `扫描包根 (${index}/${total})`, { 包根: packageRoot })
if (isRestrictedInternalPath(packageRoot, mergePkg)) {
logStepFail(STAGE.PATH, '跳过:非本应用内部包根', { 包根: packageRoot })
return 'restricted'
}
if (isOwnAppStoragePath(packageRoot, mergePkg)) {
logStep(STAGE.PATH, '本应用 alternate 包根,开始探测数据库', { 包根: packageRoot })
}
const dbPath = await findDbInPackageRoot(packageRoot)
let outcome = 'no_db'
if (dbPath) {
if (!isRestrictedInternalPath(dbPath, mergePkg)) {
logStep(STAGE.PATH, '发现来源库', { 包根: packageRoot, 库: dbPath })
outcome = await mergeFromDbFile(dbPath, packageRoot, mergePkg)
} else {
logStepFail(STAGE.PATH, '发现库但路径受限,跳过合并', { 库路径: dbPath })
outcome = 'restricted'
}
}
const canMarkHandled = ['no_db', 'empty', 'merged', 'restricted'].includes(outcome)
if (canMarkHandled) {
markAlternateRootHandled(currentRoot, packageRoot)
}
logStep(STAGE.PATH, `包根扫描结束 (${index}/${total})`, { 包根: packageRoot, 结果: outcome })
return outcome
}
/** 主库在 apps/xxx/doc 时,包根下扁平 zyzs.db 视为遗留库 */
async function processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg) {
if (!currentRoot || isRestrictedInternalPath(currentRoot, mergePkg)) {
logStep(STAGE.PATH, '跳过遗留扁平库检查', {
原因: !currentRoot ? '无当前包根' : '内部路径受限',
包根: currentRoot
})
return
}
const root = normalizePath(currentRoot)
const flatDb = `${root}/${DB_FILE}`
const mainDocDb = normalizePath(`${root}/apps/${getAppId()}/doc/${DB_FILE}`)
if (!(await fileExists(flatDb))) {
return
}
if (normalizePath(flatDb) === mainDocDb) {
return
}
logStep(STAGE.PATH, '发现遗留扁平库,进入合并流程', { 路径: flatDb })
await mergeFromDbFile(flatDb, `${currentRoot}#legacy-flat`, mergePkg)
}
class StoragePathMerge {
/** 进行中的归并 Promise,并发调用时复用 */
static _running = null
/** 当前进程内是否已成功跑完一次归并(force 可打破) */
static _completed = false
/**
* @param {{ force?: boolean }} [options] force=true:忽略「已完成」限制(悬浮窗手动归并)
*/
static async run(options = {}) {
const force = !!options.force
if (StoragePathMerge._running) {
logStep(STAGE.RUN, '防重入:归并正在进行,等待当前任务结束', { force })
return StoragePathMerge._running
}
if (StoragePathMerge._completed && !force) {
logStep(STAGE.RUN, '防重入:本会话已完成归并,跳过重复调用')
return
}
if (force) {
logStep(STAGE.RUN, '强制重新归并(手动触发)')
}
const task = StoragePathMerge.executeRun({ force })
StoragePathMerge._running = task
try {
await task
StoragePathMerge._completed = true
} finally {
StoragePathMerge._running = null
}
}
static async executeRun({ force = false } = {}) {
logStep(STAGE.RUN, '======== 路径合并开始 ========', { force })
const plusRef = await waitForPlus()
if (!isAndroidApp(plusRef)) {
logStep(STAGE.RUN, '结束:非 Android APP-PLUS,跳过归并', {
有Plus: !!plusRef,
系统: plusRef?.os?.name
})
return
}
logStep(STAGE.RUN, '运行环境确认:Android APP-PLUS', { 系统: plusRef?.os?.name })
try {
await uni.$dbRecord.init()
const currentRoot = await getCurrentPackageRoot()
const currentDocPath = normalizePath(await PathUtils.getFilePath())
const mergePkg = getRuntimePackageName()
logStep(STAGE.RUN, '当前运行环境', {
包名: mergePkg,
包根: currentRoot,
doc根: currentDocPath,
appId: getAppId()
})
let cache = loadPathCache()
if (!cache || !cache.length) {
cache = createDefaultCache(currentRoot)
} else {
cache = ensureDefaultRootsInCache(cache, currentRoot)
}
savePathCache(cache)
logStep(STAGE.RUN, 'PathCache 就绪', { 条目数: cache?.length || 0 })
const nonCurrentItems = getNonCurrentPaths(cache)
const allAlternateRoots = nonCurrentItems.map(p => p.path)
if (force) {
resetAlternateHandledForForce(currentRoot)
}
const scanPlan = planAlternateScan(currentRoot, nonCurrentItems, force)
const altPreview = previewList(allAlternateRoots, 4)
logStep(STAGE.RUN, 'alternate 包根扫描计划', {
非当前包根数: altPreview.count,
预览: altPreview.preview,
...(altPreview.more ? { 其余: altPreview.more } : {}),
跳过: !!scanPlan.skip,
...(scanPlan.skip ? { 原因: scanPlan.reason } : { 扫描数: scanPlan.paths?.length || 0 })
})
const appId = getAppId()
// 备用副本目录必须同时包含 uniapp_save(历史 saveFile 副本)与 records(录音插件实际输出目录),
// 否则 verifyAndRepairRecordMediaPaths 永远找不到备用副本,包根切换后录音找不回。
const alternateSaveDirs = allAlternateRoots.flatMap(root => [
resolveUniappSaveDir(root, appId),
resolveRecordDir(root, appId)
])
if (scanPlan.skip) {
// 已在扫描计划里输出原因
} else {
const scanList = scanPlan.paths
const total = scanList.length
let idx = 0
for (const packageRoot of scanList) {
idx++
try {
await processPath(packageRoot, mergePkg, currentRoot, idx, total)
} catch (e) {
logStepFail(STAGE.PATH, `包根扫描异常 (${idx}/${total})`, {
包根: packageRoot,
错误: e?.message || String(e)
})
}
}
}
if (ENABLE_LEGACY_FLAT_DB_MERGE) {
try {
await processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg)
} catch (e) {
logStepFail(STAGE.PATH, '遗留扁平库检查异常', { 错误: e?.message || String(e) })
}
} else {
logStep(STAGE.PATH, '已关闭:当前包根遗留扁平库检测(ENABLE_LEGACY_FLAT_DB_MERGE=false)')
}
try {
logStep(STAGE.MEDIA, '======== 主库媒体路径校验开始 ========')
await verifyAndRepairRecordMediaPaths(currentDocPath, alternateSaveDirs)
logStep(STAGE.MEDIA, '======== 主库媒体路径校验结束 ========')
} catch (e) {
logStepFail(STAGE.MEDIA, '媒体路径校验流程异常', { 错误: e?.message || String(e) })
}
logStep(STAGE.RUN, '======== 路径合并全部完成 ========')
} catch (e) {
logStepFail(STAGE.RUN, '路径合并总流程失败', { 错误: e?.message || String(e) })
throw e
}
}
}
export default StoragePathMerge