blob: 5b953d8c9393965f423332ff4925d6904ae5aa08 [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(){
27 new Atmos(config);
28 }, function(){
29 console.error("Failed to initialize!");
30 ga('send', 'event', 'error', 'init');
31 });
32})();
33
34var Atmos = (function(){
35 "use strict";
36
37 var closeButton = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
38
39 var guid = function(){
40 var d = new Date().getTime();
41 var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
42 var r = (d + Math.random()*16)%16 | 0;
43 d = Math.floor(d/16);
44 return (c=='x' ? r : (r&0x3|0x8)).toString(16);
45 });
46 return uuid;
47 }
48
49 /**
50 * Atmos
51 * @version 2.0
52 *
53 * Configures an Atmos object. This manages the atmos interface.
54 *
55 * @constructor
56 * @param {string} catalog - NDN path
57 * @param {Object} config - Object of configuration options for a Face.
58 */
59 var Atmos = function(config){
60
61 //Internal variables.
62 this.results = [];
63 this.resultCount = Infinity;
64 this.name = null;
65 this.page = 0;
66 this.resultsPerPage = 25;
67 this.retrievedSegments = 0;
68
69 //Config/init
70 this.config = config;
71
72 this.catalog = config['global']['catalogPrefix'];
73
74 this.face = new Face(config['global']['faceConfig']);
75
76 //Easy access dom variables
77 this.categories = $('#side-menu');
78 this.resultTable = $('#resultTable');
79 this.filters = $('#filters');
80 this.searchInput = $('#search');
81 this.searchBar = $('#searchBar');
82 this.searchButton = $('#searchButton');
83 this.resultMenu = $('.resultMenu');
84 this.alerts = $('#alerts');
85 this.requestForm = $('#requestForm');
86
87 var scope = this;
88
89 $('.requestSelectedButton').click(function(){
90 ga('send', 'event', 'button', 'click', 'request');
91 scope.request(scope.resultTable.find('.resultSelector:checked:not([disabled])').parent().parent());
92 });
93
94 this.filterSetup();
95
96 //Init autocomplete
97 this.searchInput.autoComplete(function(field, callback){
98 ga('send', 'event', 'search', 'autocomplete');
Tyler Scott94458992015-09-24 14:16:28 -070099 scope.autoComplete(field, function(data){
100 var list = data.next;
101 var last = data.lastComponent === true;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600102 callback(list.map(function(element){
Tyler Scott94458992015-09-24 14:16:28 -0700103 return field + element + (last?"/":""); //Don't add trailing slash for last component.
Tyler Scottcdfcde82015-09-14 16:13:29 -0600104 }));
105 });
106 });
107
108 //Handle search
109 this.searchBar.submit(function(e){
110 ga('send', 'event', 'search', 'submit');
111 e.preventDefault();
112 if (scope.searchInput.val().length === 0){
113 if (!scope.searchBar.hasClass('has-error')){
114 scope.searchBar.addClass('has-error').append('<span class="help-block">Search path is required!</span>');
115 }
116 return;
117 } else {
118 scope.searchBar.removeClass('has-error').find('.help-block').fadeOut(function(){$(this).remove()});
119 }
120 scope.pathSearch();
121 });
122
123 this.searchButton.click(function(){
124 console.log("Search Button Pressed");
125 ga('send', 'event', 'button', 'click', 'search');
126 scope.search();
127 });
128
129 //Result navigation handlers
130 this.resultMenu.find('.next').click(function(){
131 ga('send', 'event', 'button', 'click', 'next');
132 if (!$(this).hasClass('disabled')){
133 scope.getResults(scope.page + 1);
134 }
135 });
136 this.resultMenu.find('.previous').click(function(){
137 ga('send', 'event', 'button', 'click', 'previous');
138 if (!$(this).hasClass('disabled')){
139 scope.getResults(scope.page - 1);
140 }
141 });
Tyler Scotte8dac702015-10-13 14:33:25 -0600142 this.resultMenu.find('.clearResults').click(function(){
143 ga('send', 'event', 'button', 'click', 'resultClear');
144 scope.clearResults();
145 $('#results').fadeOut(function(){
146 $(this).addClass('hidden');
147 });
148 });
Tyler Scottcdfcde82015-09-14 16:13:29 -0600149
150 //Change the number of results per page handler
151 var rpps = $('.resultsPerPageSelector').click(function(){
152
153 var t = $(this);
154
155 if (t.hasClass('active')){
156 return;
157 }
158
159 rpps.find('.active').removeClass('active');
160 t.addClass('active');
161 scope.resultsPerPage = Number(t.text());
162 scope.getResults(0); //Force return to page 1;
163
164 });
165
166 //Init tree search
167 $('#treeSearch div').treeExplorer(function(path, callback){
168 console.log("Tree Explorer request", path);
169 ga('send', 'event', 'tree', 'request');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600170 scope.autoComplete(path, function(data){
171 var list = data.next;
172 var last = (data.lastComponent === true);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600173 console.log("Autocomplete response", list);
174 callback(list.map(function(element){
Tyler Scottb59e6de2015-09-18 14:46:30 -0600175 return (path == "/"?"/":"") + element + (!last?"/":"");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600176 }));
177 })
178 });
179
Tyler Scottb59e6de2015-09-18 14:46:30 -0600180 $('#treeSearch').on('click', '.treeSearch', function(){
181 var t = $(this);
182
183 scope.clearResults();
184
185 var path = t.parent().parent().attr('id');
186
187 console.log("Stringing tree search:", path);
188
189 scope.query(scope.catalog, {'??': path},
190 function(interest, data){ //Success
191 console.log("Tree search response", interest, data);
192
193 scope.name = data.getContent().toString().replace(/[\n\0]+/g,'');
194
195 scope.getResults(0);
196 },
197 function(interest){ //Failure
198 console.warn("Request failed! Timeout", interest);
199 scope.createAlert("Request timed out.\""+ interest.getName().toUri() + "\" See console for details.");
200 });
201
202 });
203
Tyler Scottcdfcde82015-09-14 16:13:29 -0600204 this.setupRequestForm();
205
Tyler Scott48f92cd2015-10-16 18:31:20 -0600206 this.resultTable.popover({
207 selector : ".metaDataLink",
208 content: function(){
209 return scope.getMetaData(this);
210 },
211 title: "Metadata",
212 html: true,
213 trigger: 'click',
214 placement: 'bottom'
215 });
216
217 this.resultTable.on('click', '.metaDataLink', function(e){
218 //This prevents the page from scrolling when you click on a name.
219 e.preventDefault();
220 });
221
Tyler Scottcdfcde82015-09-14 16:13:29 -0600222 }
223
224 Atmos.prototype.clearResults = function(){
225 this.results = []; //Drop any old results.
226 this.retrievedSegments = 0;
227 this.resultCount = Infinity;
228 this.page = 0;
229 this.resultTable.empty();
230 }
231
232 Atmos.prototype.pathSearch = function(){
233 var value = this.searchInput.val();
234
235 this.clearResults();
236
237 var scope = this;
238
239 this.query(this.catalog, {"??": value},
240 function(interest, data){
241 console.log("Query response:", interest, data);
242
243 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
244
245 scope.getResults(0);
246
247 },
248 function(interest){
249 console.warn("Request failed! Timeout", interest);
250 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
251 });
252
253 }
254
255 Atmos.prototype.search = function(){
256
257 var filters = this.getFilters();
258
259 console.log("Search started!", this.searchInput.val(), filters);
260
261 console.log("Initiating query");
262
263 this.clearResults();
264
265 var scope = this;
266
267 this.query(this.catalog, filters,
268 function(interest, data){ //Response function
269 console.log("Query Response:", interest, data);
270
271 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
272
273 scope.getResults(0);
274
275 }, function(interest){ //Timeout function
Tyler Scottd980a292015-10-13 15:16:34 -0600276 console.warn("Request failed after 3 attempts!", interest);
277 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600278 });
279
280 }
281
282 Atmos.prototype.autoComplete = function(field, callback){
283
284 var scope = this;
285
286 this.query(this.catalog, {"?": field},
287 function(interest, data){
288
289 var name = new Name(data.getContent().toString().replace(/[\n\0]/g,""));
290
291 var interest = new Interest(name);
Tyler Scott8724e422015-10-13 17:59:07 -0600292 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600293 interest.setMustBeFresh(true);
294
Tyler Scott8724e422015-10-13 17:59:07 -0600295 var count = 3;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600296
Tyler Scott8724e422015-10-13 17:59:07 -0600297 var run = function(){
298
299 if (--count === 0){
300 console.warn("Interest timed out!", interest);
301 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
302 return;
Tyler Scottcdfcde82015-09-14 16:13:29 -0600303 }
304
Tyler Scott8724e422015-10-13 17:59:07 -0600305 scope.face.expressInterest(interest,
306 function(interest, data){
307
308 if (data.getContent().length !== 0){
309 callback(JSON.parse(data.getContent().toString().replace(/[\n\0]/g, "")));
310 } else {
311 callback([]);
312 }
313
314 }, run);
315 }
316
317 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600318
319 }, function(interest){
320 console.error("Request failed! Timeout", interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600321 scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details.");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600322 });
323
324 }
325
326 Atmos.prototype.showResults = function(resultIndex) {
327
328 var results = this.results.slice(this.resultsPerPage * resultIndex, this.resultsPerPage * (resultIndex + 1));
329
330 var resultDOM = $(
331 results.reduce(function(prev, current){
Tyler Scott48f92cd2015-10-16 18:31:20 -0600332 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 -0600333 prev.push(current);
Tyler Scott48f92cd2015-10-16 18:31:20 -0600334 prev.push('</a></td></tr>');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600335 return prev;
336 }, ['<tr><th><input id="resultSelectAll" type="checkbox" title="Select All"> Select</th><th>Name</th></tr>']).join('')
337 );
338
339 resultDOM.find('#resultSelectAll').click(function(){
340 if ($(this).is(':checked')){
341 resultDOM.find('.resultSelector:not([disabled])').prop('checked', true);
342 } else {
343 resultDOM.find('.resultSelector:not([disabled])').prop('checked', false);
344 }
345 });
346
347 this.resultTable.hide().empty().append(resultDOM).slideDown('slow');
348
349 this.resultMenu.find('.pageNumber').text(resultIndex + 1);
350 this.resultMenu.find('.pageLength').text(this.resultsPerPage * resultIndex + results.length);
351
352 if (this.resultsPerPage * (resultIndex + 1) >= this.resultCount) {
353 this.resultMenu.find('.next').addClass('disabled');
354 } else if (resultIndex === 0){
355 this.resultMenu.find('.next').removeClass('disabled');
356 }
357
358 if (resultIndex === 0){
359 this.resultMenu.find('.previous').addClass('disabled');
360 } else if (resultIndex === 1) {
361 this.resultMenu.find('.previous').removeClass('disabled');
362 }
363
364 }
365
366 Atmos.prototype.getResults = function(index){
367
368 if ($('#results').hasClass('hidden')){
369 $('#results').removeClass('hidden').slideDown();
370 }
371
Tyler Scotte8dac702015-10-13 14:33:25 -0600372 $.scrollTo("#results", 500, {interrupt: true});
Tyler Scottb59e6de2015-09-18 14:46:30 -0600373
Tyler Scottcdfcde82015-09-14 16:13:29 -0600374 if ((this.results.length === this.resultCount) || (this.resultsPerPage * (index + 1) < this.results.length)){
375 //console.log("We already have index", index);
376 this.page = index;
377 this.showResults(index);
378 return;
379 }
380
381 if (this.name === null) {
382 console.error("This shouldn't be reached! We are getting results before a search has occured!");
383 throw new Error("Illegal State");
384 }
385
386 var first = new Name(this.name).appendSegment(this.retrievedSegments++);
387
388 console.log("Requesting data index: (", this.retrievedSegments - 1, ") at ", first.toUri());
389
390 var scope = this;
391
392 var interest = new Interest(first)
393 interest.setInterestLifetimeMilliseconds(5000);
394 interest.setMustBeFresh(true);
395
396 this.face.expressInterest(interest,
397 function(interest, data){ //Response
398
399 if (data.getContent().length === 0){
400 scope.resultMenu.find('.totalResults').text(0);
401 scope.resultMenu.find('.pageNumber').text(0);
402 scope.resultMenu.find('.pageLength').text(0);
403 console.log("Empty response.");
404 return;
405 }
406
407 var content = JSON.parse(data.getContent().toString().replace(/[\n\0]/g,""));
408
409 if (!content.results){
410 scope.resultMenu.find('.totalResults').text(0);
411 scope.resultMenu.find('.pageNumber').text(0);
412 scope.resultMenu.find('.pageLength').text(0);
413 console.log("No results were found!");
414 return;
415 }
416
417 scope.results = scope.results.concat(content.results);
418
419 scope.resultCount = content.resultCount;
420
421 scope.resultMenu.find('.totalResults').text(scope.resultCount);
422
423 scope.page = index;
424
425 scope.getResults(index); //Keep calling this until we have enough data.
426
427 },
428 function(interest){ //Timeout
429 console.error("Failed to retrieve results: timeout", interest);
430 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
431 }
432 );
433
434 }
435
436 Atmos.prototype.query = function(prefix, parameters, callback, timeout) {
437
438 var queryPrefix = new Name(prefix);
439 queryPrefix.append("query");
440
441 var jsonString = JSON.stringify(parameters);
442 queryPrefix.append(jsonString);
443
444 var queryInterest = new Interest(queryPrefix);
Tyler Scott8724e422015-10-13 17:59:07 -0600445 queryInterest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600446 queryInterest.setMustBeFresh(true);
447
Tyler Scott8724e422015-10-13 17:59:07 -0600448 var face = this.face;
449 var retry = 3;
450 var run = function(interest){
451 if (--retry === 0){
452 timeout(interest);
453 } else {
454 face.expressInterest(queryInterest, callback, run);
455 }
456 }
457 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600458
459 }
460
461 /**
462 * This function returns a map of all the categories active filters.
463 * @return {Object<string, string>}
464 */
465 Atmos.prototype.getFilters = function(){
466 var filters = this.filters.children().toArray().reduce(function(prev, current){
467 var data = $(current).text().split(/:/);
468 prev[data[0]] = data[1];
469 return prev;
470 }, {}); //Collect a map<category, filter>.
471 //TODO Make the return value map<category, Array<filter>>
472 return filters;
473 }
474
475 /**
476 * Creates a closable alert for the user.
477 *
478 * @param {string} message
479 * @param {string} type - Override the alert type.
480 */
481 Atmos.prototype.createAlert = function(message, type) {
482
483 var alert = $('<div class="alert"><div>');
484 alert.addClass(type?type:'alert-info');
485 alert.text(message);
486 alert.append(closeButton);
487
488 this.alerts.append(alert);
489 }
490
491 /**
492 * Requests all of the names represented by the buttons in the elements list.
493 *
494 * @param elements {Array<jQuery>} A list of the table row elements
495 */
496 Atmos.prototype.request = function(){
497
498 //Pseudo globals.
499 var keyChain;
500 var certificateName;
501 var keyAdded = false;
502
503 return function(elements){
504
505 var names = [];
506 var destination = $('#requestDest .active').text();
507 $(elements).find('>*:nth-child(2)').each(function(){
508 var name = $(this).text();
509 names.push(name);
510 });//.append('<span class="badge">Requested!</span>')
511 //Disabling the checkbox doesn't make sense anymore with the ability to request to multiple destinations.
512 //$(elements).find('.resultSelector').prop('disabled', true).prop('checked', false);
513
514 var scope = this;
515 this.requestForm.on('submit', function(e){ //This will be registered for the next submit from the form.
516 e.preventDefault();
517
518 //Form checking
519 var dest = scope.requestForm.find('#requestDest .active');
520 if (dest.length !== 1){
521 $('#requestForm').append($('<div class="alert alert-warning">A destination is required!' + closeButton + '<div>'));
522 return;
523 }
524
525 $('#request').modal('hide')//Initial params are ok. We can close the form.
526 .remove('.alert') //Remove any alerts
Tyler Scottb59e6de2015-09-18 14:46:30 -0600527
528 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600529
530 $(this).off(e); //Don't fire this again, the request must be regenerated
531
532 //Key setup
533 if (!keyAdded){
534 if (!scope.config.retrieval.demoKey || !scope.config.retrieval.demoKey.pub || !scope.config.retrieval.demoKey.priv){
535 scope.createAlert("This host was not configured to handle retrieval! See console for details.", 'alert-danger');
536 console.error("Missing/invalid key! This must be configured in the config on the server.", scope.config.demoKey);
537 return;
538 }
539
540 //FIXME base64 may or may not exist in other browsers. Need a new polyfill.
541 var pub = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.pub)); //MUST be a Buffer (Buffer != Uint8Array)
542 var priv = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.priv));
543
544 var identityStorage = new MemoryIdentityStorage();
545 var privateKeyStorage = new MemoryPrivateKeyStorage();
546 keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage),
547 new SelfVerifyPolicyManager(identityStorage));
548
549 var keyName = new Name("/retrieve/DSK-123");
550 certificateName = keyName.getSubName(0, keyName.size() - 1)
551 .append("KEY").append(keyName.get(-1))
552 .append("ID-CERT").append("0");
553
554 identityStorage.addKey(keyName, KeyType.RSA, new Blob(pub, false));
555 privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, pub, priv);
556
557 scope.face.setCommandSigningInfo(keyChain, certificateName);
558
559 keyAdded = true;
560
561 }
562
563 //Retrieval
564 var retrievePrefix = new Name("/catalog/ui/" + guid());
565
Tyler Scottcdfcde82015-09-14 16:13:29 -0600566 scope.face.registerPrefix(retrievePrefix,
567 function(prefix, interest, face, interestFilterId, filter){ //On Interest
568 //This function will exist until the page exits but will likely only be used once.
569
570 var data = new Data(interest.getName());
571 var content = JSON.stringify(names);
572 data.setContent(content);
573 keyChain.sign(data, certificateName);
574
575 try {
576 face.putData(data);
577 console.log("Responded for", interest.getName().toUri(), data);
Tyler Scottd980a292015-10-13 15:16:34 -0600578 scope.createAlert("Data retrieval has initiated.", "alert-success");
Tyler Scottcdfcde82015-09-14 16:13:29 -0600579 } catch (e) {
580 console.error("Failed to respond to", interest.getName().toUri(), data);
581 scope.createAlert("Data retrieval failed.");
582 }
583
584 }, function(prefix){ //On fail
Tyler Scottcdfcde82015-09-14 16:13:29 -0600585 scope.createAlert("Failed to register the retrieval URI! See console for details.", "alert-danger");
586 console.error("Failed to register URI:", prefix.toUri(), prefix);
587
Tyler Scottd980a292015-10-13 15:16:34 -0600588 }, function(prefix, registeredPrefixId){ //On success
589 var name = new Name(dest.text());
590 name.append(prefix);
591 var interest = new Interest(name);
592 interest.setInterestLifetimeMilliseconds(1500);
593 var count = 3;
594 var run = function(i2){
595
596 if (--count === 0) {
597 console.error("Request for", name.toUri(), "timed out (3 times).", i2);
598 scope.createAlert("Request for " + name.toUri() + " timed out after 3 attempts. This means that the retrieve failed! See console for more details.");
599 return;
600 }
601
602 scope.face.expressInterest(interest,
603 function(interest, data){ //Success
604 console.log("Request for", name.toUri(), "succeeded.", interest, data);
605 },
606 run
607 );
608 }
609 run();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600610 }
611 );
612
613 });
614 $('#request').modal(); //This forces the form to be the only option.
615
616 }
617 }();
618
619 Atmos.prototype.filterSetup = function() {
620 //Filter setup
621
622 var prefix = new Name(this.catalog).append("filters-initialization");
623
624 var scope = this;
625
626 this.getAll(prefix, function(data) { //Success
627 var raw = JSON.parse(data.replace(/[\n\0]/g, '')); //Remove null byte and parse
628
629 console.log("Filter categories:", raw);
630
631 $.each(raw, function(index, object){ //Unpack list of objects
632 $.each(object, function(category, searchOptions) { //Unpack category from object (We don't know what it is called)
633 //Create the category
634 var e = $('<li><a href="#">' + category.replace(/_/g, " ") + '</a><ul class="subnav nav nav-pills nav-stacked"></ul></li>');
635
636 var sub = e.find('ul.subnav');
637 $.each(searchOptions, function(index, name){
638 //Create the filter list inside the category
639 var item = $('<li><a href="#">' + name + '</a></li>');
640 sub.append(item);
641 item.click(function(){ //Click on the side menu filters
642 if (item.hasClass('active')){ //Does the filter already exist?
643 item.removeClass('active');
644 scope.filters.find(':contains(' + category + ':' + name + ')').remove();
645 } else { //Add a filter
646 item.addClass('active');
647 var filter = $('<span class="label label-default"></span>');
648 filter.text(category + ':' + name);
649
650 scope.filters.append(filter);
651
652 filter.click(function(){ //Click on a filter
653 filter.remove();
654 item.removeClass('active');
655 });
656 }
657
658 });
659 });
660
661 //Toggle the menus. (Only respond when the immediate tab is clicked.)
662 e.find('> a').click(function(){
663 scope.categories.find('.subnav').slideUp();
664 var t = $(this).siblings('.subnav');
665 if ( !t.is(':visible') ){ //If the sub menu is not visible
666 t.slideDown(function(){
667 t.triggerHandler('focus');
668 }); //Make it visible and look at it.
669 }
670 });
671
672 scope.categories.append(e);
673
674 });
675 });
676
677 }, function(interest){ //Timeout
678 scope.createAlert("Failed to initialize the filters!", "alert-danger");
679 console.error("Failed to initialize filters!", interest);
680 ga('send', 'event', 'error', 'filters');
681 });
682
683 }
684
685 /**
686 * This function retrieves all segments in order until it knows it has reached the last one.
687 * It then returns the final joined result.
688 */
Tyler Scott48f92cd2015-10-16 18:31:20 -0600689 Atmos.prototype.getAll = function(prefix, callback, failure){
Tyler Scottcdfcde82015-09-14 16:13:29 -0600690
691 var scope = this;
692 var d = [];
693
Tyler Scott8724e422015-10-13 17:59:07 -0600694 var count = 3;
695 var retry = function(interest){
696 if (count === 0){
Tyler Scott48f92cd2015-10-16 18:31:20 -0600697 console.log("Failed to 'getAll' after 3 attempts", interest);
698 failure(interest);
Tyler Scott8724e422015-10-13 17:59:07 -0600699 } else {
700 count--;
701 request(interest.getName().get(-1).toSegment());
702 }
703 }
704
Tyler Scottcdfcde82015-09-14 16:13:29 -0600705 var request = function(segment){
706
707 var name = new Name(prefix);
708 name.appendSegment(segment);
709
710 var interest = new Interest(name);
Tyler Scott8724e422015-10-13 17:59:07 -0600711 interest.setInterestLifetimeMilliseconds(1500);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600712 interest.setMustBeFresh(true); //Is this needed?
713
Tyler Scott8724e422015-10-13 17:59:07 -0600714 scope.face.expressInterest(interest, handleData, retry);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600715
716 }
717
Tyler Scottcdfcde82015-09-14 16:13:29 -0600718 var handleData = function(interest, data){
719
720 d.push(data.getContent().toString());
721
722 if (interest.getName().get(-1).toSegment() == data.getMetaInfo().getFinalBlockId().toSegment()){
723 callback(d.join(""));
724 } else {
Tyler Scott8724e422015-10-13 17:59:07 -0600725 request(interest.getName().get(-1).toSegment() + 1);
Tyler Scottcdfcde82015-09-14 16:13:29 -0600726 }
727
728 }
729
730 request(0);
731
732 }
733
Tyler Scottb59e6de2015-09-18 14:46:30 -0600734 Atmos.prototype.cleanRequestForm = function(){
735 $('#requestDest').prev().removeClass('btn-success').addClass('btn-default');
736 $('#requestDropText').text('Destination');
737 $('#requestDest .active').removeClass('active');
738 }
739
Tyler Scottcdfcde82015-09-14 16:13:29 -0600740 Atmos.prototype.setupRequestForm = function(){
Tyler Scottb59e6de2015-09-18 14:46:30 -0600741
742 var scope = this;
743
Tyler Scottcdfcde82015-09-14 16:13:29 -0600744 this.requestForm.find('#requestCancel').click(function(){
745 $('#request').unbind('submit') //Removes all event handlers.
746 .modal('hide'); //Hides the form.
Tyler Scottb59e6de2015-09-18 14:46:30 -0600747 scope.cleanRequestForm();
Tyler Scottcdfcde82015-09-14 16:13:29 -0600748 });
749
750 var dests = $(this.config['retrieval']['destinations'].reduce(function(prev, current){
751 prev.push('<li><a href="#">');
752 prev.push(current);
753 prev.push("</a></li>");
754 return prev;
755 }, []).join(""));
756
757 this.requestForm.find('#requestDest').append(dests)
758 .on('click', 'a', function(e){
759 $('#requestDest .active').removeClass('active');
Tyler Scottb59e6de2015-09-18 14:46:30 -0600760 var t = $(this);
761 t.parent().addClass('active');
762 $('#requestDropText').text(t.text());
763 $('#requestDest').prev().removeClass('btn-default').addClass('btn-success');
Tyler Scottcdfcde82015-09-14 16:13:29 -0600764 });
765
766 //This code will remain unused until users must use their own keys instead of the demo key.
767// var scope = this;
768
769// var warning = '<div class="alert alert-warning">' + closeButton + '<div>';
770
771// var handleFile = function(e){
772// var t = $(this);
773// if (e.target.files.length > 1){
774// var el = $(warning);
775// t.append(el.append("We are looking for a single file, we will try the first only!"));
776// } else if (e.target.files.length === 0) {
777// var el = $(warning.replace("alert-warning", "alert-danger"));
778// t.append(el.append("No file was supplied!"));
779// return;
780// }
781
782// var reader = new FileReader();
783// reader.onload = function(e){
784// var key;
785// try {
786// key = JSON.parse(e.target.result);
787// } catch (e) {
788// console.error("Could not parse the key! (", key, ")");
789// var el = $(warning.replace("alert-warning", "alert-danger"));
790// t.append(el.append("Failed to parse the key file, is it a valid json key?"));
791// }
792
793// if (!key.DEFAULT_RSA_PUBLIC_KEY_DER || !key.DEFAULT_RSA_PRIVATE_KEY_DER) {
794// console.warn("Invalid key", key);
795// var el = $(warning.replace("alert-warning", "alert-danger"));
796// t.append(el.append("Failed to parse the key file, it is missing required attributes."));
797// }
798
799
800// };
801
802// }
803
804// this.requestForm.find('#requestDrop').on('dragover', function(e){
805// e.dataTransfer.dropEffect = 'copy';
806// }).on('drop', handleFile);
807
808// this.requestForm.find('input[type=file]').change(handleFile);
809
810 }
811
Tyler Scott48f92cd2015-10-16 18:31:20 -0600812 Atmos.prototype.getMetaData = (function(){
813
814 var cache = {};
815
816 return function(element) {
817 var name = $(element).text();
818
819 if (cache[name]) {
820 return ['<pre class="metaData">', cache[name], '</pre>'].join('');
821 }
822
823 var prefix = new Name(name).append("metadata");
824 var id = guid(); //We need an id because the return MUST be a string.
825 var ret = '<div id="' + id + '"><span class="fa fa-spinner fa-spin"></span></div>';
826
827 this.getAll(prefix, function(data){
828 var el = $('<pre class="metaData"></pre>');
829 el.text(data);
830 $('#' + id).remove('span').append(el);
831 cache[name] = data;
832 }, function(interest){
833 $('#' + id).text("The metadata is unavailable for this name.");
834 console.log("Data is unavailable for " + name);
835 });
836
837 return ret;
838
839 }
840 })();
841
Tyler Scottcdfcde82015-09-14 16:13:29 -0600842 return Atmos;
843
844})();