Commit d7c7478d by 岑成威

fix: 同步路径

1 parent 2b36e97b
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js' import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
// #ifdef APP-PLUS // #ifdef APP-PLUS
import StoragePathMerge from '@/utils/storageMerge/StoragePathMerge.js' import StoragePathMerge from '@/utils/storageMerge/StoragePathMerge.js'
import { logInfo as mergeLogInfo, logError as mergeLogError } from '@/utils/storageMerge/log.js'
// #endif // #endif
export default { export default {
computed: { computed: {
...@@ -24,15 +25,14 @@ ...@@ -24,15 +25,14 @@
/* ignore */ /* ignore */
} }
// #ifdef APP-PLUS // #ifdef APP-PLUS
console.log('[StoragePathMerge] 启动时开始路径合并') mergeLogInfo('启动时开始路径合并')
try { try {
await StoragePathMerge.run() await StoragePathMerge.run()
} catch (e) { } catch (e) {
console.error('[StoragePathMerge] 启动合并异常', e?.message || e) mergeLogError('启动合并异常 ' + (e?.message || e))
uni.$logger?.local?.error('[StoragePathMerge] ' + (e?.message || e))
} finally { } finally {
uni.$resolveStorageMerge?.() uni.$resolveStorageMerge?.()
console.log('[StoragePathMerge] 启动合并流程结束,可继续初始化数据库') mergeLogInfo('启动合并流程结束,可继续初始化数据库')
} }
// #endif // #endif
// #ifndef APP-PLUS // #ifndef APP-PLUS
......
...@@ -75,6 +75,7 @@ ...@@ -75,6 +75,7 @@
<script> <script>
import FloatLogBus from '@/utils/logger/FloatLogBus.js' import FloatLogBus from '@/utils/logger/FloatLogBus.js'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js' import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import { loadPersistedMergeLogs } from '@/utils/storageMerge/log.js'
// #ifdef APP-PLUS // #ifdef APP-PLUS
import StoragePathMerge from '@/utils/storageMerge/StoragePathMerge.js' import StoragePathMerge from '@/utils/storageMerge/StoragePathMerge.js'
import { seedOneRecordToNonCurrentPath } from '@/utils/storageMerge/seedMergeTest.js' import { seedOneRecordToNonCurrentPath } from '@/utils/storageMerge/seedMergeTest.js'
...@@ -188,11 +189,26 @@ export default { ...@@ -188,11 +189,26 @@ export default {
} }
}, REFRESH_THROTTLE_MS) }, REFRESH_THROTTLE_MS)
}, },
_isMergeKeyword(kw) {
const k = (kw || '').trim().toLowerCase()
return k.includes('storagepathmerge')
},
refresh() { refresh() {
const kw = (this.keyword || '').trim() const kw = (this.keyword || '').trim()
this.lines = kw if (this._isMergeKeyword(kw)) {
? FloatLogBus.getLines() const byId = new Map()
: FloatLogBus.getRecentLines(DISPLAY_LIMIT + 50) loadPersistedMergeLogs().forEach(item => {
if (item && item.id) byId.set(item.id, item)
})
FloatLogBus.getMergeLines().forEach(item => {
if (item && item.id) byId.set(item.id, item)
})
this.lines = [...byId.values()]
} else if (kw) {
this.lines = FloatLogBus.getLines()
} else {
this.lines = FloatLogBus.getRecentLines(DISPLAY_LIMIT + 50)
}
this._syncLineCount() this._syncLineCount()
}, },
togglePanel() { togglePanel() {
...@@ -211,6 +227,7 @@ export default { ...@@ -211,6 +227,7 @@ export default {
}, },
setKeyword(value) { setKeyword(value) {
this.keyword = value this.keyword = value
if (this.expanded) this.refresh()
this.$nextTick(() => this.scrollToBottom()) this.$nextTick(() => this.scrollToBottom())
}, },
scrollToBottom() { scrollToBottom() {
...@@ -236,13 +253,16 @@ export default { ...@@ -236,13 +253,16 @@ export default {
uni.showToast({ title: '已清空', icon: 'none', duration: 800 }) uni.showToast({ title: '已清空', icon: 'none', duration: 800 })
}, },
onCopy() { onCopy() {
let list = FloatLogBus.getLines() const kw = (this.keyword || '').trim()
let list = this._isMergeKeyword(kw)
? [...loadPersistedMergeLogs(), ...FloatLogBus.getMergeLines()]
: FloatLogBus.getLines()
if (this.levelFilter !== 'all') { if (this.levelFilter !== 'all') {
list = list.filter(l => l.level === this.levelFilter) list = list.filter(l => l.level === this.levelFilter)
} }
const kw = (this.keyword || '').trim().toLowerCase() const kwLower = kw.toLowerCase()
if (kw) { if (kw && !this._isMergeKeyword(kw)) {
list = list.filter(l => l.text.toLowerCase().includes(kw)) list = list.filter(l => l.text.toLowerCase().includes(kwLower))
} }
const text = list const text = list
.map(l => `${l.time} [${l.level}] ${l.text}`) .map(l => `${l.time} [${l.level}] ${l.text}`)
......
const target = ['ip', 'dev', 'uat', 'prod', 'beta'] const target = ['ip', 'dev', 'uat', 'prod', 'beta']
const index = 3 const index = 2
/** /**
* *
0本地 0本地
......
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) {
......
...@@ -23,6 +23,8 @@ function trimLines() { ...@@ -23,6 +23,8 @@ function trimLines() {
} }
let lines = [] let lines = []
/** 路径合并等启动期日志,单独保留,避免被后续刷屏挤掉 */
let mergeLines = []
let listeners = new Set() let listeners = new Set()
let installed = false let installed = false
let originalConsole = null let originalConsole = null
...@@ -80,6 +82,12 @@ function pushLine(level, text) { ...@@ -80,6 +82,12 @@ function pushLine(level, text) {
text: msg text: msg
} }
lines.push(line) 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() trimLines()
listeners.forEach(fn => { listeners.forEach(fn => {
try { try {
...@@ -126,6 +134,10 @@ const FloatLogBus = { ...@@ -126,6 +134,10 @@ const FloatLogBus = {
return installed return installed
}, },
getOriginalConsole() {
return originalConsole
},
install() { install() {
if (installed) return if (installed) return
installed = true installed = true
...@@ -159,6 +171,11 @@ const FloatLogBus = { ...@@ -159,6 +171,11 @@ const FloatLogBus = {
return lines.slice() return lines.slice()
}, },
/** 仅路径合并相关日志(冷启动后仍可在悬浮窗看到) */
getMergeLines() {
return mergeLines.slice()
},
/** 取尾部日志,避免面板一次性拷贝/渲染过多 */ /** 取尾部日志,避免面板一次性拷贝/渲染过多 */
getRecentLines(limit = 200) { getRecentLines(limit = 200) {
if (!limit || lines.length <= limit) return lines.slice() if (!limit || lines.length <= limit) return lines.slice()
...@@ -167,6 +184,7 @@ const FloatLogBus = { ...@@ -167,6 +184,7 @@ const FloatLogBus = {
clearLines() { clearLines() {
lines = [] lines = []
mergeLines = []
listeners.forEach(fn => { listeners.forEach(fn => {
try { try {
fn(null) fn(null)
......
...@@ -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)
......
...@@ -13,6 +13,7 @@ import { FileStatus } from '@/utils/common' ...@@ -13,6 +13,7 @@ import { FileStatus } from '@/utils/common'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import store from '@/store' import store from '@/store'
import FileUploadManager from './FileUploadManager.js' import FileUploadManager from './FileUploadManager.js'
import { isMergeSeedRecordId } from '@/utils/storageMerge/mergeTestRecord.js'
const UPLOAD_INTERVAL = 0.5 * 60 * 1000 const UPLOAD_INTERVAL = 0.5 * 60 * 1000
...@@ -91,6 +92,17 @@ class RecordSaveService { ...@@ -91,6 +92,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 +142,11 @@ class RecordSaveService { ...@@ -130,8 +142,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 +165,19 @@ class RecordSaveService { ...@@ -150,6 +165,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)
} }
...@@ -439,14 +467,18 @@ class RecordSaveService { ...@@ -439,14 +467,18 @@ class RecordSaveService {
const result = [] const result = []
try { try {
for (const cur of records) { for (const cur of records) {
if (isMergeSeedRecordId(cur.id)) {
uni.$logger.local.warn(`【接待记录保存服务】 == 跳过路径合并测试记录: ${cur.id}`)
continue
}
const recordUrlList = this.urlListFilter(cur.recordUrlList) const recordUrlList = this.urlListFilter(cur.recordUrlList)
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题) // 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
if (this._isInBlackList(cur.id)) { if (this._isInBlackList(cur.id)) {
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) {
......
import { TEMP_DB_FILE } from './constants.js' import { TEMP_DB_FILE, DB_FILE } from './constants.js'
import { normalizePath } from './pathCache.js'
import { import {
loadPathCache, loadPathCache,
savePathCache, savePathCache,
...@@ -10,16 +11,19 @@ import { ...@@ -10,16 +11,19 @@ import {
getCurrentPackageRoot, getCurrentPackageRoot,
findDbInPackageRoot, findDbInPackageRoot,
getRuntimePackageName, getRuntimePackageName,
getPackageNamesForMerge getPackageNamesForMerge,
getAppId
} from './pathResolver.js' } from './pathResolver.js'
import { copyFileToDoc, removeFile, removeDocRelative } from './fileIo.js' import { copyFileToDoc, removeFile, removeDocRelative, fileExists } from './fileIo.js'
import { import {
openTempDb, openTempDb,
closeTempDb, closeTempDb,
openMainDbIfNeeded, openMainDbIfNeeded,
selectTempRecords, selectTempRecords,
mergeRecordsToMain mergeRecordsToMain,
purgeMergeSeedRecordsFromMain
} from './dbMerge.js' } from './dbMerge.js'
import { isRestrictedInternalPath } from './pathAccess.js'
import { logInfo, logError, waitForPlus } from './log.js' import { logInfo, logError, waitForPlus } from './log.js'
function isAndroidApp(plusRef) { function isAndroidApp(plusRef) {
...@@ -27,12 +31,8 @@ function isAndroidApp(plusRef) { ...@@ -27,12 +31,8 @@ function isAndroidApp(plusRef) {
return !!plusRef && (osName === 'Android' || osName === 'android') return !!plusRef && (osName === 'Android' || osName === 'android')
} }
async function processPath(packageRoot) { async function mergeFromDbFile(dbPath, label) {
const dbPath = await findDbInPackageRoot(packageRoot) if (!dbPath || isRestrictedInternalPath(dbPath)) return
if (!dbPath) {
logInfo(`该路径下未找到数据库:${packageRoot}`)
return
}
logInfo(`发现待合并数据库:${dbPath}`) logInfo(`发现待合并数据库:${dbPath}`)
...@@ -49,7 +49,7 @@ async function processPath(packageRoot) { ...@@ -49,7 +49,7 @@ async function processPath(packageRoot) {
await openTempDb() await openTempDb()
const rows = await selectTempRecords() const rows = await selectTempRecords()
if (!rows || rows.length === 0) { if (!rows || rows.length === 0) {
logInfo(`临时库无 records 数据,跳过:${packageRoot}`) logInfo(`临时库无 records 数据,跳过:${label || dbPath}`)
await closeTempDb() await closeTempDb()
await removeDocRelative(TEMP_DB_FILE) await removeDocRelative(TEMP_DB_FILE)
return return
...@@ -69,10 +69,10 @@ async function processPath(packageRoot) { ...@@ -69,10 +69,10 @@ async function processPath(packageRoot) {
logError(`合并成功但删除源库失败:${e?.message || e}`) logError(`合并成功但删除源库失败:${e?.message || e}`)
} }
} else { } else {
logError(`合并失败:${packageRoot}`) logError(`合并失败:${label || dbPath}`)
} }
} catch (e) { } catch (e) {
logError(`处理路径异常 ${packageRoot}:${e?.message || e}`) logError(`处理路径异常 ${label || dbPath}:${e?.message || e}`)
try { try {
await closeTempDb() await closeTempDb()
} catch (_) { } catch (_) {
...@@ -86,6 +86,48 @@ async function processPath(packageRoot) { ...@@ -86,6 +86,48 @@ async function processPath(packageRoot) {
} }
} }
async function processPath(packageRoot) {
if (isRestrictedInternalPath(packageRoot)) {
logInfo(`跳过内部私有路径(API29+ 不可直接复制):${packageRoot}`)
return
}
const dbPath = await findDbInPackageRoot(packageRoot)
if (!dbPath) {
logInfo(`该路径下未找到数据库:${packageRoot}`)
return
}
if (isRestrictedInternalPath(dbPath)) {
logInfo(`跳过内部路径下的数据库:${dbPath}`)
return
}
await mergeFromDbFile(dbPath, packageRoot)
}
/** 主库在 apps/xxx/doc 时,包根下扁平 zyzs.db 视为遗留库(同包名场景可测) */
async function processLegacyFlatDbAtCurrentRoot(currentRoot) {
if (!currentRoot || isRestrictedInternalPath(currentRoot)) return
const root = normalizePath(currentRoot)
const flatDb = `${root}/${DB_FILE}`
const mainDocDb = normalizePath(`${root}/apps/${getAppId()}/doc/${DB_FILE}`)
if (!(await fileExists(flatDb))) {
logInfo(`当前包根无遗留扁平库:${flatDb}`)
return
}
if (normalizePath(flatDb) === mainDocDb) {
logInfo(`包根库与 _doc 主库路径相同,跳过:${flatDb}`)
return
}
logInfo(`扫描当前包根遗留库(${DB_FILE} 在包根,非 apps/.../doc)`)
await mergeFromDbFile(flatDb, `${currentRoot}#legacy-flat`)
}
class StoragePathMerge { class StoragePathMerge {
static async run() { static async run() {
logInfo('开始执行路径合并') logInfo('开始执行路径合并')
...@@ -104,7 +146,9 @@ class StoragePathMerge { ...@@ -104,7 +146,9 @@ class StoragePathMerge {
const runtimePkg = getRuntimePackageName() const runtimePkg = getRuntimePackageName()
const mergePkgs = getPackageNamesForMerge() const mergePkgs = getPackageNamesForMerge()
logInfo(`当前运行包名:${runtimePkg};参与扫描的包名:${mergePkgs.join('、')}`) logInfo(`当前运行包名:${runtimePkg};参与扫描的包名:${mergePkgs.join('、')}`)
logInfo(`当前包根目录(正在使用的路径,不会在此合并):${currentRoot}`) logInfo(
`当前包根目录:${currentRoot}(其它包名目录整包扫描;本包仅合并包根下遗留 ${DB_FILE})`
)
let cache = loadPathCache() let cache = loadPathCache()
if (!cache || !cache.length) { if (!cache || !cache.length) {
...@@ -125,6 +169,17 @@ class StoragePathMerge { ...@@ -125,6 +169,17 @@ class StoragePathMerge {
logError(`扫描路径出错 ${item.path}:${e?.message || e}`) logError(`扫描路径出错 ${item.path}:${e?.message || e}`)
} }
} }
try {
await processLegacyFlatDbAtCurrentRoot(currentRoot)
} catch (e) {
logError(`扫描包根遗留库出错:${e?.message || e}`)
}
const purged = await purgeMergeSeedRecordsFromMain()
if (purged > 0) {
logInfo(`已清理主库中 ${purged} 条路径合并测试记录`)
}
logInfo('路径合并执行完毕') logInfo('路径合并执行完毕')
} catch (e) { } catch (e) {
logError(`路径合并失败:${e?.message || e}`) logError(`路径合并失败:${e?.message || e}`)
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
} from './constants.js' } from './constants.js'
import { logInfo, logError } from './log.js' import { logInfo, logError } from './log.js'
import { isMergeSeedRecordId, MERGE_SEED_ID_PREFIX } from './mergeTestRecord.js'
function formatValue(value) { function formatValue(value) {
let strVal = '' let strVal = ''
...@@ -143,6 +144,13 @@ export async function mergeRecordsToMain(rows) { ...@@ -143,6 +144,13 @@ export async function mergeRecordsToMain(rows) {
if (!sql) continue if (!sql) continue
await executeSql(MAIN_DB_NAME, sql) await executeSql(MAIN_DB_NAME, sql)
merged++ merged++
if (isMergeSeedRecordId(record.id)) {
await executeSql(
MAIN_DB_NAME,
`DELETE FROM ${TABLE_NAME} WHERE id='${String(record.id).replace(/'/g, "''")}'`
)
logInfo(`测试记录已合并验证并从主库移除,避免触发上传:id=${record.id}`)
}
} catch (e) { } catch (e) {
logError(`合并单条记录失败 id=${record.id}:${e?.message || e}`) logError(`合并单条记录失败 id=${record.id}:${e?.message || e}`)
return false return false
...@@ -151,3 +159,28 @@ export async function mergeRecordsToMain(rows) { ...@@ -151,3 +159,28 @@ export async function mergeRecordsToMain(rows) {
logInfo(`已合并 ${merged} 条记录到主库`) logInfo(`已合并 ${merged} 条记录到主库`)
return true return true
} }
/** 清理主库中遗留的路径合并测试记录(避免接待上传服务反复拉取) */
export async function purgeMergeSeedRecordsFromMain() {
try {
await openMainDbIfNeeded()
const exists = await isTableExists(MAIN_DB_NAME, TABLE_NAME)
if (!exists) return 0
const rows = await selectSql(
MAIN_DB_NAME,
`SELECT id FROM ${TABLE_NAME} WHERE id LIKE '${MERGE_SEED_ID_PREFIX.replace(/'/g, "''")}%'`
)
let n = 0
for (const row of rows || []) {
if (!row?.id) continue
const escaped = String(row.id).replace(/'/g, "''")
await executeSql(MAIN_DB_NAME, `DELETE FROM ${TABLE_NAME} WHERE id='${escaped}'`)
n++
logInfo(`已清理遗留测试记录:${row.id}`)
}
return n
} catch (e) {
logError(`清理测试记录失败:${e?.message || e}`)
return 0
}
}
import { isRestrictedInternalPath } from './pathAccess.js'
function toFileUrl(path) { function toFileUrl(path) {
if (!path) return path if (!path) return path
const p = String(path).trim() const p = String(path).trim()
...@@ -22,6 +24,13 @@ export function fileExists(path) { ...@@ -22,6 +24,13 @@ export function fileExists(path) {
} }
export function copyFileToDoc(sourceAbsolutePath, destFileName) { export function copyFileToDoc(sourceAbsolutePath, destFileName) {
if (isRestrictedInternalPath(sourceAbsolutePath)) {
return Promise.reject(
new Error(
'targetSdkVersion>=29 不支持通过绝对路径访问 /data/data,请使用外置 Android/data/<包名>/ 下的库文件'
)
)
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL( plus.io.resolveLocalFileSystemURL(
toFileUrl(sourceAbsolutePath), toFileUrl(sourceAbsolutePath),
......
import FloatLogBus from '@/utils/logger/FloatLogBus.js' import FloatLogBus from '@/utils/logger/FloatLogBus.js'
const TAG = '[StoragePathMerge]' const TAG = 'StoragePathMerge'
const MERGE_LOG_STORAGE_KEY = 'zyzs_storage_merge_log_history'
function emit(level, msg, extra) { function formatLine(msg, extra) {
const line = extra !== undefined ? `${msg} ${JSON.stringify(extra)}` : msg return extra !== undefined ? `${msg} ${JSON.stringify(extra)}` : msg
const full = `${TAG} ${line}` }
function persistMergeLog(full) {
try { try {
// 始终写入悬浮窗缓冲区(启动早于 install 时也能在面板里看到) let raw = uni.getStorageSync(MERGE_LOG_STORAGE_KEY)
FloatLogBus.push(level, full) let arr = []
if (!FloatLogBus.isInstalled()) { 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 */
}
}
/**
* 统一走 uni.$logger.local(LogCat 落盘 + LocalLog 监听进悬浮窗 + 控制台镜像)
* 悬浮窗未 install 前补一条 FloatLogBus,避免启动合并日志丢失
*/
function emit(level, msg, extra) {
const line = formatLine(msg, extra)
const full = `[${TAG}] ${line}`
const local = uni.$logger?.local
if (local) {
if (level === 'error' && typeof local.error === 'function') {
local.error(full)
} else if (typeof local.info === 'function') {
local.info(full)
}
} else {
const oc = FloatLogBus.getOriginalConsole?.()
if (level === 'error') { if (level === 'error') {
console.error(TAG, line) ;(oc?.error || console.error)(full)
} else { } else {
console.log(TAG, line) ;(oc?.log || console.log)(full)
} }
} try {
} catch (e) { FloatLogBus.push(level, full)
} catch (_) {
/* ignore */ /* ignore */
} }
}
if (local && !FloatLogBus.isInstalled()) {
try { try {
const fn = level === 'error' ? uni.$logger?.local?.error : uni.$logger?.local?.info FloatLogBus.push(level, full)
fn && fn(full) } catch (_) {
} catch (e) {
/* ignore */ /* ignore */
} }
}
persistMergeLog(full)
} }
export function logInfo(msg, extra) { export function logInfo(msg, extra) {
...@@ -34,6 +74,17 @@ export function logError(msg, extra) { ...@@ -34,6 +74,17 @@ export function logError(msg, extra) {
emit('error', msg, extra) emit('error', 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) { export function waitForPlus(timeoutMs = 5000) {
return new Promise(resolve => { return new Promise(resolve => {
if (typeof plus !== 'undefined') { if (typeof plus !== 'undefined') {
......
/** 路径合并测试用记录 id 前缀,勿进入接待上传队列 */
export const MERGE_SEED_ID_PREFIX = '__merge_seed_'
export function isMergeSeedRecordId(id) {
return id != null && String(id).includes(MERGE_SEED_ID_PREFIX)
}
import { RELEASE_PACKAGE_NAME } from './constants.js' import { RELEASE_PACKAGE_NAME } from './constants.js'
import { getMergeAccessiblePackageRoots } from './pathAccess.js'
/** /**
* 当前安装包名(自定义基座多为 io.dcloud.HBuilder,正式包为 uni.gltap) * 当前安装包名(自定义基座多为 io.dcloud.HBuilder,正式包为 uni.gltap)
...@@ -19,29 +20,20 @@ export function getRuntimePackageName() { ...@@ -19,29 +20,20 @@ export function getRuntimePackageName() {
return RELEASE_PACKAGE_NAME return RELEASE_PACKAGE_NAME
} }
/** 参与路径合并扫描的包名:当前运行包 + 正式发包名(遗留数据) */ /**
* 参与路径合并扫描的包名:当前运行包 + 正式包(若不同,用于基座扫 uni.gltap 遗留)
* 当前已是 uni.gltap 时通常只有 uni.gltap 一项
*/
export function getPackageNamesForMerge() { export function getPackageNamesForMerge() {
const names = new Set() const names = new Set()
const runtime = getRuntimePackageName() const runtime = getRuntimePackageName()
if (runtime) names.add(runtime) if (runtime) names.add(runtime)
if (RELEASE_PACKAGE_NAME) names.add(RELEASE_PACKAGE_NAME) if (RELEASE_PACKAGE_NAME && RELEASE_PACKAGE_NAME !== runtime) {
names.add(RELEASE_PACKAGE_NAME)
}
return [...names] return [...names]
} }
export function getDefaultPackageRoots() { export function getDefaultPackageRoots() {
const roots = [] return getMergeAccessiblePackageRoots(getPackageNamesForMerge)
const seen = new Set()
for (const pkg of getPackageNamesForMerge()) {
for (const path of [
`/data/data/${pkg}`,
`/data/user/0/${pkg}`,
`/storage/emulated/0/Android/data/${pkg}`
]) {
if (!seen.has(path)) {
seen.add(path)
roots.push(path)
}
}
}
return roots
} }
/**
* targetSdkVersion >= 29 时,plus.io 不能直接读写 /data/data、/data/user 下绝对路径。
* 合并/测试库应使用外置 Android/data/<包名>/ 等应用可访问目录。
*/
export function isRestrictedInternalPath(path) {
if (!path) return false
const p = String(path).replace(/^file:\/\//, '').trim()
return p.startsWith('/data/data/') || p.startsWith('/data/user/')
}
export function isExternalAppDataRoot(path) {
if (!path) return false
const p = String(path).replace(/^file:\/\//, '').replace(/\/+$/, '')
return p.includes('/Android/data/')
}
/** 参与扫描/写入的包根(仅外置,避免 API29+ 复制失败) */
export function getMergeAccessiblePackageRoots(getPackageNamesForMerge) {
const names = typeof getPackageNamesForMerge === 'function' ? getPackageNamesForMerge() : []
const roots = []
const seen = new Set()
for (const pkg of names) {
const path = `/storage/emulated/0/Android/data/${pkg}`
if (!seen.has(path)) {
seen.add(path)
roots.push(path)
}
}
return roots
}
import { PATH_CACHE_KEY } from './constants.js' import { PATH_CACHE_KEY } from './constants.js'
import { getDefaultPackageRoots } from './packageName.js' import { getDefaultPackageRoots } from './packageName.js'
import { isRestrictedInternalPath } from './pathAccess.js'
export function normalizePath(path) { export function normalizePath(path) {
if (!path) return '' if (!path) return ''
...@@ -17,7 +18,7 @@ export function loadPathCache() { ...@@ -17,7 +18,7 @@ export function loadPathCache() {
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (!Array.isArray(parsed)) return null if (!Array.isArray(parsed)) return null
return parsed return parsed
.filter(item => item && item.path) .filter(item => item && item.path && !isRestrictedInternalPath(item.path))
.map(item => ({ .map(item => ({
path: normalizePath(item.path), path: normalizePath(item.path),
isCurrent: !!item.isCurrent isCurrent: !!item.isCurrent
...@@ -100,7 +101,9 @@ export function syncCurrentFlag(cache, currentRoot) { ...@@ -100,7 +101,9 @@ export function syncCurrentFlag(cache, currentRoot) {
} }
export function getNonCurrentPaths(cache) { export function getNonCurrentPaths(cache) {
return (cache || []).filter(item => !item.isCurrent && item.path) return (cache || []).filter(
item => !item.isCurrent && item.path && !isRestrictedInternalPath(item.path)
)
} }
/** /**
......
import { DB_FILE, RECORDS_TABLE_COLUMNS, TABLE_NAME } from './constants.js' import { DB_FILE, RECORDS_TABLE_COLUMNS, TABLE_NAME, RELEASE_PACKAGE_NAME } from './constants.js'
import { getCurrentPackageRoot, getDefaultPackageRoots } from './pathResolver.js' import {
getCurrentPackageRoot,
getDefaultPackageRoots,
getRuntimePackageName
} from './pathResolver.js'
import { isRestrictedInternalPath } from './pathAccess.js'
/** Android10+ 只能写本应用 Android/data/<当前包名>/,不能写其它包名目录 */
function isWritablePackageRoot(root, runtimePkg) {
if (!root || !runtimePkg || isRestrictedInternalPath(root)) return false
const match = String(root).match(/\/Android\/data\/([^/]+)/)
return !!(match && match[1] === runtimePkg)
}
import { logInfo, logError, waitForPlus } from './log.js' import { logInfo, logError, waitForPlus } from './log.js'
const SEED_DB_NAME = 'zyzs_seed_merge_manual' const SEED_DB_NAME = 'zyzs_seed_merge_manual'
...@@ -148,7 +160,8 @@ async function createSeedDbWithOneRecord(recordId) { ...@@ -148,7 +160,8 @@ async function createSeedDbWithOneRecord(recordId) {
const createSql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (${RECORDS_TABLE_COLUMNS.join(', ')})` const createSql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (${RECORDS_TABLE_COLUMNS.join(', ')})`
await execSql(SEED_DB_NAME, createSql) await execSql(SEED_DB_NAME, createSql)
const escapedId = String(recordId).replace(/'/g, "''") const escapedId = String(recordId).replace(/'/g, "''")
const insertSql = `INSERT INTO ${TABLE_NAME} (id, staffUuid, staffName, receptionStatus) VALUES ('${escapedId}', 'seed-merge', '手动写入合并测试', 1)` // recordStatus=0:避免被 RecordSaveService 当作已完成记录反复上传
const insertSql = `INSERT INTO ${TABLE_NAME} (id, staffUuid, staffName, receptionStatus, recordStatus) VALUES ('${escapedId}', 'seed-merge', '手动写入合并测试', 1, 0)`
await execSql(SEED_DB_NAME, insertSql) await execSql(SEED_DB_NAME, insertSql)
await closeDb(SEED_DB_NAME) await closeDb(SEED_DB_NAME)
} }
...@@ -157,9 +170,10 @@ function pickNonCurrentRoots(currentRoot) { ...@@ -157,9 +170,10 @@ function pickNonCurrentRoots(currentRoot) {
const current = normalizeNoTrailingSlash(currentRoot) const current = normalizeNoTrailingSlash(currentRoot)
const roots = (getDefaultPackageRoots() || []).map(r => normalizeNoTrailingSlash(r)).filter(Boolean) const roots = (getDefaultPackageRoots() || []).map(r => normalizeNoTrailingSlash(r)).filter(Boolean)
const unique = [...new Set(roots)] const unique = [...new Set(roots)]
const nonCurrent = unique.filter(r => r && r !== current) const nonCurrent = unique.filter(
r => r && r !== current && !isRestrictedInternalPath(r)
)
// 优先外置 Android/data(更直观且常用于迁移)
nonCurrent.sort((a, b) => { nonCurrent.sort((a, b) => {
const ak = a.includes('/Android/data/') ? 0 : 1 const ak = a.includes('/Android/data/') ? 0 : 1
const bk = b.includes('/Android/data/') ? 0 : 1 const bk = b.includes('/Android/data/') ? 0 : 1
...@@ -170,6 +184,31 @@ function pickNonCurrentRoots(currentRoot) { ...@@ -170,6 +184,31 @@ function pickNonCurrentRoots(currentRoot) {
} }
/** /**
* 写入测试库候选路径(仅本应用可写的外置包根)
* - 正式包 uni.gltap:只能写 .../uni.gltap/zyzs.db(包根遗留库,重启后合并)
* - 自定义基座:只能写 .../io.dcloud.HBuilder/zyzs.db(不能写 uni.gltap 目录,系统会拦截)
*/
function buildSeedWriteTargets(currentRoot) {
const current = normalizeNoTrailingSlash(currentRoot)
const runtime = getRuntimePackageName()
const nonCurrentSameApp = pickNonCurrentRoots(currentRoot).filter(root =>
isWritablePackageRoot(root, runtime)
)
if (nonCurrentSameApp.length) return nonCurrentSameApp
if (current && isWritablePackageRoot(current, runtime)) {
logInfo(
'将测试库写到当前应用包根(模拟遗留 zyzs.db,冷启动后合并到 _doc)',
{ 包根: current, 运行包名: runtime }
)
return [current]
}
return []
}
/**
* 一键生成一条 records,并把 zyzs.db 放到“非当前”包根(自动挑可写的那个)。 * 一键生成一条 records,并把 zyzs.db 放到“非当前”包根(自动挑可写的那个)。
* 适合在自定义基座(io.dcloud.HBuilder)下模拟迁移合并。 * 适合在自定义基座(io.dcloud.HBuilder)下模拟迁移合并。
*/ */
...@@ -182,9 +221,12 @@ export async function seedOneRecordToNonCurrentPath() { ...@@ -182,9 +221,12 @@ export async function seedOneRecordToNonCurrentPath() {
} }
const currentRoot = await getCurrentPackageRoot() const currentRoot = await getCurrentPackageRoot()
const candidates = pickNonCurrentRoots(currentRoot) const candidates = buildSeedWriteTargets(currentRoot)
if (!candidates.length) { if (!candidates.length) {
logError('写入测试库失败:没有可用的非当前路径') logError('写入测试库失败:无法解析包根目录', {
当前包根: currentRoot,
运行包名: getRuntimePackageName()
})
return { ok: false, reason: 'no-non-current' } return { ok: false, reason: 'no-non-current' }
} }
...@@ -203,7 +245,11 @@ export async function seedOneRecordToNonCurrentPath() { ...@@ -203,7 +245,11 @@ export async function seedOneRecordToNonCurrentPath() {
} }
} }
logError('写入测试库失败:所有候选路径均不可写', { 失败详情: errors }) const hint =
getRuntimePackageName() === RELEASE_PACKAGE_NAME
? '正式包仅支持写入本应用包根;勿尝试 io.dcloud.HBuilder 等其它包目录(Android10+ 禁止跨应用写入)'
: '自定义基座仅支持写入本应用包根;要模拟 uni.gltap 遗留库请用正式包或 adb'
logError('写入测试库失败:所有候选路径均不可写', { 失败详情: errors, 说明: hint })
return { ok: false, reason: 'all-failed', errors } return { ok: false, reason: 'all-failed', errors }
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!