-
Notifications
You must be signed in to change notification settings - Fork 2k
/
application.js
1463 lines (1359 loc) · 46.5 KB
/
application.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
var CKAN = CKAN || {};
CKAN.View = CKAN.View || {};
CKAN.Model = CKAN.Model || {};
CKAN.Utils = CKAN.Utils || {};
/* ================================= */
/* == Initialise CKAN Application == */
/* ================================= */
(function ($) {
$(document).ready(function () {
CKAN.Utils.setupUserAutocomplete($('input.autocomplete-user'));
CKAN.Utils.setupPublisherUserAutocomplete($('input.autocomplete-publisher-user'));
CKAN.Utils.setupGroupAutocomplete($('input.autocomplete-group'));
CKAN.Utils.setupAuthzGroupAutocomplete($('input.autocomplete-authzgroup'));
CKAN.Utils.setupPackageAutocomplete($('input.autocomplete-dataset'));
CKAN.Utils.setupTagAutocomplete($('input.autocomplete-tag'));
$('input.autocomplete-format').live('keyup', function(){
CKAN.Utils.setupFormatAutocomplete($(this));
});
CKAN.Utils.setupMarkdownEditor($('.markdown-editor'));
// bootstrap collapse
$('.collapse').collapse({toggle: false});
// Buttons with href-action should navigate when clicked
$('input.href-action').click(function(e) {
e.preventDefault();
window.location = ($(e.target).attr('action'));
});
var isGroupView = $('body.group.read').length > 0;
if (isGroupView) {
// Show extract of notes field
CKAN.Utils.setupNotesExtract();
}
var isDatasetView = $('body.package.read').length > 0;
if (isDatasetView) {
// Show extract of notes field
CKAN.Utils.setupNotesExtract();
}
var isResourceView = $('body.package.resource_read').length > 0;
if (isResourceView) {
CKAN.DataPreview.loadPreviewDialog(preload_resource);
}
var isDatasetNew = $('body.package.new').length > 0;
if (isDatasetNew) {
// Set up magic URL slug editor
var urlEditor = new CKAN.View.UrlEditor({
slugType: 'package'
});
$('#save').val(CKAN.Strings.addDataset);
$("#title").focus();
}
var isGroupNew = $('body.group.new').length > 0;
if (isGroupNew) {
// Set up magic URL slug editor
var urlEditor = new CKAN.View.UrlEditor({
slugType: 'group'
});
$('#save').val(CKAN.Strings.addGroup);
$("#title").focus();
}
var isDatasetEdit = $('body.package.edit').length > 0;
if (isDatasetEdit) {
CKAN.Utils.warnOnFormChanges($('form#dataset-edit'));
var urlEditor = new CKAN.View.UrlEditor({
slugType: 'package'
});
// Set up dataset delete button
CKAN.Utils.setupDatasetDeleteButton();
}
var isDatasetResourceEdit = $('body.package.editresources').length > 0;
if (isDatasetNew || isDatasetResourceEdit) {
// Selectively enable the upload button
var storageEnabled = $.inArray('storage',CKAN.plugins)>=0;
if (storageEnabled) {
$('li.js-upload-file').show();
}
// Backbone model/view
var _dataset = new CKAN.Model.Dataset(preload_dataset);
var $el=$('form#dataset-edit');
var view=new CKAN.View.ResourceEditor({
collection: _dataset.get('resources'),
el: $el
});
view.render();
$( ".drag-drop-list" ).sortable({
distance: 10
});
$( ".drag-drop-list" ).disableSelection();
}
var isGroupEdit = $('body.group.edit').length > 0;
if (isGroupEdit) {
var urlEditor = new CKAN.View.UrlEditor({
slugType: 'group'
});
}
// OpenID hack
// We need to remember the language we are using whilst logging in
// we set this in the user session so we don't forget then
// carry on as before.
if (window.openid && openid.signin){
openid._signin = openid.signin;
openid.signin = function (arg) {
$.get('/user/set_lang/' + CKAN.LANG, function (){openid._signin(arg);})
};
}
if ($('#login').length){
$('#login').submit( function () {
$.ajax('/user/set_lang/' + CKAN.LANG, {async:false});
});
}
});
}(jQuery));
/* ============================== */
/* == Backbone View: UrlEditor == */
/* ============================== */
CKAN.View.UrlEditor = Backbone.View.extend({
initialize: function() {
_.bindAll(this,'titleToSlug','titleChanged','urlChanged','checkSlugIsValid','apiCallback');
// Initial state
var self = this;
this.updateTimer = null;
this.titleInput = $('.js-title');
this.urlInput = $('.js-url-input');
this.validMsg = $('.js-url-is-valid');
this.lengthMsg = $('.url-is-long');
this.lastTitle = "";
this.disableTitleChanged = false;
// Settings
this.regexToHyphen = [ new RegExp('[ .:/_]', 'g'),
new RegExp('[^a-zA-Z0-9-_]', 'g'),
new RegExp('-+', 'g')];
this.regexToDelete = [ new RegExp('^-*', 'g'),
new RegExp('-*$', 'g')];
// Default options
if (!this.options.apiUrl) {
this.options.apiUrl = CKAN.SITE_URL + '/api/2/util/is_slug_valid';
}
if (!this.options.MAX_SLUG_LENGTH) {
this.options.MAX_SLUG_LENGTH = 90;
}
this.originalUrl = this.urlInput.val();
// Hook title changes to the input box
CKAN.Utils.bindInputChanges(this.titleInput, this.titleChanged);
CKAN.Utils.bindInputChanges(this.urlInput, this.urlChanged);
// If you've bothered typing a URL, I won't overwrite you
function disable() {
self.disableTitleChanged = true;
};
this.urlInput.keyup (disable);
this.urlInput.keydown (disable);
this.urlInput.keypress(disable);
// Set up the form
this.urlChanged();
},
titleToSlug: function(title) {
var slug = title;
$.each(this.regexToHyphen, function(idx,regex) { slug = slug.replace(regex, '-'); });
$.each(this.regexToDelete, function(idx,regex) { slug = slug.replace(regex, ''); });
slug = slug.toLowerCase();
if (slug.length<this.options.MAX_SLUG_LENGTH) {
slug=slug.substring(0,this.options.MAX_SLUG_LENGTH);
}
return slug;
},
/* Called when the title changes */
titleChanged: function() {
if (this.disableTitleChanged) { return; }
var title = this.titleInput.val();
if (title == this.lastTitle) { return; }
this.lastTitle = title;
slug = this.titleToSlug(title);
this.urlInput.val(slug);
this.urlInput.change();
},
/* Called when the url is changed */
urlChanged: function() {
var slug = this.urlInput.val();
if (this.updateTimer) { clearTimeout(this.updateTimer); }
if (slug.length<2) {
this.validMsg.html('<span style="font-weight: bold; color: #444;">'+CKAN.Strings.urlIsTooShort+'</span>');
}
else if (slug==this.originalUrl) {
this.validMsg.html('<span style="font-weight: bold; color: #000;">'+CKAN.Strings.urlIsUnchanged+'</span>');
}
else {
this.validMsg.html('<span style="color: #777;">'+CKAN.Strings.checking+'</span>');
var self = this;
this.updateTimer = setTimeout(function () {
self.checkSlugIsValid(slug);
}, 200);
}
if (slug.length>20) {
this.lengthMsg.show();
}
else {
this.lengthMsg.hide();
}
},
checkSlugIsValid: function(slug) {
$.ajax({
url: this.options.apiUrl,
data: 'type='+this.options.slugType+'&slug=' + slug,
dataType: 'jsonp',
type: 'get',
jsonpCallback: 'callback',
success: this.apiCallback
});
},
/* Called when the slug-validator gets back to us */
apiCallback: function(data) {
if (data.valid) {
this.validMsg.html('<span style="font-weight: bold; color: #0c0">'+CKAN.Strings.urlIsAvailable+'</span>');
} else {
this.validMsg.html('<span style="font-weight: bold; color: #c00">'+CKAN.Strings.urlIsNotAvailable+'</span>');
}
}
});
/* =================================== */
/* == Backbone View: ResourceEditor == */
/* =================================== */
CKAN.View.ResourceEditor = Backbone.View.extend({
initialize: function() {
// Init bindings
_.bindAll(this, 'resourceAdded', 'resourceRemoved', 'sortStop', 'openFirstPanel', 'closePanel', 'openAddPanel');
this.collection.bind('add', this.resourceAdded);
this.collection.bind('remove', this.resourceRemoved);
this.collection.each(this.resourceAdded);
this.el.find('.resource-list-edit').bind("sortstop", this.sortStop);
// Delete the barebones editor. We will populate our own form.
this.el.find('.js-resource-edit-barebones').remove();
// Warn on form changes
var flashWarning = CKAN.Utils.warnOnFormChanges(this.el);
this.collection.bind('add', flashWarning);
this.collection.bind('remove', flashWarning);
// Trigger the Add Resource pane
this.el.find('.js-resource-add').click(this.openAddPanel);
// Tabs for adding resources
new CKAN.View.ResourceAddUrl({
collection: this.collection,
el: this.el.find('.js-add-url-form'),
mode: 'file'
});
new CKAN.View.ResourceAddUrl({
collection: this.collection,
el: this.el.find('.js-add-api-form'),
mode: 'api'
});
new CKAN.View.ResourceAddUpload({
collection: this.collection,
el: this.el.find('.js-add-upload-form')
});
// Close details button
this.el.find('.resource-panel-close').click(this.closePanel);
// Did we embed some form errors?
if (typeof global_form_errors == 'object') {
if (global_form_errors.resources) {
var openedOne = false;
for (i in global_form_errors.resources) {
var resource_errors = global_form_errors.resources[i];
if (CKAN.Utils.countObject(resource_errors) > 0) {
var resource = this.collection.at(i);
resource.view.setErrors(resource_errors);
if (!openedOne) {
resource.view.openMyPanel();
openedOne = true;
}
}
}
}
}
else {
// Initial state
this.openFirstPanel();
}
},
/*
* Called when the page loads or the current resource is deleted.
* Reset page state to the first available edit panel.
*/
openFirstPanel: function() {
if (this.collection.length>0) {
this.collection.at(0).view.openMyPanel();
}
else {
this.openAddPanel();
}
},
/*
* Open the 'Add New Resource' special-case panel on the right.
*/
openAddPanel: function(e) {
if (e) { e.preventDefault(); }
var panel = this.el.find('.resource-panel');
var addLi = this.el.find('.resource-list-add > li');
this.el.find('.resource-list > li').removeClass('active');
$('.resource-details').hide();
this.el.find('.resource-details.resource-add').show();
addLi.addClass('active');
panel.show();
panel.css('top', Math.max(0, addLi.position().top + addLi.height() - panel.height()));
},
/*
* Close the panel on the right.
*/
closePanel: function(e) {
if (e) { e.preventDefault(); }
this.el.find('.resource-list > li').removeClass('active');
this.el.find('.resource-panel').hide();
},
/*
* Update the resource__N__field names to match
* new sort order.
*/
sortStop: function(e,ui) {
this.collection.each(function(resource) {
// Ask the DOM for the new sort order
var index = resource.view.li.index();
resource.view.options.position = index;
// Update the form element names
var table = resource.view.table;
$.each(table.find('input,textarea,select'), function(input_index, input) {
var name = $(input).attr('name');
if (name) {
name = name.replace(/(resources__)\d+(.*)/, '$1'+index+'$2');
$(input).attr('name',name);
}
});
});
},
/*
* Calculate id of the next resource to create
*/
nextIndex: function() {
var maxId=-1;
var root = this.el.find('.resource-panel');
root.find('input').each(function(idx,input) {
var name = $(input).attr('name') || '';
var splitName=name.split('__');
if (splitName.length>1) {
var myId = parseInt(splitName[1],10);
maxId = Math.max(myId, maxId);
}
});
return maxId+1;
},
/*
* Create DOM elements for new resource.
*/
resourceAdded: function(resource) {
var self = this;
resource.view = new CKAN.View.Resource({
position: this.nextIndex(),
model: resource,
callback_deleteMe: function() { self.collection.remove(resource); }
});
this.el.find('.resource-list-edit').append(resource.view.li);
this.el.find('.resource-panel').append(resource.view.table);
if (resource.isNew()) {
resource.view.openMyPanel();
}
},
/*
* Destroy DOM elements for deleted resource.
*/
resourceRemoved: function(resource) {
resource.view.removeFromDom();
delete resource.view;
this.openFirstPanel();
}
});
/* ============================== */
/* == Backbone View: Resource == */
/* ============================== */
CKAN.View.Resource = Backbone.View.extend({
initialize: function() {
this.el = $(this.el);
_.bindAll(this,'updateName','updateIcon','name','askToDelete','openMyPanel','setErrors','setupDynamicExtras','addDynamicExtra', 'onDatastoreEnabledChange');
this.render();
},
render: function() {
this.raw_resource = this.model.toTemplateJSON();
var resource_object = {
resource: this.raw_resource,
num: this.options.position,
resource_icon: '/images/icons/page_white.png',
resourceTypeOptions: [
['file', 'Data File'],
['api', 'API'],
['visualization', 'Visualization'],
['image', 'Image'],
['metadata', 'Metadata'],
['documentation', 'Documentation'],
['code', 'Code'],
['example', 'Example']
]
};
// Generate DOM elements
this.li = $($.tmpl(CKAN.Templates.resourceEntry, resource_object));
this.table = $($.tmpl(CKAN.Templates.resourceDetails, resource_object));
// Hook to changes in name
this.nameBox = this.table.find('input.js-resource-edit-name');
this.descriptionBox = this.table.find('textarea.js-resource-edit-description');
CKAN.Utils.bindInputChanges(this.nameBox,this.updateName);
CKAN.Utils.bindInputChanges(this.descriptionBox,this.updateName);
// Hook to changes in format
this.formatBox = this.table.find('input.js-resource-edit-format');
CKAN.Utils.bindInputChanges(this.formatBox,this.updateIcon);
// Hook to open panel link
this.li.find('.resource-open-my-panel').click(this.openMyPanel);
this.table.find('.js-resource-edit-delete').click(this.askToDelete);
this.table.find('.js-datastore-enabled-checkbox').change(this.onDatastoreEnabledChange);
// Hook to markdown editor
CKAN.Utils.setupMarkdownEditor(this.table.find('.markdown-editor'));
if (resource_object.resource.webstore_url) {
this.table.find('.js-datastore-enabled-checkbox').prop('checked', true);
}
// Set initial state
this.updateName();
this.updateIcon();
this.setupDynamicExtras();
this.hasErrors = false;
},
/*
* Process a JSON object of errors attached to this resource
*/
setErrors: function(obj) {
if (CKAN.Utils.countObject(obj) > 0) {
this.hasErrors = true;
this.errors = obj;
this.li.addClass('hasErrors');
var errorList = $('<dl/>').addClass('errorList');
$.each(obj,function(k,v) {
var errorText = '';
var newLine = false;
$.each(v,function(index,value) {
if (newLine) { errorText += '<br/>'; }
errorText += value;
newLine = true;
});
errorList.append($('<dt/>').html(k));
errorList.append($('<dd/>').html(errorText));
});
this.table.find('.resource-errors').append(errorList).show();
}
},
/*
* Work out what I should be called. Rough-match
* of helpers.py:resource_display_name.
*/
name: function() {
var name = this.nameBox.val();
if (!name) {
name = this.descriptionBox.val();
if (!name) {
if (this.model.isNew()) {
name = '<em>[new resource]</em>';
}
else {
name = '[no name] ' + this.model.id;
}
}
}
if (name.length>45) {
name = name.substring(0,45)+'...';
}
return name;
},
/*
* Called when the user types to update the name in
* my <li> to match the <input> values.
*/
updateName: function() {
// Need to structurally modify the DOM to force a re-render of text
var $link = this.li.find('.js-resource-edit-name');
$link.html('<span>'+this.name()+'</span>');
},
/*
* Called when the user types to update the icon <img>
* tags. Uses server API to select icon.
*/
updateIcon: function() {
var self = this;
if (self.updateIconTimer) {
clearTimeout(self.updateIconTimer);
}
self.updateIconTimer = setTimeout(function() {
// AJAX to server API
$.getJSON('/api/2/util/resource/format_icon?format='+encodeURIComponent(self.formatBox.val()), function(data) {
if (data && data.icon && data.format==self.formatBox.val()) {
self.li.find('.js-resource-icon').attr('src',data.icon);
self.table.find('.js-resource-icon').attr('src',data.icon);
}
});
delete self.updateIconTimer;
},
100);
},
/*
* Closes all other panels on the right and opens my editor panel.
*/
openMyPanel: function(e) {
if (e) { e.preventDefault(); }
// Close all tables
var panel = this.table.parents('.resource-panel');
panel.find('.resource-details').hide();
this.li.parents('fieldset#resources').find('.resource-list > li').removeClass('active');
panel.show();
this.table.show();
this.table.find('.js-resource-edit-name').focus();
this.li.addClass('active');
panel.css('top', Math.max(0, this.li.position().top+this.li.height() - panel.height()));
},
/*
* Called when my delete button is clicked. Calls back to the parent
* resource editor.
*/
askToDelete: function(e) {
e.preventDefault();
var confirmMessage = CKAN.Strings.deleteThisResourceQuestion.replace('%name%', this.name());
if (confirm(confirmMessage)) {
this.options.callback_deleteMe();
}
},
/*
* Set up the dynamic-extras section of the table.
*/
setupDynamicExtras: function() {
var self = this;
$.each(this.raw_resource, function(key,value) {
// Skip the known keys
if (self.reservedWord(key)) { return; }
self.addDynamicExtra(key,value);
});
this.table.find('.add-resource-extra').click(function(e) {
e.preventDefault();
self.addDynamicExtra('','');
});
},
addDynamicExtra: function(key,value) {
// Create elements
var dynamicExtra = $($.tmpl(CKAN.Templates.resourceExtra, {
num: this.options.position,
key: key,
value: value}));
this.table.find('.dynamic-extras').append(dynamicExtra);
// Captured values
var inputKey = dynamicExtra.find('.extra-key');
var inputValue = dynamicExtra.find('.extra-value');
// Callback function
var self = this;
var setExtraName = function() {
var _key = inputKey.val();
var key = $.trim(_key).replace(/\s+/g,'');
// Don't allow you to create an extra called mimetype (etc)
if (self.reservedWord(key)) { key=''; }
// Set or unset the field's name
if (key.length) {
var newName = 'resources__'+self.options.position+'__'+key;
inputValue.attr('name',newName);
inputValue.removeClass('strikethrough');
}
else {
inputValue.removeAttr('name');
inputValue.addClass('strikethrough');
}
};
// Callback function
var clickRemove = function(e) {
e.preventDefault();
dynamicExtra.remove();
};
// Init with bindings
CKAN.Utils.bindInputChanges(dynamicExtra.find('.extra-key'), setExtraName);
dynamicExtra.find('.remove-resource-extra').click(clickRemove);
setExtraName();
},
reservedWord: function(word) {
return word=='cache_last_updated' ||
word=='cache_url' ||
word=='dataset' ||
word=='description' ||
word=='displaytitle' ||
word=='extras' ||
word=='format' ||
word=='hash' ||
word=='id' ||
word=='last_modified' ||
word=='mimetype' ||
word=='mimetype_inner' ||
word=='name' ||
word=='package_id' ||
word=='position' ||
word=='resource_group_id' ||
word=='resource_type' ||
word=='revision_id' ||
word=='revision_timestamp' ||
word=='size' ||
word=='size_extra' ||
word=='state' ||
word=='url' ||
word=='webstore_last_updated' ||
word=='webstore_url';
},
/*
* Called when my model is destroyed. Remove me from the page.
*/
removeFromDom: function() {
this.li.remove();
this.table.remove();
},
onDatastoreEnabledChange: function(e) {
var isChecked = this.table.find('.js-datastore-enabled-checkbox').prop('checked');
var webstore_url = isChecked ? 'enabled' : null;
this.model.set({webstore_url: webstore_url});
this.table.find('.js-datastore-enabled-text').val(webstore_url);
}
});
/* ============================================= */
/* Backbone View: Add Resource by uploading file */
/* ============================================= */
CKAN.View.ResourceAddUpload = Backbone.View.extend({
tagName: 'div',
initialize: function(options) {
this.el = $(this.el);
_.bindAll(this, 'render', 'updateFormData', 'setMessage', 'uploadFile');
$(CKAN.Templates.resourceUpload).appendTo(this.el);
this.$messages = this.el.find('.alert');
this.setupFileUpload();
},
events: {
'click input[type="submit"]': 'uploadFile'
},
setupFileUpload: function() {
var self = this;
this.el.find('.fileupload').fileupload({
// needed because we are posting to remote url
forceIframeTransport: true,
replaceFileInput: false,
autoUpload: false,
fail: function(e, data) {
alert('Upload failed');
},
add: function(e,data) {
self.fileData = data;
self.fileUploadData = data;
self.key = self.makeUploadKey(data.files[0].name);
self.updateFormData(self.key);
},
send: function(e, data) {
self.setMessage('Uploading file ... <img src="http://assets.okfn.org/images/icons/ajaxload-circle.gif" class="spinner" />');
},
done: function(e, data) {
self.onUploadComplete(self.key);
}
})
},
ISODateString: function(d) {
function pad(n) {return n<10 ? '0'+n : n};
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds());
},
// Create an upload key/label for this file.
//
// Form: {current-date}/file-name. Do not just use the file name as this
// would lead to collisions.
// (Could add userid/username and/or a small random string to reduce
// collisions but chances seem very low already)
makeUploadKey: function(fileName) {
// google storage replaces ' ' with '+' which breaks things
// See http://trac.ckan.org/ticket/1518 for more.
var corrected = fileName.replace(/ /g, '-');
// note that we put hh mm ss as hhmmss rather hh:mm:ss (former is 'basic
// format')
var now = new Date();
// replace ':' with nothing
var str = this.ISODateString(now).replace(':', '').replace(':', '');
return str + '/' + corrected;
},
updateFormData: function(key) {
var self = this;
self.setMessage('Checking upload permissions ... <img src="http://assets.okfn.org/images/icons/ajaxload-circle.gif" class="spinner" />');
self.el.find('.fileinfo').text(key);
$.ajax({
url: CKAN.SITE_URL + '/api/storage/auth/form/' + key,
async: false,
success: function(data) {
self.el.find('form').attr('action', data.action);
_tmpl = '<input type="hidden" name="${name}" value="${value}" />';
var $hidden = $(self.el.find('form div.hidden-inputs')[0]);
$.each(data.fields, function(idx, item) {
$hidden.append($.tmpl(_tmpl, item));
});
self.hideMessage();
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: more graceful error handling (e.g. of 409)
self.setMessage('Failed to get credentials for storage upload. Upload cannot proceed', 'error');
self.el.find('input[name="upload"]').hide();
}
});
},
uploadFile: function(e) {
e.preventDefault();
if (!this.fileData) {
alert('No file selected');
return;
}
var jqXHR = this.fileData.submit();
},
onUploadComplete: function(key) {
var self = this;
$.ajax({
url: CKAN.SITE_URL + '/api/storage/metadata/' + self.key,
success: function(data) {
var name = data._label;
if (name && name.length > 0 && name[0] === '/') {
name = name.slice(1);
}
var d = new Date(data._last_modified);
var lastmod = self.ISODateString(d);
var newResource = new CKAN.Model.Resource({});
newResource.set({
url: data._location
, name: name
, size: data._content_length
, last_modified: lastmod
, format: data._format
, mimetype: data._format
, resource_type: 'file.upload'
, owner: data['uploaded-by']
, hash: data._checksum
, cache_url: data._location
, cache_url_updated: lastmod
}
, {
error: function(model, error) {
var msg = 'Filed uploaded OK but error adding resource: ' + error + '.';
msg += 'You may need to create a resource directly. Uploaded file at: ' + data._location;
CKAN.View.flash(msg, 'error');
}
}
);
self.collection.add(newResource);
self.setMessage('File uploaded OK and resource added', 'success');
CKAN.View.flash('File uploaded OK and resource added');
}
});
},
setMessage: function(msg, category) {
var category = category || 'alert-info';
this.$messages.removeClass('alert-info alert-success alert-error');
this.$messages.addClass(category);
this.$messages.show();
this.$messages.html(msg);
},
hideMessage: function() {
this.$messages.hide('slow');
}
});
/* ======================================== */
/* == Backbone View: Add resource by URL == */
/* ======================================== */
CKAN.View.ResourceAddUrl = Backbone.View.extend({
initialize: function(options) {
_.bindAll(this, 'clickSubmit');
},
clickSubmit: function(e) {
e.preventDefault();
var self = this;
var newResource = new CKAN.Model.Resource({});
this.el.find('input[name=save]').addClass("disabled");
var urlVal = this.el.find('input[name=url]').val();
var qaEnabled = $.inArray('qa',CKAN.plugins)>=0;
if(qaEnabled && this.options.mode=='file') {
$.ajax({
url: CKAN.SITE_URL + '/qa/link_checker',
context: newResource,
data: {url: urlVal},
dataType: 'json',
error: function(){
newResource.set({url: urlVal, resource_type: 'file'});
self.collection.add(newResource);
self.resetForm();
},
success: function(data){
data = data[0];
newResource.set({
url: urlVal,
resource_type: 'file',
format: data.format,
size: data.size,
mimetype: data.mimetype,
last_modified: data.last_modified,
url_error: (data.url_errors || [""])[0]
});
self.collection.add(newResource);
self.resetForm();
}
});
}
else {
newResource.set({url: urlVal, resource_type: this.options.mode});
this.collection.add(newResource);
this.resetForm();
}
},
resetForm: function() {
this.el.find('input[name=save]').removeClass("disabled");
this.el.find('input[name=url]').val('');
},
events: {
'click .btn': 'clickSubmit'
}
});
/* ================ */
/* == CKAN.Utils == */
/* ================ */
CKAN.Utils = function($, my) {
// Animate the appearance of an element by expanding its height
my.animateHeight = function(element, animTime) {
if (!animTime) { animTime = 350; }
element.show();
var finalHeight = element.height();
element.height(0);
element.animate({height:finalHeight}, animTime);
};
my.bindInputChanges = function(input, callback) {
input.keyup(callback);
input.keydown(callback);
input.keypress(callback);
input.change(callback);
};
my.setupDatasetDeleteButton = function() {
var select = $('select.dataset-delete');
select.attr('disabled','disabled');
select.css({opacity: 0.3});
$('button.dataset-delete').click(function(e) {
select.removeAttr('disabled');
select.fadeTo('fast',1.0);
$(e.target).css({opacity:0});
$(e.target).attr('disabled','disabled');
return false;
});
};
// Attach dataset autocompletion to provided elements
//
// Requires: jquery-ui autocomplete
my.setupPackageAutocomplete = function(elements) {
elements.autocomplete({
minLength: 0,
source: function(request, callback) {
var url = '/dataset/autocomplete?q=' + request.term;
$.ajax({
url: url,
success: function(data) {
// atm is a string with items broken by \n and item = title (name)|name
var out = [];
var items = data.split('\n');
$.each(items, function(idx, value) {
var _tmp = value.split('|');
var _newItem = {
label: _tmp[0],
value: _tmp[1]
};
out.push(_newItem);
});
callback(out);
}
});
}
, select: function(event, ui) {
var input_box = $(this);
input_box.val('');
var parent_dd = input_box.parent('dd');
var old_name = input_box.attr('name');
var field_name_regex = /^(\S+)__(\d+)__(\S+)$/;
var split = old_name.match(field_name_regex);
var new_name = split[1] + '__' + (parseInt(split[2],10) + 1) + '__' + split[3];
input_box.attr('name', new_name);
input_box.attr('id', new_name);
parent_dd.before(
'<input type="hidden" name="' + old_name + '" value="' + ui.item.value + '">' + '<dd>' + ui.item.label + '</dd>'
);
}
});
};
// Attach tag autocompletion to provided elements
//
// Requires: jquery-ui autocomplete
my.setupTagAutocomplete = function(elements) {
// don't navigate away from the field on tab when selecting an item
elements.bind( "keydown",
function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
}
).autocomplete({
minLength: 1,
source: function(request, callback) {
// here request.term is whole list of tags so need to get last
var _realTerm = $.trim(request.term.split(',').pop());
var url = CKAN.SITE_URL + '/api/2/util/tag/autocomplete?incomplete=' + _realTerm;
$.getJSON(url, function(data) {
// data = { ResultSet: { Result: [ {Name: tag} ] } } (Why oh why?)
var tags = $.map(data.ResultSet.Result, function(value, idx) {
return value.Name;
});
callback( $.ui.autocomplete.filter(tags, _realTerm) );
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = this.value.split(',');
// remove the current input
terms.pop();
// add the selected item
terms.push( " "+ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( " " );
this.value = terms.join( "," );
return false;
}