-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathufs-server.js
405 lines (352 loc) · 12.7 KB
/
ufs-server.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Karl STEIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import SparkMD5 from 'spark-md5';
import { UploadFS } from './ufs';
if (Meteor.isServer) {
const domain = Npm.require('domain');
const fs = Npm.require('fs');
const http = Npm.require('http');
const https = Npm.require('https');
const mkdirp = Npm.require('mkdirp');
const stream = Npm.require('stream');
const URL = Npm.require('url');
const zlib = Npm.require('zlib');
Meteor.startup(() => {
let path = UploadFS.config.tmpDir;
let mode = UploadFS.config.tmpDirPermissions;
fs.stat(path, (err) => {
if (err) {
// Create the temp directory
mkdirp(path, { mode: mode }, (err) => {
if (err) {
console.error(`ufs: cannot create temp directory at "${path}" (${err.message})`);
} else {
console.log(`ufs: temp directory created at "${path}"`);
}
});
} else {
// Set directory permissions
fs.chmod(path, mode, (err) => {
err && console.error(`ufs: cannot set temp directory permissions ${mode} (${err.message})`);
});
}
});
});
// Create domain to handle errors
// and possibly avoid server crashes.
let d = domain.create();
d.on('error', (err) => {
console.error('ufs: ' + err.message);
});
// Listen HTTP requests to serve files
WebApp.connectHandlers.use((req, res, next) => {
const trimmedStoresPath = (UploadFS.config.storesPath || '')
// Ensure there is no slash at the beginning of the path
.replace(/^\/+/g, '')
// Ensure there is no slash at the end of the path
.replace(/\/+$/g, '');
// Quick check to see if request should be handled
if (typeof trimmedStoresPath !== 'string'
|| trimmedStoresPath.length < 1
|| !req.url.includes(`/${trimmedStoresPath}/`)) {
next();
return;
}
// Remove store path
let parsedUrl = URL.parse(req.url);
let path = parsedUrl.pathname.substr(UploadFS.config.storesPath.length + 1);
let allowCORS = () => {
// res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
};
if (req.method === 'OPTIONS') {
let regExp = new RegExp('^\/([^\/\?]+)\/([^\/\?]+)$');
let match = regExp.exec(path);
// Request is not valid
if (match === null) {
res.writeHead(400);
res.end();
return;
}
// Get store
let store = UploadFS.getStore(match[1]);
if (!store) {
res.writeHead(404);
res.end();
return;
}
// If a store is found, go ahead and allow the origin
allowCORS();
next();
} else if (req.method === 'POST') {
// Get store
let regExp = new RegExp('^\/([^\/\?]+)\/([^\/\?]+)$');
let match = regExp.exec(path);
// Request is not valid
if (match === null) {
res.writeHead(400);
res.end();
return;
}
// Get store
let store = UploadFS.getStore(match[1]);
if (!store) {
res.writeHead(404);
res.end();
return;
}
// If a store is found, go ahead and allow the origin
allowCORS();
// Get file
let fileId = match[2];
if (store.getCollection().find({ _id: fileId }).count() === 0) {
res.writeHead(404);
res.end();
return;
}
// Check upload token
if (!store.checkToken(req.query.token, fileId)) {
res.writeHead(403);
res.end();
return;
}
//Check if duplicate
const unique = function (hash) {
const originalId = store.getCollection().findOne({ hash: hash, _id: { $ne: fileId } });
return originalId ? originalId._id : false;
};
let spark = new SparkMD5.ArrayBuffer();
let tmpFile = UploadFS.getTempFilePath(fileId);
let ws = fs.createWriteStream(tmpFile, { flags: 'a' });
let fields = { uploading: true };
let progress = parseFloat(req.query.progress);
if (!isNaN(progress) && progress > 0) {
fields.progress = Math.min(progress, 1);
}
req.on('data', (chunk) => {
ws.write(chunk);
spark.append(chunk);
});
req.on('error', (err) => {
res.writeHead(500);
res.end();
});
req.on('end', Meteor.bindEnvironment(() => {
// Update completed state without triggering hooks
fields.hash = spark.end();
fields.originalId = unique(fields.hash);
store.getCollection().direct.update({ _id: fileId }, { $set: fields });
ws.end();
}));
ws.on('error', (err) => {
console.error(`ufs: cannot write chunk of file "${fileId}" (${err.message})`);
fs.stat(tmpFile, (err) => {
!err && fs.unlink(tmpFile, (err2) => {
err2 && console.error(`ufs: cannot delete temp file "${tmpFile}" (${err2.message})`);
});
});
res.writeHead(500);
res.end();
});
ws.on('finish', () => {
res.writeHead(204, { 'Content-Type': 'text/plain' });
res.end();
});
} else if (req.method === 'GET') {
// Get store, file Id and file name
let regExp = new RegExp('^\/([^\/\?]+)\/([^\/\?]+)(?:\/([^\/\?]+))?$');
let match = regExp.exec(path);
// Avoid 504 Gateway timeout error
// if file is not handled by UploadFS.
if (match === null) {
next();
return;
}
// Get store
const storeName = match[1];
const store = UploadFS.getStore(storeName);
if (!store) {
res.writeHead(404);
res.end();
return;
}
if (store.onRead !== null && store.onRead !== undefined && typeof store.onRead !== 'function') {
console.error(`ufs: Store.onRead is not a function in store "${storeName}"`);
res.writeHead(500);
res.end();
return;
}
// Remove file extension from file Id
let index = match[2].indexOf('.');
let fileId = index !== -1 ? match[2].substr(0, index) : match[2];
// Get file from database
const file = store.getCollection().findOne({ _id: fileId });
if (!file) {
res.writeHead(404);
res.end();
return;
}
// Simulate read speed
if (UploadFS.config.simulateReadDelay) {
Meteor._sleepForMs(UploadFS.config.simulateReadDelay);
}
d.run(() => {
// Check if the file can be accessed
if (store.onRead.call(store, fileId, file, req, res) !== false) {
let options = {};
let status = 200;
// Prepare response headers
let headers = {
'Content-Type': file.type,
'Content-Length': file.size,
};
// Add ETag header
if (typeof file.etag === 'string') {
headers['ETag'] = file.etag;
}
// Add Last-Modified header
if (file.modifiedAt instanceof Date) {
headers['Last-Modified'] = file.modifiedAt.toUTCString();
} else if (file.uploadedAt instanceof Date) {
headers['Last-Modified'] = file.uploadedAt.toUTCString();
}
// Parse request headers
if (typeof req.headers === 'object') {
// Compare ETag
if (req.headers['if-none-match']) {
if (file.etag === req.headers['if-none-match']) {
res.writeHead(304); // Not Modified
res.end();
return;
}
}
// Compare file modification date
if (req.headers['if-modified-since']) {
const modifiedSince = new Date(req.headers['if-modified-since']);
if ((file.modifiedAt instanceof Date && file.modifiedAt > modifiedSince)
|| file.uploadedAt instanceof Date && file.uploadedAt > modifiedSince) {
res.writeHead(304); // Not Modified
res.end();
return;
}
}
// Support range request
if (typeof req.headers.range === 'string') {
const range = req.headers.range;
// Range is not valid
if (!range) {
res.writeHead(416);
res.end();
return;
}
const total = file.size;
const unit = range.substr(0, range.indexOf('='));
if (unit !== 'bytes') {
res.writeHead(416);
res.end();
return;
}
const ranges = range.substr(unit.length).replace(/[^0-9\-,]/, '').split(',');
if (ranges.length > 1) {
//todo: support multipart ranges: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
} else {
const r = ranges[0].split('-');
const start = parseInt(r[0], 10);
const end = r[1] ? parseInt(r[1], 10) : total - 1;
// Range is not valid
if (start < 0 || end >= total || start > end) {
res.writeHead(416);
res.end();
return;
}
// Update headers
headers['Content-Range'] = `bytes ${start}-${end}/${total}`;
headers['Content-Length'] = end - start + 1;
options.start = start;
options.end = end;
}
status = 206; // partial content
}
} else {
headers['Accept-Ranges'] = 'bytes';
}
// Open the file stream
const rs = store.getReadStream(fileId, file, options);
const ws = new stream.PassThrough();
rs.on('error', Meteor.bindEnvironment((err) => {
store.onReadError.call(store, err, fileId, file);
res.end();
}));
ws.on('error', Meteor.bindEnvironment((err) => {
store.onReadError.call(store, err, fileId, file);
res.end();
}));
ws.on('close', () => {
// Close output stream at the end
ws.emit('end');
});
// Transform stream
store.transformRead(rs, ws, fileId, file, req, headers);
// Parse request headers
if (typeof req.headers === 'object') {
// Compress data using if needed (ignore audio/video as they are already compressed)
if (typeof req.headers['accept-encoding'] === 'string' && !/^(audio|video)/.test(file.type)) {
let accept = req.headers['accept-encoding'];
// Compress with gzip
if (accept.match(/\bgzip\b/)) {
headers['Content-Encoding'] = 'gzip';
delete headers['Content-Length'];
res.writeHead(status, headers);
ws.pipe(zlib.createGzip()).pipe(res);
return;
}
// Compress with deflate
else if (accept.match(/\bdeflate\b/)) {
headers['Content-Encoding'] = 'deflate';
delete headers['Content-Length'];
res.writeHead(status, headers);
ws.pipe(zlib.createDeflate()).pipe(res);
return;
}
}
}
// Send raw data
if (!headers['Content-Encoding']) {
res.writeHead(status, headers);
ws.pipe(res);
}
} else {
res.end();
}
});
} else {
next();
}
});
}