-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (85 loc) · 2.12 KB
/
index.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const express = require("express");
const app = express();
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const urlJoin = require("url-join");
const minio = require("minio");
const client = new minio.Client({
endPoint: process.env.MINIO_ENDPOINT,
port: parseInt(process.env.MINIO_PORT),
useSSL: process.env.MINIO_USE_SSL === "true",
accessKey: process.env.MINIO_ACCESS_KEY,
secretKey: process.env.MINIO_SECRET_KEY,
});
const object = process.env.MINIO_OBJECT || "stuyactivities";
client.bucketExists(object, (err, exists) => {
if (exists) {
return console.log("OK!");
}
if (err) {
console.log(err);
}
console.log("Creating bucket " + object);
client.makeBucket(object);
return null;
})
const images = {};
function downloadImage(url, filename) {
return new Promise(async (resolve) => {
// axios image download with response type "stream"
const response = await axios({
method: "GET",
url: url,
responseType: "stream",
});
client.putObject(
object,
filename,
response.data,
response.headers,
(er) => {
if (er) {
console.log(er);
throw er;
}
resolve();
}
);
});
}
const objectSet = new Set();
const stream = client.listObjects(object, "", true);
stream.on("data", (obj) => objectSet.add(obj.name));
app.use(async (req, res) => {
if (req.path.startsWith("/")) {
req.path = req.path.replace("/", "");
}
let p = req.path.replace("/", "");
const info = path.parse(p);
if (!info.ext) {
p += ".png";
}
if (!objectSet.has(p)) {
const cloudinaryUrl = urlJoin(
"https://res.cloudinary.com/stuyactivities/",
p
);
await downloadImage(cloudinaryUrl, p);
}
const now = new Date();
const round = new Date(now.getFullYear(), now.getMonth(), now.getDate());
client.presignedUrl(
"GET",
object,
p,
60 * 60 * 24 * 7,
round,
(er, url) => res.redirect(url)
);
});
const port = Number(process.env.PORT) || 3002;
app.listen(port, () => {
console.log("Listening on port ", port);
});