recordMediaVerify.js 6.45 KB
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 = '归并·媒体'

/** 与 RecordSaveService.checkFileExists 一致:表内路径可能是历史包根的绝对路径,
 *  targetSdk>=29 下 plus.io 读不到,必须走 fileIo.fileExists(Java File 优先 + plus.io 降级)。
 *  否则会把"读不到"误判成"文件不存在",备用副本修复永远不触发。 */
export function checkMediaFileExists(filePath) {
  if (!filePath || !String(filePath).toLowerCase().endsWith('.mp3')) {
    return Promise.resolve(false)
  }
  return fileExists(filePath)
}

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, '媒体路径校验准备', { doc根: curDoc, 备用录音目录数: altDirs.length })

  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) {
      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) {
        continue
      }

      const list = parseRecordUrlList(row.recordUrlList)
      let listChanged = false
      let tempFilePath = row.tempFilePath
      let recordOk = 0
      let recordMissing = 0
      let recordRepaired = 0

      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
        }

        let repaired = false
        for (const altDir of altDirs) {
          const candidate = `${altDir}/${fileName}`
          const altExists = await fileExists(candidate)
          if (!altExists) continue

          try {
            await copyFileIntoDocSaveDir(candidate, fileName)
            item.file = buildMediaFilePathForCurrentDoc(curDoc, fileName)
            listChanged = true
            repaired = true
            repairedCount++
            recordRepaired++
            logStep(STAGE, `片段修复成功 recordId=${row.id}`, { 文件名: fileName })
            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)

          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}`, { 文件名: fileName })
              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) {
        try {
          await dbRecord.updateRecord(
            {
              recordUrlList: JSON.stringify(list),
              tempFilePath
            },
            { id: row.id }
          )
        } catch (e) {
          logStepFail(STAGE, `主库路径更新失败 recordId=${row.id}`, {
            错误: e?.message || String(e)
          })
        }
      }
    }

    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 }
  }
}