summary refs log tree commit diff
path: root/cdn/src
diff options
context:
space:
mode:
authorMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-07-24 13:45:46 +1000
committerMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-07-24 13:45:46 +1000
commite304ee320321247fda3814ca79718465c924cbd8 (patch)
treef28c8cf91b4ff7d399ca42795443afc67b986a8d /cdn/src
parentMerge branch 'feat/notesTable' into slowcord (diff)
downloadserver-e304ee320321247fda3814ca79718465c924cbd8.tar.xz
Really shitty external image resizing
Diffstat (limited to 'cdn/src')
-rw-r--r--cdn/src/routes/external.ts38
1 files changed, 37 insertions, 1 deletions
diff --git a/cdn/src/routes/external.ts b/cdn/src/routes/external.ts
index dc90e3c8..65b8bcb1 100644
--- a/cdn/src/routes/external.ts
+++ b/cdn/src/routes/external.ts
@@ -3,8 +3,9 @@ import fetch from "node-fetch";
 import { HTTPError } from "lambert-server";
 import { Snowflake } from "@fosscord/util";
 import { storage } from "../util/Storage";
-import FileType from "file-type";
+import FileType, { stream } from "file-type";
 import { Config } from "@fosscord/util";
+import sharp from "sharp";
 
 // TODO: somehow handle the deletion of images posted to the /external route
 
@@ -56,4 +57,39 @@ router.get("/:id", async (req: Request, res: Response) => {
 	return res.send(file);
 });
 
+// this method is gross lol don't care
+router.get("/resize/:url", async (req: Request, res: Response) => {
+	const url = decodeURIComponent(req.params.url);
+	const { width, height } = req.query;
+	if (!width || !height) throw new HTTPError("Must provide width and height");
+	const w = parseInt(width as string);
+	const h = parseInt(height as string);
+	if (w < 1 || h < 1) throw new HTTPError("Width and height must be greater than 0");
+
+	const { resizeHeightMax, resizeWidthMax } = Config.get().cdn;
+	if (resizeHeightMax && resizeWidthMax &&
+		(w > resizeWidthMax || h > resizeHeightMax))
+		throw new HTTPError(`Width and height must not exceed ${resizeWidthMax}, ${resizeHeightMax}`);
+
+	let buffer;
+	try {
+		const response = await fetch(url, DEFAULT_FETCH_OPTIONS);
+		buffer = await response.buffer();
+	}
+	catch (e) {
+		throw new HTTPError("Couldn't fetch website");
+	}
+
+	const resizedBuffer = await sharp(buffer)
+		.resize(parseInt(width as string), parseInt(height as string), {
+			fit: "inside",
+		})
+		.png()
+		.toBuffer();
+
+	res.setHeader("Content-Disposition", "attachment");
+	res.setHeader("Content-Type", "image/png");
+	return res.end(resizedBuffer);
+});
+
 export default router;