187 lines
5.7 KiB
TypeScript
187 lines
5.7 KiB
TypeScript
/**
|
||
* 下载指定素材的源文件
|
||
*
|
||
* 使用方法:
|
||
* npx tsx scripts/download-material-source.ts <materialId>
|
||
*
|
||
* 环境变量:
|
||
* DATABASE_URL - 数据库连接(可选,默认使用.env中的DATABASE_URL)
|
||
*/
|
||
|
||
import { PrismaClient } from '@prisma/client'
|
||
import { writeFileSync, existsSync, mkdirSync } from 'fs'
|
||
import path from 'path'
|
||
import { createWriteStream } from 'fs'
|
||
import { pipeline } from 'stream/promises'
|
||
import { Readable } from 'stream'
|
||
|
||
const DATABASE_URL = process.env.DATABASE_URL || 'postgresql://gongxiangpan:gongxiangpan123@192.168.58.20:5432/lobechat'
|
||
|
||
const prisma = new PrismaClient({
|
||
datasources: {
|
||
db: {
|
||
url: DATABASE_URL,
|
||
},
|
||
},
|
||
})
|
||
|
||
async function downloadMaterialSource(materialId: string) {
|
||
try {
|
||
console.log('========================================')
|
||
console.log('下载素材源文件')
|
||
console.log('========================================')
|
||
console.log(`素材ID: ${materialId}`)
|
||
console.log('')
|
||
|
||
// 查询素材信息
|
||
const material = await prisma.material.findUnique({
|
||
where: { id: materialId },
|
||
select: {
|
||
id: true,
|
||
productModel: true,
|
||
categoryName: true,
|
||
sceneName: true,
|
||
productCategoryName: true,
|
||
materialType: true,
|
||
zipFileName: true,
|
||
zipFilePath: true,
|
||
zipFileSize: true,
|
||
videoSourceUrl: true,
|
||
},
|
||
})
|
||
|
||
if (!material) {
|
||
console.error(`❌ 素材不存在: ${materialId}`)
|
||
process.exit(1)
|
||
}
|
||
|
||
console.log('素材信息:')
|
||
console.log(` 类型: ${material.materialType}`)
|
||
console.log(` SPU: ${material.productModel}`)
|
||
console.log(` 使用店铺: ${material.categoryName}`)
|
||
console.log(` 场景: ${material.sceneName}`)
|
||
console.log(` 文件名: ${material.zipFileName}`)
|
||
console.log(` 文件路径: ${material.zipFilePath}`)
|
||
console.log(` 文件大小: ${material.zipFileSize ? Number(material.zipFileSize).toLocaleString() + ' 字节' : '未知'}`)
|
||
console.log('')
|
||
|
||
// 确定源文件路径
|
||
let sourceFilePath = material.zipFilePath || material.videoSourceUrl
|
||
if (!sourceFilePath) {
|
||
console.error('❌ 素材没有源文件路径')
|
||
process.exit(1)
|
||
}
|
||
|
||
// 判断是否为老素材(外网服务器)
|
||
const isOldMaterial =
|
||
sourceFilePath.includes('103.118.245.6') ||
|
||
sourceFilePath.startsWith('http')
|
||
|
||
let downloadUrl: string
|
||
let localFilePath: string
|
||
let fileName: string
|
||
|
||
if (isOldMaterial) {
|
||
// 老素材:直接使用URL
|
||
downloadUrl = sourceFilePath
|
||
fileName = material.zipFileName || path.basename(new URL(sourceFilePath).pathname)
|
||
} else {
|
||
// 新素材:相对路径转换为外网URL
|
||
// 如果数据库中是相对路径,但实际文件在外网服务器
|
||
if (sourceFilePath.startsWith('uploads/') || sourceFilePath.startsWith('/uploads/')) {
|
||
const relativePath = sourceFilePath.replace(/^\/+/, '')
|
||
downloadUrl = `http://103.118.245.6/${relativePath}`
|
||
fileName = material.zipFileName || path.basename(relativePath)
|
||
} else {
|
||
// 已经是完整路径或本地文件
|
||
downloadUrl = sourceFilePath
|
||
fileName = material.zipFileName || path.basename(sourceFilePath)
|
||
}
|
||
}
|
||
|
||
console.log(`下载URL: ${downloadUrl}`)
|
||
console.log(`保存文件名: ${fileName}`)
|
||
console.log('')
|
||
|
||
// 创建下载目录
|
||
const downloadDir = path.join(process.cwd(), 'downloads')
|
||
if (!existsSync(downloadDir)) {
|
||
mkdirSync(downloadDir, { recursive: true })
|
||
}
|
||
|
||
// 保存文件路径
|
||
localFilePath = path.join(downloadDir, fileName)
|
||
|
||
console.log('开始下载...')
|
||
|
||
// 下载文件
|
||
const response = await fetch(downloadUrl)
|
||
if (!response.ok) {
|
||
console.error(`❌ 下载失败: HTTP ${response.status} ${response.statusText}`)
|
||
process.exit(1)
|
||
}
|
||
|
||
if (!response.body) {
|
||
console.error('❌ 响应体为空')
|
||
process.exit(1)
|
||
}
|
||
|
||
// 将响应流转换为Node.js流
|
||
const nodeStream = Readable.fromWeb(response.body as any)
|
||
const writeStream = createWriteStream(localFilePath)
|
||
|
||
// 显示进度
|
||
let downloadedBytes = 0
|
||
const contentLength = response.headers.get('content-length')
|
||
const totalBytes = contentLength ? parseInt(contentLength, 10) : null
|
||
|
||
nodeStream.on('data', (chunk: Buffer) => {
|
||
downloadedBytes += chunk.length
|
||
if (totalBytes) {
|
||
const percent = ((downloadedBytes / totalBytes) * 100).toFixed(1)
|
||
process.stdout.write(`\r下载进度: ${percent}% (${(downloadedBytes / 1024 / 1024).toFixed(2)} MB / ${(totalBytes / 1024 / 1024).toFixed(2)} MB)`)
|
||
} else {
|
||
process.stdout.write(`\r已下载: ${(downloadedBytes / 1024 / 1024).toFixed(2)} MB`)
|
||
}
|
||
})
|
||
|
||
// 使用pipeline确保流正确关闭
|
||
await pipeline(nodeStream, writeStream)
|
||
|
||
console.log('')
|
||
console.log('✅ 下载完成!')
|
||
console.log(`文件保存到: ${localFilePath}`)
|
||
|
||
// 验证文件大小
|
||
if (existsSync(localFilePath)) {
|
||
const fs = await import('fs/promises')
|
||
const stats = await fs.stat(localFilePath)
|
||
console.log(`文件大小: ${stats.size.toLocaleString()} 字节 (${(stats.size / 1024 / 1024).toFixed(2)} MB)`)
|
||
}
|
||
|
||
} catch (error: any) {
|
||
console.error('❌ 下载失败:', error.message)
|
||
if (error.stack) {
|
||
console.error(error.stack)
|
||
}
|
||
process.exit(1)
|
||
} finally {
|
||
await prisma.$disconnect()
|
||
}
|
||
}
|
||
|
||
// 主函数
|
||
async function main() {
|
||
const materialId = process.argv[2]
|
||
|
||
if (!materialId) {
|
||
console.error('❌ 请提供素材ID')
|
||
console.error('使用方法: npx tsx scripts/download-material-source.ts <materialId>')
|
||
process.exit(1)
|
||
}
|
||
|
||
await downloadMaterialSource(materialId)
|
||
}
|
||
|
||
main()
|