summary refs log tree commit diff
path: root/src/cdn/routes/role-icons.ts
blob: 8040405a43adc93a2c6314c338ffee47327334ec (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
	Spacebar: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2023 Spacebar and Spacebar Contributors
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published
	by the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.
	
	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

import { Router, Response, Request } from "express";
import { Config, Snowflake } from "@spacebar/util";
import { storage } from "../util/Storage";
import FileType from "file-type";
import { HTTPError } from "lambert-server";
import crypto from "crypto";
import { multer } from "../util/multer";

//Role icons ---> avatars.ts modified

// TODO: check user rights and perks and animated pfp are allowed in the policies
// TODO: generate different sizes of icon
// TODO: generate different image types of icon

const STATIC_MIME_TYPES = [
	"image/png",
	"image/jpeg",
	"image/webp",
	"image/svg+xml",
	"image/svg",
];
const ALLOWED_MIME_TYPES = [...STATIC_MIME_TYPES];

const router = Router();

router.post(
	"/:role_id",
	multer.single("file"),
	async (req: Request, res: Response) => {
		if (req.headers.signature !== Config.get().security.requestSignature)
			throw new HTTPError("Invalid request signature");
		if (!req.file) throw new HTTPError("Missing file");
		const { buffer, size } = req.file;
		const { role_id } = req.params;

		const hash = crypto
			.createHash("md5")
			.update(Snowflake.generate())
			.digest("hex");

		const type = await FileType.fromBuffer(buffer);
		if (!type || !ALLOWED_MIME_TYPES.includes(type.mime))
			throw new HTTPError("Invalid file type");

		const path = `role-icons/${role_id}/${hash}.png`;
		const endpoint =
			Config.get().cdn.endpointPublic || "http://localhost:3001";

		await storage.set(path, buffer);

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

router.get("/:role_id", async (req: Request, res: Response) => {
	const { role_id } = req.params;
	//role_id = role_id.split(".")[0]; // remove .file extension
	const path = `role-icons/${role_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);
	res.set("Cache-Control", "public, max-age=31536000, must-revalidate");

	return res.send(file);
});

router.get("/:role_id/:hash", async (req: Request, res: Response) => {
	const { role_id, hash } = req.params;
	//hash = hash.split(".")[0]; // remove .file extension
	const requested_extension = hash.split(".")[1];
	const role_icon_hash = hash.split(".")[0];
	let file: Buffer | null = null;

	const extensions_to_try = [
		requested_extension,
		"png",
		"jpg",
		"jpeg",
		"webp",
		"svg",
	];

	for (let i = 0; i < extensions_to_try.length; i++) {
		file = await storage.get(
			`role-icons/${role_id}/${role_icon_hash}.${extensions_to_try[i]}`,
		);
		if (file) break;
	}

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

	res.set("Content-Type", type?.mime);
	res.set("Cache-Control", "public, max-age=31536000, must-revalidate");

	return res.send(file);
});

router.delete("/:role_id/:id", async (req: Request, res: Response) => {
	if (req.headers.signature !== Config.get().security.requestSignature)
		throw new HTTPError("Invalid request signature");
	const { role_id, id } = req.params;
	const path = `role-icons/${role_id}/${id}`;

	await storage.delete(path);

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

export default router;