server.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. 'use strict';
  2. import PlayerId from './players/player-id';
  3. import DuelController from './game-server/duel-controller';
  4. import MariadbConnector from './db/mariadb-connector';
  5. import ServerToolListner from './tools/server-tool-listener';
  6. function Server() {
  7. console.log('Starting 12 heroes server');
  8. const io = require('socket.io');
  9. const server = io.listen(2610);
  10. let mariadbConn = new MariadbConnector();
  11. let authorizedPlayers = new Map();
  12. let connectedPlayers = new Map();
  13. let authorizedPlayersNames = new Set();
  14. // let players = [];
  15. // let addNewPlayer = function (playerSocket, playerName) {
  16. // console.log('players length : ' + players.length + ' : ' + players);
  17. // if (players.length < 2) {
  18. // let newPlayer = new PlayerId(playerSocket, playerName);
  19. // console.log('push player : ' + newPlayer);
  20. // players.push(newPlayer);
  21. // }
  22. // if (players.length === 2) {
  23. // let duelController = new DuelController(players[0], players[1]);
  24. // }
  25. // };
  26. server.on('connection', function (socket) {
  27. console.log("A player connected with id : " + socket.id);
  28. socket.on('disconnect', (reason) => {
  29. removeAllGamesCreatedByPlayer(connectedPlayers.get(socket.id));
  30. forceClientsReloadGames();
  31. if (reason === 'client namespace disconnect') {
  32. console.log("A player disconnected with id : " + socket.id);
  33. let playerName = connectedPlayers.get(socket.id);
  34. if (playerName) {
  35. connectedPlayers.delete(socket.id);
  36. authorizedPlayers.get(playerName).setConnected(false);
  37. authorizedPlayers.get(playerName).setSocket(null);
  38. console.log(playerName + " disconnected");
  39. }
  40. } else {
  41. console.log("disconnected unexpectidly with reason : " + reason);
  42. }
  43. });
  44. socket.on('connect', () => {
  45. console.log("Connected to server");
  46. });
  47. socket.on('auth', async (playerName, callback) => {
  48. console.log(' Received auth message, player name : ' + playerName);
  49. await updatePlayersFromDb();
  50. let response = {};
  51. let kickout = false;
  52. if (!authorizedPlayersNames.has(playerName)) {
  53. response = {
  54. res: "ko",
  55. message: playerName + " Not found"
  56. };
  57. kickout = true;
  58. }
  59. // If the player is already connected and active
  60. else if (authorizedPlayers.get(playerName).isConnected()
  61. && authorizedPlayers.get(playerName).getSocket().connected) {
  62. response = {
  63. res: "ko",
  64. message: playerName + " already connected"
  65. };
  66. kickout = true;
  67. }
  68. else {
  69. // Player marked as connected but socket is down, clean it
  70. if (authorizedPlayers.get(playerName).isConnected()) {
  71. authorizedPlayers.get(playerName).getSocket().disconnect(true);
  72. } else {
  73. // In case server did not detect disconnection and did not clean the pending created games
  74. removeAllGamesCreatedByPlayer(playerName);
  75. }
  76. response = {
  77. res: "ok",
  78. message: playerName + " connected"
  79. };
  80. authorizedPlayers.get(playerName).setConnected(true);
  81. authorizedPlayers.get(playerName).setSocket(socket);
  82. connectedPlayers.set(socket.id, playerName);
  83. }
  84. callback(response);
  85. if (kickout === true) {
  86. setTimeout(() => {
  87. socket.disconnect(true);
  88. }, 600);
  89. }
  90. });
  91. socket.on('games-list', async (playerName, callback) => {
  92. console.log(' Received games-list message, player name : ' + playerName);
  93. let response = {};
  94. try {
  95. let games = await getJoinableGames(playerName);
  96. response = {
  97. res: "ok",
  98. message: games
  99. };
  100. } catch (error) {
  101. response = {
  102. res: "ko",
  103. message: 'Error from server'
  104. };
  105. }
  106. callback(response);
  107. });
  108. socket.on('create-game', async (game, callback) => {
  109. let response = {};
  110. try {
  111. let id = await addGameDb(game);
  112. response = {
  113. res: "ok",
  114. message: id
  115. };
  116. console.log('Force all clients to reload their games');
  117. forceClientsReloadGames();
  118. } catch (error) {
  119. response = {
  120. res: "ko",
  121. message: 'Error from server'
  122. };
  123. }
  124. callback(response);
  125. });
  126. });
  127. let updatePlayersFromDb = async function () {
  128. try {
  129. let usernames = await mariadbConn.getUsernames();
  130. authorizedPlayersNames = new Set(usernames);
  131. console.log('authorizedPlayersNames update : ', authorizedPlayersNames);
  132. authorizedPlayersNames.forEach(name => {
  133. if (!authorizedPlayers.has(name)) {
  134. console.log('New username authorized :', name);
  135. authorizedPlayers.set(name, new PlayerId(name));
  136. }
  137. });
  138. return 'ok';
  139. } catch (error) {
  140. console.log('Error getting usernames from DB : ', error);
  141. return error.Error;
  142. }
  143. };
  144. let getCurrentListAuthorizedPlayers = function () {
  145. return [...authorizedPlayersNames];
  146. };
  147. let addPlayerDb = async function (username) {
  148. console.log('add player in db : ' + username);
  149. try {
  150. let response = await mariadbConn.addPlayer(username);
  151. authorizedPlayersNames.add(username);
  152. authorizedPlayers.set(username, new PlayerId(username));
  153. return 'OK ' + JSON.stringify(response);
  154. } catch (err) {
  155. return 'KO ' + err.message;
  156. }
  157. };
  158. let removePlayerDb = async function (username) {
  159. console.log('remove player in db : ' + username);
  160. try {
  161. let response = await mariadbConn.removePlayer(username);
  162. authorizedPlayersNames.delete(username);
  163. authorizedPlayers.delete(username);
  164. return 'OK ' + JSON.stringify(response);
  165. } catch (err) {
  166. return 'KO ' + err.message;
  167. }
  168. };
  169. let addGameDb = async function (game) {
  170. try {
  171. let response = await mariadbConn.addNewGame(game);
  172. return response;
  173. } catch (err) {
  174. console.log('KO ' + err.message);
  175. throw err;
  176. }
  177. };
  178. let removeGameDb = async function (method, ...args) {
  179. try {
  180. let response;
  181. switch (method) {
  182. case 'byId':
  183. response = await mariadbConn.removeGameById(args[0]);
  184. break;
  185. case 'byPlayer1':
  186. response = await mariadbConn.removeGamesByPlayer1(args[0]);
  187. break;
  188. case 'byPlayerAny':
  189. response = await mariadbConn.removeGamesByPlayerAny(args[0]);
  190. break;
  191. case 'byStatus':
  192. response = await mariadbConn.removeGamesByStatus(args[0]);
  193. break;
  194. case 'byDays':
  195. response = await mariadbConn.removeGamesByDays(args[0]);
  196. break;
  197. case 'finishedByDays':
  198. response = await mariadbConn.removeFinishedGamesByDays(args[0]);
  199. break;
  200. default:
  201. return 'KO : Unknown method to remove game from DB : ' + method;
  202. }
  203. return 'OK ' + JSON.stringify(response);
  204. } catch (err) {
  205. return 'KO ' + err.message;
  206. }
  207. };
  208. let getJoinableGames = async function (username) {
  209. try {
  210. let games = await mariadbConn.getJoinableGamesForPlayer(username);
  211. return games;
  212. } catch (err) {
  213. console.log('KO : not able to get games : ' + err);
  214. throw err;
  215. }
  216. };
  217. let removeAllGamesCreatedByPlayer = async function(playerName) {
  218. try {
  219. let result = await mariadbConn.removeCreatedGamesByPlayer1(playerName);
  220. return result;
  221. } catch (err) {
  222. console.log('KO : not able to remove created games : ' + err);
  223. throw err;
  224. }
  225. };
  226. let forceClientsReloadGames = function () {
  227. server.emit('reload-games-list');
  228. };
  229. return {
  230. updatePlayersFromDb,
  231. getCurrentListAuthorizedPlayers,
  232. addPlayerDb,
  233. removePlayerDb,
  234. addGameDb,
  235. removeGameDb,
  236. getJoinableGames
  237. };
  238. }
  239. let server = new Server();
  240. let serverToolListner = new ServerToolListner(server);
  241. serverToolListner.listen(1664);