Пример #1
0
        /// <inheritdoc />
        public void Save(IPlayerEntity player)
        {
            var skillsSet = from x in _database.Skills.Where(x => x.CharacterId == player.PlayerData.Id).AsNoTracking().ToList()
                            join s in player.SkillTree.Skills on
                            new { x.SkillId, x.CharacterId }
            equals
            new { s.SkillId, s.CharacterId }
            select new { DbSkill = x, PlayerSkill = s };

            foreach (var skillToUpdate in skillsSet)
            {
                skillToUpdate.DbSkill.Level = (byte)skillToUpdate.PlayerSkill.Level;

                _database.Skills.Update(skillToUpdate.DbSkill);
            }

            foreach (SkillInfo skill in player.SkillTree.Skills)
            {
                if (!skill.DatabaseId.HasValue && skill.Level > 0)
                {
                    var newSkill = new DbSkill
                    {
                        SkillId     = skill.SkillId,
                        Level       = (byte)skill.Level,
                        CharacterId = player.PlayerData.Id
                    };

                    _database.Skills.Add(newSkill);
                }
            }

            _database.SaveChanges();
        }
Пример #2
0
        /// <inheritdoc />
        public void Save(IPlayerEntity player)
        {
            DbCharacter          character     = _database.Characters.FirstOrDefault(x => x.Id == player.PlayerData.Id);
            IEnumerable <DbItem> itemsToDelete = (from dbItem in character.Items
                                                  let inventoryItem = player.Inventory.GetItem(x => x != null && x.DbId == dbItem.Id)
                                                                      where !dbItem.IsDeleted && inventoryItem == null
                                                                      select dbItem).ToList();

            foreach (DbItem dbItem in itemsToDelete)
            {
                dbItem.IsDeleted = true;

                _database.Items.Update(dbItem);
            }

            // Add or update items
            foreach (Item item in player.Inventory)
            {
                if (item == null)
                {
                    continue;
                }

                DbItem dbItem = character.Items.FirstOrDefault(x => x.Id == item.DbId && !x.IsDeleted);

                if (dbItem != null && dbItem.Id != 0)
                {
                    dbItem.CharacterId   = player.PlayerData.Id;
                    dbItem.ItemId        = item.Id;
                    dbItem.ItemCount     = item.Quantity;
                    dbItem.ItemSlot      = item.Slot;
                    dbItem.Refine        = item.Refine;
                    dbItem.Element       = (byte)item.Element;
                    dbItem.ElementRefine = item.ElementRefine;

                    _database.Items.Update(dbItem);
                }
                else
                {
                    dbItem = new DbItem
                    {
                        CharacterId   = player.PlayerData.Id,
                        CreatorId     = item.CreatorId,
                        ItemId        = item.Id,
                        ItemCount     = item.Quantity,
                        ItemSlot      = item.Slot,
                        Refine        = item.Refine,
                        Element       = (byte)item.Element,
                        ElementRefine = item.ElementRefine
                    };

                    _database.Items.Add(dbItem);
                }
            }

            _database.SaveChanges();
        }
