-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
100 lines (91 loc) · 2.65 KB
/
server.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
const http = require("http");
const https = require("https");
const { URL } = require("url");
const gm = require("gm").subClass({
imageMagick: true,
});
const bucketName = process.env.BUCKET_NAME || "assets.cytoid.io";
function requestURLForPath(url) {
let path = url.pathname;
if (path.startsWith("/")) {
path = path.substr(1);
}
return `https://assets.cytoid.io/` + path;
}
function requestListener(req, res) {
res.setHeader("X-Powered-By", "cytoid");
if (req.method !== "GET") {
res.writeHead(405);
res.end("Method not allowed");
}
const url = new URL(req.url, "https://images.cytoid.io");
const request = https.get(
requestURLForPath(url),
{
headers: {
"user-agent": "cytoid-img-resizer",
},
},
(response) => {
if (response.statusCode === 200) {
// Image exists.
const contentType = response.headers["content-type"];
res.setHeader("content-type", contentType);
if (!contentType.startsWith("image/")) {
res.writeHead(response.statusCode);
response.pipe(res);
return;
}
// Copy headers
for (const headerName of [
"expires",
"etag",
"content-disposition",
"date",
"vary",
]) {
const header = response.headers[headerName];
if (header) res.setHeader(headerName, header);
}
res.setHeader("cache-control", "max-age=3153600,public");
let height = url.searchParams.get("h");
if (height) height = parseInt(height) || null;
let width = url.searchParams.get("w");
if (width) width = parseInt(width) || null;
res.writeHead(response.statusCode);
if (height && width) {
gm(response)
.resize(width, height, "^")
.gravity("Center")
.crop(width, height)
.stream()
.pipe(res);
} else if (height || width) {
gm(response).resize(width, height).stream().pipe(res);
} else {
response.pipe(res);
}
} else {
// Error
for (const headerName of [
"content-type",
"expires",
"etag",
"content-disposition",
"date",
"vary",
]) {
const header = response.headers[headerName];
if (header) res.setHeader(headerName, header);
}
res.writeHead(response.statusCode);
response.pipe(res);
}
}
);
}
const port = process.env.PORT || 8040;
const server = http.createServer(requestListener);
server.listen(port, "0.0.0.0", () => {
console.log("Server listening on " + port);
});