-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
156 lines (130 loc) · 4.38 KB
/
server.js
File metadata and controls
156 lines (130 loc) · 4.38 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
const express = require('express');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const md5 = require('md5');
const sharp = require('sharp');
const { strategy } = require('sharp');
const app = express();
const PORT = 80;
// Disable image operation caching for lower memory footprint.
sharp.cache(false);
// Auto create the public/downloads folder used for cache.
if (!fs.existsSync(path.join(__dirname, 'public', 'downloads'))) {
fs.mkdirSync(path.join(__dirname, 'public', 'downloads'), { recursive: true });
}
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
let url = req.query['url'];
if (url === undefined) {
returnError(url, res, 400);
return;
}
(async () => {
let extension = getFileExtension(url).toLowerCase();
let downloadPath = path.join(__dirname, `public/downloads/${md5(url)}`);
if (isSupportedImageExtension(extension)) {
await downloadImage(url, downloadPath).then(() => {
handleImageResponse(url, req, res, extension, downloadPath);
}).catch((e) => {
console.log(e);
returnError(url, res, 500);
});
}
else {
// Unsupported file type.
returnError(url, res, 400);
}
})();
})
app.listen(PORT, () => {
console.log(`Started server on port ${PORT}`);
});
function handleImageResponse(url, req, res, extension, downloadPath) {
let maxRes = tryParseInt(req.query['maxRes'], 16000);
let targetQuality = tryParseInt(req.query['quality'], 80);
let enforceJPEG = req.query.hasOwnProperty('enforceJPEG');
if (targetQuality < 1 || targetQuality > 100) {
returnError(url, res, 400);
return;
}
let tmpBuf = [];
const reader = fs.createReadStream(downloadPath);
reader.on('data', (d) => {
tmpBuf.push(d);
});
reader.on('error', (err) => {
console.log(`Reader error: ${err}`);
returnError(url, res, 500);
});
reader.on('end', () => {
res.header('Cache-Control', 'public, max-age=31557600');
let finalBuffer = Buffer.concat(tmpBuf);
const img = sharp(finalBuffer);
img.metadata().then((info) => {
if (info.width > maxRes || info.height > maxRes) {
// Downsample the image
img.resize(maxRes, maxRes, { fit: 'inside' });
}
if (enforceJPEG || extension == 'jpg') {
res.header('Content-Type', 'image/jpeg');
img.jpeg({ quality: targetQuality });
}
else if (extension == 'png') {
res.header('Content-Type', 'image/png');
img.png();
}
else {
returnError(url, res, 500);
return;
}
img.pipe(res);
console.log(`Finished: ${url}`);
})
.catch((err) => {
console.log(err);
returnError(url, res, 500);
});
});
}
async function downloadImage(url, path) {
if (!fs.existsSync(path)) {
// Start downloading original file and store to disk.
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
});
if (response.status != 200) {
return new Promise((_, reject) => reject());
}
const writer = fs.createWriteStream(path);
response.data.pipe(writer);
// Return promise that writes to the target file.
return new Promise((resolve, reject) => {
writer.on('finish', () => resolve())
writer.on('error', e => {
reject(e);
});
});
}
else {
return new Promise((resolve) => resolve());
}
}
function returnError(url, res, code) {
console.log(`Error: ${url} failed to load (code ${code})`);
res.status(code).send();
}
function tryParseInt(value, defaultValue) {
let val = parseInt(value);
return (!isNaN(val)) ? val : defaultValue;
}
function getFileExtension(str) {
// Efficient way to get file extension: https://stackoverflow.com/a/12900504
return str.slice((str.lastIndexOf('.') - 1 >>> 0) + 2);
}
function isSupportedImageExtension(ext) {
// Extension should be lowercase.
return (ext == 'png' || ext == 'jpg');
}