2024-12-30 20:18:48 +01:00
|
|
|
import { apiRoute } from "@/api";
|
2025-02-05 21:49:39 +01:00
|
|
|
import { createRoute, z } from "@hono/zod-openapi";
|
2024-12-30 18:00:23 +01:00
|
|
|
import { ApiError } from "~/classes/errors/api-error";
|
2023-11-29 01:34:09 +01:00
|
|
|
|
2024-12-30 20:26:56 +01:00
|
|
|
const schemas = {
|
2024-05-06 09:16:33 +02:00
|
|
|
param: z.object({
|
2024-06-14 11:55:39 +02:00
|
|
|
hash: z.string(),
|
2024-06-14 11:54:47 +02:00
|
|
|
name: z.string(),
|
2024-05-06 09:16:33 +02:00
|
|
|
}),
|
|
|
|
|
header: z.object({
|
|
|
|
|
range: z.string().optional().default(""),
|
|
|
|
|
}),
|
|
|
|
|
};
|
|
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
const route = createRoute({
|
|
|
|
|
method: "get",
|
|
|
|
|
path: "/media/{hash}/{name}",
|
|
|
|
|
summary: "Get media file by hash and name",
|
|
|
|
|
request: {
|
|
|
|
|
params: schemas.param,
|
|
|
|
|
headers: schemas.header,
|
|
|
|
|
},
|
|
|
|
|
responses: {
|
|
|
|
|
200: {
|
|
|
|
|
description: "Media",
|
|
|
|
|
content: {
|
|
|
|
|
"*": {
|
|
|
|
|
schema: z.any(),
|
|
|
|
|
},
|
|
|
|
|
},
|
2024-05-06 09:16:33 +02:00
|
|
|
},
|
2024-09-16 15:29:09 +02:00
|
|
|
404: {
|
|
|
|
|
description: "File not found",
|
|
|
|
|
content: {
|
|
|
|
|
"application/json": {
|
2025-03-24 14:42:09 +01:00
|
|
|
schema: ApiError.zodSchema,
|
2024-09-16 15:29:09 +02:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export default apiRoute((app) =>
|
|
|
|
|
app.openapi(route, async (context) => {
|
|
|
|
|
const { hash, name } = context.req.valid("param");
|
|
|
|
|
const { range } = context.req.valid("header");
|
|
|
|
|
|
|
|
|
|
// parse `Range` header
|
|
|
|
|
const [start = 0, end = Number.POSITIVE_INFINITY] = (
|
|
|
|
|
range
|
|
|
|
|
.split("=") // ["Range: bytes", "0-100"]
|
|
|
|
|
.at(-1) || ""
|
|
|
|
|
) // "0-100"
|
|
|
|
|
.split("-") // ["0", "100"]
|
|
|
|
|
.map(Number); // [0, 100]
|
|
|
|
|
|
|
|
|
|
// Serve file from filesystem
|
|
|
|
|
const file = Bun.file(`./uploads/${hash}/${name}`);
|
|
|
|
|
|
|
|
|
|
const buffer = await file.arrayBuffer();
|
|
|
|
|
|
|
|
|
|
if (!(await file.exists())) {
|
2024-12-30 18:00:23 +01:00
|
|
|
throw new ApiError(404, "File not found");
|
2024-09-16 15:29:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Can't directly copy file into Response because this crashes Bun for now
|
2024-12-07 12:20:06 +01:00
|
|
|
return context.body(buffer, 200, {
|
2024-09-16 15:29:09 +02:00
|
|
|
"Content-Type": file.type || "application/octet-stream",
|
|
|
|
|
"Content-Length": `${file.size - start}`,
|
|
|
|
|
"Content-Range": `bytes ${start}-${end}/${file.size}`,
|
|
|
|
|
// biome-ignore lint/suspicious/noExplicitAny: Hono doesn't type this response so this has a TS error
|
|
|
|
|
}) as any;
|
|
|
|
|
}),
|
2024-08-19 20:06:38 +02:00
|
|
|
);
|