forked from veliovgroup/Meteor-Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.coffee
executable file
·2400 lines (2158 loc) · 86.6 KB
/
files.coffee
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
NOOP = -> return
if Meteor.isServer
###
@summary Require NPM packages
###
fs = Npm.require 'fs-extra'
events = Npm.require 'events'
request = Npm.require 'request'
Throttle = Npm.require 'throttle'
fileType = Npm.require 'file-type'
nodePath = Npm.require 'path'
###
@var {Object} bound - Meteor.bindEnvironment (Fiber wrapper)
###
bound = Meteor.bindEnvironment (callback) -> return callback()
###
@private
@locus Server
@class writeStream
@param path {String} - Path to file on FS
@param maxLength {Number} - Max amount of chunks in stream
@param file {Object} - fileRef Object
@summary writableStream wrapper class, makes sure chunks is written in given order. Implementation of queue stream.
###
class writeStream
constructor: (@path, @maxLength, @file) ->
if not @path or not _.isString @path
return
self = @
fs.ensureFileSync @path
@stream = fs.createWriteStream @path, {flags: 'a', mode: self.permissions, highWaterMark: 0}
@drained = true
@aborted = false
@writtenChunks = 0
@stream.on 'drain', -> bound ->
++self.writtenChunks
self.drained = true
return
@stream.on 'error', (error) -> bound ->
console.error "[FilesCollection] [writeStream] [ERROR:]", error
self.abort()
return
###
@memberOf writeStream
@name write
@param {Number} num - Chunk position in stream
@param {Buffer} chunk - Chunk binary data
@param {Function} callback - Callback
@summary Write chunk in given order
@returns {Boolean} - True if chunk is sent to stream, false if chunk is set into queue
###
write: (num, chunk, callback) ->
if not @aborted and (not @stream._writableState.ended and num > @writtenChunks)
if @drained and num is (@writtenChunks + 1)
@drained = false
@stream.write chunk, callback
return true
else
self = @
Meteor.setTimeout ->
self.write num, chunk
return
, 25
return false
###
@memberOf writeStream
@name end
@param {Function} callback - Callback
@summary Finishes writing to writableStream, only after all chunks in queue is written
@returns {Boolean} - True if stream is fulfilled, false if queue is in progress
###
end: (callback) ->
if not @aborted and not @stream._writableState.ended
if @writtenChunks is @maxLength
@stream.end callback
return true
else
self = @
Meteor.setTimeout ->
self.end callback
return
, 25
return false
###
@memberOf writeStream
@name abort
@summary Aborts writing to writableStream, prevent memory leaks caused by unsatisfied queue
@returns {Boolean} - True
###
abort: ->
@aborted = true
return true
else
`import { EventEmitter } from './event-emitter.jsx'`
###
@private
@locus Anywhere
@class FileCursor
@param _fileRef {Object} - Mongo-Style selector (http://docs.meteor.com/api/collections.html#selectors)
@param _collection {FilesCollection} - FilesCollection Instance
@summary Internal class, represents each record in `FilesCursor.each()` or document returned from `.findOne()` method
###
class FileCursor
constructor: (@_fileRef, @_collection) ->
self = @
self = _.extend self, @_fileRef
###
@locus Anywhere
@memberOf FileCursor
@name remove
@param callback {Function} - Triggered asynchronously after item is removed or failed to be removed
@summary Remove document
@returns {FileCursor}
###
remove: (callback) ->
console.info '[FilesCollection] [FileCursor] [remove()]' if @_collection.debug
if @_fileRef
@_collection.remove(@_fileRef._id, callback)
else
callback and callback new Meteor.Error 404, 'No such file'
return @
###
@locus Anywhere
@memberOf FileCursor
@name link
@param version {String} - Name of file's subversion
@summary Returns downloadable URL to File
@returns {String}
###
link: (version) ->
console.info "[FilesCollection] [FileCursor] [link(#{version})]" if @_collection.debug
return if @_fileRef then @_collection.link(@_fileRef, version) else ''
###
@locus Anywhere
@memberOf FileCursor
@name get
@param property {String} - Name of sub-object property
@summary Returns current document as a plain Object, if `property` is specified - returns value of sub-object property
@returns {Object|mix}
###
get: (property) ->
console.info "[FilesCollection] [FileCursor] [get(#{property})]" if @_collection.debug
if property
return @_fileRef[property]
else
return @_fileRef
###
@locus Anywhere
@memberOf FileCursor
@name fetch
@summary Returns document as plain Object in Array
@returns {[Object]}
###
fetch: ->
console.info '[FilesCollection] [FileCursor] [fetch()]' if @_collection.debug
return [@_fileRef]
###
@locus Anywhere
@memberOf FileCursor
@name with
@summary Returns reactive version of current FileCursor, useful to use with `{{#with}}...{{/with}}` block template helper
@returns {[Object]}
###
with: ->
console.info '[FilesCollection] [FileCursor] [with()]' if @_collection.debug
self = @
return _.extend self, @_collection.collection.findOne @_fileRef._id
###
@private
@locus Anywhere
@class FilesCursor
@param _selector {String|Object} - Mongo-Style selector (http://docs.meteor.com/api/collections.html#selectors)
@param options {Object} - Mongo-Style selector Options (http://docs.meteor.com/api/collections.html#selectors)
@param _collection {FilesCollection} - FilesCollection Instance
@summary Implementation of Cursor for FilesCollection
###
class FilesCursor
constructor: (@_selector = {}, options, @_collection) ->
@_current = -1
@cursor = @_collection.collection.find @_selector, options
###
@locus Anywhere
@memberOf FilesCursor
@name get
@summary Returns all matching document(s) as an Array. Alias of `.fetch()`
@returns {[Object]}
###
get: ->
console.info "[FilesCollection] [FilesCursor] [get()]" if @_collection.debug
return @cursor.fetch()
###
@locus Anywhere
@memberOf FilesCursor
@name hasNext
@summary Returns `true` if there is next item available on Cursor
@returns {Boolean}
###
hasNext: ->
console.info '[FilesCollection] [FilesCursor] [hasNext()]' if @_collection.debug
return @_current < @cursor.count() - 1
###
@locus Anywhere
@memberOf FilesCursor
@name next
@summary Returns next item on Cursor, if available
@returns {Object|undefined}
###
next: ->
console.info '[FilesCollection] [FilesCursor] [next()]' if @_collection.debug
if @hasNext()
return @cursor.fetch()[++@_current]
###
@locus Anywhere
@memberOf FilesCursor
@name hasPrevious
@summary Returns `true` if there is previous item available on Cursor
@returns {Boolean}
###
hasPrevious: ->
console.info '[FilesCollection] [FilesCursor] [hasPrevious()]' if @_collection.debug
return @_current isnt -1
###
@locus Anywhere
@memberOf FilesCursor
@name previous
@summary Returns previous item on Cursor, if available
@returns {Object|undefined}
###
previous: ->
console.info '[FilesCollection] [FilesCursor] [previous()]' if @_collection.debug
if @hasPrevious()
return @cursor.fetch()[--@_current]
###
@locus Anywhere
@memberOf FilesCursor
@name fetch
@summary Returns all matching document(s) as an Array.
@returns {[Object]}
###
fetch: ->
console.info '[FilesCollection] [FilesCursor] [fetch()]' if @_collection.debug
return @cursor.fetch()
###
@locus Anywhere
@memberOf FilesCursor
@name first
@summary Returns first item on Cursor, if available
@returns {Object|undefined}
###
first: ->
console.info '[FilesCollection] [FilesCursor] [first()]' if @_collection.debug
@_current = 0
return @fetch()?[@_current]
###
@locus Anywhere
@memberOf FilesCursor
@name last
@summary Returns last item on Cursor, if available
@returns {Object|undefined}
###
last: ->
console.info '[FilesCollection] [FilesCursor] [last()]' if @_collection.debug
@_current = @count() - 1
return @fetch()?[@_current]
###
@locus Anywhere
@memberOf FilesCursor
@name count
@summary Returns the number of documents that match a query
@returns {Number}
###
count: ->
console.info '[FilesCollection] [FilesCursor] [count()]' if @_collection.debug
return @cursor.count()
###
@locus Anywhere
@memberOf FilesCursor
@name remove
@param callback {Function} - Triggered asynchronously after item is removed or failed to be removed
@summary Removes all documents that match a query
@returns {FilesCursor}
###
remove: (callback) ->
console.info '[FilesCollection] [FilesCursor] [remove()]' if @_collection.debug
@_collection.remove @_selector, callback
return @
###
@locus Anywhere
@memberOf FilesCursor
@name forEach
@param callback {Function} - Function to call. It will be called with three arguments: the `file`, a 0-based index, and cursor itself
@param context {Object} - An object which will be the value of `this` inside `callback`
@summary Call `callback` once for each matching document, sequentially and synchronously.
@returns {undefined}
###
forEach: (callback, context = {}) ->
console.info '[FilesCollection] [FilesCursor] [forEach()]' if @_collection.debug
@cursor.forEach callback, context
return
###
@locus Anywhere
@memberOf FilesCursor
@name each
@summary Returns an Array of FileCursor made for each document on current cursor
Useful when using in {{#each FilesCursor#each}}...{{/each}} block template helper
@returns {[FileCursor]}
###
each: ->
self = @
return @map (file) ->
return new FileCursor file, self._collection
###
@locus Anywhere
@memberOf FilesCursor
@name map
@param callback {Function} - Function to call. It will be called with three arguments: the `file`, a 0-based index, and cursor itself
@param context {Object} - An object which will be the value of `this` inside `callback`
@summary Map `callback` over all matching documents. Returns an Array.
@returns {Array}
###
map: (callback, context = {}) ->
console.info '[FilesCollection] [FilesCursor] [map()]' if @_collection.debug
return @cursor.map callback, context
###
@locus Anywhere
@memberOf FilesCursor
@name current
@summary Returns current item on Cursor, if available
@returns {Object|undefined}
###
current: ->
console.info '[FilesCollection] [FilesCursor] [current()]' if @_collection.debug
@_current = 0 if @_current < 0
return @fetch()[@_current]
###
@locus Anywhere
@memberOf FilesCursor
@name observe
@param callbacks {Object} - Functions to call to deliver the result set as it changes
@summary Watch a query. Receive callbacks as the result set changes.
@url http://docs.meteor.com/api/collections.html#Mongo-Cursor-observe
@returns {Object} - live query handle
###
observe: (callbacks) ->
console.info '[FilesCollection] [FilesCursor] [observe()]' if @_collection.debug
return @cursor.observe callbacks
###
@locus Anywhere
@memberOf FilesCursor
@name observeChanges
@param callbacks {Object} - Functions to call to deliver the result set as it changes
@summary Watch a query. Receive callbacks as the result set changes. Only the differences between the old and new documents are passed to the callbacks.
@url http://docs.meteor.com/api/collections.html#Mongo-Cursor-observeChanges
@returns {Object} - live query handle
###
observeChanges: (callbacks) ->
console.info '[FilesCollection] [FilesCursor] [observeChanges()]' if @_collection.debug
return @cursor.observeChanges callbacks
###
@var {Function} fixJSONParse - Fix issue with Date parse
###
fixJSONParse = (obj) ->
for key, value of obj
if _.isString(value) and !!~value.indexOf '=--JSON-DATE--='
value = value.replace '=--JSON-DATE--=', ''
obj[key] = new Date parseInt value
else if _.isObject value
obj[key] = fixJSONParse value
else if _.isArray value
for v, i in value
if _.isObject(v)
obj[key][i] = fixJSONParse v
else if _.isString(v) and !!~v.indexOf '=--JSON-DATE--='
v = v.replace '=--JSON-DATE--=', ''
obj[key][i] = new Date parseInt v
return obj
###
@var {Function} fixJSONStringify - Fix issue with Date stringify
###
fixJSONStringify = (obj) ->
for key, value of obj
if _.isDate value
obj[key] = '=--JSON-DATE--=' + (+value)
else if _.isObject value
obj[key] = fixJSONStringify value
else if _.isArray value
for v, i in value
if _.isObject(v)
obj[key][i] = fixJSONStringify v
else if _.isDate v
obj[key][i] = '=--JSON-DATE--=' + (+v)
return obj
###
@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.ddp {Object} - [Client] Custom DDP connection. Object returned form `DDP.connect()`
@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} - [Both] 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` - On server only
- `response` - On server only
- `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] 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.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.interceptDownload {Function} - [Server] Intercept download request, so you can serve file from third-party resource, arguments {http: {request: {...}, response: {...}}, fileRef: {...}}
@param config.onbeforeunloadMessage {String|Function} - [Client] Message shown to user when closing browser's window or tab while upload process is running
@summary Create new instance of FilesCollection
###
class FilesCollection
__proto__: do -> if Meteor.isServer then events.EventEmitter.prototype else EventEmitter.prototype
constructor: (config) ->
if Meteor.isServer
events.EventEmitter.call @
else
EventEmitter.call @
{storagePath, @ddp, @collection, @collectionName, @downloadRoute, @schema, @chunkSize, @namingFunction, @debug, @onbeforeunloadMessage, @permissions, @parentDirPermissions, @allowClientCode, @onBeforeUpload, @onInitiateUpload, @integrityCheck, @protected, @public, @strict, @downloadCallback, @cacheControl, @responseHeaders, @throttle, @onAfterUpload, @onAfterRemove, @interceptDownload, @onBeforeRemove, @continueUploadTTL} = config if config
self = @
cookie = new Cookies()
@debug ?= false
@public ?= false
@protected ?= false
@chunkSize ?= 1024*512
@chunkSize = Math.floor(@chunkSize / 8) * 8
if @public and not @downloadRoute
throw new Meteor.Error 500, "[FilesCollection.#{@collectionName}]: \"downloadRoute\" must be precisely provided on \"public\" collections! Note: \"downloadRoute\" must be equal or be inside of your web/proxy-server (relative) root."
@collection ?= new Mongo.Collection @collectionName
@collectionName ?= @collection._name
check @collectionName, String
@downloadRoute ?= '/cdn/storage'
@downloadRoute = @downloadRoute.replace /\/$/, ''
@collectionName ?= 'MeteorUploadFiles'
@namingFunction ?= false
@onBeforeUpload ?= false
@allowClientCode ?= true
@ddp ?= Meteor
@onInitiateUpload ?= false
@interceptDownload ?= false
storagePath ?= -> "assets#{nodePath.sep}app#{nodePath.sep}uploads#{nodePath.sep}#{@collectionName}"
if _.isString storagePath
@storagePath = -> storagePath
else
@storagePath = ->
sp = storagePath.apply @, arguments
unless _.isString sp
throw new Meteor.Error 400, "[FilesCollection.#{self.collectionName}] \"storagePath\" function must return a String!"
sp = sp.replace /\/$/, ''
return if Meteor.isServer then nodePath.normalize(sp) else sp
if Meteor.isClient
@onbeforeunloadMessage ?= 'Upload in a progress... Do you want to abort?'
delete @strict
delete @throttle
delete @permissions
delete @parentDirPermissions
delete @cacheControl
delete @onAfterUpload
delete @onAfterRemove
delete @onBeforeRemove
@onInitiateUpload = false
delete @integrityCheck
delete @downloadCallback
delete @interceptDownload
delete @continueUploadTTL
delete @responseHeaders
setTokenCookie = ->
Meteor.setTimeout ->
if (not cookie.has('x_mtok') and Meteor.connection._lastSessionId) or (cookie.has('x_mtok') and (cookie.get('x_mtok') isnt Meteor.connection._lastSessionId))
cookie.set 'x_mtok', Meteor.connection._lastSessionId, null, '/'
cookie.send()
return
, 25
return
unsetTokenCookie = ->
if cookie.has 'x_mtok'
cookie.remove 'x_mtok'
cookie.send()
return
if Accounts?
Accounts.onLogin ->
setTokenCookie()
return
Accounts.onLogout ->
unsetTokenCookie()
return
check @onbeforeunloadMessage, Match.OneOf String, Function
if window?.Worker and window?.Blob
@_supportWebWorker = true
_URL = window.URL || window.webkitURL || window.mozURL
@_webWorkerUrl = _URL.createObjectURL(new Blob(['"use strict";self.onmessage=function(a){if(a.data.ib===!0)postMessage({bin:a.data.f.slice(a.data.cs*(a.data.cc-1),a.data.cs*a.data.cc),chunkId:a.data.cc});else{var b;self.FileReader?(b=new FileReader,b.onloadend=function(c){postMessage({bin:(b.result||c.srcElement||c.target).split(",")[1],chunkId:a.data.cc,s:a.data.s})},b.onerror=function(a){throw(a.target||a.srcElement).error},b.readAsDataURL(a.data.f.slice(a.data.cs*(a.data.cc-1),a.data.cs*a.data.cc))):self.FileReaderSync?(b=new FileReaderSync,postMessage({bin:b.readAsDataURL(a.data.f.slice(a.data.cs*(a.data.cc-1),a.data.cs*a.data.cc)).split(",")[1],chunkId:a.data.cc})):postMessage({bin:null,chunkId:a.data.cc,error:"File API is not supported in WebWorker!"})}};'], {type: 'application/javascript'}))
else if window?.Worker
@_supportWebWorker = true
@_webWorkerUrl = Meteor.absoluteUrl 'packages/ostrio_files/worker.min.js'
else
@_supportWebWorker = false
else
@strict ?= true
@throttle ?= false
@permissions ?= parseInt('644', 8)
@parentDirPermissions ?= parseInt('755', 8)
@cacheControl ?= 'public, max-age=31536000, s-maxage=31536000'
@onAfterUpload ?= false
@onAfterRemove ?= false
@onBeforeRemove ?= false
@integrityCheck ?= true
@_currentUploads ?= {}
@downloadCallback ?= false
@continueUploadTTL ?= 10800
@responseHeaders ?= (responseCode, fileRef, versionRef) ->
headers = {}
switch responseCode
when '206'
headers['Pragma'] = 'private'
headers['Trailer'] = 'expires'
headers['Transfer-Encoding'] = 'chunked'
when '400'
headers['Cache-Control'] = 'no-cache'
when '416'
headers['Content-Range'] = "bytes */#{versionRef.size}"
headers['Connection'] = 'keep-alive'
headers['Content-Type'] = versionRef.type or 'application/octet-stream'
headers['Accept-Ranges'] = 'bytes'
return headers
if @public and (not storagePath or not _.isString(storagePath))
throw new Meteor.Error 500, "[FilesCollection.#{@collectionName}] \"storagePath\" must be set on \"public\" collections! Note: \"storagePath\" must be equal on be inside of your web/proxy-server (absolute) root."
console.info('[FilesCollection.storagePath] Set to:', @storagePath({})) if @debug
fs.mkdirs @storagePath({}), {mode: @parentDirPermissions}, (error) ->
if error
throw new Meteor.Error 401, "[FilesCollection.#{self.collectionName}] Path \"#{self.storagePath}\" is not writable!", error
return
check @strict, Boolean
check @throttle, Match.OneOf false, Number
check @permissions, Number
check @storagePath, Function
check @cacheControl, String
check @onAfterRemove, Match.OneOf false, Function
check @onAfterUpload, Match.OneOf false, Function
check @integrityCheck, Boolean
check @onBeforeRemove, Match.OneOf false, Function
check @downloadCallback, Match.OneOf false, Function
check @interceptDownload, Match.OneOf false, Function
check @continueUploadTTL, Number
check @responseHeaders, Match.OneOf Object, Function
@_preCollection = new Mongo.Collection '__pre_' + @collectionName
@_preCollection._ensureIndex {'createdAt': 1}, {expireAfterSeconds: @continueUploadTTL, background: true}
_preCollectionCursor = @_preCollection.find {}
_preCollectionCursor.observeChanges removed: (_id) ->
# Free memory after upload is done
# Or if upload is unfinished
console.info "[FilesCollection] [_preCollectionCursor.observeChanges] [removed]: #{_id}" if self.debug
if self._currentUploads?[_id]
self._currentUploads[_id].end()
self._currentUploads[_id].abort()
delete self._currentUploads[_id]
return
@_createStream = (_id, path, opts) ->
return self._currentUploads[_id] = new writeStream path, opts.fileLength, opts
# This little function allows to continue upload
# even after server is restarted (*not on dev-stage*)
@_continueUpload = (_id) ->
if self._currentUploads?[_id]?.file
unless self._currentUploads[_id].stream._writableState.ended
return self._currentUploads[_id].file
else
self._createStream _id, self._currentUploads[_id].file.file.path, self._currentUploads[_id].file
return self._currentUploads[_id].file
else
contUpld = self._preCollection.findOne {_id}
if contUpld
self._createStream _id, contUpld.file.path, contUpld.file
return contUpld
if not @schema
@schema =
size: type: Number
name: type: String
type: type: String
path: type: String
isVideo: type: Boolean
isAudio: type: Boolean
isImage: type: Boolean
isText: type: Boolean
isJSON: type: Boolean
isPDF: type: Boolean
extension:
type: String
optional: true
_storagePath: type: String
_downloadRoute: type: String
_collectionName: type: String
public:
type: Boolean
optional: true
meta:
type: Object
blackbox: true
optional: true
userId:
type: String
optional: true
updatedAt:
type: Date
optional: true
versions:
type: Object
blackbox: true
check @debug, Boolean
check @schema, Object
check @public, Boolean
check @protected, Match.OneOf Boolean, Function
check @chunkSize, Number
check @downloadRoute, String
check @namingFunction, Match.OneOf false, Function
check @onBeforeUpload, Match.OneOf false, Function
check @onInitiateUpload, Match.OneOf false, Function
check @allowClientCode, Boolean
check @ddp, Match.Any
if @public and @protected
throw new Meteor.Error 500, "[FilesCollection.#{@collectionName}]: Files can not be public and protected at the same time!"
@_checkAccess = (http) ->
if self.protected
{user, userId} = self._getUser http
if _.isFunction self.protected
if http?.params?._id
fileRef = self.collection.findOne http.params._id
result = if http then self.protected.call(_.extend(http, {user, userId}), (fileRef or null)) else self.protected.call {user, userId}, (fileRef or null)
else
result = !!userId
if (http and result is true) or not http
return true
else
rc = if _.isNumber(result) then result else 401
console.warn '[FilesCollection._checkAccess] WARN: Access denied!' if self.debug
if http
text = 'Access denied!'
http.response.writeHead rc,
'Content-Length': text.length
'Content-Type': 'text/plain'
http.response.end text
return false
else
return true
@_methodNames =
_Abort: "_FilesCollectionAbort_#{@collectionName}"
_Write: "_FilesCollectionWrite_#{@collectionName}"
_Start: "_FilesCollectionStart_#{@collectionName}"
_Remove: "_FilesCollectionRemove_#{@collectionName}"
if Meteor.isServer
@on '_handleUpload', @_handleUpload
@on '_finishUpload', @_finishUpload
WebApp.connectHandlers.use (request, response, next) ->
if !!~request._parsedUrl.path.indexOf "#{self.downloadRoute}/#{self.collectionName}/__upload"
if request.method is 'POST'
handleError = (error) ->
console.warn "[FilesCollection] [Upload] [HTTP] Exception:", error
response.writeHead 500
response.end JSON.stringify {error}
return
body = ''
request.on 'data', (data) -> bound ->
body += data
return
request.on 'end', -> bound ->
try
if request.headers['x-mtok'] and Meteor.server.sessions?[request.headers['x-mtok']]
user = userId: Meteor.server.sessions[request.headers['x-mtok']]?.userId
else
user = self._getUser {request, response}
unless request.headers['x-start'] is '1'
opts = fileId: request.headers['x-fileid']
if request.headers['x-eof'] is '1'
opts.eof = true
else
opts.binData = new Buffer body, 'base64'
opts.chunkId = parseInt request.headers['x-chunkid']
_continueUpload = self._continueUpload opts.fileId
unless _continueUpload
throw new Meteor.Error 408, 'Can\'t continue upload, session expired. Start upload again.'
{result, opts} = self._prepareUpload _.extend(opts, _continueUpload), user.userId, 'HTTP'
if opts.eof
Meteor.wrapAsync(self._handleUpload.bind(self, result, opts))()
response.writeHead 200
result.file.meta = fixJSONStringify result.file.meta if result?.file?.meta
response.end JSON.stringify result
else
self.emit '_handleUpload', result, opts, NOOP
response.writeHead 204
response.end()
else
opts = JSON.parse body
opts.___s = true
console.info "[FilesCollection] [File Start HTTP] #{opts.file.name} - #{opts.fileId}" if self.debug
opts.file.meta = fixJSONParse opts.file.meta if opts?.file?.meta
{result} = self._prepareUpload _.clone(opts), user.userId, 'Start Method'
opts._id = opts.fileId
opts.createdAt = new Date()
self._preCollection.insert _.omit(opts, '___s')
self._createStream result._id, result.path, _.omit(opts, '___s')
if opts.returnMeta
response.writeHead 200
response.end JSON.stringify {
uploadRoute: "#{self.downloadRoute}/#{self.collectionName}/__upload"
file: result
}
else
response.writeHead 204
response.end()
catch error
handleError error
return
else
next()
return
unless self.public
if !!~request._parsedUrl.path.indexOf "#{self.downloadRoute}/#{self.collectionName}"
uri = request._parsedUrl.path.replace "#{self.downloadRoute}/#{self.collectionName}", ''
if uri.indexOf('/') is 0
uri = uri.substring 1
uris = uri.split '/'
if uris.length is 3
params =
query: if request._parsedUrl.query then JSON.parse('{"' + decodeURI(request._parsedUrl.query).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}') else {}
_id: uris[0]
version: uris[1]
name: uris[2]
http = {request, response, params}
self.download http, uris[1], self.collection.findOne(uris[0]) if self._checkAccess http
else
next()
else
next()
else
if !!~request._parsedUrl.path.indexOf "#{self.downloadRoute}"
uri = request._parsedUrl.path.replace "#{self.downloadRoute}", ''
if uri.indexOf('/') is 0
uri = uri.substring 1
uris = uri.split '/'
_file = uris[uris.length - 1]
if _file
if !!~_file.indexOf '-'
version = _file.split('-')[0]
_file = _file.split('-')[1].split('?')[0]
else
version = 'original'
_file = _file.split('?')[0]
params =
query: if request._parsedUrl.query then JSON.parse('{"' + decodeURI(request._parsedUrl.query).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}') else {}
file: _file
_id: _file.split('.')[0]
version: version
name: _file
http = {request, response, params}
self.download http, version, self.collection.findOne params._id
else
next()
else
next()
return
_methods = {}
# Method used to remove file
# from Client side
_methods[self._methodNames._Remove] = (selector) ->
check selector, Match.OneOf String, Object
console.info "[FilesCollection] [Unlink Method] [.remove(#{selector})]" if self.debug
if self.allowClientCode
if self.onBeforeRemove and _.isFunction self.onBeforeRemove
user = false
userFuncs = {
userId: @userId
user: -> if Meteor.users then Meteor.users.findOne(@userId) else null
}
unless self.onBeforeRemove.call userFuncs, (self.find(selector) or null)
throw new Meteor.Error 403, '[FilesCollection] [remove] Not permitted!'
self.remove selector
return true
else
throw new Meteor.Error 401, '[FilesCollection] [remove] Run code from client is not allowed!'
return
# 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[self._methodNames._Start] = (opts, returnMeta) ->
check opts, {
file: Object
fileId: String
FSName: Match.Optional String
chunkSize: Number
fileLength: Number
}
check returnMeta, Match.Optional Boolean
console.info "[FilesCollection] [File Start Method] #{opts.file.name} - #{opts.fileId}" if self.debug
opts.___s = true
{result} = self._prepareUpload _.clone(opts), @userId, 'Start Method'
opts._id = opts.fileId
opts.createdAt = new Date()
self._preCollection.insert _.omit(opts, '___s')
self._createStream result._id, result.path, _.omit(opts, '___s')
if returnMeta
return {
uploadRoute: "#{self.downloadRoute}/#{self.collectionName}/__upload"
file: result
}
else
return true
# Method used to write file chunks
# it receives very limited amount of meta-data
# This method also responsible for EOF
_methods[self._methodNames._Write] = (opts) ->
check opts, {
eof: Match.Optional Boolean
fileId: String
binData: Match.Optional String
chunkId: Match.Optional Number
}
opts.binData = new Buffer(opts.binData, 'base64') if opts.binData
_continueUpload = self._continueUpload opts.fileId
unless _continueUpload
throw new Meteor.Error 408, 'Can\'t continue upload, session expired. Start upload again.'
@unblock()
{result, opts} = self._prepareUpload _.extend(opts, _continueUpload), @userId, 'DDP'
if opts.eof
try
return Meteor.wrapAsync(self._handleUpload.bind(self, result, opts))()
catch e
console.warn "[FilesCollection] [Write Method] [DDP] Exception:", e if self.debug
throw e
else
self.emit '_handleUpload', result, opts, NOOP
return true
# Method used to Abort upload
# - Feeing memory by .end()ing writableStreams
# - Removing temporary record from @_preCollection
# - Removing record from @collection
# - .unlink()ing chunks from FS
_methods[self._methodNames._Abort] = (_id) ->
check _id, String
_continueUpload = self._continueUpload _id
console.info "[FilesCollection] [Abort Method]: #{_id} - #{_continueUpload?.file?.path}" if self.debug
if _continueUpload
self._preCollection.remove {_id}
self.remove {_id}
self.unlink {_id, path: _continueUpload.file.path} if _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: if Meteor.isServer then (opts, userId, transport) ->
opts.eof ?= false
opts.binData ?= 'EOF'
opts.chunkId ?= -1
opts.FSName ?= opts.fileId
opts.file.meta ?= {}
console.info "[FilesCollection] [Upload] [#{transport}] Got ##{opts.chunkId}/#{opts.fileLength} chunks, dst: #{opts.file.name or opts.file.fileName}" if @debug
fileName = @_getFileName opts.file
{extension, extensionWithDot} = @_getExt fileName
result = opts.file
result.name = fileName
result.meta = opts.file.meta
result.extension = extension
result.ext = extension
result._id = opts.fileId
result.userId = userId or null
result.path = "#{@storagePath(result)}#{nodePath.sep}#{opts.FSName}#{extensionWithDot}"
result = _.extend result, @_dataToSchema result
if @onBeforeUpload and _.isFunction @onBeforeUpload
ctx = _.extend {
file: opts.file
}, {
chunkId: opts.chunkId
userId: result.userId