ai-chatbot/lib/canvas/photoshop-download-normalize.ts

213 lines
7.7 KiB
TypeScript

export type DownloadFileItem = {
url: string;
name?: string;
};
export type CanvasDownloadAssetResult =
| {
ok: true;
filename: string;
bytes: Buffer;
contentType: string;
}
| {
ok: false;
url: string;
name?: string;
error: string;
};
export function sanitizeCanvasDownloadFileName(value: string, fallback: string): string {
const cleaned = String(value || "")
.replace(/\.[a-zA-Z0-9]{2,6}$/g, "")
.replace(/[\\/:*?"<>|]+/g, "-")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.trim()
.slice(0, 120);
return cleaned || fallback;
}
export function buildAttachmentContentDisposition(filename: string): string {
const safeAsciiName =
filename
.replace(/[^\x20-\x7E]+/g, "")
.replace(/"/g, "")
.trim() || `canvas-image-${Date.now()}.png`;
return `attachment; filename="${safeAsciiName}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
}
function getContentTypeMime(contentType: string): string {
return String(contentType || "")
.split(";")[0]
?.trim()
.toLowerCase();
}
function hasAsciiAt(buffer: Buffer, offset: number, value: string): boolean {
return buffer.subarray(offset, offset + value.length).toString("latin1") === value;
}
function looksLikeSvg(buffer: Buffer, contentType: string): boolean {
if (getContentTypeMime(contentType) === "image/svg+xml") return true;
const text = buffer.subarray(0, Math.min(buffer.length, 1024)).toString("utf8").trimStart();
return /^(?:<\?xml[^>]*>\s*)?<svg[\s>]/i.test(text);
}
function looksLikeErrorDocument(buffer: Buffer, contentType: string): boolean {
const mime = getContentTypeMime(contentType);
if (
mime.startsWith("text/") ||
mime === "application/json" ||
mime === "application/xml" ||
mime === "application/xhtml+xml"
) {
return true;
}
const text = buffer.subarray(0, Math.min(buffer.length, 512)).toString("utf8").trimStart();
return /^(?:<!doctype\s+html|<html[\s>]|<\?xml|<error[\s>]|[{[])/i.test(text);
}
function detectAsset(bytes: Buffer, contentType: string): { kind: "image" | "video" | "audio"; mimeType: string; ext: string } | null {
if (bytes.length < 4) return null;
if (bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
return { kind: "image", mimeType: "image/png", ext: "png" };
}
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
return { kind: "image", mimeType: "image/jpeg", ext: "jpg" };
}
if (hasAsciiAt(bytes, 0, "RIFF") && hasAsciiAt(bytes, 8, "WEBP")) {
return { kind: "image", mimeType: "image/webp", ext: "webp" };
}
if (hasAsciiAt(bytes, 0, "GIF87a") || hasAsciiAt(bytes, 0, "GIF89a")) {
return { kind: "image", mimeType: "image/gif", ext: "gif" };
}
if (hasAsciiAt(bytes, 0, "BM")) {
return { kind: "image", mimeType: "image/bmp", ext: "bmp" };
}
if (
bytes.subarray(0, 4).equals(Buffer.from([0x49, 0x49, 0x2a, 0x00])) ||
bytes.subarray(0, 4).equals(Buffer.from([0x4d, 0x4d, 0x00, 0x2a]))
) {
return { kind: "image", mimeType: "image/tiff", ext: "tiff" };
}
if (looksLikeSvg(bytes, contentType)) {
return { kind: "image", mimeType: "image/svg+xml", ext: "svg" };
}
if (hasAsciiAt(bytes, 0, "RIFF") && hasAsciiAt(bytes, 8, "WAVE")) return {kind:"audio",mimeType:"audio/wav",ext:"wav"};
if (hasAsciiAt(bytes, 0, "ID3") || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0 && (bytes[1] & 0x06) !== 0)) return {kind:"audio",mimeType:"audio/mpeg",ext:"mp3"};
if (hasAsciiAt(bytes, 0, "OggS")) return {kind:"audio",mimeType:"audio/ogg",ext:"ogg"};
if (hasAsciiAt(bytes, 0, "fLaC")) return {kind:"audio",mimeType:"audio/flac",ext:"flac"};
if (getContentTypeMime(contentType).startsWith("audio/")) return {kind:"audio",mimeType:getContentTypeMime(contentType),ext:getContentTypeMime(contentType).includes("mp4") ? "m4a" : getContentTypeMime(contentType).split("/")[1]};
if (hasAsciiAt(bytes, 4, "ftyp")) {
const brand = bytes.subarray(8, Math.min(bytes.length, 32)).toString("latin1").toLowerCase();
if (brand.includes("m4a")) return {kind:"audio",mimeType:"audio/mp4",ext:"m4a"};
if (brand.includes("avif")) return { kind: "image", mimeType: "image/avif", ext: "avif" };
if (brand.includes("heic") || brand.includes("heif") || brand.includes("mif1")) {
return { kind: "image", mimeType: "image/heic", ext: "heic" };
}
return { kind: "video", mimeType: "video/mp4", ext: "mp4" };
}
if (bytes.subarray(0, 4).equals(Buffer.from([0x1a, 0x45, 0xdf, 0xa3]))) {
return { kind: "video", mimeType: "video/webm", ext: "webm" };
}
const mime = getContentTypeMime(contentType);
if (mime.startsWith("image/")) {
const ext = mime.includes("jpeg") ? "jpg" : mime.split("/")[1] || "png";
return { kind: "image", mimeType: mime, ext };
}
if (mime.startsWith("video/")) {
const ext = mime.includes("quicktime") ? "mov" : mime.split("/")[1] || "mp4";
return { kind: "video", mimeType: mime, ext };
}
return null;
}
export async function convertImageToPhotoshopPng(bytes: Buffer): Promise<Buffer> {
const sharp = await import("sharp");
const image = sharp.default(bytes, {
animated: false,
failOn: "none",
limitInputPixels: false,
});
const metadata = await image.metadata();
if (!metadata.width || !metadata.height) {
throw new Error("无法解析图片尺寸");
}
// RGB/RGBA, 8-bit, single-frame PNG is already compatible; preserve its exact bytes.
const rgb = (metadata.space === "srgb" && metadata.depth === "uchar")
|| (metadata.space === "rgb16" && metadata.depth === "ushort");
if (metadata.format === "png" && rgb
&& !metadata.isPalette && (metadata.pages || 1) === 1 && (!metadata.orientation || metadata.orientation === 1)) return bytes;
const output = image.rotate().toColorspace("srgb");
if (metadata.icc) output.withIccProfile("srgb");
return output.png({ compressionLevel: 3, adaptiveFiltering: true }).toBuffer();
}
function buildCanvasAssetFilename(params: {
item: DownloadFileItem;
index: number;
ext: string;
includeSequencePrefix: boolean;
}) {
const baseName = sanitizeCanvasDownloadFileName(
params.item.name || `canvas-image-${params.index + 1}`,
`canvas-image-${params.index + 1}`
);
if (!params.includeSequencePrefix) {
return `${baseName}.${params.ext}`;
}
const sequencePrefix = String(params.index + 1).padStart(3, "0");
return `${sequencePrefix}-${baseName}.${params.ext}`;
}
export async function normalizeCanvasDownloadAsset(params: {
item: DownloadFileItem;
index: number;
bytes: Buffer;
contentType: string;
includeSequencePrefix: boolean;
}, convert = convertImageToPhotoshopPng): Promise<CanvasDownloadAssetResult> {
if (params.bytes.length === 0) {
throw new Error("empty response");
}
if (looksLikeErrorDocument(params.bytes, params.contentType) && !looksLikeSvg(params.bytes, params.contentType)) {
throw new Error("源地址返回的不是图片文件");
}
const detected = detectAsset(params.bytes, params.contentType);
if (!detected) {
throw new Error("无法识别图片格式");
}
if (detected.kind !== "image") {
return {
ok: true,
filename: buildCanvasAssetFilename({
item: params.item,
index: params.index,
ext: detected.ext,
includeSequencePrefix: params.includeSequencePrefix,
}),
bytes: params.bytes,
contentType: detected.mimeType,
};
}
const pngBytes = await convert(params.bytes);
return {
ok: true,
filename: buildCanvasAssetFilename({
item: params.item,
index: params.index,
ext: "png",
includeSequencePrefix: params.includeSequencePrefix,
}),
bytes: pngBytes,
contentType: "image/png",
};
}