gui/js: Update to latest NDN.JS

Change-Id: Ica3a4e20fe36ad3c4dedeee729dcc899684d6b77
diff --git a/gui/html/chronoshare.js b/gui/html/chronoshare.js
index 38743ad..916b092 100644
--- a/gui/html/chronoshare.js
+++ b/gui/html/chronoshare.js
@@ -1,10 +1,22 @@
+info_actions_collection = [];
+info_actions_counter = 0;
+info_files_collection = [];
+info_files_counter = 0;
+lastSegmentRequested = -1;
+file_data = "";
+file_segments = 0;
+file_callback = file_onData;
+restore_callback = file_onData;
+
+face = null;
+
 $.Class("ChronoShare", {}, {
   init: function(username, foldername) {
     $("#folder-name").text(foldername);
     $("#user-name").text(username);
 
     this.username = new Name(username);
-    this.files = new Name("/localhost")
+    this.files = new Name("/localhop")
                    .add(this.username)
                    .add("chronoshare")
                    .add(foldername)
@@ -12,14 +24,14 @@
                    .add("files")
                    .add("folder");
 
-    this.actions = new Name("/localhost")
+    this.actions = new Name("/localhop")
                      .add(this.username)
                      .add("chronoshare")
                      .add(foldername)
                      .add("info")
                      .add("actions");
 
-    this.restore = new Name("/localhost")
+    this.restore = new Name("/localhop")
                      .add(this.username)
                      .add("chronoshare")
                      .add(foldername)
@@ -27,8 +39,15 @@
                      .add("restore")
                      .add("file");
 
-    this.ndn = new NDN({host: "127.0.0.1"});
-    this.ndn.verify = false; // disable content verification, works WAAAAY faster
+
+    $("#json").empty();
+
+    if (face == null) {
+      var host = "localhost";
+      // Connect to the forwarder with a WebSocket.
+      face = new Face({host: host});
+      console.log("Init Face OK!");
+    }
   },
 
   run: function() {
@@ -38,30 +57,20 @@
 
     cmd = {};
     if (PAGE == "fileList") {
+      info_files_collection = [];
+      info_files_counter = 0;
       cmd = this.info_files(PARAMS.item);
     }
     else if (PAGE == "folderHistory") {
+      info_actions_collection = [];
+      info_actions_counter = 0;
       cmd = this.info_actions("folder", PARAMS.item);
     }
     else if (PAGE == "fileHistory") {
+      info_actions_collection = [];
+      info_actions_counter = 0;
       cmd = this.info_actions("file", PARAMS.item);
     }
-
-    if (cmd.request && cmd.callback) {
-      console.log(cmd.request.to_uri());
-      this.ndn.expressInterest(cmd.request, cmd.callback);
-    }
-    else {
-      $("#loader").fadeOut(500); // ("hidden");
-      $("#content").empty();
-      if (cmd.error) {
-        $("#error").html(cmd.error);
-      }
-      else {
-        $("#error").html("Unknown error with " + PAGE);
-      }
-      $("#error").removeClass("hidden");
-    }
   },
 
   info_files: function(folder) {
@@ -69,7 +78,8 @@
                 .add(this.files)
                 ./*add (folder_in_question).*/ addSegment(
                   PARAMS.offset ? PARAMS.offset : 0);
-    return {request: request, callback: new FilesClosure(this)};
+    face.expressInterest(request, info_files_onData, on_Timeout);
+    console.log("Express OK: " + request.to_uri());
   },
 
   info_actions: function(type /*"file" or "folder"*/,
@@ -83,7 +93,9 @@
       request.add(fileOrFolder);
     }
     request.addSegment(PARAMS.offset ? PARAMS.offset : 0);
-    return {request: request, callback: new HistoryClosure(this)};
+
+    face.expressInterest(request, info_actions_onData, on_Timeout);
+    console.log("Express OK: " + request.to_uri());
   },
 
   cmd_restore_file:
@@ -92,8 +104,9 @@
       request =
         new Name().add(this.restore).add(filename).addSegment(version).add(hash);
       console.log(request.to_uri());
-      this.ndn.expressInterest(request,
-                               new CmdRestoreFileClosure(this, callback));
+
+      restore_callback = callback;
+      face.expressInterest(request, restore_onData, on_Timeout);
     },
 
   get_file:
