Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 1 | //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 | |
| 34 | var Atmos = (function(){ |
| 35 | "use strict"; |
| 36 | |
| 37 | var closeButton = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</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 Scott | 9445899 | 2015-09-24 14:16:28 -0700 | [diff] [blame] | 99 | scope.autoComplete(field, function(data){ |
| 100 | var list = data.next; |
| 101 | var last = data.lastComponent === true; |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 102 | callback(list.map(function(element){ |
Tyler Scott | 9445899 | 2015-09-24 14:16:28 -0700 | [diff] [blame] | 103 | return field + element + (last?"/":""); //Don't add trailing slash for last component. |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 104 | })); |
| 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 Scott | e8dac70 | 2015-10-13 14:33:25 -0600 | [diff] [blame] | 142 | 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 Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 149 | |
| 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 Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 170 | scope.autoComplete(path, function(data){ |
| 171 | var list = data.next; |
| 172 | var last = (data.lastComponent === true); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 173 | console.log("Autocomplete response", list); |
| 174 | callback(list.map(function(element){ |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 175 | return (path == "/"?"/":"") + element + (!last?"/":""); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 176 | })); |
| 177 | }) |
| 178 | }); |
| 179 | |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 180 | $('#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 Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 204 | this.setupRequestForm(); |
| 205 | |
| 206 | } |
| 207 | |
| 208 | Atmos.prototype.clearResults = function(){ |
| 209 | this.results = []; //Drop any old results. |
| 210 | this.retrievedSegments = 0; |
| 211 | this.resultCount = Infinity; |
| 212 | this.page = 0; |
| 213 | this.resultTable.empty(); |
| 214 | } |
| 215 | |
| 216 | Atmos.prototype.pathSearch = function(){ |
| 217 | var value = this.searchInput.val(); |
| 218 | |
| 219 | this.clearResults(); |
| 220 | |
| 221 | var scope = this; |
| 222 | |
| 223 | this.query(this.catalog, {"??": value}, |
| 224 | function(interest, data){ |
| 225 | console.log("Query response:", interest, data); |
| 226 | |
| 227 | scope.name = data.getContent().toString().replace(/[\n\0]/g,""); |
| 228 | |
| 229 | scope.getResults(0); |
| 230 | |
| 231 | }, |
| 232 | function(interest){ |
| 233 | console.warn("Request failed! Timeout", interest); |
| 234 | scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details."); |
| 235 | }); |
| 236 | |
| 237 | } |
| 238 | |
| 239 | Atmos.prototype.search = function(){ |
| 240 | |
| 241 | var filters = this.getFilters(); |
| 242 | |
| 243 | console.log("Search started!", this.searchInput.val(), filters); |
| 244 | |
| 245 | console.log("Initiating query"); |
| 246 | |
| 247 | this.clearResults(); |
| 248 | |
| 249 | var scope = this; |
| 250 | |
| 251 | this.query(this.catalog, filters, |
| 252 | function(interest, data){ //Response function |
| 253 | console.log("Query Response:", interest, data); |
| 254 | |
| 255 | scope.name = data.getContent().toString().replace(/[\n\0]/g,""); |
| 256 | |
| 257 | scope.getResults(0); |
| 258 | |
| 259 | }, function(interest){ //Timeout function |
Tyler Scott | d980a29 | 2015-10-13 15:16:34 -0600 | [diff] [blame] | 260 | console.warn("Request failed after 3 attempts!", interest); |
| 261 | scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details."); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 262 | }); |
| 263 | |
| 264 | } |
| 265 | |
| 266 | Atmos.prototype.autoComplete = function(field, callback){ |
| 267 | |
| 268 | var scope = this; |
| 269 | |
| 270 | this.query(this.catalog, {"?": field}, |
| 271 | function(interest, data){ |
| 272 | |
| 273 | var name = new Name(data.getContent().toString().replace(/[\n\0]/g,"")); |
| 274 | |
| 275 | var interest = new Interest(name); |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 276 | interest.setInterestLifetimeMilliseconds(1500); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 277 | interest.setMustBeFresh(true); |
| 278 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 279 | var count = 3; |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 280 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 281 | var run = function(){ |
| 282 | |
| 283 | if (--count === 0){ |
| 284 | console.warn("Interest timed out!", interest); |
| 285 | scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details."); |
| 286 | return; |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 287 | } |
| 288 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 289 | scope.face.expressInterest(interest, |
| 290 | function(interest, data){ |
| 291 | |
| 292 | if (data.getContent().length !== 0){ |
| 293 | callback(JSON.parse(data.getContent().toString().replace(/[\n\0]/g, ""))); |
| 294 | } else { |
| 295 | callback([]); |
| 296 | } |
| 297 | |
| 298 | }, run); |
| 299 | } |
| 300 | |
| 301 | run(); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 302 | |
| 303 | }, function(interest){ |
| 304 | console.error("Request failed! Timeout", interest); |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 305 | scope.createAlert("Request failed after 3 attempts. \"" + interest.getName().toUri() + "\" See console for details."); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 306 | }); |
| 307 | |
| 308 | } |
| 309 | |
| 310 | Atmos.prototype.showResults = function(resultIndex) { |
| 311 | |
| 312 | var results = this.results.slice(this.resultsPerPage * resultIndex, this.resultsPerPage * (resultIndex + 1)); |
| 313 | |
| 314 | var resultDOM = $( |
| 315 | results.reduce(function(prev, current){ |
| 316 | prev.push('<tr><td><input class="resultSelector" type="checkbox"></td><td>'); |
| 317 | prev.push(current); |
| 318 | prev.push('</td></tr>'); |
| 319 | return prev; |
| 320 | }, ['<tr><th><input id="resultSelectAll" type="checkbox" title="Select All"> Select</th><th>Name</th></tr>']).join('') |
| 321 | ); |
| 322 | |
| 323 | resultDOM.find('#resultSelectAll').click(function(){ |
| 324 | if ($(this).is(':checked')){ |
| 325 | resultDOM.find('.resultSelector:not([disabled])').prop('checked', true); |
| 326 | } else { |
| 327 | resultDOM.find('.resultSelector:not([disabled])').prop('checked', false); |
| 328 | } |
| 329 | }); |
| 330 | |
| 331 | this.resultTable.hide().empty().append(resultDOM).slideDown('slow'); |
| 332 | |
| 333 | this.resultMenu.find('.pageNumber').text(resultIndex + 1); |
| 334 | this.resultMenu.find('.pageLength').text(this.resultsPerPage * resultIndex + results.length); |
| 335 | |
| 336 | if (this.resultsPerPage * (resultIndex + 1) >= this.resultCount) { |
| 337 | this.resultMenu.find('.next').addClass('disabled'); |
| 338 | } else if (resultIndex === 0){ |
| 339 | this.resultMenu.find('.next').removeClass('disabled'); |
| 340 | } |
| 341 | |
| 342 | if (resultIndex === 0){ |
| 343 | this.resultMenu.find('.previous').addClass('disabled'); |
| 344 | } else if (resultIndex === 1) { |
| 345 | this.resultMenu.find('.previous').removeClass('disabled'); |
| 346 | } |
| 347 | |
| 348 | } |
| 349 | |
| 350 | Atmos.prototype.getResults = function(index){ |
| 351 | |
| 352 | if ($('#results').hasClass('hidden')){ |
| 353 | $('#results').removeClass('hidden').slideDown(); |
| 354 | } |
| 355 | |
Tyler Scott | e8dac70 | 2015-10-13 14:33:25 -0600 | [diff] [blame] | 356 | $.scrollTo("#results", 500, {interrupt: true}); |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 357 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 358 | if ((this.results.length === this.resultCount) || (this.resultsPerPage * (index + 1) < this.results.length)){ |
| 359 | //console.log("We already have index", index); |
| 360 | this.page = index; |
| 361 | this.showResults(index); |
| 362 | return; |
| 363 | } |
| 364 | |
| 365 | if (this.name === null) { |
| 366 | console.error("This shouldn't be reached! We are getting results before a search has occured!"); |
| 367 | throw new Error("Illegal State"); |
| 368 | } |
| 369 | |
| 370 | var first = new Name(this.name).appendSegment(this.retrievedSegments++); |
| 371 | |
| 372 | console.log("Requesting data index: (", this.retrievedSegments - 1, ") at ", first.toUri()); |
| 373 | |
| 374 | var scope = this; |
| 375 | |
| 376 | var interest = new Interest(first) |
| 377 | interest.setInterestLifetimeMilliseconds(5000); |
| 378 | interest.setMustBeFresh(true); |
| 379 | |
| 380 | this.face.expressInterest(interest, |
| 381 | function(interest, data){ //Response |
| 382 | |
| 383 | if (data.getContent().length === 0){ |
| 384 | scope.resultMenu.find('.totalResults').text(0); |
| 385 | scope.resultMenu.find('.pageNumber').text(0); |
| 386 | scope.resultMenu.find('.pageLength').text(0); |
| 387 | console.log("Empty response."); |
| 388 | return; |
| 389 | } |
| 390 | |
| 391 | var content = JSON.parse(data.getContent().toString().replace(/[\n\0]/g,"")); |
| 392 | |
| 393 | if (!content.results){ |
| 394 | scope.resultMenu.find('.totalResults').text(0); |
| 395 | scope.resultMenu.find('.pageNumber').text(0); |
| 396 | scope.resultMenu.find('.pageLength').text(0); |
| 397 | console.log("No results were found!"); |
| 398 | return; |
| 399 | } |
| 400 | |
| 401 | scope.results = scope.results.concat(content.results); |
| 402 | |
| 403 | scope.resultCount = content.resultCount; |
| 404 | |
| 405 | scope.resultMenu.find('.totalResults').text(scope.resultCount); |
| 406 | |
| 407 | scope.page = index; |
| 408 | |
| 409 | scope.getResults(index); //Keep calling this until we have enough data. |
| 410 | |
| 411 | }, |
| 412 | function(interest){ //Timeout |
| 413 | console.error("Failed to retrieve results: timeout", interest); |
| 414 | scope.createAlert("Request timed out. \"" + interest.getName().toUri() + "\" See console for details."); |
| 415 | } |
| 416 | ); |
| 417 | |
| 418 | } |
| 419 | |
| 420 | Atmos.prototype.query = function(prefix, parameters, callback, timeout) { |
| 421 | |
| 422 | var queryPrefix = new Name(prefix); |
| 423 | queryPrefix.append("query"); |
| 424 | |
| 425 | var jsonString = JSON.stringify(parameters); |
| 426 | queryPrefix.append(jsonString); |
| 427 | |
| 428 | var queryInterest = new Interest(queryPrefix); |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 429 | queryInterest.setInterestLifetimeMilliseconds(1500); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 430 | queryInterest.setMustBeFresh(true); |
| 431 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 432 | var face = this.face; |
| 433 | var retry = 3; |
| 434 | var run = function(interest){ |
| 435 | if (--retry === 0){ |
| 436 | timeout(interest); |
| 437 | } else { |
| 438 | face.expressInterest(queryInterest, callback, run); |
| 439 | } |
| 440 | } |
| 441 | run(); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 442 | |
| 443 | } |
| 444 | |
| 445 | /** |
| 446 | * This function returns a map of all the categories active filters. |
| 447 | * @return {Object<string, string>} |
| 448 | */ |
| 449 | Atmos.prototype.getFilters = function(){ |
| 450 | var filters = this.filters.children().toArray().reduce(function(prev, current){ |
| 451 | var data = $(current).text().split(/:/); |
| 452 | prev[data[0]] = data[1]; |
| 453 | return prev; |
| 454 | }, {}); //Collect a map<category, filter>. |
| 455 | //TODO Make the return value map<category, Array<filter>> |
| 456 | return filters; |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * Creates a closable alert for the user. |
| 461 | * |
| 462 | * @param {string} message |
| 463 | * @param {string} type - Override the alert type. |
| 464 | */ |
| 465 | Atmos.prototype.createAlert = function(message, type) { |
| 466 | |
| 467 | var alert = $('<div class="alert"><div>'); |
| 468 | alert.addClass(type?type:'alert-info'); |
| 469 | alert.text(message); |
| 470 | alert.append(closeButton); |
| 471 | |
| 472 | this.alerts.append(alert); |
| 473 | } |
| 474 | |
| 475 | /** |
| 476 | * Requests all of the names represented by the buttons in the elements list. |
| 477 | * |
| 478 | * @param elements {Array<jQuery>} A list of the table row elements |
| 479 | */ |
| 480 | Atmos.prototype.request = function(){ |
| 481 | |
| 482 | //Pseudo globals. |
| 483 | var keyChain; |
| 484 | var certificateName; |
| 485 | var keyAdded = false; |
| 486 | |
| 487 | return function(elements){ |
| 488 | |
| 489 | var names = []; |
| 490 | var destination = $('#requestDest .active').text(); |
| 491 | $(elements).find('>*:nth-child(2)').each(function(){ |
| 492 | var name = $(this).text(); |
| 493 | names.push(name); |
| 494 | });//.append('<span class="badge">Requested!</span>') |
| 495 | //Disabling the checkbox doesn't make sense anymore with the ability to request to multiple destinations. |
| 496 | //$(elements).find('.resultSelector').prop('disabled', true).prop('checked', false); |
| 497 | |
| 498 | var scope = this; |
| 499 | this.requestForm.on('submit', function(e){ //This will be registered for the next submit from the form. |
| 500 | e.preventDefault(); |
| 501 | |
| 502 | //Form checking |
| 503 | var dest = scope.requestForm.find('#requestDest .active'); |
| 504 | if (dest.length !== 1){ |
| 505 | $('#requestForm').append($('<div class="alert alert-warning">A destination is required!' + closeButton + '<div>')); |
| 506 | return; |
| 507 | } |
| 508 | |
| 509 | $('#request').modal('hide')//Initial params are ok. We can close the form. |
| 510 | .remove('.alert') //Remove any alerts |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 511 | |
| 512 | scope.cleanRequestForm(); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 513 | |
| 514 | $(this).off(e); //Don't fire this again, the request must be regenerated |
| 515 | |
| 516 | //Key setup |
| 517 | if (!keyAdded){ |
| 518 | if (!scope.config.retrieval.demoKey || !scope.config.retrieval.demoKey.pub || !scope.config.retrieval.demoKey.priv){ |
| 519 | scope.createAlert("This host was not configured to handle retrieval! See console for details.", 'alert-danger'); |
| 520 | console.error("Missing/invalid key! This must be configured in the config on the server.", scope.config.demoKey); |
| 521 | return; |
| 522 | } |
| 523 | |
| 524 | //FIXME base64 may or may not exist in other browsers. Need a new polyfill. |
| 525 | var pub = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.pub)); //MUST be a Buffer (Buffer != Uint8Array) |
| 526 | var priv = new Buffer(base64.toByteArray(scope.config.retrieval.demoKey.priv)); |
| 527 | |
| 528 | var identityStorage = new MemoryIdentityStorage(); |
| 529 | var privateKeyStorage = new MemoryPrivateKeyStorage(); |
| 530 | keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage), |
| 531 | new SelfVerifyPolicyManager(identityStorage)); |
| 532 | |
| 533 | var keyName = new Name("/retrieve/DSK-123"); |
| 534 | certificateName = keyName.getSubName(0, keyName.size() - 1) |
| 535 | .append("KEY").append(keyName.get(-1)) |
| 536 | .append("ID-CERT").append("0"); |
| 537 | |
| 538 | identityStorage.addKey(keyName, KeyType.RSA, new Blob(pub, false)); |
| 539 | privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA, pub, priv); |
| 540 | |
| 541 | scope.face.setCommandSigningInfo(keyChain, certificateName); |
| 542 | |
| 543 | keyAdded = true; |
| 544 | |
| 545 | } |
| 546 | |
| 547 | //Retrieval |
| 548 | var retrievePrefix = new Name("/catalog/ui/" + guid()); |
| 549 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 550 | scope.face.registerPrefix(retrievePrefix, |
| 551 | function(prefix, interest, face, interestFilterId, filter){ //On Interest |
| 552 | //This function will exist until the page exits but will likely only be used once. |
| 553 | |
| 554 | var data = new Data(interest.getName()); |
| 555 | var content = JSON.stringify(names); |
| 556 | data.setContent(content); |
| 557 | keyChain.sign(data, certificateName); |
| 558 | |
| 559 | try { |
| 560 | face.putData(data); |
| 561 | console.log("Responded for", interest.getName().toUri(), data); |
Tyler Scott | d980a29 | 2015-10-13 15:16:34 -0600 | [diff] [blame] | 562 | scope.createAlert("Data retrieval has initiated.", "alert-success"); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 563 | } catch (e) { |
| 564 | console.error("Failed to respond to", interest.getName().toUri(), data); |
| 565 | scope.createAlert("Data retrieval failed."); |
| 566 | } |
| 567 | |
| 568 | }, function(prefix){ //On fail |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 569 | scope.createAlert("Failed to register the retrieval URI! See console for details.", "alert-danger"); |
| 570 | console.error("Failed to register URI:", prefix.toUri(), prefix); |
| 571 | |
Tyler Scott | d980a29 | 2015-10-13 15:16:34 -0600 | [diff] [blame] | 572 | }, function(prefix, registeredPrefixId){ //On success |
| 573 | var name = new Name(dest.text()); |
| 574 | name.append(prefix); |
| 575 | var interest = new Interest(name); |
| 576 | interest.setInterestLifetimeMilliseconds(1500); |
| 577 | var count = 3; |
| 578 | var run = function(i2){ |
| 579 | |
| 580 | if (--count === 0) { |
| 581 | console.error("Request for", name.toUri(), "timed out (3 times).", i2); |
| 582 | scope.createAlert("Request for " + name.toUri() + " timed out after 3 attempts. This means that the retrieve failed! See console for more details."); |
| 583 | return; |
| 584 | } |
| 585 | |
| 586 | scope.face.expressInterest(interest, |
| 587 | function(interest, data){ //Success |
| 588 | console.log("Request for", name.toUri(), "succeeded.", interest, data); |
| 589 | }, |
| 590 | run |
| 591 | ); |
| 592 | } |
| 593 | run(); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 594 | } |
| 595 | ); |
| 596 | |
| 597 | }); |
| 598 | $('#request').modal(); //This forces the form to be the only option. |
| 599 | |
| 600 | } |
| 601 | }(); |
| 602 | |
| 603 | Atmos.prototype.filterSetup = function() { |
| 604 | //Filter setup |
| 605 | |
| 606 | var prefix = new Name(this.catalog).append("filters-initialization"); |
| 607 | |
| 608 | var scope = this; |
| 609 | |
| 610 | this.getAll(prefix, function(data) { //Success |
| 611 | var raw = JSON.parse(data.replace(/[\n\0]/g, '')); //Remove null byte and parse |
| 612 | |
| 613 | console.log("Filter categories:", raw); |
| 614 | |
| 615 | $.each(raw, function(index, object){ //Unpack list of objects |
| 616 | $.each(object, function(category, searchOptions) { //Unpack category from object (We don't know what it is called) |
| 617 | //Create the category |
| 618 | var e = $('<li><a href="#">' + category.replace(/_/g, " ") + '</a><ul class="subnav nav nav-pills nav-stacked"></ul></li>'); |
| 619 | |
| 620 | var sub = e.find('ul.subnav'); |
| 621 | $.each(searchOptions, function(index, name){ |
| 622 | //Create the filter list inside the category |
| 623 | var item = $('<li><a href="#">' + name + '</a></li>'); |
| 624 | sub.append(item); |
| 625 | item.click(function(){ //Click on the side menu filters |
| 626 | if (item.hasClass('active')){ //Does the filter already exist? |
| 627 | item.removeClass('active'); |
| 628 | scope.filters.find(':contains(' + category + ':' + name + ')').remove(); |
| 629 | } else { //Add a filter |
| 630 | item.addClass('active'); |
| 631 | var filter = $('<span class="label label-default"></span>'); |
| 632 | filter.text(category + ':' + name); |
| 633 | |
| 634 | scope.filters.append(filter); |
| 635 | |
| 636 | filter.click(function(){ //Click on a filter |
| 637 | filter.remove(); |
| 638 | item.removeClass('active'); |
| 639 | }); |
| 640 | } |
| 641 | |
| 642 | }); |
| 643 | }); |
| 644 | |
| 645 | //Toggle the menus. (Only respond when the immediate tab is clicked.) |
| 646 | e.find('> a').click(function(){ |
| 647 | scope.categories.find('.subnav').slideUp(); |
| 648 | var t = $(this).siblings('.subnav'); |
| 649 | if ( !t.is(':visible') ){ //If the sub menu is not visible |
| 650 | t.slideDown(function(){ |
| 651 | t.triggerHandler('focus'); |
| 652 | }); //Make it visible and look at it. |
| 653 | } |
| 654 | }); |
| 655 | |
| 656 | scope.categories.append(e); |
| 657 | |
| 658 | }); |
| 659 | }); |
| 660 | |
| 661 | }, function(interest){ //Timeout |
| 662 | scope.createAlert("Failed to initialize the filters!", "alert-danger"); |
| 663 | console.error("Failed to initialize filters!", interest); |
| 664 | ga('send', 'event', 'error', 'filters'); |
| 665 | }); |
| 666 | |
| 667 | } |
| 668 | |
| 669 | /** |
| 670 | * This function retrieves all segments in order until it knows it has reached the last one. |
| 671 | * It then returns the final joined result. |
| 672 | */ |
| 673 | Atmos.prototype.getAll = function(prefix, callback, timeout){ |
| 674 | |
| 675 | var scope = this; |
| 676 | var d = []; |
| 677 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 678 | var count = 3; |
| 679 | var retry = function(interest){ |
| 680 | if (count === 0){ |
| 681 | timeout(interest); |
| 682 | } else { |
| 683 | count--; |
| 684 | request(interest.getName().get(-1).toSegment()); |
| 685 | } |
| 686 | } |
| 687 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 688 | var request = function(segment){ |
| 689 | |
| 690 | var name = new Name(prefix); |
| 691 | name.appendSegment(segment); |
| 692 | |
| 693 | var interest = new Interest(name); |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 694 | interest.setInterestLifetimeMilliseconds(1500); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 695 | interest.setMustBeFresh(true); //Is this needed? |
| 696 | |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 697 | scope.face.expressInterest(interest, handleData, retry); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 698 | |
| 699 | } |
| 700 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 701 | var handleData = function(interest, data){ |
| 702 | |
| 703 | d.push(data.getContent().toString()); |
| 704 | |
| 705 | if (interest.getName().get(-1).toSegment() == data.getMetaInfo().getFinalBlockId().toSegment()){ |
| 706 | callback(d.join("")); |
| 707 | } else { |
Tyler Scott | 8724e42 | 2015-10-13 17:59:07 -0600 | [diff] [blame^] | 708 | request(interest.getName().get(-1).toSegment() + 1); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 709 | } |
| 710 | |
| 711 | } |
| 712 | |
| 713 | request(0); |
| 714 | |
| 715 | } |
| 716 | |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 717 | Atmos.prototype.cleanRequestForm = function(){ |
| 718 | $('#requestDest').prev().removeClass('btn-success').addClass('btn-default'); |
| 719 | $('#requestDropText').text('Destination'); |
| 720 | $('#requestDest .active').removeClass('active'); |
| 721 | } |
| 722 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 723 | Atmos.prototype.setupRequestForm = function(){ |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 724 | |
| 725 | var scope = this; |
| 726 | |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 727 | this.requestForm.find('#requestCancel').click(function(){ |
| 728 | $('#request').unbind('submit') //Removes all event handlers. |
| 729 | .modal('hide'); //Hides the form. |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 730 | scope.cleanRequestForm(); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 731 | }); |
| 732 | |
| 733 | var dests = $(this.config['retrieval']['destinations'].reduce(function(prev, current){ |
| 734 | prev.push('<li><a href="#">'); |
| 735 | prev.push(current); |
| 736 | prev.push("</a></li>"); |
| 737 | return prev; |
| 738 | }, []).join("")); |
| 739 | |
| 740 | this.requestForm.find('#requestDest').append(dests) |
| 741 | .on('click', 'a', function(e){ |
| 742 | $('#requestDest .active').removeClass('active'); |
Tyler Scott | b59e6de | 2015-09-18 14:46:30 -0600 | [diff] [blame] | 743 | var t = $(this); |
| 744 | t.parent().addClass('active'); |
| 745 | $('#requestDropText').text(t.text()); |
| 746 | $('#requestDest').prev().removeClass('btn-default').addClass('btn-success'); |
Tyler Scott | cdfcde8 | 2015-09-14 16:13:29 -0600 | [diff] [blame] | 747 | }); |
| 748 | |
| 749 | //This code will remain unused until users must use their own keys instead of the demo key. |
| 750 | // var scope = this; |
| 751 | |
| 752 | // var warning = '<div class="alert alert-warning">' + closeButton + '<div>'; |
| 753 | |
| 754 | // var handleFile = function(e){ |
| 755 | // var t = $(this); |
| 756 | // if (e.target.files.length > 1){ |
| 757 | // var el = $(warning); |
| 758 | // t.append(el.append("We are looking for a single file, we will try the first only!")); |
| 759 | // } else if (e.target.files.length === 0) { |
| 760 | // var el = $(warning.replace("alert-warning", "alert-danger")); |
| 761 | // t.append(el.append("No file was supplied!")); |
| 762 | // return; |
| 763 | // } |
| 764 | |
| 765 | // var reader = new FileReader(); |
| 766 | // reader.onload = function(e){ |
| 767 | // var key; |
| 768 | // try { |
| 769 | // key = JSON.parse(e.target.result); |
| 770 | // } catch (e) { |
| 771 | // console.error("Could not parse the key! (", key, ")"); |
| 772 | // var el = $(warning.replace("alert-warning", "alert-danger")); |
| 773 | // t.append(el.append("Failed to parse the key file, is it a valid json key?")); |
| 774 | // } |
| 775 | |
| 776 | // if (!key.DEFAULT_RSA_PUBLIC_KEY_DER || !key.DEFAULT_RSA_PRIVATE_KEY_DER) { |
| 777 | // console.warn("Invalid key", key); |
| 778 | // var el = $(warning.replace("alert-warning", "alert-danger")); |
| 779 | // t.append(el.append("Failed to parse the key file, it is missing required attributes.")); |
| 780 | // } |
| 781 | |
| 782 | |
| 783 | // }; |
| 784 | |
| 785 | // } |
| 786 | |
| 787 | // this.requestForm.find('#requestDrop').on('dragover', function(e){ |
| 788 | // e.dataTransfer.dropEffect = 'copy'; |
| 789 | // }).on('drop', handleFile); |
| 790 | |
| 791 | // this.requestForm.find('input[type=file]').change(handleFile); |
| 792 | |
| 793 | } |
| 794 | |
| 795 | return Atmos; |
| 796 | |
| 797 | })(); |