/
files.coffee
executable file
路1661 lines (1487 loc) 路 59.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()
###
@var {Function} sortNumber - Natural Number sort
###
sortNumber = (a, b) -> return a - b
###
@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} - [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} - [Server] Storage path on file system
@param config.cacheControl {String} - [Server] Default `Cache-Control` header
@param config.throttle {Number} - [Server] bps throttle threshold
@param config.downloadRoute {String} - [Both] Server Route used to retrieve files
@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.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.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, @collectionName, @downloadRoute, @schema, @chunkSize, @namingFunction, @debug, @onbeforeunloadMessage, @permissions, @parentDirPermissions, @allowClientCode, @onBeforeUpload, @integrityCheck, @protected, @public, @strict, @downloadCallback, @cacheControl, @throttle, @onAfterUpload, @interceptDownload, @onBeforeRemove} = 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 explicitly provided on \"public\" collections! Note: \"downloadRoute\" must be equal on be inside of your web/proxy-server (relative) root."
@downloadRoute ?= '/cdn/storage'
@downloadRoute = @downloadRoute.replace /\/$/, ''
@collectionName ?= 'MeteorUploadFiles'
@namingFunction ?= false
@onBeforeUpload ?= false
@allowClientCode ?= true
@interceptDownload?= false
if Meteor.isClient
@onbeforeunloadMessage ?= 'Upload in a progress... Do you want to abort?'
delete @strict
delete @throttle
delete @storagePath
delete @permissions
delete @parentDirPermissions
delete @cacheControl
delete @onAfterUpload
delete @integrityCheck
delete @downloadCallback
delete @interceptDownload
delete @onBeforeRemove
if @protected
localStorageSupport = do ->
try
support = "localStorage" of window and window.localStorage isnt null
if support
window.localStorage.setItem '___test___', 'test'
window.localStorage.removeItem '___test___'
return true
else
return false
catch
return false
if localStorageSupport
if not cookie.has('meteor_login_token') and window.localStorage.getItem('Meteor.loginToken')
cookie.set 'meteor_login_token', window.localStorage.getItem('Meteor.loginToken'), null, '/'
check @onbeforeunloadMessage, Match.OneOf String, Function
else
@_writableStreams ?= {}
@strict ?= true
@throttle ?= false
@permissions ?= parseInt('644', 8)
@parentDirPermissions ?= parseInt('755', 8)
@cacheControl ?= 'public, max-age=31536000, s-maxage=31536000'
@onBeforeRemove ?= false
@onAfterUpload ?= false
@integrityCheck ?= true
@downloadCallback ?= false
if @public and not @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."
@storagePath ?= "assets/app/uploads/#{@collectionName}"
@storagePath = @storagePath.replace /\/$/, ''
@storagePath = nodePath.normalize @storagePath
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, String
check @cacheControl, String
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
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
_prefix: type: String
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
autoValue: -> new Date()
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 @collectionName, String
check @namingFunction, Match.OneOf false, Function
check @onBeforeUpload, Match.OneOf false, Function
check @allowClientCode, Boolean
if @public and @protected
throw new Meteor.Error 500, "[FilesCollection.#{@collectionName}]: Files can not be public and protected at the same time!"
@cursor = null
@search = {}
@collection = new Mongo.Collection @collectionName
@currentFile = null
@_prefix = SHA256 @collectionName + @downloadRoute
@checkAccess = (http) ->
if self.protected
user = false
userFuncs = self.getUser http
{user, userId} = userFuncs
user = user()
if _.isFunction self.protected
result = if http then self.protected.call(_.extend(http, userFuncs), (self.currentFile or null)) else self.protected.call userFuncs, (self.currentFile or null)
else
result = !!user
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 =
MeteorFileAbort: "MeteorFileAbort#{@_prefix}"
MeteorFileWrite: "MeteorFileWrite#{@_prefix}"
MeteorFileUnlink: "MeteorFileUnlink#{@_prefix}"
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'
body = ''
request.on 'data', (data) -> bound ->
body += data
return
request.on 'end', -> bound ->
try
opts = JSON.parse body
user = self.getUser http
{result, opts} = self.prepareUpload opts, user.userId, 'HTTP'
if opts.eof
try
Meteor.wrapAsync(self.handleUpload.bind(self, result, opts))()
response.writeHead 200
response.end JSON.stringify result
return
catch e
console.warn "[FilesCollection] [Write Method] [HTTP] Exception:", e
response.writeHead 500
response.end JSON.stringify {error: 2}
else
self.emit 'handleUpload', result, opts, NOOP
response.writeHead 200
response.end JSON.stringify {success: true}
catch e
console.warn "[FilesCollection] [Write Method] [HTTP] Exception:", e
response.writeHead 500
response.end JSON.stringify {error: e}
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.findOne(uris[0]).download.call(self, http, uris[1]) 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.findOne(params._id).download.call self, http, version
else
next()
else
next()
return
_methods = {}
_methods[self.methodNames.MeteorFileUnlink] = (search) ->
check search, Match.OneOf String, Object
console.info "[FilesCollection] [Unlink Method] [.remove(#{search})]" 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 undefined
}
unless self.onBeforeRemove.call userFuncs, (self.find(search) or null)
throw new Meteor.Error 403, '[FilesCollection] [remove] Not permitted!'
self.remove search
return true
else
throw new Meteor.Error 401, '[FilesCollection] [remove] Run code from client is not allowed!'
return
_methods[self.methodNames.MeteorFileWrite] = (opts) ->
@unblock()
check opts, {
eof: Match.Optional Boolean
file: Object
fileId: String
FSName: Match.Optional String
binData: Match.Optional String
chunkId: Match.Optional Number
chunkSize: Number
fileLength: Number
}
{result, opts} = self.prepareUpload opts, @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
_methods[self.methodNames.MeteorFileAbort] = (opts) ->
check opts, {
fileId: String
fileData: Object
fileLength: Number
}
ext = ".#{opts.fileData.ext}"
path = "#{self.storagePath}/#{opts.fileId}#{ext}"
console.info "[FilesCollection] [Abort Method]: For #{path}" if self.debug
if self._writableStreams?[opts.fileId]
self._writableStreams[opts.fileId].stream.end()
delete self._writableStreams[opts.fileId]
self.remove({_id: opts.fileId})
self.unlink({_id: opts.fileId, 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.meta ?= {}
opts.binData ?= 'EOF'
opts.chunkId ?= -1
opts.FSName ?= opts.fileId
fileName = @getFileName opts.file
{extension, extensionWithDot} = @getExt fileName
result = opts.file
result.path = "#{@storagePath}/#{opts.FSName}#{extensionWithDot}"
result.name = fileName
result.meta = opts.file.meta
result.extension = extension
result.ext = extension
result = @dataToSchema result
result._id = opts.fileId
result.userId = userId if userId
console.info "[FilesCollection] [Write Method] [#{transport}] Got ##{opts.chunkId}/#{opts.fileLength} chunks, dst: #{opts.file.name or opts.file.fileName}" if @debug
if @onBeforeUpload and _.isFunction @onBeforeUpload
isUploadAllowed = @onBeforeUpload.call(_.extend({
file: opts.file
}, {
userId: result.userId
user: -> if Meteor.users then Meteor.users.findOne(result.userId) else undefined
chunkId: opts.chunkId
eof: opts.eof
}), result)
if isUploadAllowed isnt true
throw new Meteor.Error(403, if _.isString(isUploadAllowed) then isUploadAllowed else '@onBeforeUpload() returned false')
return {result, opts}
else undefined
###
@locus Server
@memberOf FilesCollection
@name finishUpload
@summary Internal method. Finish upload, close Writable stream, add recored to MongoDB and flush used memory
@returns {undefined}
###
finishUpload: if Meteor.isServer then (result, opts, cb) ->
fs.chmod result.path, @permissions, NOOP
self = @
result.type = @getMimeType opts.file
result.public = @public
@collection.insert _.clone(result), (error, _id) ->
if error
cb new Meteor.Error 500, error
else
result._id = _id
console.info "[FilesCollection] [Write Method] [finishUpload] -> #{result.path}" if self.debug
self.onAfterUpload and self.onAfterUpload.call self, result
self.emit 'afterUpload', result
cb null, result
return
else undefined
###
@locus Server
@memberOf FilesCollection
@name handleUpload
@summary Internal method to handle upload process, pipe incoming data to Writable stream
@returns {undefined}
###
handleUpload: if Meteor.isServer then (result, opts, cb) ->
self = @
if opts.eof
binary = opts.binData
else
binary = new Buffer opts.binData, 'base64'
try
writeDelayed = ->
chunks = Object.keys self._writableStreams[result._id].delayed
if chunks.length
chunks.sort sortNumber
for chunk in chunks
if self._writableStreams[result._id].stream.bytesWritten is opts.chunkSize * (chunk - 1)
self._writableStreams[result._id].stream.write self._writableStreams[result._id].delayed?[chunk]
delete self._writableStreams[result._id].delayed[chunk]
return true
@_writableStreams[result._id] ?=
stream: fs.createWriteStream result.path, {flags: 'a', mode: @permissions}
delayed: {}
if opts.eof
writeDelayed()
@_writableStreams[result._id].stream.end()
delete @_writableStreams[result._id]
@emit 'finishUpload', result, opts, cb
else if opts.chunkId is 1
@_writableStreams[result._id].stream.write binary
@_writableStreams[result._id].stream.on 'drain', () ->
writeDelayed()
return
else if opts.chunkId > 0
start = opts.chunkSize * (opts.chunkId - 1)
@_writableStreams[result._id].delayed[opts.chunkId] = binary
writeDelayed()
catch e
cb and cb e
return
else undefined
###
@locus Anywhere
@memberOf FilesCollection
@name getMimeType
@param {Object} fileData - File Object
@summary Returns file's mime-type
@returns {String}
###
getMimeType: (fileData) ->
check fileData, Object
mime = fileData.type if fileData?.type
if Meteor.isServer and fileData.path and (not mime or not _.isString mime)
try
buf = new Buffer 262
fd = fs.openSync fileData.path, 'r'
br = fs.readSync fd, buf, 0, 262, 0
fs.close fd, NOOP
buf = buf.slice 0, br if br < 262
{mime, ext} = fileType buf
catch error
if not mime or not _.isString mime
mime = 'application/octet-stream'
return mime
###
@locus Anywhere
@memberOf FilesCollection
@name getFileName
@param {Object} fileData - File Object
@summary Returns file's name
@returns {String}
###
getFileName: (fileData) ->
fileName = fileData.name or fileData.fileName
if _.isString(fileName) and fileName.length > 0
cleanName = (str) -> str.replace(/\.\./g, '').replace /\//g, ''
return cleanName(fileData.name or fileData.fileName)
else
return ''
###
@locus Anywhere
@memberOf FilesCollection
@name getUser
@summary Returns object with `userId` and `user()` method which return user's object
@returns {Object}
###
getUser: (http) ->
result =
user: -> return null
userId: null
if Meteor.isServer
if http
cookie = http.request.Cookies
if _.has(Package, 'accounts-base') and cookie.has 'meteor_login_token'
user = Meteor.users.findOne 'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken cookie.get 'meteor_login_token'
if user
result.user = () -> return user
result.userId = user._id
else
if _.has(Package, 'accounts-base') and Meteor.userId()
result.user = -> return Meteor.user()
result.userId = Meteor.userId()
return result
###
@locus Anywhere
@memberOf FilesCollection
@name getExt
@param {String} FileName - File name
@summary Get extension from FileName
@returns {Object}
###
getExt: (fileName) ->
if !!~fileName.indexOf('.')
extension = fileName.split('.').pop()
return { ext: extension, extension, extensionWithDot: '.' + extension }
else
return { ext: '', extension: '', extensionWithDot: '' }
###
@locus Anywhere
@memberOf FilesCollection
@name dataToSchema
@param {Object} data - File data
@summary Build object in accordance with schema from File data
@returns {Object}
###
dataToSchema: (data) ->
return {
name: data.name
extension: data.extension
path: data.path
meta: data.meta
type: data.type
size: data.size
versions:
original:
path: data.path
size: data.size
type: data.type
extension: data.extension
isVideo: !!~data.type.toLowerCase().indexOf('video')
isAudio: !!~data.type.toLowerCase().indexOf('audio')
isImage: !!~data.type.toLowerCase().indexOf('image')
isText: !!~data.type.toLowerCase().indexOf('text')
isJSON: !!~data.type.toLowerCase().indexOf('json')
_prefix: data._prefix or @_prefix
_storagePath: data._storagePath or @storagePath
_downloadRoute: data._downloadRoute or @downloadRoute
_collectionName: data._collectionName or @collectionName
}
###
@locus Anywhere
@memberOf FilesCollection
@name srch
@param {String|Object} search - Search data
@summary Build search object
@returns {Object}
###
srch: (search) ->
if search and _.isString search
@search =
_id: search
else
@search = search or {}
@search
###
@locus Server
@memberOf FilesCollection
@name write
@param {Buffer} buffer - Binary File's Buffer
@param {Object} opts - Object with file-data
@param {String} opts.name - File name, alias: `fileName`
@param {String} opts.type - File mime-type
@param {Object} opts.meta - File additional meta-data
@param {Function} callback - function(error, fileObj){...}
@summary Write buffer to FS and add to FilesCollection Collection
@returns {FilesCollection} Instance
###
write: if Meteor.isServer then (buffer, opts = {}, callback) ->
console.info "[FilesCollection] [write()]" if @debug
if _.isFunction opts
callback = opts
opts = {}
check opts, Match.Optional Object
check callback, Match.Optional Function
fileId = Random.id()
FSName = if @namingFunction then @namingFunction() else fileId
fileName = if (opts.name or opts.fileName) then (opts.name or opts.fileName) else FSName
{extension, extensionWithDot} = @getExt fileName
self = @
opts ?= {}
opts.path = "#{@storagePath}/#{FSName}#{extensionWithDot}"
opts.type = @getMimeType opts
opts.meta ?= {}
opts.size ?= buffer.length
result = @dataToSchema
name: fileName
path: opts.path
meta: opts.meta
type: opts.type
size: opts.size
extension: extension
result._id = fileId
stream = fs.createWriteStream opts.path, {flags: 'w', mode: @permissions}
stream.end buffer, (error) -> bound ->
if error
callback and callback error
else
self.collection.insert _.clone(result), (error) ->
if error
callback and callback error
console.warn "[FilesCollection] [write] [insert] Error: #{fileName} -> #{self.collectionName}", error if self.debug
else
callback and callback null, result
console.info "[FilesCollection] [write]: #{fileName} -> #{self.collectionName}" if self.debug
return @
else
undefined
###
@locus Server
@memberOf FilesCollection
@name load
@param {String} url - URL to file
@param {Object} opts - Object with file-data
@param {String} opts.name - File name, alias: `fileName`
@param {String} opts.type - File mime-type
@param {Object} opts.meta - File additional meta-data
@param {Function} callback - function(error, fileObj){...}
@summary Download file, write stream to FS and add to FilesCollection Collection
@returns {FilesCollection} Instance
###
load: if Meteor.isServer then (url, opts, callback) ->
console.info "[FilesCollection] [load(#{url}, #{JSON.stringify(opts)}, callback)]" if @debug
if _.isFunction opts
callback = opts
opts = {}
check url, String
check opts, Match.Optional Object
check callback, Match.Optional Function
self = @
opts ?= {}
fileId = Random.id()
FSName = if @namingFunction then @namingFunction() else fileId
pathParts = url.split('/')
fileName = if (opts.name or opts.fileName) then (opts.name or opts.fileName) else pathParts[pathParts.length - 1] or FSName
{extension, extensionWithDot} = @getExt fileName
opts.path = "#{@storagePath}/#{FSName}#{extensionWithDot}"
opts.meta ?= {}
request.get(url).on('error', (error)-> bound ->
throw new Meteor.Error 500, "Error on [load(#{url})]:" + JSON.stringify error
).on('response', (response) -> bound ->
console.info "[FilesCollection] [load] Received: #{url}" if self.debug
result = self.dataToSchema
name: fileName
path: opts.path
meta: opts.meta
type: opts.type or response.headers['content-type']
size: opts.size or parseInt(response.headers['content-length'] or 0)
extension: extension
result._id = fileId
self.collection.insert _.clone(result), (error) ->
if error
callback and callback error
console.warn "[FilesCollection] [load] [insert] Error: #{fileName} -> #{self.collectionName}", error if self.debug
else
callback and callback null, result
console.info "[FilesCollection] [load] [insert] #{fileName} -> #{self.collectionName}" if self.debug
).pipe fs.createWriteStream(opts.path, {flags: 'w', mode: @permissions})
return @
else
undefined
###
@locus Server
@memberOf FilesCollection
@name addFile
@param {String} path - Path to file
@param {String} opts - Object with file-data
@param {String} opts.type - File mime-type
@param {Object} opts.meta - File additional meta-data
@param {Function} callback - function(error, fileObj){...}
@summary Add file from FS to FilesCollection
@returns {FilesCollection} Instance
###
addFile: if Meteor.isServer then (path, opts, callback) ->
console.info "[FilesCollection] [addFile(#{path})]" if @debug
if _.isFunction opts
callback = opts
opts = {}
throw new Meteor.Error 403, 'Can not run [addFile] on public collection! Just Move file to root of your server, then add record to Collection' if @public
check path, String
check opts, Match.Optional Object
check callback, Match.Optional Function
self = @
fs.stat path, (error, stats) -> bound ->
if error
callback and callback error
else if stats.isFile()
pathParts = path.split '/'
fileName = pathParts[pathParts.length - 1]
{extension, extensionWithDot} = self.getExt fileName
opts ?= {}
opts.path = path
opts.type ?= self.getMimeType opts
opts.meta ?= {}
opts.size ?= stats.size
result = self.dataToSchema
name: fileName
path: path
meta: opts.meta
type: opts.type
size: opts.size
extension: extension
_storagePath: path.replace "/#{fileName}", ''
result._id = Random.id()
self.collection.insert _.clone(result), (error) ->
if error
callback and callback error
console.warn "[FilesCollection] [addFile] [insert] Error: #{fileName} -> #{self.collectionName}", error if self.debug
else
callback and callback null, result
console.info "[FilesCollection] [addFile]: #{fileName} -> #{self.collectionName}" if self.debug
else
callback and callback new Meteor.Error 400, "[FilesCollection] [addFile(#{path})]: File does not exist"
return @
else
undefined
###
@locus Anywhere
@memberOf FilesCollection
@name findOne
@param {String|Object} search - `_id` of the file or `Object` like, {prop:'val'}
@summary Load file
@returns {FilesCollection} Instance
###
findOne: (search) ->
console.info "[FilesCollection] [findOne(#{JSON.stringify(search)})]" if @debug
check search, Match.Optional Match.OneOf Object, String
@srch search
if @checkAccess()
@currentFile = @collection.findOne @search
@cursor = null
return @
###
@locus Anywhere
@memberOf FilesCollection
@name find
@param {String|Object} search - `_id` of the file or `Object` like, {prop:'val'}
@summary Load file or bunch of files
@returns {FilesCollection} Instance
###
find: (search) ->
console.info "[FilesCollection] [find(#{JSON.stringify(search)})]" if @debug
check search, Match.Optional Match.OneOf Object, String
@srch search
if @checkAccess()
@currentFile = null
@cursor = @collection.find @search
return @
###
@locus Anywhere
@memberOf FilesCollection
@name get
@summary Return value of current cursor or file
@returns {Object|[Object]}
###
get: () ->
console.info '[FilesCollection] [get()]' if @debug
return @cursor.fetch() if @cursor
return @currentFile
###
@locus Anywhere
@memberOf FilesCollection
@name fetch
@summary Alias for `get()` method
@returns {[Object]}
###
fetch: () ->
console.info '[FilesCollection] [fetch()]' if @debug
data = @get()
if not _.isArray data
return [data]
else
data
###
@locus Client
@memberOf FilesCollection
@name insert
@see https://developer.mozilla.org/en-US/docs/Web/API/FileReader
@param {Object} config - Configuration object with next properties:
{File|Object} file - HTML5 `files` item, like in change event: `e.currentTarget.files[0]`
{Object} meta - Additional data as object, use later for search
{Boolean} allowWebWorkers- Allow/Deny WebWorkers usage
{Number|dynamic} streams - Quantity of parallel upload streams, default: 2
{Number|dynamic} chunkSize - Chunk size for upload
{Function} onUploaded - Callback triggered when upload is finished, with two arguments `error` and `fileRef`
{Function} onStart - Callback triggered when upload is started after all successful validations, with two arguments `error` (always null) and `fileRef`
{Function} onError - Callback triggered on error in upload and/or FileReader, with two arguments `error` and `fileData`
{Function} onProgress - Callback triggered when chunk is sent, with only argument `progress`
{Function} onBeforeUpload - Callback triggered right before upload is started:
return true to continue
return false to abort upload
@param {Boolean} autoStart - Start upload immediately. If set to false, you need manually call .start() method on returned class. Useful to set EventListeners.
@summary Upload file to server over DDP
@returns {UploadInstance} Instance. UploadInstance has next properties:
{ReactiveVar} onPause - Is upload process on the pause?
{ReactiveVar} state - active|paused|aborted|completed
{ReactiveVar} progress - Current progress in percentage
{Function} pause - Pause upload process
{Function} continue - Continue paused upload process
{Function} toggle - Toggle continue/pause if upload process
{Function} abort - Abort upload
{Function} readAsDataURL - Current file as data URL, use to create image preview and etc. Be aware of big files, may lead to browser crash
###
insert: if Meteor.isClient then (config, autoStart = true) ->
if @checkAccess()
mName = if autoStart then 'start' else 'manual'
return (new @_UploadInstance(config, @))[mName]()
else
throw new Meteor.Error 401, "[FilesCollection] [insert] Access Denied"
else undefined
###
@locus Client
@memberOf FilesCollection
@name _UploadInstance
@class UploadInstance
@summary Internal Class, used in upload
###
_UploadInstance: if Meteor.isClient then class UploadInstance
__proto__: EventEmitter.prototype
constructor: (@config, @collection) ->
EventEmitter.call @
console.info '[FilesCollection] [insert()]' if @collection.debug
self = @
@config.meta ?= {}
@config.streams ?= 2
@config.streams = 2 if @config.streams < 1
@config.transport ?= 'ddp'
@config.chunkSize ?= @collection.chunkSize
@config.allowWebWorkers ?= true
@config.transport = @config.transport.toLowerCase()
check @config, {
file: Match.Any
meta: Match.Optional Object
onError: Match.Optional Function
onAbort: Match.Optional Function
streams: Match.OneOf 'dynamic', Number
onStart: Match.Optional Function
transport: Match.OneOf 'http', 'ddp'
chunkSize: Match.OneOf 'dynamic', Number
onUploaded: Match.Optional Function
onProgress: Match.Optional Function
onBeforeUpload: Match.Optional Function
allowWebWorkers: Boolean
}
if @config.file
console.time('insert ' + @config.file.name) if @collection.debug
console.time('loadFile ' + @config.file.name) if @collection.debug
if Worker and @config.allowWebWorkers
@worker = new Worker '/packages/ostrio_files/worker.js'
else
@worker = null
@trackerComp = null
@currentChunk = 0
@sentChunks = 0
@EOFsent = false
@transferTime = 0
@fileLength = 1
@fileId = Random.id()
@FSName = if @namingFunction then @namingFunction() else @fileId
@pipes = []
@fileData =
size: @config.file.size
type: @config.file.type
name: @config.file.name
meta: @config.meta
@fileData = _.extend @fileData, @collection.getExt(self.config.file.name), {mime: @collection.getMimeType(@fileData)}
@fileData['mime-type'] = @fileData.mime
@result = new @collection._FileUpload _.extend self.config, {@fileData, @fileId, MeteorFileAbort: @collection.methodNames.MeteorFileAbort}