Ejemplo n.º 1
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var playerLogoutInfo = message.ReadManagementPlayerLogoutInfo();

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Account_Id == playerLogoutInfo.AccountId).FirstOrDefault();

                if (playerRecord != null)
                {
                    playerRecord.Level     = playerLogoutInfo.Level;
                    playerRecord.Vocation  = playerLogoutInfo.Vocation;
                    playerRecord.Residence = playerLogoutInfo.Residence;
                    playerRecord.Lastlogin = playerLogoutInfo.LastLogin;

                    playerRecord.Online = 0;

                    var onlineRecord = otContext.Online.Where(o => o.Name.Equals(playerRecord.Charname)).FirstOrDefault();

                    if (onlineRecord != null)
                    {
                        otContext.Online.Remove(onlineRecord);
                    }

                    otContext.SaveChanges();

                    this.ResponsePackets.Add(new DefaultNoErrorPacket());
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var gameConfig   = ServiceConfiguration.GetConfiguration();
            var outXmlString = string.Empty;

            var playersOnline = 0;
            var onlineRecord  = 0;

            using (var otContext = new OpenTibiaDbContext())
            {
                var statusRecord = otContext.Stats.FirstOrDefault();

                if (statusRecord != null)
                {
                    playersOnline = statusRecord.PlayersOnline;
                    onlineRecord  = statusRecord.RecordOnline;
                }
            }

            using (var sw = new StringWriter())
            {
                using (var writer = XmlWriter.Create(sw))
                {
                    writer.WriteStartDocument();
                    writer.WriteAttributeString("version", "1.0");
                    // writer.WriteStartElement("tsqp");
                    // writer.WriteAttributeString("version", "1.0");
                    writer.WriteStartElement("serverinfo");
                    writer.WriteAttributeString("uptime", $"{DateTimeOffset.UtcNow.Ticks}");
                    writer.WriteAttributeString("ip", $"{gameConfig.PublicGameIpAddress}");
                    writer.WriteAttributeString("servername", "OpenTibia");             // TODO: handle multiple game servers. gameConfig.ServerName
                    writer.WriteAttributeString("port", $"{gameConfig.PublicGamePort}");
                    writer.WriteAttributeString("location", gameConfig.LocationString); // TODO: add location to game servers...
                    writer.WriteAttributeString("url", @"http://www.randomot.com");     // TODO: make configurable gameConfig.URL
                    writer.WriteAttributeString("server", "OpenTibia");                 // TODO: handle multiple game servers. gameConfig.ServerName
                    writer.WriteAttributeString("version", "0.1a");                     // TODO: handle. gameConfig.GameVersion
                    writer.WriteAttributeString("client", "7.7");                       // TODO: handle. gameConfig.ClientVersion
                    writer.WriteEndElement();                                           // "serverinfo"
                    writer.WriteStartElement("owner");
                    writer.WriteAttributeString("name", "Gamemaster");                  // TODO: make configurable
                    writer.WriteAttributeString("email", "*****@*****.**");       // TODO: make configurable
                    writer.WriteEndElement();                                           // "owner"
                    writer.WriteStartElement("players");
                    writer.WriteAttributeString("online", $"{playersOnline}");
                    writer.WriteAttributeString("max", $"{gameConfig.MaximumTotalPlayers}");
                    writer.WriteAttributeString("peak", $"{onlineRecord}");
                    writer.WriteEndElement(); // "players"
                    writer.WriteStartElement("motd");
                    writer.WriteString(gameConfig.MessageOfTheDay);
                    writer.WriteEndElement(); // "motd"
                    writer.WriteEndDocument();
                }

                outXmlString = sw.ToString();
            }

            this.ResponsePackets.Add(new ServerStatusPacket(outXmlString));
        }
Ejemplo n.º 3
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var createPlayerListPacket = new CreatePlayerListPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var currentRecord = otContext.Stats.Select(s => s.RecordOnline).FirstOrDefault();
                var isNewRecord   = createPlayerListPacket.PlayerList.Count > currentRecord;

                var currentRemove = new Dictionary <string, OnlinePlayer>();

                foreach (var player in otContext.Online.ToList())
                {
                    currentRemove.Add(player.Name, player);
                }

                foreach (var player in createPlayerListPacket.PlayerList)
                {
                    var dbRecord = otContext.Online.Where(o => o.Name.Equals(player.Name)).FirstOrDefault();

                    if (dbRecord != null)
                    {
                        dbRecord.Level    = player.Level;
                        dbRecord.Vocation = player.Vocation;
                    }
                    else
                    {
                        otContext.Online.Add(new OnlinePlayer
                        {
                            Name     = player.Name,
                            Level    = player.Level,
                            Vocation = player.Vocation
                        });
                    }

                    if (currentRemove.ContainsKey(player.Name))
                    {
                        currentRemove.Remove(player.Name);
                    }
                }

                foreach (var player in currentRemove.Values)
                {
                    otContext.Online.Remove(player);
                }

                otContext.SaveChanges();

                ResponsePackets.Add(new CreatePlayerListResultPacket
                {
                    IsNewRecord = isNewRecord
                });
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var loadPlayersPacket = message.ReadDefaultInfo();

            using (var otContext = new OpenTibiaDbContext())
            {
                var thirtyDaysBack = new DateTimeOffset(DateTime.Today).AddDays(-30).ToUnixTimeSeconds();

                var loadedPlayers = otContext.Players.Where(p => p.Lastlogin > thirtyDaysBack);

                this.ResponsePackets.Add(new LoadPlayersResultPacket(loadedPlayers.ToList()));
            }
        }
