gongxiangp2/scripts/check-old-materials-source-files.ts

247 lines
7.1 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.

/**
* 检查老素材的源文件情况
* 判断老素材的源文件是否真的缺失
*/
import { PrismaClient } from '@prisma/client'
import { exec } from 'child_process'
import { promisify } from 'util'
import { writeFile } from 'fs/promises'
import path from 'path'
import fs from 'fs'
const execAsync = promisify(exec)
const prisma = new PrismaClient()
const cutoffDate = new Date('2025-10-27T23:59:59.999Z')
const IS_IN_CONTAINER = process.env.IS_IN_CONTAINER === 'true' || process.env.NODE_ENV === 'production'
const UPLOADS_PATH = IS_IN_CONTAINER ? '/app/uploads' : '/mnt/PoolOne/apps/youyidian-3d/uploads'
/**
* 判断是否为老素材
*/
function isOldMaterial(material: any): boolean {
// 1. 检查创建时间
if (material.createdAt <= cutoffDate) {
return true
}
// 2. 检查预览图URL
const previewUrl = material.previewUrl || ''
if (previewUrl.includes('s3.1080p.hk') &&
previewUrl.includes('/jsxiangche/') &&
!previewUrl.includes('由壹点AI/')) {
return true
}
return false
}
/**
* 检查文件是否存在(容器内)
*/
function checkFileExistsInContainer(filePath: string): boolean {
if (!IS_IN_CONTAINER) return false
try {
const fileName = path.basename(filePath)
const localPath = path.join(UPLOADS_PATH, fileName)
fs.accessSync(localPath, fs.constants.F_OK)
return true
} catch {
return false
}
}
async function main() {
console.log('='.repeat(60))
console.log('检查老素材源文件情况')
console.log('='.repeat(60))
console.log(`分界日期: ${cutoffDate.toISOString()}`)
console.log()
// 1. 查询所有老素材
console.log('📋 查询老素材...')
const allMaterials = await prisma.material.findMany({
where: {
deletedAt: null,
OR: [
{ createdAt: { lte: cutoffDate } },
{ previewUrl: { contains: 's3.1080p.hk' } },
{ previewUrl: { contains: 'jsxiangche' } },
],
},
select: {
id: true,
materialType: true,
productModel: true,
authorName: true,
categoryName: true,
createdAt: true,
previewUrl: true,
zipFilePath: true,
zipFileName: true,
zipFileSize: true,
},
})
// 筛选老素材
const oldMaterials = allMaterials.filter(isOldMaterial)
console.log(` 找到 ${oldMaterials.length} 个老素材`)
console.log()
// 2. 分析源文件情况
console.log('🔍 分析源文件情况...')
const stats = {
total: oldMaterials.length,
hasLocalPath: 0, // 有本地路径(uploads/...)
hasHttpUrl: 0, // 有HTTP URL(http://103.118.245.6/...)
hasS3Url: 0, // 有S3 URL(zipFileName字段)
noSourceFile: 0, // 没有源文件路径
localFileExists: 0, // 本地文件存在
localFileMissing: 0, // 本地文件缺失
}
const results: Array<{
id: string
materialType: string
productModel: string
authorName: string
categoryName: string
createdAt: Date
zipFilePath: string | null
zipFileName: string | null
sourceType: string // 'local' | 'http' | 's3' | 'none'
fileExists: boolean
}> = []
for (const material of oldMaterials) {
let sourceType = 'none'
let fileExists = false
if (material.zipFilePath) {
// 本地路径
if (material.zipFilePath.startsWith('uploads/') ||
material.zipFilePath.startsWith('/app/uploads/') ||
material.zipFilePath.startsWith('./uploads/')) {
sourceType = 'local'
stats.hasLocalPath++
fileExists = checkFileExistsInContainer(material.zipFilePath)
if (fileExists) {
stats.localFileExists++
} else {
stats.localFileMissing++
}
}
// HTTP URL
else if (material.zipFilePath.startsWith('http://') ||
material.zipFilePath.startsWith('https://')) {
sourceType = 'http'
stats.hasHttpUrl++
fileExists = true // HTTP URL标记为存在(需要单独检查)
}
}
// S3 URL(zipFileName字段)
if (material.zipFileName &&
(material.zipFileName.startsWith('http://') ||
material.zipFileName.startsWith('https://'))) {
if (sourceType === 'none') {
sourceType = 's3'
stats.hasS3Url++
fileExists = true // S3 URL标记为存在
}
}
if (sourceType === 'none') {
stats.noSourceFile++
}
results.push({
id: material.id,
materialType: material.materialType || '',
productModel: material.productModel || '',
authorName: material.authorName || '',
categoryName: material.categoryName || '',
createdAt: material.createdAt,
zipFilePath: material.zipFilePath,
zipFileName: material.zipFileName,
sourceType,
fileExists,
})
}
// 3. 输出统计
console.log('📊 统计结果:')
console.log(` 总老素材数: ${stats.total}`)
console.log(` 有本地路径: ${stats.hasLocalPath} 个`)
console.log(` - 文件存在: ${stats.localFileExists} 个`)
console.log(` - 文件缺失: ${stats.localFileMissing} 个`)
console.log(` 有HTTP URL: ${stats.hasHttpUrl} 个`)
console.log(` 有S3 URL: ${stats.hasS3Url} 个`)
console.log(` 无源文件路径: ${stats.noSourceFile} 个`)
console.log()
// 4. 生成详细报告
console.log('📝 生成详细报告...')
const reportRows: string[] = []
reportRows.push('素材ID,素材类型,产品型号,作者,使用店铺,创建时间,源文件类型,源文件路径,源文件名,文件是否存在')
for (const result of results) {
const row = [
result.id,
result.materialType,
result.productModel,
result.authorName,
result.categoryName,
result.createdAt.toISOString(),
result.sourceType,
result.zipFilePath || '',
result.zipFileName || '',
result.fileExists ? '是' : '否',
]
reportRows.push(row.map(field => {
if (field === null || field === undefined) return ''
const str = String(field)
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`
}
return str
}).join(','))
}
const reportContent = reportRows.join('\n')
const reportFile = IS_IN_CONTAINER ? '/tmp/老素材源文件检查报告.csv' : '老素材源文件检查报告.csv'
await writeFile(reportFile, reportContent, 'utf-8')
console.log(` ✅ 报告已生成: ${reportFile}`)
console.log()
// 5. 缺失文件统计
const missingFiles = results.filter(r => r.sourceType === 'local' && !r.fileExists)
console.log('⚠️ 本地文件缺失的老素材:')
console.log(` 数量: ${missingFiles.length} 个`)
console.log()
if (missingFiles.length > 0) {
console.log('前10个缺失文件的素材:')
missingFiles.slice(0, 10).forEach((m, i) => {
console.log(` ${i + 1}. ${m.productModel} (${m.materialType}) - ${m.zipFilePath}`)
})
}
console.log()
console.log('='.repeat(60))
console.log('检查完成')
console.log('='.repeat(60))
await prisma.$disconnect()
}
main().catch((error) => {
console.error('执行失败:', error)
process.exit(1)
})