123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306 |
- 'use strict';
- import PlayerId from './players/player-id';
- import GamesManager from './game-server/games-manager';
- import MariadbConnector from './db/mariadb-connector';
- import ServerToolListner from './tools/server-tool-listener';
- function Server() {
- console.log('Starting 12 heroes server');
- const io = require('socket.io');
- const server = io.listen(2610);
- let mariadbConn = new MariadbConnector();
- let gamesManager = new GamesManager(server, mariadbConn);
- let authorizedPlayers = new Map();
- let connectedPlayers = new Map();
- let authorizedPlayersNames = new Set();
- server.on('connection', function(socket) {
- console.log('A player connected with id : ' + socket.id);
- socket.on('disconnect', reason => {
- console.log('A player disconnected, reason : ' + reason);
- if (
- reason === 'client namespace disconnect' ||
- reason === 'server namespace disconnect' ||
- reason === 'transport close'
- ) {
- let username = connectedPlayers.get(socket.id);
- if (username) {
- let player = authorizedPlayers.get(username);
- // First, tell game manager a player left, is he was playing
- if (player.isPlayingGameId >= 0) {
- gamesManager.playerLeft(player, true);
- }
- // If player had created a game, remove it
- removeAllGamesCreatedByPlayer(username)
- .then(res => {
- if (res.affectedRows > 0) {
- // Tell other clients to reload their games if there were
- forceClientsReloadGames();
- }
- })
- .catch(err => console.log('Error removing game :>> ', err.message));
- connectedPlayers.delete(socket.id);
- player.setConnected(false);
- player.setSocket(null);
- console.log(username + ' disconnected');
- }
- }
- });
- socket.on('connect', () => {
- console.log('Connected to server');
- });
- socket.on('auth', async (playerName, callback) => {
- console.log(' Received auth message, player name : ' + playerName);
- await updatePlayersFromDb();
- let response = {};
- let kickout = false;
- if (!authorizedPlayersNames.has(playerName)) {
- response = {
- res: 'ko',
- message: playerName + ' Not found'
- };
- kickout = true;
- }
- // If the player is already connected and active
- else if (
- authorizedPlayers.get(playerName).isConnected() &&
- authorizedPlayers.get(playerName).getSocket().connected
- ) {
- response = {
- res: 'ko',
- message: playerName + ' already connected'
- };
- kickout = true;
- } else {
- // 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
- try {
- await removeAllGamesCreatedByPlayer(playerName);
- } catch (err) {
- console.log('Error removing games : ' + err.message);
- }
- }
- response = {
- res: 'ok',
- message: playerName + ' connected'
- };
- authorizedPlayers.get(playerName).setConnected(true);
- authorizedPlayers.get(playerName).setSocket(socket);
- connectedPlayers.set(socket.id, playerName);
- }
- callback(response);
- if (kickout === true) {
- setTimeout(() => {
- socket.disconnect(true);
- }, 600);
- }
- });
- socket.on('games-list', async (playerName, callback) => {
- console.log(' Received games-list message, player name : ' + playerName);
- let response = {};
- try {
- let games = await getJoinableGames(playerName);
- response = {
- res: 'ok',
- message: games
- };
- } catch (error) {
- response = {
- res: 'ko',
- message: 'Error from server'
- };
- }
- callback(response);
- });
- socket.on('create-game', async (game, callback) => {
- let response = {};
- try {
- let id = await addGameDb(game);
- response = {
- res: 'ok',
- message: id
- };
- gamesManager.addPlayerInGame(
- authorizedPlayers.get(connectedPlayers.get(socket.id)),
- id,
- false
- );
- console.log('Force all clients to reload their games');
- forceClientsReloadGames();
- } catch (error) {
- console.log('error in create-game:>> ', error);
- response = {
- res: 'ko',
- message: 'Error from server'
- };
- }
- callback(response);
- });
- socket.on('join-game', async (gameDetails, callback) => {
- let result = gamesManager.addPlayerInGame(
- authorizedPlayers.get(connectedPlayers.get(socket.id)),
- gameDetails.id,
- gameDetails.joinCreatedGame
- );
- let response = {};
- if (result === true) {
- response.res = 'ok';
- response.message = 'Game joined';
- } else {
- response.res = 'ko';
- response.message = 'Unable to join game';
- }
- callback(response);
- });
- socket.on('leave-game', async (username, callback) => {
- // Remove player from game he is playing
- gamesManager.playerLeft(authorizedPlayers.get(username), false);
- try {
- let res = removeAllGamesCreatedByPlayer(username);
- if (res.affectedRows > 0) {
- forceClientsReloadGames();
- }
- } catch (err) {
- console.log('Error removing games : ' + err.message);
- }
- callback(true);
- });
- });
- let updatePlayersFromDb = async function() {
- try {
- let usernames = await mariadbConn.getUsernames();
- authorizedPlayersNames = new Set(usernames);
- console.log('authorizedPlayersNames update : ', authorizedPlayersNames);
- authorizedPlayersNames.forEach(name => {
- if (!authorizedPlayers.has(name)) {
- console.log('New username authorized :', name);
- authorizedPlayers.set(name, new PlayerId(name));
- }
- });
- return 'ok';
- } catch (error) {
- console.log('Error getting usernames from DB : ', error);
- return error.Error;
- }
- };
- let getCurrentListAuthorizedPlayers = function() {
- return [...authorizedPlayersNames];
- };
- let addPlayerDb = async function(username) {
- console.log('add player in db : ' + username);
- try {
- let response = await mariadbConn.addPlayer(username);
- authorizedPlayersNames.add(username);
- authorizedPlayers.set(username, new PlayerId(username));
- return 'OK ' + JSON.stringify(response);
- } catch (err) {
- return 'KO ' + err.message;
- }
- };
- let removePlayerDb = async function(username) {
- console.log('remove player in db : ' + username);
- try {
- let response = await mariadbConn.removePlayer(username);
- authorizedPlayersNames.delete(username);
- authorizedPlayers.delete(username);
- return 'OK ' + JSON.stringify(response);
- } catch (err) {
- return 'KO ' + err.message;
- }
- };
- let addGameDb = async function(game) {
- try {
- let response = await mariadbConn.addNewGame(game);
- return response;
- } catch (err) {
- console.log('KO ' + err.message);
- throw err;
- }
- };
- let removeGameDb = async function(method, ...args) {
- try {
- let response;
- switch (method) {
- case 'byId':
- response = await mariadbConn.removeGameById(args[0]);
- break;
- case 'byPlayer1':
- response = await mariadbConn.removeGamesByPlayer1(args[0]);
- break;
- case 'byPlayerAny':
- response = await mariadbConn.removeGamesByPlayerAny(args[0]);
- break;
- case 'byStatus':
- response = await mariadbConn.removeGamesByStatus(args[0]);
- break;
- case 'byDays':
- response = await mariadbConn.removeGamesByDays(args[0]);
- break;
- case 'finishedByDays':
- response = await mariadbConn.removeFinishedGamesByDays(args[0]);
- break;
- default:
- return 'KO : Unknown method to remove game from DB : ' + method;
- }
- return 'OK ' + JSON.stringify(response);
- } catch (err) {
- return 'KO ' + err.message;
- }
- };
- let getJoinableGames = async function(username) {
- try {
- let games = await mariadbConn.getJoinableGamesForPlayer(username);
- return games;
- } catch (err) {
- console.log('KO : not able to get games : ' + err);
- throw err;
- }
- };
- let removeAllGamesCreatedByPlayer = async function(playerName) {
- let result = await mariadbConn.removeCreatedGamesByPlayer1(playerName);
- return result;
- };
- let forceClientsReloadGames = function() {
- server.emit('reload-games-list');
- };
- return {
- updatePlayersFromDb,
- getCurrentListAuthorizedPlayers,
- addPlayerDb,
- removePlayerDb,
- addGameDb,
- removeGameDb,
- getJoinableGames
- };
- }
- let server = new Server();
- let serverToolListner = new ServerToolListner(server);
- serverToolListner.listen(1664);
|