gongxiangp2/scripts/fix-video-filename-format.ts

116 lines
3.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 修复视频源文件命名格式脚本
*
* 将已迁移的 video-source-*.mp4 格式统一改为 video-*.mp4 格式
* 同时重命名本地文件并更新数据库中的 videoSourceUrl
*/
import { PrismaClient } from '@prisma/client'
import { rename, access } from 'fs/promises'
import { existsSync } from 'fs'
import path from 'path'
const prisma = new PrismaClient()
const UPLOAD_DIR = process.env.UPLOAD_DIR || './uploads'
async function main() {
console.log('==== 修复视频源文件命名格式 ====\n')
// 查找所有 videoSourceUrl 以 /uploads/video-source- 开头的视频素材
const materials = await prisma.material.findMany({
where: {
deletedAt: null,
materialType: {
in: ['主图视频', '安装视频', '种草视频'],
},
videoSourceUrl: {
startsWith: '/uploads/video-source-',
},
},
select: {
id: true,
materialType: true,
videoSourceUrl: true,
},
})
console.log(`找到 ${materials.length} 条需要修复的视频素材\n`)
if (materials.length === 0) {
console.log('✅ 没有需要修复的记录')
await prisma.$disconnect()
return
}
let successCount = 0
let errorCount = 0
for (const material of materials) {
const { id, materialType, videoSourceUrl } = material
if (!videoSourceUrl) {
console.log(`[${id}] 跳过:videoSourceUrl 为空`)
continue
}
try {
// 提取旧文件名(去掉 /uploads/ 前缀)
const oldFileName = videoSourceUrl.replace('/uploads/', '')
const oldFilePath = path.join(UPLOAD_DIR, oldFileName)
// 检查旧文件是否存在
if (!existsSync(oldFilePath)) {
console.log(`[${id}] ⚠️ 跳过:本地文件不存在 ${oldFilePath}`)
continue
}
// 生成新文件名:video-source-xxx.mp4 -> video-xxx.mp4
// 去掉 "video-source-" 前缀,保留后面的部分
const newFileName = oldFileName.replace(/^video-source-/, 'video-')
const newFilePath = path.join(UPLOAD_DIR, newFileName)
const newVideoSourceUrl = `/uploads/${newFileName}`
// 检查新文件名是否已存在(避免冲突)
if (existsSync(newFilePath)) {
console.log(`[${id}] ⚠️ 跳过:目标文件已存在 ${newFilePath}`)
continue
}
console.log(`[${id}] ${materialType}`)
console.log(` 旧文件: ${oldFileName}`)
console.log(` 新文件: ${newFileName}`)
// 重命名本地文件
await rename(oldFilePath, newFilePath)
console.log(` ✅ 文件重命名成功`)
// 更新数据库
await prisma.material.update({
where: { id },
data: {
videoSourceUrl: newVideoSourceUrl,
},
})
console.log(` ✅ 数据库更新成功: ${newVideoSourceUrl}\n`)
successCount++
} catch (error) {
console.error(`[${id}] ❌ 处理失败:`, error)
errorCount++
}
}
console.log('\n==== 修复完成 ====')
console.log(`成功: ${successCount} 条`)
console.log(`失败: ${errorCount} 条`)
await prisma.$disconnect()
}
main().catch((error) => {
console.error('脚本执行出错:', error)
process.exit(1)
})