summary refs log tree commit diff
path: root/src/cdn/routes/external.ts
diff options
context:
space:
mode:
authorMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-08-30 15:05:23 +1000
committerMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2022-08-30 15:08:18 +1000
commit16315a3170ec018a834e68360e06b506415446d2 (patch)
tree90cfe456040fce35b904e88462886e3c73a2f3f2 /src/cdn/routes/external.ts
parentStart listening after database and config has been loaded (diff)
parentOop, deprecated typeorm call (diff)
downloadserver-16315a3170ec018a834e68360e06b506415446d2.tar.xz
Merge branch 'staging' into dev/Maddy/fix/listeningAfterDb
Diffstat (limited to 'src/cdn/routes/external.ts')
-rw-r--r--src/cdn/routes/external.ts55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/cdn/routes/external.ts b/src/cdn/routes/external.ts
new file mode 100644
index 00000000..7ccf9b8a
--- /dev/null
+++ b/src/cdn/routes/external.ts
@@ -0,0 +1,55 @@
+import { Config, HTTPError, Snowflake } from "@fosscord/util";
+import { Request, Response, Router } from "express";
+import FileType from "file-type";
+import fetch from "node-fetch";
+import { storage } from "../util/Storage";
+
+// TODO: somehow handle the deletion of images posted to the /external route
+
+const router = Router();
+const DEFAULT_FETCH_OPTIONS: any = {
+	redirect: "follow",
+	follow: 1,
+	headers: {
+		"user-agent": "Mozilla/5.0 (compatible Fosscordbot/0.1; +https://fosscord.com)"
+	},
+	size: 1024 * 1024 * 8,
+	compress: true,
+	method: "GET"
+};
+
+router.post("/", async (req: Request, res: Response) => {
+	if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature");
+
+	if (!req.body) throw new HTTPError("Invalid Body");
+
+	const { url } = req.body;
+	if (!url || typeof url !== "string") throw new HTTPError("Invalid url");
+
+	const id = Snowflake.generate();
+
+	try {
+		const response = await fetch(url, DEFAULT_FETCH_OPTIONS);
+		const buffer = await response.buffer();
+
+		await storage.set(`/external/${id}`, buffer);
+
+		res.send({ id });
+	} catch (error) {
+		throw new HTTPError("Couldn't fetch website");
+	}
+});
+
+router.get("/:id", async (req: Request, res: Response) => {
+	const { id } = req.params;
+
+	const file = await storage.get(`/external/${id}`);
+	if (!file) throw new HTTPError("File not found");
+	const result = await FileType.fromBuffer(file);
+
+	res.set("Content-Type", result?.mime);
+
+	return res.send(file);
+});
+
+export default router;