-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote_download.js
81 lines (67 loc) · 1.89 KB
/
remote_download.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
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');
const http = require('https');
const { parseToken, parsePath, encodePath } = require('./utils.js');
const { ByteCounterStream } = require('./byte_counter.js');
async function handleRemoteDownload(req, res, fsRoot, reqPath, pauth, emit) {
const u = url.parse(req.url);
const params = querystring.parse(u.query);
const remoteUrl = url.parse(decodeURIComponent(params.url));
const remotePath = parsePath(remoteUrl.pathname)
const filename = decodeURIComponent(remotePath[remotePath.length - 1]);
const dstPath = encodePath([...parsePath(reqPath), filename]);
const token = parseToken(req);
const perms = await pauth.getPerms(token);
if (perms.canWrite(dstPath)) {
const fsPath = fsRoot + reqPath + '/' + filename;
http.get(params['url'], (getRes) => {
emit(dstPath, {
type: 'start',
remfs: {
size: 0,
},
});
// emit updates every 10MB
const updateByteCount = 10*1024*1024;
let count = 0;
const byteCounter = new ByteCounterStream(updateByteCount, (n) => {
count += n;
emit(dstPath, {
type: 'progress',
remfs: {
size: count,
},
});
});
const stream = fs.createWriteStream(fsPath);
getRes
.pipe(byteCounter)
.pipe(stream);
getRes.on('end', async () => {
res.end();
let stats;
try {
stats = await fs.promises.stat(fsPath);
}
catch (e) {
console.error("remote-downalod", e);
}
emit(dstPath, {
type: 'complete',
remfs: {
size: stats.size,
},
});
});
});
}
else {
res.statusCode = 403;
res.write("Unauthorized");
res.end();
}
}
module.exports = {
handleRemoteDownload,
};