-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
70 lines (65 loc) · 2.18 KB
/
index.ts
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
69
70
import express, { Express, Request, Response } from "express";
import cors from "cors";
import axios from "axios";
const fs = require("fs");
const { http, https } = require("follow-redirects");
const environment = require("./environment");
const crypto = require("crypto");
const app = express();
const PORT = environment.port;
const validExtensions = environment.validFormats;
app.use(cors());
app.get("/", async (req: Request, res: Response) => {
if (req.query?.media) {
try {
const mediaLink: string = req.query.media as string;
const mediaLinkArray = mediaLink.split(".");
let linkExtension =
mediaLinkArray[mediaLinkArray.length - 1].toLowerCase();
// calckey images have no extension
if (validExtensions.indexOf(linkExtension) === -1) {
linkExtension = "";
}
const mediaLinkHash = crypto
.createHash("sha256")
.update(mediaLink)
.digest("hex");
const localFileName = linkExtension
? `cache/${mediaLinkHash}.${linkExtension}`
: `cache/${mediaLinkHash}`;
if (fs.existsSync(localFileName)) {
// We have the image! we just serve it
res.set("Cache-control", "public, max-age=36000");
res.sendFile(localFileName, { root: "." });
} else {
// its downloading time!
try {
const remoteResponse = await axios.get(mediaLink, {
responseType: "stream",
headers: { "User-Agent": "wafrn-cache-generator" },
});
const path = `${__dirname}/${localFileName}`;
const filePath = fs.createWriteStream(path);
filePath.on("finish", () => {
filePath.close();
res.set("Cache-control", "public, max-age=36000");
res.sendFile(localFileName, { root: "." });
});
remoteResponse.data.pipe(filePath);
} catch (error) {
console.log(error);
res.sendStatus(404);
}
}
} catch (error) {
res.sendStatus(500);
res.send();
console.log(error);
}
} else {
res.sendStatus(404);
}
});
app.listen(PORT, "0.0.0.0", () => {
console.log(`⚡️Server is running at https://localhost:${PORT}`);
});