gongxiangp2/lib/task-detail-change-review.ts

153 lines
6.0 KiB
TypeScript

import { lstat } from 'fs/promises'
import sharp from 'sharp'
import { withImageProcessingSlot } from '@/lib/image-processing-limiter'
import { resolveStrictChildPath } from '@/lib/path-security'
import { prisma } from '@/lib/prisma'
import { getS3ObjectStream, getTrustedS3MutationKey, isS3Url } from '@/lib/s3'
import type { StoredTaskDetailChangeOperation } from '@/lib/task-detail-change-approval'
import { resolveTaskDetailStagedFile } from '@/lib/task-detail-change-staging'
import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy'
import { getUploadRootDir } from '@/lib/upload-paths'
export type TaskDetailReviewSide = 'before' | 'after'
const PREVIEW_TYPES = ['main-preview', 'sku-preview', 'detail-preview']
const MAX_EXISTING_PREVIEW_BYTES = 16 * 1024 * 1024
const MAX_NOTIFICATION_IMAGE_BYTES = 44 * 1024
export function getTaskDetailReviewSources(operation: StoredTaskDetailChangeOperation) {
return {
before: operation.kind === 'group_images'
? operation.assetIds
: operation.kind === 'replace' || operation.kind === 'delete' ? [operation.assetId] : [],
after: operation.kind === 'group_images' ? operation.stagedFiles : 'stagedFile' in operation ? [operation.stagedFile] : [],
}
}
export function hasCurrentTaskDetailReviewImages(request: {
status: string
expiresAt: Date
baseMaterialUpdatedAt: Date
material: { deletedAt?: Date | null; updatedAt: Date }
}) {
return request.status === 'pending_manager_approval'
&& request.expiresAt > new Date()
&& !request.material.deletedAt
&& request.baseMaterialUpdatedAt?.getTime() === request.material.updatedAt?.getTime()
}
async function readOldPreview(materialId: string, assetId: string): Promise<Buffer | string | null> {
const asset = await prisma.materialAsset.findFirst({
where: { id: assetId, materialId, assetType: { in: PREVIEW_TYPES } },
select: { fileUrl: true },
})
if (!asset) return null
if (isS3Url(asset.fileUrl)) {
const { body, contentLength } = await getS3ObjectStream(getTrustedS3MutationKey(asset.fileUrl))
if (contentLength && contentLength > MAX_EXISTING_PREVIEW_BYTES) {
body.destroy()
return null
}
const chunks: Buffer[] = []
let bytes = 0
for await (const chunk of body) {
const buffer = Buffer.from(chunk)
bytes += buffer.length
if (bytes > MAX_EXISTING_PREVIEW_BYTES) return null
chunks.push(buffer)
}
return Buffer.concat(chunks)
}
const storedPath = asset.fileUrl.replace(/\\/g, '/')
if (!storedPath.startsWith('uploads/')) return null
return resolveStrictChildPath(getUploadRootDir(), ...storedPath.slice('uploads/'.length).split('/'))
}
export async function readTaskDetailReviewImage(input: {
requestId: string
materialId: string
operation: StoredTaskDetailChangeOperation
side: TaskDetailReviewSide
index: number
thumbnail?: boolean
}) {
const sources = getTaskDetailReviewSources(input.operation)
try {
let image: string | Buffer | null
if (input.side === 'before') {
const assetId = sources.before[input.index]
if (!assetId) return null
image = await readOldPreview(input.materialId, assetId)
} else {
const file = sources.after[input.index]
if (!file) return null
image = resolveTaskDetailStagedFile(input.requestId, file).filePath
}
if (!image) return null
if (typeof image === 'string') {
const info = await lstat(image)
const maxBytes = input.side === 'before' ? MAX_EXISTING_PREVIEW_BYTES : TASK_DETAIL_UPLOAD_LIMITS.maxSingleImageBytes
if (!info.isFile() || info.size > maxBytes) return null
}
return await withImageProcessingSlot(async () => {
const pipeline = sharp(image!, { limitInputPixels: 60_000_000 })
.rotate()
.flatten({ background: '#f4f5f6' })
if (input.thumbnail) {
const { width, height } = await pipeline.metadata()
if (width && height && height > width * 2) {
pipeline.resize(300, 180, { fit: 'cover', position: 'north' })
} else {
pipeline.resize(300, 180, { fit: 'contain', background: '#f4f5f6' })
}
} else {
pipeline.resize(1200, 6000, { fit: 'inside', withoutEnlargement: true })
}
return pipeline.jpeg({ quality: 84 }).toBuffer()
})
} catch {
return null
}
}
export async function buildTaskDetailNotificationReviewImage(
requestId: string,
materialId: string,
operations: StoredTaskDetailChangeOperation[],
) {
const labels = { main: '主图', sku: 'SKU 图', detail: '详情图' }
const rows: Array<{ label: string; before: Buffer | null; after: Buffer | null }> = []
for (let index = 0; index < operations.length && rows.length < 3; index += 1) {
const operation = operations[index]
const input = { requestId, materialId, operation, index: 0, thumbnail: true }
const before = await readTaskDetailReviewImage({ ...input, side: 'before' })
const after = await readTaskDetailReviewImage({ ...input, side: 'after' })
if (!before && !after) continue
const label = operation.kind === 'group_images' ? labels[operation.group] : `操作 ${index + 1}`
rows.push({ label, before, after })
}
if (rows.length === 0) return null
const tiles = rows.flatMap(({ before, after }, index) => {
const top = index * 188
return [
...(before ? [{ input: before, left: 0, top }] : []),
...(after ? [{ input: after, left: 308, top }] : []),
]
})
const height = rows.length * 188 - 8
const sheet = await withImageProcessingSlot(() =>
sharp({ create: { width: 608, height, channels: 3, background: '#f4f5f6' } })
.composite(tiles)
.png()
.toBuffer(),
)
for (const { width, quality } of [{ width: 608, quality: 72 }, { width: 608, quality: 52 }, { width: 420, quality: 42 }]) {
const image = await withImageProcessingSlot(() => sharp(sheet).resize(width).jpeg({ quality, mozjpeg: true }).toBuffer())
if (image.length <= MAX_NOTIFICATION_IMAGE_BYTES) {
return { image, rowLabels: rows.map(({ label }) => label) }
}
}
return null
}