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