summary refs log tree commit diff
path: root/src/routes/avatars.ts
blob: c447db9fa31798f664b362dafdee087869631bc0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { Router } from "express";
import { Config, Snowflake } from "@fosscord/server-util";
import { storage } from "../util/Storage";
import FileType from "file-type";
import { HTTPError } from "lambert-server";
import { multer } from "../Server";

// TODO: check premium and animated pfp are allowed in the config
// TODO: generate different sizes of avatar
// TODO: generate different image types of avatar
// TODO: delete old avatars
// TODO: check request signature for modify methods

const ANIMATED_MIME_TYPES = ["image/apng", "image/gif", "image/gifv"];
const STATIC_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"];
const ALLOWED_MIME_TYPES = [...ANIMATED_MIME_TYPES, ...STATIC_MIME_TYPES];

const router = Router();

router.post("/:user_id", multer.single("file"), async (req, res) => {
	const { buffer, mimetype, size, originalname, fieldname } = req.file;
	const { user_id } = req.params;

	const id = Snowflake.generate();

	const type = await FileType.fromBuffer(buffer);
	if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) throw new HTTPError("Invalid file type");
	const path = `avatars/${user_id}/${id}`;
	const endpoint = Config.get().cdn.endpoint || "http://localhost:3003";

	await storage.set(path, buffer);

	return res.json({
		id,
		content_type: type.mime,
		size,
		url: `${endpoint}/path`,
	});
});

router.get("/:user_id/:id", async (req, res) => {
	const { user_id, id } = req.params;
	const path = `avatars/${user_id}/${id}`;

	const file = await storage.get(path);
	if (!file) throw new HTTPError("not found", 404);
	const type = await FileType.fromBuffer(file);

	res.set("Content-Type", type?.mime);

	return res.send(file);
});

router.delete("/:user_id/:id", async (req, res) => {
	const { user_id, id } = req.params;
	const path = `avatars/${user_id}/${id}`;

	await storage.delete(path);

	return res.send({ success: true });
});

export default router;