blob: 3e025b6e9bc90eeb4c51a3be668508ac3b329fc8 [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, " "));
Chengyu Fan7b978f82015-12-09 17:03:23 -070033 };
Tyler Scott2118a412015-10-29 15:17:05 -060034
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;
Chengyu Fan7b978f82015-12-09 17:03:23 -070063 };
Tyler Scottcdfcde82015-09-14 16:13:29 -060064
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'];
Chengyu Fan7b978f82015-12-09 17:03:23 -070089 this.catalogPrefix = new Name(this.catalog);
Tyler Scottcdfcde82015-09-14 16:13:29 -060090
91 this.face = new Face(config['global']['faceConfig']);
92
93 //Easy access dom variables
94 this.categories = $('#side-menu');
95 this.resultTable = $('#resultTable');
96 this.filters = $('#filters');
97 this.searchInput = $('#search');
98 this.searchBar = $('#searchBar');
99 this.searchButton = $('#searchButton');
100 this.resultMenu = $('.resultMenu');
101 this.alerts = $('#alerts');
102 this.requestForm = $('#requestForm');
103
104 var scope = this;
105
106 $('.requestSelectedButton').click(function(){
107 ga('send', 'event', 'button', 'click', 'request');
108 scope.request(scope.resultTable.find('.resultSelector:checked:not([disabled])').parent().parent());
109 });
110
111 this.filterSetup();
112
113 //Init autocomplete
114 this.searchInput.autoComplete(function(field, callback){
115 ga('send', 'event', 'search', 'autocomplete');
Tyler Scott94458992015-09-24 14:16:28 -0700116 scope.autoComplete(field, function(data){
117 var list = data.next;
118 var last = data.lastComponent === true;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600119 callback(list.map(function(element){
Tyler Scott94458992015-09-24 14:16:28 -0700120 return field + element + (last?"/":""); //Don't add trailing slash for last component.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600121 }));
122 });
123 });
124
125 //Handle search
126 this.searchBar.submit(function(e){
127 ga('send', 'event', 'search', 'submit');
128 e.preventDefault();
129 if (scope.searchInput.val().length === 0){
130 if (!scope.searchBar.hasClass('has-error')){
131 scope.searchBar.addClass('has-error').append('<span class="help-block">Search path is required!</span>');
132 }
133 return;
134 } else {
135 scope.searchBar.removeClass('has-error').find('.help-block').fadeOut(function(){$(this).remove()});
136 }
137 scope.pathSearch();
138 });
139
140 this.searchButton.click(function(){
141 console.log("Search Button Pressed");
142 ga('send', 'event', 'button', 'click', 'search');
143 scope.search();
144 });
145
146 //Result navigation handlers
147 this.resultMenu.find('.next').click(function(){
148 ga('send', 'event', 'button', 'click', 'next');
149 if (!$(this).hasClass('disabled')){
150 scope.getResults(scope.page + 1);
151 }
152 });
153 this.resultMenu.find('.previous').click(function(){
154 ga('send', 'event', 'button', 'click', 'previous');
155 if (!$(this).hasClass('disabled')){
156 scope.getResults(scope.page - 1);
157 }
158 });
Tyler Scotte8dac702015-10-13 14:33:25 -0600159 this.resultMenu.find('.clearResults').click(function(){
160 ga('send', 'event', 'button', 'click', 'resultClear');
161 scope.clearResults();
162 $('#results').fadeOut(function(){
163 $(this).addClass('hidden');
164 });
165 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600166
167 //Change the number of results per page handler
168 var rpps = $('.resultsPerPageSelector').click(function(){
169
170 var t = $(this);
171
172 if (t.hasClass('active')){
173 return;
174 }
175
176 rpps.find('.active').removeClass('active');
177 t.addClass('active');
178 scope.resultsPerPage = Number(t.text());
179 scope.getResults(0); //Force return to page 1;
180
181 });
182
183 //Init tree search
184 $('#treeSearch div').treeExplorer(function(path, callback){
185 console.log("Tree Explorer request", path);
186 ga('send', 'event', 'tree', 'request');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600187 scope.autoComplete(path, function(data){
188 var list = data.next;
189 var last = (data.lastComponent === true);
Tyler Scottbb42ed22015-10-21 17:02:56 -0600190
191 if (last) {
192 console.log("Redirecting last element request to a search.");
193 scope.clearResults();
194 scope.query(scope.catalog, {'??': path},
195 function(interest, data){
196 console.log("Search response", interest, data);
Chengyu Fan7b978f82015-12-09 17:03:23 -0700197 scope.name = interest.getName();
Tyler Scottbb42ed22015-10-21 17:02:56 -0600198 scope.getResults(0);
199 }, function(interest){
200 console.warn("Failed to retrieve final component.", interest, path);
201 scope.createAlert("Failed to request final component. " + path + " See console for details.");
202 });
203 return; //Don't call the callback
204 }
205
Tyler Scottcdfcde82015-09-14 16:13:29 -0600206 console.log("Autocomplete response", list);
207 callback(list.map(function(element){
Tyler Scottbb42ed22015-10-21 17:02:56 -0600208 return (path == "/"?"/":"") + element + "/";
Tyler Scottcdfcde82015-09-14 16:13:29 -0600209 }));
Chengyu Fan7b978f82015-12-09 17:03:23 -0700210 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600211 });
212
Tyler Scottb59e6de2015-09-18 14:46:30 -0600213 $('#treeSearch').on('click', '.treeSearch', function(){
214 var t = $(this);
215
216 scope.clearResults();
217
218 var path = t.parent().parent().attr('id');
219
Tyler Scottbb42ed22015-10-21 17:02:56 -0600220 console.log("Tree search:", path);
Tyler Scottb59e6de2015-09-18 14:46:30 -0600221
222 scope.query(scope.catalog, {'??': path},
223 function(interest, data){ //Success
224 console.log("Tree search response", interest, data);
225
Chengyu Fan7b978f82015-12-09 17:03:23 -0700226 scope.name = interest.getName();
Tyler Scottb59e6de2015-09-18 14:46:30 -0600227
228 scope.getResults(0);
229 },
230 function(interest){ //Failure
231 console.warn("Request failed! Timeout", interest);
232 scope.createAlert("Request timed out.\""+ interest.getName().toUri() + "\" See console for details.");
233 });
234
235 });
236
Tyler Scottcdfcde82015-09-14 16:13:29 -0600237 this.setupRequestForm();
238
Tyler Scott48f92cd2015-10-16 18:31:20 -0600239 this.resultTable.popover({
240 selector : ".metaDataLink",
241 content: function(){
242 return scope.getMetaData(this);
243 },
244 title: "Metadata",
245 html: true,
246 trigger: 'click',
247 placement: 'bottom'
248 });
249
250 this.resultTable.on('click', '.metaDataLink', function(e){
251 //This prevents the page from scrolling when you click on a name.
252 e.preventDefault();
253 });
254
Tyler Scottf355e452015-11-06 21:35:14 -0700255 this.resultTable.on('click', '.subsetButton', function(){
256 var metaData = $(this).siblings('pre').text();
257 var exp = /netcdf ([\w-]+)/;
258 var match = exp.exec(metaData);
259 var filename = match[0].replace(/netcdf /,'') + '.nc';
260 scope.request(null, filename);
261 });
262
Chengyu Fan7b978f82015-12-09 17:03:23 -0700263 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600264
265 Atmos.prototype.clearResults = function(){
266 this.results = []; //Drop any old results.
267 this.retrievedSegments = 0;
268 this.resultCount = Infinity;
269 this.page = 0;
270 this.resultTable.empty();
Chengyu Fan7b978f82015-12-09 17:03:23 -0700271 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600272
273 Atmos.prototype.pathSearch = function(){
274 var value = this.searchInput.val();
275
276 this.clearResults();
277
278 var scope = this;
279
280 this.query(this.catalog, {"??": value},
281 function(interest, data){
282 console.log("Query response:", interest, data);
283
Tyler Scott27b03692016-02-11 14:27:43 -0700284 scope.name = data.getName();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600285
286 scope.getResults(0);
287
288 },
289 function(interest){
290 console.warn("Request failed! Timeout", interest);
291 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
292 });
293
Chengyu Fan7b978f82015-12-09 17:03:23 -0700294 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600295
296 Atmos.prototype.search = function(){
297
298 var filters = this.getFilters();
299
300 console.log("Search started!", this.searchInput.val(), filters);
301
302 console.log("Initiating query");
303
304 this.clearResults();
305
306 var scope = this;
307
308 this.query(this.catalog, filters,
309 function(interest, data){ //Response function
310 console.log("Query Response:", interest, data);
311
Chengyu Fan7b978f82015-12-09 17:03:23 -0700312 scope.name = interest.getName();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600313
314 scope.getResults(0);
315
316 }, function(interest){ //Timeout function
Tyler Scottd980a292015-10-13 15:16:34 -0600317 console.warn("Request failed after 3 attempts!", interest);
318 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600319 });
320
Chengyu Fan7b978f82015-12-09 17:03:23 -0700321 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600322
323 Atmos.prototype.autoComplete = function(field, callback){
324
325 var scope = this;
326
327 this.query(this.catalog, {"?": field},
328 function(interest, data){
329
Chengyu Fan7b978f82015-12-09 17:03:23 -0700330 var name = interest.getName();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600331
332 var interest = new Interest(name);
Tyler Scott8724e422015-10-13 17:59:07 -0600333 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600334 interest.setMustBeFresh(true);
335
Tyler Scottd61bf832015-11-30 16:36:17 -0700336 async.retry(4, function(done){
Tyler Scott8724e422015-10-13 17:59:07 -0600337 scope.face.expressInterest(interest,
338 function(interest, data){
339
340 if (data.getContent().length !== 0){
341 callback(JSON.parse(data.getContent().toString().replace(/[\n\0]/g, "")));
Tyler Scottd61bf832015-11-30 16:36:17 -0700342 done();
Tyler Scott8724e422015-10-13 17:59:07 -0600343 } else {
344 callback([]);
Tyler Scottd61bf832015-11-30 16:36:17 -0700345 done();
Tyler Scott8724e422015-10-13 17:59:07 -0600346 }
347
Tyler Scottd61bf832015-11-30 16:36:17 -0700348 }, function(){
349 done("Failed attempt to request data.")
350 });
351 }, function(err, results){
352 if (err){
353 console.warn("Interest timed out!", interest);
354 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
355 }
356 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600357
358 }, function(interest){
359 console.error("Request failed! Timeout", interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600360 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600361 });
362
Chengyu Fan7b978f82015-12-09 17:03:23 -0700363 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600364
365 Atmos.prototype.showResults = function(resultIndex) {
366
367 var results = this.results.slice(this.resultsPerPage * resultIndex, this.resultsPerPage * (resultIndex + 1));
368
369 var resultDOM = $(
370 results.reduce(function(prev, current){
Tyler Scott48f92cd2015-10-16 18:31:20 -0600371 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 -0600372 prev.push(current);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600373 prev.push('</a></td></tr>');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600374 return prev;
375 }, ['<tr><th><input id="resultSelectAll" type="checkbox" title="Select All"> Select</th><th>Name</th></tr>']).join('')
376 );
377
378 resultDOM.find('#resultSelectAll').click(function(){
379 if ($(this).is(':checked')){
380 resultDOM.find('.resultSelector:not([disabled])').prop('checked', true);
381 } else {
382 resultDOM.find('.resultSelector:not([disabled])').prop('checked', false);
383 }
384 });
385
386 this.resultTable.hide().empty().append(resultDOM).slideDown('slow');
387
388 this.resultMenu.find('.pageNumber').text(resultIndex + 1);
389 this.resultMenu.find('.pageLength').text(this.resultsPerPage * resultIndex + results.length);
390
391 if (this.resultsPerPage * (resultIndex + 1) >= this.resultCount) {
392 this.resultMenu.find('.next').addClass('disabled');
393 } else if (resultIndex === 0){
394 this.resultMenu.find('.next').removeClass('disabled');
395 }
396
397 if (resultIndex === 0){
398 this.resultMenu.find('.previous').addClass('disabled');
399 } else if (resultIndex === 1) {
400 this.resultMenu.find('.previous').removeClass('disabled');
401 }
402
Tyler Scottf355e452015-11-06 21:35:14 -0700403 $.scrollTo("#results", 500, {interrupt: true});
404
Chengyu Fan7b978f82015-12-09 17:03:23 -0700405 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600406
407 Atmos.prototype.getResults = function(index){
Chengyu Fan7b978f82015-12-09 17:03:23 -0700408 var scope = this;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600409
410 if ($('#results').hasClass('hidden')){
411 $('#results').removeClass('hidden').slideDown();
412 }
413
Chengyu Fan7b978f82015-12-09 17:03:23 -0700414 if ((scope.results.length === scope.resultCount) || (scope.resultsPerPage * (index + 1) < scope.results.length)){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600415 //console.log("We already have index", index);
Chengyu Fan7b978f82015-12-09 17:03:23 -0700416 scope.page = index;
417 scope.showResults(index);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600418 return;
419 }
420
Chengyu Fan7b978f82015-12-09 17:03:23 -0700421 if (scope.name === null) {
Tyler Scottcdfcde82015-09-14 16:13:29 -0600422 console.error("This shouldn't be reached! We are getting results before a search has occured!");
423 throw new Error("Illegal State");
424 }
425
Chengyu Fan7b978f82015-12-09 17:03:23 -0700426 var interestName = new Name(scope.name);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600427
Chengyu Fan7b978f82015-12-09 17:03:23 -0700428 // Interest name should be /<catalog-prefix>/query/<query-param>/<version>/<#seq>
429 if (scope.name.size() === (scope.catalogPrefix.size() + 3)) {
430 interestName = interestName.appendSegment(scope.retrievedSegments++);
431 console.log("Requesting data index: (", scope.retrievedSegments - 1, ") at ", interestName.toUri());
432 }
Tyler Scottcdfcde82015-09-14 16:13:29 -0600433
Chengyu Fan7b978f82015-12-09 17:03:23 -0700434 var interest = new Interest(interestName);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600435
Tyler Scottd61bf832015-11-30 16:36:17 -0700436 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600437 interest.setMustBeFresh(true);
438
Tyler Scottd61bf832015-11-30 16:36:17 -0700439 async.retry(4, function(done){
Chengyu Fan7b978f82015-12-09 17:03:23 -0700440 scope.face.expressInterest(interest,
Tyler Scottd61bf832015-11-30 16:36:17 -0700441 function(interest, data){ //Response
Tyler Scottcdfcde82015-09-14 16:13:29 -0600442
Tyler Scottd61bf832015-11-30 16:36:17 -0700443 if (data.getContent().length === 0){
444 scope.resultMenu.find('.totalResults').text(0);
445 scope.resultMenu.find('.pageNumber').text(0);
446 scope.resultMenu.find('.pageLength').text(0);
447 console.log("Empty response.");
448 scope.resultTable.html("<tr><td>Empty response. This usually means no results.</td></tr>");
449 return;
450 }
451
452 var content = JSON.parse(data.getContent().toString().replace(/[\n\0]/g,""));
453
454 if (!content.results){
455 scope.resultMenu.find('.totalResults').text(0);
456 scope.resultMenu.find('.pageNumber').text(0);
457 scope.resultMenu.find('.pageLength').text(0);
458 console.log("No results were found!");
459 scope.resultTable.html("<tr><td>No Results</td></tr>");
460 return;
461 }
462
463 scope.results = scope.results.concat(content.results);
464
465 scope.resultCount = content.resultCount;
466
467 scope.resultMenu.find('.totalResults').text(scope.resultCount);
468
469 scope.page = index;
470
Chengyu Fan7b978f82015-12-09 17:03:23 -0700471 // reset scope.name
472 scope.name = new Name(data.getName().getPrefix(scope.catalogPrefix.size() + 3));
473
Tyler Scottd61bf832015-11-30 16:36:17 -0700474 scope.getResults(index); //Keep calling this until we have enough data.
475
476 done();
477
478 },
479 function(interest){ //Timeout
480 done("Failed to request results.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600481 }
Tyler Scottd61bf832015-11-30 16:36:17 -0700482 );
483 }, function(err){
484 if (err){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600485 console.error("Failed to retrieve results: timeout", interest);
Tyler Scottd61bf832015-11-30 16:36:17 -0700486 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600487 }
Tyler Scottd61bf832015-11-30 16:36:17 -0700488 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600489
Chengyu Fan7b978f82015-12-09 17:03:23 -0700490 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600491
492 Atmos.prototype.query = function(prefix, parameters, callback, timeout) {
493
494 var queryPrefix = new Name(prefix);
495 queryPrefix.append("query");
496
497 var jsonString = JSON.stringify(parameters);
498 queryPrefix.append(jsonString);
499
500 var queryInterest = new Interest(queryPrefix);
Tyler Scott8724e422015-10-13 17:59:07 -0600501 queryInterest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600502 queryInterest.setMustBeFresh(true);
503
Tyler Scott8724e422015-10-13 17:59:07 -0600504 var face = this.face;
Tyler Scottd61bf832015-11-30 16:36:17 -0700505
506 async.retry(4, function(done){
507 face.expressInterest(queryInterest, function(interest, data){
508 callback(interest, data);
509 done();
510 }, function(interest){
511 done("Failed attempt to query results", interest);
512 });
513 }, function(err, interest){
514 if (err){
Tyler Scott8724e422015-10-13 17:59:07 -0600515 timeout(interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600516 }
Tyler Scottd61bf832015-11-30 16:36:17 -0700517 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600518
Chengyu Fan7b978f82015-12-09 17:03:23 -0700519 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600520
521 /**
522 * This function returns a map of all the categories active filters.
523 * @return {Object<string, string>}
524 */
525 Atmos.prototype.getFilters = function(){
526 var filters = this.filters.children().toArray().reduce(function(prev, current){
527 var data = $(current).text().split(/:/);
528 prev[data[0]] = data[1];
529 return prev;
530 }, {}); //Collect a map<category, filter>.
531 //TODO Make the return value map<category, Array<filter>>
532 return filters;
Chengyu Fan7b978f82015-12-09 17:03:23 -0700533 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600534
535 /**
536 * Creates a closable alert for the user.
537 *
538 * @param {string} message
539 * @param {string} type - Override the alert type.
540 */
541 Atmos.prototype.createAlert = function(message, type) {
542
543 var alert = $('<div class="alert"><div>');
544 alert.addClass(type?type:'alert-info');
545 alert.text(message);
546 alert.append(closeButton);
547
548 this.alerts.append(alert);
Chengyu Fan7b978f82015-12-09 17:03:23 -0700549 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600550
551 /**
552 * Requests all of the names represented by the buttons in the elements list.
553 *
554 * @param elements {Array<jQuery>} A list of the table row elements
Tyler Scottf355e452015-11-06 21:35:14 -0700555 * @param subsetFileName {String} If present then do a subsetting request instead.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600556 */
557 Atmos.prototype.request = function(){
558
559 //Pseudo globals.
560 var keyChain;
561 var certificateName;
562 var keyAdded = false;
563
Tyler Scottf355e452015-11-06 21:35:14 -0700564 return function(elements, subsetFilename){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600565
566 var names = [];
Tyler Scottf355e452015-11-06 21:35:14 -0700567 $(elements).find('.metaDataLink').each(function(){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600568 var name = $(this).text();
569 names.push(name);
Tyler Scottf355e452015-11-06 21:35:14 -0700570 });
571
572 var subset = false;
573
574 if (!subsetFilename){
575 $('#subsetting').hide();
576 } else {
577 $('#subsetting').show();
578 subset = true;
579 }
Tyler Scottcdfcde82015-09-14 16:13:29 -0600580
581 var scope = this;
582 this.requestForm.on('submit', function(e){ //This will be registered for the next submit from the form.
583 e.preventDefault();
584
Tyler Scottf355e452015-11-06 21:35:14 -0700585 $('#request .alert').remove();
586
587 var variables = [];
588 if (subset){
589 $('#subsetVariables .row').each(function(){
590 var t = $(this);
591 var values = {};
592 t.find('.values input').each(function(){
593 var t = $(this);
594 values[t.attr('name')] = t.val();
595 });
596 variables.push({variable: t.find('.variable').val(), values: values});
597 });
598 }
599
Tyler Scottcdfcde82015-09-14 16:13:29 -0600600 //Form checking
601 var dest = scope.requestForm.find('#requestDest .active');
602 if (dest.length !== 1){
Tyler Scottf355e452015-11-06 21:35:14 -0700603 var alert = $('<div class="alert alert-warning">A destination is required!' + closeButton + '<div>');
604 $('#request > .panel-body').append(alert);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600605 return;
606 }
607
Tyler Scottf355e452015-11-06 21:35:14 -0700608 $('#request').modal('hide');//Initial params are ok. We can close the form.
Tyler Scottb59e6de2015-09-18 14:46:30 -0600609
610 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600611
612 $(this).off(e); //Don't fire this again, the request must be regenerated
613
614 //Key setup
615 if (!keyAdded){
616 if (!scope.config.retrieval.demoKey || !scope.config.retrieval.demoKey.pub || !scope.config.retrieval.demoKey.priv){
617 scope.createAlert("This host was not configured to handle retrieval! See console for details.", 'alert-danger');
618 console.error("Missing/invalid key! This must be configured in the config on the server.", scope.config.demoKey);
619 return;
620 }
621
622 //FIXME base64 may or may not exist in other browsers. Need a new polyfill.
623 var pub = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.pub)); //MUST be a Buffer (Buffer != Uint8Array)
624 var priv = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.priv));
625
626 var identityStorage = new MemoryIdentityStorage();
627 var privateKeyStorage = new MemoryPrivateKeyStorage();
628 keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage),
629 new SelfVerifyPolicyManager(identityStorage));
630
631 var keyName = new Name("/retrieve/DSK-123");
632 certificateName = keyName.getSubName(0, keyName.size() - 1)
633 .append("KEY").append(keyName.get(-1))
634 .append("ID-CERT").append("0");
635
636 identityStorage.addKey(keyName, KeyType.RSA, new Blob(pub, false));
637 privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, pub, priv);
638
639 scope.face.setCommandSigningInfo(keyChain, certificateName);
640
641 keyAdded = true;
642
643 }
644
645 //Retrieval
646 var retrievePrefix = new Name("/catalog/ui/" + guid());
647
Tyler Scottcdfcde82015-09-14 16:13:29 -0600648 scope.face.registerPrefix(retrievePrefix,
649 function(prefix, interest, face, interestFilterId, filter){ //On Interest
650 //This function will exist until the page exits but will likely only be used once.
651
652 var data = new Data(interest.getName());
Tyler Scottf355e452015-11-06 21:35:14 -0700653 var content;
654 if (subset){
655 content = JSON.stringify({name: subsetFilename, subset: variables});
656 } else {
657 content = JSON.stringify(names);
658 }
659 //Blob breaks the data! Don't use it
660 data.setContent(content); //TODO Packetize this.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600661 keyChain.sign(data, certificateName);
662
663 try {
664 face.putData(data);
665 console.log("Responded for", interest.getName().toUri(), data);
Tyler Scottd980a292015-10-13 15:16:34 -0600666 scope.createAlert("Data retrieval has initiated.", "alert-success");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600667 } catch (e) {
668 console.error("Failed to respond to", interest.getName().toUri(), data);
669 scope.createAlert("Data retrieval failed.");
670 }
671
672 }, function(prefix){ //On fail
Tyler Scottcdfcde82015-09-14 16:13:29 -0600673 scope.createAlert("Failed to register the retrieval URI! See console for details.", "alert-danger");
674 console.error("Failed to register URI:", prefix.toUri(), prefix);
Tyler Scottd980a292015-10-13 15:16:34 -0600675 }, function(prefix, registeredPrefixId){ //On success
676 var name = new Name(dest.text());
677 name.append(prefix);
678 var interest = new Interest(name);
679 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottd980a292015-10-13 15:16:34 -0600680
Tyler Scottd61bf832015-11-30 16:36:17 -0700681 async.retry(4, function(done){
Tyler Scottd980a292015-10-13 15:16:34 -0600682 scope.face.expressInterest(interest,
683 function(interest, data){ //Success
684 console.log("Request for", name.toUri(), "succeeded.", interest, data);
Tyler Scottd61bf832015-11-30 16:36:17 -0700685 done();
Tyler Scottd980a292015-10-13 15:16:34 -0600686 },
Tyler Scottd61bf832015-11-30 16:36:17 -0700687 function(){
688 done("Failed to request from retrieve agent.");
689 }
Tyler Scottd980a292015-10-13 15:16:34 -0600690 );
Tyler Scottd61bf832015-11-30 16:36:17 -0700691 }, function(err){
692 if (err){
693 console.error("Request for", name.toUri(), "timed out (3 times).", interest);
694 scope.createAlert("Request for " + name.toUri() + " timed out after 3 attempts. This means that the retrieve failed! See console for more details.");
695 }
696 });
697
Tyler Scottcdfcde82015-09-14 16:13:29 -0600698 }
699 );
700
701 });
702 $('#request').modal(); //This forces the form to be the only option.
703
Chengyu Fan7b978f82015-12-09 17:03:23 -0700704 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600705 }();
706
707 Atmos.prototype.filterSetup = function() {
708 //Filter setup
709
710 var prefix = new Name(this.catalog).append("filters-initialization");
711
712 var scope = this;
713
714 this.getAll(prefix, function(data) { //Success
715 var raw = JSON.parse(data.replace(/[\n\0]/g, '')); //Remove null byte and parse
716
717 console.log("Filter categories:", raw);
718
719 $.each(raw, function(index, object){ //Unpack list of objects
720 $.each(object, function(category, searchOptions) { //Unpack category from object (We don't know what it is called)
721 //Create the category
722 var e = $('<li><a href="#">' + category.replace(/_/g, " ") + '</a><ul class="subnav nav nav-pills nav-stacked"></ul></li>');
723
724 var sub = e.find('ul.subnav');
725 $.each(searchOptions, function(index, name){
726 //Create the filter list inside the category
727 var item = $('<li><a href="#">' + name + '</a></li>');
728 sub.append(item);
729 item.click(function(){ //Click on the side menu filters
730 if (item.hasClass('active')){ //Does the filter already exist?
731 item.removeClass('active');
732 scope.filters.find(':contains(' + category + ':' + name + ')').remove();
733 } else { //Add a filter
734 item.addClass('active');
735 var filter = $('<span class="label label-default"></span>');
736 filter.text(category + ':' + name);
737
738 scope.filters.append(filter);
739
740 filter.click(function(){ //Click on a filter
741 filter.remove();
742 item.removeClass('active');
743 });
744 }
745
746 });
747 });
748
749 //Toggle the menus. (Only respond when the immediate tab is clicked.)
750 e.find('> a').click(function(){
751 scope.categories.find('.subnav').slideUp();
752 var t = $(this).siblings('.subnav');
753 if ( !t.is(':visible') ){ //If the sub menu is not visible
754 t.slideDown(function(){
755 t.triggerHandler('focus');
756 }); //Make it visible and look at it.
757 }
758 });
759
760 scope.categories.append(e);
761
762 });
763 });
764
765 }, function(interest){ //Timeout
766 scope.createAlert("Failed to initialize the filters!", "alert-danger");
767 console.error("Failed to initialize filters!", interest);
768 ga('send', 'event', 'error', 'filters');
769 });
770
Chengyu Fan7b978f82015-12-09 17:03:23 -0700771 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600772
773 /**
774 * This function retrieves all segments in order until it knows it has reached the last one.
775 * It then returns the final joined result.
Tyler Scottd61bf832015-11-30 16:36:17 -0700776 *
Tyler Scottf355e452015-11-06 21:35:14 -0700777 * @param prefix {String|Name} The ndn name we are retrieving.
778 * @param callback {function(String)} if successful, will call the callback with a string of data.
779 * @param failure {function(Interest)} if unsuccessful, will call failure with the last failed interest.
780 * @param stop {boolean} stop if no finalBlock.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600781 */
Tyler Scottf355e452015-11-06 21:35:14 -0700782 Atmos.prototype.getAll = function(prefix, callback, failure, stop){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600783
784 var scope = this;
785 var d = [];
786
Tyler Scottd61bf832015-11-30 16:36:17 -0700787 var name = new Name(prefix);
788 var segment = 0;
Tyler Scott8724e422015-10-13 17:59:07 -0600789
Tyler Scottd61bf832015-11-30 16:36:17 -0700790 var request = function(){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600791
Tyler Scottd61bf832015-11-30 16:36:17 -0700792 var n2 = new Name(name);
793 n2.appendSegment(segment);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600794
Tyler Scottd61bf832015-11-30 16:36:17 -0700795 var interest = new Interest(n2);
Tyler Scott8724e422015-10-13 17:59:07 -0600796 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600797 interest.setMustBeFresh(true); //Is this needed?
798
Tyler Scottd61bf832015-11-30 16:36:17 -0700799 async.retry(4, function(done){
800 scope.face.expressInterest(interest,
801 function(interest, data){
802 handleData(interest, data);
803 done();
804 }, function(){
805 done("Failed to get segment.");
806 }
807 );
808 }, function(err){
809 if (err){
810 console.log("Failed after 3 attempts:", err);
811 }
812 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600813
Chengyu Fan7b978f82015-12-09 17:03:23 -0700814 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600815
Tyler Scottcdfcde82015-09-14 16:13:29 -0600816 var handleData = function(interest, data){
817
818 d.push(data.getContent().toString());
819
Tyler Scottf355e452015-11-06 21:35:14 -0700820 var hasFinalBlock = data.getMetaInfo().getFinalBlockId().value.length === 0;
821 var finalBlockStop = hasFinalBlock && stop;
822
823 if (finalBlockStop ||
824 (!hasFinalBlock && interest.getName().get(-1).toSegment() == data.getMetaInfo().getFinalBlockId().toSegment())){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600825 callback(d.join(""));
826 } else {
Tyler Scottd61bf832015-11-30 16:36:17 -0700827 segment++;
828 request();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600829 }
830
Chengyu Fan7b978f82015-12-09 17:03:23 -0700831 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600832
Tyler Scottd61bf832015-11-30 16:36:17 -0700833 request();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600834
Chengyu Fan7b978f82015-12-09 17:03:23 -0700835 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600836
Tyler Scottb59e6de2015-09-18 14:46:30 -0600837 Atmos.prototype.cleanRequestForm = function(){
838 $('#requestDest').prev().removeClass('btn-success').addClass('btn-default');
839 $('#requestDropText').text('Destination');
840 $('#requestDest .active').removeClass('active');
Tyler Scottf355e452015-11-06 21:35:14 -0700841 $('#subsetMenu').attr('class', 'collapse');
842 $('#subsetVariables').empty();
843 $('#request .alert').alert('close').remove();
Chengyu Fan7b978f82015-12-09 17:03:23 -0700844 };
Tyler Scottb59e6de2015-09-18 14:46:30 -0600845
Tyler Scottcdfcde82015-09-14 16:13:29 -0600846 Atmos.prototype.setupRequestForm = function(){
Tyler Scottb59e6de2015-09-18 14:46:30 -0600847
848 var scope = this;
849
Tyler Scottcdfcde82015-09-14 16:13:29 -0600850 this.requestForm.find('#requestCancel').click(function(){
851 $('#request').unbind('submit') //Removes all event handlers.
852 .modal('hide'); //Hides the form.
Tyler Scottb59e6de2015-09-18 14:46:30 -0600853 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600854 });
855
856 var dests = $(this.config['retrieval']['destinations'].reduce(function(prev, current){
857 prev.push('<li><a href="#">');
858 prev.push(current);
859 prev.push("</a></li>");
860 return prev;
861 }, []).join(""));
862
863 this.requestForm.find('#requestDest').append(dests)
864 .on('click', 'a', function(e){
865 $('#requestDest .active').removeClass('active');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600866 var t = $(this);
867 t.parent().addClass('active');
868 $('#requestDropText').text(t.text());
869 $('#requestDest').prev().removeClass('btn-default').addClass('btn-success');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600870 });
871
Tyler Scottf355e452015-11-06 21:35:14 -0700872 var addVariable = function(selector){
873 var ele = $(selector).clone().attr('id','');
874 ele.find('.close').click(function(){
875 ele.remove();
876 });
877 $('#subsetVariables').append(ele);
878 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600879
Tyler Scottf355e452015-11-06 21:35:14 -0700880 $('#subsetAddVariableBtn').click(function(){
881 addVariable('#customTemplate');
882 });
883 $('#subsetAddTimeVariable').click(function(){
884 addVariable('#timeTemplate');
885 });
886 $('#subsetAddLocVariable').click(function(){
887 addVariable('#locationTemplate');
888 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600889
Chengyu Fan7b978f82015-12-09 17:03:23 -0700890 };
Tyler Scottcdfcde82015-09-14 16:13:29 -0600891
Tyler Scott48f92cd2015-10-16 18:31:20 -0600892 Atmos.prototype.getMetaData = (function(){
893
894 var cache = {};
895
896 return function(element) {
897 var name = $(element).text();
898
Tyler Scottf355e452015-11-06 21:35:14 -0700899 ga('send', 'event', 'request', 'metaData');
900
901 var subsetButton = '<button class="btn btn-default subsetButton" type="button">Subset</button>';
902
Tyler Scott48f92cd2015-10-16 18:31:20 -0600903 if (cache[name]) {
Tyler Scottf355e452015-11-06 21:35:14 -0700904 return [subsetButton, '<pre class="metaData">', cache[name], '</pre>'].join('');
Tyler Scott48f92cd2015-10-16 18:31:20 -0600905 }
906
907 var prefix = new Name(name).append("metadata");
908 var id = guid(); //We need an id because the return MUST be a string.
909 var ret = '<div id="' + id + '"><span class="fa fa-spinner fa-spin"></span></div>';
910
911 this.getAll(prefix, function(data){
912 var el = $('<pre class="metaData"></pre>');
913 el.text(data);
Tyler Scottf355e452015-11-06 21:35:14 -0700914 var container = $('<div></div>');
915 container.append($(subsetButton));
916 container.append(el);
917 $('#' + id).empty().append(container);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600918 cache[name] = data;
919 }, function(interest){
920 $('#' + id).text("The metadata is unavailable for this name.");
921 console.log("Data is unavailable for " + name);
922 });
923
924 return ret;
925
Chengyu Fan7b978f82015-12-09 17:03:23 -0700926 };
Tyler Scott48f92cd2015-10-16 18:31:20 -0600927 })();
928
Tyler Scottcdfcde82015-09-14 16:13:29 -0600929 return Atmos;
930
931})();