server.js 8.3 KB

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