ai-chatbot/lib/video-canvas/media-import.ts

43 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { IMAGE_UPLOAD_TOO_LARGE_MESSAGE, isImageUploadTooLarge } from "@/lib/image-upload-limits";
const mimeByExtension: Record<string, string> = {
jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", webp: "image/webp",
avif: "image/avif", tif: "image/tiff", tiff: "image/tiff", svg: "image/svg+xml",
heic: "image/heic", heif: "image/heif",
mp4: "video/mp4", mov: "video/quicktime", webm: "video/webm",
mp3: "audio/mpeg", m4a: "audio/mp4", wav: "audio/wav", ogg: "audio/ogg", flac: "audio/flac",
};
const acceptedTypes = new Set([...Object.values(mimeByExtension), "image/jpg", "image/x-tiff", "audio/mp3", "audio/x-m4a", "audio/x-wav", "audio/webm"]);
// Finder and some browsers provide no MIME type. Only infer it for known extensions;
// the upload endpoints still validate/decode the actual file contents.
export function prepareCanvasMediaFiles(input: File[]) {
const files: File[] = [], errors: string[] = [];
for (const file of input) {
const originalType = file.type.toLowerCase();
const type = !originalType || originalType === "application/octet-stream"
? mimeByExtension[file.name.split(".").pop()?.toLowerCase() || ""]
: originalType;
if (!type || !acceptedTypes.has(type)) {
errors.push(`${file.name}:不支持此格式,请拖入图片、MP4/MOV/WebM 视频或音频文件`);
} else if (!file.size) {
errors.push(`${file.name}:文件为空,请选择完整素材`);
} else if (type.startsWith("image/") && isImageUploadTooLarge(file.size)) {
errors.push(`${file.name}:${IMAGE_UPLOAD_TOO_LARGE_MESSAGE}`);
} else if (!type.startsWith("image/") && file.size > 125 * 1024 * 1024) {
errors.push(`${file.name}:音视频不能超过 125 MiB`);
} else {
files.push(type === file.type ? file : new File([file], file.name, { type, lastModified: file.lastModified }));
}
}
if (files.length > 10) errors.push("每次最多导入 10 个素材,其余文件请分批拖入");
return { files: files.slice(0, 10), errors };
}
export function canvasMediaType(file: File): "image" | "video" | "audio" {
if (file.type.startsWith("image/")) return "image";
if (file.type.startsWith("video/")) return "video";
if (file.type.startsWith("audio/")) return "audio";
throw Error(`${file.name}:不支持此素材格式`);
}