-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.js
More file actions
85 lines (69 loc) · 1.78 KB
/
Copy pathupload.js
File metadata and controls
85 lines (69 loc) · 1.78 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
const fs = require('fs');
const path = require('path');
const { ByteCounterStream } = require('./byte_counter.js');
const { parseToken, parsePath, encodePath, buildJsonListing } = require('./utils.js');
async function handleUpload(req, res, fsRoot, reqPath, pauth, emit) {
const token = parseToken(req);
const perms = await pauth.getPerms(token);
if (!perms.canWrite(reqPath)) {
res.statusCode = 403;
res.write("Unauthorized");
res.end();
return;
}
const fsPath = fsRoot + '/' + reqPath;
const pathParts = parsePath(reqPath);
// TODO: Might not need to traverse here. Maybe just check if the parent
// path exists.
let curDir = fsRoot;
for (const pathPart of pathParts.slice(0, pathParts.length - 1)) {
curDir += '/' + pathPart;
try {
await fs.promises.stat(curDir);
}
catch (e) {
res.statusCode = 400;
res.write(e.toString());
res.end();
return;
}
}
const stream = fs.createWriteStream(fsPath);
// emit updates every 10MB
const updateByteCount = 10*1024*1024;
let count = 0;
const byteCounter = new ByteCounterStream(updateByteCount, (n) => {
count += n;
emit(reqPath, {
type: 'update',
remfs: {
size: count,
},
});
});
emit(reqPath, {
type: 'start',
remfs: {
size: 0,
},
});
req
.pipe(byteCounter)
.pipe(stream);
req.on('end', async () => {
const remfsPath = path.dirname(fsPath);
const filename = path.basename(fsPath);
const remfs = await buildJsonListing(remfsPath);
res.write(JSON.stringify(remfs.children[filename], null, 2));
emit(reqPath, {
type: 'complete',
remfs: {
size: remfs.children[filename].size,
},
});
res.end();
});
}
module.exports = {
handleUpload,
};