Refactor models (merge Players in Games), add cursor to correspondance games. Finishe...
[vchess.git] / server / sockets.js
index 11f7d8e..7de7abb 100644 (file)
@@ -2,8 +2,7 @@ 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)
-{
+function getJsonFromUrl(url) {
   const query = url.substr(2); //starts with "/?"
   let result = {};
   query.split("&").forEach((part) => {
@@ -13,226 +12,324 @@ function getJsonFromUrl(url)
   return result;
 }
 
+// Helper to safe-send some message through a (web-)socket:
+function send(socket, message) {
+  if (!!socket && socket.readyState == 1)
+    socket.send(JSON.stringify(message));
+}
+
 module.exports = function(wss) {
-  // Associative array sid --> tmpId --> {socket, page},
+  // 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 = {};
+  let sidToPages = {};
+  let idToSid = {};
   wss.on("connection", (socket, req) => {
     const query = getJsonFromUrl(req.url);
     const sid = query["sid"];
+    const id = query["id"];
     const tmpId = query["tmpId"];
-    const notifyRoom = (page,code,obj={},excluded=[]) => {
-      Object.keys(clients).forEach(k => {
-        if (k in excluded)
-          return;
-        if (k != sid && clients[k].page == page)
-        {
-          clients[k].sock.send(JSON.stringify(Object.assign(
-            {code:code, from:[sid,tmpId]}, obj)));
-        }
+    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) => {
+      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)
+          );
+        });
       });
     };
+    const deleteConnexion = () => {
+      if (!clients[page] || !clients[page][sid] || !clients[page][sid][tmpId])
+        return; //job already done
+      delete clients[page][sid][tmpId];
+      if (Object.keys(clients[page][sid]).length == 0) {
+        delete clients[page][sid];
+        const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
+        sidToPages[sid].splice(pgIndex, 1);
+        if (Object.keys(clients[page]).length == 0)
+          delete clients[page];
+        // Am I totally offline?
+        if (sidToPages[sid].length == 0) {
+          delete sidToPages[sid];
+          delete idToSid[id];
+        }
+      }
+    };
+
+    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:
+        notifyRoom(page, "disconnect");
+        if (page.indexOf("/game/") >= 0)
+          notifyRoom("/", "gdisconnect", { page:page });
+      }
+    };
     const messageListener = (objtxt) => {
       let obj = JSON.parse(objtxt);
-      if (!!obj.target && !clients[obj.target])
-        return; //receiver not connected, nothing we can do
-      switch (obj.code)
-      {
+      switch (obj.code) {
         // Wait for "connect" message to notify connection to the room,
         // because if game loading is slow the message listener might
         // not be ready too early.
-        case "connect":
-        {
-          const curPage = clients[sid][tmpId].page;
-          notifyRoom(curPage, "connect"); //Hall or Game
-          if (curPage.indexOf("/game/") >= 0)
-            notifyRoom("/", "gconnect"); //notify main hall
+        case "connect": {
+          notifyRoom(page, "connect");
+          if (page.indexOf("/game/") >= 0)
+            notifyRoom("/", "gconnect", { page:page });
           break;
         }
         case "disconnect":
-        {
-          const oldPage = obj.page;
-          notifyRoom(oldPage, "disconnect"); //Hall or Game
-          if (oldPage.indexOf("/game/") >= 0)
-            notifyRoom("/", "gdisconnect"); //notify main hall
+          // When page changes:
+          doDisconnect();
           break;
-        }
-        case "pollclients":
-        {
-          const curPage = clients[sid][tmpId].page;
-          let sockIds = {}; //result, object sid ==> [tmpIds]
-          Object.keys(clients).forEach(k => {
-            Object.keys(clients[k]).forEach(x => {
-              if ((k != sid || x != tmpId)
-                && clients[k][x].page == curPage)
-              {
-                if (!sockIds[k])
-                  sockIds[k] = [x];
-                else
-                  sockIds[k].push(x);
-              }
+        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" });
             });
-          });
-          socket.send(JSON.stringify({code:"pollclients", sockIds:sockIds}));
-          break;
-        }
-        case "pollgamers":
-        {
-          let sockIds = {};
-          Object.keys(clients).forEach(k => {
-            Object.keys(clients[k]).forEach(x => {
-              if ((k != sid || x != tmpId)
-                && clients[k][x].page.indexOf("/game/") >= 0)
-              {
-                if (!sockIds[k])
-                  sockIds[k] = [x];
-                else
-                  sockIds[k].push(x);
+            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 });
+            }
           });
-          socket.send(JSON.stringify({code:"pollgamers", sockIds:sockIds}));
           break;
         }
-        case "askidentity":
-        {
-          // Identity only depends on sid, so select a tmpId at random
-          const tmpIds = Object.keys(clients[obj.target]);
-          const tmpId_idx = Math.floor(Math.random() * tmpIds.length);
-          clients[obj.target][tmpIds[tmpId_idx]].sock.send(JSON.stringify(
-            {code:"askidentity",from:[sid,tmpId]}));
+        case "pollclients": {
+          // From Hall or Game
+          let sockIds = [];
+          Object.keys(clients[page]).forEach(k => {
+            // Avoid polling myself: no new information to get
+            if (k != sid) sockIds.push(k);
+          });
+          send(socket, { code: "pollclients", sockIds: sockIds });
           break;
         }
-        case "asklastate":
-          clients[obj.target[0]][obj.target[1]].sock.send(JSON.stringify(
-            {code:"asklastate",from:[sid,tmpId]}));
-          break;
-        case "askchallenge":
-          clients[obj.target[0]][obj.target[1]].sock.send(JSON.stringify(
-            {code:"askchallenge",from:[sid,tmpId]}));
-          break;
-        case "askgames":
-        {
-          // Check all clients playing, and send them a "askgame" message
-          // game ID --> [ sid1 --> array of tmpIds, sid2 --> array of tmpIds]
-          let gameSids = {};
-          const regexpGid = /\/[a-zA-Z0-9]+$/;
-          Object.keys(clients).forEach(k => {
-            Object.keys(clients[k]).forEach(x => {
-              if ((k != sid || x != tmpId)
-                && clients[k][x].page.indexOf("/game/") >= 0)
-            {
-              const gid = clients[k][x].page.match(regexpGid)[0];
-              if (!gameSids[gid])
-                gameSids[gid] = [{k: [x]}];
-              else if (k == Object.keys(gameSids[gid][0])[0])
-                gameSids[gid][0][k].push(x);
-              else if (gameSids[gid].length == 1)
-                gameSids[gid].push({k: [x]});
-              else
-                Object.values(gameSids[gid][1]).push(x);
-            }
+        case "pollclientsandgamers": {
+          // From Hall
+          let sockIds = [];
+          Object.keys(clients["/"]).forEach(k => {
+            // Avoid polling myself: no new information to get
+            if (k != sid) sockIds.push({sid:k});
           });
-          // Request only one client out of 2 (TODO: this is a bit heavy)
-          // Alt: ask game to all, and filter later?
-          Object.keys(gameSids).forEach(gid => {
-            const L = gameSids[gid].length;
-            const sidIdx = L > 1
-              ? Math.floor(Math.random() * Math.floor(L))
-              : 0;
-            const tmpIdx = Object.values(gameSids[gid][sidIdx]
-            const rid = gameSids[gid][sidIdx][tmpIdx];
-            clients[sidIdx][tmpIdx].sock.send(JSON.stringify(
-              {code:"askgame", from: [sid,tmpId]}));
+          // 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 });
+              });
+            }
           });
+          send(socket, { code: "pollclientsandgamers", sockIds: sockIds });
           break;
         }
+
+        // Asking something: from is fully identified,
+        // but the requested resource can be from any tmpId (except current!)
+        case "askidentity":
+        case "asklastate":
+        case "askchallenges":
         case "askgame":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"askgame", from:sid}));
-          break;
-        case "askfullgame":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"askfullgame", from:sid}));
-          break;
-        case "fullgame":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"fullgame", game:obj.game}));
-          break;
-        case "identity":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"identity",user:obj.user}));
+        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]) {
+            const 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] }
+            );
+          }
           break;