Пример #3
0
        public void OnCertify(ILoginClient client, CertifyPacket certifyPacket)
        {
            if (certifyPacket.BuildVersion != _loginConfiguration.BuildVersion)
            {
                AuthenticationFailed(client, ErrorType.ILLEGAL_VER, "bad client build version");
                return;
            }

            DbUser user = _database.Users.FirstOrDefault(x => x.Username.Equals(certifyPacket.Username));
            AuthenticationResult authenticationResult = Authenticate(user, certifyPacket.Password);

            switch (authenticationResult)
            {
            case AuthenticationResult.BadUsername:
                AuthenticationFailed(client, ErrorType.FLYFF_ACCOUNT, "bad username");
                break;

            case AuthenticationResult.BadPassword:
                AuthenticationFailed(client, ErrorType.FLYFF_PASSWORD, "bad password");
                break;

            case AuthenticationResult.AccountSuspended:
                // TODO
                break;

            case AuthenticationResult.AccountTemporarySuspended:
                // TODO
                break;

            case AuthenticationResult.AccountDeleted:
                AuthenticationFailed(client, ErrorType.ILLEGAL_ACCESS, "logged in with deleted account");
                break;

            case AuthenticationResult.Success:
                if (_loginServer.IsClientConnected(certifyPacket.Username))
                {
                    AuthenticationFailed(client, ErrorType.DUPLICATE_ACCOUNT, "client already connected", disconnectClient: false);
                    return;
                }

                user.LastConnectionTime = DateTime.UtcNow;
                _database.Users.Update(user);
                _database.SaveChanges();

                _loginPacketFactory.SendServerList(client, certifyPacket.Username, _coreServer.GetConnectedClusters());
                client.SetClientUsername(certifyPacket.Username);
                _logger.LogInformation($"User '{client.Username}' logged succesfully from {client.Socket.RemoteEndPoint}.");
                break;

            default:
                break;
            }
        }
Пример #4
0
        /// <inheritdoc />
        public void SavePlayer(IPlayerEntity player)
        {
            if (player == null)
            {
                return;
            }

            DbCharacter character = _database.Characters.FirstOrDefault(x => x.Id == player.PlayerData.Id);

            if (character != null)
            {
                character.LastConnectionTime = player.PlayerData.LoggedInAt;
                character.PlayTime          += (long)(DateTime.UtcNow - player.PlayerData.LoggedInAt).TotalSeconds;

                character.PosX       = player.Object.Position.X;
                character.PosY       = player.Object.Position.Y;
                character.PosZ       = player.Object.Position.Z;
                character.Angle      = player.Object.Angle;
                character.MapId      = player.Object.MapId;
                character.MapLayerId = player.Object.LayerId;
                character.Gender     = player.VisualAppearance.Gender;
                character.HairColor  = player.VisualAppearance.HairColor;
                character.HairId     = player.VisualAppearance.HairId;
                character.FaceId     = player.VisualAppearance.FaceId;
                character.SkinSetId  = player.VisualAppearance.SkinSetId;
                character.Level      = player.Object.Level;

                character.JobId      = (int)player.PlayerData.Job;
                character.Gold       = player.PlayerData.Gold;
                character.Experience = player.PlayerData.Experience;

                character.Strength     = player.Attributes[DefineAttributes.STR];
                character.Stamina      = player.Attributes[DefineAttributes.STA];
                character.Dexterity    = player.Attributes[DefineAttributes.DEX];
                character.Intelligence = player.Attributes[DefineAttributes.INT];
                character.StatPoints   = player.Statistics.StatPoints;
                character.SkillPoints  = player.Statistics.SkillPoints;

                character.Hp = player.Attributes[DefineAttributes.HP];
                character.Mp = player.Attributes[DefineAttributes.MP];
                character.Fp = player.Attributes[DefineAttributes.FP];

                _database.SaveChanges();

                var gameSystems = _serviceProvider.GetRequiredService <IEnumerable <IGameSystemLifeCycle> >().OrderBy(x => x.Order);

                foreach (IGameSystemLifeCycle system in gameSystems)
                {
                    system.Save(player);
                }
            }
        }