@@ -101,10 +114,144 @@
              callback /*function (bool <- data received, data <- returned data)*/) {
       baseName = new Name(modifiedBy).add("chronoshare").add("file").add(hash);
 
-      new FileGetter(this.ndn, baseName, segments, callback).start();
-    }
+      lastSegmentRequested = 0;
+      file_data = "";
+      file_segments = segments;
+      file_callback = callback;
+
+      request = new Name().add(baseName).addSegment(lastSegmentRequested);
+      console.log("Express get_file Name: ", request.to_uri());
+      console.log("Total Segments: ", file_segments);
+      face.expressInterest(request, file_onData, on_Timeout);
+
+    },
+
 });
 
+function restore_onData(interest, upcallInfo)
+{
+  convertedData = upcallInfo.getContent().buf().toString('binary');
+  console.log("restore_onData");
+  console.log(convertedData);
+  restore_callback(true, convertedData);
+};
+
+function file_onData(interest, upcallInfo)
+{
+  convertedData = upcallInfo.getContent().buf().toString('binary');
+  console.log("file_onData");
+  console.log(convertedData);
+  file_data += convertedData;
+  if (lastSegmentRequested + 1 == file_segments) {
+    file_callback(true, file_data);
+  }
+  else {
+    lastSegmentRequested++;
+    nextSegment =
+      interest.getName().getPrefix(-1).addSegment(lastSegmentRequested);
+    face.expressInterest(nextSegment, file_onData, on_Timeout);
+  }
+};
+
+function info_actions_onData(interest, upcallInfo)
+{
+  convertedData = upcallInfo.getContent().buf().toString(
+    'binary'); //DataUtils.toString (upcallInfo.contentObject.content);
+  console.log(convertedData);
+  moreName = "more";
+  collectionName = "actions";
+
+  if (PARAMS.debug) {
+    $("#json").append($(document.createTextNode(convertedData)));
+    $("#json").removeClass("hidden");
+  }
+
+  console.log("Prefix");
+  console.log(interest.getName().getPrefix(-1).to_uri());
+
+  data = JSON.parse(convertedData);
+  console.log(data);
+  console.log(data[collectionName]);
+  var collection = data[collectionName];
+  info_actions_collection = info_actions_collection.concat(data[collectionName]);
+
+  console.log(info_actions_collection);
+
+  if (data[moreName] !== undefined) {
+    nextSegment = interest.getName().getPrefix(-1).addSegment(data[moreName]);
+    info_actions_counter++;
+
+    if (info_actions_counter < 5) {
+      console.log("MORE: " + nextSegment.to_uri());
+      face.expressInterest(nextSegment, info_actions_onData, on_Timeout);
+    }
+    else {
+      $("#loader").fadeOut(500); // ("hidden");
+      var HD = new HistoryDisplay(CHRONOSHARE);
+      HD.onData(info_actions_collection, data[moreName]);
+    }
+  }
+  else {
+    $("#loader").fadeOut(500); // ("hidden");
+    console.log("I'm triggered more undefined~");
+    var HD = new HistoryDisplay(CHRONOSHARE);
+    HD.onData(info_actions_collection, undefined);
+  }
+};
+
+function info_files_onData(interest, upcallInfo)
+{
+  convertedData = upcallInfo.getContent().buf().toString(
+    'binary'); //DataUtils.toString (upcallInfo.contentObject.content);
+  console.log(convertedData);
+  moreName = "more";
+  collectionName = "files";
+
+  if (PARAMS.debug) {
+    $("#json").append($(document.createTextNode(convertedData)));
+    $("#json").removeClass("hidden");
+  }
+
+  console.log("Prefix");
+  console.log(interest.getName().getPrefix(-1).to_uri());
+
+  data = JSON.parse(convertedData);
+  console.log(data);
+  console.log(data[collectionName]);
+  var collection = data[collectionName];
+  info_files_collection = info_files_collection.concat(data[collectionName]);
+
+  console.log(info_files_collection);
+
+  if (data[moreName] !== undefined) {
+    nextSegment = interest.getName().getPrefix(-1).addSegment(data[moreName]);
+    info_files_counter++;
+
+    if (info_files_counter < 5) {
+      console.log("MORE: " + nextSegment.to_uri());
+      face.expressInterest(nextSegment, info_files_onData, on_Timeout);
+    }
+    else {
+      $("#loader").fadeOut(500); // ("hidden");
+      var HD = new FilesDisplay(CHRONOSHARE);
+      HD.onData(info_files_collection, data[moreName]);
+    }
+  }
+  else {
+    $("#loader").fadeOut(500); // ("hidden");
+    console.log("I'm triggered more undefined~");
+    var HD = new FilesDisplay(CHRONOSHARE);
+    HD.onData(info_files_collection, undefined);
+  }
+};
+
+
+function on_Timeout(interest)
+{
+  $("#error").html("Ha Ha Interest time out");
+  $("#error").removeClass("hidden");
+}
+
 $.Class("CmdRestoreFileClosure", {}, {
   init: function(chronoshare, callback) {
     this.chronoshare = chronoshare;
@@ -112,12 +259,12 @@
   },
   upcall: function(kind, upcallInfo) {
     if (kind == Closure.UPCALL_CONTENT ||
-        kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
+        kind == Closure.UPCALL_CONTENT_UNVERIFIED) { //disable content verification
       convertedData = DataUtils.toString(upcallInfo.contentObject.content);
       this.callback(true, convertedData);
     }
     else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
-      this.callback(false, "Interest timed out");
+      this.callback(false, "Interest timed out 99");
     }
     else {
       this.callback(false, "Unknown error happened");
@@ -125,230 +272,9 @@
   }
 });
 
