Ejemplo n.º 1
0
        /// <summary>
        /// Obtient le token de la game en cours.
        /// </summary>
        /// <param name="room">Room</param>
        /// <returns>null si aucune partie. Sinon le Guid :^)</returns>
        public Guid?GetCurrentGameToken(Guid room)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    Room r = context.Room.First(p => p.Token == room);

                    if (!r.Started)
                    {
                        return(null);
                    }

                    var lstPRS = r.PlayerRoomState;

                    foreach (PlayerRoomState prs in lstPRS)
                    {
                        DateTime hb = context.LoggedInUser.First(p => p.UserId == prs.UserId).LastHeartbeat;
                        hb.AddSeconds(30);
                    }

                    return(r.Game.Token);
                }
            }
            catch
            {
            }

            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Envoie un nouveau message.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="message"></param>
        /// <returns>True si succès.</returns>
        public bool SendPrivateMessage(Guid from, string to, string message)
        {
            bool ok = false;

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser user       = context.LoggedInUser.First(p => p.Token == from);
                    int          receiverId = context.User.First(p => p.Name.Trim() == to.Trim()).UserId;

                    PrivateMessage pm = new PrivateMessage();
                    pm.Message        = message.Trim();
                    pm.Read           = false;
                    pm.ReceiverUserId = receiverId;
                    pm.SenderUserId   = user.UserId;
                    pm.SentTime       = DateTime.UtcNow;

                    context.PrivateMessage.Add(pm);
                    context.SaveChanges();

                    ok = true;
                }
            }
            catch
            {
            }

            return(ok);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Envoie un mess
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <param name="message"></param>
        /// <returns>True si envoyé avec succès.</returns>
        public bool SendGlobalMessage(Guid player, string message)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int userId = context.LoggedInUser.Where(p => p.Token == player)
                                 .ToList().First().UserId;

                    Message msg = new Message();
                    msg.Content = message;
                    msg.Date    = DateTime.UtcNow;
                    msg.UserId  = userId;
                    msg.Type    = MessageType.GLOBAL;

                    context.Message.Add(msg);
                    context.SaveChanges();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Obtient la liste des salles actuellement ouverte.
        /// </summary>
        /// <returns>Liste des salles.</returns>
        public List <Models.RoomInfo> GetOpenRoomsInfo()
        {
            List <Models.RoomInfo> lstRoomsInfo = new List <Models.RoomInfo>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var lstRooms = context.Room.Where(p => p.Started == false);

                    foreach (var room in lstRooms)
                    {
                        RoomInfo ri = new RoomInfo();
                        ri.MasterName = context.User.Find(room.MasterUserId).Name;
                        ri.Name       = room.Name;
                        ri.Token      = room.Token;

                        lstRoomsInfo.Add(ri);
                    }
                }
            }
            catch
            {
            }

            return(lstRoomsInfo);
        }
Ejemplo n.º 5
0
        public UserMessage[] GetGameMessagesSinceDate(Guid gameToken, DateTime sinceDateUtc)
        {
            using (var context = new MilleBornesEntities())
            {
                var game = context.Game
                           .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                var messagesSinceDate = game.Message
                                        .Where(msg => msg.Date > sinceDateUtc)
                                        .Select(msg => new UserMessage()
                {
                    Username = msg.User.Name,
                    Date     = msg.Date,
                    Content  = msg.Content
                })
                                        .ToArray();

                return(messagesSinceDate);
            }
        }
