Add Castle Chess
[vchess.git] / server / sockets.js
index b16135b..9fa09bc 100644 (file)
@@ -1,7 +1,4 @@
-const url = require('url');
-
 // Node version in Ubuntu 16.04 does not know about URL class
-// NOTE: url is already transformed, without ?xxx=yyy... parts
 function getJsonFromUrl(url) {
   const query = url.substr(2); //starts with "/?"
   let result = {};
@@ -24,6 +21,7 @@ module.exports = function(wss) {
   // or "/mygames" for Mygames page (simpler: no 'people' array).
   // tmpId is required if a same user (browser) has different tabs
   let clients = {};
+  // NOTE: only purpose of sidToPages = know when to delete keys in idToSid
   let sidToPages = {};
   let idToSid = {};
   wss.on("connection", (socket, req) => {
@@ -32,27 +30,16 @@ module.exports = function(wss) {
     const id = query["id"];
     const tmpId = query["tmpId"];
     const page = query["page"];
-    const notifyRoom = (page,code,obj={}) => {
-      if (!clients[page]) return;
-      Object.keys(clients[page]).forEach(k => {
-        Object.keys(clients[page][k]).forEach(x => {
-          if (k == sid && x == tmpId) return;
-          send(
-            clients[page][k][x].socket,
-            Object.assign({ code: code, from: sid }, obj)
-          );
-        });
-      });
-    };
-    // For focus events: no need to target self
-    const notifyAllBut = (page,code,obj={},except) => {
+    const notifyRoom = (page, code, obj={}, except) => {
       if (!clients[page]) return;
+      except = except || [];
       Object.keys(clients[page]).forEach(k => {
         if (except.includes(k)) return;
         Object.keys(clients[page][k]).forEach(x => {
+          if (k == sid && x == tmpId) return;
           send(
             clients[page][k][x].socket,
-            Object.assign({ code: code, from: sid }, obj)
+            Object.assign({ code: code, from: [sid, tmpId] }, obj)
           );
         });
       });
@@ -78,11 +65,10 @@ module.exports = function(wss) {
     const doDisconnect = () => {
       deleteConnexion();
       // Nothing to notify when disconnecting from MyGames page:
-      if (page != "/mygames" && (!clients[page] || !clients[page][sid])) {
-        // I effectively disconnected from this page:
+      if (page != "/mygames") {
         notifyRoom(page, "disconnect");
         if (page.indexOf("/game/") >= 0)
-          notifyRoom("/", "gdisconnect", { page:page });
+          notifyRoom("/", "gdisconnect", { page: page });
       }
     };
     const messageListener = (objtxt) => {
@@ -94,66 +80,55 @@ module.exports = function(wss) {
         case "connect": {
           notifyRoom(page, "connect");
           if (page.indexOf("/game/") >= 0)
-            notifyRoom("/", "gconnect", { page:page });
+            notifyRoom("/", "gconnect", { page: page });
           break;
         }
         case "disconnect":
           // When page changes:
           doDisconnect();
           break;
-        case "killme": {
-          // Self multi-connect: manual removal + disconnect
-          const doKill = (pg) => {
-            Object.keys(clients[pg][obj.sid]).forEach(x => {
-              send(clients[pg][obj.sid][x].socket, { code: "killed" });
-            });
-            delete clients[pg][obj.sid];
-          };
-          const disconnectFromOtherConnexion = (pg,code,o={}) => {
-            Object.keys(clients[pg]).forEach(k => {
-              if (k != obj.sid) {
-                Object.keys(clients[pg][k]).forEach(x => {
-                  send(
-                    clients[pg][k][x].socket,
-                    Object.assign({ code: code, from: obj.sid }, o)
-                  );
-                });
-              }
-            });
-          };
-          Object.keys(clients).forEach(pg => {
-            if (clients[pg][obj.sid]) {
-              doKill(pg);
-              disconnectFromOtherConnexion(pg, "disconnect");
-              if (pg.indexOf("/game/") >= 0 && clients["/"])
-                disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
-            }
-          });
-          break;
-        }
         case "pollclients": {
-          // From Hall or Game
-          let sockIds = [];
+          // From Game
+          let sockIds = {};
           Object.keys(clients[page]).forEach(k => {
-            // Avoid polling myself: no new information to get
-            if (k != sid) sockIds.push(k);
+            sockIds[k] = {};
+            Object.keys(clients[page][k]).forEach(x => {
+              // Avoid polling my tmpId: no information to get
+              if (k != sid || x != tmpId)
+                sockIds[k][x] = { focus: clients[page][k][x].focus };
+            });
           });
           send(socket, { code: "pollclients", sockIds: sockIds });
           break;
         }
         case "pollclientsandgamers": {
           // From Hall
-          let sockIds = [];
+          let sockIds = {};
           Object.keys(clients["/"]).forEach(k => {
-            // Avoid polling myself: no new information to get
-            if (k != sid) sockIds.push({sid:k});
+            sockIds[k] = {};
+            Object.keys(clients[page][k]).forEach(x => {
+              // Avoid polling my tmpId: no information to get
+              if (k != sid || x != tmpId) {
+                sockIds[k][x] = {
+                  page: "/",
+                  focus: clients[page][k][x].focus
+                };
+              }
+            });
           });
           // NOTE: a "gamer" could also just be an observer
           Object.keys(clients).forEach(p => {
             if (p.indexOf("/game/") >= 0) {
               Object.keys(clients[p]).forEach(k => {
-                // 'page' indicator is needed for gamers
-                if (k != sid) sockIds.push({ sid:k, page:p });
+                if (!sockIds[k]) sockIds[k] = {};
+                Object.keys(clients[p][k]).forEach(x => {
+                  if (k != sid || x != tmpId) {
+                    sockIds[k][x] = {
+                      page: p,
+                      focus: clients[p][k][x].focus
+                    };
+                  }
+                });
               });
             }
           });
@@ -166,22 +141,45 @@ module.exports = function(wss) {
         case "askidentity":
         case "asklastate":
         case "askchallenges":
-        case "askgame":
-        case "askfullgame": {
+        case "askgame": {
           const pg = obj.page || page; //required for askidentity and askgame
-          // In cas askfullgame to wrong SID for example, would crash:
           if (!!clients[pg] && !!clients[pg][obj.target]) {
-            const tmpIds = Object.keys(clients[pg][obj.target]);
+            let tmpIds = Object.keys(clients[pg][obj.target]);
             if (obj.target == sid) {
               // Targetting myself
               const idx_myTmpid = tmpIds.findIndex(x => x == tmpId);
               if (idx_myTmpid >= 0) tmpIds.splice(idx_myTmpid, 1);
             }
-            const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
-            send(
-              clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
-              { code: obj.code, from: [sid,tmpId,page] }
-            );
+            if (tmpIds.length > 0) {
+              const ttmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
+              send(
+                clients[pg][obj.target][ttmpId].socket,
+                { code: obj.code, from: [sid,tmpId,page] }
+              );
+            }
+          }
+          break;
+        }
+
+        // Special situation of the previous "case":
+        // Full game can be asked to any observer.
+        case "askfullgame": {
+          if (!!clients[page]) {
+            let sids = Object.keys(clients[page]).filter(k => k != sid);
+            if (sids.length > 0) {
+              // Pick a SID at random in this set, and ask full game:
+              const rid = sids[Math.floor(Math.random() * sids.length)];
+              // ..to a random tmpId:
+              const tmpIds = Object.keys(clients[page][rid]);
+              const rtmpId = tmpIds[Math.floor(Math.random() * tmpIds.length)];
+              send(
+                clients[page][rid][rtmpId].socket,
+                { code: "askfullgame", from: [sid,tmpId] }
+              );
+            } else {
+              // I'm the only person who have the game for the moment:
+              send(socket, { code: "fullgame", data: { empty: true } });
+            }
           }
           break;
         }
@@ -208,14 +206,18 @@ module.exports = function(wss) {
         case "drawoffer":
         case "rematchoffer":
         case "draw":
-          notifyRoom(page, obj.code, {data: obj.data});
+          // "newgame" message can provide a page (corr Game --> Hall)
+          notifyRoom(
+            obj.page || page, obj.code, {data: obj.data}, obj.excluded);
           break;
 
         case "rnewgame":
           // A rematch game started:
-          // NOTE: no need to explicitely notify Hall: the game will be sent
-          notifyAllBut(page, "newgame", {data: obj.data}, [sid]);
-          notifyRoom("/mygames", "newgame", {data: obj.data});
+          notifyRoom(page, "newgame", {data: obj.data});
+          // Explicitely notify Hall if gametype == corr.
+          // Live games will be polled from Hall after gconnect event.
+          if (obj.data.cadence.indexOf('d') >= 0)
+            notifyRoom("/", "newgame", {data: obj.data});
           break;
 
         case "newmove": {
@@ -269,7 +271,7 @@ module.exports = function(wss) {
         case "notifynewgame":
           if (!!clients["/mygames"]) {
             obj.targets.forEach(t => {
-              const k = t.sid || idToSid[t.uid];
+              const k = t.sid || idToSid[t.id];
               if (!!clients["/mygames"][k]) {
                 Object.keys(clients["/mygames"][k]).forEach(x => {
                   send(
@@ -284,11 +286,18 @@ module.exports = function(wss) {
 
         case "getfocus":
         case "losefocus":
-          if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
+          if (
+            !!clients[page] &&
+            !!clients[page][sid] &&
+            !!clients[page][sid][tmpId]
+          ) {
+            clients[page][sid][tmpId].focus = (obj.code == "getfocus");
+          }
+          if (page == "/") notifyRoom("/", obj.code, { page: "/" }, [sid]);
           else {
             // Notify game room + Hall:
-            notifyAllBut(page, obj.code, {}, [sid]);
-            notifyAllBut("/", obj.code, { page: page }, [sid]);
+            notifyRoom(page, obj.code, {}, [sid]);
+            notifyRoom("/", obj.code, { page: page }, [sid]);
           }
           break;
 
@@ -301,8 +310,8 @@ module.exports = function(wss) {
         case "lastate":
         {
           const pg = obj.target[2] || page; //required for identity and game
-          // NOTE: if in game we ask identity to opponent still in Hall,
-          // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
+          // NOTE: if in game we ask identity to opponent still in Hall, but
+          // leaving Hall, clients[pg] or clients[pg][target] could be undef.
           if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
             send(
               clients[pg][obj.target[0]][obj.target[1]].socket,