Ejemplo n.º 5
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var loadPlayersPacket = new DefaultReadPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var thirtyDaysBack = DateTime.Today.AddDays(-30).ToFileTimeUtc();

                var loadedPlayers = otContext.Players.Where(p => p.Lastlogin > thirtyDaysBack);

                ResponsePackets.Add(new LoadPlayersResultPacket
                {
                    LoadedPlayers = loadedPlayers.ToList()
                });
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var defaultInfo = message.ReadDefaultInfo();

            using (var otContext = new OpenTibiaDbContext())
            {
                var housesJustAssigned = otContext.AssignedHouses.Where(h => h.Virgin > 0);

                foreach (var house in housesJustAssigned)
                {
                    house.Virgin = 0;
                }

                otContext.SaveChanges();

                this.ResponsePackets.Add(new AuctionsResultPacket(housesJustAssigned.ToList()));
            }
        }
Ejemplo n.º 7
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var ruleViolationPacket = new RuleViolationPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Charname.Equals(ruleViolationPacket.CharacterName)).FirstOrDefault();

                if (playerRecord != null)
                {
                    var userRecord = otContext.Users.Where(u => u.Login == playerRecord.Account_Nr).FirstOrDefault();

                    if (userRecord != null)
                    {
                        var nowUnixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                        otContext.Banishments.Add(new Banishment
                        {
                            AccountId      = playerRecord.Account_Id,
                            AccountNr      = playerRecord.Account_Nr,
                            Ip             = ruleViolationPacket.IpAddress,
                            GmId           = ruleViolationPacket.GamemasterId,
                            Violation      = ruleViolationPacket.Reason,
                            Comment        = ruleViolationPacket.Comment,
                            Timestamp      = nowUnixTimestamp,
                            BanishedUntil  = nowUnixTimestamp,
                            PunishmentType = 0x02
                        });

                        otContext.SaveChanges();

                        ResponsePackets.Add(new NotationResultPacket
                        {
                            GamemasterId = (uint)ruleViolationPacket.GamemasterId
                        });

                        return;
                    }
                }
            }

            ResponsePackets.Add(new DefaultErrorPacket());
        }
Ejemplo n.º 8
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var finishAuctionsPacket = new DefaultReadPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var housesJustAssigned = otContext.AssignedHouses.Where(h => h.Virgin > 0);

                foreach (var house in housesJustAssigned)
                {
                    house.Virgin = 0;
                }

                otContext.SaveChanges();

                ResponsePackets.Add(new FinishAuctionsResultPacket
                {
                    Houses = housesJustAssigned.ToList()
                });
            }
        }
Ejemplo n.º 9
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var clearOnlinePacket = new DefaultReadPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var onlinePlayers = otContext.Players.Where(p => p.Online > 0).ToList();

                foreach (var player in onlinePlayers)
                {
                    player.Online = 0;
                }

                otContext.SaveChanges();

                ResponsePackets.Add(new ClearOnlinePlayersResultPacket
                {
                    ClearedCount = (ushort)onlinePlayers.Count
                });
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var ruleViolationInfo = message.ReadRuleViolationInfo();

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Charname.Equals(ruleViolationInfo.CharacterName)).FirstOrDefault();

                if (playerRecord != null)
                {
                    var userRecord = otContext.Users.Where(u => u.Login == playerRecord.Account_Nr).FirstOrDefault();

                    if (userRecord != null)
                    {
                        var nowUnixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                        otContext.Banishments.Add(new Banishment
                        {
                            AccountId      = playerRecord.Account_Id,
                            AccountNr      = playerRecord.Account_Nr,
                            Ip             = ruleViolationInfo.IpAddress,
                            GmId           = ruleViolationInfo.GamemasterId,
                            Violation      = ruleViolationInfo.Reason,
                            Comment        = ruleViolationInfo.Comment,
                            Timestamp      = nowUnixTimestamp,
                            BanishedUntil  = nowUnixTimestamp,
                            PunishmentType = 0x02,
                        });

                        otContext.SaveChanges();

                        this.ResponsePackets.Add(new NotationResultPacket(ruleViolationInfo.GamemasterId));

                        return;
                    }
                }
            }

            this.ResponsePackets.Add(new DefaultErrorPacket());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Handles the contents of a network message.
        /// </summary>
        /// <param name="message">The message to handle.</param>
        /// <param name="connection">A reference to the connection from where this message is comming from, for context.</param>
        public override void HandleRequest(INetworkMessage message, IConnection connection)
        {
            var characterDeathInfo = message.ReadCharacterDeathInfo();

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerKilledPlayer = characterDeathInfo.KillerId > 0;

                otContext.Deaths.Add(new Death
                {
                    PlayerId       = characterDeathInfo.VictimId,
                    Level          = characterDeathInfo.VictimLevel,
                    ByPeekay       = (byte)(playerKilledPlayer ? 1 : 0),
                    PeekayId       = playerKilledPlayer ? characterDeathInfo.KillerId : 0,
                    CreatureString = characterDeathInfo.KillerName,
                    Unjust         = (byte)(characterDeathInfo.Unjustified ? 0x01 : 0x00),
                    Timestamp      = characterDeathInfo.Timestamp.ToUnixTimeSeconds(),
                });

                otContext.SaveChanges();

                this.ResponsePackets.Add(new DefaultNoErrorPacket());
            }
        }
