forked from veliovgroup/Meteor-Files
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
1924 lines (1689 loc) · 66.3 KB
/
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Mongo } from 'meteor/mongo';
import { fetch } from 'meteor/fetch';
import { WebApp } from 'meteor/webapp';
import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { Cookies } from 'meteor/ostrio:cookies';
import { check, Match } from 'meteor/check';
import WriteStream from './write-stream.js';
import FilesCollectionCore from './core.js';
import { fixJSONParse, fixJSONStringify, helpers } from './lib.js';
import AbortController from 'abort-controller';
import fs from 'fs-extra';
import nodeQs from 'querystring';
import nodePath from 'path';
/*
* @const {Object} bound - Meteor.bindEnvironment (Fiber wrapper)
* @const {Function} NOOP - No Operation function, placeholder for required callbacks
*/
const bound = Meteor.bindEnvironment(callback => callback());
const NOOP = () => { };
/*
* @locus Anywhere
* @class FilesCollection
* @param config {Object} - [Both] Configuration object with next properties:
* @param config.debug {Boolean} - [Both] Turn on/of debugging and extra logging
* @param config.schema {Object} - [Both] Collection Schema
* @param config.public {Boolean} - [Both] Store files in folder accessible for proxy servers, for limits, and more - read docs
* @param config.strict {Boolean} - [Server] Strict mode for partial content, if is `true` server will return `416` response code, when `range` is not specified, otherwise server return `206`
* @param config.protected {Function} - [Server] If `true` - files will be served only to authorized users, if `function()` - you're able to check visitor's permissions in your own way function's context has:
* - `request`
* - `response`
* - `user()`
* - `userId`
* @param config.chunkSize {Number} - [Both] Upload chunk size, default: 524288 bytes (0,5 Mb)
* @param config.permissions {Number} - [Server] Permissions which will be set to uploaded files (octal), like: `511` or `0o755`. Default: 0644
* @param config.parentDirPermissions {Number} - [Server] Permissions which will be set to parent directory of uploaded files (octal), like: `611` or `0o777`. Default: 0755
* @param config.storagePath {String|Function} - [Server] Storage path on file system
* @param config.cacheControl {String} - [Server] Default `Cache-Control` header
* @param config.responseHeaders {Object|Function} - [Server] Custom response headers, if function is passed, must return Object
* @param config.throttle {Number} - [Server] DEPRECATED bps throttle threshold
* @param config.downloadRoute {String} - [Both] Server Route used to retrieve files
* @param config.collection {Mongo.Collection} - [Both] Mongo Collection Instance
* @param config.collectionName {String} - [Both] Collection name
* @param config.namingFunction {Function}- [Both] Function which returns `String`
* @param config.integrityCheck {Boolean} - [Server] Check file's integrity before serving to users
* @param config.onAfterUpload {Function}- [Server] Called right after file is ready on FS. Use to transfer file somewhere else, or do other thing with file directly
* @param config.onAfterRemove {Function} - [Server] Called right after file is removed. Removed objects is passed to callback
* @param config.continueUploadTTL {Number} - [Server] Time in seconds, during upload may be continued, default 3 hours (10800 seconds)
* @param config.onBeforeUpload {Function}- [Both] Function which executes on server after receiving each chunk and on client right before beginning upload. Function context is `File` - so you are able to check for extension, mime-type, size and etc.:
* - return `true` to continue
* - return `false` or `String` to abort upload
* @param config.getUser {Function} - [Server] Replace default way of recognizing user, usefull when you want to auth user based on custom cookie (or other way). arguments {http: {request: {...}, response: {...}}}, need to return {userId: String, user: Function}
* @param config.onInitiateUpload {Function} - [Server] Function which executes on server right before upload is begin and right after `onBeforeUpload` hook. This hook is fully asynchronous.
* @param config.onBeforeRemove {Function} - [Server] Executes before removing file on server, so you can check permissions. Return `true` to allow action and `false` to deny.
* @param config.allowClientCode {Boolean} - [Both] Allow to run `remove` from client
* @param config.downloadCallback {Function} - [Server] Callback triggered each time file is requested, return truthy value to continue download, or falsy to abort
* @param config.interceptRequest {Function} - [Server] Intercept incoming HTTP request, so you can whatever you want, no checks or preprocessing, arguments {http: {request: {...}, response: {...}}, params: {...}}
* @param config.interceptDownload {Function} - [Server] Intercept download request, so you can serve file from third-party resource, arguments {http: {request: {...}, response: {...}}, fileRef: {...}}
* @param config.disableUpload {Boolean} - Disable file upload, useful for server only solutions
* @param config.disableDownload {Boolean} - Disable file download (serving), useful for file management only solutions
* @param config.allowedOrigins {Regex|Boolean} - [Server] Regex of Origins that are allowed CORS access or `false` to disable completely. Defaults to `/^http:\/\/localhost:12[0-9]{3}$/` for allowing Meteor-Cordova builds access
* @param config.allowQueryStringCookies {Boolean} - Allow passing Cookies in a query string (in URL). Primary should be used only in Cordova environment. Note: this option will be used only on Cordova. Default: `false`
* @param config._preCollection {Mongo.Collection} - [Server] Mongo preCollection Instance
* @param config._preCollectionName {String} - [Server] preCollection name
* @summary Create new instance of FilesCollection
*/
export class FilesCollection extends FilesCollectionCore {
constructor(config) {
super();
let storagePath;
if (config) {
({
storagePath,
debug: this.debug,
schema: this.schema,
public: this.public,
strict: this.strict,
getUser: this.getUser,
chunkSize: this.chunkSize,
protected: this.protected,
collection: this.collection,
permissions: this.permissions,
cacheControl: this.cacheControl,
downloadRoute: this.downloadRoute,
onAfterUpload: this.onAfterUpload,
onAfterRemove: this.onAfterRemove,
disableUpload: this.disableUpload,
onBeforeRemove: this.onBeforeRemove,
integrityCheck: this.integrityCheck,
collectionName: this.collectionName,
onBeforeUpload: this.onBeforeUpload,
namingFunction: this.namingFunction,
responseHeaders: this.responseHeaders,
disableDownload: this.disableDownload,
allowedOrigins: this.allowedOrigins,
allowClientCode: this.allowClientCode,
downloadCallback: this.downloadCallback,
onInitiateUpload: this.onInitiateUpload,
interceptRequest: this.interceptRequest,
interceptDownload: this.interceptDownload,
continueUploadTTL: this.continueUploadTTL,
parentDirPermissions: this.parentDirPermissions,
allowQueryStringCookies: this.allowQueryStringCookies,
_preCollection: this._preCollection,
_preCollectionName: this._preCollectionName,
} = config);
}
const self = this;
if (!helpers.isBoolean(this.debug)) {
this.debug = false;
}
if (!helpers.isBoolean(this.public)) {
this.public = false;
}
if (!this.protected) {
this.protected = false;
}
if (!this.chunkSize) {
this.chunkSize = 1024 * 512;
}
this.chunkSize = Math.floor(this.chunkSize / 8) * 8;
if (!helpers.isString(this.collectionName) && !this.collection) {
this.collectionName = 'MeteorUploadFiles';
}
if (!this.collection) {
this.collection = new Mongo.Collection(this.collectionName);
} else {
this.collectionName = this.collection._name;
}
this.collection.filesCollection = this;
check(this.collectionName, String);
if (this.public && !this.downloadRoute) {
throw new Meteor.Error(500, `[FilesCollection.${this.collectionName}]: "downloadRoute" must be precisely provided on "public" collections! Note: "downloadRoute" must be equal or be inside of your web/proxy-server (relative) root.`);
}
if (!helpers.isString(this.downloadRoute)) {
this.downloadRoute = '/cdn/storage';
}
this.downloadRoute = this.downloadRoute.replace(/\/$/, '');
if (!helpers.isFunction(this.namingFunction)) {
this.namingFunction = false;
}
if (!helpers.isFunction(this.onBeforeUpload)) {
this.onBeforeUpload = false;
}
if (!helpers.isFunction(this.getUser)) {
this.getUser = false;
}
if (!helpers.isBoolean(this.allowClientCode)) {
this.allowClientCode = true;
}
if (!helpers.isFunction(this.onInitiateUpload)) {
this.onInitiateUpload = false;
}
if (!helpers.isFunction(this.interceptRequest)) {
this.interceptRequest = false;
}
if (!helpers.isFunction(this.interceptDownload)) {
this.interceptDownload = false;
}
if (!helpers.isBoolean(this.strict)) {
this.strict = true;
}
if (!helpers.isBoolean(this.allowQueryStringCookies)) {
this.allowQueryStringCookies = false;
}
if (!helpers.isNumber(this.permissions)) {
this.permissions = parseInt('644', 8);
}
if (!helpers.isNumber(this.parentDirPermissions)) {
this.parentDirPermissions = parseInt('755', 8);
}
if (!helpers.isString(this.cacheControl)) {
this.cacheControl = 'public, max-age=31536000, s-maxage=31536000';
}
if (!helpers.isFunction(this.onAfterUpload)) {
this.onAfterUpload = false;
}
if (!helpers.isBoolean(this.disableUpload)) {
this.disableUpload = false;
}
if (!helpers.isFunction(this.onAfterRemove)) {
this.onAfterRemove = false;
}
if (!helpers.isFunction(this.onBeforeRemove)) {
this.onBeforeRemove = false;
}
if (!helpers.isBoolean(this.integrityCheck)) {
this.integrityCheck = true;
}
if (!helpers.isBoolean(this.disableDownload)) {
this.disableDownload = false;
}
if (!helpers.isBoolean(this.allowedOrigins) || this.allowedOrigins === true) {
this.allowedOrigins = /^http:\/\/localhost:12[0-9]{3}$/;
}
if (!helpers.isObject(this._currentUploads)) {
this._currentUploads = {};
}
if (!helpers.isFunction(this.downloadCallback)) {
this.downloadCallback = false;
}
if (!helpers.isNumber(this.continueUploadTTL)) {
this.continueUploadTTL = 10800;
}
if (!helpers.isFunction(this.responseHeaders)) {
this.responseHeaders = (responseCode, fileRef, versionRef) => {
const headers = {};
switch (responseCode) {
case '206':
headers.Pragma = 'private';
headers['Transfer-Encoding'] = 'chunked';
break;
case '400':
headers['Cache-Control'] = 'no-cache';
break;
case '416':
headers['Content-Range'] = `bytes */${versionRef.size}`;
break;
default:
break;
}
headers.Connection = 'keep-alive';
headers['Content-Type'] = versionRef.type || 'application/octet-stream';
headers['Accept-Ranges'] = 'bytes';
return headers;
};
}
if (this.public && !storagePath) {
throw new Meteor.Error(500, `[FilesCollection.${this.collectionName}] "storagePath" must be set on "public" collections! Note: "storagePath" must be equal on be inside of your web/proxy-server (absolute) root.`);
}
if (!storagePath) {
storagePath = function () {
return `assets${nodePath.sep}app${nodePath.sep}uploads${nodePath.sep}${self.collectionName}`;
};
}
if (helpers.isString(storagePath)) {
this.storagePath = () => storagePath;
} else {
this.storagePath = function () {
let sp = storagePath.apply(self, arguments);
if (!helpers.isString(sp)) {
throw new Meteor.Error(400, `[FilesCollection.${self.collectionName}] "storagePath" function must return a String!`);
}
sp = sp.replace(/\/$/, '');
return nodePath.normalize(sp);
};
}
this._debug('[FilesCollection.storagePath] Set to:', this.storagePath({}));
fs.mkdirs(this.storagePath({}), { mode: this.parentDirPermissions }, (error) => {
if (error) {
throw new Meteor.Error(401, `[FilesCollection.${self.collectionName}] Path "${this.storagePath({})}" is not writable! ${error}`);
}
});
check(this.strict, Boolean);
check(this.permissions, Number);
check(this.storagePath, Function);
check(this.cacheControl, String);
check(this.onAfterRemove, Match.OneOf(false, Function));
check(this.onAfterUpload, Match.OneOf(false, Function));
check(this.disableUpload, Boolean);
check(this.integrityCheck, Boolean);
check(this.onBeforeRemove, Match.OneOf(false, Function));
check(this.disableDownload, Boolean);
check(this.downloadCallback, Match.OneOf(false, Function));
check(this.interceptRequest, Match.OneOf(false, Function));
check(this.interceptDownload, Match.OneOf(false, Function));
check(this.continueUploadTTL, Number);
check(this.responseHeaders, Match.OneOf(Object, Function));
check(this.allowQueryStringCookies, Boolean);
new Cookies({
allowQueryStringCookies: this.allowQueryStringCookies,
allowedCordovaOrigins: this.allowedOrigins
});
if (!this.disableUpload) {
if (!helpers.isString(this._preCollectionName) && !this._preCollection) {
this._preCollectionName = `__pre_${this.collectionName}`;
}
if (!this._preCollection) {
this._preCollection = new Mongo.Collection(this._preCollectionName);
} else {
this._preCollectionName = this._preCollection._name;
}
check(this._preCollectionName, String);
this._preCollection._ensureIndex({ createdAt: 1 }, { expireAfterSeconds: this.continueUploadTTL, background: true });
const _preCollectionCursor = this._preCollection.find({}, {
fields: {
_id: 1,
isFinished: 1
}
});
_preCollectionCursor.observe({
changed(doc) {
if (doc.isFinished) {
self._debug(`[FilesCollection] [_preCollectionCursor.observe] [changed]: ${doc._id}`);
self._preCollection.remove({_id: doc._id}, NOOP);
}
},
removed(doc) {
// Free memory after upload is done
// Or if upload is unfinished
self._debug(`[FilesCollection] [_preCollectionCursor.observe] [removed]: ${doc._id}`);
if (helpers.isObject(self._currentUploads[doc._id])) {
self._currentUploads[doc._id].stop();
self._currentUploads[doc._id].end();
// We can be unlucky to run into a race condition where another server removed this document before the change of `isFinished` is registered on this server.
// Therefore it's better to double-check with the main collection if the file is referenced there. Issue: https://github.com/VeliovGroup/Meteor-Files/issues/672
if (!doc.isFinished && self.collection.find({ _id: doc._id }).count() === 0) {
self._debug(`[FilesCollection] [_preCollectionCursor.observe] [removeUnfinishedUpload]: ${doc._id}`);
self._currentUploads[doc._id].abort();
}
delete self._currentUploads[doc._id];
}
}
});
this._createStream = (_id, path, opts) => {
this._currentUploads[_id] = new WriteStream(path, opts.fileLength, opts, this.permissions);
};
// This little function allows to continue upload
// even after server is restarted (*not on dev-stage*)
this._continueUpload = (_id) => {
if (this._currentUploads[_id] && this._currentUploads[_id].file) {
if (!this._currentUploads[_id].aborted && !this._currentUploads[_id].ended) {
return this._currentUploads[_id].file;
}
this._createStream(_id, this._currentUploads[_id].file.file.path, this._currentUploads[_id].file);
return this._currentUploads[_id].file;
}
const contUpld = this._preCollection.findOne({_id});
if (contUpld) {
this._createStream(_id, contUpld.file.path, contUpld);
return this._currentUploads[_id].file;
}
return false;
};
}
if (!this.schema) {
this.schema = FilesCollectionCore.schema;
}
check(this.debug, Boolean);
check(this.schema, Object);
check(this.public, Boolean);
check(this.getUser, Match.OneOf(false, Function));
check(this.protected, Match.OneOf(Boolean, Function));
check(this.chunkSize, Number);
check(this.downloadRoute, String);
check(this.namingFunction, Match.OneOf(false, Function));
check(this.onBeforeUpload, Match.OneOf(false, Function));
check(this.onInitiateUpload, Match.OneOf(false, Function));
check(this.allowClientCode, Boolean);
if (this.public && this.protected) {
throw new Meteor.Error(500, `[FilesCollection.${this.collectionName}]: Files can not be public and protected at the same time!`);
}
this._checkAccess = (http) => {
if (this.protected) {
let result;
const {user, userId} = this._getUser(http);
if (helpers.isFunction(this.protected)) {
let fileRef;
if (helpers.isObject(http.params) && http.params._id) {
fileRef = this.collection.findOne(http.params._id);
}
result = http ? this.protected.call(Object.assign(http, {user, userId}), (fileRef || null)) : this.protected.call({user, userId}, (fileRef || null));
} else {
result = !!userId;
}
if ((http && (result === true)) || !http) {
return true;
}
const rc = helpers.isNumber(result) ? result : 401;
this._debug('[FilesCollection._checkAccess] WARN: Access denied!');
if (http) {
const text = 'Access denied!';
if (!http.response.headersSent) {
http.response.writeHead(rc, {
'Content-Type': 'text/plain',
'Content-Length': text.length
});
}
if (!http.response.finished) {
http.response.end(text);
}
}
return false;
}
return true;
};
this._methodNames = {
_Abort: `_FilesCollectionAbort_${this.collectionName}`,
_Write: `_FilesCollectionWrite_${this.collectionName}`,
_Start: `_FilesCollectionStart_${this.collectionName}`,
_Remove: `_FilesCollectionRemove_${this.collectionName}`
};
this.on('_handleUpload', this._handleUpload);
this.on('_finishUpload', this._finishUpload);
this._handleUploadSync = Meteor.wrapAsync(this._handleUpload.bind(this));
if (this.disableUpload && this.disableDownload) {
return;
}
WebApp.connectHandlers.use((httpReq, httpResp, next) => {
if (this.allowedOrigins && httpReq._parsedUrl.path.includes(`${this.downloadRoute}/`) && !httpResp.headersSent) {
if (this.allowedOrigins.test(httpReq.headers.origin)) {
httpResp.setHeader('Access-Control-Allow-Credentials', 'true');
httpResp.setHeader('Access-Control-Allow-Origin', httpReq.headers.origin);
}
if (httpReq.method === 'OPTIONS') {
httpResp.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
httpResp.setHeader('Access-Control-Allow-Headers', 'Range, Content-Type, x-mtok, x-start, x-chunkid, x-fileid, x-eof');
httpResp.setHeader('Access-Control-Expose-Headers', 'Accept-Ranges, Content-Encoding, Content-Length, Content-Range');
httpResp.setHeader('Allow', 'GET, POST, OPTIONS');
httpResp.writeHead(200);
httpResp.end();
return;
}
}
if (!this.disableUpload && httpReq._parsedUrl.path.includes(`${this.downloadRoute}/${this.collectionName}/__upload`)) {
if (httpReq.method !== 'POST') {
next();
return;
}
const handleError = (_error) => {
let error = _error;
console.warn('[FilesCollection] [Upload] [HTTP] Exception:', error);
console.trace();
if (!httpResp.headersSent) {
httpResp.writeHead(500);
}
if (!httpResp.finished) {
if (helpers.isObject(error) && helpers.isFunction(error.toString)) {
error = error.toString();
}
if (!helpers.isString(error)) {
error = 'Unexpected error!';
}
httpResp.end(JSON.stringify({ error }));
}
};
let body = '';
const handleData = () => {
try {
let opts;
let result;
let user = this._getUser({request: httpReq, response: httpResp});
if (httpReq.headers['x-start'] !== '1') {
// CHUNK UPLOAD SCENARIO:
opts = {
fileId: httpReq.headers['x-fileid']
};
if (httpReq.headers['x-eof'] === '1') {
opts.eof = true;
} else {
opts.binData = Buffer.from(body, 'base64');
opts.chunkId = parseInt(httpReq.headers['x-chunkid']);
}
const _continueUpload = this._continueUpload(opts.fileId);
if (!_continueUpload) {
throw new Meteor.Error(408, 'Can\'t continue upload, session expired. Start upload again.');
}
({result, opts} = this._prepareUpload(Object.assign(opts, _continueUpload), user.userId, 'HTTP'));
if (opts.eof) {
// FINISH UPLOAD SCENARIO:
this._handleUpload(result, opts, (_error) => {
let error = _error;
if (error) {
if (!httpResp.headersSent) {
httpResp.writeHead(500);
}
if (!httpResp.finished) {
if (helpers.isObject(error) && helpers.isFunction(error.toString)) {
error = error.toString();
}
if (!helpers.isString(error)) {
error = 'Unexpected error!';
}
httpResp.end(JSON.stringify({ error }));
}
}
if (!httpResp.headersSent) {
httpResp.writeHead(200);
}
if (helpers.isObject(result.file) && result.file.meta) {
result.file.meta = fixJSONStringify(result.file.meta);
}
if (!httpResp.finished) {
httpResp.end(JSON.stringify(result));
}
});
return;
}
this.emit('_handleUpload', result, opts, NOOP);
if (!httpResp.headersSent) {
httpResp.writeHead(204);
}
if (!httpResp.finished) {
httpResp.end();
}
} else {
// START SCENARIO:
try {
opts = JSON.parse(body);
} catch (jsonErr) {
console.error('Can\'t parse incoming JSON from Client on [.insert() | upload], something went wrong!', jsonErr);
opts = {file: {}};
}
if (!helpers.isObject(opts.file)) {
opts.file = {};
}
this._debug(`[FilesCollection] [File Start HTTP] ${opts.file.name || '[no-name]'} - ${opts.fileId}`);
if (helpers.isObject(opts.file) && opts.file.meta) {
opts.file.meta = fixJSONParse(opts.file.meta);
}
opts.___s = true;
({result} = this._prepareUpload(helpers.clone(opts), user.userId, 'HTTP Start Method'));
if (this.collection.findOne(result._id)) {
throw new Meteor.Error(400, 'Can\'t start upload, data substitution detected!');
}
opts._id = opts.fileId;
opts.createdAt = new Date();
opts.maxLength = opts.fileLength;
this._preCollection.insert(helpers.omit(opts, '___s'));
this._createStream(result._id, result.path, helpers.omit(opts, '___s'));
if (opts.returnMeta) {
if (!httpResp.headersSent) {
httpResp.writeHead(200);
}
if (!httpResp.finished) {
httpResp.end(JSON.stringify({
uploadRoute: `${this.downloadRoute}/${this.collectionName}/__upload`,
file: result
}));
}
} else {
if (!httpResp.headersSent) {
httpResp.writeHead(204);
}
if (!httpResp.finished) {
httpResp.end();
}
}
}
} catch (httpRespErr) {
handleError(httpRespErr);
}
};
httpReq.setTimeout(20000, handleError);
if (typeof httpReq.body === 'object' && Object.keys(httpReq.body).length !== 0) {
body = JSON.stringify(httpReq.body);
handleData();
} else {
httpReq.on('data', (data) => bound(() => {
body += data;
}));
httpReq.on('end', () => bound(() => {
handleData();
}));
}
return;
}
if (!this.disableDownload) {
let uri;
if (!this.public) {
if (httpReq._parsedUrl.path.includes(`${this.downloadRoute}/${this.collectionName}`)) {
uri = httpReq._parsedUrl.path.replace(`${this.downloadRoute}/${this.collectionName}`, '');
if (uri.indexOf('/') === 0) {
uri = uri.substring(1);
}
const uris = uri.split('/');
if (uris.length === 3) {
const params = {
_id: uris[0],
query: httpReq._parsedUrl.query ? nodeQs.parse(httpReq._parsedUrl.query) : {},
name: uris[2].split('?')[0],
version: uris[1]
};
const http = {request: httpReq, response: httpResp, params};
if (this.interceptRequest && helpers.isFunction(this.interceptRequest) && this.interceptRequest(http) === true) {
return;
}
if (this._checkAccess(http)) {
this.download(http, uris[1], this.collection.findOne(uris[0]));
}
} else {
next();
}
} else {
next();
}
} else {
if (httpReq._parsedUrl.path.includes(`${this.downloadRoute}`)) {
uri = httpReq._parsedUrl.path.replace(`${this.downloadRoute}`, '');
if (uri.indexOf('/') === 0) {
uri = uri.substring(1);
}
const uris = uri.split('/');
let _file = uris[uris.length - 1];
if (_file) {
let version;
if (_file.includes('-')) {
version = _file.split('-')[0];
_file = _file.split('-')[1].split('?')[0];
} else {
version = 'original';
_file = _file.split('?')[0];
}
const params = {
query: httpReq._parsedUrl.query ? nodeQs.parse(httpReq._parsedUrl.query) : {},
file: _file,
_id: _file.split('.')[0],
version,
name: _file
};
const http = {request: httpReq, response: httpResp, params};
if (this.interceptRequest && helpers.isFunction(this.interceptRequest) && this.interceptRequest(http) === true) {
return;
}
this.download(http, version, this.collection.findOne(params._id));
} else {
next();
}
} else {
next();
}
}
return;
}
next();
});
if (!this.disableUpload) {
const _methods = {};
// Method used to remove file
// from Client side
_methods[this._methodNames._Remove] = function (selector) {
check(selector, Match.OneOf(String, Object));
self._debug(`[FilesCollection] [Unlink Method] [.remove(${selector})]`);
if (self.allowClientCode) {
if (self.onBeforeRemove && helpers.isFunction(self.onBeforeRemove)) {
const userId = this.userId;
const userFuncs = {
userId: this.userId,
user() {
if (Meteor.users) {
return Meteor.users.findOne(userId);
}
return null;
}
};
if (!self.onBeforeRemove.call(userFuncs, (self.find(selector) || null))) {
throw new Meteor.Error(403, '[FilesCollection] [remove] Not permitted!');
}
}
const cursor = self.find(selector);
if (cursor.count() > 0) {
self.remove(selector);
return true;
}
throw new Meteor.Error(404, 'Cursor is empty, no files is removed');
} else {
throw new Meteor.Error(401, '[FilesCollection] [remove] Run code from client is not allowed!');
}
};
// Method used to receive "first byte" of upload
// and all file's meta-data, so
// it won't be transferred with every chunk
// Basically it prepares everything
// So user can pause/disconnect and
// continue upload later, during `continueUploadTTL`
_methods[this._methodNames._Start] = function (opts, returnMeta) {
check(opts, {
file: Object,
fileId: String,
FSName: Match.Optional(String),
chunkSize: Number,
fileLength: Number
});
check(returnMeta, Match.Optional(Boolean));
self._debug(`[FilesCollection] [File Start Method] ${opts.file.name} - ${opts.fileId}`);
opts.___s = true;
const { result } = self._prepareUpload(helpers.clone(opts), this.userId, 'DDP Start Method');
if (self.collection.findOne(result._id)) {
throw new Meteor.Error(400, 'Can\'t start upload, data substitution detected!');
}
opts._id = opts.fileId;
opts.createdAt = new Date();
opts.maxLength = opts.fileLength;
try {
self._preCollection.insert(helpers.omit(opts, '___s'));
self._createStream(result._id, result.path, helpers.omit(opts, '___s'));
} catch (e) {
self._debug(`[FilesCollection] [File Start Method] [EXCEPTION:] ${opts.file.name} - ${opts.fileId}`, e);
throw new Meteor.Error(500, 'Can\'t start');
}
if (returnMeta) {
return {
uploadRoute: `${self.downloadRoute}/${self.collectionName}/__upload`,
file: result
};
}
return true;
};
// Method used to write file chunks
// it receives very limited amount of meta-data
// This method also responsible for EOF
_methods[this._methodNames._Write] = function (_opts) {
let opts = _opts;
let result;
check(opts, {
eof: Match.Optional(Boolean),
fileId: String,
binData: Match.Optional(String),
chunkId: Match.Optional(Number)
});
if (opts.binData) {
opts.binData = Buffer.from(opts.binData, 'base64');
}
const _continueUpload = self._continueUpload(opts.fileId);
if (!_continueUpload) {
throw new Meteor.Error(408, 'Can\'t continue upload, session expired. Start upload again.');
}
this.unblock();
({result, opts} = self._prepareUpload(Object.assign(opts, _continueUpload), this.userId, 'DDP'));
if (opts.eof) {
try {
return self._handleUploadSync(result, opts);
} catch (handleUploadErr) {
self._debug('[FilesCollection] [Write Method] [DDP] Exception:', handleUploadErr);
throw handleUploadErr;
}
} else {
self.emit('_handleUpload', result, opts, NOOP);
}
return true;
};
// Method used to Abort upload
// - Freeing memory by ending writableStreams
// - Removing temporary record from @_preCollection
// - Removing record from @collection
// - .unlink()ing chunks from FS
_methods[this._methodNames._Abort] = function (_id) {
check(_id, String);
const _continueUpload = self._continueUpload(_id);
self._debug(`[FilesCollection] [Abort Method]: ${_id} - ${(helpers.isObject(_continueUpload.file) ? _continueUpload.file.path : '')}`);
if (self._currentUploads && self._currentUploads[_id]) {
self._currentUploads[_id].stop();
self._currentUploads[_id].abort();
}
if (_continueUpload) {
self._preCollection.remove({_id});
self.remove({_id});
if (helpers.isObject(_continueUpload.file) && _continueUpload.file.path) {
self.unlink({_id, path: _continueUpload.file.path});
}
}
return true;
};
Meteor.methods(_methods);
}
}
/*
* @locus Server
* @memberOf FilesCollection
* @name _prepareUpload
* @summary Internal method. Used to optimize received data and check upload permission
* @returns {Object}
*/
_prepareUpload(opts = {}, userId, transport) {
let ctx;
if (!helpers.isBoolean(opts.eof)) {
opts.eof = false;
}
if (!opts.binData) {
opts.binData = 'EOF';
}
if (!helpers.isNumber(opts.chunkId)) {
opts.chunkId = -1;
}
if (!helpers.isString(opts.FSName)) {
opts.FSName = opts.fileId;
}
this._debug(`[FilesCollection] [Upload] [${transport}] Got #${opts.chunkId}/${opts.fileLength} chunks, dst: ${opts.file.name || opts.file.fileName}`);
const fileName = this._getFileName(opts.file);
const {extension, extensionWithDot} = this._getExt(fileName);
if (!helpers.isObject(opts.file.meta)) {
opts.file.meta = {};
}
let result = opts.file;
result.name = fileName;
result.meta = opts.file.meta;
result.extension = extension;
result.ext = extension;
result._id = opts.fileId;
result.userId = userId || null;
opts.FSName = opts.FSName.replace(/([^a-z0-9\-\_]+)/gi, '-');
result.path = `${this.storagePath(result)}${nodePath.sep}${opts.FSName}${extensionWithDot}`;
result = Object.assign(result, this._dataToSchema(result));
if (this.onBeforeUpload && helpers.isFunction(this.onBeforeUpload)) {
ctx = Object.assign({
file: opts.file
}, {
chunkId: opts.chunkId,
userId: result.userId,
user() {
if (Meteor.users && result.userId) {
return Meteor.users.findOne(result.userId);
}
return null;
},
eof: opts.eof
});
const isUploadAllowed = this.onBeforeUpload.call(ctx, result);
if (isUploadAllowed !== true) {
throw new Meteor.Error(403, helpers.isString(isUploadAllowed) ? isUploadAllowed : '@onBeforeUpload() returned false');
} else {
if ((opts.___s === true) && this.onInitiateUpload && helpers.isFunction(this.onInitiateUpload)) {
this.onInitiateUpload.call(ctx, result);
}
}
} else if ((opts.___s === true) && this.onInitiateUpload && helpers.isFunction(this.onInitiateUpload)) {
ctx = Object.assign({
file: opts.file
}, {
chunkId: opts.chunkId,
userId: result.userId,
user() {
if (Meteor.users && result.userId) {
return Meteor.users.findOne(result.userId);
}
return null;
},
eof: opts.eof
});
this.onInitiateUpload.call(ctx, result);
}
return {result, opts};
}
/*
* @locus Server
* @memberOf FilesCollection
* @name _finishUpload
* @summary Internal method. Finish upload, close Writable stream, add record to MongoDB and flush used memory
* @returns {undefined}
*/
_finishUpload(result, opts, cb) {
this._debug(`[FilesCollection] [Upload] [finish(ing)Upload] -> ${result.path}`);
fs.chmod(result.path, this.permissions, NOOP);
result.type = this._getMimeType(opts.file);
result.public = this.public;
this._updateFileTypes(result);
this.collection.insert(helpers.clone(result), (colInsert, _id) => {
if (colInsert) {
cb && cb(colInsert);
this._debug('[FilesCollection] [Upload] [_finishUpload] [insert] Error:', colInsert);
} else {
this._preCollection.update({_id: opts.fileId}, {$set: {isFinished: true}}, (preUpdateError) => {
if (preUpdateError) {
cb && cb(preUpdateError);
this._debug('[FilesCollection] [Upload] [_finishUpload] [update] Error:', preUpdateError);
} else {
result._id = _id;
this._debug(`[FilesCollection] [Upload] [finish(ed)Upload] -> ${result.path}`);