summary refs log tree commit diff
path: root/src/cdn/routes/splashes.ts
blob: 21556167ecec33acf30d885e886487357b3e9461 (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
/*
	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 crypto from "node:crypto";
import { fileTypeFromBuffer } from "file-type";
import { HTTPError } from "lambert-server/HTTPError";
import { Config } from "@spacebar/util";
import { storage, multer, cache, cacheNotFound } from "@spacebar/cdn/util";

// TODO: check premium and animated pfp are allowed in the config
// TODO: generate different sizes of icon
// TODO: generate different image types of icon
// TODO: delete old icons

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

const router = Router({ mergeParams: true });

const pathPrefix = "splashes";
router.post("/:guild_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 { guild_id } = req.params as { [key: string]: string };

    let hash = crypto.createHash("md5").update(buffer).digest("hex");

    const type = await fileTypeFromBuffer(buffer);
    if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) throw new HTTPError("Invalid file type");
    if (ANIMATED_MIME_TYPES.includes(type.mime)) hash = `a_${hash}`; // animated icons have a_ infront of the hash

    const path = `${pathPrefix}/${guild_id}/${hash}`;
    const endpoint = Config.get().cdn.endpointPublic;

    await storage.set(path, buffer);

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

router.get("/:guild_id", cache, async (req: Request, res: Response) => {
    let { guild_id } = req.params as { [key: string]: string };
    guild_id = guild_id.split(".")[0]; // remove .file extension
    const path = `${pathPrefix}/${guild_id}`;

    const file = await storage.get(path);
    if (!file) return cacheNotFound(req, res);
    const type = await fileTypeFromBuffer(file);

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

    return res.send(file);
});

export const getAvatar = async (req: Request, res: Response) => {
    const { guild_id } = req.params as { [key: string]: string };
    let { hash } = req.params as { [key: string]: string };
    hash = hash.split(".")[0]; // remove .file extension
    const path = `${pathPrefix}/${guild_id}/${hash}`;

    const file = await storage.get(path);
    if (!file) return cacheNotFound(req, res);
    const type = await fileTypeFromBuffer(file);

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

    return res.send(file);
};

router.get("/:guild_id/:hash", cache, getAvatar);

router.delete("/:guild_id/:id", async (req: Request, res: Response) => {
    if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature");
    const { guild_id, id } = req.params as { [key: string]: string };
    const path = `${pathPrefix}/${guild_id}/${id}`;

    await storage.delete(path);

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

export default router;