Browse Source

notify new games created & clean created if user disconnects

jojo 5 years ago
parent
commit
2972e08446

+ 5 - 0
server/db/mariadb-connector.js

@@ -59,6 +59,7 @@ export default class MariadbConnector {
       conn = await this.pool.getConnection();
       const val = await conn.query("INSERT INTO players value (?, NOW(),NULL)", [username]);
       console.log('OK removing player : ', val);
+
       return val;
     } catch (err) {
       console.log('error adding player : ', err);
@@ -99,6 +100,7 @@ export default class MariadbConnector {
         convertAdvRulesToString(game.advRules),
         game.status,
         game.data]);
+
       console.log('OK adding game : ', val);
       return val.insertId;
     } catch (err) {
@@ -129,6 +131,9 @@ export default class MariadbConnector {
   removeFinishedGamesByDays(days) {
     return this.removeGame("DELETE FROM games WHERE status='FINISHED' AND datediff(NOW(),last_played) > ?", [days]);
   }
+  removeCreatedGamesByPlayer1(player1Name) {
+    return this.removeGame("DELETE FROM games WHERE player1=? AND status='CREATED'", [player1Name]);
+  }
 
   async removeGame(queryStr, queryArgs) {
     console.log('mariadb remove game  : ', queryStr);

+ 27 - 5
server/server.js

@@ -39,6 +39,8 @@ function Server() {
     console.log("A player connected with id : " + socket.id);
 
     socket.on('disconnect', (reason) => {
+      removeAllGamesCreatedByPlayer(connectedPlayers.get(socket.id));
+      forceClientsReloadGames();
       if (reason === 'client namespace disconnect') {
         console.log("A player disconnected with id : " + socket.id);
         let playerName = connectedPlayers.get(socket.id);
@@ -79,9 +81,12 @@ function Server() {
         kickout = true;
       }
       else {
-        // Player marked as connected but socket is down
+        // Player marked as connected but socket is down, clean it
         if (authorizedPlayers.get(playerName).isConnected()) {
           authorizedPlayers.get(playerName).getSocket().disconnect(true);
+        } else {
+          // In case server did not detect disconnection and did not clean the pending created games
+          removeAllGamesCreatedByPlayer(playerName);
         }
         response = {
           res: "ok",
@@ -122,11 +127,13 @@ function Server() {
     socket.on('create-game', async (game, callback) => {
       let response = {};
       try {
-        let games = await addGameDb(game);
+        let id = await addGameDb(game);
         response = {
           res: "ok",
-          message: games
+          message: id
         };
+        console.log('Force all clients to reload their games');
+        forceClientsReloadGames();
       } catch (error) {
         response = {
           res: "ko",
@@ -188,9 +195,10 @@ function Server() {
 
     try {
       let response = await mariadbConn.addNewGame(game);
-      return 'OK ' + JSON.stringify(response);
+      return response;
     } catch (err) {
-      return 'KO ' + err.message;
+      console.log('KO ' + err.message);
+      throw err;
     }
   };
 
@@ -237,6 +245,20 @@ function Server() {
     }
   };
 
+  let removeAllGamesCreatedByPlayer = async function(playerName) {
+    try {
+      let result = await mariadbConn.removeCreatedGamesByPlayer1(playerName);
+      return result;
+    } catch (err) {
+      console.log('KO : not able to remove created games : ' + err);
+      throw err;
+    }
+  };
+
+  let forceClientsReloadGames = function () {
+  server.emit('reload-games-list');
+  };
+
   return {
     updatePlayersFromDb,
     getCurrentListAuthorizedPlayers,

+ 8 - 2
server/tools/server-tool-listener.js

@@ -35,8 +35,14 @@ export default class ServerToolListner {
       });
 
       socket.on('add-game', async (game,callback) =>  {
-        let response = await server.addGameDb(...game);
-        callback(response);
+        let response='';
+        try {
+          response = await server.addGameDb(...game);
+          response = "OK - inserted at id :" + response;
+        } catch(err) {
+          response= 'KO ' + err.message;
+        }
+        callback(JSON.stringify(response));
         socket.disconnect(false);
       });
       socket.on('remove-game', async (options,callback) =>  {

+ 11 - 6
src/common/socket-service.js

@@ -16,16 +16,15 @@ const SERVER_PORT = process.env.SERVER_PORT;
 
 export default class SocketService {
   constructor() {
-    this.lostConnectionListeners = new Set();
+    this.newGameCreatedListenerCb=null;
   }
 
-  addlostConnectionListener(listener) {
-    this.lostConnectionListeners.add(listener);
+  setNewGameCreatedListener(callback) {
+    this.newGameCreatedListenerCb = callback;
   }
 
-
-  removelostConnectionListener(listener) {
-    this.lostConnectionListeners.delete(listener);
+  unsetNewGameCreatedListener() {
+    this.newGameCreatedListenerCb=null;
   }
 
   connect(name) {
@@ -61,6 +60,12 @@ export default class SocketService {
         reject('Cannot reach server');
       });
 
+      this.ioClient.on('reload-games-list', () => {
+        console.log("force reload games list !");
+        if(this.newGameCreatedListenerCb !== null) {
+          this.newGameCreatedListenerCb();
+        }
+      });
     });
     return promise;
   }

+ 9 - 1
src/menu/control/menu-controller.js

@@ -37,7 +37,9 @@ export default class MenuController {
       onOnlineGamesListRequested: this.onOnlineGamesListRequested.bind(this),
       onTryConnect: this.tryConnect.bind(this),
       onRequestDisconnection: this.onRequestDisconnection.bind(this),
-      onGameCreationRequest: this.onGameCreationRequest.bind(this)
+      onGameCreationRequest: this.onGameCreationRequest.bind(this),
+      onSetNewGameListenerCb: this.onSetNewGameListenerCb.bind(this),
+      onUnsetNewGameListenerCb: this.onSetNewGameListenerCb.bind(this)
     };
   }
 
@@ -63,4 +65,10 @@ export default class MenuController {
     };
     return this.socketService.createGame(game);
   }
+  onSetNewGameListenerCb(callback) {
+    this.socketService.setNewGameCreatedListener(callback);
+  }
+  onUnsetNewGameListenerCb() {
+    this.socketService.unsetNewGameCreatedListener();
+  }
 }

+ 20 - 7
src/menu/views/main-menu-scene.js

@@ -78,7 +78,9 @@ export default class MainMenuScene extends Phaser.Scene {
     return {
       onRequestOnlineGamesList: this.onRequestOnlineGamesList.bind(this),
       onGoGameCreation: this.onGoGameCreation.bind(this),
-      onGoPreviousPage: this.onGoPreviousPage.bind(this)
+      onGoPreviousPage: this.onGoPreviousPage.bind(this),
+      onSetNewGameListenerCb: this.onSetNewGameListenerCb.bind(this),
+      onUnsetNewGameListenerCb: this.onSetNewGameListenerCb.bind(this)
     };
   }
 
@@ -87,6 +89,7 @@ export default class MainMenuScene extends Phaser.Scene {
     return {
       onGoPreviousPage: this.onGoPreviousPage.bind(this),
       onValidGameCreation: this.onValidGameCreation.bind(this),
+      onGameCreated:this.onGameCreated.bind(this)
     };
   }
 
@@ -96,10 +99,6 @@ export default class MainMenuScene extends Phaser.Scene {
     this.previousPages.pop().show();
   }
 
-  onValidGameCreation(deckModeSelected, advancedOptions) {
-    return this.menuEventListener.onGameCreationRequest(this.username, deckModeSelected, advancedOptions);
-  }
-
   // Login page specific
   onGoOnlineRoom() {
 
@@ -127,9 +126,23 @@ export default class MainMenuScene extends Phaser.Scene {
     this.gameCreationDivPage.show();
   }
 
-  // Game cration specific
-  onGameCreated() {
+  onSetNewGameListenerCb(callback) {
+    this.menuEventListener.onSetNewGameListenerCb(callback);
+  }
+  onUnsetNewGameListenerCb() {
+    this.menuEventListener.onUnsetNewGameListenerCb();
+  }
 
+
+  // Game cration div page specific
+
+  onValidGameCreation(deckModeSelected, advancedOptions) {
+    return this.menuEventListener.onGameCreationRequest(this.username, deckModeSelected, advancedOptions);
+  }
+
+  onGameCreated() {
+    console.log('Game created, send user to game scene');
+    this.gameCreationDivPage.hide();
     // let gameDeckMode = "factions";
     // let advancedRules = [];
     // console.log("Calling listener");

+ 13 - 1
src/menu/views/menu-pages/game-creation-div-page.js

@@ -24,9 +24,21 @@ export default function GameCreationDivPage(element, listener) {
           break;
 
         case "validGameCreation":
+          divSelectDeckMode.selectedIndex=0;
+          createGameButton.disabled=true;
           console.log(deckModeSelected);
           console.log(advancedOptions);
-          listener.onValidGameCreation(deckModeSelected, advancedOptions);
+          listener.onValidGameCreation(deckModeSelected, advancedOptions)
+            .then( () => {
+
+              listener.onGameCreated();
+            })
+            .catch( () => {
+              createGameButton.value='Server Error !';
+              setTimeout(() => {
+                createGameButton.value='CREATE';
+              }, 3000);
+            });
           break;
         case "discard":
         case "popularity":

+ 73 - 54
src/menu/views/menu-pages/online-room-div-page.js

@@ -2,8 +2,8 @@ import * as DivCommon from './div-page-common';
 
 export default function OnlineRoomDivPage(element, listener) {
 
-  const id='online-room';
-  const className=OnlineRoomDivPage.name;
+  const id = 'online-room';
+  const className = OnlineRoomDivPage.name;
   let div = element.getChildByID(id);
 
   let createOnlineGameButton = element.getChildByName('createOnlineGame');
@@ -13,7 +13,7 @@ export default function OnlineRoomDivPage(element, listener) {
   let connectionStatus = element.getChildByID('connectionStatusOnline');
   let loaderOnlineGames = element.getChildByID('loader-online-games');
 
-  let eventListener = function(event) {
+  let eventListener = function (event) {
     let eventName = event.target.name;
     switch (eventName) {
       case "backToMain":
@@ -30,66 +30,85 @@ export default function OnlineRoomDivPage(element, listener) {
 
   };
 
-  div.addEventListener('click',eventListener);
+  div.addEventListener('click', eventListener);
 
-  let onShow = function() {
+  let onShow = function () {
     listener.onRequestOnlineGamesList()
-      .then( (games) => {
+      .then((games) => {
         console.log('received games : ', games);
-
-        while(listOnlineGames.firstChild) listOnlineGames.removeChild(listOnlineGames.firstChild);
-        console.log('removed ex list');
-        games.forEach(game => {
-          console.log(game);
-          let title='';
-          let desc='';
-          let rules= '';
-          if (game.adv_rules.length !== 0) {
-            game.adv_rules.forEach(rule => {
-              rules += ' + ' + rule;
-            });
-          } else {
-            rules= ' + no adv. rules';
-          }
-          desc=`${game.deck}${rules}`;
-          if (game.player2 !== '') {
-            title=`Resume ${game.player1} VS ${game.player2}`;
-          } else {
-            title=`${game.player1} waiting...`;
-          }
-          let li = document.createElement("li");
-          let spanTitle = document.createElement("span");
-          let spanDesc = document.createElement("span");
-          let div = document.createElement("div");
-          spanTitle.setAttribute("class", "game-entry-title");
-          spanDesc.setAttribute("class", "game-entry-desc");
-          spanTitle.appendChild(document.createTextNode(title));
-          spanDesc.appendChild(document.createTextNode(desc));
-          li.appendChild(spanTitle);
-          li.appendChild(div);
-          li.appendChild(spanDesc);
-          li.setAttribute("id",game.id);
-          listOnlineGames.appendChild(li);
-        });
-        loaderOnlineGames.style.display= 'none';
-        listOnlineGames.style.display= 'block';
+        displayGamesList(games);
+        loaderOnlineGames.style.display = 'none';
+        listOnlineGames.style.display = 'block';
       })
-      .catch( (error) => {
-        loaderOnlineGames.style.display= 'none';
-        listOnlineGames.style.display= 'block';
-        listOnlineGames.innerText=error;
-        connectionStatus.innerText=error;
-        createOnlineGameButton.disabled=true;
+      .catch((error) => {
+        loaderOnlineGames.style.display = 'none';
+        listOnlineGames.style.display = 'block';
+        listOnlineGames.innerText = error;
+        connectionStatus.innerText = error;
+        createOnlineGameButton.disabled = true;
         console.log('error to receive games : ' + error);
       });
+
+    listener.onSetNewGameListenerCb(reloadGamesCallback);
+  };
+
+  let onHide = function () {
+    listener.onUnsetNewGameListenerCb();
+    listOnlineGames.style.display = 'none';
+    loaderOnlineGames.style.display = 'block';
+    createOnlineGameButton.disabled = false;
+    listOnlineGames.innerText = '';
   };
 
-  let onHide = function() {
+  let displayGamesList = function (games) {
+    console.log(games);
+
+    while (listOnlineGames.firstChild) listOnlineGames.removeChild(listOnlineGames.firstChild);
+    console.log('removed ex list');
+    games.forEach(game => {
 
-    listOnlineGames.style.display= 'none';
-    loaderOnlineGames.style.display= 'block';
-    createOnlineGameButton.disabled=false;
-    listOnlineGames.innerText='';
+      let title = '';
+      let desc = '';
+      let rules = '';
+      if (game.adv_rules.length !== 0) {
+        game.adv_rules.forEach(rule => {
+          rules += ' + ' + rule;
+        });
+      } else {
+        rules = ' + no adv. rules';
+      }
+      desc = `${game.deck}${rules}`;
+      if (game.player2 !== '') {
+        title = `Resume ${game.player1} VS ${game.player2}`;
+      } else {
+        title = `${game.player1} waiting...`;
+      }
+      let li = document.createElement("li");
+      let spanTitle = document.createElement("span");
+      let spanDesc = document.createElement("span");
+      let div = document.createElement("div");
+      spanTitle.setAttribute("class", "game-entry-title");
+      spanDesc.setAttribute("class", "game-entry-desc");
+      spanTitle.appendChild(document.createTextNode(title));
+      spanDesc.appendChild(document.createTextNode(desc));
+      li.appendChild(spanTitle);
+      li.appendChild(div);
+      li.appendChild(spanDesc);
+      li.setAttribute("id", game.id);
+      listOnlineGames.appendChild(li);
+    });
+  };
+
+  let reloadGamesCallback = function () {
+
+    listener.onRequestOnlineGamesList()
+      .then((games) => {
+        console.log('received games : ', games);
+        displayGamesList(games);
+      })
+      .catch((error) => {
+        console.log('error to receive games : ' + error);
+      });
   };
 
   let onlineRoomDivPage = {