gongxiangp2/lib/external-task-details.ts

227 lines
9.9 KiB
TypeScript

import type { Prisma } from '@prisma/client'
import path from 'node:path'
import { lookup } from 'mime-types'
import { generateDownloadUrl, TASK_DETAIL_DOWNLOAD_TTL_SECONDS, type TaskDetailFileReference } from '@/lib/download-token'
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { prisma } from '@/lib/prisma'
import { getPublicAppOrigin } from '@/lib/public-app-url'
import { deriveTaskDetailIsFullSet } from '@/lib/task-detail-full-set'
import { resolveStoredUploadPath } from '@/lib/upload-paths'
import { listZipEntries, openZipEntryStream, type ZipEntryInfo } from '@/lib/zip-entry-reader'
const groups = ['main', 'sku', 'detail'] as const
type Group = (typeof groups)[number]
type ArchiveGroup = Group | 'all'
const previewTypes = ['preview', 'main-preview', 'sku-preview', 'detail-preview']
const archiveTypes = [...groups, 'all', 'zip']
const fileTypes = [...previewTypes, ...archiveTypes, 'psd']
const visibleTaskDetail = {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
materialType: '任务-详情',
deletedAt: null,
isIncompleteShell: false,
taskStatus: { in: ['completed', 'fetched'] },
} satisfies Prisma.MaterialWhereInput
const fileSelect = {
id: true, assetType: true, fileUrl: true, fileName: true, fileSize: true, updatedAt: true,
createdAt: true, sortOrder: true, skuCode: true,
} satisfies Prisma.MaterialAssetSelect
const materialFileSelect = {
id: true, previewUrl: true, displayImages: true, zipFileName: true, zipFilePath: true, zipFileSize: true,
updatedAt: true,
} satisfies Prisma.MaterialSelect
function fileName(value: string): string {
let name = path.posix.basename(value.replace(/\\/g, '/'))
if (/^https?:\/\//i.test(value)) {
try {
name = path.posix.basename(new URL(value).pathname)
name = decodeURIComponent(name)
} catch {
return name
}
}
return name
}
function originalEntry(entry: ZipEntryInfo): boolean {
const contentType = lookup(entry.name)
return Boolean(contentType && contentType.startsWith('image/') && contentType !== 'image/svg+xml' &&
(entry.flags & 1) === 0 && [0, 8].includes(entry.compressionMethod))
}
function localZipPath(fileUrl: string): string {
if (/^https?:\/\//i.test(fileUrl)) throw new Error('Task detail ZIP is not on the upload volume')
return resolveStoredUploadPath(fileUrl.replace(/^\/+uploads\//i, 'uploads/'))
}
export async function getExternalTaskDetail(id: string) {
const material = await prisma.material.findUnique({
where: { ...visibleTaskDetail, id },
select: {
...materialFileSelect,
materialType: true, productModel: true, categoryName: true, sceneName: true, platformName: true,
productCategoryName: true, authorName: true, renderer: true, isFullSet: true, isAiGenerated: true,
taskDetailSourceType: true, taskDetailRequesterUserId: true, taskDetailRequesterName: true, taskDetailDemandType: true,
taskDetailPrivate: true, accessScope: true, taskNo: true, dingtalkApprovalNo: true, taskStatus: true,
taskFetchedAt: true, createdAt: true, downloadCount: true, likeCount: true,
assets: {
where: { assetType: { in: fileTypes } },
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
select: { ...fileSelect, barcodes: { select: { barcode: true }, orderBy: { barcode: 'asc' } } },
},
},
})
if (!material) return null
const { assets, previewUrl, displayImages, zipFilePath, zipFileName, zipFileSize, id: materialId, ...fields } = material
const base = getPublicAppOrigin()
const url = (taskDetailFile: TaskDetailFileReference) =>
generateDownloadUrl(base, { materialId, downloadType: 'task-detail-file', taskDetailFile })
const availableAssets = assets.filter(asset => asset.fileUrl.trim())
function describeAsset(asset: (typeof assets)[number]) {
return {
assetId: asset.id,
assetType: asset.assetType,
fileName: fileName(asset.fileName || asset.fileUrl),
fileSize: Number(asset.fileSize),
sortOrder: asset.sortOrder,
skuCode: asset.skuCode,
barcodes: asset.barcodes.map(link => link.barcode),
createdAt: asset.createdAt,
updatedAt: asset.updatedAt,
downloadUrl: url({ kind: 'asset', assetId: asset.id }),
}
}
const previews = availableAssets.filter(asset => previewTypes.includes(asset.assetType))
const archiveAssets = availableAssets.filter(asset => archiveTypes.includes(asset.assetType))
const legacyArchive = zipFilePath.trim() && !archiveAssets.some(asset => asset.fileUrl === zipFilePath)
? {
assetId: null, assetType: 'all', group: 'all' as const,
fileName: fileName(zipFileName || zipFilePath), fileSize: Number(zipFileSize), sortOrder: 0,
skuCode: null, barcodes: [], createdAt: fields.createdAt, updatedAt: fields.updatedAt,
downloadUrl: url({ kind: 'archive' }),
}
: null
const archives = [
...archiveAssets.map(asset => ({
...describeAsset(asset),
group: (asset.assetType === 'zip' ? 'all' : asset.assetType) as ArchiveGroup,
})),
...(legacyArchive ? [legacyArchive] : []),
]
const groupedArchives = archiveAssets.filter(asset => asset.assetType !== 'all' && asset.assetType !== 'zip')
const originals: Array<{
archiveAssetId: string | null; group: ArchiveGroup; entryName: string; fileName: string; fileSize: number; downloadUrl: string
}> = []
const issues: Array<{ code: 'ORIGINALS_UNAVAILABLE'; group: ArchiveGroup; archiveAssetId?: string | null }> = []
const sources: Array<{ id: string | null; fileUrl: string; version: number; group: ArchiveGroup }> =
(groupedArchives.length ? groupedArchives : archiveAssets).map(asset => ({
id: asset.id, fileUrl: asset.fileUrl, version: asset.updatedAt.getTime(),
group: (asset.assetType === 'zip' ? 'all' : asset.assetType) as ArchiveGroup,
}))
if (!groupedArchives.length && legacyArchive) {
sources.push({ id: null, fileUrl: zipFilePath, version: fields.updatedAt.getTime(), group: 'all' })
}
for (const { id, fileUrl, version, group } of sources) {
const previousCount = originals.length
try {
const entries = await listZipEntries(localZipPath(fileUrl))
entries.forEach((entry, entryIndex) => {
if (!originalEntry(entry)) return
originals.push({
archiveAssetId: id,
group,
entryName: entry.name,
fileName: fileName(entry.name),
fileSize: entry.uncompressedSize,
downloadUrl: url({ kind: 'original', assetId: id, archiveVersion: version, entryIndex }),
})
})
} catch {
console.warn('[external/task-details] cannot read archive', { materialId, archiveAssetId: id, group })
}
if (originals.length === previousCount) {
issues.push({ code: 'ORIGINALS_UNAVAILABLE', group, archiveAssetId: id })
}
}
if (!originals.some(image => image.group === 'all')) {
for (const group of groups) {
if (previews.some(asset => asset.assetType === `${group}-preview`) &&
!groupedArchives.some(asset => asset.assetType === group)) {
issues.push({ code: 'ORIGINALS_UNAVAILABLE', group })
}
}
}
const coverAsset = previews.find(asset => asset.fileUrl === previewUrl)
return {
materialId,
...fields,
isFullSet: deriveTaskDetailIsFullSet(fields.materialType, availableAssets, fields.isFullSet),
zipFileName: zipFileName ? fileName(zipFileName) : '',
zipFileSize: Number(zipFileSize),
previewUrl: previewUrl.trim() ? url(coverAsset ? { kind: 'asset', assetId: coverAsset.id } : { kind: 'cover' }) : null,
displayImages: displayImages.flatMap((value, index) => value.trim() ? [url({ kind: 'display', index })] : []),
previews: previews.map(asset => ({ ...describeAsset(asset), group: groups.find(group => `${group}-preview` === asset.assetType) ?? null })),
originals,
archives,
sourceFiles: availableAssets.filter(asset => asset.assetType === 'psd').map(describeAsset),
issues,
downloadExpiresInSeconds: TASK_DETAIL_DOWNLOAD_TTL_SECONDS,
}
}
export async function resolveTaskDetailDownload(materialId: string, reference?: TaskDetailFileReference) {
if (!reference) return null
const material = await prisma.material.findUnique({
where: { ...visibleTaskDetail, id: materialId },
select: {
...materialFileSelect,
assets: {
where: {
id: ('assetId' in reference && reference.assetId) || { in: [] },
assetType: { in: fileTypes },
},
select: fileSelect,
},
},
})
if (!material) return null
const [asset] = material.assets
if (reference.kind === 'original') {
const archive = reference.assetId === null
? { fileUrl: material.zipFilePath, updatedAt: material.updatedAt }
: asset && archiveTypes.includes(asset.assetType) ? asset : null
if (!archive?.fileUrl.trim() || archive.updatedAt.getTime() !== reference.archiveVersion) return null
try {
const zip = localZipPath(archive.fileUrl)
const entry = (await listZipEntries(zip))[reference.entryIndex]
if (!entry || !originalEntry(entry)) return null
return { kind: 'original' as const, fileName: fileName(entry.name), size: entry.uncompressedSize, stream: await openZipEntryStream(zip, entry) }
} catch {
return null
}
}
if (reference.kind === 'asset') {
if (!asset?.fileUrl.trim()) return null
return {
kind: 'file' as const,
fileUrl: asset.fileUrl,
fileName: fileName(asset.fileName || asset.fileUrl),
preview: previewTypes.includes(asset.assetType),
}
}
if (reference.kind === 'archive') {
return material.zipFilePath.trim()
? { kind: 'file' as const, fileUrl: material.zipFilePath, fileName: fileName(material.zipFileName || material.zipFilePath), preview: false }
: null
}
const previewUrl = reference.kind === 'cover' ? material.previewUrl : material.displayImages[reference.index]
return previewUrl?.trim() ? { kind: 'file' as const, fileUrl: previewUrl, fileName: fileName(previewUrl), preview: true } : null
}