aboutsummaryrefslogtreecommitdiffstats
path: root/lib/upload.js
diff options
context:
space:
mode:
Diffstat (limited to 'lib/upload.js')
-rw-r--r--lib/upload.js66
1 files changed, 42 insertions, 24 deletions
diff --git a/lib/upload.js b/lib/upload.js
index 4deaa130..ceead928 100644
--- a/lib/upload.js
+++ b/lib/upload.js
@@ -1,30 +1,48 @@
-import { auth } from "./passport";
import app from "$app";
-import multer from "multer";
+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";
-const storage = multer.diskStorage({
- destination: (req, file, cb) => {
- cb(null, "uploads");
- },
- filename: async (req, file, cb) => {
- const parts = file.originalname.split(".");
- const ext = parts.length > 1 ? parts[parts.length - 1] : "bin";
- cb(null, `${req.user.username}-${file.fieldname}.${ext}`);
- }
-});
+app.register(fastifyMultipart);
-export const upload = multer({
- storage,
- onFileUploadStart: (file, req, res) => {
- console.log("CHECKING SIZE");
- const maxSize = 32 * 1000 * 1000;
- if (req.files.file.length > maxSize) {
- return false;
- }
- }
+app.register(fastifyStatic, {
+ root: path.join("/app/uploads"),
+ prefix: "/public/"
});
-app.post("/profile", auth, upload.single("squirt"), async (req, res) => {
- let { filename } = req.file;
- res.send({ filename });
+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}.png`;
+ let path = `/app/uploads/${name}`;
+
+ await new Promise(resolve =>
+ s2.pipe(fs.createWriteStream(path).on("finish", resolve))
+ );
+
+ req.user[type] = true;
+ await req.user.save();
+
+ res.send(name);
+ } catch (e) {
+ console.log(e);
+ return res.status(500).send(e);
+ }
});