iceshrimp/packages/backend/src/server/api/mastodon/endpoints/media.ts

92 lines
2.5 KiB
TypeScript
Raw Normal View History

import Router from "@koa/router";
import { convertId, IdType } from "@/misc/convert-id.js";
import { convertAttachment } from "@/server/api/mastodon/converters.js";
import multer from "@koa/multer";
2023-09-29 21:39:02 +02:00
import authenticate from "@/server/api/authenticate.js";
import { MediaHelpers } from "@/server/api/mastodon/helpers/media.js";
import { FileConverter } from "@/server/api/mastodon/converters/file.js";
export function setupEndpointsMedia(router: Router, fileRouter: Router, upload: multer.Instance): void {
router.get<{ Params: { id: string } }>("/v1/media/:id", async (ctx) => {
try {
2023-09-29 21:24:16 +02:00
const auth = await authenticate(ctx.headers.authorization, null);
const user = auth[0] ?? null;
if (!user) {
ctx.status = 401;
return;
}
const id = convertId(ctx.params.id, IdType.IceshrimpId);
2023-09-29 21:37:35 +02:00
const file = await MediaHelpers.getMediaPacked(user, id);
2023-09-29 21:24:16 +02:00
if (!file) {
ctx.status = 404;
ctx.body = { error: "File not found" };
return;
}
const attachment = FileConverter.encode(file);
ctx.body = convertAttachment(attachment);
} catch (e: any) {
console.error(e);
2023-09-29 21:24:16 +02:00
ctx.status = 500;
ctx.body = e.response.data;
}
});
router.put<{ Params: { id: string } }>("/v1/media/:id", async (ctx) => {
try {
2023-09-29 21:37:35 +02:00
const auth = await authenticate(ctx.headers.authorization, null);
const user = auth[0] ?? null;
if (!user) {
ctx.status = 401;
return;
}
const id = convertId(ctx.params.id, IdType.IceshrimpId);
const file = await MediaHelpers.getMedia(user, id);
if (!file) {
ctx.status = 404;
ctx.body = { error: "File not found" };
return;
}
const result = await MediaHelpers.updateMedia(user, file, ctx.request.body)
.then(p => FileConverter.encode(p));
ctx.body = convertAttachment(result);
} catch (e: any) {
console.error(e);
ctx.status = 401;
ctx.body = e.response.data;
}
});
2023-09-29 21:39:02 +02:00
fileRouter.post(["/v2/media", "/v1/media"], upload.single("file"), async (ctx) => {
try {
2023-09-29 21:39:02 +02:00
const auth = await authenticate(ctx.headers.authorization, null);
const user = auth[0] ?? null;
if (!user) {
ctx.status = 401;
return;
}
2023-09-29 21:39:02 +02:00
const file = await ctx.file;
if (!file) {
ctx.body = { error: "No image" };
2023-09-29 21:39:02 +02:00
ctx.status = 400;
return;
}
2023-09-29 21:39:02 +02:00
const result = await MediaHelpers.uploadMedia(user, file, ctx.request.body)
.then(p => FileConverter.encode(p));
ctx.body = convertAttachment(result);
} catch (e: any) {
console.error(e);
2023-09-29 21:39:02 +02:00
ctx.status = 500;
ctx.body = { error: e.message };
}
});
}