Fix rematch process
[vchess.git] / server / sockets.js
index 3854ca2..d1489f7 100644 (file)
@@ -14,13 +14,14 @@ function getJsonFromUrl(url) {
 
 // Helper to safe-send some message through a (web-)socket:
 function send(socket, message) {
-  if (socket && socket.readyState == 1)
+  if (!!socket && socket.readyState == 1)
     socket.send(JSON.stringify(message));
 }
 
 module.exports = function(wss) {
   // Associative array page --> sid --> tmpId --> socket
   // "page" is either "/" for hall or "/game/some_gid" for Game,
+  // or "/mygames" for Mygames page (simpler: no 'people' array).
   // tmpId is required if a same user (browser) has different tabs
   let clients = {};
   wss.on("connection", (socket, req) => {
@@ -34,8 +35,21 @@ module.exports = function(wss) {
         Object.keys(clients[page][k]).forEach(x => {
           if (k == sid && x == tmpId) return;
           send(
-            clients[page][k][x],
-            Object.assign({code: code, from: sid}, obj)
+            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) => {
+      if (!clients[page]) return;
+      Object.keys(clients[page]).forEach(k => {
+        if (except.includes(k)) return;
+        Object.keys(clients[page][k]).forEach(x => {
+          send(
+            clients[page][k][x].socket,
+            Object.assign({ code: code, from: sid }, obj)
           );
         });
       });
@@ -57,7 +71,7 @@ module.exports = function(wss) {
         // I effectively disconnected from this page:
         notifyRoom(page, "disconnect");
         if (page.indexOf("/game/") >= 0)
-          notifyRoom("/", "gdisconnect", {page:page});
+          notifyRoom("/", "gdisconnect", { page:page });
       }
     };
     const messageListener = (objtxt) => {
@@ -69,7 +83,7 @@ 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":
@@ -80,7 +94,7 @@ module.exports = function(wss) {
           // Self multi-connect: manual removal + disconnect
           const doKill = (pg) => {
             Object.keys(clients[pg][obj.sid]).forEach(x => {
-              send(clients[pg][obj.sid][x], {code: "killed"});
+              send(clients[pg][obj.sid][x].socket, { code: "killed" });
             });
             delete clients[pg][obj.sid];
           };
@@ -89,8 +103,8 @@ module.exports = function(wss) {
               if (k != obj.sid) {
                 Object.keys(clients[pg][k]).forEach(x => {
                   send(
-                    clients[pg][k][x],
-                    Object.assign({code: code, from: obj.sid}, o)
+                    clients[pg][k][x].socket,
+                    Object.assign({ code: code, from: obj.sid }, o)
                   );
                 });
               }
@@ -101,7 +115,7 @@ module.exports = function(wss) {
               doKill(pg);
               disconnectFromOtherConnexion(pg, "disconnect");
               if (pg.indexOf("/game/") >= 0 && clients["/"])
-                disconnectFromOtherConnexion("/", "gdisconnect", {page: pg});
+                disconnectFromOtherConnexion("/", "gdisconnect", { page: pg });
             }
           });
           break;
@@ -113,7 +127,7 @@ module.exports = function(wss) {
             // Avoid polling myself: no new information to get
             if (k != sid) sockIds.push(k);
           });
-          send(socket, {code: "pollclients", sockIds: sockIds});
+          send(socket, { code: "pollclients", sockIds: sockIds });
           break;
         }
         case "pollclientsandgamers": {
@@ -128,11 +142,11 @@ module.exports = function(wss) {
             if (p != "/") {
               Object.keys(clients[p]).forEach(k => {
                 // 'page' indicator is needed for gamers
-                if (k != sid) sockIds.push({sid:k, page:p});
+                if (k != sid) sockIds.push({ sid:k, page:p });
               });
             }
           });
-          send(socket, {code: "pollclientsandgamers", sockIds: sockIds});
+          send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
           break;
         }
 
@@ -145,7 +159,7 @@ module.exports = function(wss) {
         case "askfullgame": {
           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]) {
+          if (!!clients[pg] && !!clients[pg][obj.target]) {
             const tmpIds = Object.keys(clients[pg][obj.target]);
             if (obj.target == sid) {
               // Targetting myself
@@ -154,8 +168,8 @@ module.exports = function(wss) {
             }
             const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
             send(
-              clients[pg][obj.target][tmpIds[tmpId_idx]],
-              {code: obj.code, from: [sid,tmpId,page]}
+              clients[pg][obj.target][tmpIds[tmpId_idx]].socket,
+              { code: obj.code, from: [sid,tmpId,page] }
             );
           }
           break;
@@ -167,8 +181,8 @@ module.exports = function(wss) {
           Object.keys(clients[page][obj.target]).forEach(x => {
             if (obj.target != sid || x != tmpId)
               send(
-                clients[page][obj.target][x],
-                {code: obj.code, data: obj.data}
+                clients[page][obj.target][x].socket,
+                { code: obj.code, data: obj.data }
               );
           });
           break;
@@ -176,19 +190,57 @@ module.exports = function(wss) {
         // Notify all room: mostly game events
         case "newchat":
         case "newchallenge":
-        case "newgame":
         case "deletechallenge":
-        case "newmove":
+        case "newgame":
         case "resign":
         case "abort":
         case "drawoffer":
+        case "rematchoffer":
         case "draw":
-          notifyRoom(page, obj.code, {data: obj.data});
+          if (!!obj.oppsid)
+            // "newgame" message from Hall: do not target players
+            notifyAllBut(page, "newgame", {data: obj.data}, [sid, obj.oppsid]);
+          else notifyRoom(page, obj.code, {data: obj.data});
+          break;
+
+        case "rnewgame":
+          // A rematch game started: players are already informed
+          notifyAllBut(page, "newgame", {data: obj.data}, [sid]);
+          notifyAllBut("/", "newgame", {data: obj.data}, [sid, obj.oppsid]);
+          notifyRoom("/mygames", "newgame", {data: obj.data});
+          break;
+
+        case "newmove": {
+          const dataWithFrom = { from: [sid,tmpId], data: obj.data };
+          // Special case re-send newmove only to opponent:
+          if (!!obj.target && !!clients[page][obj.target]) {
+            Object.keys(clients[page][obj.target]).forEach(x => {
+              send(
+                clients[page][obj.target][x].socket,
+                Object.assign({ code: "newmove" }, dataWithFrom)
+              );
+            });
+          } else {
+            // NOTE: data.from is useful only to opponent
+            notifyRoom(page, "newmove", dataWithFrom);
+          }
+          break;
+        }
+        case "gotmove":
+          if (
+            !!clients[page][obj.target[0]] &&
+            !!clients[page][obj.target[0]][obj.target[1]]
+          ) {
+            send(
+              clients[page][obj.target[0]][obj.target[1]].socket,
+              { code: "gotmove" }
+            );
+          }
           break;
 
         case "result":
           // Special case: notify all, 'transroom': Game --> Hall
-          notifyRoom("/", "result", {gid: obj.gid, score: obj.score});
+          notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
           break;
 
         case "mconnect":
@@ -200,8 +252,8 @@ module.exports = function(wss) {
             Object.keys(clients[pg]).forEach(s => {
               Object.keys(clients[pg][s]).forEach(x => {
                 send(
-                  clients[pg][s][x],
-                  {code: "mconnect", data: obj.data}
+                  clients[pg][s][x].socket,
+                  { code: "mconnect", from: sid }
                 );
               });
             });
@@ -211,6 +263,28 @@ module.exports = function(wss) {
           // TODO
           // Also TODO: pass newgame to MyGames, and gameover (result)
           break;
+        case "mabort": {
+          const gamePg = "/game/" + obj.gid;
+          if (!!clients[gamePg] && !!clients[gamePg][obj.target]) {
+            Object.keys(clients[gamePg][obj.target]).forEach(x => {
+              send(
+                clients[gamePg][obj.target][x].socket,
+                { code: "abort" }
+              );
+            });
+          }
+          break;
+        }
+
+        case "getfocus":
+        case "losefocus":
+          if (page == "/") notifyAllBut("/", obj.code, { page: "/" }, [sid]);
+          else {
+            // Notify game room + Hall:
+            notifyAllBut(page, obj.code, {}, [sid]);
+            notifyAllBut("/", obj.code, { page: page }, [sid]);
+          }
+          break;
 
         // Passing, relaying something: from isn't needed,
         // but target is fully identified (sid + tmpId)
@@ -222,9 +296,13 @@ module.exports = function(wss) {
         {
           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 ndefined
-          if (clients[pg] && clients[pg][obj.target[0]])
-            send(clients[pg][obj.target[0]][obj.target[1]], {code:obj.code, data:obj.data});
+          // but leaving Hall, clients[pg] or clients[pg][target] could be undefined
+          if (!!clients[pg] && !!clients[pg][obj.target[0]]) {
+            send(
+              clients[pg][obj.target[0]][obj.target[1]].socket,
+              { code:obj.code, data:obj.data }
+            );
+          }
           break;
         }
       }
@@ -234,12 +312,13 @@ module.exports = function(wss) {
       doDisconnect();
     };
     // Update clients object: add new connexion
+    const newElt = { socket: socket, focus: true };
     if (!clients[page])
-      clients[page] = {[sid]: {[tmpId]: socket}};
+      clients[page] = { [sid]: {[tmpId]: newElt } };
     else if (!clients[page][sid])
-      clients[page][sid] = {[tmpId]: socket};
+      clients[page][sid] = { [tmpId]: newElt };
     else
-      clients[page][sid][tmpId] = socket;
+      clients[page][sid][tmpId] = newElt;
     socket.on("message", messageListener);
     socket.on("close", closeListener);
   });