-
Notifications
You must be signed in to change notification settings - Fork 1
/
infowrap-filepicker.coffee
1157 lines (967 loc) · 36.8 KB
/
infowrap-filepicker.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
###*
* @ngdoc module
* @name infowrapFilepicker
* @description
*
* The primary module which needs to be injected into your application to provide filepicker services and directives.
*
###
infowrapFilepicker = angular.module("infowrapFilepicker", [])
infowrapFilepicker
.config ['$provide', ($provide) ->
$provide.decorator '$rootScope', ['$delegate', ($delegate) ->
# everybody needs a safeApply :)
$delegate.safeApply = (fn) ->
phase = $delegate.$$phase
if phase is "$apply" or phase is "$digest"
if fn and typeof fn is 'function'
# in middle of digest, just execute function normally
fn()
else
$delegate.$apply(fn)
return $delegate
]
]
infowrapFilepicker.provider "fpConfig", ->
_apiKey = undefined
_debug = false
_security = false
_options = {}
setApiKey: (apiKey) ->
_apiKey = apiKey
setDebug: (enable) ->
_debug = enable
setSecurity: (enable) ->
_security = enable
setOptions: (options) ->
_options = options or {}
$get: ->
api = {}
api.apiKey = ->
_apiKey
api.debug = ->
_debug
api.security = ->
_security
api.options = ->
_options
api
###*
* @ngdoc object
* @name infowrapFilepicker.service:infowrapFilepickerService
* @requires $log
* @requires $window
* @requires $q
* @requires $rootScope
* @requires $timeout
* @description
*
* FilepickerService is responsible for exposing filepicker's api to your angular app.
*
* Currently, only a basic subset of their api is implemented.
* However, in the future we would like for this service to be configurable to implement only the api's you need/use.
*
* Feel free to issue a pull request if you find yourself motivated to flush out all the implementations.
* For a complete list of filepicker api calls, see <a href="https://developers.inkfilepicker.com/docs/web/" target="_blank">filepicker's documentation</a>.
*
###
infowrapFilepicker.provider "infowrapFilepickerService", ->
$get: ["fpConfig", "infowrapFilepickerSecurity", "$log", "$window", "$q", "$rootScope", "$timeout", (config, fps, $log, $window, $q, $rootScope, $timeout) ->
api = {}
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#loadFilepicker
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Loads the filepicker javascript library.
*
* @returns {object} promise - gets resolved when filepicker library is loaded
*
###
api.loadFilepicker = ->
defer = $q.defer()
# Configure a specific protocol to use or fallback to using whatever protocol this is being hosted from
configuredProtocol = config.options().loadProtocol or ""
$('body').append("<script type=\"text/javascript\" src=\"#{configuredProtocol}//api.filepicker.io/v2/filepicker.js\"></script>")
checkIfLoaded = ->
if _.isUndefined($window.filepicker)
$timeout ->
checkIfLoaded()
, 50
else
defer.resolve()
checkIfLoaded()
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#log
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Basic utility to provide debug logging for the module.
*
* @param {string} message - the message to log to output
* @param {string} type (error, info, etc)
*
###
api.log = (msg, type) ->
if config.debug()
if type
$log[type](msg)
else
$log.log(msg)
api.events = {}
# standardize event names
# uniquely identify event names with prefix
eventPrefix = "infowrapFilepicker"
# should match filepicker's api methods
apiMethods = ["pick", "pickAndStore", "exportFile", "read", "stat", "write", "writeUrl", "store", "convert", "remove"]
# helper events
helperEvents = ["pickedFiles", "error", "readingFiles", "readingFilesComplete", "readVCard", "readProgress", "resetFilesUploading", "progress", "storeProgress", "writeUrlProgress", "uploadProgress", "uploadsComplete"]
# combine api and helper events for processing
allEvents = apiMethods.concat(helperEvents)
# modal events
modalEvents = ["close"]
api.events.modal = {}
_.forEach modalEvents, (event) ->
api.events.modal[event] = "#{eventPrefix}:modal:" + event
_.forEach allEvents, (event) ->
api.events[event] = "#{eventPrefix}:" + event
# build service interface
if _.includes(apiMethods, event)
# if valid api method, mock the implementation (full implementations added below)
api[event] = ->
api.log("#{event} needs implementation!", "error")
# DEFAULT PICK OPTIONS
defaultPickOptions =
container: "modal" # default to modal
maxSize: 5 * 1024 * 1024 # 5 MB
pickOptions = _.extend(defaultPickOptions, config.options().pickOptions)
preparePickOptions = (opt) ->
opt = opt or {}
# always default to multiple if unspecified
# must check hasOwnProperty because we could be explicitly passing in false (bool)
opt.multiple = if opt.hasOwnProperty('multiple') then opt.multiple else true
# when using custom options, clone default pickOptions so they are not modified for later usage!
options = _.clone(pickOptions, true)
_.extend(options, opt) # merge custom options with defaults
return options
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#positionModal
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* When using iframe container, this will center the modal on screen.
*
###
api.positionModal = () ->
# only used when FilePickerIO.config provides a value for 'iframeContainer'
if config.options().iframeContainer
$iframeContainer = $("##{config.options().iframeContainer}")
$win = angular.element($window)
h = $win.outerHeight(true)
if config.options().isMobile
# fill entire viewport on mobile
top = left = 0
width = '100%'
height = "#{h + 60}px" # add address bar
else
w = $win.outerWidth(true)
width = "#{w}px"
height = "#{h}px"
top = 50
left = w/2 - $iframeContainer.width()/2
if left < 0
# if negative, make flush left
left = 0
positionSettings =
top:"#{top}px"
left:"#{left}px"
_.extend(positionSettings, {width:width, height:height}) if config.options().isMobile
$iframeContainer.css(positionSettings)
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#modalToggle
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Toggle on/off the picker modal.
*
* This also sets up ESC key listener to close the modal as well as window resize to reposition modal.
*
###
api.modalToggle = (force) ->
enabled = if _.isUndefined(force) then not $rootScope.filepickerModalOpen else force
$rootScope.filepickerModalOpen = enabled
$rootScope.safeApply()
handleEscapeKey = (e) ->
if e.which is 27
e.preventDefault()
if $rootScope.filepickerModalOpen
# toggle modal off when hitting ESC, only if it's actually open
$rootScope.safeApply ->
api.modalToggle(false)
handleModalPosition = (e) ->
if $rootScope.filepickerModalOpen
api.positionModal()
$body = angular.element('body')
$win = angular.element($window)
if enabled
$body.bind('keydown', handleEscapeKey)
$win.bind('resize', handleModalPosition)
$timeout ->
# always ensure window is scrolled to top when this modal appears
$win.scrollTop(0)
, if config.options().isMobile then 300 else 0
else
$body.unbind('keydown', handleEscapeKey)
$win.unbind('resize', handleModalPosition)
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#pick
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* This combines `pick` and `pickMultiple`.
*
* They are combined here for simplicity and code reduction.
* The `options` parameter defaults `multiple:true`, so it will call `pickMultiple` by default.
* However, pass in multiple:false to limit the picker to just one file selection.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#pick) to learn more.
###
api.pick = (opt) ->
defer = $q.defer()
opt = preparePickOptions(opt)
api.log(opt)
# show modal
api.modalToggle(true)
onSuccess = (fpfiles) ->
$rootScope.safeApply ->
api.modalToggle(false)
defer.resolve(fpfiles)
onError = (fperror) ->
api.log(fperror)
$rootScope.safeApply ->
api.modalToggle(false)
defer.reject(fperror)
if opt.multiple
filepicker.pickMultiple(opt, onSuccess, onError)
else
filepicker.pick(opt, onSuccess, onError)
# post evaluate modal positioning
$timeout ->
# important that this is evaluated after angular has digested everything
api.positionModal()
, 0
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#pickAndStore
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `pickAndStore`.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#pickAndStore) to learn more.
###
api.pickAndStore = (opt) ->
defer = $q.defer()
opt = preparePickOptions(opt)
api.log(opt)
# show modal
api.modalToggle(true)
onSuccess = (fpfiles) ->
$rootScope.safeApply ->
api.modalToggle(false)
defer.resolve(fpfiles)
onError = (fperror) ->
api.log(fperror)
$rootScope.safeApply ->
api.modalToggle(false)
defer.reject(fperror)
storeOptions =
location:'S3'
path:opt.path
filepicker.pickAndStore(opt, storeOptions, onSuccess, onError)
# post evaluate modal positioning
$timeout ->
# important that this is evaluated after angular has digested everything
api.positionModal()
, 0
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#writeUrl
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `writeUrl`.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#writeUrl) to learn more.
###
api.writeUrl = (targetFpFile, url, opt) ->
defer = $q.defer()
opt = opt or {}
cleanUrl = _.first(url.split('?'))
api.log(cleanUrl)
filepicker.writeUrl targetFpFile, cleanUrl, opt, (fpfile) ->
$rootScope.safeApply ->
defer.resolve(fpfile)
, (fperror) ->
api.log(fperror)
$rootScope.safeApply ->
defer.reject(fperror)
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#store
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `store`.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#store) to learn more.
###
api.store = (input, opt) ->
defer = $q.defer()
storeFile = (signedPolicy) ->
result = input: input
options =
location:'S3'
if config.security()
# assign signed policy first
options.policy = signedPolicy.encoded_policy
options.signature = signedPolicy.signature
options.path = signedPolicy.policy.path
else
options.path = opt.path
options.base64decode = true if opt.base64encode
options.filename = opt.filename if opt.filename
options.mimetype = opt.mimetype if opt.mimetype
percentProgress = (percent) ->
$rootScope.safeApply ->
$rootScope.$broadcast(api.events.storeProgress, percent)
percentDispatch = _.throttle(percentProgress, 400)
filepicker.store input, options, (data) ->
_.extend(result, data: data)
$rootScope.safeApply ->
defer.resolve(result)
, (fperror) ->
api.log(fperror)
_.extend(result, error: fperror)
$rootScope.safeApply ->
defer.reject(result)
, percentDispatch
# commenting out progress events due to filepicker bug
# , (percent) ->
# _.extend(result, progress: percent)
# $rootScope.safeApply ->
# $rootScope.$broadcast(api.events.storeProgress, result)
if config.security()
# check if a cached policy already exist for this
cachedPolicy = fps.getCachedPolicy({new:true})
if cachedPolicy
storeFile(cachedPolicy)
else
# no cached policy, sign to get one
signOptions =
new:true
if opt.wrapId
signOptions.wrapId = opt.wrapId
else if opt.signType
signOptions.signType = opt.signType
fps.sign(signOptions).then (signedPolicy) ->
storeFile(signedPolicy)
else
storeFile()
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#storeUrl
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `storeUrl`.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#store) to learn more.
###
api.storeUrl = (input, opt) ->
defer = $q.defer()
storeFile = (signedPolicy) ->
result = input: input
# assign signed policy first
options =
policy: signedPolicy.encoded_policy
signature: signedPolicy.signature
path: signedPolicy.policy.path
location:'S3'
options.filename = opt.filename if opt.filename
filepicker.storeUrl input, options, (data) ->
_.extend(result, data: data)
$rootScope.safeApply ->
defer.resolve(result)
, (fperror) ->
api.log(fperror)
_.extend(result, error: fperror)
$rootScope.safeApply ->
defer.reject(result)
# commenting out progress events due to filepicker bug
# , (percent) ->
# _.extend(result, progress: percent)
# $rootScope.safeApply ->
# $rootScope.$broadcast(api.events.storeProgress, result)
# check if a cached policy already exist for this
cachedPolicy = fps.getCachedPolicy({new:true})
if cachedPolicy
storeFile(cachedPolicy)
else
# no cached policy, sign to get one
signOptions =
new:true
if opt.wrapId
signOptions.wrapId = opt.wrapId
else if opt.signType
signOptions.signType = opt.signType
fps.sign(signOptions).then (signedPolicy) ->
storeFile(signedPolicy)
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#export
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `export`.
*
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#export) to learn more.
###
api.export = (input, opt, success, failure) ->
defer = $q.defer()
opt = opt or {}
fps.sign({id:input.id, new:true}).then () ->
newPolicy = fps.cachedPolicies.new
options =
policy: newPolicy.encoded_policy
signature: newPolicy.signature
opt = _.extend opt, options
# fps.secureForReading([input], {id:true}).then (result) ->
# api.log(result)
filepicker.exportFile input.url.url, opt, (data) ->
$rootScope.safeApply ->
defer.resolve(data)
, (fperror) ->
api.log(fperror)
$rootScope.safeApply ->
defer.reject(fperror)
defer.promise
###*
* @doc method
* @name infowrapFilepicker.service:infowrapFilepickerService#read
* @methodOf infowrapFilepicker.service:infowrapFilepickerService
* @description
*
* Filepicker's `read`.
*
* `base64encode:true` is the default. Use this to read images.
*
* If you need to read text, pass in `asText:true`
*
* @param {object} input - The object to read. Can be an InkBlob, a URL, a DOM File Object, or a file input.
* @param {object} options - see filepicker docs [here](https://developers.inkfilepicker.com/docs/web/#read) to learn more.
###
api.read = (input, opt) ->
defer = $q.defer()
opt = opt or {base64encode: true}
usingImage = opt.base64encode
readFile = (url) ->
api.log("filepicker.read: #{url}")
existingPolicy = fps.cachedPolicies.existing
_.extend opt,
policy: existingPolicy.encoded_policy
signature: existingPolicy.signature
result = input: input
filepicker.read url, opt, (data) ->
data = "data:image/png;base64,#{data}" if usingImage
_.extend(result, data: data)
$rootScope.safeApply ->
defer.resolve(result)
$rootScope.$broadcast(api.events.read, result)
, (fperror) ->
api.log(fperror)
_.extend(result, error: fperror)
$rootScope.safeApply ->
defer.reject(result)
# commenting out progress events due to filepicker bug
# , (percent) ->
# _.extend(result, progress: percent)
# $rootScope.safeApply ->
# $rootScope.$broadcast(api.events.readProgress, result)
getUrlToReadFrom = (input, options) ->
url = input
if _.isObject(input)
# only specify file_id if a valid id (as a number) is present on the input
_.extend(options, {id:input.id}) if options and _.isNumber(input.id)
if _.isObject(input.url)
# bizbuilt.com api wraps filepicker in a hash {exp:'expiry',url:'fp_url'}
url = input.url.url
else
url = input.url
# only specify handle as an option when no policy/signature are found on the url (meaning haven't been saved)
# handle is used to generate clientside previews for files that have not been stored yet
_.extend(options, {handle:url}) if options and url.indexOf('policy') is -1
url
# must always sign when reading files as the handle is critical to match the encoded policy
signOptions = {}
url = getUrlToReadFrom(input, signOptions)
fps.sign(signOptions).then ->
readFile(url)
defer.promise
###
END filepicker api implementations
###
###
Helper functions and sweeteners
###
api.previewTargetLoad = () ->
if api.dropDomId
$el = $("##{api.dropDomId}")
$el.addClass('loading-image')
api.previewTargetReady = (result, ignoreImgLoad) ->
$el = $("##{api.dropDomId}")
fieldName = $el.data('field-name')
cleanSrc = undefined
cleanSrc = result.data.replace(/\n/g, "")
unless ignoreImgLoad
targetImage = document.createElement("image")
targetImage.onload = ->
#$el.css "background-image": "none"
$timeout(->
$el.removeClass('loading-image') #.addClass('preview-loaded')
$el.css
"background-image": "url(" + cleanSrc + ")"
, 100)
targetImage.src = ""
targetImage.src = cleanSrc
target =
fieldName: fieldName
data: _.extend(result.input, {id:_.uniqueId()})
target
# vCard
api.readVCardData = (input) ->
defer = $q.defer()
if input
api.read(input, asText:true).then (readResult) ->
result =
data: vCard.initialize(readResult.data)
input: readResult.input
defer.resolve(result)
$rootScope.$broadcast api.events.readVCard, result
defer.promise
api.readFiles = (files, dropZone, preventDefault) ->
$rootScope.$broadcast api.events.readingFiles unless preventDefault
unless api.dropTargetField
# when dropTargetField is defined, we want to ignore reading files altogether
# dropTargetField will cause an immediate resource update and therefore not require further user action or preview
if dropZone
api.log("--------\nDropped on specific zone target!")
api.log(dropZone)
api.log("for: " + dropZone.data("for"))
else
cnt = 0
continueReading = () ->
cnt++
if cnt < files.length
# read next file
readFile()
else
$rootScope.$broadcast api.events.readingFilesComplete
$rootScope.safeApply()
readFile = () ->
file = files[cnt]
fileName = file.name or file.filename
if file.type isnt 'file_asset'
fileType = file.type or file.mimetype or file.mime_type
else
fileType = file.mime_type
result = input: file
api.log("---------\nReading file:")
api.log(fileName + " (#{fileType})")
fileType = "image" if fileType.search(/image\/(gif|jpeg|png|tiff)/) > -1
switch fileType
when "text/directory"
api.readVCardData(file).then ->
continueReading()
when "image"
api.read(file).then ->
continueReading()
when "text/plain"
continueReading()
$rootScope.$broadcast api.events.read, _.extend(result)
when "application/pdf"
continueReading()
$rootScope.$broadcast api.events.read, _.extend(result)
# start reading
readFile()
# this safeApply is CRITICAL! do not remove! ... or be a lost soul on a lonely island!
$rootScope.safeApply()
api.addToFilesUploading = (files) ->
api.filesUploading = api.filesUploading.concat(_.flatten(files))
_.forEach api.filesUploading, (file) ->
# provide unique id's for view handling
file.id = _.uniqueId((file.name or file.filename))
# upload progress
api.setUploadProgress = (data) ->
percent = Math.floor(data)
api.log("Uploading (" + percent + "%)")
api.uploadProgress = percent
api.uploadProgressStyle = width: percent + "%"
if percent > 25
$timeout (->
$fileStatus = $(".file-status")
totalWidth = $fileStatus.find(".upload-percentage").width()
rightOffset = totalWidth - Math.floor(totalWidth * (percent * .01))
$fileStatus.find(".upload-percent-text").css right: (rightOffset + 12) + "px"
), 200
api.uploadProgressClasses = ->
(if api.filesUploading.length then "progress-striped active" else "progress-info")
api.addToFilesUploaded = (files) ->
# You could potentially persist filesUploaded to localStorage here
api.filesUploaded = api.filesUploaded.concat(_.flatten(files))
_.forEach api.filesUploaded, (file) ->
unless file.hasOwnProperty('created_at')
file.created_at = JSON.parse(JSON.stringify(new Date()))
# when adding to filesUploaded, always clear filesUploading
api.filesUploading = []
$rootScope.uploadsInProgress = false
api.clearFilesUploaded = ->
api.filesUploaded = []
api.resetFileStatus = ->
$rootScope.uploadsInProgress = false
api.usedFilePickerDialog = false
api.dropDomId = undefined
api.dropTargetId = undefined
api.dropTargetParentId = undefined
api.dropTargetType = undefined
api.dropTargetField = undefined
api.dropWindow = undefined
api.uploadProgress = 0
api.uploadProgressStyle =
width: "0px"
api.filesUploading = api.filesUploaded = []
api.resetFileStatus() # call reset status to initialize properties
api
]
###*
* @ngdoc object
* @name infowrapFilepicker.service:infowrapFilepickerSecurity
* @requires infowrapFilepickerService
* @requires $log
* @requires $q
* @requires $rootScope
* @requires $http
* @description
*
* FilepickerSecurity is an implementation of the security signing scheme devised by the Filepicker team.
*
* This security signing is setup to work directly with our ruby gem, <a href="https://github.com/infowrap/filepicker_client" target="_blank">filepicker_client</a>.
*
*
###
infowrapFilepicker.provider "infowrapFilepickerSecurity", ->
$get: ["fpConfig", "$log", "$q", "$rootScope", "$http", (config, $log, $q, $rootScope, $http) ->
# security for filepicker
signingInProcess = false # helps avoid multiple signing calls at once
getOperations = (isNew) ->
if isNew then api.operations.new else api.operations.existing
api = {}
# useful to cache policies in case the same operation is being used in farely rapid succession
api.cachedPolicies =
new:{}
existing:{}
# types: this is for specific types of signing which may use a special sign api call than the default
types:{}
# due to their nature, best to have filepicker's api split out into 2 different sets of operations
# this makes signing simpler for various purposes
api.operations =
new:['pick', 'store', 'storeUrl'] # for creation of 'new' filepicker files
existing: ['read', 'stat', 'convert', 'write', 'writeUrl'] # for working with 'existing' filepicker files
# use this to check if a valid cached policy exists for the set of operations needed
api.getCachedPolicy = (opt) ->
opt = opt or {}
# opt:
# new(bool) - flag to check the appropriate cached policy for the particular set of operations
#
# ...more options may be required in the future
if _.isUndefined(opt.signType)
cachedPolicy = api.cachedPolicies[if opt.new then 'new' else 'existing']
else
cachedPolicy = api.cachedPolicies.types[opt.signType]
if cachedPolicy
cachedPolicy = api.cachedPolicies.types[opt.signType][if opt.new then 'new' else 'existing']
if cachedPolicy and cachedPolicy.policy
operations = getOperations(opt.new)
# check if operation requested already has a valid policy cached
isCached = _.find cachedPolicy.policy.call, (operation) ->
_.includes(operations, operation)
if isCached and cachedPolicy.policy.expiry
# check the expiration
rightNowEpoch = Math.floor(new Date().getTime() / 1000)
if rightNowEpoch <= Number(cachedPolicy.policy.expiry)
return cachedPolicy
return false
api.sign = (opt) ->
opt = opt or {}
# opt: new(bool), id(int), size(int)
defer = $q.defer()
signage =
options:
call:getOperations(opt.new)
_.extend(signage.options, {file_id:opt.id}) if opt.id
# handle is primarily for reading files that have not been stored yet
# must strip the filepicker id off the end of the handle
_.extend(signage.options, {handle:opt.handle.substr(opt.handle.lastIndexOf('/') + 1)}) if opt.handle
_.extend(signage.options, {file_size:opt.size}) if opt.size
# Infowrap specific
# default to wrap
activeWrapId = if $rootScope.activeWrap then $rootScope.activeWrap.id else undefined
opt.resourceId = opt.wrapId or activeWrapId
if opt.signType is 'account'
# override resourceId for specific types
opt.resourceId = opt.signTypeResourceId or $rootScope.currentUser.id
unless signingInProcess
# prevent multiple simultaneous signing calls (can happen on page load)
signingInProcess = true
handleError = (error) ->
$log.log("--- filepicker security sign ERROR ---")
if error is 'filenotfound'
if config.debug()
$log.log(error)
if config.options().errorHandling
# check all errors that need to be handled
for errorHandler in config.options().errorHandling
if _.includes errorHandler.msgs, error
$rootScope.$emit errorHandler.eventName,
data:
error: error
$http.post(config.options().signApiUrl(opt.resourceId, opt.signType), signage).success((result) ->
signingInProcess = false
# cache the policy for the appropriate operation sets
if result and result.error
handleError(result.error)
defer.reject(result.error)
else
if config.debug()
$log.log("--- filepicker security sign ---")
$log.log(signage.options.call)
updateSignTypePolicy = () ->
cachedType = api.cachedPolicies.types[opt.signType]
if _.isUndefined(cachedType)
api.cachedPolicies.types[opt.signType] = {}
api.cachedPolicies.types[opt.signType][if opt.new then 'new' else 'existing'] = result
getSignedPolicy = () ->
if opt.new
if _.isUndefined(opt.signType)
api.cachedPolicies.new = result
else
updateSignTypePolicy()
else
if _.isUndefined(opt.signType)
api.cachedPolicies.existing = result
else
updateSignTypePolicy()
defer.resolve(getSignedPolicy())
).error (result) ->
signingInProcess = false
# TODO: should probably handle these errors in a standard way
if result and result.error
handleError(result.error)
defer.reject(result.error)
# safe apply is critical here - sometimes a sign() call will be made outside of angular's digest
# without this, the $http call above will sometimes not fire! - do not remove
$rootScope.safeApply()
defer.promise
api.secureForReading = (fpfiles, options) ->
defer = $q.defer()
fileCnt = 0
signFile = () ->
file = fpfiles[fileCnt]
signOptions = {}
if options and options.id
signOptions.id = file.id
else
# defaults to using url as handle
signOptions.handle = if _.isObject(file.url) then file.url.url else file.url
signOptions.signType = options.signType if options.signType
signOptions.signTypeResourceId = options.signTypeResourceId if options.signTypeResourceId
api.sign(signOptions).then ->
if _.isUndefined(signOptions.signType)
existingPolicy = api.cachedPolicies.existing
else
existingPolicy = api.cachedPolicies.types[signOptions.signType].existing
# update url to have a secure policy
appendedSecurity = "?signature=#{existingPolicy.signature}&policy=#{existingPolicy.encoded_policy}"
if _.isObject(file.url)
# our wrapped file_assets
file.url.url += appendedSecurity
else
# filepicker file
file.url += appendedSecurity
fileCnt++
if fileCnt is fpfiles.length
defer.resolve(fpfiles)
else
signFile()
signFile()
defer.promise
api
]
infowrapFilepicker.run(['fpConfig', 'infowrapFilepickerService', '$rootScope', '$window', (config, fp, $rootScope, $window) ->
if config.apiKey()
fp.loadFilepicker().then ->
$window.filepicker.setKey(config.apiKey())
else
fp.log("apiKey is required!", "error")
$rootScope.filepickerModalOpen = false
$rootScope.filepickerModalClose = () ->
fp.modalToggle(false)
$rootScope.$on '$routeChangeSuccess', () ->
# always reset on route change