Пример #5
0
        public void OnCreatePlayer(IClusterClient client, CreatePlayerPacket packet)
        {
            DbUser dbUser = _database.Users.FirstOrDefault(x => x.Username == packet.Username && x.Password == packet.Password);

            if (dbUser == null)
            {
                _logger.LogWarning($"[SECURITY] Unable to create new character for user '{packet.Username}' from {client.Socket.RemoteEndPoint}. " +
                                   "Reason: bad presented credentials compared to the database.");
                client.Disconnect();
                return;
            }

            if (_database.Characters.Any(x => x.Name == packet.CharacterName))
            {
                _logger.LogWarning(
                    $"Unable to create new character for user '{packet.Username}' from {client.Socket.RemoteEndPoint}. " +
                    $"Reason: character name '{packet.CharacterName}' already exists.");

                _clusterPacketFactory.SendClusterError(client, ErrorType.USER_EXISTS);
                return;
            }

            DefaultCharacter  defaultCharacter = _clusterServer.ClusterConfiguration.DefaultCharacter;
            DefaultStartItems defaultEquipment = packet.Gender == 0 ? defaultCharacter.Man : defaultCharacter.Woman;

            if (!_gameResources.Jobs.TryGetValue(packet.Job, out JobData jobData))
            {
                _logger.LogError($"Cannot find job data for job '{packet.Job}' for user '{dbUser.Username}'.");
                client.Disconnect();
                return;
            }

            var newCharacter = new DbCharacter()
            {
                UserId    = dbUser.Id,
                Name      = packet.CharacterName,
                Slot      = (byte)packet.Slot,
                SkinSetId = packet.SkinSet,
                HairColor = (int)packet.HairColor,
                FaceId    = packet.HeadMesh,
                HairId    = packet.HairMeshId,
                BankCode  = packet.BankPassword,
                Gender    = packet.Gender,
                JobId     = (int)packet.Job,
                Hp        = HealthFormulas.GetMaxOriginHp(defaultCharacter.Level, defaultCharacter.Stamina,
                                                          jobData.MaxHpFactor),
                Mp = HealthFormulas.GetMaxOriginMp(defaultCharacter.Level, defaultCharacter.Intelligence,
                                                   jobData.MaxMpFactor, true),
                Fp = HealthFormulas.GetMaxOriginFp(defaultCharacter.Level, defaultCharacter.Stamina,
                                                   defaultCharacter.Dexterity, defaultCharacter.Strength, jobData.MaxFpFactor, true),
                Strength     = defaultCharacter.Strength,
                Stamina      = defaultCharacter.Stamina,
                Dexterity    = defaultCharacter.Dexterity,
                Intelligence = defaultCharacter.Intelligence,
                MapId        = defaultCharacter.MapId,
                PosX         = defaultCharacter.PosX,
                PosY         = defaultCharacter.PosY,
                PosZ         = defaultCharacter.PosZ,
                Level        = defaultCharacter.Level,
                Gold         = defaultCharacter.Gold,
                StatPoints   = 0, //TODO: create default stat point constant.
                SkillPoints  = 0, //TODO: create default skill point constant.
                Experience   = 0,
            };

            //TODO: create game constants for slot.
            newCharacter.Items.Add(new DbItem(defaultEquipment.StartSuit, 44));
            newCharacter.Items.Add(new DbItem(defaultEquipment.StartHand, 46));
            newCharacter.Items.Add(new DbItem(defaultEquipment.StartShoes, 47));
            newCharacter.Items.Add(new DbItem(defaultEquipment.StartWeapon, 52));

            _database.Characters.Add(newCharacter);
            _database.SaveChanges();

            _logger.LogInformation($"Character '{newCharacter.Name}' has been created successfully for user '{dbUser.Username}' from {client.Socket.RemoteEndPoint}.");

            IEnumerable <DbCharacter> dbCharacters = GetCharacters(dbUser.Id);

            _clusterPacketFactory.SendPlayerList(client, packet.AuthenticationKey, dbCharacters);
        }