+        }
+
+        // Some Hall events: target all tmpId's (except mine),
         case "refusechallenge":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"refusechallenge", cid:obj.cid, from:sid}));
-          break;
-        case "deletechallenge":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"deletechallenge", cid:obj.cid, from:sid}));
+        case "startgame":
+          Object.keys(clients[page][obj.target]).forEach(x => {
+            if (obj.target != sid || x != tmpId)
+              send(
+                clients[page][obj.target][x].socket,
+                { code: obj.code, data: obj.data }
+              );
+          });
           break;
+
+        // Notify all room: mostly game events
+        case "newchat":
+        case "newchallenge":
+        case "deletechallenge_s":
         case "newgame":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid}));
+        case "resign":
+        case "abort":
+        case "drawoffer":
+        case "rematchoffer":
+        case "draw":
+          notifyRoom(page, obj.code, {data: obj.data});
           break;
-        case "challenge":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"challenge", chall:obj.chall, from:sid}));
+
+        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});
           break;
-        case "game":
-          if (!!obj.target)
-          {
-            clients[obj.target].sock.send(JSON.stringify(
-              {code:"game", game:obj.game, from:sid}));
-          }
-          else
-          {
-            // Notify all room except opponent and me:
-            notifyRoom("/", "game", {game:obj.game}, [obj.oppsid]);
+
+        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 "newchat":
-          notifyRoom(clients[sid].page, "newchat", {chat:obj.chat});
-          break;
-        // TODO: WebRTC instead in this case (most demanding?)
-        // --> Or else: at least do a "notifyRoom" (also for draw, resign...)
-        case "newmove":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"newmove", move:obj.move}));
+        }
+        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 "lastate":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"lastate", state:obj.state}));
+
+        case "result":
+          // Special case: notify all, 'transroom': Game --> Hall
+          notifyRoom("/", "result", { gid: obj.gid, score: obj.score });
           break;
