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

/** 与 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 }
  }
}