Ejemplo n.º 12
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var characterDeathPacket = new CharacterDeathPacket(message);

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerKilledPlayer = characterDeathPacket.KillerId > 0;

                otContext.Deaths.Add(new Death
                {
                    PlayerId       = characterDeathPacket.VictimId,
                    Level          = characterDeathPacket.VictimLevel,
                    ByPeekay       = (byte)(playerKilledPlayer ? 1 : 0),
                    PeekayId       = playerKilledPlayer ? characterDeathPacket.KillerId : 0,
                    CreatureString = characterDeathPacket.KillerName,
                    Unjust         = (byte)(characterDeathPacket.Unjustified ? 0x01 : 0x00),
                    Timestamp      = characterDeathPacket.Timestamp.ToFileTimeUtc()
                });

                otContext.SaveChanges();

                ResponsePackets.Add(new DefaultNoErrorPacket());
            }
        }
Ejemplo n.º 13
0
        public override void ProcessMessage(Connection connection, NetworkMessage inboundMessage)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            if (inboundMessage == null)
            {
                throw new ArgumentNullException(nameof(inboundMessage));
            }

            var packetType = (LoginOrManagementIncomingPacketType)inboundMessage.GetByte();

            if (packetType != LoginOrManagementIncomingPacketType.LoginServerRequest)
            {
                // This packet should NOT have been routed to this protocol.
                Trace.TraceWarning("Non LoginServerRequest packet routed to LoginProtocol. Packet was ignored.");
                return;
            }

            var newConnPacket = new NewConnectionPacket(inboundMessage);
            var gameConfig    = ServiceConfiguration.GetConfiguration();

            if (gameConfig.ReceivedClientVersionInt < gameConfig.ClientMinVersionInt || gameConfig.ReceivedClientVersionInt > gameConfig.ClientMaxVersionInt)
            {
                //ResponsePackets.Add(new GameServerDisconnectPacket {
                //	Reason = $"You need client version in between {gameConfig.ClientMinVersionString} and {gameConfig.ClientMaxVersionString} to connect to this server."
                //});

                return;
            }

            // Make a copy of the message in case we fail to decrypt using the first set of keys.

            var messageCopy = NetworkMessage.Copy(inboundMessage);

            inboundMessage.RsaDecrypt(useRsa2: true);

            if (inboundMessage.GetByte() != 0)
            {
                inboundMessage = messageCopy;

                inboundMessage.RsaDecrypt(useCipKeys: gameConfig.UsingCipsoftRsaKeys);

                if (inboundMessage.GetByte() != 0)                 // means the RSA decrypt was unsuccessful, lets try with the other set of RSA keys...
                {
                    inboundMessage = messageCopy;

                    inboundMessage.RsaDecrypt(useCipKeys: !gameConfig.UsingCipsoftRsaKeys);

                    if (inboundMessage.GetByte() != 0)
                    {
                        // These RSA keys are also unsuccessful... give up.
                        // loginPacket = new AccountLoginPacket(inboundMessage);

                        // connection.SetXtea(loginPacket?.XteaKey);

                        //// TODO: hardcoded messages.
                        // if (gameConfig.UsingCipsoftRSAKeys)
                        // {
                        //    SendDisconnect(connection, $"The RSA encryption keys used by your client cannot communicate with this game server.\nPlease use an IP changer that does not replace the RSA Keys.\nWe recommend using Tibia Loader's 7.7 client.\nYou may also download the client from out website.");
                        // }
                        // else
                        // {
                        //    SendDisconnect(connection, $"The RSA encryption keys used by your client cannot communicate with this game server.\nPlease use an IP changer that replaces the RSA Keys.\nWe recommend using OTLand's IP changer with a virgin 7.7 client.\nYou may also download the client from out website.");
                        // }
                        return;
                    }
                }
            }

            IAccountLoginInfo loginPacket = new AccountLoginPacket(inboundMessage);

            connection.SetXtea(loginPacket.XteaKey);

            using (var otContext = new OpenTibiaDbContext())
            {
                if (!otContext.Users.Any())
                {
                    var u = new User()
                    {
                        Id           = 1,
                        Email        = "1",
                        Login        = 1,
                        Passwd       = "1",
                        Userlevel    = 255,
                        Premium      = 1,
                        Premium_Days = 100
                    };

                    otContext.Users.Add(u);
                    otContext.SaveChanges();

                    var p = new PlayerModel()
                    {
                        Account_Id = 1,
                        Player_Id  = 1,
                        Account_Nr = 1,
                        Charname   = "MUNIZ",
                        Level      = 10,
                        Comment    = "Felipe Muniz"
                    };

                    otContext.Players.Add(p);
                    otContext.SaveChanges();

                    var u2 = new User()
                    {
                        Id           = 2,
                        Email        = "2",
                        Login        = 2,
                        Passwd       = "2",
                        Userlevel    = 50,
                        Premium      = 1,
                        Premium_Days = 100
                    };

                    otContext.Users.Add(u2);
                    otContext.SaveChanges();

                    var p2 = new PlayerModel()
                    {
                        Account_Id = 2,
                        Player_Id  = 2,
                        Account_Nr = 2,
                        Charname   = "FELIPE",
                        Level      = 10,
                        Comment    = "Felipe"
                    };

                    otContext.Players.Add(p2);
                    otContext.SaveChanges();
                }

                // validate credentials.
                var user = otContext.Users.FirstOrDefault(u => u.Login == loginPacket.AccountNumber && u.Passwd.Equals(loginPacket.Password));

                if (user == null)
                {
                    // TODO: hardcoded messages.
                    SendDisconnect(connection, "Please enter a valid account number and password.");
                }
                else
                {
                    var charactersFound = otContext.Players.Where(p => p.Account_Nr == user.Login);

                    if (!charactersFound.Any())
                    {
                        // TODO: hardcoded messages.
                        SendDisconnect(connection, $"Your account does not have any characters.\nPlease create a new character in our web site first: {gameConfig.WebsiteUrl}");
                    }
                    else
                    {
                        var charList = new List <ICharacterListItem>();

                        foreach (var character in charactersFound)
                        {
                            charList.Add(new CharacterListItem(character.Charname, gameConfig.PublicGameIpAddress, gameConfig.PublicGamePort, gameConfig.WorldName));
                        }

                        // TODO: motd
                        SendCharacterList(connection, gameConfig.MessageOfTheDay, (ushort)Math.Min(user.Premium_Days + user.Trial_Premium_Days, ushort.MaxValue), charList);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public override void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var playerLoginPacket = new PlayerLoginPacket(message);

            connection.SetXtea(playerLoginPacket.XteaKey);

            if (ServiceConfiguration.GetConfiguration().ReceivedClientVersionInt < ServiceConfiguration.GetConfiguration().ClientMinVersionInt ||
                playerLoginPacket.Version > ServiceConfiguration.GetConfiguration().ClientMaxVersionInt)
            {
                ResponsePackets.Add(new GameServerDisconnectPacket {
                    Reason = $"You need client version in between {ServiceConfiguration.GetConfiguration().ClientMinVersionString} and {ServiceConfiguration.GetConfiguration().ClientMaxVersionString} to connect to this server."
                });

                return;
            }

            if (Game.Instance.Status == WorldState.Creating)
            {
                ResponsePackets.Add(new GameServerDisconnectPacket
                {
                    Reason = "The game is just starting.\nPlease try again in a few minutes."
                });

                return;
            }

            using (var otContext = new OpenTibiaDbContext())
            {
                var failure = LoginFailureReason.None;

                var userRecord   = otContext.Users.FirstOrDefault(u => u.Login == playerLoginPacket.AccountNumber && u.Passwd.Equals(playerLoginPacket.Password));
                var playerRecord = otContext.Players.FirstOrDefault(p => p.Account_Nr == playerLoginPacket.AccountNumber && p.Charname.Equals(playerLoginPacket.CharacterName));

                if (userRecord == null || playerRecord == null)
                {
                    failure = LoginFailureReason.AccountOrPasswordIncorrect;
                }
                else
                {
                    // Check bannishment.
                    if (userRecord.Banished > 0 || userRecord.Bandelete > 0)
                    {
                        // Lift if time is up
                        if (userRecord.Bandelete > 0 || DateTime.FromFileTimeUtc(userRecord.Banished_Until) > DateTime.Now)
                        {
                            failure = LoginFailureReason.Bannished;
                        }
                        else
                        {
                            userRecord.Banished = 0;
                        }
                    }

                    // Check that no other characters from this account are logged in.
                    var anotherCharacterIsLoggedIn = otContext.Players.Any(p => p.Account_Nr == playerLoginPacket.AccountNumber && p.Online > 0 && !p.Charname.Equals(playerLoginPacket.CharacterName));

                    if (anotherCharacterIsLoggedIn)
                    {
                        failure = LoginFailureReason.AnotherCharacterIsLoggedIn;
                    }

                    // Check if game is open to public
                    if (Game.Instance.Status != WorldState.Open)
                    {
                        ResponsePackets.Add(new GameServerDisconnectPacket
                        {
                            Reason = "The game is not open to the public yet.\nCheck for news on our webpage."
                        });

                        return;
                    }
                }

                if (failure == LoginFailureReason.None)
                {
                    try
                    {
                        // Set player status to online.
                        // playerRecord.online = 1;

                        // otContext.SaveChanges();
                        var player = Game.Instance.Login(playerRecord, connection);

                        // set this to allow future packets from this connection.
                        connection.IsAuthenticated = true;
                        connection.PlayerId        = player.CreatureId;

                        ResponsePackets.Add(new SelfAppearPacket
                        {
                            CreatureId = player.CreatureId,
                            IsLogin    = true,
                            Player     = player
                        });

                        // Add MapDescription
                        ResponsePackets.Add(new MapDescriptionPacket
                        {
                            Origin           = player.Location,
                            DescriptionBytes = Game.Instance.GetMapDescriptionAt(player, player.Location)
                        });

                        ResponsePackets.Add(new MagicEffectPacket
                        {
                            Location = player.Location,
                            Effect   = EffectT.BubbleBlue
                        });

                        ResponsePackets.Add(new PlayerInventoryPacket {
                            Player = player
                        });
                        ResponsePackets.Add(new PlayerStatusPacket {
                            Player = player
                        });
                        ResponsePackets.Add(new PlayerSkillsPacket {
                            Player = player
                        });

                        ResponsePackets.Add(new WorldLightPacket {
                            Level = Game.Instance.LightLevel, Color = Game.Instance.LightColor
                        });

                        ResponsePackets.Add(new CreatureLightPacket {
                            Creature = player
                        });

                        // Adds a text message
                        ResponsePackets.Add(new TextMessagePacket
                        {
                            Type    = MessageType.StatusDefault,
                            Message = "This is a test message"
                        });

                        // std::string tempstring = g_config.getString(ConfigManager::LOGIN_MSG);
                        // if (tempstring.size() > 0)
                        // {
                        //    AddTextMessage(msg, MSG_STATUS_DEFAULT, tempstring.c_str());
                        // }

                        // if (player->getLastLoginSaved() != 0)
                        // {
                        //    tempstring = "Your last visit was on ";
                        //    time_t lastLogin = player->getLastLoginSaved();
                        //    tempstring += ctime(&lastLogin);
                        //    tempstring.erase(tempstring.length() - 1);
                        //    tempstring += ".";

                        // AddTextMessage(msg, MSG_STATUS_DEFAULT, tempstring.c_str());
                        // }
                        // else
                        // {
                        //    tempstring = "Welcome to ";
                        //    tempstring += g_config.getString(ConfigManager::SERVER_NAME);
                        //    tempstring += ". Please choose an outfit.";
                        //    sendOutfitWindow(player);
                        // }

                        // Add any Vips here.

                        // for (VIPListSet::iterator it = player->VIPList.begin(); it != player->VIPList.end(); it++)
                        // {
                        //    bool online;
                        //    std::string vip_name;
                        //    if (IOPlayer::instance()->getNameByGuid((*it), vip_name))
                        //    {
                        //        online = (g_game.getPlayerByName(vip_name) != NULL);
                        //
                        // msg->AddByte(0xD2);
                        // msg->AddU32(guid);
                        // msg->AddString(name);
                        // msg->AddByte(isOnline ? 1 : 0);
                        //    }
                        // }

                        // Send condition icons
                        ResponsePackets.Add(new PlayerConditionsPacket {
                            Player = player
                        });

                        return;
                    }
                    catch (Exception ex)
                    {
                        // TODO: propper logging
                        Console.WriteLine(ex);

                        failure = LoginFailureReason.InternalServerError;
                    }
                }

                if (failure != LoginFailureReason.None)
                {
                    ResponsePackets.Add(new GameServerDisconnectPacket
                    {
                        Reason = failure.ToString() // TODO: implement correctly.
                    });
                }
            }
        }
Ejemplo n.º 15
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var ruleViolationPacket = new RuleViolationPacket(message);

            byte banDays      = 0;
            var  banUntilDate = DateTime.Now;

            using (var otContext = new OpenTibiaDbContext())
            {
                var playerRecord = otContext.Players.Where(p => p.Charname.Equals(ruleViolationPacket.CharacterName)).FirstOrDefault();

                if (playerRecord != null)
                {
                    var userRecord = otContext.Users.Where(u => u.Login == playerRecord.Account_Nr).FirstOrDefault();

                    if (userRecord != null)
                    {
                        // Calculate Banishment date based on number of previous banishments youger than 60 days...
                        var todayMinus60Days = DateTime.Today.AddDays(-60).ToFileTimeUtc();
                        var banCount         = otContext.Banishments.Where(b => b.AccountNr == playerRecord.Account_Nr && b.Timestamp > todayMinus60Days && b.PunishmentType == 1).Count();

                        switch (banCount)
                        {
                        case 0:
                            banDays = 7;
                            break;

                        case 1:
                            banDays = 15;
                            break;

                        case 2:
                            banDays = 30;
                            break;

                        case 3:
                            banDays = 90;
                            break;

                        default:
                            banDays = 255;
                            break;
                        }

                        banUntilDate = banUntilDate.AddDays(banDays);
                        var nowUnixTimestamp      = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                        var banUntilUnixTimestamp = (int)banUntilDate.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                        otContext.Banishments.Add(new Banishment
                        {
                            AccountId      = playerRecord.Account_Id,
                            AccountNr      = playerRecord.Account_Nr,
                            Ip             = ruleViolationPacket.IpAddress,
                            GmId           = ruleViolationPacket.GamemasterId,
                            Violation      = ruleViolationPacket.Reason,
                            Comment        = ruleViolationPacket.Comment,
                            Timestamp      = nowUnixTimestamp,
                            BanishedUntil  = banUntilUnixTimestamp,
                            PunishmentType = 1
                        });

                        userRecord.Banished       = 1;
                        userRecord.Banished_Until = banUntilUnixTimestamp;

                        otContext.SaveChanges();

                        ResponsePackets.Add(new BanismentResultPacket
                        {
                            BanDays       = banDays,
                            BanishedUntil = (uint)banUntilDate.ToFileTimeUtc()
                        });

                        return;
                    }
                }
            }

            ResponsePackets.Add(new DefaultErrorPacket());
        }
Ejemplo n.º 16
0
        public void HandleMessageContents(NetworkMessage message, Connection connection)
        {
            var playerLoginPacket = new ManagementPlayerLoginPacket(message);
            var failure           = LoginFailureReason.None;

            using (var otContext = new OpenTibiaDbContext())
            {
                if (!otContext.Users.Any())
                {
                    var user = new User()
                    {
                        Email  = "1",
                        Login  = 1,
                        Passwd = "1"
                    };

                    otContext.Users.Add(user);
                }

                var userRecord   = otContext.Users.Where(u => u.Login == playerLoginPacket.AccountNumber && u.Passwd.Equals(playerLoginPacket.Password)).FirstOrDefault();
                var playerRecord = otContext.Players.Where(p => p.Account_Nr == playerLoginPacket.AccountNumber && p.Charname.Equals(playerLoginPacket.CharacterName)).FirstOrDefault();

                if (userRecord == null || playerRecord == null)
                {
                    Console.WriteLine("if userRecord == null || playerRecord == null");
                    failure = LoginFailureReason.AccountOrPasswordIncorrect;
                }
                else
                {
                    Console.WriteLine("else userRecord == null || playerRecord == null");
                    // Check bannishment.
                    if (userRecord.Banished > 0 || userRecord.Bandelete > 0)
                    {
                        // Lift if time is up
                        if (userRecord.Bandelete > 0 || DateTime.FromFileTimeUtc(userRecord.Banished_Until) > DateTime.Now)
                        {
                            failure = LoginFailureReason.Bannished;
                        }
                        else
                        {
                            userRecord.Banished = 0;
                        }
                    }

                    // Check that no other characters from this account are logged in.
                    var anotherCharacterIsLoggedIn = otContext.Players.Where(p => p.Account_Nr == playerLoginPacket.AccountNumber && p.Online > 0 && !p.Charname.Equals(playerLoginPacket.CharacterName)).Any();

                    if (anotherCharacterIsLoggedIn)
                    {
                        failure = LoginFailureReason.AnotherCharacterIsLoggedIn;
                    }
                }

                if (failure == LoginFailureReason.None)
                {
                    try
                    {
                        // Set player status to online.
                        playerRecord.Online = 1;

                        // Pull guild information
                        var guildMembershipInfo = otContext.GuildMembers.Where(gm => gm.AccountId == playerRecord.Account_Id && gm.Invitation == 0).FirstOrDefault();
                        var guildInfo           = guildMembershipInfo == null ? null : otContext.Guilds.Where(g => g.GuildId == guildMembershipInfo.GuildId).FirstOrDefault();
                        var guildMemberCount    = guildInfo == null ? 0 : otContext.GuildMembers.Where(gm => gm.Invitation == 0 && gm.GuildId == guildInfo.GuildId).Count();

                        var rankString = string.Empty;

                        if (guildMembershipInfo != null)
                        {
                            switch (guildMembershipInfo.Rank)
                            {
                            default:
                            case 1:
                                rankString = guildInfo.Rank1;
                                break;

                            case 2:
                                rankString = guildInfo.Rank2;
                                break;

                            case 3:
                                rankString = guildInfo.Rank3;
                                break;

                            case 4:
                                rankString = guildInfo.Rank4;
                                break;

                            case 5:
                                rankString = guildInfo.Rank5;
                                break;

                            case 6:
                                rankString = guildInfo.Rank6;
                                break;

                            case 7:
                                rankString = guildInfo.Rank7;
                                break;

                            case 8:
                                rankString = guildInfo.Rank8;
                                break;

                            case 9:
                                rankString = guildInfo.Rank9;
                                break;

                            case 10:
                                rankString = guildInfo.Rank10;
                                break;
                            }
                        }

                        var vipCollection = otContext.Buddies.Where(b => b.AccountNr == playerRecord.Account_Nr).Take(100).ToList();

                        // TODO: load "privileges" from somewhere other than user level
                        var privileges = new HashSet <string>();

                        if (userRecord.Premium_Days > 0 || userRecord.Trial_Premium_Days > 0)
                        {
                            privileges.Add("PREMIUM_ACCOUNT");
                        }

                        if (userRecord.Userlevel >= 50)
                        {
                            privileges.Add("HIGHLIGHT_HELP_CHANNEL");
                            privileges.Add("READ_TUTOR_CHANNEL");
                            privileges.Add("SEND_BUGREPORTS");
                            privileges.Add("STATEMENT_ADVERT_MONEY");
                            privileges.Add("STATEMENT_ADVERT_OFFTOPIC");
                            privileges.Add("STATEMENT_CHANNEL_OFFTOPIC");
                            privileges.Add("STATEMENT_INSULTING");
                            privileges.Add("STATEMENT_NON_ENGLISH");
                            privileges.Add("STATEMENT_REPORT");
                            privileges.Add("STATEMENT_SPAMMING");
                            privileges.Add("STATEMENT_VIOLATION_INCITING");
                        }

                        if (userRecord.Userlevel >= 100)
                        {
                            privileges.Add("ALLOW_MULTICLIENT");
                            privileges.Add("BANISHMENT");
                            privileges.Add("CHEATING_ACCOUNT_SHARING");
                            privileges.Add("CHEATING_ACCOUNT_TRADING");
                            privileges.Add("CHEATING_BUG_ABUSE");
                            privileges.Add("CHEATING_GAME_WEAKNESS");
                            privileges.Add("CHEATING_HACKING");
                            privileges.Add("CHEATING_MACRO_USE");
                            privileges.Add("CHEATING_MODIFIED_CLIENT");
                            privileges.Add("CHEATING_MULTI_CLIENT");
                            privileges.Add("CLEANUP_FIELDS");
                            privileges.Add("CREATECHAR_GAMEMASTER");
                            privileges.Add("DESTRUCTIVE_BEHAVIOUR");
                            privileges.Add("FINAL_WARNING");
                            privileges.Add("GAMEMASTER_BROADCAST");
                            privileges.Add("GAMEMASTER_FALSE_REPORTS");
                            privileges.Add("GAMEMASTER_INFLUENCE");
                            privileges.Add("GAMEMASTER_PRETENDING");
                            privileges.Add("GAMEMASTER_THREATENING");
                            privileges.Add("GAMEMASTER_OUTFIT");
                            privileges.Add("HOME_TELEPORT");
                            privileges.Add("IGNORED_BY_MONSTERS");
                            privileges.Add("ILLUMINATE");
                            privileges.Add("INVALID_PAYMENT");
                            privileges.Add("INVULNERABLE");
                            privileges.Add("IP_BANISHMENT");
                            privileges.Add("KEEP_ACCOUNT");
                            privileges.Add("KEEP_CHARACTER");
                            privileges.Add("KEEP_INVENTORY");
                            privileges.Add("MODIFY_GOSTRENGTH");
                            privileges.Add("NAMELOCK");
                            privileges.Add("NAME_BADLY_FORMATTED");
                            privileges.Add("NAME_CELEBRITY");
                            privileges.Add("NAME_COUNTRY");
                            privileges.Add("NAME_FAKE_IDENTITY");
                            privileges.Add("NAME_FAKE_POSITION");
                            privileges.Add("NAME_INSULTING");
                            privileges.Add("NAME_NONSENSICAL_LETTERS");
                            privileges.Add("NAME_NO_PERSON");
                            privileges.Add("NAME_SENTENCE");
                            privileges.Add("NO_ATTACK");
                            privileges.Add("NOTATION");
                            privileges.Add("NO_BANISHMENT");
                            privileges.Add("NO_LOGOUT_BLOCK");
                            privileges.Add("NO_RUNES");
                            privileges.Add("NO_STATISTICS");
                            privileges.Add("READ_GAMEMASTER_CHANNEL");
                            privileges.Add("TELEPORT_TO_CHARACTER");
                            privileges.Add("TELEPORT_TO_MARK");
                            privileges.Add("TELEPORT_VERTICAL");
                            privileges.Add("VIEW_CRIMINAL_RECORD");
                            privileges.Add("ZERO_CAPACITY");
                        }

                        if (userRecord.Userlevel >= 255)
                        {
                            privileges.Add("ALL_SPELLS");
                            privileges.Add("ANONYMOUS_BROADCAST");
                            privileges.Add("APPOINT_CIP");
                            privileges.Add("APPOINT_JGM");
                            privileges.Add("APPOINT_SENATOR");
                            privileges.Add("APPOINT_SGM");
                            privileges.Add("ATTACK_EVERYWHERE");
                            privileges.Add("BOARD_ANONYMOUS_EDIT");
                            privileges.Add("BOARD_MODERATION");
                            privileges.Add("BOARD_PRECONFIRMED");
                            privileges.Add("BOARD_REPORT");
                            privileges.Add("CHANGE_PROFESSION");
                            privileges.Add("CHANGE_SKILLS");
                            privileges.Add("CREATE_OBJECTS");
                            privileges.Add("CIPWATCH_ADMIN");
                            privileges.Add("CIPWATCH_USER");
                            privileges.Add("CLEAR_CHARACTER_INFO");
                            privileges.Add("CLEAR_GUILDS");
                            privileges.Add("CREATECHAR_GOD");
                            privileges.Add("CREATECHAR_TEST");
                            privileges.Add("CREATE_MONEY");
                            privileges.Add("CREATE_MONSTERS");
                            privileges.Add("DELETE_GUILDS");
                            privileges.Add("ENTER_HOUSES");
                            privileges.Add("EXTRA_CHARACTER");
                            privileges.Add("KICK");
                            privileges.Add("KILLING_EXCESSIVE_UNJUSTIFIED");
                            privileges.Add("LEVITATE");
                            privileges.Add("LOG_COMMUNICATION");
                            privileges.Add("MODIFY_BANISHMENT");
                            privileges.Add("OPEN_NAMEDDOORS");
                            privileges.Add("RETRIEVE");
                            privileges.Add("SET_ACCOUNTGROUP_RIGHTS");
                            privileges.Add("SET_ACCOUNT_RIGHTS");
                            privileges.Add("SET_CHARACTERGROUP_RIGHTS");
                            privileges.Add("SET_CHARACTER_RIGHTS");
                            privileges.Add("SHOW_COORDINATE");
                            privileges.Add("SHOW_KEYHOLE_NUMBERS");
                            privileges.Add("SPECIAL_MOVEUSE");
                            privileges.Add("SPOILING_AUCTION");
                            privileges.Add("TELEPORT_TO_COORDINATE");
                            privileges.Add("UNLIMITED_CAPACITY");
                            privileges.Add("UNLIMITED_MANA");
                            privileges.Add("VIEW_ACCOUNT");
                            privileges.Add("VIEW_GAMEMASTER_RECORD");
                            privileges.Add("VIEW_LOG_FILES");
                        }

                        otContext.SaveChanges();

                        ResponsePackets.Add(new PlayerLoginSucessPacket
                        {
                            AccountId                 = playerRecord.Account_Id,
                            CharacterName             = playerRecord.Charname,
                            Gender                    = (byte)(playerRecord.Gender == 1 ? 0x01 : 0x02),
                            Guild                     = guildInfo?.GuildName,
                            GuildTitle                = rankString,
                            PlayerTitle               = guildMembershipInfo?.PlayerTitle,
                            VipContacts               = vipCollection,
                            PremiumDays               = userRecord.Premium_Days + userRecord.Trial_Premium_Days,
                            RecentlyActivatedPremmium = false, // TODO: load
                            Privileges                = privileges
                        });

                        return;
                    }
                    catch
                    {
                        failure = LoginFailureReason.InternalServerError;
                    }
                }

                ResponsePackets.Add(new PlayerLoginRejectionPacket
                {
                    Reason = (byte)failure
                });
            }
        }