/
library-foldertoolbar-view.js
1547 lines (1468 loc) · 63.2 KB
/
library-foldertoolbar-view.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
define([
"layout/masthead",
"utils/utils",
"libs/toastr",
"mvc/library/library-model",
"mvc/ui/ui-select"
],
function( mod_masthead,
mod_utils,
mod_toastr,
mod_library_model,
mod_select
){
var FolderToolbarView = Backbone.View.extend({
el: '#center',
events: {
'click #toolbtn_create_folder' : 'createFolderFromModal',
'click #toolbtn_bulk_import' : 'modalBulkImport',
'click #include_deleted_datasets_chk' : 'checkIncludeDeleted',
'click #toolbtn_bulk_delete' : 'deleteSelectedItems',
'click .toolbtn-show-locinfo' : 'showLocInfo',
'click .page_size_prompt' : 'showPageSizePrompt'
},
defaults: {
'can_add_library_item' : false,
'contains_file_or_folder' : false,
'chain_call_control' : {
'total_number' : 0,
'failed_number' : 0
},
'disabled_jstree_element' : 'folders'
},
modal : null,
// directory browsing object
jstree: null,
// user's histories
histories : null,
// genome select
select_genome : null,
// extension select
select_extension : null,
// extension types
list_extensions :[],
// datatype placeholder for extension auto-detection
auto: {
id : 'auto',
text : 'Auto-detect',
description : 'This system will try to detect the file type automatically.' +
' If your file is not detected properly as one of the known formats,' +
' it most likely means that it has some format problems (e.g., different' +
' number of columns on different rows). You can still coerce the system' +
' to set your data to the format you think it should be.' +
' You can also upload compressed files, which will automatically be decompressed.'
},
// genomes
list_genomes : [],
initialize: function(options){
this.options = _.defaults( options || {}, this.defaults );
this.fetchExtAndGenomes();
this.render();
},
render: function(options){
this.options = _.extend( this.options, options );
var toolbar_template = this.templateToolBar();
var template_defaults = {
id: this.options.id,
is_admin: false,
is_anonym: true,
mutiple_add_dataset_options: false
}
if (Galaxy.user){
template_defaults.is_admin = Galaxy.user.isAdmin();
template_defaults.is_anonym = Galaxy.user.isAnonymous();
if ( Galaxy.config.user_library_import_dir !== null || Galaxy.config.allow_library_path_paste !== false || Galaxy.config.library_import_dir !== null ){
template_defaults.mutiple_add_dataset_options = true;
}
}
this.$el.html(toolbar_template(template_defaults));
},
/**
* Called from FolderListView when needed.
* @param {object} options common options
*/
renderPaginator: function( options ){
this.options = _.extend( this.options, options );
var paginator_template = this.templatePaginator();
$("body").find( '.folder-paginator' ).html( paginator_template({
id: this.options.id,
show_page: parseInt( this.options.show_page ),
page_count: parseInt( this.options.page_count ),
total_items_count: this.options.total_items_count,
items_shown: this.options.items_shown
}));
},
configureElements: function(options){
this.options = _.extend(this.options, options);
if (this.options.can_add_library_item === true){
$('.add-library-items').show();
} else{
$('.add-library-items').hide();
}
if (this.options.contains_file_or_folder === true){
if (Galaxy.user){
if (!Galaxy.user.isAnonymous()){
$('.logged-dataset-manipulation').show();
$('.dataset-manipulation').show();
} else {
$('.dataset-manipulation').show();
$('.logged-dataset-manipulation').hide();
}
} else {
$('.logged-dataset-manipulation').hide();
$('.dataset-manipulation').hide();
}
} else {
$('.logged-dataset-manipulation').hide();
$('.dataset-manipulation').hide();
}
this.$el.find('[data-toggle]').tooltip();
},
// shows modal for creating folder
createFolderFromModal: function( event ){
event.preventDefault();
event.stopPropagation();
// create modal
var self = this;
var template = this.templateNewFolderInModal();
this.modal = Galaxy.modal;
this.modal.show({
closing_events : true,
title : 'Create New Folder',
body : template(),
buttons : {
'Create' : function() {self.create_new_folder_event();},
'Close' : function() {Galaxy.modal.hide();}
}
});
},
// create the new folder from modal
create_new_folder_event: function(){
var folderDetails = this.serialize_new_folder();
if (this.validate_new_folder(folderDetails)){
var folder = new mod_library_model.FolderAsModel();
var url_items = Backbone.history.fragment.split('/'),
current_folder_id;
if(url_items.indexOf('page') > -1){
current_folder_id = url_items[url_items.length-3];
}else {
current_folder_id = url_items[url_items.length-1];
}
folder.url = folder.urlRoot + current_folder_id ;
folder.save(folderDetails, {
success: function (folder) {
Galaxy.modal.hide();
mod_toastr.success('Folder created.');
folder.set({'type' : 'folder'});
Galaxy.libraries.folderListView.collection.add(folder);
},
error: function(model, response){
Galaxy.modal.hide();
if (typeof response.responseJSON !== "undefined"){
mod_toastr.error(response.responseJSON.err_msg);
} else {
mod_toastr.error('An error occurred.');
}
}
});
} else {
mod_toastr.error('Folder\'s name is missing.');
}
return false;
},
// serialize data from the modal
serialize_new_folder : function(){
return {
name: $("input[name='Name']").val(),
description: $("input[name='Description']").val()
};
},
// validate new folder info
validate_new_folder: function(folderDetails){
return folderDetails.name !== '';
},
// show bulk import modal
modalBulkImport : function(){
var $checkedValues = this.findCheckedRows();
if($checkedValues.length === 0){
mod_toastr.info('You must select some datasets first.');
} else {
var that = this;
this.histories = new mod_library_model.GalaxyHistories();
this.histories.fetch()
.done(function(){
var template = that.templateBulkImportInModal();
that.modal = Galaxy.modal;
that.modal.show({
closing_events : true,
title : 'Import into History',
body : template({histories : that.histories.models}),
buttons : {
'Import' : function() {that.importAllIntoHistory();},
'Close' : function() {Galaxy.modal.hide();}
}
});
})
.fail(function(model, response){
if (typeof response.responseJSON !== "undefined"){
mod_toastr.error(response.responseJSON.err_msg);
} else {
mod_toastr.error('An error occurred.');
}
});
}
},
/**
* Import all selected datasets into history.
*/
importAllIntoHistory : function (){
this.modal.disableButton('Import');
var new_history_name = this.modal.$('input[name=history_name]').val();
var that = this;
if (new_history_name !== ''){
$.post(Galaxy.root + 'api/histories', {name: new_history_name})
.done(function( new_history ) {
that.options.last_used_history_id = new_history.id;
that.processImportToHistory(new_history.id, new_history.name);
})
.fail(function( xhr, status, error ) {
mod_toastr.error('An error occurred.');
})
.always(function() {
that.modal.enableButton('Import');
});
} else {
var history_id = $("select[name=dataset_import_bulk] option:selected").val();
this.options.last_used_history_id = history_id;
var history_name = $("select[name=dataset_import_bulk] option:selected").text();
this.processImportToHistory(history_id, history_name);
this.modal.enableButton('Import');
}
},
processImportToHistory: function( history_id, history_name ){
var dataset_ids = [];
var folder_ids = [];
this.findCheckedRows().each(function(){
var row_id = $(this).closest('tr').data('id');
if (row_id.substring(0,1) == 'F'){
folder_ids.push(row_id);
} else {
dataset_ids.push(row_id);
}
});
// prepare the dataset objects to be imported
var datasets_to_import = [];
for (var i = dataset_ids.length - 1; i >= 0; i--) {
var library_dataset_id = dataset_ids[i];
var historyItem = new mod_library_model.HistoryItem();
historyItem.url = historyItem.urlRoot + history_id + '/contents';
historyItem.content = library_dataset_id;
historyItem.source = 'library';
datasets_to_import.push(historyItem);
}
// prepare the folder objects to be imported
var folders_to_import = [];
for (var i = folder_ids.length - 1; i >= 0; i--) {
var library_folder_id = folder_ids[i];
var historyItem = new mod_library_model.HistoryItem();
historyItem.url = historyItem.urlRoot + history_id + '/contents';
historyItem.content = library_folder_id;
historyItem.source = 'library_folder';
datasets_to_import.push(historyItem);
}
this.initChainCallControl( { length: datasets_to_import.length, action: 'to_history', history_name: history_name } );
// set the used history as current so user will see the last one
// that he imported into in the history panel on the 'analysis' page
jQuery.getJSON( Galaxy.root + 'history/set_as_current?id=' + history_id );
this.chainCallImportingIntoHistory( datasets_to_import, history_name );
},
/**
* Update the progress bar in modal window.
*/
updateProgress: function(){
this.progress += this.progressStep;
$( '.progress-bar-import' ).width( Math.round( this.progress ) + '%' );
var txt_representation = Math.round( this.progress ) + '% Complete';
$( '.completion_span' ).text( txt_representation );
},
/**
* download selected datasets
* @param {str} folder_id id of the current folder
* @param {str} format requested archive format
*/
download : function( folder_id, format ){
var dataset_ids = [];
var folder_ids = [];
this.findCheckedRows().each( function(){
var row_id = $(this).closest('tr').data('id');
if (row_id.substring(0,1) == 'F'){
folder_ids.push(row_id);
} else {
dataset_ids.push(row_id);
}
} );
var url = Galaxy.root + 'api/libraries/datasets/download/' + format;
var data = { 'ld_ids' : dataset_ids, 'folder_ids' : folder_ids };
this.processDownload( url, data, 'get' );
},
/**
* Create hidden form and submit it through POST
* to initialize the download.
* @param {str} url url to call
* @param {obj} data data to include in the request
* @param {str} method method of the request
*/
processDownload: function( url, data, method ){
if ( url && data ){
// data can be string of parameters or array/object
data = typeof data === 'string' ? data : $.param( data );
// split params into form inputs
var inputs = '';
$.each( data.split( '&' ), function(){
var pair = this.split( '=' );
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
// send request
$('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo( 'body' ).submit().remove();
mod_toastr.info( 'Your download will begin soon.' );
} else {
mod_toastr.error( 'An error occurred.' );
}
},
addFilesFromHistoryModal: function(){
this.histories = new mod_library_model.GalaxyHistories();
var self = this;
this.histories.fetch()
.done(function(){
self.modal = Galaxy.modal;
var template_modal = self.templateAddFilesFromHistory();
self.modal.show({
closing_events : true,
title : 'Adding datasets from your history',
body : template_modal({histories: self.histories.models}),
buttons : {
'Add' : function() {self.addAllDatasetsFromHistory();},
'Close' : function() {Galaxy.modal.hide();}
},
closing_callback: function(){
Galaxy.libraries.library_router.navigate('folders/' + self.id, {trigger: true});
}
});
self.fetchAndDisplayHistoryContents(self.histories.models[0].id);
$( "#dataset_add_bulk" ).change(function(event) {
self.fetchAndDisplayHistoryContents(event.target.value);
});
})
.fail(function(model, response){
if (typeof response.responseJSON !== "undefined"){
mod_toastr.error(response.responseJSON.err_msg);
} else {
mod_toastr.error('An error occurred.');
}
});
},
/**
* Create modal for importing from Galaxy path.
* This feature is admin-only.
*/
importFilesFromPathModal: function(){
var that = this;
this.modal = Galaxy.modal;
var template_modal = this.templateImportPathModal();
this.modal.show({
closing_events : true,
title : 'Please enter paths to import',
body : template_modal({}),
buttons : {
'Import' : function() { that.importFromPathsClicked(that); },
'Close' : function() { Galaxy.modal.hide(); }
},
closing_callback: function(){
// TODO: should not trigger routes outside of the router
Galaxy.libraries.library_router.navigate( 'folders/' + that.id, { trigger: true } );
}
});
this.renderSelectBoxes();
},
/**
* Request all extensions and genomes from Galaxy
* and save them sorted in arrays.
*/
fetchExtAndGenomes: function(){
var that = this;
mod_utils.get({
url : Galaxy.root + "api/datatypes?extension_only=False",
success : function( datatypes ) {
that.list_extensions = [];
for (var key in datatypes) {
that.list_extensions.push({
id : datatypes[key].extension,
text : datatypes[key].extension,
description : datatypes[key].description,
description_url : datatypes[key].description_url
});
}
that.list_extensions.sort(function(a, b) {
return a.id > b.id ? 1 : a.id < b.id ? -1 : 0;
});
that.list_extensions.unshift(that.auto);
},
cache : true
});
mod_utils.get({
url : Galaxy.root + "api/genomes",
success : function( genomes ) {
that.list_genomes = [];
for (var key in genomes ) {
that.list_genomes.push({
id : genomes[key][1],
text : genomes[key][0]
});
}
that.list_genomes.sort(function(a, b) {
return a.id > b.id ? 1 : a.id < b.id ? -1 : 0;
});
},
cache : true
});
},
renderSelectBoxes: function(){
// This won't work properly unlesss we already have the data fetched.
// See this.fetchExtAndGenomes()
// TODO switch to common resources:
// https://trello.com/c/dIUE9YPl/1933-ui-common-resources-and-data-into-galaxy-object
var that = this;
this.select_genome = new mod_select.View( {
css: 'library-genome-select',
data: that.list_genomes,
container: Galaxy.modal.$el.find( '#library_genome_select' ),
value: '?'
} );
this.select_extension = new mod_select.View({
css: 'library-extension-select',
data: that.list_extensions,
container: Galaxy.modal.$el.find( '#library_extension_select' ),
value: 'auto'
});
},
/**
* Create modal for importing from given directory
* on Galaxy. Bind jQuery events.
*/
importFilesFromGalaxyFolderModal: function( options ){
var that = this;
var template_modal = this.templateBrowserModal();
this.modal = Galaxy.modal;
this.modal.show({
closing_events : true,
title : 'Please select folders or files',
body : template_modal({}),
buttons : {
'Import' : function() {
that.importFromJstreePath( that, options );
},
'Close' : function() {
Galaxy.modal.hide();
}
},
closing_callback: function(){
// TODO: should not trigger routes outside of the router
Galaxy.libraries.library_router.navigate('folders/' + that.id, {trigger: true});
}
});
$('.libimport-select-all').bind("click", function(){
$('#jstree_browser').jstree("check_all");
});
$('.libimport-select-none').bind("click", function(){
$('#jstree_browser').jstree("uncheck_all");
});
this.renderSelectBoxes();
options.disabled_jstree_element = 'folders';
this.renderJstree( options );
$( 'input[type=radio]' ).change( function( event ){
if (event.target.value ==='jstree-disable-folders') {
options.disabled_jstree_element = 'folders';
that.renderJstree( options );
$('.jstree-folders-message').hide();
$('.jstree-preserve-structure').hide();
$('.jstree-files-message').show();
} else if ( event.target.value ==='jstree-disable-files' ){
$('.jstree-files-message').hide();
$('.jstree-folders-message').show();
$('.jstree-preserve-structure').show();
options.disabled_jstree_element = 'files';
that.renderJstree( options );
}
}
);
},
/**
* Fetch the contents of user directory on Galaxy
* and render jstree component based on received
* data.
* @param {[type]} options [description]
*/
renderJstree: function( options ){
var that = this;
this.options = _.extend( this.options, options );
var target = options.source || 'userdir';
var disabled_jstree_element = this.options.disabled_jstree_element;
this.jstree = new mod_library_model.Jstree();
this.jstree.url = this.jstree.urlRoot +
'?target=' + target +
'&format=jstree' +
'&disable=' + disabled_jstree_element;
this.jstree.fetch({
success: function(model, response){
// This is to prevent double jquery load. I think. Carl is magician.
define( 'jquery', function(){ return jQuery; });
// Now we need jstree, time to lazy load it.
require([ 'libs/jquery/jstree' ], function(jstree){
$('#jstree_browser').jstree("destroy");
$('#jstree_browser').jstree({
'core':{
'data': model
},
'plugins': ['types', 'checkbox'],
'types': {
"folder": {
"icon": "jstree-folder"
},
"file": {
"icon": "jstree-file"
}
},
'checkbox': {
three_state: false
}
});
});
},
error: function(model, response){
if (typeof response.responseJSON !== "undefined"){
if (response.responseJSON.err_code === 404001){
mod_toastr.warning(response.responseJSON.err_msg);
} else{
mod_toastr.error(response.responseJSON.err_msg);
}
} else {
mod_toastr.error('An error occurred.');
}
}
})
},
/**
* Take the paths from the textarea, split it, create
* a request queue and call a function that starts sending
* one by one to be imported on the server.
*/
importFromPathsClicked: function(){
var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked');
var link_data = this.modal.$el.find('.link-checkbox').is(':checked');
var space_to_tab = this.modal.$el.find('.spacetab-checkbox').is(':checked');
var to_posix_lines = this.modal.$el.find('.posix-checkbox').is(':checked');
var tag_using_filenames = this.modal.$el.find('.tag-files').is(':checked');
var file_type = this.select_extension.value();
var dbkey = this.select_genome.value();
var paths = $('textarea#import_paths').val();
var valid_paths = [];
if (!paths){
mod_toastr.info('Please enter a path relative to Galaxy root.');
} else {
this.modal.disableButton('Import');
paths = paths.split('\n');
for (var i = paths.length - 1; i >= 0; i--) {
var trimmed = paths[i].trim();
if (trimmed.length!==0){
valid_paths.push(trimmed);
}
};
this.initChainCallControl( { length: valid_paths.length, action: 'adding_datasets' } );
this.chainCallImportingFolders( { paths: valid_paths,
preserve_dirs: preserve_dirs,
link_data: link_data,
space_to_tab: space_to_tab,
to_posix_lines: to_posix_lines,
source: 'admin_path',
file_type: file_type,
tag_using_filenames: tag_using_filenames,
dbkey: dbkey } );
}
},
/**
* Initialize the control of chaining requests
* in the current modal.
* @param {int} length The number of items in the chain call.
*/
initChainCallControl: function( options ){
var template;
switch( options.action ){
case "adding_datasets":
template = this.templateAddingDatasetsProgressBar();
this.modal.$el.find( '.modal-body' ).html( template( { folder_name : this.options.folder_name } ) );
break;
case "deleting_datasets":
template = this.templateDeletingItemsProgressBar();
this.modal.$el.find( '.modal-body' ).html( template() );
break;
case "to_history":
template = this.templateImportIntoHistoryProgressBar();
this.modal.$el.find( '.modal-body' ).html( template( { history_name : options.history_name } ) );
break;
default:
Galaxy.emit.error( 'Wrong action specified.', 'datalibs');
break;
}
// var progress_bar_tmpl = this.templateAddingDatasetsProgressBar();
// this.modal.$el.find( '.modal-body' ).html( progress_bar_tmpl( { folder_name : this.options.folder_name } ) );
this.progress = 0;
this.progressStep = 100 / options.length;
this.options.chain_call_control.total_number = options.length;
this.options.chain_call_control.failed_number = 0;
},
/**
* Take the selected items from the jstree, create a request queue
* and send them one by one to the server for importing into
* the current folder.
*
* jstree.js has to be loaded before
* @see renderJstree
*/
importFromJstreePath: function ( that, options ){
var all_nodes = $( '#jstree_browser' ).jstree().get_selected( true );
// remove the disabled elements that could have been trigerred with the 'select all'
var selected_nodes = _.filter(all_nodes, function(node){ return node.state.disabled == false; })
var preserve_dirs = this.modal.$el.find( '.preserve-checkbox' ).is( ':checked' );
var link_data = this.modal.$el.find( '.link-checkbox' ).is( ':checked' );
var space_to_tab = this.modal.$el.find('.spacetab-checkbox').is(':checked');
var to_posix_lines = this.modal.$el.find('.posix-checkbox').is(':checked');
var file_type = this.select_extension.value();
var dbkey = this.select_genome.value();
var tag_using_filenames = this.modal.$el.find( '.tag-files' ).is( ':checked' );
var selection_type = selected_nodes[0].type;
var paths = [];
if ( selected_nodes.length < 1 ){
mod_toastr.info( 'Please select some items first.' );
} else {
this.modal.disableButton( 'Import' );
for ( var i = selected_nodes.length - 1; i >= 0; i-- ){
if ( selected_nodes[i].li_attr.full_path !== undefined ){
paths.push( selected_nodes[i].li_attr.full_path );
}
}
this.initChainCallControl( { length: paths.length, action: 'adding_datasets' } );
if ( selection_type === 'folder' ){
var full_source = options.source + '_folder';
this.chainCallImportingFolders( { paths: paths,
preserve_dirs: preserve_dirs,
link_data: link_data,
space_to_tab: space_to_tab,
to_posix_lines: to_posix_lines,
source: full_source,
file_type: file_type,
dbkey: dbkey,
tag_using_filenames: tag_using_filenames } );
} else if ( selection_type === 'file' ){
var full_source = options.source + '_file';
this.chainCallImportingUserdirFiles( { paths : paths,
file_type: file_type,
dbkey: dbkey,
link_data: link_data,
space_to_tab: space_to_tab,
to_posix_lines: to_posix_lines,
source: full_source,
tag_using_filenames: tag_using_filenames } );
}
}
},
fetchAndDisplayHistoryContents: function(history_id){
var history_contents = new mod_library_model.HistoryContents({id:history_id});
var self = this;
history_contents.fetch({
success: function(history_contents){
var history_contents_template = self.templateHistoryContents();
self.histories.get(history_id).set({'contents' : history_contents});
self.modal.$el.find('#selected_history_content').html(history_contents_template({history_contents: history_contents.models.reverse()}));
self.modal.$el.find('.history-import-select-all').bind("click", function(){
$('#selected_history_content [type=checkbox]').prop('checked', true);
});
self.modal.$el.find('.history-import-unselect-all').bind("click", function(){
$('#selected_history_content [type=checkbox]').prop('checked', false);
});
},
error: function(model, response){
if (typeof response.responseJSON !== "undefined"){
mod_toastr.error(response.responseJSON.err_msg);
} else {
mod_toastr.error('An error occurred.');
}
}
});
},
/**
* Import all selected datasets from history into the current folder.
*/
addAllDatasetsFromHistory : function (){
var checked_hdas = this.modal.$el.find( '#selected_history_content' ).find( ':checked' );
var history_item_ids = []; // can be hda or hdca
var history_item_types = [];
var items_to_add = [];
if ( checked_hdas.length < 1 ){
mod_toastr.info( 'You must select some datasets first.' );
} else {
this.modal.disableButton( 'Add' );
checked_hdas.each(function(){
var hid = $(this).closest('li').data( 'id' );
if ( hid ) {
var item_type = $(this).closest('li').data( 'name' );
history_item_ids.push( hid );
history_item_types.push( item_type );
}
});
for ( var i = history_item_ids.length - 1; i >= 0; i-- ) {
var history_item_id = history_item_ids[i];
var folder_item = new mod_library_model.Item();
folder_item.url = Galaxy.root + 'api/folders/' + this.options.id + '/contents';
if (history_item_types[i] === 'collection') {
folder_item.set({'from_hdca_id': history_item_id});
} else {
folder_item.set({'from_hda_id': history_item_id});
}
items_to_add.push(folder_item);
}
this.initChainCallControl( { length: items_to_add.length, action: 'adding_datasets' } );
this.chainCallAddingHdas( items_to_add );
}
},
/**
* Take array of empty history items and make request for each of them
* to create it on server. Update progress in between calls.
* @param {array} history_item_set array of empty history items
* @param {str} history_name name of the history to import to
*/
chainCallImportingIntoHistory: function( history_item_set, history_name ){
var self = this;
var popped_item = history_item_set.pop();
if ( typeof popped_item == "undefined" ) {
if ( this.options.chain_call_control.failed_number === 0 ){
mod_toastr.success( 'Selected datasets imported into history. Click this to start analyzing it.', '', { onclick: function() { window.location=Galaxy.root } } );
} else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){
mod_toastr.error( 'There was an error and no datasets were imported into history.' );
} else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){
mod_toastr.warning( 'Some of the datasets could not be imported into history. Click this to see what was imported.', '', { onclick: function() { window.location=Galaxy.root } } );
}
Galaxy.modal.hide();
return true;
}
var promise = $.when( popped_item.save( { content: popped_item.content, source: popped_item.source } ) );
promise.done( function(){
self.updateProgress();
self.chainCallImportingIntoHistory( history_item_set, history_name );
} )
.fail( function(){
self.options.chain_call_control.failed_number += 1;
self.updateProgress();
self.chainCallImportingIntoHistory( history_item_set, history_name );
} );
},
/**
* Take the array of paths and create a request for each of them
* calling them in chain. Update the progress bar in between each.
* @param {array} paths paths relative to user folder on Galaxy
* @param {boolean} tag_using_filenames add tags to datasets using names of files
*/
chainCallImportingUserdirFiles: function( options ){
var that = this;
var popped_item = options.paths.pop();
if ( typeof popped_item === "undefined" ) {
if ( this.options.chain_call_control.failed_number === 0 ){
mod_toastr.success( 'Selected files imported into the current folder' );
Galaxy.modal.hide();
} else {
mod_toastr.error( 'An error occured.' );
}
return true;
}
var promise = $.when( $.post( Galaxy.root + 'api/libraries/datasets?encoded_folder_id=' + that.id +
'&source=' + options.source +
'&path=' + popped_item +
'&file_type=' + options.file_type +
'&link_data=' + options.link_data +
'&space_to_tab=' + options.space_to_tab +
'&to_posix_lines=' + options.to_posix_lines +
'&dbkey=' + options.dbkey +
'&tag_using_filenames=' + options.tag_using_filenames ) )
promise.done( function( response ){
that.updateProgress();
that.chainCallImportingUserdirFiles( options );
} )
.fail( function(){
that.options.chain_call_control.failed_number += 1;
that.updateProgress();
that.chainCallImportingUserdirFiles( options );
} );
},
/**
* Take the array of paths and create a request for each of them
* calling them in series. Update the progress bar in between each.
* @param {array} paths paths relative to Galaxy root folder
* @param {boolean} preserve_dirs indicates whether to preserve folder structure
* @param {boolean} link_data copy files to Galaxy or link instead
* @param {boolean} to_posix_lines convert line endings to POSIX standard
* @param {boolean} space_to_tab convert spaces to tabs
* @param {str} source string representing what type of folder
* is the source of import
* @param {boolean} tag_using_filenames add tags to datasets using names of files
*/
chainCallImportingFolders: function( options ){
// TODO need to check which paths to call
var that = this;
var popped_item = options.paths.pop();
if (typeof popped_item == "undefined") {
if (this.options.chain_call_control.failed_number === 0){
mod_toastr.success('Selected folders and their contents imported into the current folder.');
Galaxy.modal.hide();
} else {
// TODO better error report
mod_toastr.error('An error occured.');
}
return true;
}
var promise = $.when( $.post( Galaxy.root + 'api/libraries/datasets?encoded_folder_id=' + that.id +
'&source=' + options.source +
'&path=' + popped_item +
'&preserve_dirs=' + options.preserve_dirs +
'&link_data=' + options.link_data +
'&to_posix_lines=' + options.to_posix_lines +
'&space_to_tab=' + options.space_to_tab +
'&file_type=' + options.file_type +
'&dbkey=' + options.dbkey +
'&tag_using_filenames=' + options.tag_using_filenames ) )
promise.done(function(response){
that.updateProgress();
that.chainCallImportingFolders( options );
})
.fail(function(){
that.options.chain_call_control.failed_number += 1;
that.updateProgress();
that.chainCallImportingFolders( options );
});
},
/**
* Take the array of hdas and create a request for each.
* Call them in chain and update progress bar in between each.
* @param {array} hdas_set array of empty hda objects
*/
chainCallAddingHdas: function( hdas_set ){
var self = this;
this.added_hdas = new mod_library_model.Folder();
var popped_item = hdas_set.pop();
if ( typeof popped_item == "undefined" ) {
if ( this.options.chain_call_control.failed_number === 0 ){
mod_toastr.success( 'Selected datasets from history added to the folder' );
} else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){
mod_toastr.error( 'There was an error and no datasets were added to the folder.' );
} else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){
mod_toastr.warning( 'Some of the datasets could not be added to the folder' );
}
Galaxy.modal.hide();
return this.added_hdas;
}
var promise = $.when( popped_item.save( { from_hda_id: popped_item.get( 'from_hda_id' ) } ) );
promise.done( function( model ){
Galaxy.libraries.folderListView.collection.add( model );
self.updateProgress();
self.chainCallAddingHdas( hdas_set );
})
.fail( function(){
self.options.chain_call_control.failed_number += 1;
self.updateProgress();
self.chainCallAddingHdas( hdas_set );
});
},
/**
* Take the array of lddas, create request for each and
* call them in chain. Update progress bar in between each.
* @param {array} lddas_set array of lddas to delete
*/
chainCallDeletingItems: function( items_to_delete ){
var self = this;
this.deleted_items = new mod_library_model.Folder();
var item_to_delete = items_to_delete.pop();
if ( typeof item_to_delete === "undefined" ) {
if ( this.options.chain_call_control.failed_number === 0 ){
mod_toastr.success( 'Selected items were deleted.' );
} else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){
mod_toastr.error( 'There was an error and no items were deleted. Please make sure you have sufficient permissions.' );
} else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){
mod_toastr.warning( 'Some of the items could not be deleted. Please make sure you have sufficient permissions.' );
}
Galaxy.modal.hide();
return this.deleted_items;
}
item_to_delete.destroy()
.done( function( item ){
Galaxy.libraries.folderListView.collection.remove( item_to_delete.id );
self.updateProgress();
// add the deleted item to collection, triggers rendering
if ( Galaxy.libraries.folderListView.options.include_deleted ){
var updated_item = null;
if (item.type === 'folder' || item.model_class === 'LibraryFolder'){
updated_item = new mod_library_model.FolderAsModel( item );
} else if (item.type === 'file' || item.model_class === 'LibraryDataset'){
updated_item = new mod_library_model.Item( item );
} else {
Galaxy.emit.error('Unknown library item type found.', 'datalibs');
Galaxy.emit.error(item.type || item.model_class, 'datalibs');
}
Galaxy.libraries.folderListView.collection.add( updated_item );
}
self.chainCallDeletingItems( items_to_delete );
})
.fail( function(){
self.options.chain_call_control.failed_number += 1;
self.updateProgress();
self.chainCallDeletingItems( items_to_delete );
});
},
/**
* Handles the click on 'show deleted' checkbox
*/
checkIncludeDeleted: function(event){
if (event.target.checked){
Galaxy.libraries.folderListView.fetchFolder({include_deleted: true});
} else{
Galaxy.libraries.folderListView.fetchFolder({include_deleted: false});
}
},
/**
* Delete the selected items. Atomic. One by one.
*/
deleteSelectedItems: function(){
var dataset_ids = [];
var folder_ids = [];
var $checkedValues = this.findCheckedRows();