Пример #6
0
        /// <inheritdoc />
        public void Save(IPlayerEntity player)
        {
            DbCharacter character = _database.Characters.FirstOrDefault(x => x.Id == player.PlayerData.Id);

            character.TaskbarShortcuts.Clear();

            foreach (var applet in player.Taskbar.Applets.Objects)
            {
                if (applet == null)
                {
                    continue;
                }

                var dbApplet = new DbShortcut(ShortcutTaskbarTarget.Applet, applet.SlotIndex, applet.Type,
                                              applet.ObjectId, applet.ObjectType, applet.ObjectIndex, applet.UserId, applet.ObjectData, applet.Text);

                if (applet.Type == ShortcutType.Item)
                {
                    var item = player.Inventory.GetItemAtIndex((int)applet.ObjectId);
                    if (item is null)
                    {
                        continue;
                    }

                    dbApplet.ObjectId = (uint)item.Slot;
                }

                character.TaskbarShortcuts.Add(dbApplet);
            }


            for (int slotLevel = 0; slotLevel < player.Taskbar.Items.Objects.Count; slotLevel++)
            {
                for (int slot = 0; slot < player.Taskbar.Items.Objects[slotLevel].Count; slot++)
                {
                    var itemShortcut = player.Taskbar.Items.Objects[slotLevel][slot];
                    if (itemShortcut == null)
                    {
                        continue;
                    }

                    var dbItem = new DbShortcut(ShortcutTaskbarTarget.Item, slotLevel, itemShortcut.SlotIndex,
                                                itemShortcut.Type, itemShortcut.ObjectId, itemShortcut.ObjectType, itemShortcut.ObjectIndex,
                                                itemShortcut.UserId, itemShortcut.ObjectData, itemShortcut.Text);

                    if (itemShortcut.Type == ShortcutType.Item)
                    {
                        var item = player.Inventory.GetItemAtIndex((int)itemShortcut.ObjectId);
                        if (item is null)
                        {
                            continue;
                        }

                        dbItem.ObjectId = (uint)item.Slot;
                    }

                    character.TaskbarShortcuts.Add(dbItem);
                }
            }

            foreach (var queueItem in player.Taskbar.Queue.Shortcuts)
            {
                if (queueItem == null)
                {
                    continue;
                }

                character.TaskbarShortcuts.Add(new DbShortcut(ShortcutTaskbarTarget.Queue, queueItem.SlotIndex,
                                                              queueItem.Type, queueItem.ObjectId, queueItem.ObjectType, queueItem.ObjectIndex, queueItem.UserId,
                                                              queueItem.ObjectData, queueItem.Text));
            }

            _database.SaveChanges();
        }
Пример #7
0
        public void OnExecute()
        {
            if (string.IsNullOrEmpty(DatabaseConfigurationFile))
            {
                DatabaseConfigurationFile = ConfigurationConstants.DatabasePath;
            }

            var dbConfig = ConfigurationHelper.Load <DatabaseConfiguration>(DatabaseConfigurationFile, ConfigurationConstants.DatabaseConfiguration);

            if (dbConfig is null)
            {
                Console.WriteLine("Couldn't load database configuration file during execution of user create command.");
                return;
            }

            Console.Write("Username to update: ");
            string username = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(username))
            {
                Console.WriteLine("You must type a username.");
                return;
            }

            using IRhisisDatabase database = _databaseFactory.CreateDatabaseInstance(dbConfig);
            DbUser user = database.Users.FirstOrDefault(x => x.Username == username);

            if (user == null)
            {
                Console.WriteLine($"Could not locate any username named '{username}'.");
                return;
            }

            bool response = _consoleHelper.AskConfirmation($"Are you sure you want to update the account '{user.Username}'");

            if (!response)
            {
                return;
            }

            bool changeEmail = _consoleHelper.AskConfirmation($"Would you like to change the email? '{user.Email}'");

            if (changeEmail)
            {
                Console.Write("Type the new email: ");
                user.Email = Console.ReadLine();
            }

            bool   changePassword       = _consoleHelper.AskConfirmation("Would you like to change the password?");
            string passwordConfirmation = string.Empty;
            string passwordSalt         = string.Empty;

            if (changePassword)
            {
                Console.Write("New password: "******"New password confirmation: ");
                passwordConfirmation = _consoleHelper.ReadPassword();

                Console.Write("Password salt: ");
                passwordSalt = _consoleHelper.ReadStringOrDefault();
            }

            bool changeAuthority = _consoleHelper.AskConfirmation("Would you like to change the account authority?");

            if (changeAuthority)
            {
                Console.WriteLine("New authority: ");
                _consoleHelper.DisplayEnum <AuthorityType>();
                user.Authority = (int)_consoleHelper.ReadEnum <AuthorityType>();
            }

            Console.WriteLine("--------------------------------");
            Console.WriteLine("User account information:");
            Console.WriteLine($"Username: {user.Username}");
            Console.WriteLine($"Email: {user.Email}");
            Console.WriteLine($"Authority: {(AuthorityType)user.Authority}");
            Console.WriteLine("--------------------------------");

            bool updateUser = (changeEmail || changePassword || changeAuthority) && _consoleHelper.AskConfirmation("Update user?");

            if (updateUser)
            {
                if (changeEmail)
                {
                    if (!user.Email.IsValidEmail())
                    {
                        Console.WriteLine($"Email '{user.Email}' is not valid.");
                        return;
                    }

                    if (database.Users.Any(x => x.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        Console.WriteLine($"Email '{user.Email}' is already used.");
                        return;
                    }
                }

                if (changePassword)
                {
                    if (!user.Password.Equals(passwordConfirmation))
                    {
                        Console.WriteLine("Passwords doesn't match.");
                        return;
                    }

                    user.Password = MD5.GetMD5Hash(passwordSalt, user.Password);
                }

                database.Users.Update(user);
                database.SaveChanges();
                Console.WriteLine($"User '{user.Username}' has been updated.");
            }
        }