-$.Class("FileGetter", {}, {
-  init: function(ndn, baseName, segments, callback) {
-    this.ndn = ndn;
-    this.callback = callback;
-    this.baseName = baseName;
-    this.segments = segments;
-    this.lastSegmentRequested = -1;
 
-    this.data = "";
-  },
-
-  start: function() {
-    this.lastSegmentRequested++;
-
-    request =
-      new Name().add(this.baseName).addSegment(this.lastSegmentRequested);
-
-    console.log(request.to_uri());
-    this.ndn.expressInterest(request, this);
-  },
-
-  upcall: function(kind, upcallInfo) {
-    if (kind == Closure.UPCALL_CONTENT ||
-        kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
-      convertedData = DataUtils.toString(upcallInfo.contentObject.content);
-
-      this.data += convertedData;
-
-      if (this.lastSegmentRequested + 1 == this.segments) {
-        this.callback(true, this.data);
-      }
-      else {
-        this.start();
-      }
-    }
-    else {
-      this.callback(false, "Interest timed out");
-    }
-  }
-});
-
-$.Class("RestPipelineClosure", {}, {
-  init: function(collectionName, moreName) {
-    this.collectionName = collectionName;
-    this.moreName = moreName;
-    $("#json").empty();
-
-    this.collection = [];
-    this.counter = 0;
-  },
-
-  upcall: function(kind, upcallInfo) {
-    if (kind == Closure.UPCALL_CONTENT ||
-        kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
-
-      convertedData = DataUtils.toString(upcallInfo.contentObject.content);
-      if (PARAMS.debug) {
-        $("#json").append($(document.createTextNode(convertedData)));
-        $("#json").removeClass("hidden");
-      }
-      data = JSON.parse(convertedData);
-
-      this.collection = this.collection.concat(data[this.collectionName]);
-      if (data[this.moreName] !== undefined) {
-        nextSegment =
-          upcallInfo.interest.name.cut(1).addSegment(data[this.moreName]);
-        this.counter++;
-
-        if (this.counter < 5) {
-          console.log("MORE: " + nextSegment.to_uri());
-          CHRONOSHARE.ndn.expressInterest(nextSegment, this);
-        }
-        else {
-          $("#loader").fadeOut(500); // ("hidden");
-          this.onData(this.collection, data[this.moreName]);
-        }
-      }
-      else {
-        $("#loader").fadeOut(500); // ("hidden");
-        this.onData(this.collection, undefined);
-      }
-    }
-    else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
-      $("#loader").fadeOut(500); // ("hidden");
-      this.onTimeout(upcallInfo.interest);
-    }
-    else {
-      $("#loader").fadeOut(500); // ("hidden");
-      this.onUnknownError(upcallInfo.interest);
-    }
-
-    return Closure.RESULT_OK; // make sure we never re-express the interest
-  },
-
-  onData: function(data, more) {},
-
-  onTimeout: function() {
-    $("#error").html("Interest timed out");
-    $("#error").removeClass("hidden");
-  },
-
-  onUnknownError: function() {
-    $("#error").html("Unknown error happened");
-    $("#error").removeClass("hidden");
-  }
-});
-
-// $.Class ("FilesClosure", {}, {
-RestPipelineClosure("FilesClosure", {}, {
+$.Class("HistoryDisplay", {}, {
   init: function(chronoshare) {
-    this._super("files", "more");
-    this.chronoshare = chronoshare;
-  },
-
-  onData: function(data, more) {
-    tbody = $("<tbody />", {"id": "file-list-files"});
-
-    /// @todo Eventually set title for other pages
-    $("title").text("ChronoShare - List of files" +
-                    (PARAMS.item ? " - " + PARAMS.item : ""));
-
-    // error handling?
-    newcontent =
-      $("<div />", {"id": "content"})
-        .append($("<h2 />").append($(document.createTextNode("List of files ")),
-                                   $("<green />").text(PARAMS.item)),
-                $("<table />", {"class": "item-list"})
-                  .append(
-                    $("<thead />")
-                      .append($("<tr />")
-                                .append($("<th />", {
-                                          "class": "filename border-left",
-                                          "scope": "col"
-                                        }).text("Filename"))
-                                .append($("<th />",
-                                          {"class": "version", "scope": "col"})
-                                          .text("Version"))
-                                .append($("<th />",
-                                          {"class": "size", "scope": "col"})
-                                          .text("Size"))
-                                .append($("<th />", {
-                                          "class": "modified",
-                                          "scope": "col"
-                                        }).text("Modified"))
-                                .append($("<th />", {
-                                          "class": "modified-by border-right",
-                                          "scope": "col"
-                                        }).text("Modified By"))))
-                  .append(tbody)
-                  .append($("<tfoot />").append($("<tr />").append($("<td />", {
-                    "colspan": "5",
-                    "class": "border-right border-left"
-                  })))));
-    newcontent.hide();
-
-    for (var i = 0; i < data.length; i++) {
-      file = data[i];
-
-      row = $("<tr />", {"class": "with-context-menu"});
-      if (i % 2) {
-        row.addClass("odd");
-      }
-
-      row.bind('mouseenter mouseleave', function() {
-        $(this).toggleClass('highlighted');
-      });
-
-      row.attr("filename",
-               file.filename); // encodeURIComponent(encodeURIComponent(file.filename)));
-      row.bind('click', function(e) {
-        openHistoryForItem($(this).attr("filename"))
-      });
-
-      row.append(
-        $("<td />", {"class": "filename border-left"})
-          .text(file.filename)
-          .prepend(
-            $("<img />", {"src": imgFullPath(fileExtension(file.filename))})));
-      row.append($("<td />", {"class": "version"}).text(file.version));
-      row.append(
-        $("<td />", {"class": "size"}).text(SegNumToFileSize(file.segNum)));
-      row.append($("<td />", {
-                   "class": "modified"
-                 }).text(new Date(file.timestamp + "+00:00"))); // convert from UTC
-      row.append($("<td />", {"class": "modified-by border-right"})
-                   .append($("<userName />").text(file.owner.userName))
-                   .append($("<seqNo> /").text(file.owner.seqNo)));
-
-      tbody = tbody.append(row);
-    }
-
-    displayContent(newcontent, more, this.base_url());
-
-    $.contextMenu('destroy', ".with-context-menu"); // cleanup
-    $.contextMenu({
-      selector: ".with-context-menu",
-      items: {
-        "info": {name: "x", type: "html", html: "<b>File operations</b>"},
-        "sep1": "---------",
-        history: {
-          name: "View file history",
-          icon: "quit", // need a better icon
-          callback: function(key, opt) {
-            openHistoryForItem(opt.$trigger.attr("filename"));
-          }
-        },
-      }
-    });
-  },
-
-  base_url: function() {
-    url = "#fileList" +
-          "&user=" + encodeURIComponent(encodeURIComponent(PARAMS.user)) +
-          "&folder=" + encodeURIComponent(encodeURIComponent(PARAMS.folder));
-    if (PARAMS.item !== undefined) {
-      url += "&item=" + encodeURIComponent(encodeURIComponent(PARAMS.item));
-    }
-    return url;
-  }
-});
-
-RestPipelineClosure("HistoryClosure", {}, {
-  init: function(chronoshare) {
-    this._super("actions", "more");
     this.chronoshare = chronoshare;
   },
 
@@ -356,7 +282,8 @@
     if (fileExtension(file.attr("filename")) == "txt") {
       CHRONOSHARE.get_file(file.attr("file_modified_by"),
                            DataUtils.toNumbers(file.attr("file_hash")),
-                           file.attr("file_seg_num"), function(status, data) {
+                           file.attr("file_seg_num"),
+                           function(status, data) {
                              $("<div />", {
                                "title": "Preview of " + file.attr("filename") +
                                           " version " + file.attr("file_version")
@@ -462,13 +389,11 @@
         $("<td />", {
           "class": "size"
         }).text(action.update ? SegNumToFileSize(action.update.segNum) : ""));
-      row.append($("<td />", {
-                   "class": "timestamp"
-                 }).text(new Date(action.timestamp + "+00:00"))); // conversion
-                                                                  // from UTC
-      // timezone (we
-      // store action
-      // time in UTC)
+      row.append(
+        $("<td />", {"class": "timestamp"})
+          .text(new Date(
+            action.timestamp +
+            "+00:00"))); // conversion from UTC timezone (we store action time in UTC)
       row.append($("<td />", {"class": "modified-by border-right"})
                    .append($("<userName />").text(action.id.userName))
                    .append($("<seqNo> /").text(action.id.seqNo)));
@@ -529,6 +454,10 @@
                                                        response != "OK") {
                                                      custom_alert(response);
                                                    }
+
+                                                   custom_alert(
+                                                     "Restore Succeed!");
+
                                                    console.log(response);
                                                    self.dialog("close");
 
@@ -568,3 +497,115 @@
     return url;
   }
 });
+
+$.Class("FilesDisplay", {}, {
+  init: function(chronoshare) {
+    this.chronoshare = chronoshare;
+  },
+
+  onData: function(data, more) {
+    tbody = $("<tbody />", {"id": "file-list-files"});
+
+    /// @todo Eventually set title for other pages
+    $("title").text("ChronoShare - List of files" +
+                    (PARAMS.item ? " - " + PARAMS.item : ""));
+
+    // error handling?
+    newcontent =
+      $("<div />", {"id": "content"})
+        .append($("<h2 />").append($(document.createTextNode("List of files ")),
+                                   $("<green />").text(PARAMS.item)),
+                $("<table />", {"class": "item-list"})
+                  .append(
+                    $("<thead />")
+                      .append($("<tr />")
+                                .append($("<th />", {
+                                          "class": "filename border-left",
+                                          "scope": "col"
+                                        }).text("Filename"))
+                                .append($("<th />",
+                                          {"class": "version", "scope": "col"})
+                                          .text("Version"))
+                                .append($("<th />",
+                                          {"class": "size", "scope": "col"})
+                                          .text("Size"))
+                                .append($("<th />", {
+                                          "class": "modified",
+                                          "scope": "col"
+                                        }).text("Modified"))
+                                .append($("<th />", {
+                                          "class": "modified-by border-right",
+                                          "scope": "col"
+                                        }).text("Modified By"))))
+                  .append(tbody)
+                  .append($("<tfoot />").append($("<tr />").append($("<td />", {
+                    "colspan": "5",
+                    "class": "border-right border-left"
+                  })))));
+    newcontent.hide();
+
+    for (var i = 0; i < data.length; i++) {
+      file = data[i];
+
+      row = $("<tr />", {"class": "with-context-menu"});
+      if (i % 2) {
+        row.addClass("odd");
+      }
+
+      row.bind('mouseenter mouseleave', function() {
+        $(this).toggleClass('highlighted');
+      });
+
+      row.attr("filename",
+               file.filename); //encodeURIComponent(encodeURIComponent(file.filename)));
+      row.bind('click', function(e) {
+        openHistoryForItem($(this).attr("filename"))
+      });
+
+      row.append(
+        $("<td />", {"class": "filename border-left"})
+          .text(file.filename)
+          .prepend(
+            $("<img />", {"src": imgFullPath(fileExtension(file.filename))})));
+      row.append($("<td />", {"class": "version"}).text(file.version));
+      row.append(
+        $("<td />", {"class": "size"}).text(SegNumToFileSize(file.segNum)));
+      row.append($("<td />", {
+                   "class": "modified"
+                 }).text(new Date(file.timestamp + "+00:00"))); // convert from UTC
+      row.append($("<td />", {"class": "modified-by border-right"})
+                   .append($("<userName />").text(file.owner.userName))
+                   .append($("<seqNo> /").text(file.owner.seqNo)));
+
+      tbody = tbody.append(row);
+    }
+
+    displayContent(newcontent, more, this.base_url());
+
+    $.contextMenu('destroy', ".with-context-menu"); // cleanup
+    $.contextMenu({
+      selector: ".with-context-menu",
+      items: {
+        "info": {name: "x", type: "html", html: "<b>File operations</b>"},
+        "sep1": "---------",
+        history: {
+          name: "View file history",
+          icon: "quit", // need a better icon
+          callback: function(key, opt) {
+            openHistoryForItem(opt.$trigger.attr("filename"));
+          }
+        },
+      }
+    });
+  },
+
+  base_url: function() {
+    url = "#fileList" +
+          "&user=" + encodeURIComponent(encodeURIComponent(PARAMS.user)) +
+          "&folder=" + encodeURIComponent(encodeURIComponent(PARAMS.folder));
+    if (PARAMS.item !== undefined) {
+      url += "&item=" + encodeURIComponent(encodeURIComponent(PARAMS.item));
+    }
+    return url;
+  }
+});