summaryrefslogtreecommitdiff
path: root/src/clients/Multer.ts
blob: 81f2b0fac88cb354dcc57fd5a1eccf03891e4ccd (plain)
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
// Copyright 2022 NotDankEnough (ilotterytea)
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import multer from "multer";
import mime from "mime";
import crypto from "crypto";
import { readdirSync } from "fs";

const fileFilter = (req: Express.Request, res: Express.Response, cb: multer.FileFilterCallback) => {
    cb(null, true);
}

const storage = multer.diskStorage({
    destination: "static/images",
    filename(req, file, callback) {
        if (!req.headers["pattern"]) req.headers["pattern"] = "random";

        switch (req.headers["pattern"]) {
            case "numeration": {
                const img_id: number = readdirSync("images").length + 1;
                const max_zero: number = 5;
                var blank_string: string = "";

                for (var i = 0; i < max_zero; i++) { blank_string = blank_string + "0"; }

                blank_string = blank_string.slice(img_id.toString().length, blank_string.length);

                callback(null, `${blank_string}${img_id.toString()}.${mime.getExtension(file.mimetype)}`);
                break;
            }
            case "random": {
                crypto.randomBytes(5, (err, raw) => {
                    if (err) return callback(err, "");
                    callback(null, `${raw.toString("hex")}.${mime.getExtension(file.mimetype)}`)
                });
                break;
            }
            default: {
                crypto.randomBytes(5, (err, raw) => {
                    if (err) return callback(err, "");
                    callback(null, `${raw.toString("hex")}.${mime.getExtension(file.mimetype)}`)
                });
                break;
            }
        }
    }
});

const Multer = multer({
    fileFilter: fileFilter,
    storage: storage,
    limits: {
        fieldSize: 1.6e+7
    }
});

export default Multer;