aboutsummaryrefslogtreecommitdiffstats
path: root/lib/upload.js
blob: 8d1c85efe5abdf28b74609001e0bd9cc8561c1de (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
import app from "$app";
import { auth } from "./passport";
import fastifyMultipart from "@fastify/multipart";
import fastifyStatic from "@fastify/static";
import { fileTypeFromStream } from "file-type";
import pump from "pump";
import Clone from "readable-stream-clone";
import fs from "fs";
import path from "path";
import sharp from "sharp";
import { pipeline } from "stream";

app.register(fastifyMultipart);

app.register(fastifyStatic, {
  root: path.join("/app/uploads"),
  prefix: "/public/"
});

app.post("/upload/:type", auth, async function(req, res) {
  try {
    let { type } = req.params;
    if (!["banner", "profile"].includes(type))
      throw new Error("invalid upload");

    let data = await req.file();
    let s1 = new Clone(data.file);
    let s2 = new Clone(data.file);

    let [format, ext] = (await fileTypeFromStream(s1)).mime.split("/");

    if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext))
      throw new Error("unsupported file type");

    let name = `${req.user.username}-${type}.webp`;
    let path = `/app/uploads/${name}`;
    let size = type === "banner" ? 1920 : 240;

    let t = sharp()
      .rotate()
      .resize(size)
      .webp();

    await new Promise(r => pipeline(s2, t, fs.createWriteStream(path), r));

    req.user[type] = true;
    await req.user.save();

    res.send(name);
  } catch (e) {
    console.log(e);
    return res.code(500).send(e);
  }
});