repo: janusweb
action: commit
revision: 
path_from: 
revision_from: db1d1f3131d689b111deb8819a51c6ecab448e4d:
path_to: 
revision_to: 
git.thebackupbox.net
janusweb
git clone git://git.thebackupbox.net/janusweb
commit db1d1f3131d689b111deb8819a51c6ecab448e4d
Author: James Baicoianu 
Date:   Thu Apr 21 04:29:02 2016 -0700

    Added Reddit translator, use promises for translators, more room init cleanup

diff --git a/scripts/room.js b/scripts/room.js
index 3877a683a40e4bc9ea042bd5188b0ddc076951a2..
index ..dac1ffed434ab7b8ac163d196e3bc8ea48a46f95 100644
--- a/scripts/room.js
+++ b/scripts/room.js
@@ -2,7 +2,7 @@ elation.require([
     'ui.textarea', 'ui.window', 
      'engine.things.generic', 'engine.things.sound', 'engine.things.label', 
     'janusweb.object', 'janusweb.portal', 'janusweb.image', 'janusweb.video', 'janusweb.text',
-    'janusweb.translators.bookmarks'
+    'janusweb.translators.bookmarks', 'janusweb.translators.reddit'
   ], function() {
   elation.component.add('engine.things.janusroom', function() {
     this.postinit = function() {
@@ -25,7 +25,8 @@ elation.require([
         'run_speed': { type: 'float', default: 5.4 },
       });
       this.translators = {
-        bookmarks: elation.janusweb.translators.bookmarks({}),
+        '^bookmarks$': elation.janusweb.translators.bookmarks({}),
+        '^https?:\/\/(www\.)?reddit.com': elation.janusweb.translators.reddit({})
       };
       this.playerstartposition = [0,0,0];
       this.playerstartorientation = new THREE.Quaternion();
@@ -195,14 +196,18 @@ elation.require([
         fullurl = proxyurl + fullurl;
       }

+      var translator = this.getTranslator(url);
+
       if (url == document.location.href) {
         setTimeout(elation.bind(this, function() {
-          this.parseSource(document.documentElement.outerHTML);
+          this.roomsrc = this.parseSource(document.documentElement.outerHTML);
+          var roomdata = this.parseFireBox(this.roomsrc.source);
+          this.createRoomObjects(roomdata);
         }), 0);
-      } else if (url in this.translators) {
+      } else if (translator) {
         setTimeout(elation.bind(this, function() {
-          var roomdata = this.translators[url].exec({url: url, janus: this.properties.janus});
-          this.createRoomObjects(roomdata);
+          translator.exec({url: url, janus: this.properties.janus, room: this})
+                    .then(elation.bind(this, this.createRoomObjects));
         }), 0);
       } else {
         elation.net.get(fullurl, null, { 
@@ -211,7 +216,10 @@ elation.require([
             //'X-Requested-With':'JanusWeb Client'
           },
           callback: elation.bind(this, function(data, xhr) { 
-            if (this.parseSource(data)) {
+            var source = this.parseSource(data);
+            if (source) {
+              var roomdata = this.parseFireBox(source.source);
+              this.createRoomObjects(roomdata);
               var responseURL = xhr.getResponseHeader('X-Final-URL');
               if (!responseURL) {
                 responseURL = xhr.responseURL.replace(proxyurl, '');
@@ -236,7 +244,12 @@ elation.require([
       var titlere = /([\s\S]*?)<\/title>/mi; 
       var re = /<fireboxroom>[\s\S]*?<\/fireboxroom>/mi; 
       var mtitle = data.match(titlere); 
+      var parsed = {
+        title: 'Untitled Room',
+        source: ''
+      }
       if (mtitle) {
+        parsed.title = mtitle[1];
         this.setTitle(mtitle[1]);
       } else {
         this.setTitle(null);
@@ -244,20 +257,17 @@ elation.require([
       var datapath = elation.config.get('janusweb.datapath', '/media/janusweb');
       var m = data.match(re); 
       if (m) { 
-        this.roomsrc = m[0];
-        this.parseFireBox(this.roomsrc);
-        return true;
+        parsed.source = m[0];
       } else {
         console.log('no firebox room, load the translator');
         var transpath = datapath + 'assets/translator/web/';
         this.load(transpath + 'Parallelogram.html', transpath );
       }
-      return false;
+      return parsed;
     }

     this.parseFireBox = function(fireboxsrc) {
       var xml = elation.utils.parseXML(fireboxsrc, false, true); 
-
       var rooms = this.getAsArray(elation.utils.arrayget(xml, 'fireboxroom._children.room', {})); 
       var room = {_children: {}};
       for (var i = 0; i < rooms.length; i++) {
@@ -273,7 +283,7 @@ elation.require([
       }

       var roomdata = this.getRoomData(xml, room);
-      this.createRoomObjects(roomdata);
+      return roomdata;
     }

     this.createRoomObjects = function(roomdata) {
@@ -287,7 +297,7 @@ elation.require([
           texts = roomdata.texts || [],
           videos = roomdata.videos || [];

-      if (room.use_local_asset && room.visible != 'false') {
+      if (room.use_local_asset && room.visible !== false) {
         var localasset = this.spawn('janusobject', 'local_asset_' + Math.round(Math.random() * 10000), { 
           'room': this,
           'render.model': room.use_local_asset,
@@ -321,7 +331,7 @@ elation.require([
         }
       }));
       if (links) links.forEach(elation.bind(this, function(n) {
-        var linkurl = (n.url.match(/^https?:/) || n.url in this.translators ? n.url : this.baseurl + n.url);
+        var linkurl = (n.url.match(/^https?:/) || this.getTranslator(n.url) ? n.url : this.baseurl + n.url);
         var portalargs = { 
           'room': this,
           'janus': this.properties.janus,
@@ -440,7 +450,6 @@ elation.require([
       if (room.skybox_front_id) this.properties.skybox_front = room.skybox_front_id;
       if (room.skybox_back_id) this.properties.skybox_back = room.skybox_back_id;

-console.log('room', room);
       this.properties.near_dist = parseFloat(room.near_dist) || 0.01;
       this.properties.far_dist = parseFloat(room.far_dist) || 1000;
       this.properties.fog = room.fog;
@@ -582,27 +591,16 @@ console.log('room', room);
       return assets;
     }
     this.parseNode = function(n) {
-      var nodeinfo = {
-/*
-        pos: (n.pos ? n.pos.split(' ').map(parseFloat) : [0,0,0]),
-        scale: (n.scale ? n.scale.split(' ').map(parseFloat) : [1,1,1]),
-        orientation: this.getOrientation(n.xdir, n.ydir || n.up, n.zdir || n.fwd),
-        col: (n.col ? (n.col[0] == '#' ? [parseInt(n.col.substr(1,2), 16)/255, parseInt(n.col.substr(3, 2), 16)/255, parseInt(n.col.substr(5, 2), 16)/255] : n.col.split(' ')) : [1,1,1]),
-        visible: (n.visible !== false && n.visible !== 0 && n.visible !== 'false'),
-        lighting: (n.lighting !== false && n.lighting !== 0 && n.lighting !== 'false')
-*/
-      };
+      var nodeinfo = {};
       var attrs = Object.keys(n);
       attrs.forEach(elation.bind(this, function(k) {
-        nodeinfo[k] = n[k];
+        nodeinfo[k] = (n[k] == 'false' ? false : n[k]);
       }));

       nodeinfo.pos = (n.pos ? (elation.utils.isArray(n.pos) ? n.pos : n.pos.split(' ')).map(parseFloat) : [0,0,0]);
       nodeinfo.scale = (n.scale ? (elation.utils.isArray(n.scale) ? n.scale : n.scale.split(' ')).map(parseFloat) : [1,1,1]);
       nodeinfo.orientation = this.getOrientation(n.xdir, n.ydir || n.up, n.zdir || n.fwd);
       nodeinfo.col = (n.col ? (n.col[0] == '#' ? [parseInt(n.col.substr(1,2), 16)/255, parseInt(n.col.substr(3, 2), 16)/255, parseInt(n.col.substr(5, 2), 16)/255] : (elation.utils.isArray(n.col) ? n.col : n.col.split(' '))) : [1,1,1]);
-      nodeinfo.visible = (n.visible !== false && n.visible !== 0 && n.visible !== 'false');
-      nodeinfo.lighting = (n.lighting !== false && n.lighting !== 0 && n.lighting !== 'false');

       var minscale = 1e-6;
       nodeinfo.scale[0] = Math.max(minscale, nodeinfo.scale[0]);
@@ -611,6 +609,17 @@ console.log('room', room);

       return nodeinfo;
     }
+    this.getTranslator = function(url) {
+      var keys = Object.keys(this.translators);
+      for (var i = 0; i < keys.length; i++) {
+        var re = new RegExp(keys[i]);
+        if (url.match(re)) {
+          return this.translators[keys[i]];
+        }
+      }
+      // TODO - implement default page handling as translator
+      return false;
+    }
     this.enable = function() {
     }
     this.disable = function() {
diff --git a/scripts/translators/bookmarks.js b/scripts/translators/bookmarks.js
</pre>
<div><a href="https://gemini.nicfab.eu/lxy/external/git.thebackupbox.net%2Fjanusweb%2Fblob%2F%3Fid%3D62044551e8e1041d4aa9c6c080149cafa7cf2275">index 62044551e8e1041d4aa9c6c080149cafa7cf2275..</a></div>
<div><a href="https://gemini.nicfab.eu/lxy/external/git.thebackupbox.net%2Fjanusweb%2Fblob%2F%3Fid%3Daa4b422070e5c6730a65e98adcc3d31573927083">index ..aa4b422070e5c6730a65e98adcc3d31573927083 100644</a></div>
<pre>
--- a/scripts/translators/bookmarks.js
+++ b/scripts/translators/bookmarks.js
@@ -1,35 +1,37 @@
 elation.require(['elation.collection'], function() {
   elation.component.add('janusweb.translators.bookmarks', function() {
     this.exec = function(args) {
-      var roomdata = {
-        room: {
-          use_local_asset: 'room2',
-          pos: [-18, 0, 0],
-          orientation: new THREE.Quaternion().setFromEuler(new THREE.Euler(0,0,0))
-        },
-        objects: [],
-        links: []
-      };
-      //var bookmarks = elation.collection.localindexed({key: 'janusweb.bookmarks'});
-      var bookmarks = args.janus.bookmarks;
-      var x = 0, y = 0,
-          spacex = 1.5, spacey = 1.2,
-          numy = 1,
-          offsetx = -19, offsety = 0;
-      if (bookmarks.length > 0) {
-        var items = bookmarks.items;
-        for (var i = 0; i < items.length; i++) {
-          var item = items[items.length - i - 1];
-          roomdata.links.push({
-            url: item.url,
-            title: item.title,
-            scale: [1.2, 2, 1],
-            pos: [Math.floor(i / numy) * spacex + offsetx, offsety - ((i % numy) * spacey), 5],
-            orientation: new THREE.Quaternion().setFromEuler(new THREE.Euler(0,Math.PI,0))
-          });
+      return new Promise(function(resolve, reject) {
+        var roomdata = {
+          room: {
+            use_local_asset: 'room2',
+            pos: [-18, 0, 0],
+            orientation: new THREE.Quaternion().setFromEuler(new THREE.Euler(0,0,0))
+          },
+          objects: [],
+          links: []
         };
-      }
-      return roomdata;
+        //var bookmarks = elation.collection.localindexed({key: 'janusweb.bookmarks'});
+        var bookmarks = args.janus.bookmarks;
+        var x = 0, y = 0,
+            spacex = 1.5, spacey = 1.2,
+            numy = 1,
+            offsetx = -19, offsety = 0;
+        if (bookmarks.length > 0) {
+          var items = bookmarks.items;
+          for (var i = 0; i < items.length; i++) {
+            var item = items[items.length - i - 1];
+            roomdata.links.push({
+              url: item.url,
+              title: item.title,
+              scale: [1.2, 2, 1],
+              pos: [Math.floor(i / numy) * spacex + offsetx, offsety - ((i % numy) * spacey), 5],
+              orientation: new THREE.Quaternion().setFromEuler(new THREE.Euler(0,Math.PI,0))
+            });
+          };
+        }
+        resolve(roomdata);
+      });
     }
   });
 });
diff --git a/scripts/translators/reddit.js b/scripts/translators/reddit.js
new file mode 100644
index 0000000000000000000000000000000000000000..877046afd539b5267ff4dfc3f15ba070bd9c1ddc
--- /dev/null
+++ b/scripts/translators/reddit.js
@@ -0,0 +1,104 @@
+elation.require(['elation.collection'], function() {
+  elation.component.add('janusweb.translators.reddit', function() {
+    this.init = function() {
+      var datapath = elation.config.get('janusweb.datapath', '/media/janusweb');
+      var fullfile = datapath + 'assets/translator/reddit/RedditRoomConcept.html';
+      this.queue = [];
+      this.promise = false;
+      this.roomsource = '<fireboxroom><room use_local_asset="room2"></room></fireboxroom>';
+      elation.net.get(fullfile, null, { callback: elation.bind(this, this.handleLoad) });
+    }
+    this.handleLoad = function(source) {
+      this.roomsource = source;
+
+      if (this.queue) {
+        this.queue.forEach(elation.bind(this, this.exec));
+      }
+    }
+    this.exec = function(args) {
+      return new Promise(elation.bind(this, function(resolve, reject) {
+        args.resolve = resolve;
+        args.reject = reject;
+        if (!this.roomsource) {
+          this.queue.push(args);
+        } else {
+          var datapath = elation.config.get('janusweb.datapath', '/media/janusweb');
+          var fullpath = datapath + 'assets/translator/reddit/';
+          var room = args.room;
+          room.baseurl = fullpath;
+          var endpoint = args.url.replace(/^https?:\/\/(www\.)?reddit\.com/, '');
+          var idx = endpoint.indexOf('?');
+          if (idx != -1) {
+            endpoint = endpoint.substr(0, idx) + '.json' + endpoint.substr(idx);
+          } else {
+            endpoint += '.json';
+          }
+
+          var collection = elation.collection.jsonapi({
+            host: 'https://www.reddit.com',
+            endpoint: endpoint,
+            datatransform: {
+              items: function(data) {
+                var items = [];
+                data.data.children.forEach(function(c) {
+                  items.push(c.data);
+                });
+                return items;
+              },
+            },
+            events: {
+              collection_load: elation.bind(this, this.translate, args)
+            }
+          });
+          console.log(collection.items);
+        }
+      }));
+    }
+    this.translate = function(args, ev) {
+console.log('dud');
+      var room = args.room;
+      var source = room.parseSource(this.roomsource);
+      var roomdata = room.parseFireBox(source.source);
+      var items = ev.target.items;
+      var numlinks = 25;
+      var flip = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0));
+      var lastid = false;
+      var texts = {};
+      roomdata.texts.forEach(function(t) { texts[t.js_id] = t; });
+      var offset = 3;
+      for (var i = 0; i < numlinks; i++) {
+        var item = items[i];
+        var link = roomdata.links[i];
+        if (item && link) {
+          link.title = item.title;
+          link.url = item.url;
+          lastid = item.name;
+        }
+        var textid = offset + (i * 6);
+        //texts[textid]._content = item.title;
+        texts[textid]._content = (i+1);
+        texts[textid+1]._content = item.title;
+        texts[textid+2]._content = this.getRelativeDate(item.created) + ' by';
+        texts[textid+3]._content = item.author;
+        //texts[textid+3]._content = item.user;
+        texts[textid+4]._content = item.score + ' upvotes';
+      }
+      var idx = args.url.indexOf('?');
+      var nexturl = (idx == -1 ? args.url : args.url.substr(0, idx)) + '?count=25&after=' + lastid;
+      
+      roomdata.links[roomdata.links.length-1].url = nexturl;
+      args.resolve(roomdata);
+    }
+    this.getRelativeDate = function(ts) {
+      var now = new Date().getTime() / 1000;
+      var diff = now - ts;
+      var str = diff + ' seconds ago';
+      if (diff > 60) str = Math.floor(diff / 60) + ' minutes ago';
+      if (diff > 3600) str = Math.floor(diff / 3600) + ' hours ago';
+      if (diff > 86400) str = Math.floor(diff / 86400) + ' days ago';
+      if (diff > 2592000) str = Math.floor(diff / 2592000) + ' months ago';
+      if (diff > 31536000) str = Math.floor(diff / 31536000) + ' years ago';
+      return str;
+    }
+  });
+});
</pre>
<p>-----END OF PAGE-----</p>

</main>
</body>

</html>