Ejemplo n.º 6
0
        public void TakePlayerDisconnectionDecision(Guid playerToken, Guid gameToken, bool continueGame)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                                   .Where(us => us.LoggedInUser != null)
                                   .SingleOrDefault(us => us.LoggedInUser.Token == playerToken);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var game = context.Game
                           .SingleOrDefault(rm => rm.Token == gameToken);
                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                if (game.Room == null)
                {
                    throw new FaultException("La partie n'est pas associée à une salle.");
                }

                if (game.Room.Count > 1)
                {
                    throw new FaultException("La partie est associée à plusieurs salles.");
                }

                if (game.Room.First().MasterUserId != playerEntity.UserId)
                {
                    throw new FaultException("Seul le maître de la salle peut prendre la décision.");
                }

                if (!game.IsTakingDisconnectDecision)
                {
                    throw new FaultException("La partie n'est pas en attente d'une décision.");
                }

                if (continueGame)
                {
                    var disconnectedPlayers = GetPlayersInGame(game)
                                              .Where(pg => !ValidatePlayerHeartbeat(pg));

                    foreach (var player in disconnectedPlayers)
                    {
                        player.Order = -player.Order;
                    }

                    game.IsTakingDisconnectDecision = false;
                }
                else
                {
                    EndGame(game, GameEndReason.PLAYER_DISCONNECTION);
                    game.IsTakingDisconnectDecision = false;
                }

                context.SaveChanges();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Set un joueur "prêt".
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <param name="ready"></param>
        /// <returns>True si succès, false autrement</returns>
        public bool SetReady(Guid player, bool ready)
        {
            try
            {
                using (MilleBornesEntities tities = new MilleBornesEntities())
                {
                    LoggedInUser    liu     = tities.LoggedInUser.First(p => p.Token == player);
                    PlayerRoomState prsUser = tities.PlayerRoomState.First(p => p.UserId == liu.UserId);
                    prsUser.IsReady = ready;

                    tities.SaveChanges();

                    if (ready)
                    {
                        SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), prsUser.Room.Token, "**" + prsUser.User.Name + " est prêt! ☺**");
                    }
                    else
                    {
                        SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), prsUser.Room.Token, "**" + prsUser.User.Name + " n'est pas prêt! ☹**");
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Défini l'équipe laquelle le joueur join.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <param name="team"></param>
        /// <returns></returns>
        public bool SetTeam(Guid player, Guid room, int team)
        {
            if (team > 2)
            {
                return(false);
            }

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var user = context.LoggedInUser
                               .First(p => p.Token == player);

                    PlayerRoomState prs = context.PlayerRoomState.First(p => p.UserId == user.UserId);
                    prs.Team = team;

                    context.SaveChanges();

                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"),
                                    room,
                                    "**Le joueur " + user.User.Name + " a rejoint l'équipe #" + (team + 1).ToString() + ". **");

                    return(true);
                }
            }
            catch
            {
            }

            return(false);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Vérifie si il y a de nouveaux messages pour l'utilisateur.
        /// </summary>
        /// <param name="player"></param>
        /// <returns>Renvoie une liste de username de gens qui ont des messages.</returns>
        public List <string> DoTheBigBastardThatWaveHisFlagHasNewMessageFromSomeoneIfSoTellMeLad(Guid player)
        {
            List <string> lstUsers = new List <string>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser liu = context.LoggedInUser.First(p => p.Token == player);

                    var pms = context.PrivateMessage.Where(p => p.Receiver.UserId == liu.UserId &&
                                                           p.Read == false);

                    HashSet <string> temp = new HashSet <string>();

                    foreach (PrivateMessage pm in pms)
                    {
                        temp.Add(pm.Sender.Name);
                    }

                    lstUsers = temp.ToList();
                }
            }
            catch
            {
            }

            return(lstUsers);
        }
Ejemplo n.º 10
0
        public Guid CreateGame(Guid player, Guid room)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                                   .Where(us => us.LoggedInUser != null)
                                   .SingleOrDefault(us => us.LoggedInUser.Token == player);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var roomEntity = context.Room
                                 .SingleOrDefault(rm => rm.Token == room);
                if (roomEntity == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                if (roomEntity.MasterUserId != playerEntity.UserId)
                {
                    throw new FaultException("Seul le maître de la salle peut démarrer la partie.");
                }

                var newGame = new Game()
                {
                    Token     = Guid.NewGuid(),
                    StartDate = DateTime.UtcNow,
                    IsTakingDisconnectDecision = false
                };

                FillPlayerConfig(context, roomEntity, newGame);

                roomEntity.Game    = newGame;
                roomEntity.Started = true;
                context.Game.Add(newGame);
                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    throw;
                }

                InitializeGame(newGame);
                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    throw;
                }

                return(newGame.Token);
            }
        }
