-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
settings.js
1677 lines (1511 loc) · 46.7 KB
/
settings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function(){
// TODO: move to a separate file
var MOUNT_OPTIONS_DROPDOWN_TEMPLATE =
'<div class="drop dropdown mountOptionsDropdown">' +
// FIXME: options are hard-coded for now
' <div class="optionRow">' +
' <input id="mountOptionsEncrypt" name="encrypt" type="checkbox" value="true" checked="checked"/>' +
' <label for="mountOptionsEncrypt">{{t "files_external" "Enable encryption"}}</label>' +
' </div>' +
' <div class="optionRow">' +
' <input id="mountOptionsReadonly" name="read_only" type="checkbox" value="true"/>' +
' <label for="mountOptionsReadonly">{{t "files_external" "Set read-only"}}</label>' +
' </div>' +
' <div class="optionRow">' +
' <input id="mountOptionsPreviews" name="previews" type="checkbox" value="true" checked="checked"/>' +
' <label for="mountOptionsPreviews">{{t "files_external" "Enable previews"}}</label>' +
' </div>' +
' <div class="optionRow" title="{{mountOptionsSharingTitle}}">' +
' <input id="mountOptionsSharing" name="enable_sharing" type="checkbox" value="true" {{#if sharingDisabled}}disabled{{/if}}/>' +
' <label for="mountOptionsSharing">{{t "files_external" "Enable sharing"}}</label>' +
' </div>' +
' <div class="optionRow">' +
' <label for="mountOptionsFilesystemCheck">{{t "files_external" "Check for changes"}}</label>' +
' <select id="mountOptionsFilesystemCheck" name="filesystem_check_changes" data-type="int">' +
' <option value="0">{{t "files_external" "Never"}}</option>' +
' <option value="1" selected="selected">{{t "files_external" "Once every direct access"}}</option>' +
' </select>' +
' </div>' +
' <div class="optionRow">' +
' <input id="mountOptionsEncoding" name="encoding_compatibility" type="checkbox" value="true"/>' +
' <label for="mountOptionsEncoding">{{mountOptionsEncodingLabel}}</label>' +
' </div>' +
'</div>';
/**
* Returns the selection of applicable users in the given configuration row
*
* @param $row configuration row
* @return array array of user names
*/
function getSelection($row) {
var values = $row.find('.applicableUsers').select2('val');
if (!values || values.length === 0) {
values = [];
}
return values;
}
function highlightBorder($element, highlight) {
$element.toggleClass('warning-input', highlight);
return highlight;
}
function isInputValid($input) {
var optional = $input.hasClass('optional');
switch ($input.attr('type')) {
case 'text':
case 'password':
if ($input.val() === '' && !optional) {
return false;
}
break;
}
return true;
}
function highlightInput($input) {
switch ($input.attr('type')) {
case 'text':
case 'password':
return highlightBorder($input, !isInputValid($input));
}
}
/**
* Initialize select2 plugin on the given elements
*
* @param {Array<Object>} array of jQuery elements
* @param {int} userListLimit page size for result list
*/
function addSelect2 ($elements, userListLimit) {
if (!$elements.length) {
return;
}
$elements.select2({
placeholder: t('files_external', 'All users. Type to select user or group.'),
allowClear: true,
multiple: true,
//minimumInputLength: 1,
ajax: {
url: OC.generateUrl('apps/files_external/applicable/search'),
dataType: 'json',
quietMillis: 100,
data: function (term, page) { // page is the one-based page number tracked by Select2
return {
pattern: term, //search term
limit: userListLimit, // page size
offset: userListLimit*(page-1) // page number starts with 0
};
},
results: function (data) {
if (data.status === 'success') {
var results = [];
var userCount = 0; // users is an object
// add groups
$.each(data.groups, function(id, group) {
results.push({name:'g:'+id, displayname:group, type:'group'});
});
// add users
$.each(data.users, function(id, user) {
userCount++;
results.push({name:'u:'+id, displayname:user, type:'user'});
});
var more = (userCount >= userListLimit) || (data.groups.length >= userListLimit);
return {results: results, more: more};
} else {
//FIXME add error handling
}
}
},
initSelection: function(element, callback) {
var storageConfig = element.closest('tr').data('storageConfig');
$.when(
$.ajax(OC.generateUrl('apps/files_external/applicable/users'), {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'users' : storageConfig.applicableUsers}),
dataType: 'json'
}),
$.ajax(OC.generateUrl('apps/files_external/applicable/groups'), {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'groups' : storageConfig.applicableGroups}),
dataType: 'json'
})
).done(function (d1, d2) {
var results = [];
if (d1[0].status === 'success') {
$.each(d1[0].users, function(user, displayname) {
results.push({name:'u:'+user, displayname:displayname, type:'user'});
});
} else {
//FIXME add error handling
}
if (d2[0].status === 'success') {
$.each(d2[0].groups, function(group, displayname) {
results.push({name:'g:'+group, displayname:displayname, type:'group'});
});
} else {
//FIXME add error handling
}
callback(results);
})
},
id: function(element) {
return element.name;
},
formatResult: function (element) {
var $result = $('<span><div class="avatardiv"/><span>'+escapeHTML(element.displayname)+'</span></span>');
var $div = $result.find('.avatardiv')
.attr('data-type', element.type)
.attr('data-name', element.name)
.attr('data-displayname', element.displayname);
if (element.type === 'group') {
var url = OC.imagePath('core','places/contacts-dark'); // TODO better group icon
$div.html('<img width="32" height="32" src="'+url+'">');
}
return $result.get(0).outerHTML;
},
formatSelection: function (element) {
if (element.type === 'group') {
return '<span title="'+escapeHTML(element.name)+'" class="group">'+escapeHTML(element.displayname+' '+t('files_external', '(group)'))+'</span>';
} else {
return '<span title="'+escapeHTML(element.name)+'" class="user">'+escapeHTML(element.displayname)+'</span>';
}
},
escapeMarkup: function (m) { return m; } // we escape the markup in formatResult and formatSelection
}).on('select2-loaded', function() {
$.each($('.avatardiv'), function(i, div) {
var $div = $(div);
if ($div.data('type') === 'user') {
$div.avatar($div.data('name').substring(2),32); // need to remove the 'u:' prefix
}
});
});
var $selectAll = $elements.closest('tr').find('.select2-drop').
prepend(
'<ul class="select2-controls">' +
' <li class="selectAllApplicableUsers">' +
' <div class="avatardiv"><img width="32" height="32" src="'+OC.imagePath('core','places/contacts-dark')+'"></div>' +
' <span>'+t('files_external', 'All users')+'</span>' +
' </li>' +
'</ul>');
$selectAll.on('click', function (){
$($elements).val(null).trigger('change');
});
}
/**
* @class OCA.External.Settings.StorageConfig
*
* @classdesc External storage config
*/
var StorageConfig = function(id) {
this.id = id;
this.backendOptions = {};
};
// Keep this in sync with \OC_Mount_Config::STATUS_*
StorageConfig.Status = {
IN_PROGRESS: -1,
SUCCESS: 0,
ERROR: 1,
INDETERMINATE: 2
};
StorageConfig.Visibility = {
NONE: 0,
PERSONAL: 1,
ADMIN: 2,
DEFAULT: 3
};
/**
* @memberof OCA.External.Settings
*/
StorageConfig.prototype = {
_url: null,
/**
* Storage id
*
* @type int
*/
id: null,
/**
* Mount point
*
* @type string
*/
mountPoint: '',
/**
* Backend
*
* @type string
*/
backend: null,
/**
* Authentication mechanism
*
* @type string
*/
authMechanism: null,
/**
* Backend-specific configuration
*
* @type Object.<string,object>
*/
backendOptions: null,
/**
* Mount-specific options
*
* @type Object.<string,object>
*/
mountOptions: null,
/**
* Creates or saves the storage.
*
* @param {Function} [options.success] success callback, receives result as argument
* @param {Function} [options.error] error callback
*/
save: function(options) {
var self = this;
var url = OC.generateUrl(this._url);
var method = 'POST';
if (_.isNumber(this.id)) {
method = 'PUT';
url = OC.generateUrl(this._url + '/{id}', {id: this.id});
}
$.ajax({
type: method,
url: url,
contentType: 'application/json',
data: JSON.stringify(this.getData()),
success: function(result) {
self.id = result.id;
if (_.isFunction(options.success)) {
options.success(result);
}
},
error: options.error
});
},
/**
* Returns the data from this object
*
* @return {Array} JSON array of the data
*/
getData: function() {
var data = {
mountPoint: this.mountPoint,
backend: this.backend,
authMechanism: this.authMechanism,
backendOptions: this.backendOptions,
testOnly: true
};
if (this.id) {
data.id = this.id;
}
if (this.mountOptions) {
data.mountOptions = this.mountOptions;
}
return data;
},
/**
* Recheck the storage
*
* @param {Function} [options.success] success callback, receives result as argument
* @param {Function} [options.error] error callback
*/
recheck: function(options) {
if (!_.isNumber(this.id)) {
if (_.isFunction(options.error)) {
options.error();
}
return;
}
$.ajax({
type: 'GET',
url: OC.generateUrl(this._url + '/{id}', {id: this.id}),
data: {'testOnly': true},
success: options.success,
error: options.error
});
},
/**
* Deletes the storage
*
* @param {Function} [options.success] success callback
* @param {Function} [options.error] error callback
*/
destroy: function(options) {
if (!_.isNumber(this.id)) {
// the storage hasn't even been created => success
if (_.isFunction(options.success)) {
options.success();
}
return;
}
$.ajax({
type: 'DELETE',
url: OC.generateUrl(this._url + '/{id}', {id: this.id}),
success: options.success,
error: options.error
});
},
/**
* Validate this model
*
* @return {boolean} false if errors exist, true otherwise
*/
validate: function() {
if (this.mountPoint === '') {
return false;
}
if (!this.backend) {
return false;
}
if (this.errors) {
return false;
}
return true;
}
};
/**
* @class OCA.External.Settings.GlobalStorageConfig
* @augments OCA.External.Settings.StorageConfig
*
* @classdesc Global external storage config
*/
var GlobalStorageConfig = function(id) {
this.id = id;
this.applicableUsers = [];
this.applicableGroups = [];
};
/**
* @memberOf OCA.External.Settings
*/
GlobalStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
/** @lends OCA.External.Settings.GlobalStorageConfig.prototype */ {
_url: 'apps/files_external/globalstorages',
/**
* Applicable users
*
* @type Array.<string>
*/
applicableUsers: null,
/**
* Applicable groups
*
* @type Array.<string>
*/
applicableGroups: null,
/**
* Storage priority
*
* @type int
*/
priority: null,
/**
* Returns the data from this object
*
* @return {Array} JSON array of the data
*/
getData: function() {
var data = StorageConfig.prototype.getData.apply(this, arguments);
return _.extend(data, {
applicableUsers: this.applicableUsers,
applicableGroups: this.applicableGroups,
priority: this.priority,
});
}
});
/**
* @class OCA.External.Settings.UserStorageConfig
* @augments OCA.External.Settings.StorageConfig
*
* @classdesc User external storage config
*/
var UserStorageConfig = function(id) {
this.id = id;
};
UserStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
/** @lends OCA.External.Settings.UserStorageConfig.prototype */ {
_url: 'apps/files_external/userstorages'
});
/**
* @class OCA.External.Settings.UserGlobalStorageConfig
* @augments OCA.External.Settings.StorageConfig
*
* @classdesc User external storage config
*/
var UserGlobalStorageConfig = function (id) {
this.id = id;
};
UserGlobalStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
/** @lends OCA.External.Settings.UserStorageConfig.prototype */ {
_url: 'apps/files_external/userglobalstorages'
});
/**
* @class OCA.External.Settings.MountOptionsDropdown
*
* @classdesc Dropdown for mount options
*
* @param {Object} $container container DOM object
*/
var MountOptionsDropdown = function() {
};
/**
* @memberof OCA.External.Settings
*/
MountOptionsDropdown.prototype = {
/**
* Dropdown element
*
* @var Object
*/
$el: null,
/**
* Show dropdown
*
* @param {Object} $container container
* @param {Object} mountOptions mount options
* @param {Array} visibleOptions enabled mount options
* @param {GlobalStorageConfig} storageConfig
*/
show: function($container, mountOptions, visibleOptions, storageConfig) {
if (MountOptionsDropdown._last) {
MountOptionsDropdown._last.hide();
}
var template = MountOptionsDropdown._template;
if (!template) {
template = Handlebars.compile(MOUNT_OPTIONS_DROPDOWN_TEMPLATE);
MountOptionsDropdown._template = template;
}
var sharingDisabled = storageConfig.authMechanism === 'password::sessioncredentials';
var $el = $(template({
mountOptionsEncodingLabel: t('files_external', 'Compatibility with Mac NFD encoding (slow)'),
mountOptionsSharingTitle: sharingDisabled ? t('files_external', 'Sharing cannot be enabled due to the chosen authentication method') : '',
sharingDisabled: sharingDisabled,
}));
this.$el = $el;
this.setOptions(mountOptions, visibleOptions);
this.$el.appendTo($container);
MountOptionsDropdown._last = this;
this.$el.trigger('show');
},
hide: function() {
if (this.$el) {
this.$el.trigger('hide');
this.$el.remove();
this.$el = null;
MountOptionsDropdown._last = null;
}
},
/**
* Returns the mount options from the dropdown controls
*
* @return {Object} options mount options
*/
getOptions: function() {
var options = {};
this.$el.find('input, select').each(function() {
var $this = $(this);
var key = $this.attr('name');
var value = null;
if ($this.attr('type') === 'checkbox') {
value = $this.prop('checked');
} else {
value = $this.val();
}
if ($this.attr('data-type') === 'int') {
value = parseInt(value, 10);
}
options[key] = value;
});
return options;
},
/**
* Sets the mount options to the dropdown controls
*
* @param {Object} options mount options
* @param {Array} visibleOptions enabled mount options
*/
setOptions: function(options, visibleOptions) {
var $el = this.$el;
_.each(options, function(value, key) {
var $optionEl = $el.find('input, select').filterAttr('name', key);
if ($optionEl.attr('type') === 'checkbox') {
if (_.isString(value)) {
value = (value === 'true');
}
$optionEl.prop('checked', !!value);
} else {
$optionEl.val(value);
}
});
$el.find('.optionRow').each(function(i, row){
var $row = $(row);
var optionId = $row.find('input, select').attr('name');
if (visibleOptions.indexOf(optionId) === -1) {
$row.hide();
} else {
$row.show();
}
});
}
};
/**
* @class OCA.External.Settings.MountConfigListView
*
* @classdesc Mount configuration list view
*
* @param {Object} $el DOM object containing the list
* @param {Object} [options]
* @param {int} [options.userListLimit] page size in applicable users dropdown
*/
var MountConfigListView = function($el, options) {
this.initialize($el, options);
};
MountConfigListView.ParameterFlags = {
OPTIONAL: 1,
USER_PROVIDED: 2
};
MountConfigListView.ParameterTypes = {
TEXT: 0,
BOOLEAN: 1,
PASSWORD: 2,
HIDDEN: 3
};
/**
* @memberOf OCA.External.Settings
*/
MountConfigListView.prototype = _.extend({
/**
* jQuery element containing the config list
*
* @type Object
*/
$el: null,
/**
* Storage config class
*
* @type Class
*/
_storageConfigClass: null,
/**
* Flag whether the list is about user storage configs (true)
* or global storage configs (false)
*
* @type bool
*/
_isPersonal: false,
/**
* Page size in applicable users dropdown
*
* @type int
*/
_userListLimit: 30,
/**
* List of supported backends
*
* @type Object.<string,Object>
*/
_allBackends: null,
/**
* List of all supported authentication mechanisms
*
* @type Object.<string,Object>
*/
_allAuthMechanisms: null,
_encryptionEnabled: false,
/**
* @param {Object} $el DOM object containing the list
* @param {Object} [options]
* @param {int} [options.userListLimit] page size in applicable users dropdown
*/
initialize: function($el, options) {
this.$el = $el;
this._isPersonal = ($el.data('admin') !== true);
if (this._isPersonal) {
this._storageConfigClass = OCA.External.Settings.UserStorageConfig;
} else {
this._storageConfigClass = OCA.External.Settings.GlobalStorageConfig;
}
if (options && !_.isUndefined(options.userListLimit)) {
this._userListLimit = options.userListLimit;
}
this._encryptionEnabled = options.encryptionEnabled;
this._allowUserMountSharing = options.allowUserMountSharing;
// read the backend config that was carefully crammed
// into the data-configurations attribute of the select
this._allBackends = this.$el.find('.selectBackend').data('configurations');
this._allAuthMechanisms = this.$el.find('#addMountPoint .authentication').data('mechanisms');
},
/**
* Custom JS event handlers
* Trigger callback for all existing configurations
*/
whenSelectBackend: function(callback) {
this.$el.find('tbody tr:not(#addMountPoint)').each(function(i, tr) {
var backend = $(tr).find('.backend').data('identifier');
callback($(tr), backend);
});
this.on('selectBackend', callback);
},
whenSelectAuthMechanism: function(callback) {
var self = this;
this.$el.find('tbody tr:not(#addMountPoint)').each(function(i, tr) {
var authMechanism = $(tr).find('.selectAuthMechanism').val();
if (authMechanism !== undefined) {
var onCompletion = jQuery.Deferred();
callback($(tr), authMechanism, self._allAuthMechanisms[authMechanism]['scheme'], onCompletion);
onCompletion.resolve();
}
});
this.on('selectAuthMechanism', callback);
},
/**
* Initialize DOM event handlers
*/
_initEvents: function() {
var self = this;
var onChangeHandler = _.bind(this._onChange, this);
//this.$el.on('input', 'td input', onChangeHandler);
this.$el.on('keyup', 'td input', onChangeHandler);
this.$el.on('paste', 'td input', onChangeHandler);
this.$el.on('change', 'td input:checkbox', onChangeHandler);
this.$el.on('change', '.applicable', onChangeHandler);
this.$el.on('click', '.status>span', function() {
self.recheckStorageConfig($(this).closest('tr'));
});
this.$el.on('click', 'td.remove>img', function() {
self.deleteStorageConfig($(this).closest('tr'));
});
this.$el.on('click', 'td.mountOptionsToggle>img', function() {
self._showMountOptionsDropdown($(this).closest('tr'));
});
this.$el.on('change', '.selectBackend', _.bind(this._onSelectBackend, this));
this.$el.on('change', '.selectAuthMechanism', _.bind(this._onSelectAuthMechanism, this));
},
_onChange: function(event) {
var self = this;
var $target = $(event.target);
if ($target.closest('.dropdown').length) {
// ignore dropdown events
return;
}
highlightInput($target);
var $tr = $target.closest('tr');
this.updateStatus($tr, null);
var timer = $tr.data('save-timer');
clearTimeout(timer);
timer = setTimeout(function() {
self.saveStorageConfig($tr, null, timer);
}, 2000);
$tr.data('save-timer', timer);
},
_onSelectBackend: function(event) {
var $target = $(event.target);
var $tr = $target.closest('tr');
var storageConfig = new this._storageConfigClass();
storageConfig.mountPoint = $tr.find('.mountPoint input').val();
storageConfig.backend = $target.val();
$tr.find('.mountPoint input').val('');
var onCompletion = jQuery.Deferred();
$tr = this.newStorage(storageConfig, onCompletion);
onCompletion.resolve();
$tr.find('td.applicable').children().first().select2('open');
this.saveStorageConfig($tr);
},
_onSelectAuthMechanism: function(event) {
var $target = $(event.target);
var $tr = $target.closest('tr');
var authMechanism = $target.val();
var onCompletion = jQuery.Deferred();
this.configureAuthMechanism($tr, authMechanism, onCompletion);
onCompletion.resolve();
this.saveStorageConfig($tr);
},
/**
* Execute the target callback when all the deferred objects have been
* finished, either resolved or rejected
*
* @param {Deferred[]} deferreds array with all the deferred objects to check
* this will usually be a list of ajax requests, but other deferred
* objects can be included
* @param {callback} callback the callback to be executed after all the
* deferred object have finished
*/
_executeCallbackWhenFinished: function(deferreds, callback) {
var self = this;
$.when.apply($, deferreds).always(function() {
var pendingDeferreds = [];
// some deferred objects can still be pending to be resolved
// or rejected. Get all of those which are still pending so we can
// make another call
if (deferreds.length > 0) {
for (i = 0 ; i < deferreds.length ; i++) {
if (deferreds[i].state() === 'pending') {
pendingDeferreds.push(deferreds[i]);
}
}
}
if (pendingDeferreds.length > 0) {
self._executeCallbackWhenFinished(pendingDeferreds, callback);
} else {
callback();
}
});
},
/**
* Configure the storage config with a new authentication mechanism
*
* @param {jQuery} $tr config row
* @param {string} authMechanism
* @param {jQuery.Deferred} onCompletion
*/
configureAuthMechanism: function($tr, authMechanism, onCompletion) {
var authMechanismConfiguration = this._allAuthMechanisms[authMechanism];
var $td = $tr.find('td.configuration');
$td.find('.auth-param').remove();
$.each(authMechanismConfiguration['configuration'], _.partial(
this.writeParameterInput, $td, _, _, ['auth-param']
).bind(this));
this.trigger('selectAuthMechanism',
$tr, authMechanism, authMechanismConfiguration['scheme'], onCompletion
);
},
/**
* Create a config row for a new storage
*
* @param {StorageConfig} storageConfig storage config to pull values from
* @param {jQuery.Deferred} onCompletion
* @return {jQuery} created row
*/
newStorage: function(storageConfig, onCompletion) {
var mountPoint = storageConfig.mountPoint;
var backend = this._allBackends[storageConfig.backend];
var isInvalidAuth = false;
if (!backend) {
backend = {
name: 'Unknown backend: ' + storageConfig.backend,
invalid: true
};
}
if (backend && storageConfig.authMechanism && !this._allAuthMechanisms[storageConfig.authMechanism]) {
// mark invalid to prevent editing
backend.invalid = true;
isInvalidAuth = true;
}
// FIXME: Replace with a proper Handlebar template
var $tr = this.$el.find('tr#addMountPoint');
var $trCloned = $tr.clone();
$trCloned.find('td.mountPoint input').removeAttr('disabled');
this.$el.find('tbody').append($trCloned);
$tr.data('storageConfig', storageConfig);
$tr.show();
$tr.find('td').last().attr('class', 'remove');
$tr.find('td.mountOptionsToggle').removeClass('hidden');
$tr.find('td').last().removeAttr('style');
$tr.removeAttr('id');
addSelect2($tr.find('.applicableUsers'), this._userListLimit);
if (storageConfig.id) {
$tr.data('id', storageConfig.id);
}
$tr.find('.backend').text(backend.name);
if (mountPoint === '') {
mountPoint = this._suggestMountPoint(backend.name);
}
$tr.find('.mountPoint input').val(mountPoint);
$tr.addClass(backend.identifier);
$tr.find('.backend').data('identifier', backend.identifier);
if (backend.invalid || isInvalidAuth) {
$tr.addClass('invalid');
$tr.find('[name=mountPoint]').prop('disabled', true);
$tr.find('.applicable,.mountOptionsToggle').empty();
this.updateStatus($tr, false, 'Unknown backend: ' + backend.name);
if (isInvalidAuth) {
$tr.find('td.authentication').append('<span class="error-invalid">' +
t('files_external', 'Unknown auth backend "{b}"', {b: storageConfig.authMechanism}) +
'</span>'
);
}
$tr.find('td.configuration').append('<span class="error-invalid">' +
t('files_external', 'Please make sure that the app that provides this backend is installed and enabled') +
'</span>'
);
return $tr;
}
var selectAuthMechanism = $('<select class="selectAuthMechanism"></select>');
var neededVisibility = (this._isPersonal) ? StorageConfig.Visibility.PERSONAL : StorageConfig.Visibility.ADMIN;
$.each(this._allAuthMechanisms, function(authIdentifier, authMechanism) {
if ((backend.authSchemes[authMechanism.scheme] || backend.authSchemes[authMechanism.identifier]) && (authMechanism.visibility & neededVisibility)) {
selectAuthMechanism.append(
$('<option value="'+authMechanism.identifier+'" data-scheme="'+authMechanism.scheme+'">'+authMechanism.name+'</option>')
);
}
});
if (storageConfig.authMechanism) {
selectAuthMechanism.val(storageConfig.authMechanism);
} else {
storageConfig.authMechanism = selectAuthMechanism.val();
}
$tr.find('td.authentication').append(selectAuthMechanism);
var $td = $tr.find('td.configuration');
$.each(backend.configuration, _.partial(this.writeParameterInput, $td).bind(this));
this.trigger('selectBackend', $tr, backend.identifier, onCompletion);
this.configureAuthMechanism($tr, storageConfig.authMechanism, onCompletion);
if (storageConfig.backendOptions) {
$td.find('input, select').each(function() {
var input = $(this);
var val = storageConfig.backendOptions[input.data('parameter')];
if (val !== undefined) {
if(input.is('input:checkbox')) {
input.prop('checked', val);
}
input.val(storageConfig.backendOptions[input.data('parameter')]);
highlightInput(input);
}
});
}
var applicable = [];
if (storageConfig.applicableUsers) {
applicable = applicable.concat(
_.map(storageConfig.applicableUsers, function(user) {
return 'u:'+user;
})
);
}
if (storageConfig.applicableGroups) {
applicable = applicable.concat(
_.map(storageConfig.applicableGroups, function(group) {
return 'g:'+group;
})
);
}
$tr.find('.applicableUsers').val(applicable).trigger('change');
var priorityEl = $('<input type="hidden" class="priority" value="' + backend.priority + '" />');
$tr.append(priorityEl);
if (storageConfig.mountOptions) {
$tr.find('input.mountOptions').val(JSON.stringify(storageConfig.mountOptions));
} else {
// FIXME default backend mount options
$tr.find('input.mountOptions').val(JSON.stringify({
'encrypt': true,
'read_only': false,
'previews': true,
'enable_sharing': false,
'filesystem_check_changes': 1,
'encoding_compatibility': false