Пример #8
0
        public void OnExecute()
        {
            if (string.IsNullOrEmpty(DatabaseConfigurationFile))
            {
                DatabaseConfigurationFile = ConfigurationConstants.DatabasePath;
            }

            var dbConfig = ConfigurationHelper.Load <DatabaseConfiguration>(DatabaseConfigurationFile, ConfigurationConstants.DatabaseConfiguration);

            if (dbConfig is null)
            {
                Console.WriteLine("Couldn't load database configuration file during execution of user create command.");
                return;
            }

            var user = new DbUser();

            Console.Write("Username: "******"Email: ");
            user.Email = Console.ReadLine();

            Console.Write("Password: "******"Password confirmation: ");
            string passwordConfirmation = _consoleHelper.ReadPassword();

            Console.Write("Password salt: ");
            string passwordSalt = _consoleHelper.ReadStringOrDefault();

            Console.WriteLine("Authority: ");
            _consoleHelper.DisplayEnum <AuthorityType>();
            user.Authority = (int)_consoleHelper.ReadEnum <AuthorityType>();

            Console.WriteLine("--------------------------------");
            Console.WriteLine("User account information:");
            Console.WriteLine($"Username: {user.Username}");
            Console.WriteLine($"Email: {user.Email}");
            Console.WriteLine($"Authority: {(AuthorityType)user.Authority}");
            Console.WriteLine("--------------------------------");

            bool response = _consoleHelper.AskConfirmation("Create user?");

            if (response)
            {
                using IRhisisDatabase database = _databaseFactory.CreateDatabaseInstance(dbConfig);

                if (database.Users.Any(x => x.Username.Equals(user.Username, StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine($"User '{user.Username}' is already used.");
                    return;
                }

                if (!user.Email.IsValidEmail())
                {
                    Console.WriteLine($"Email '{user.Email}' is not valid.");
                    return;
                }

                if (database.Users.Any(x => x.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine($"Email '{user.Email}' is already used.");
                    return;
                }

                if (!user.Password.Equals(passwordConfirmation))
                {
                    Console.WriteLine("Passwords doesn't match.");
                    return;
                }

                user.Password = MD5.GetMD5Hash(passwordSalt, user.Password);

                database.Users.Add(user);
                database.SaveChanges();

                Console.WriteLine($"User '{user.Username}' created.");
            }
        }