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