import { createReadStream } from "node:fs"; import { stat, writeFile, rm } from "node:fs/promises"; import { join } from "node:path"; import JSZip from "jszip"; import { writeDownloadZip } from "./download-zip-stream"; import { assertZipDiskSpace, saveZipTask, zipTaskPath, type ZipTask } from "./download-zip-task-store"; import type { CanvasDownloadAssetResult } from "./photoshop-safe-download"; export function buildZipContentDisposition(folderName: string) { const name = `${folderName}.zip`; const asciiName = folderName.replace(/[^\x20-\x7E]+/g, "").replace(/"/g, "").trim() || "canvas-images"; return `attachment; filename="${asciiName}.zip"; filename*=UTF-8''${encodeURIComponent(name)}`; } export async function prepareCanvasZip( task: ZipTask, fetchAsset: (params: { file: ZipTask["files"][number]; index: number; signal: AbortSignal }) => Promise, ) { delete task.zipFile; delete task.contentDisposition; delete task.cdnUrl; // Stage each image on disk, not all PNG buffers in the web process heap. // A restart resumes from these files using the current owner's session. let cursor = 0; let writes = Promise.resolve(); const persist = () => { const current = task; writes = writes.then(() => saveZipTask(current)); return writes; }; const results = await Promise.allSettled(Array.from({ length: Math.min(2, task.files.length) }, async () => { while (cursor < task.files.length) { const index = cursor++; const file = task.files[index]; const path = join(zipTaskPath(task.id), `${index}.image`); if (file.prepared && file.filename && (await stat(path).catch(() => null))?.size) continue; delete file.prepared; delete file.filename; const result = await fetchAsset({ file, index, signal: AbortSignal.timeout(120_000) }).catch(() => ({ ok: false as const, error: "原图读取超时或源地址暂时不可用" })); if (result.ok) { await assertZipDiskSpace(result.bytes.length); await writeFile(path, result.bytes, { mode: 0o600 }); file.prepared = `${index}.image`; file.filename = result.filename; delete file.error; } else file.error = result.error; task.processedCount = task.files.filter(f => f.prepared || f.error).length; task.successCount = task.files.filter(f => f.prepared).length; task.failedCount = task.files.filter(f => f.error).length; task.stage = `正在准备原图 ${task.processedCount}/${task.totalCount}`; task.updatedAt = Date.now(); await persist(); } })); const rejected = results.find(result => result.status === "rejected"); if (rejected?.status === "rejected") throw rejected.reason; if (!task.successCount) throw new Error("所选原图暂时都无法读取,请稍后重试;画布图片不会被删除"); const zip = new JSZip(); const folder = zip.folder(task.folderName) || zip; for (const file of task.files) if (file.prepared && file.filename) folder.file(file.filename, createReadStream(join(zipTaskPath(task.id), file.prepared)) .once("close", () => { void rm(join(zipTaskPath(task.id), file.prepared!), { force: true }).catch(() => undefined); })); if (task.failedCount) folder.file("_download-failures.txt", task.files.filter(f => f.error) .map(f => `${f.name || "图片"}:${f.error}`).join("\n")); task.stage = "正在生成完整 ZIP 文件"; await saveZipTask(task); task.zipFile = await writeDownloadZip(zip, task.id, percent => { task.compressPercent = percent; }); task.contentDisposition = buildZipContentDisposition(task.folderName); }