180 lines
6.0 KiB
TypeScript
180 lines
6.0 KiB
TypeScript
import { createCanvas, loadImage, GlobalFonts } from "@napi-rs/canvas";
|
|
import { createWriteStream } from "node:fs";
|
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { finished } from "node:stream/promises";
|
|
import { createZipArchive } from "@/lib/create-zip";
|
|
import { drawIdText } from "@/lib/draw-id";
|
|
import { isPresetFont } from "@/lib/fonts";
|
|
import {
|
|
CUSTOM_FONT_FAMILY,
|
|
formatUserId,
|
|
MAX_FONT_BYTES,
|
|
MAX_IMAGE_BYTES,
|
|
parseGenerateConfig,
|
|
sanitizeFilename,
|
|
toIdDrawStyle,
|
|
} from "@/lib/id-config";
|
|
import { saveJob } from "@/lib/jobs";
|
|
import type { GenerateProgressEvent } from "@/lib/progress";
|
|
import { registerPresetFonts } from "@/lib/register-fonts";
|
|
|
|
export const runtime = "nodejs";
|
|
export const maxDuration = 300;
|
|
export const dynamic = "force-dynamic";
|
|
|
|
function jsonError(message: string, status = 400): Response {
|
|
return Response.json({ error: message }, { status });
|
|
}
|
|
|
|
export async function POST(req: Request): Promise<Response> {
|
|
try {
|
|
const form = await req.formData();
|
|
const imageFile = form.get("image");
|
|
const fontFile = form.get("font");
|
|
const configRaw = form.get("config");
|
|
|
|
if (!(imageFile instanceof File)) {
|
|
return jsonError("A base image is required");
|
|
}
|
|
if (imageFile.size === 0) {
|
|
return jsonError("The base image is empty");
|
|
}
|
|
if (imageFile.size > MAX_IMAGE_BYTES) {
|
|
return jsonError("Base image must be 10MB or smaller");
|
|
}
|
|
if (typeof configRaw !== "string") {
|
|
return jsonError("Missing generate config");
|
|
}
|
|
|
|
let config;
|
|
try {
|
|
config = parseGenerateConfig(JSON.parse(configRaw));
|
|
} catch (error) {
|
|
const message =
|
|
error instanceof Error ? error.message : "Invalid generate config";
|
|
return jsonError(message);
|
|
}
|
|
|
|
if (config.useCustomFont) {
|
|
if (!(fontFile instanceof File) || fontFile.size === 0) {
|
|
return jsonError("Custom font file is required when using a custom font");
|
|
}
|
|
if (fontFile.size > MAX_FONT_BYTES) {
|
|
return jsonError("Custom font must be 5MB or smaller");
|
|
}
|
|
} else if (!isPresetFont(config.fontFamily)) {
|
|
return jsonError("Unknown font family");
|
|
}
|
|
|
|
const encoder = new TextEncoder();
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
async start(controller) {
|
|
let tmpDir: string | null = null;
|
|
const send = (event: GenerateProgressEvent) => {
|
|
controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));
|
|
};
|
|
|
|
try {
|
|
tmpDir = await mkdtemp(path.join(tmpdir(), "kk-card-"));
|
|
const pngDir = path.join(tmpDir, "png");
|
|
await mkdir(pngDir);
|
|
|
|
registerPresetFonts();
|
|
const style = toIdDrawStyle(config);
|
|
|
|
if (config.useCustomFont && fontFile instanceof File) {
|
|
const ext = fontFile.name.toLowerCase().endsWith(".otf")
|
|
? ".otf"
|
|
: ".ttf";
|
|
const fontPath = path.join(tmpDir, `custom${ext}`);
|
|
await writeFile(fontPath, Buffer.from(await fontFile.arrayBuffer()));
|
|
GlobalFonts.registerFromPath(fontPath, CUSTOM_FONT_FAMILY);
|
|
}
|
|
|
|
const image = await loadImage(
|
|
Buffer.from(await imageFile.arrayBuffer()),
|
|
);
|
|
const canvas = createCanvas(image.width, image.height);
|
|
const ctx = canvas.getContext("2d");
|
|
const usedNames = new Set<string>();
|
|
const files: { name: string; path: string }[] = [];
|
|
|
|
for (let i = 0; i < config.count; i += 1) {
|
|
const id = formatUserId(
|
|
config.prefix,
|
|
config.start + i,
|
|
config.pad,
|
|
config.suffix,
|
|
);
|
|
let name = `${sanitizeFilename(id)}.png`;
|
|
if (usedNames.has(name)) {
|
|
name = `${sanitizeFilename(id)}-${i}.png`;
|
|
}
|
|
usedNames.add(name);
|
|
|
|
ctx.drawImage(image, 0, 0);
|
|
drawIdText(ctx, id, image.width, image.height, style);
|
|
const png = await canvas.encode("png");
|
|
const filePath = path.join(pngDir, name);
|
|
await writeFile(filePath, png);
|
|
files.push({ name, path: filePath });
|
|
send({ phase: "generate", current: i + 1, total: config.count });
|
|
}
|
|
|
|
send({ phase: "zip", current: 0, total: files.length });
|
|
|
|
const zipPath = path.join(tmpDir, "ids.zip");
|
|
const output = createWriteStream(zipPath);
|
|
const archive = createZipArchive();
|
|
archive.on("error", (error: Error) => {
|
|
output.destroy(error);
|
|
});
|
|
archive.on("progress", (progress) => {
|
|
send({
|
|
phase: "zip",
|
|
current: progress.entries.processed,
|
|
total: Math.max(progress.entries.total, files.length),
|
|
});
|
|
});
|
|
archive.pipe(output);
|
|
|
|
for (const file of files) {
|
|
archive.file(file.path, { name: file.name });
|
|
}
|
|
|
|
await archive.finalize();
|
|
await finished(output);
|
|
send({ phase: "zip", current: files.length, total: files.length });
|
|
|
|
const id = saveJob(tmpDir, zipPath);
|
|
tmpDir = null;
|
|
send({ phase: "done", id });
|
|
controller.close();
|
|
} catch (error) {
|
|
if (tmpDir) {
|
|
await rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
|
}
|
|
const message =
|
|
error instanceof Error ? error.message : "Failed to generate images";
|
|
send({ phase: "error", message });
|
|
controller.close();
|
|
}
|
|
},
|
|
});
|
|
|
|
return new Response(stream, {
|
|
headers: {
|
|
"Content-Type": "application/x-ndjson",
|
|
"Cache-Control": "no-store",
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
});
|
|
} catch (error) {
|
|
const message =
|
|
error instanceof Error ? error.message : "Failed to generate images";
|
|
return jsonError(message, 500);
|
|
}
|
|
}
|