blob: d013fdae2e120e563c04198bfe0ea63351f72718 [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');
99 scope.autoComplete(field, function(list){
100 callback(list.map(function(element){
101 return field + element + "/";
102 }));
103 });
104 });
105
106 //Handle search
107 this.searchBar.submit(function(e){
108 ga('send', 'event', 'search', 'submit');
109 e.preventDefault();
110 if (scope.searchInput.val().length === 0){
111 if (!scope.searchBar.hasClass('has-error')){
112 scope.searchBar.addClass('has-error').append('<span class="help-block">Search path is required!</span>');
113 }
114 return;
115 } else {
116 scope.searchBar.removeClass('has-error').find('.help-block').fadeOut(function(){$(this).remove()});
117 }
118 scope.pathSearch();
119 });
120
121 this.searchButton.click(function(){
122 console.log("Search Button Pressed");
123 ga('send', 'event', 'button', 'click', 'search');
124 scope.search();
125 });
126
127 //Result navigation handlers
128 this.resultMenu.find('.next').click(function(){
129 ga('send', 'event', 'button', 'click', 'next');
130 if (!$(this).hasClass('disabled')){
131 scope.getResults(scope.page + 1);
132 }
133 });
134 this.resultMenu.find('.previous').click(function(){
135 ga('send', 'event', 'button', 'click', 'previous');
136 if (!$(this).hasClass('disabled')){
137 scope.getResults(scope.page - 1);
138 }
139 });
140
141 //Change the number of results per page handler
142 var rpps = $('.resultsPerPageSelector').click(function(){
143
144 var t = $(this);
145
146 if (t.hasClass('active')){
147 return;
148 }
149
150 rpps.find('.active').removeClass('active');
151 t.addClass('active');
152 scope.resultsPerPage = Number(t.text());
153 scope.getResults(0); //Force return to page 1;
154
155 });
156
157 //Init tree search
158 $('#treeSearch div').treeExplorer(function(path, callback){
159 console.log("Tree Explorer request", path);
160 ga('send', 'event', 'tree', 'request');
161 scope.autoComplete(path, function(list){
162 console.log("Autocomplete response", list);
163 callback(list.map(function(element){
164 return (path == "/"?"/":"") + element + "/";
165 }));
166 })
167 });
168
169 this.setupRequestForm();
170
171 }
172
173 Atmos.prototype.clearResults = function(){
174 this.results = []; //Drop any old results.
175 this.retrievedSegments = 0;
176 this.resultCount = Infinity;
177 this.page = 0;
178 this.resultTable.empty();
179 }
180
181 Atmos.prototype.pathSearch = function(){
182 var value = this.searchInput.val();
183
184 this.clearResults();
185
186 var scope = this;
187
188 this.query(this.catalog, {"??": value},
189 function(interest, data){
190 console.log("Query response:", interest, data);
191
192 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
193
194 scope.getResults(0);
195
196 },
197 function(interest){
198 console.warn("Request failed! Timeout", interest);
199 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
200 });
201
202 }
203
204 Atmos.prototype.search = function(){
205
206 var filters = this.getFilters();
207
208 console.log("Search started!", this.searchInput.val(), filters);
209
210 console.log("Initiating query");
211
212 this.clearResults();
213
214 var scope = this;
215
216 this.query(this.catalog, filters,
217 function(interest, data){ //Response function
218 console.log("Query Response:", interest, data);
219
220 scope.name = data.getContent().toString().replace(/[\n\0]/g,"");
221
222 scope.getResults(0);
223
224 }, function(interest){ //Timeout function
225 console.warn("Request failed! Timeout");
226 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
227 });
228
229 }
230
231 Atmos.prototype.autoComplete = function(field, callback){
232
233 var scope = this;
234
235 this.query(this.catalog, {"?": field},
236 function(interest, data){
237
238 var name = new Name(data.getContent().toString().replace(/[\n\0]/g,""));
239
240 var interest = new Interest(name);
241 interest.setInterestLifetimeMilliseconds(5000);
242 interest.setMustBeFresh(true);
243
244 scope.face.expressInterest(interest,
245 function(interest, data){
246
247 if (data.getContent().length !== 0){
248 callback(JSON.parse(data.getContent().toString().replace(/[\n\0]/g, "")).next);
249 } else {
250 callback([]);
251 }
252
253 }, function(interest){
254 console.warn("Interest timed out!", interest);
255 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
256 });
257
258 }, function(interest){
259 console.error("Request failed! Timeout", interest);
260 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
261 });
262
263 }
264
265 Atmos.prototype.showResults = function(resultIndex) {
266
267 var results = this.results.slice(this.resultsPerPage * resultIndex, this.resultsPerPage * (resultIndex + 1));
268
269 var resultDOM = $(
270 results.reduce(function(prev, current){
271 prev.push('<tr><td><input class="resultSelector" type="checkbox"></td><td>');
272 prev.push(current);
273 prev.push('</td></tr>');
274 return prev;
275 }, ['<tr><th><input id="resultSelectAll" type="checkbox" title="Select All"> Select</th><th>Name</th></tr>']).join('')
276 );
277
278 resultDOM.find('#resultSelectAll').click(function(){
279 if ($(this).is(':checked')){
280 resultDOM.find('.resultSelector:not([disabled])').prop('checked', true);
281 } else {
282 resultDOM.find('.resultSelector:not([disabled])').prop('checked', false);
283 }
284 });
285
286 this.resultTable.hide().empty().append(resultDOM).slideDown('slow');
287
288 this.resultMenu.find('.pageNumber').text(resultIndex + 1);
289 this.resultMenu.find('.pageLength').text(this.resultsPerPage * resultIndex + results.length);
290
291 if (this.resultsPerPage * (resultIndex + 1) >= this.resultCount) {
292 this.resultMenu.find('.next').addClass('disabled');
293 } else if (resultIndex === 0){
294 this.resultMenu.find('.next').removeClass('disabled');
295 }
296
297 if (resultIndex === 0){
298 this.resultMenu.find('.previous').addClass('disabled');
299 } else if (resultIndex === 1) {
300 this.resultMenu.find('.previous').removeClass('disabled');
301 }
302
303 }
304
305 Atmos.prototype.getResults = function(index){
306
307 if ($('#results').hasClass('hidden')){
308 $('#results').removeClass('hidden').slideDown();
309 }
310
311 if ((this.results.length === this.resultCount) || (this.resultsPerPage * (index + 1) < this.results.length)){
312 //console.log("We already have index", index);
313 this.page = index;
314 this.showResults(index);
315 return;
316 }
317
318 if (this.name === null) {
319 console.error("This shouldn't be reached! We are getting results before a search has occured!");
320 throw new Error("Illegal State");
321 }
322
323 var first = new Name(this.name).appendSegment(this.retrievedSegments++);
324
325 console.log("Requesting data index: (", this.retrievedSegments - 1, ") at ", first.toUri());
326
327 var scope = this;
328
329 var interest = new Interest(first)
330 interest.setInterestLifetimeMilliseconds(5000);
331 interest.setMustBeFresh(true);
332
333 this.face.expressInterest(interest,
334 function(interest, data){ //Response
335
336 if (data.getContent().length === 0){
337 scope.resultMenu.find('.totalResults').text(0);
338 scope.resultMenu.find('.pageNumber').text(0);
339 scope.resultMenu.find('.pageLength').text(0);
340 console.log("Empty response.");
341 return;
342 }
343
344 var content = JSON.parse(data.getContent().toString().replace(/[\n\0]/g,""));
345
346 if (!content.results){
347 scope.resultMenu.find('.totalResults').text(0);
348 scope.resultMenu.find('.pageNumber').text(0);
349 scope.resultMenu.find('.pageLength').text(0);
350 console.log("No results were found!");
351 return;
352 }
353
354 scope.results = scope.results.concat(content.results);
355
356 scope.resultCount = content.resultCount;
357
358 scope.resultMenu.find('.totalResults').text(scope.resultCount);
359
360 scope.page = index;
361
362 scope.getResults(index); //Keep calling this until we have enough data.
363
364 },
365 function(interest){ //Timeout
366 console.error("Failed to retrieve results: timeout", interest);
367 scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details.");
368 }
369 );
370
371 }
372
373 Atmos.prototype.query = function(prefix, parameters, callback, timeout) {
374
375 var queryPrefix = new Name(prefix);
376 queryPrefix.append("query");
377
378 var jsonString = JSON.stringify(parameters);
379 queryPrefix.append(jsonString);
380
381 var queryInterest = new Interest(queryPrefix);
382 queryInterest.setInterestLifetimeMilliseconds(4000);
383 queryInterest.setMustBeFresh(true);
384
385 this.face.expressInterest(queryInterest, callback, timeout);
386
387 }
388
389 /**
390 * This function returns a map of all the categories active filters.
391 * @return {Object<string, string>}
392 */
393 Atmos.prototype.getFilters = function(){
394 var filters = this.filters.children().toArray().reduce(function(prev, current){
395 var data = $(current).text().split(/:/);
396 prev[data[0]] = data[1];
397 return prev;
398 }, {}); //Collect a map<category, filter>.
399 //TODO Make the return value map<category, Array<filter>>
400 return filters;
401 }
402
403 /**
404 * Creates a closable alert for the user.
405 *
406 * @param {string} message
407 * @param {string} type - Override the alert type.
408 */
409 Atmos.prototype.createAlert = function(message, type) {
410
411 var alert = $('<div class="alert"><div>');
412 alert.addClass(type?type:'alert-info');
413 alert.text(message);
414 alert.append(closeButton);
415
416 this.alerts.append(alert);
417 }
418
419 /**
420 * Requests all of the names represented by the buttons in the elements list.
421 *
422 * @param elements {Array<jQuery>} A list of the table row elements
423 */
424 Atmos.prototype.request = function(){
425
426 //Pseudo globals.
427 var keyChain;
428 var certificateName;
429 var keyAdded = false;
430
431 return function(elements){
432
433 var names = [];
434 var destination = $('#requestDest .active').text();
435 $(elements).find('>*:nth-child(2)').each(function(){
436 var name = $(this).text();
437 names.push(name);
438 });//.append('<span class="badge">Requested!</span>')
439 //Disabling the checkbox doesn't make sense anymore with the ability to request to multiple destinations.
440 //$(elements).find('.resultSelector').prop('disabled', true).prop('checked', false);
441
442 var scope = this;
443 this.requestForm.on('submit', function(e){ //This will be registered for the next submit from the form.
444 e.preventDefault();
445
446 //Form checking
447 var dest = scope.requestForm.find('#requestDest .active');
448 if (dest.length !== 1){
449 $('#requestForm').append($('<div class="alert alert-warning">A destination is required!' + closeButton + '<div>'));
450 return;
451 }
452
453 $('#request').modal('hide')//Initial params are ok. We can close the form.
454 .remove('.alert') //Remove any alerts
455 .find('.active').removeClass('active'); //Disable the active destination
456
457 $(this).off(e); //Don't fire this again, the request must be regenerated
458
459 //Key setup
460 if (!keyAdded){
461 if (!scope.config.retrieval.demoKey || !scope.config.retrieval.demoKey.pub || !scope.config.retrieval.demoKey.priv){
462 scope.createAlert("This host was not configured to handle retrieval! See console for details.", 'alert-danger');
463 console.error("Missing/invalid key! This must be configured in the config on the server.", scope.config.demoKey);
464 return;
465 }
466
467 //FIXME base64 may or may not exist in other browsers. Need a new polyfill.
468 var pub = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.pub)); //MUST be a Buffer (Buffer != Uint8Array)
469 var priv = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.priv));
470
471 var identityStorage = new MemoryIdentityStorage();
472 var privateKeyStorage = new MemoryPrivateKeyStorage();
473 keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage),
474 new SelfVerifyPolicyManager(identityStorage));
475
476 var keyName = new Name("/retrieve/DSK-123");
477 certificateName = keyName.getSubName(0, keyName.size() - 1)
478 .append("KEY").append(keyName.get(-1))
479 .append("ID-CERT").append("0");
480
481 identityStorage.addKey(keyName, KeyType.RSA, new Blob(pub, false));
482 privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, pub, priv);
483
484 scope.face.setCommandSigningInfo(keyChain, certificateName);
485
486 keyAdded = true;
487
488 }
489
490 //Retrieval
491 var retrievePrefix = new Name("/catalog/ui/" + guid());
492
493 //Due to a lack of success callback in the register prefix function, we have to pretend we
494 //know it succeeded with an arbitrary timeout.
495 var sendTimer = setTimeout(function(){
496 var prefix = new Name(dest.text());
497 prefix.append(retrievePrefix);
498 var interest = new Interest(prefix);
499 interest.setInterestLifetimeMilliseconds(3000);
500 scope.face.expressInterest(interest,
501 function(interest, data){ //Success
502 console.log("Request for", prefix.toUri(), "succeeded.", interest, data);
503 }, function(interest){ //Failure
504 console.error("Failure to request", prefix.toUri(), interest);
505 scope.createAlert("Failed to request " + prefix.toUri() + ". This means that the retrieve failed! See console for more details.");
506 }
507 );
508 }, 10000); //Wait 10 seconds
509
510 scope.face.registerPrefix(retrievePrefix,
511 function(prefix, interest, face, interestFilterId, filter){ //On Interest
512 //This function will exist until the page exits but will likely only be used once.
513
514 var data = new Data(interest.getName());
515 var content = JSON.stringify(names);
516 data.setContent(content);
517 keyChain.sign(data, certificateName);
518
519 try {
520 face.putData(data);
521 console.log("Responded for", interest.getName().toUri(), data);
522 scope.createAlert("Data retrieval has initiated.", "alert-success");
523 } catch (e) {
524 console.error("Failed to respond to", interest.getName().toUri(), data);
525 scope.createAlert("Data retrieval failed.");
526 }
527
528 }, function(prefix){ //On fail
529 clearTimeout(sendTimer); //Cancel the earlier request timer
530 scope.createAlert("Failed to register the retrieval URI! See console for details.", "alert-danger");
531 console.error("Failed to register URI:", prefix.toUri(), prefix);
532
533 }
534 );
535
536 });
537 $('#request').modal(); //This forces the form to be the only option.
538
539 }
540 }();
541
542 Atmos.prototype.filterSetup = function() {
543 //Filter setup
544
545 var prefix = new Name(this.catalog).append("filters-initialization");
546
547 var scope = this;
548
549 this.getAll(prefix, function(data) { //Success
550 var raw = JSON.parse(data.replace(/[\n\0]/g, '')); //Remove null byte and parse
551
552 console.log("Filter categories:", raw);
553
554 $.each(raw, function(index, object){ //Unpack list of objects
555 $.each(object, function(category, searchOptions) { //Unpack category from object (We don't know what it is called)
556 //Create the category
557 var e = $('<li><a href="#">' + category.replace(/_/g, " ") + '</a><ul class="subnav nav nav-pills nav-stacked"></ul></li>');
558
559 var sub = e.find('ul.subnav');
560 $.each(searchOptions, function(index, name){
561 //Create the filter list inside the category
562 var item = $('<li><a href="#">' + name + '</a></li>');
563 sub.append(item);
564 item.click(function(){ //Click on the side menu filters
565 if (item.hasClass('active')){ //Does the filter already exist?
566 item.removeClass('active');
567 scope.filters.find(':contains(' + category + ':' + name + ')').remove();
568 } else { //Add a filter
569 item.addClass('active');
570 var filter = $('<span class="label label-default"></span>');
571 filter.text(category + ':' + name);
572
573 scope.filters.append(filter);
574
575 filter.click(function(){ //Click on a filter
576 filter.remove();
577 item.removeClass('active');
578 });
579 }
580
581 });
582 });
583
584 //Toggle the menus. (Only respond when the immediate tab is clicked.)
585 e.find('> a').click(function(){
586 scope.categories.find('.subnav').slideUp();
587 var t = $(this).siblings('.subnav');
588 if ( !t.is(':visible') ){ //If the sub menu is not visible
589 t.slideDown(function(){
590 t.triggerHandler('focus');
591 }); //Make it visible and look at it.
592 }
593 });
594
595 scope.categories.append(e);
596
597 });
598 });
599
600 }, function(interest){ //Timeout
601 scope.createAlert("Failed to initialize the filters!", "alert-danger");
602 console.error("Failed to initialize filters!", interest);
603 ga('send', 'event', 'error', 'filters');
604 });
605
606 }
607
608 /**
609 * This function retrieves all segments in order until it knows it has reached the last one.
610 * It then returns the final joined result.
611 */
612 Atmos.prototype.getAll = function(prefix, callback, timeout){
613
614 var scope = this;
615 var d = [];
616
617 var request = function(segment){
618
619 var name = new Name(prefix);
620 name.appendSegment(segment);
621
622 var interest = new Interest(name);
623 interest.setInterestLifetimeMilliseconds(1000);
624 interest.setMustBeFresh(true); //Is this needed?
625
626 scope.face.expressInterest(interest, handleData, timeout);
627
628 }
629
630
631 var handleData = function(interest, data){
632
633 d.push(data.getContent().toString());
634
635 if (interest.getName().get(-1).toSegment() == data.getMetaInfo().getFinalBlockId().toSegment()){
636 callback(d.join(""));
637 } else {
638 request(interest.getName().toSegment()++);
639 }
640
641 }
642
643 request(0);
644
645 }
646
647 Atmos.prototype.setupRequestForm = function(){
648 this.requestForm.find('#requestCancel').click(function(){
649 $('#request').unbind('submit') //Removes all event handlers.
650 .modal('hide'); //Hides the form.
651 });
652
653 var dests = $(this.config['retrieval']['destinations'].reduce(function(prev, current){
654 prev.push('<li><a href="#">');
655 prev.push(current);
656 prev.push("</a></li>");
657 return prev;
658 }, []).join(""));
659
660 this.requestForm.find('#requestDest').append(dests)
661 .on('click', 'a', function(e){
662 $('#requestDest .active').removeClass('active');
663 $(this).parent().addClass('active');
664 });
665
666 //This code will remain unused until users must use their own keys instead of the demo key.
667// var scope = this;
668
669// var warning = '<div class="alert alert-warning">' + closeButton + '<div>';
670
671// var handleFile = function(e){
672// var t = $(this);
673// if (e.target.files.length > 1){
674// var el = $(warning);
675// t.append(el.append("We are looking for a single file, we will try the first only!"));
676// } else if (e.target.files.length === 0) {
677// var el = $(warning.replace("alert-warning", "alert-danger"));
678// t.append(el.append("No file was supplied!"));
679// return;
680// }
681
682// var reader = new FileReader();
683// reader.onload = function(e){
684// var key;
685// try {
686// key = JSON.parse(e.target.result);
687// } catch (e) {
688// console.error("Could not parse the key! (", key, ")");
689// var el = $(warning.replace("alert-warning", "alert-danger"));
690// t.append(el.append("Failed to parse the key file, is it a valid json key?"));
691// }
692
693// if (!key.DEFAULT_RSA_PUBLIC_KEY_DER || !key.DEFAULT_RSA_PRIVATE_KEY_DER) {
694// console.warn("Invalid key", key);
695// var el = $(warning.replace("alert-warning", "alert-danger"));
696// t.append(el.append("Failed to parse the key file, it is missing required attributes."));
697// }
698
699
700// };
701
702// }
703
704// this.requestForm.find('#requestDrop').on('dragover', function(e){
705// e.dataTransfer.dropEffect = 'copy';
706// }).on('drop', handleFile);
707
708// this.requestForm.find('input[type=file]').change(handleFile);
709
710 }
711
712 return Atmos;
713
714})();