105 lines
2.6 KiB
TypeScript
Raw Normal View History

import { FreshContext, Handlers } from "$fresh/server.ts";
import * as cache from "@lib/cache/image.ts";
2023-08-01 17:50:00 +02:00
import { SILVERBULLET_SERVER } from "@lib/env.ts";
2023-08-05 22:16:14 +02:00
import { createLogger } from "@lib/log.ts";
import { isLocalImage } from "@lib/string.ts";
2023-08-02 02:24:08 +02:00
2023-08-05 22:16:14 +02:00
const log = createLogger("api/image");
// Constants for image processing
const CONFIG = {
maxDimension: 2048,
minDimension: 1,
acceptedMimeTypes: new Set([
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
]),
};
2023-07-26 15:48:03 +02:00
interface ImageParams {
image: string;
height: number;
width: number;
2023-07-26 15:48:03 +02:00
}
/**
* Validates and parses URL parameters for image processing
*/
function parseParams(reqUrl: URL): ImageParams | string {
try {
const image = reqUrl.searchParams.get("image")?.replace(/^\//, "");
if (!image) {
return "Missing 'image' query parameter.";
2023-08-09 13:32:28 +02:00
}
// Parse dimensions with defaults
const height = Math.floor(Number(reqUrl.searchParams.get("height")) || 0);
const width = Math.floor(Number(reqUrl.searchParams.get("width")) || 0);
2023-07-26 15:48:03 +02:00
// Validate dimensions
if (height < 0 || width < 0) {
return "Negative height or width is not supported.";
}
if (height > CONFIG.maxDimension || width > CONFIG.maxDimension) {
return `Width and height cannot exceed ${CONFIG.maxDimension}.`;
}
2023-07-26 15:48:03 +02:00
// If dimensions are provided, ensure they're not too small
if (
(height > 0 && height < CONFIG.minDimension) ||
(width > 0 && width < CONFIG.minDimension)
) {
return `Dimensions must be at least ${CONFIG.minDimension} pixel.`;
}
2023-08-02 02:24:08 +02:00
return { image, height, width };
} catch (error) {
log.error("Error parsing parameters:", error);
return "Invalid parameters provided.";
2023-08-02 02:24:08 +02:00
}
}
2023-08-01 17:50:00 +02:00
const GET = async (
req: Request,
_ctx: FreshContext,
2023-07-26 13:47:01 +02:00
): Promise<Response> => {
try {
const url = new URL(req.url);
const params = parseParams(url);
if (typeof params === "string") {
return new Response(params, {
status: 400,
headers: { "Content-Type": "text/plain" },
});
}
2023-07-26 15:48:03 +02:00
const imageUrl = isLocalImage(params.image)
? `${SILVERBULLET_SERVER}/${params.image.replace(/^\//, "")}`
: params.image;
2023-07-26 15:48:03 +02:00
log.debug("Processing image request:", { imageUrl, params });
const image = await cache.getImageContent(imageUrl, params);
return new Response(image.content, {
headers: {
"Content-Type": image.mimeType,
},
});
} catch (error) {
log.error("Error processing image:", error);
return new Response("Internal server error", {
status: 500,
headers: { "Content-Type": "text/plain" },
});
}
2023-07-26 13:47:01 +02:00
};
2023-08-01 17:50:00 +02:00
export const handler: Handlers = {
GET,
};