Ejemplo n.º 11
0
        private static void FillPlayerConfig(MilleBornesEntities context, Room roomEntity, Game newGame)
        {
            // Essayer en premier lieu avec le service, sinon
            // regarder directement dans la base de données.

            List <PlayerGame> playerGameSource = new List <PlayerGame>();

#if false
            try
            {
                using (var client = new LobbyGameProxy.LobbyServiceClient())
                {
                    var configEntries = client.GetPlayerConfig(roomEntity.Token);

                    foreach (var entry in configEntries)
                    {
                        var user = context.User
                                   .Where(us => us.LoggedInUser != null)
                                   .SingleOrDefault(us => us.LoggedInUser.Token == entry.UserToken);

                        if (user == null)
                        {
                            continue;
                        }

                        var playerGame = new PlayerGame()
                        {
                            Game          = newGame,
                            UserId        = user.UserId,
                            User          = user,
                            LastHeartbeat = DateTime.UtcNow,
                            Order         = entry.Order,
                            Team          = entry.Team + 1,
                            HasJoined     = user.UserId == roomEntity.MasterUserId
                        };
                    }
                }
            }
#endif
            //catch (Exception ex)
            //{
            playerGameSource = roomEntity.PlayerRoomState.Select((prs, inx) => new PlayerGame()
            {
                Game          = newGame,
                UserId        = prs.UserId,
                User          = prs.User,
                LastHeartbeat = DateTime.UtcNow,
                Order         = inx,
                Team          = prs.Team + 1,
                HasJoined     = prs.UserId == roomEntity.MasterUserId
            })
                               .ToList();
            //}

            newGame.PlayerGame = playerGameSource;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Crée la room avec le master associé.
        /// </summary>
        /// <param name="name">Nom de la salle</param>
        /// <param name="roomMaster">Guid du créateur.</param>
        /// <returns>Le guid de la room. </returns>
        public Guid?CreateRoom(string name, Guid roomMaster)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    // Fetch le master id.
                    int mId = context.LoggedInUser.First(p => p.Token == roomMaster).UserId;
                    // Vérifie si déjà master d'une room ou membre d'une room.
                    bool alreadyInRoom = context.Room
                                         .Where(p => p.MasterUserId == mId)
                                         .Count() > 0;

                    if (alreadyInRoom)
                    {
                        return(null);
                    }

                    alreadyInRoom = context.PlayerRoomState
                                    .Where(p => p.UserId == mId)
                                    .Count() > 0;

                    if (alreadyInRoom)
                    {
                        return(null);
                    }

                    Guid roomGuid = Guid.NewGuid();
                    Room r        = new Room();
                    r.Name             = name;
                    r.Started          = false;
                    r.Token            = roomGuid;
                    r.MasterUserId     = mId;
                    r.GameInProgressId = null;

                    // Crée le playerroomstate du roommaster
                    PlayerRoomState prs = new PlayerRoomState();
                    prs.Room          = r;
                    prs.UserId        = mId;
                    prs.IsReady       = false;
                    prs.Order         = 0;
                    prs.Team          = 0;
                    prs.LastHeartbeat = DateTime.UtcNow;

                    context.Room.Add(r);
                    context.PlayerRoomState.Add(prs);
                    context.SaveChanges();

                    return(roomGuid);
                }
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 13
0
        private User GetPlayerFromToken(MilleBornesEntities context, Guid playerToken)
        {
            var loggedInUser = context.LoggedInUser
                               .SingleOrDefault(lu => lu.Token == playerToken);

            if (loggedInUser == null)
            {
                return(null);
            }

            return(loggedInUser.User);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Vérifie la connexion de l'utilisateur.
        /// </summary>
        /// <param name="username">Nom d'utilisateur</param>
        /// <param name="password">Mot de passe</param>
        /// <returns>Retourne le Guid de l'utilisateur.</returns>
        /// <remarks>Si cet appel retourne null, c'est que l'utilisateur n'a pas réussi à se logger.</remarks>
        public Guid?Login(string username, string password)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    string hashedPassword = GetSHA1HashString(password);
                    var    lstUsers       = new List <User>();

                    lstUsers = new List <User>(context.User
                                               .Where(p => p.Name == username.Trim() &&
                                                      p.PasswordHash.ToLower() == hashedPassword.ToLower()));

                    if (lstUsers.Count() < 1)
                    {
                        return(null);
                    }

                    User user = lstUsers.First();

                    LoggedInUser loggedInfo = new LoggedInUser();
                    loggedInfo.LoginDate = DateTime.UtcNow;
                    Guid guid = Guid.NewGuid();

                    loggedInfo.Token  = guid;
                    loggedInfo.UserId = user.UserId;
                    DateTime hb = DateTime.UtcNow;
                    loggedInfo.LastHeartbeat = hb.AddMilliseconds(DELAY_MS_HEARTBEAT * 10);

                    LoggedInUser old = context.LoggedInUser.Find(loggedInfo.UserId);

                    if (old == null)
                    {
                        context.LoggedInUser.Add(loggedInfo);
                    }
                    else
                    {
                        old.Token         = loggedInfo.Token;
                        old.LoginDate     = DateTime.UtcNow;
                        old.LastHeartbeat = DateTime.UtcNow;
                    }

                    context.SaveChanges();
                    return(guid);
                }
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Permet de joindre une room!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <returns>True si succès, false autrement.</returns>
        public bool JoinRoom(Guid player, Guid room)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser liu = context.LoggedInUser.First(p => p.Token == player);

                    // On vérifie si le user est dans la room...
                    // vérifie si déjà dans une room
                    bool alreadyInRoom = context.PlayerRoomState
                                         .Where(p => p.UserId == liu.UserId)
                                         .Count() > 0;

                    Room r = context.Room.First(p => p.Token == room);

                    // Si il est dans une autre room.
                    if (alreadyInRoom)
                    {
                        if (r.MasterUserId == liu.UserId || r.PlayerRoomState.First(p => p.UserId == liu.UserId).Room.Token == room)
                        {
                            SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le joueur " + liu.User.Name + " revenu dans la partie ☺**");
                            return(true);
                        }

                        return(false);
                    }

                    PlayerRoomState prsUser = new PlayerRoomState();
                    prsUser.UserId        = liu.UserId;
                    prsUser.RoomId        = r.RoomId;
                    prsUser.IsReady       = false;
                    prsUser.Order         = 0;
                    prsUser.Team          = 0;
                    prsUser.LastHeartbeat = DateTime.UtcNow;

                    context.PlayerRoomState.Add(prsUser);
                    context.SaveChanges();
                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le joueur " + liu.User.Name + " a join la partie ☺**");
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 16
0
        public bool DoHeartbeat(Guid playerToken, Guid gameToken)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                           .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                var playerGame = game.PlayerGame
                                 .SingleOrDefault(pg => pg.UserId == player.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                if (!playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur n'a pas rejoint la partie.");
                }

                bool validPlayerHeartbeat = ValidatePlayerHeartbeat(playerGame);
                if (validPlayerHeartbeat)
                {
                    playerGame.LastHeartbeat = DateTime.UtcNow;
                    context.SaveChanges();
                }

                if (!CheckAllPlayersHeartbeat(game))
                {
                    context.SaveChanges();
                }

                return(validPlayerHeartbeat);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Obtient les utilisateurs connectés.
        /// </summary>
        /// <returns>[UserName] => [Connected?]</returns>
        public Dictionary <string, byte> GetLoggedUsers()
        {
            Dictionary <string, byte> users = new Dictionary <string, byte>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    IQueryable <LoggedInUser> lstLogged = context.LoggedInUser;
                    Dictionary <string, byte> lstUsers  = new Dictionary <string, byte>();

                    foreach (LoggedInUser u in lstLogged)
                    {
                        KeyValuePair <string, byte> kp;

                        if (GetHeartBeat(u.Token))
                        {
                            if (u.User.PlayerGame.Count(p => (DateTime.UtcNow - p.LastHeartbeat).TotalMilliseconds < DELAY_MS_HEARTBEAT * 10) > 0)
                            {
                                kp = new KeyValuePair <string, byte>(u.User.Name, 2);
                            }
                            else if (u.User.PlayerRoomState.Count > 0)
                            {
                                kp = new KeyValuePair <string, byte>(u.User.Name, 1);
                            }
                            else
                            {
                                kp = new KeyValuePair <string, byte>(u.User.Name, 0);
                            }

                            lstUsers.Add(kp.Key, kp.Value);
                        }
                    }

                    foreach (var uu in lstUsers.OrderBy(p => p.Value))
                    {
                        users.Add(uu.Key, uu.Value);
                    }
                }
            }
            catch
            {
            }

            return(users);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Définit le nom de la salle.
        /// </summary>
        /// <param name="room"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public bool SetRoomName(Guid room, string newName)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    context.Room.First(p => p.Token == room).Name = newName;
                    context.SaveChanges();

                    return(true);
                }
            }
            catch
            {
            }

            return(false);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Détermine si on est toujours en ligne.
        /// </summary>
        /// <remarks>Contrairement à celui dans UserService, celui là ne rafraichi pas le hearbeat.</remarks>
        /// <param name="userToken"></param>
        /// <returns></returns>
        private bool GetHeartBeat(Guid userToken)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    LoggedInUser loggedUser = context.LoggedInUser.First(p => p.Token == userToken);

                    // Différence de temps.
                    TimeSpan dt = DateTime.UtcNow - loggedUser.LastHeartbeat;
                    return(dt.TotalMilliseconds <= DELAY_MS_HEARTBEAT * 10);
                }
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 20
0
        public Guid JoinGame(Guid player, Guid room)
        {
            using (var context = new MilleBornesEntities())
            {
                var playerEntity = context.User
                                   .Where(us => us.LoggedInUser != null)
                                   .SingleOrDefault(us => us.LoggedInUser.Token == player);
                if (playerEntity == null)
                {
                    throw new FaultException("Le joueur n'est pas valide ou est hors-ligne.");
                }

                var roomEntity = context.Room
                                 .SingleOrDefault(rm => rm.Token == room);
                if (roomEntity == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                var game = roomEntity.Game;
                if (game == null)
                {
                    throw new FaultException("Celle salle n'est pas associée à une partie en cours.");
                }

                var playerGame = game.PlayerGame
                                 .SingleOrDefault(pg => pg.UserId == playerEntity.UserId);
                if (playerGame == null)
                {
                    throw new FaultException("Le joueur n'est pas dans cette partie.");
                }

                if (playerGame.HasJoined)
                {
                    throw new FaultException("Le joueur a déja rejoint la partie.");
                }

                playerGame.HasJoined     = true;
                playerGame.LastHeartbeat = DateTime.UtcNow;
                context.SaveChanges();

                return(game.Token);
            }
        }
Ejemplo n.º 21
0
        public bool SendGameMessage(Guid playerToken, Guid gameToken, string message)
        {
            using (var context = new MilleBornesEntities())
            {
                var player = GetPlayerFromToken(context, playerToken);

                if (player == null)
                {
                    throw new FaultException("Le joueur n'est pas trouvé.");
                }

                var game = context.Game
                           .SingleOrDefault(gm => gm.Token == gameToken);

                if (game == null)
                {
                    throw new FaultException("La partie n'est pas trouvée.");
                }

                if (!GetPlayersInGame(game).Any(pg => pg.UserId == player.UserId))
                {
                    throw new FaultException("Le joueur n'est pas dans la partie.");
                }

                game.Message.Add(new Message()
                {
                    UserId  = player.UserId,
                    Type    = MessageType.GAME,
                    Date    = DateTime.UtcNow,
                    Content = message
                });

                try
                {
                    context.SaveChanges();
                    return(true);
                }
                catch (System.Data.Entity.Infrastructure.DbUpdateException dbue)
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Obtient le nom du master muahahahahaha
        /// </summary>
        /// <param name="room"></param>
        /// <returns></returns>
        public string GetMasterName(Guid room)
        {
            try
            {
                using (MilleBornesEntities tities = new MilleBornesEntities())
                {
                    int mid = tities.Room.First(p => p.Token == room).MasterUserId;

                    return(tities.User
                           .First(p => p.UserId == mid)
                           .Name);
                }
            }
            catch
            {
            }

            return("");
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Obtient l'index de l'équipe courante (0-1-2)
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public int GetCurrentTeamIndex(Guid player)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int uId = context.LoggedInUser
                              .First(p => p.Token == player)
                              .UserId;

                    return(context.PlayerRoomState.First(p => p.UserId == uId).Team);
                }
            }
            catch
            {
            }

            return(-1);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Envoie une message dans une salle.
        /// </summary>
        /// <param name="player">Guid du joueur.</param>
        /// <param name="room">Guid de la salle.</param>
        /// <param name="message">Contenu du message.</param>
        /// <returns>True si succès, false autrement.</returns>
        public bool SendRoomMessage(Guid player, Guid room, string message)
        {
            // Si c'est une commande.
            if (message.StartsWith("/"))
            {
                bool ok = GetCommandOuput(player, room, message);
                return(ok);
            }

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    //Message msg = new Message();
                    //msg.Content = message;
                    //msg.Date = DateTime.UtcNow;
                    //msg.Type = MessageType.ROOM; // 1== room.

                    //Room r = context.Room.First(p => p.Token == room);
                    //if (player != Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"))
                    //{
                    //    int userId = context.LoggedInUser.First(p => p.Token == player).UserId;
                    //    msg.UserId = userId;
                    //}
                    //else
                    //{
                    //    msg.UserId = 5; // id du système...
                    //}

                    //msg.Room.Add(r);

                    //context.Message.Add(msg);
                    //context.SaveChanges();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Change le nom de la salle.
        /// </summary>
        /// <remarks>Le joueur doit être master.</remarks>
        /// <param name="player">Guid du joueur qui requiert.</param>
        /// <param name="room">Guid de la salle.</param>
        /// <param name="newName">Nouveau nom de la salle.</param>
        /// <returns>True si réussi, false autrement.</returns>
        public bool SetName(Guid player, Guid room, string newName)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var lstRooms = context.Room.Where(p => p.Token == room);

                    if (lstRooms.Count() < 1)
                    {
                        return(false);
                    }

                    var lstUsers = context.LoggedInUser.Where(p => p.Token == player);

                    if (lstUsers.Count() < 1)
                    {
                        return(false);
                    }

                    if (lstUsers.First().UserId != lstRooms.First().MasterUserId)
                    {
                        return(false);
                    }

                    Room r = context.Room.Find(lstRooms.First().RoomId);

                    r.Name = newName;
                    context.SaveChanges();

                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le nom de la salle est désormais " + r.Name + " **");
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Crée l'utilisateur en fonction des informations fournies.
        /// </summary>
        /// <param name="info"></param>
        /// <returns>True si créé avec succès. False autrement.</returns>
        public bool CreateUser(Models.CreateUserInfo info)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    // Vérification basiques.
                    if (info.Email.Trim() == "" || !info.Email.Contains("@"))
                    {
                        return(false);
                    }

                    if (info.Username.Trim().Length < 2 || info.Password.Length < 3)
                    {
                        return(false);
                    }

                    User user = new User();
                    user.Name         = info.Username.Trim();
                    user.PasswordHash = GetSHA1HashString(info.Password);
                    user.EmailAddress = info.Email.Trim();

                    // Si l'utilisateur est déjà présent, soit email soit name.
                    if (context.User.Where(p => p.Name == user.Name ||
                                           user.EmailAddress == p.EmailAddress).Count() > 0)
                    {
                        return(false);
                    }


                    context.User.Add(user);
                    context.SaveChanges();
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Quitte la salle présentement dedans.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="room"></param>
        /// <returns>True si succès, false autrement</returns>
        public bool LeaveRoom(Guid player, Guid room)
        {
            try
            {
                using (MilleBornesEntities tities = new MilleBornesEntities())
                {
                    LoggedInUser u = tities.LoggedInUser.First(p => p.Token == player);

                    Room r = tities.Room.First(p => p.Token == room);

                    // Si c'est le master, on DÉTRUIT LA ROOOOOOOOOOOOOOOOOOOOOOOOOM
                    // Et tout les player state.
                    // Et tous les messages.
                    if (r.MasterUserId == u.UserId)
                    {
                        var lstPrs = tities.PlayerRoomState.Where(p => p.RoomId == r.RoomId).ToList();
                        tities.Message.RemoveRange(r.Message);
                        tities.PlayerRoomState.RemoveRange(lstPrs);
                        tities.Room.Remove(r);
                    }
                    else
                    {
                        // Sinon on quitte la salle, simplement.
                        PlayerRoomState prsUser = tities.PlayerRoomState.First(p => p.UserId == u.UserId);
                        tities.PlayerRoomState.Remove(prsUser);
                    }

                    tities.SaveChanges();

                    SendRoomMessage(Guid.ParseExact("00000000-0000-0000-0000-000000000000", "D"), room, "**Le joueur " + u.User.Name + " a quitté la partie ☹**");
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Détermine si la connexion est toujours vivante.
        /// </summary>
        /// <param name="userToken"></param>
        /// <returns>True si c'est le cas, false autrement.</returns>
        /// <remarks>Tolérance d'un skip de heartbeat.
        /// Valeur par défaut 1 heartbeat == 2000ms</remarks>
        public bool Heartbeat(Guid userToken)
        {
            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    var          lstLoggedUsers = context.LoggedInUser.Where(p => p.Token == userToken);
                    LoggedInUser liu            = lstLoggedUsers.First();

                    // Différence de temps.
                    TimeSpan dt = DateTime.UtcNow - liu.LastHeartbeat;

                    liu.LastHeartbeat = DateTime.UtcNow;
                    context.SaveChanges();

                    return(dt.TotalMilliseconds <= DELAY_MS_HEARTBEAT * 10);
                }
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Obtient la liste des joueurs dans la salle spécifiée
        /// </summary>
        /// <param name="room"></param>
        /// <returns>Liste des joueurs</returns>
        public List <string> GetRoomPlayers(Guid room)
        {
            List <string> lstPlayers = new List <string>();

            try
            {
                using (MilleBornesEntities context = new MilleBornesEntities())
                {
                    int rId    = context.Room.First(p => p.Token == room).RoomId;
                    var lstPrs = context.PlayerRoomState.Where(p => p.RoomId == rId);

                    foreach (PlayerRoomState prs in lstPrs)
                    {
                        lstPlayers.Add(prs.User.Name);
                    }
                }
            }
            catch
            {
            }

            return(lstPlayers);
        }
Ejemplo n.º 30
0
        public Models.PlayerConfigEntry[] GetPlayerConfig(Guid roomToken)
        {
            using (var context = new MilleBornesEntities())
            {
                var room = context.Room
                           .SingleOrDefault(rm => rm.Token == roomToken);
                if (room == null)
                {
                    throw new FaultException("La salle n'est pas trouvée.");
                }

                var playerConfig = room.PlayerRoomState
                                   .Select((prs, inx) => new PlayerConfigEntry()
                {
                    UserToken = prs.User.LoggedInUser.Token,
                    Order     = prs.Order,
                    Team      = prs.Team
                })
                                   .ToArray();

                return(playerConfig);
            }
        }