StoragePathMerge.js 3.54 KB
import { TEMP_DB_FILE } from './constants.js'
import {
  loadPathCache,
  savePathCache,
  createDefaultCache,
  ensureDefaultRootsInCache,
  getNonCurrentPaths
} from './pathCache.js'
import {
  getCurrentPackageRoot,
  findDbInPackageRoot,
  getRuntimePackageName,
  getPackageNamesForMerge
} from './pathResolver.js'
import { copyFileToDoc, removeFile, removeDocRelative } from './fileIo.js'
import {
  openTempDb,
  closeTempDb,
  openMainDbIfNeeded,
  selectTempRecords,
  mergeRecordsToMain
} from './dbMerge.js'
import { logInfo, logError, waitForPlus } from './log.js'

function isAndroidApp(plusRef) {
  const osName = plusRef?.os?.name
  return !!plusRef && (osName === 'Android' || osName === 'android')
}

async function processPath(packageRoot) {
  const dbPath = await findDbInPackageRoot(packageRoot)
  if (!dbPath) {
    logInfo(`该路径下未找到数据库:${packageRoot}`)
    return
  }

  logInfo(`发现待合并数据库:${dbPath}`)

  await removeDocRelative(TEMP_DB_FILE)

  try {
    await copyFileToDoc(dbPath, TEMP_DB_FILE)
  } catch (e) {
    logError(`复制数据库失败(来源 ${dbPath}):${e?.message || e}`)
    return
  }

  try {
    await openTempDb()
    const rows = await selectTempRecords()
    if (!rows || rows.length === 0) {
      logInfo(`临时库无 records 数据,跳过:${packageRoot}`)
      await closeTempDb()
      await removeDocRelative(TEMP_DB_FILE)
      return
    }

    await openMainDbIfNeeded()
    const ok = await mergeRecordsToMain(rows)
    await closeTempDb()

    await removeDocRelative(TEMP_DB_FILE)

    if (ok) {
      try {
        await removeFile(dbPath)
        logInfo(`合并成功,已删除源库:${dbPath}`)
      } catch (e) {
        logError(`合并成功但删除源库失败:${e?.message || e}`)
      }
    } else {
      logError(`合并失败:${packageRoot}`)
    }
  } catch (e) {
    logError(`处理路径异常 ${packageRoot}:${e?.message || e}`)
    try {
      await closeTempDb()
    } catch (_) {
      /* ignore */
    }
    try {
      await removeDocRelative(TEMP_DB_FILE)
    } catch (_) {
      /* ignore */
    }
  }
}

class StoragePathMerge {
  static async run() {
    logInfo('开始执行路径合并')

    const plusRef = await waitForPlus()
    if (!isAndroidApp(plusRef)) {
      logInfo('跳过:非 Android APP-PLUS 环境', {
        有Plus: !!plusRef,
        系统: plusRef?.os?.name
      })
      return
    }

    try {
      const currentRoot = await getCurrentPackageRoot()
      const runtimePkg = getRuntimePackageName()
      const mergePkgs = getPackageNamesForMerge()
      logInfo(`当前运行包名:${runtimePkg};参与扫描的包名:${mergePkgs.join('、')}`)
      logInfo(`当前包根目录(正在使用的路径,不会在此合并):${currentRoot}`)

      let cache = loadPathCache()
      if (!cache || !cache.length) {
        cache = createDefaultCache(currentRoot)
      } else {
        cache = ensureDefaultRootsInCache(cache, currentRoot)
      }
      savePathCache(cache)

      const paths = getNonCurrentPaths(cache)
      const scanList = paths.map(p => p.path)
      logInfo(`待扫描非当前路径 ${paths.length} 个`, { 路径列表: scanList })

      for (const item of paths) {
        try {
          await processPath(item.path)
        } catch (e) {
          logError(`扫描路径出错 ${item.path}:${e?.message || e}`)
        }
      }
      logInfo('路径合并执行完毕')
    } catch (e) {
      logError(`路径合并失败:${e?.message || e}`)
      throw e
    }
  }
}

export default StoragePathMerge