blob: d8937cde51e29ed0274136cba661dde3cdd5e4c4 [file] [log] [blame]
Tyler Scottcdfcde82015-09-14 16:13:29 -06001//Run when the document loads AND we have the config loaded.
2(function(){
3 "use strict";
4 var config;
5 Promise.all([
6 new Promise(function(resolve, reject){
7 $.ajax('config.json').done(function(data){
8 config = data;
9 resolve();
10 }).fail(function(){
11 console.error("Failed to get config.");
12 ga('send', 'event', 'error', 'config');
13 reject();
14 });
15 }),
16 new Promise(function(resolve, reject){
17 var timeout = setTimeout(function(){
18 console.error("Document never loaded? Something bad has happened!");
19 reject();
20 }, 10000);
21 $(function () {
22 clearTimeout(timeout);
23 resolve();
24 });
25 })
26 ]).then(function(){
Tyler Scott2118a412015-10-29 15:17:05 -060027
28 var getParameterByName = function(name){
29 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
30 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
31 results = regex.exec(location.search);
32 return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
33 }
34
35 //Overwrite config if present. Any failure will just cause this to be skipped.
36 try{
37 var configParam = JSON.parse(getParameterByName('config'));
38 config = jQuery.extend(true, config, configParam);
39 } catch(e){
40 console.warn("Failure in config overwrite, skipping.", e);
41 }
42
Tyler Scottcdfcde82015-09-14 16:13:29 -060043 new Atmos(config);
44 }, function(){
45 console.error("Failed to initialize!");
46 ga('send', 'event', 'error', 'init');
47 });
48})();
49
50var Atmos = (function(){
51 "use strict";
52
53 var closeButton = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
54
55 var guid = function(){
56 var d = new Date().getTime();
57 var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
58 var r = (d + Math.random()*16)%16 | 0;
59 d = Math.floor(d/16);
60 return (c=='x' ? r : (r&0x3|0x8)).toString(16);
61 });
62 return uuid;
63 }
64
65 /**
66 * Atmos
67 * @version 2.0
68 *
69 * Configures an Atmos object. This manages the atmos interface.
70 *
71 * @constructor
72 * @param {string} catalog - NDN path
73 * @param {Object} config - Object of configuration options for a Face.
74 */
75 var Atmos = function(config){
76
77 //Internal variables.
78 this.results = [];
79 this.resultCount = Infinity;
80 this.name = null;
81 this.page = 0;
82 this.resultsPerPage = 25;
83 this.retrievedSegments = 0;
84
85 //Config/init
86 this.config = config;
87
88 this.catalog = config['global']['catalogPrefix'];
89
90 this.face = new Face(config['global']['faceConfig']);
91
92 //Easy access dom variables
93 this.categories = $('#side-menu');
94 this.resultTable = $('#resultTable');
95 this.filters = $('#filters');
96 this.searchInput = $('#search');
97 this.searchBar = $('#searchBar');
98 this.searchButton = $('#searchButton');
99 this.resultMenu = $('.resultMenu');
100 this.alerts = $('#alerts');
101 this.requestForm = $('#requestForm');
102
103 var scope = this;
104
105 $('.requestSelectedButton').click(function(){
106 ga('send', 'event', 'button', 'click', 'request');
107 scope.request(scope.resultTable.find('.resultSelector:checked:not([disabled])').parent().parent());
108 });
109
110 this.filterSetup();
111
112 //Init autocomplete
113 this.searchInput.autoComplete(function(field, callback){
114 ga('send', 'event', 'search', 'autocomplete');
Tyler Scott94458992015-09-24 14:16:28 -0700115 scope.autoComplete(field, function(data){
116 var list = data.next;
117 var last = data.lastComponent === true;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600118 callback(list.map(function(element){
Tyler Scott94458992015-09-24 14:16:28 -0700119 return field + element + (last?"/":""); //Don't add trailing slash for last component.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600120 }));
121 });
122 });
123
124 //Handle search
125 this.searchBar.submit(function(e){
126 ga('send', 'event', 'search', 'submit');
127 e.preventDefault();
128 if (scope.searchInput.val().length === 0){
129 if (!scope.searchBar.hasClass('has-error')){
130 scope.searchBar.addClass('has-error').append('<span class="help-block">Search path is required!</span>');
131 }
132 return;
133 } else {
134 scope.searchBar.removeClass('has-error').find('.help-block').fadeOut(function(){$(this).remove()});
135 }
136 scope.pathSearch();
137 });
138
139 this.searchButton.click(function(){
140 console.log("Search Button Pressed");
141 ga('send', 'event', 'button', 'click', 'search');
142 scope.search();
143 });
144
145 //Result navigation handlers
146 this.resultMenu.find('.next').click(function(){
147 ga('send', 'event', 'button', 'click', 'next');
148 if (!$(this).hasClass('disabled')){
149 scope.getResults(scope.page + 1);
150 }
151 });
152 this.resultMenu.find('.previous').click(function(){
153 ga('send', 'event', 'button', 'click', 'previous');
154 if (!$(this).hasClass('disabled')){
155 scope.getResults(scope.page - 1);
156 }
157 });
Tyler Scotte8dac702015-10-13 14:33:25 -0600158 this.resultMenu.find('.clearResults').click(function(){
159 ga('send', 'event', 'button', 'click', 'resultClear');
160 scope.clearResults();
161 $('#results').fadeOut(function(){
162 $(this).addClass('hidden');
163 });
164 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600165
166 //Change the number of results per page handler
167 var rpps = $('.resultsPerPageSelector').click(function(){
168
169 var t = $(this);
170
171 if (t.hasClass('active')){
172 return;
173 }
174
175 rpps.find('.active').removeClass('active');
176 t.addClass('active');
177 scope.resultsPerPage = Number(t.text());
178 scope.getResults(0); //Force return to page 1;
179
180 });
181
182 //Init tree search
183 $('#treeSearch div').treeExplorer(function(path, callback){
184 console.log("Tree Explorer request", path);
185 ga('send', 'event', 'tree', 'request');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600186 scope.autoComplete(path, function(data){
187 var list = data.next;
188 var last = (data.lastComponent === true);
Tyler Scottbb42ed22015-10-21 17:02:56 -0600189
190 if (last) {
191 console.log("Redirecting last element request to a search.");
192 scope.clearResults();
193 scope.query(scope.catalog, {'??': path},
194 function(interest, data){
195 console.log("Search response", interest, data);
196 scope.name = data.getContent().toString().replace(/[\n\0]+/g, '');
197 scope.getResults(0);
198 }, function(interest){
199 console.warn("Failed to retrieve final component.", interest, path);
200 scope.createAlert("Failed to request final component. " + path + " See console for details.");
201 });
202 return; //Don't call the callback
203 }
204
Tyler Scottcdfcde82015-09-14 16:13:29 -0600205 console.log("Autocomplete response", list);
206 callback(list.map(function(element){
Tyler Scottbb42ed22015-10-21 17:02:56 -0600207 return (path == "/"?"/":"") + element + "/";
Tyler Scottcdfcde82015-09-14 16:13:29 -0600208 }));
209 })
210 });
211
Tyler Scottb59e6de2015-09-18 14:46:30 -0600212 $('#treeSearch').on('click', '.treeSearch', function(){
213 var t = $(this);
214
215 scope.clearResults();
216
217 var path = t.parent().parent().attr('id');
218
Tyler Scottbb42ed22015-10-21 17:02:56 -0600219 console.log("Tree search:", path);
Tyler Scottb59e6de2015-09-18 14:46:30 -0600220
221 scope.query(scope.catalog, {'??': path},
222 function(interest, data){ //Success
223 console.log("Tree search response", interest, data);
224
225 scope.name = data.getContent().toString().replace(/[\n\0]+/g,'');
226
227 scope.getResults(0);
228 },
229 function(interest){ //Failure
230 console.warn("Request failed! Timeout", interest);
231 scope.createAlert("Request timed out.\""+ interest.getName().toUri() + "\" See console for details.");
232 });
233
234 });
235
Tyler Scottcdfcde82015-09-14 16:13:29 -0600236 this.setupRequestForm();
237
Tyler Scott48f92cd2015-10-16 18:31:20 -0600238 this.resultTable.popover({
239 selector : ".metaDataLink",
240 content: function(){
241 return scope.getMetaData(this);
242 },
243 title: "Metadata",
244 html: true,
245 trigger: 'click',
246 placement: 'bottom'
247 });
248
249 this.resultTable.on('click', '.metaDataLink', function(e){
250 //This prevents the page from scrolling when you click on a name.
251 e.preventDefault();
252 });
253
Tyler Scottf355e452015-11-06 21:35:14 -0700254 this.resultTable.on('click', '.subsetButton', function(){
255 var metaData = $(this).siblings('pre').text();
256 var exp = /netcdf ([\w-]+)/;
257 var match = exp.exec(metaData);
258 var filename = match[0].replace(/netcdf /,'') + '.nc';
259 scope.request(null, filename);
260 });
261
Tyler Scottcdfcde82015-09-14 16:13:29 -0600262 }
263
264 Atmos.prototype.clearResults = function(){
265 this.results = []; //Drop any old results.
266 this.retrievedSegments = 0;
267 this.resultCount = Infinity;
268 this.page = 0;
269 this.resultTable.empty();
270 }
271
272 Atmos.prototype.pathSearch = function(){
273 var value = this.searchInput.val();
274
275 this.clearResults();
276
277 var scope = this;
278
279 this.query(this.catalog, {"??": value},
280 function(interest, data){
281 console.log("Query response:", interest, data);
282
283 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
284
285 scope.getResults(0);
286
287 },
288 function(interest){
289 console.warn("Request failed! Timeout", interest);
290 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
291 });
292
293 }
294
295 Atmos.prototype.search = function(){
296
297 var filters = this.getFilters();
298
299 console.log("Search started!", this.searchInput.val(), filters);
300
301 console.log("Initiating query");
302
303 this.clearResults();
304
305 var scope = this;
306
307 this.query(this.catalog, filters,
308 function(interest, data){ //Response function
309 console.log("Query Response:", interest, data);
310
311 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
312
313 scope.getResults(0);
314
315 }, function(interest){ //Timeout function
Tyler Scottd980a292015-10-13 15:16:34 -0600316 console.warn("Request failed after 3 attempts!", interest);
317 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600318 });
319
320 }
321
322 Atmos.prototype.autoComplete = function(field, callback){
323
324 var scope = this;
325
326 this.query(this.catalog, {"?": field},
327 function(interest, data){
328
329 var name = new Name(data.getContent().toString().replace(/[\n\0]/g,""));
330
331 var interest = new Interest(name);
Tyler Scott8724e422015-10-13 17:59:07 -0600332 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600333 interest.setMustBeFresh(true);
334
Tyler Scott8724e422015-10-13 17:59:07 -0600335 var count = 3;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600336
Tyler Scott8724e422015-10-13 17:59:07 -0600337 var run = function(){
338
339 if (--count === 0){
340 console.warn("Interest timed out!", interest);
341 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
342 return;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600343 }
344
Tyler Scott8724e422015-10-13 17:59:07 -0600345 scope.face.expressInterest(interest,
346 function(interest, data){
347
348 if (data.getContent().length !== 0){
349 callback(JSON.parse(data.getContent().toString().replace(/[\n\0]/g, "")));
350 } else {
351 callback([]);
352 }
353
354 }, run);
355 }
356
357 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600358
359 }, function(interest){
360 console.error("Request failed! Timeout", interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600361 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600362 });
363
364 }
365
366 Atmos.prototype.showResults = function(resultIndex) {
367
368 var results = this.results.slice(this.resultsPerPage * resultIndex, this.resultsPerPage * (resultIndex + 1));
369
370 var resultDOM = $(
371 results.reduce(function(prev, current){
Tyler Scott48f92cd2015-10-16 18:31:20 -0600372 prev.push('<tr><td><input class="resultSelector" type="checkbox"></td><td class="popover-container"><a href="#" class="metaDataLink">');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600373 prev.push(current);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600374 prev.push('</a></td></tr>');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600375 return prev;
376 }, ['<tr><th><input id="resultSelectAll" type="checkbox" title="Select All"> Select</th><th>Name</th></tr>']).join('')
377 );
378
379 resultDOM.find('#resultSelectAll').click(function(){
380 if ($(this).is(':checked')){
381 resultDOM.find('.resultSelector:not([disabled])').prop('checked', true);
382 } else {
383 resultDOM.find('.resultSelector:not([disabled])').prop('checked', false);
384 }
385 });
386
387 this.resultTable.hide().empty().append(resultDOM).slideDown('slow');
388
389 this.resultMenu.find('.pageNumber').text(resultIndex + 1);
390 this.resultMenu.find('.pageLength').text(this.resultsPerPage * resultIndex + results.length);
391
392 if (this.resultsPerPage * (resultIndex + 1) >= this.resultCount) {
393 this.resultMenu.find('.next').addClass('disabled');
394 } else if (resultIndex === 0){
395 this.resultMenu.find('.next').removeClass('disabled');
396 }
397
398 if (resultIndex === 0){
399 this.resultMenu.find('.previous').addClass('disabled');
400 } else if (resultIndex === 1) {
401 this.resultMenu.find('.previous').removeClass('disabled');
402 }
403
Tyler Scottf355e452015-11-06 21:35:14 -0700404 $.scrollTo("#results", 500, {interrupt: true});
405
Tyler Scottcdfcde82015-09-14 16:13:29 -0600406 }
407
408 Atmos.prototype.getResults = function(index){
409
410 if ($('#results').hasClass('hidden')){
411 $('#results').removeClass('hidden').slideDown();
412 }
413
414 if ((this.results.length === this.resultCount) || (this.resultsPerPage * (index + 1) < this.results.length)){
415 //console.log("We already have index", index);
416 this.page = index;
417 this.showResults(index);
418 return;
419 }
420
421 if (this.name === null) {
422 console.error("This shouldn't be reached! We are getting results before a search has occured!");
423 throw new Error("Illegal State");
424 }
425
426 var first = new Name(this.name).appendSegment(this.retrievedSegments++);
427
428 console.log("Requesting data index: (", this.retrievedSegments - 1, ") at ", first.toUri());
429
430 var scope = this;
431
432 var interest = new Interest(first)
433 interest.setInterestLifetimeMilliseconds(5000);
434 interest.setMustBeFresh(true);
435
436 this.face.expressInterest(interest,
437 function(interest, data){ //Response
438
439 if (data.getContent().length === 0){
440 scope.resultMenu.find('.totalResults').text(0);
441 scope.resultMenu.find('.pageNumber').text(0);
442 scope.resultMenu.find('.pageLength').text(0);
443 console.log("Empty response.");
444 return;
445 }
446
447 var content = JSON.parse(data.getContent().toString().replace(/[\n\0]/g,""));
448
449 if (!content.results){
450 scope.resultMenu.find('.totalResults').text(0);
451 scope.resultMenu.find('.pageNumber').text(0);
452 scope.resultMenu.find('.pageLength').text(0);
453 console.log("No results were found!");
454 return;
455 }
456
457 scope.results = scope.results.concat(content.results);
458
459 scope.resultCount = content.resultCount;
460
461 scope.resultMenu.find('.totalResults').text(scope.resultCount);
462
463 scope.page = index;
464
465 scope.getResults(index); //Keep calling this until we have enough data.
466
467 },
468 function(interest){ //Timeout
469 console.error("Failed to retrieve results: timeout", interest);
470 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
471 }
472 );
473
474 }
475
476 Atmos.prototype.query = function(prefix, parameters, callback, timeout) {
477
478 var queryPrefix = new Name(prefix);
479 queryPrefix.append("query");
480
481 var jsonString = JSON.stringify(parameters);
482 queryPrefix.append(jsonString);
483
484 var queryInterest = new Interest(queryPrefix);
Tyler Scott8724e422015-10-13 17:59:07 -0600485 queryInterest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600486 queryInterest.setMustBeFresh(true);
487
Tyler Scott8724e422015-10-13 17:59:07 -0600488 var face = this.face;
489 var retry = 3;
490 var run = function(interest){
491 if (--retry === 0){
492 timeout(interest);
493 } else {
494 face.expressInterest(queryInterest, callback, run);
495 }
496 }
497 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600498
499 }
500
501 /**
502 * This function returns a map of all the categories active filters.
503 * @return {Object<string, string>}
504 */
505 Atmos.prototype.getFilters = function(){
506 var filters = this.filters.children().toArray().reduce(function(prev, current){
507 var data = $(current).text().split(/:/);
508 prev[data[0]] = data[1];
509 return prev;
510 }, {}); //Collect a map<category, filter>.
511 //TODO Make the return value map<category, Array<filter>>
512 return filters;
513 }
514
515 /**
516 * Creates a closable alert for the user.
517 *
518 * @param {string} message
519 * @param {string} type - Override the alert type.
520 */
521 Atmos.prototype.createAlert = function(message, type) {
522
523 var alert = $('<div class="alert"><div>');
524 alert.addClass(type?type:'alert-info');
525 alert.text(message);
526 alert.append(closeButton);
527
528 this.alerts.append(alert);
529 }
530
531 /**
532 * Requests all of the names represented by the buttons in the elements list.
533 *
534 * @param elements {Array<jQuery>} A list of the table row elements
Tyler Scottf355e452015-11-06 21:35:14 -0700535 * @param subsetFileName {String} If present then do a subsetting request instead.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600536 */
537 Atmos.prototype.request = function(){
538
539 //Pseudo globals.
540 var keyChain;
541 var certificateName;
542 var keyAdded = false;
543
Tyler Scottf355e452015-11-06 21:35:14 -0700544 return function(elements, subsetFilename){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600545
546 var names = [];
Tyler Scottf355e452015-11-06 21:35:14 -0700547 $(elements).find('.metaDataLink').each(function(){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600548 var name = $(this).text();
549 names.push(name);
Tyler Scottf355e452015-11-06 21:35:14 -0700550 });
551
552 var subset = false;
553
554 if (!subsetFilename){
555 $('#subsetting').hide();
556 } else {
557 $('#subsetting').show();
558 subset = true;
559 }
Tyler Scottcdfcde82015-09-14 16:13:29 -0600560
561 var scope = this;
562 this.requestForm.on('submit', function(e){ //This will be registered for the next submit from the form.
563 e.preventDefault();
564
Tyler Scottf355e452015-11-06 21:35:14 -0700565 $('#request .alert').remove();
566
567 var variables = [];
568 if (subset){
569 $('#subsetVariables .row').each(function(){
570 var t = $(this);
571 var values = {};
572 t.find('.values input').each(function(){
573 var t = $(this);
574 values[t.attr('name')] = t.val();
575 });
576 variables.push({variable: t.find('.variable').val(), values: values});
577 });
578 }
579
Tyler Scottcdfcde82015-09-14 16:13:29 -0600580 //Form checking
581 var dest = scope.requestForm.find('#requestDest .active');
582 if (dest.length !== 1){
Tyler Scottf355e452015-11-06 21:35:14 -0700583 var alert = $('<div class="alert alert-warning">A destination is required!' + closeButton + '<div>');
584 $('#request > .panel-body').append(alert);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600585 return;
586 }
587
Tyler Scottf355e452015-11-06 21:35:14 -0700588 $('#request').modal('hide');//Initial params are ok. We can close the form.
Tyler Scottb59e6de2015-09-18 14:46:30 -0600589
590 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600591
592 $(this).off(e); //Don't fire this again, the request must be regenerated
593
594 //Key setup
595 if (!keyAdded){
596 if (!scope.config.retrieval.demoKey || !scope.config.retrieval.demoKey.pub || !scope.config.retrieval.demoKey.priv){
597 scope.createAlert("This host was not configured to handle retrieval! See console for details.", 'alert-danger');
598 console.error("Missing/invalid key! This must be configured in the config on the server.", scope.config.demoKey);
599 return;
600 }
601
602 //FIXME base64 may or may not exist in other browsers. Need a new polyfill.
603 var pub = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.pub)); //MUST be a Buffer (Buffer != Uint8Array)
604 var priv = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.priv));
605
606 var identityStorage = new MemoryIdentityStorage();
607 var privateKeyStorage = new MemoryPrivateKeyStorage();
608 keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage),
609 new SelfVerifyPolicyManager(identityStorage));
610
611 var keyName = new Name("/retrieve/DSK-123");
612 certificateName = keyName.getSubName(0, keyName.size() - 1)
613 .append("KEY").append(keyName.get(-1))
614 .append("ID-CERT").append("0");
615
616 identityStorage.addKey(keyName, KeyType.RSA, new Blob(pub, false));
617 privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, pub, priv);
618
619 scope.face.setCommandSigningInfo(keyChain, certificateName);
620
621 keyAdded = true;
622
623 }
624
625 //Retrieval
626 var retrievePrefix = new Name("/catalog/ui/" + guid());
627
Tyler Scottcdfcde82015-09-14 16:13:29 -0600628 scope.face.registerPrefix(retrievePrefix,
629 function(prefix, interest, face, interestFilterId, filter){ //On Interest
630 //This function will exist until the page exits but will likely only be used once.
631
632 var data = new Data(interest.getName());
Tyler Scottf355e452015-11-06 21:35:14 -0700633 var content;
634 if (subset){
635 content = JSON.stringify({name: subsetFilename, subset: variables});
636 } else {
637 content = JSON.stringify(names);
638 }
639 //Blob breaks the data! Don't use it
640 data.setContent(content); //TODO Packetize this.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600641 keyChain.sign(data, certificateName);
642
643 try {
644 face.putData(data);
645 console.log("Responded for", interest.getName().toUri(), data);
Tyler Scottd980a292015-10-13 15:16:34 -0600646 scope.createAlert("Data retrieval has initiated.", "alert-success");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600647 } catch (e) {
648 console.error("Failed to respond to", interest.getName().toUri(), data);
649 scope.createAlert("Data retrieval failed.");
650 }
651
652 }, function(prefix){ //On fail
Tyler Scottcdfcde82015-09-14 16:13:29 -0600653 scope.createAlert("Failed to register the retrieval URI! See console for details.", "alert-danger");
654 console.error("Failed to register URI:", prefix.toUri(), prefix);
Tyler Scottd980a292015-10-13 15:16:34 -0600655 }, function(prefix, registeredPrefixId){ //On success
656 var name = new Name(dest.text());
657 name.append(prefix);
658 var interest = new Interest(name);
659 interest.setInterestLifetimeMilliseconds(1500);
660 var count = 3;
661 var run = function(i2){
662
663 if (--count === 0) {
664 console.error("Request for", name.toUri(), "timed out (3 times).", i2);
665 scope.createAlert("Request for " + name.toUri() + " timed out after 3 attempts. This means that the retrieve failed! See console for more details.");
666 return;
667 }
668
669 scope.face.expressInterest(interest,
670 function(interest, data){ //Success
671 console.log("Request for", name.toUri(), "succeeded.", interest, data);
672 },
673 run
674 );
675 }
676 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600677 }
678 );
679
680 });
681 $('#request').modal(); //This forces the form to be the only option.
682
683 }
684 }();
685
686 Atmos.prototype.filterSetup = function() {
687 //Filter setup
688
689 var prefix = new Name(this.catalog).append("filters-initialization");
690
691 var scope = this;
692
693 this.getAll(prefix, function(data) { //Success
694 var raw = JSON.parse(data.replace(/[\n\0]/g, '')); //Remove null byte and parse
695
696 console.log("Filter categories:", raw);
697
698 $.each(raw, function(index, object){ //Unpack list of objects
699 $.each(object, function(category, searchOptions) { //Unpack category from object (We don't know what it is called)
700 //Create the category
701 var e = $('<li><a href="#">' + category.replace(/_/g, " ") + '</a><ul class="subnav nav nav-pills nav-stacked"></ul></li>');
702
703 var sub = e.find('ul.subnav');
704 $.each(searchOptions, function(index, name){
705 //Create the filter list inside the category
706 var item = $('<li><a href="#">' + name + '</a></li>');
707 sub.append(item);
708 item.click(function(){ //Click on the side menu filters
709 if (item.hasClass('active')){ //Does the filter already exist?
710 item.removeClass('active');
711 scope.filters.find(':contains(' + category + ':' + name + ')').remove();
712 } else { //Add a filter
713 item.addClass('active');
714 var filter = $('<span class="label label-default"></span>');
715 filter.text(category + ':' + name);
716
717 scope.filters.append(filter);
718
719 filter.click(function(){ //Click on a filter
720 filter.remove();
721 item.removeClass('active');
722 });
723 }
724
725 });
726 });
727
728 //Toggle the menus. (Only respond when the immediate tab is clicked.)
729 e.find('> a').click(function(){
730 scope.categories.find('.subnav').slideUp();
731 var t = $(this).siblings('.subnav');
732 if ( !t.is(':visible') ){ //If the sub menu is not visible
733 t.slideDown(function(){
734 t.triggerHandler('focus');
735 }); //Make it visible and look at it.
736 }
737 });
738
739 scope.categories.append(e);
740
741 });
742 });
743
744 }, function(interest){ //Timeout
745 scope.createAlert("Failed to initialize the filters!", "alert-danger");
746 console.error("Failed to initialize filters!", interest);
747 ga('send', 'event', 'error', 'filters');
748 });
749
750 }
751
752 /**
753 * This function retrieves all segments in order until it knows it has reached the last one.
754 * It then returns the final joined result.
Tyler Scottf355e452015-11-06 21:35:14 -0700755 *
756 * @param prefix {String|Name} The ndn name we are retrieving.
757 * @param callback {function(String)} if successful, will call the callback with a string of data.
758 * @param failure {function(Interest)} if unsuccessful, will call failure with the last failed interest.
759 * @param stop {boolean} stop if no finalBlock.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600760 */
Tyler Scottf355e452015-11-06 21:35:14 -0700761 Atmos.prototype.getAll = function(prefix, callback, failure, stop){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600762
763 var scope = this;
764 var d = [];
765
Tyler Scott8724e422015-10-13 17:59:07 -0600766 var count = 3;
767 var retry = function(interest){
768 if (count === 0){
Tyler Scottf355e452015-11-06 21:35:14 -0700769 console.log("Failed to 'getAll' after 3 attempts", interest.toUri(), interest);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600770 failure(interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600771 } else {
772 count--;
773 request(interest.getName().get(-1).toSegment());
774 }
775 }
776
Tyler Scottcdfcde82015-09-14 16:13:29 -0600777 var request = function(segment){
778
779 var name = new Name(prefix);
780 name.appendSegment(segment);
781
782 var interest = new Interest(name);
Tyler Scott8724e422015-10-13 17:59:07 -0600783 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600784 interest.setMustBeFresh(true); //Is this needed?
785
Tyler Scott8724e422015-10-13 17:59:07 -0600786 scope.face.expressInterest(interest, handleData, retry);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600787
788 }
789
Tyler Scottcdfcde82015-09-14 16:13:29 -0600790 var handleData = function(interest, data){
791
792 d.push(data.getContent().toString());
793
Tyler Scottf355e452015-11-06 21:35:14 -0700794 var hasFinalBlock = data.getMetaInfo().getFinalBlockId().value.length === 0;
795 var finalBlockStop = hasFinalBlock && stop;
796
797 if (finalBlockStop ||
798 (!hasFinalBlock && interest.getName().get(-1).toSegment() == data.getMetaInfo().getFinalBlockId().toSegment())){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600799 callback(d.join(""));
800 } else {
Tyler Scott8724e422015-10-13 17:59:07 -0600801 request(interest.getName().get(-1).toSegment() + 1);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600802 }
803
804 }
805
806 request(0);
807
808 }
809
Tyler Scottb59e6de2015-09-18 14:46:30 -0600810 Atmos.prototype.cleanRequestForm = function(){
811 $('#requestDest').prev().removeClass('btn-success').addClass('btn-default');
812 $('#requestDropText').text('Destination');
813 $('#requestDest .active').removeClass('active');
Tyler Scottf355e452015-11-06 21:35:14 -0700814 $('#subsetMenu').attr('class', 'collapse');
815 $('#subsetVariables').empty();
816 $('#request .alert').alert('close').remove();
Tyler Scottb59e6de2015-09-18 14:46:30 -0600817 }
818
Tyler Scottcdfcde82015-09-14 16:13:29 -0600819 Atmos.prototype.setupRequestForm = function(){
Tyler Scottb59e6de2015-09-18 14:46:30 -0600820
821 var scope = this;
822
Tyler Scottcdfcde82015-09-14 16:13:29 -0600823 this.requestForm.find('#requestCancel').click(function(){
824 $('#request').unbind('submit') //Removes all event handlers.
825 .modal('hide'); //Hides the form.
Tyler Scottb59e6de2015-09-18 14:46:30 -0600826 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600827 });
828
829 var dests = $(this.config['retrieval']['destinations'].reduce(function(prev, current){
830 prev.push('<li><a href="#">');
831 prev.push(current);
832 prev.push("</a></li>");
833 return prev;
834 }, []).join(""));
835
836 this.requestForm.find('#requestDest').append(dests)
837 .on('click', 'a', function(e){
838 $('#requestDest .active').removeClass('active');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600839 var t = $(this);
840 t.parent().addClass('active');
841 $('#requestDropText').text(t.text());
842 $('#requestDest').prev().removeClass('btn-default').addClass('btn-success');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600843 });
844
Tyler Scottf355e452015-11-06 21:35:14 -0700845 var addVariable = function(selector){
846 var ele = $(selector).clone().attr('id','');
847 ele.find('.close').click(function(){
848 ele.remove();
849 });
850 $('#subsetVariables').append(ele);
851 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600852
Tyler Scottf355e452015-11-06 21:35:14 -0700853 $('#subsetAddVariableBtn').click(function(){
854 addVariable('#customTemplate');
855 });
856 $('#subsetAddTimeVariable').click(function(){
857 addVariable('#timeTemplate');
858 });
859 $('#subsetAddLocVariable').click(function(){
860 addVariable('#locationTemplate');
861 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600862
863 }
864
Tyler Scott48f92cd2015-10-16 18:31:20 -0600865 Atmos.prototype.getMetaData = (function(){
866
867 var cache = {};
868
869 return function(element) {
870 var name = $(element).text();
871
Tyler Scottf355e452015-11-06 21:35:14 -0700872 ga('send', 'event', 'request', 'metaData');
873
874 var subsetButton = '<button class="btn btn-default subsetButton" type="button">Subset</button>';
875
Tyler Scott48f92cd2015-10-16 18:31:20 -0600876 if (cache[name]) {
Tyler Scottf355e452015-11-06 21:35:14 -0700877 return [subsetButton, '<pre class="metaData">', cache[name], '</pre>'].join('');
Tyler Scott48f92cd2015-10-16 18:31:20 -0600878 }
879
880 var prefix = new Name(name).append("metadata");
881 var id = guid(); //We need an id because the return MUST be a string.
882 var ret = '<div id="' + id + '"><span class="fa fa-spinner fa-spin"></span></div>';
883
884 this.getAll(prefix, function(data){
885 var el = $('<pre class="metaData"></pre>');
886 el.text(data);
Tyler Scottf355e452015-11-06 21:35:14 -0700887 var container = $('<div></div>');
888 container.append($(subsetButton));
889 container.append(el);
890 $('#' + id).empty().append(container);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600891 cache[name] = data;
892 }, function(interest){
893 $('#' + id).text("The metadata is unavailable for this name.");
894 console.log("Data is unavailable for " + name);
895 });
896
897 return ret;
898
899 }
900 })();
901
Tyler Scottcdfcde82015-09-14 16:13:29 -0600902 return Atmos;
903
904})();