-        case "resign":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"resign", side:obj.side}));
+
+        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 "abort":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"abort"}));
+        }
+
+        case "notifyscore":
+        case "notifyturn":
+        case "notifynewgame":
+          if (!!clients["/mygames"]) {
+            obj.targets.forEach(t => {
+              const k = t.sid || idToSid[t.id];
+              if (!!clients["/mygames"][k]) {
+                Object.keys(clients["/mygames"][k]).forEach(x => {
+                  send(
+                    clients["/mygames"][k][x].socket,
+                    { code: obj.code, data: obj.data }
+                  );
+                });
+              }
+            });
+          }
           break;
-        case "drawoffer":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"drawoffer"}));
+
+        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;
-        case "draw":
-          clients[obj.target].sock.send(JSON.stringify(
-            {code:"draw", message:obj.message}));
+
+        // Passing, relaying something: from isn't needed,
+        // but target is fully identified (sid + tmpId)
+        case "challenges":
+        case "fullgame":
+        case "game":
+        case "identity":
+        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
+          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;
+        }
       }
     };
     const closeListener = () => {
-      delete clients[sid];
+      // For browser or tab closing (including page reload):
+      doDisconnect();
     };
-    if (!!clients[sid])
-    {
-      // Turn off old sock through current client:
-      clients[sid].sock.send(JSON.stringify({code:"duplicate"}));
-    }
-    // Potentially replace current connection:
-    clients[sid] = {sock: socket, page: query["page"]};
+    // Update clients object: add new connexion
+    const newElt = { socket: socket, focus: true };
+    if (!clients[page])
+      clients[page] = { [sid]: {[tmpId]: newElt } };
+    else if (!clients[page][sid])
+      clients[page][sid] = { [tmpId]: newElt };
+    else
+      clients[page][sid][tmpId] = newElt;
+    // Also update helper correspondances
+    if (!idToSid[id]) idToSid[id] = sid;
+    if (!sidToPages[sid]) sidToPages[sid] = [];
+    const pgIndex = sidToPages[sid].findIndex(pg => pg == page);
+    if (pgIndex === -1) sidToPages[sid].push(page);
     socket.on("message", messageListener);
     socket.on("close", closeListener);
   });