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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
|
const path = require('path');
const jetpack = require('fs-jetpack');
const multer = require('multer');
const Util = require('../../utils/Util');
const Route = require('../../structures/Route');
const multerStorage = require('../../utils/multerStorage');
const chunksData = {};
const chunkedUploadsTimeout = 1800000;
const chunksDir = path.join(__dirname, '../../../../uploads/chunks');
const uploadDir = path.join(__dirname, '../../../../uploads');
const cleanUpChunks = async (uuid, onTimeout) => {
// Remove tmp file
await jetpack.removeAsync(path.join(chunksData[uuid].root, chunksData[uuid].filename))
.catch(error => {
if (error.code !== 'ENOENT') console.error(error);
});
// Remove UUID dir
await jetpack.removeAsync(chunksData[uuid].root);
// Delete cached chunks data
if (!onTimeout) chunksData[uuid].clearTimeout();
delete chunksData[uuid];
};
class ChunksData {
constructor(uuid, root) {
this.uuid = uuid;
this.root = root;
this.filename = 'tmp';
this.chunks = 0;
this.stream = null;
this.hasher = null;
}
onTimeout() {
if (this.stream && !this.stream.writableEnded) {
this.stream.end();
}
if (this.hasher) {
this.hasher.dispose();
}
cleanUpChunks(this.uuid, true);
}
setTimeout(delay) {
this.clearTimeout();
this._timeout = setTimeout(this.onTimeout.bind(this), delay);
}
clearTimeout() {
if (this._timeout) {
clearTimeout(this._timeout);
}
}
}
const initChunks = async uuid => {
if (chunksData[uuid] === undefined) {
const root = path.join(chunksDir, uuid);
await jetpack.dirAsync(root);
chunksData[uuid] = new ChunksData(uuid, root);
}
chunksData[uuid].setTimeout(chunkedUploadsTimeout);
return chunksData[uuid];
};
const executeMulter = multer({
// Guide: https://github.com/expressjs/multer#limits
limits: {
fileSize: Util.config.maxSize * (1000 * 1000),
// Maximum number of non-file fields.
// Dropzone.js will add 6 extra fields for chunked uploads.
// We don't use them for anything else.
fields: 6,
// Maximum number of file fields.
// Chunked uploads still need to provide ONLY 1 file field.
// Otherwise, only one of the files will end up being properly stored,
// and that will also be as a chunk.
files: 1
},
fileFilter(req, file, cb) {
file.extname = Util.getExtension(file.originalname);
if (Util.isExtensionBlocked(file.extname)) {
return cb(`${file.extname ? `${file.extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`);
}
// Re-map Dropzone keys so people can manually use the API without prepending 'dz'
for (const key in req.body) {
if (!/^dz/.test(key)) continue;
req.body[key.replace(/^dz/, '')] = req.body[key];
delete req.body[key];
}
return cb(null, true);
},
storage: multerStorage({
destination(req, file, cb) {
// Is file a chunk!?
file._isChunk = req.body.uuid !== undefined && req.body.chunkindex !== undefined;
if (file._isChunk) {
initChunks(req.body.uuid)
.then(chunksData => {
file._chunksData = chunksData;
cb(null, chunksData.root);
})
.catch(error => {
console.error(error);
return cb('Could not process the chunked upload. Try again?');
});
} else {
return cb(null, uploadDir);
}
},
filename(req, file, cb) {
if (file._isChunk) {
return cb(null, chunksData[req.body.uuid].filename);
}
const name = Util.getUniqueFilename(file.extname);
if (name) return cb(null, name);
return cb('ERROR');
}
})
}).array('files[]');
const uploadFile = async (req, res) => {
const error = await new Promise(resolve => executeMulter(req, res, err => resolve(err)));
if (error) {
const suppress = [
'LIMIT_FILE_SIZE',
'LIMIT_UNEXPECTED_FILE'
];
if (suppress.includes(error.code)) {
throw error.toString();
} else {
throw error;
}
}
if (!req.files || !req.files.length) {
throw 'No files.'; // eslint-disable-line no-throw-literal
}
// If the uploaded file is a chunk then just say that it was a success
const uuid = req.body.uuid;
if (chunksData[uuid] !== undefined) {
req.files.forEach(() => {
chunksData[uuid].chunks++;
});
res.json({ success: true });
return;
}
const infoMap = req.files.map(file => ({
path: path.join(uploadDir, file.filename),
data: { ...file, mimetype: Util.getMimeFromType(file.fileType) || file.mimetype || '' }
}));
return infoMap[0];
};
const finishChunks = async req => {
const check = file => typeof file.uuid !== 'string' ||
!chunksData[file.uuid] ||
chunksData[file.uuid].chunks < 2;
const files = req.body.files;
if (!Array.isArray(files) || !files.length || files.some(check)) {
throw 'An unexpected error occurred.'; // eslint-disable-line no-throw-literal
}
const infoMap = [];
try {
await Promise.all(files.map(async file => {
// Close stream
chunksData[file.uuid].stream.end();
/*
if (chunksData[file.uuid].chunks > maxChunksCount) {
throw 'Too many chunks.'; // eslint-disable-line no-throw-literal
}
*/
file.extname = typeof file.original === 'string' ? Util.getExtension(file.original) : '';
file.fileType = chunksData[file.uuid].fileType;
file.mimetype = Util.getMimeFromType(chunksData[file.uuid].fileType) || file.mimetype || '';
if (Util.isExtensionBlocked(file.extname)) {
throw `${file.extname ? `${file.extname.substr(1).toUpperCase()} files` : 'Files with no extension'} are not permitted.`; // eslint-disable-line no-throw-literal
}
file.size = chunksData[file.uuid].stream.bytesWritten;
// Double-check file size
const tmpfile = path.join(chunksData[file.uuid].root, chunksData[file.uuid].filename);
const lstat = await jetpack.inspect(tmpfile);
if (lstat.size !== file.size) {
throw `File size mismatched (${lstat.size} vs. ${file.size}).`; // eslint-disable-line no-throw-literal
}
// Generate name
const name = Util.getUniqueFilename(file.extname);
// Move tmp file to final destination
const destination = path.join(uploadDir, name);
await jetpack.move(tmpfile, destination);
const hash = chunksData[file.uuid].hasher.digest('hex');
// Continue even when encountering errors
await cleanUpChunks(file.uuid).catch(console.error);
const data = {
filename: name,
originalname: file.original || '',
extname: file.extname,
mimetype: file.mimetype,
size: file.size,
hash
};
infoMap.push({ path: destination, data });
}));
return infoMap[0];
} catch (error) {
// Dispose unfinished hasher and clean up leftover chunks
// Should continue even when encountering errors
files.forEach(file => {
if (chunksData[file.uuid] === undefined) return;
try {
if (chunksData[file.uuid].hasher) {
chunksData[file.uuid].hasher.dispose();
}
} catch (_) {}
cleanUpChunks(file.uuid).catch(console.error);
});
// Re-throw error
throw error;
}
};
class uploadPOST extends Route {
constructor() {
super('/upload', 'post', {
bypassAuth: true,
canApiKey: true
});
}
async run(req, res, db) {
const user = await Util.isAuthorized(req);
if (!user && !Util.config.publicMode) return res.status(401).json({ message: 'Not authorized to use this resource' });
const { finishedchunks } = req.headers;
const albumId = req.headers.albumid ? req.headers.albumid === 'null' ? null : req.headers.albumid : null;
if (albumId && !user) return res.status(401).json({ message: 'Only registered users can upload files to an album' });
if (albumId && user) {
const album = await db.table('albums').where({ id: albumId, userId: user.id }).first();
if (!album) return res.status(401).json({ message: 'Album doesn\'t exist or it doesn\'t belong to the user' });
}
let file;
if (finishedchunks) {
file = await finishChunks(req, res);
} else {
// If nothing is returned we assume it was a chunk ¯\_(ツ)_/¯
file = await uploadFile(req, res);
if (!file) return;
}
// If nothing is returned means the file was duplicated and we already sent the response
const result = await Util.storeFileToDb(req, res, user, file, db);
if (!result) return;
if (albumId) await Util.saveFileToAlbum(db, albumId, result.id);
result.file = Util.constructFilePublicLink(req, result.file);
result.deleteUrl = `${Util.getHost(req)}/api/file/${result.id[0]}`;
return res.status(201).send({
message: 'Sucessfully uploaded the file.',
url: result.file.url,
name: result.file.name,
hash: result.file.hash,
deleteUrl: result.deleteUrl,
size: result.file.size,
thumb: result.file.thumb
});
}
}
module.exports = uploadPOST;
|