-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimages.js
More file actions
72 lines (56 loc) · 1.66 KB
/
Copy pathimages.js
File metadata and controls
72 lines (56 loc) · 1.66 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
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
const { parseToken, parsePath, encodePath } = require('./utils.js');
async function handleImage(req, res, fsRoot, reqPath, pauth, emit) {
const token = parseToken(req);
const perms = await pauth.getPerms(token);
const index = reqPath.indexOf('.gemdrive-img-');
const srcPathStr = reqPath.slice(0, index);
if (!perms.canRead(srcPathStr)) {
res.statusCode = 403;
res.write("Unauthorized");
res.end();
return;
}
const numStr = reqPath.slice(index + '.gemdrive-img-'.length, -4);
const size = parseInt(numStr);
if (size !== 32 && size !== 64 && size !== 128 && size !== 256 &&
size !== 512 && size !== 1024 && size !== 2048) {
res.statusCode = 404;
res.write("Not Found");
res.end();
return;
}
const srcFsPath = path.join(fsRoot, srcPathStr);
const thumbDir = path.join('gemdrive/images/', path.dirname(reqPath));
const thumbFsPath = path.join('gemdrive/images/', reqPath);
const stream = fs.createReadStream(thumbFsPath)
stream.pipe(res);
stream.on('error', async (e) => {
try {
await fs.promises.stat(srcFsPath);
await fs.promises.mkdir(thumbDir, { recursive: true });
sharp(srcFsPath)
.resize(size, size, {
fit: 'inside',
})
.toBuffer()
.then(async (data) => {
res.write(data);
await fs.promises.writeFile(thumbFsPath, data);
res.end();
});
}
catch (e) {
console.error(e);
res.statusCode = 404;
res.write("Not Found");
res.end();
return;
}
});
}
module.exports = {
handleImage,
};