示例#1
0
文件: World.cs 项目: saroque/server
        public bool PlayerExists(string name)
        {
            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {
                var count = ctx.players.Where(player => player.name == name).Count();
                Logger.DebugFormat("count is {0}", count);
                return count != 0;

            }
        }
示例#2
0
文件: World.cs 项目: saroque/server
        private void LoadData()
        {
            var random = new Random();
            var elements = Enum.GetValues(typeof(Element)); 
            try
            {
                using (var ctx = new hybrasylEntities(Constants.ConnectionString))
                {
                    var maps = ctx.maps.Include("warps").Include("worldwarps").Include("npcs").Include("spawns").ToList();

                    var worldmaps = ctx.worldmaps.Include("worldmap_points").ToList();
                    var items = ctx.items.ToList();
                    //var doors = ctx.doors.ToList();
                    var signposts = ctx.signposts.ToList();

                    Logger.InfoFormat("Adding {0} worldmaps", ctx.worldmaps.Count());

                    foreach (var wmap in worldmaps)
                    {
                        var worldmap = new WorldMap();
                        worldmap.World = this;
                        worldmap.Id = wmap.id;
                        worldmap.Name = wmap.name;
                        worldmap.ClientMap = wmap.client_map;
                        WorldMaps.Add(worldmap.Id, worldmap);

                        foreach (var mappoint in wmap.worldmap_points)
                        {
                            var point = new MapPoint();
                            point.Parent = worldmap;
                            point.Id = (Int64) mappoint.id;
                            point.Name = (string) mappoint.name;
                            point.DestinationMap = (ushort) mappoint.target_map_id;
                            point.DestinationX = (byte) mappoint.target_x;
                            point.DestinationY = (byte) mappoint.target_y;
                            point.X = (int) mappoint.map_x;
                            point.Y = (int) mappoint.map_y;
                            point.XOffset = point.X%255;
                            point.YOffset = point.Y%255;
                            point.XQuadrant = (point.X - point.XOffset)/255;
                            point.YQuadrant = (point.Y - point.YOffset)/255;
                            worldmap.Points.Add(point);
                            MapPoints.Add(point.Id, point);
                        }
                    }
                    Logger.InfoFormat("Adding {0} maps", ctx.maps.Count());

                    foreach (var map in maps)
                    {
                        var newmap = new Map();
                        newmap.World = this;
                        newmap.Id = (ushort) map.id;
                        newmap.X = (byte) map.size_x;
                        newmap.Y = (byte) map.size_y;
                        newmap.Name = (string) map.name;
                        newmap.Flags = (byte) map.flags;
                        newmap.Music = (byte) (map.music ?? 0);
                        newmap.EntityTree = new QuadTree<VisibleObject>(0, 0, map.size_x, map.size_y);

                        if (newmap.Load())
                        {
                            Maps.Add(newmap.Id, newmap);
                            try
                            {
                                MapCatalog.Add(newmap.Name, newmap);
                            }
                            catch
                            {
                                Logger.WarnFormat("map name {0}, id {1} ignored for map catalog",
                                    newmap.Name, newmap.Id);
                            }

                            foreach (var warp in map.warps)
                            {
                                AddWarp(warp);
                            }

                            foreach (var worldwarp in map.worldwarps)
                            {
                                AddWorldWarp(worldwarp);
                            }

                            foreach (var npc in map.npcs)
                            {
                                newmap.InsertNpc(npc);
                                if (npc.portrait != null)
                                {
                                    Portraits[npc.name] = npc.portrait;
                                }
                            }

                            foreach (var spawn in map.spawns)
                            {
                                AddSpawn(spawn);
                            }
                        }
                    }

                    // We have to handle signposts separately due to a bug in MySQL connector
                    foreach (var signpost in signposts)
                    {
                        Map postmap;
                        if (Maps.TryGetValue((ushort) signpost.map_id, out postmap))
                            postmap.InsertSignpost(signpost);
                        else
                            Logger.ErrorFormat("Signpost {0}: {1},{2}: Map {0} is missing ", signpost.id,
                                signpost.map_x, signpost.map_y, signpost.map_id);
                    }

                    int variantId = Hybrasyl.Constants.VARIANT_ID_START;

                    Logger.InfoFormat("Adding {0} items", items.Count);
                    var variants = ctx.item_variant.ToList();

                    foreach (var item in items)
                    {
                        Logger.DebugFormat("Adding item {0}", item.name);
                        item.Variants = new Dictionary<int, item>();

                        // Handle the case of item having random element, which is an optional bit of support
                        // and not really intended for serious use
                        if (item.element == Element.Random)
                        {
                            item.element = (Element)elements.GetValue(random.Next(elements.Length - 1 ));
                        }

                        if (item.has_consecratable_variants)
                        {
                            foreach (var variant in variants.Where(variant => variant.consecratable_variant == true))
                            {
                                var newitem = variant.ResolveVariant(item);
                                newitem.id = variantId;
                                Items.Add(variantId, newitem);
                                item.Variants[variant.id] = newitem;
                                variantId++;
                            }
                        }

                        if (item.has_elemental_variants)
                        {
                            foreach (var variant in variants.Where(variant => variant.elemental_variant == true))
                            {
                                var newitem = variant.ResolveVariant(item);
                                newitem.id = variantId;
                                Items.Add(variantId, newitem);
                                item.Variants[variant.id] = newitem;
                                variantId++;
                            }
                        }

                        if (item.has_enchantable_variants)
                        {
                            foreach (var variant in variants.Where(variant => variant.enchantable_variant == true))
                            {
                                var newitem = variant.ResolveVariant(item);
                                newitem.id = variantId;
                                Items.Add(variantId, newitem);
                                item.Variants[variant.id] = newitem;
                                variantId++;
                            }
                        }

                        if (item.has_smithable_variants)
                        {
                            foreach (var variant in variants.Where(variant => variant.smithable_variant == true))
                            {
                                var newitem = variant.ResolveVariant(item);
                                newitem.id = variantId;
                                Items.Add(variantId, newitem);
                                item.Variants[variant.id] = newitem;
                                variantId++;
                            }
                        }

                        if (item.has_tailorable_variants)
                        {
                            foreach (var variant in variants.Where(variant => variant.tailorable_variant == true))
                            {
                                var newitem = variant.ResolveVariant(item);
                                newitem.id = variantId;
                                Items.Add(variantId, newitem);
                                item.Variants[variant.id] = newitem;
                                variantId++;
                            }
                        }
                        Items.Add(item.id, item);
                        try
                        {
                            ItemCatalog.Add(new Tuple<Sex, String>(item.sex, item.name), item);
                        }
                        catch
                        {
                            Logger.WarnFormat("probable duplicate item {0} not added to item catalog", item.name);
                        }
                    }
                    Logger.InfoFormat("Added {0} item variants", variantId - Hybrasyl.Constants.VARIANT_ID_START);
                    Logger.InfoFormat("{0} items (including variants) active", Items.Count);

                    // Load national data
                    Nations = ctx.nations.Include("spawn_points").ToDictionary(n => n.name, n => n);
                }
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Error initializing Hybrasyl data: {0} {1}", e, e.InnerException);
                Logger.ErrorFormat("Beware, server is now likely inconsistent and should be shut down");
            }
        }
示例#3
0
文件: User.cs 项目: saroque/server
        public bool SaveDataToEntityFramework()
        {
            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {
                var playerquery = ctx.players.Where(player => player.name == Name).SingleOrDefault();

                if (playerquery == null)
                {
                    return false;
                }

                var inventory = new JArray();
                var equipment = new JArray();

                for (byte i = 1; i <= Inventory.Size; ++i)
                {
                    if (Inventory[i] == null) continue;
                    var obj = new JObject();
                    obj.Add("slot", (int)i);
                    obj.Add("count", Inventory[i].Count);
                    if (Inventory[i].IsVariant)
                    {
                        obj.Add("item_id", Inventory[i].ParentItem.id);
                        obj.Add("variant_id", Inventory[i].CurrentVariant.id);
                    }
                    else
                    {
                        obj.Add("item_id", Inventory[i].TemplateId);
                    }
                    inventory.Add(obj);
                }

                for (byte i = 1; i < Equipment.Size; ++i)
                {
                    if (Equipment[i] == null) continue;
                    var obj = new JObject();
                    obj.Add("slot", (int)i);
                    if (Equipment[i].IsVariant)
                    {
                        obj.Add("item_id", Equipment[i].ParentItem.id);
                        obj.Add("variant_id", Equipment[i].CurrentVariant.id);
                    }
                    else
                    {
                        obj.Add("item_id", Equipment[i].TemplateId);
                    }
                    equipment.Add(obj);
                }

                foreach (var property in GetType().GetProperties())
                {
                    string value;
                    if (User.EntityFrameworkMapping.TryGetValue(property.Name, out value))
                    {
                        // Nullables on the DB side need special handling to cast correctly.
                        var curType = property.PropertyType;
                        var destType = Nullable.GetUnderlyingType(typeof(player).GetProperty(value).PropertyType) ??
                            typeof(player).GetProperty(value).PropertyType;
                        object safevalue = (value == null) ? null : Convert.ChangeType(property.GetValue(this), destType);

                        // BEWARE - this will break if passed Enums that aren't handled via EF 5's enum support!
                        ctx.Entry(playerquery).Property(value).CurrentValue = safevalue;
                    }
                }

                ctx.Entry(playerquery).Property("inventory").CurrentValue = inventory.ToString();
                ctx.Entry(playerquery).Property("equipment").CurrentValue = equipment.ToString();

                // Save our current location
                ctx.Entry(playerquery).Property("map_id").CurrentValue = (int)Map.Id;
                ctx.Entry(playerquery).Property("map_x").CurrentValue = (int)X; ;
                ctx.Entry(playerquery).Property("map_y").CurrentValue = (int)Y;

                if (Citizenship != null)
                    ctx.Entry(playerquery).Property("nation_id").CurrentValue = Citizenship.id;

                ctx.SaveChanges();

            }

            return true;
        }
示例#4
0
文件: World.cs 项目: saroque/server
        private void LoadReactors()
        {
            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {
                foreach (var reactor in ctx.reactors)
                {
                    Map map;
                    if (Maps.TryGetValue((ushort)reactor.map_id, out map))
                    {
                        map.InsertReactor(reactor);
                    }
                }

            }
        }
示例#5
0
文件: User.cs 项目: saroque/server
        public bool LoadDataFromEntityFramework(bool updateInventory = false)
        {
            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {
                var playerquery = ctx.players.Where(player => player.name == Name).SingleOrDefault();
                if (playerquery == null)
                {
                    return false;
                }

                foreach (var property in GetType().GetProperties())
                {
                    string value;
                    if (User.EntityFrameworkMapping.TryGetValue(property.Name, out value))
                    {
                        SetValue(property, this, ctx.Entry(playerquery).Property(User.EntityFrameworkMapping[property.Name]).CurrentValue);
                    }
                }

                // Now load our attributes
                Flags = playerquery.flags.ToDictionary(v => v.name, v => true);

                Account = playerquery.account;
                // Set our citizenship
                nation citizenship;
                if (playerquery.nation != null && World.Nations.TryGetValue(playerquery.nation.name, out citizenship))
                    Citizenship = citizenship;
                else
                    Citizenship = World.Nations[Hybrasyl.Constants.DEFAULT_CITIZENSHIP];

                LogoffTime = playerquery.last_logoff ?? DateTime.Now;

                // Legend marks
                LegendMarks = playerquery.legend_marks.ToList();

                // Are we updating inventory & equipment?

                if (updateInventory)
                {
                    var inventory = JArray.Parse((string)playerquery.inventory);
                    var equipment = JArray.Parse((string)playerquery.equipment);

                    foreach (var obj in inventory)
                    {
                        Logger.DebugFormat("Inventory found");
                        PrettyPrinter.PrettyPrint(obj);
                        var itemId = (int)obj["item_id"];
                        int itemSlot = (int)obj["slot"];
                        var variantId = obj.Value<int?>("variant_id") ?? -1;

                        if (variantId > 0)
                            itemId = Game.World.Items[itemId].Variants[variantId].id;

                        var item = Game.World.CreateItem(itemId);
                        item.Count = obj.Value<int?>("count") ?? 1;

                        if (item != null)
                        {
                            Game.World.Insert(item);
                            AddItem(item, (byte)itemSlot);
                        }
                        Logger.DebugFormat("Item is {0}", itemId);
                    }

                    foreach (var obj in equipment)
                    {
                        var itemId = (int)obj["item_id"];
                        var itemSlot = (int)obj["slot"];
                        var variantId = obj.Value<int?>("variant_id") ?? -1;

                        if (variantId > 0)
                            itemId = Game.World.Items[itemId].Variants[variantId].id;

                        var item = Game.World.CreateItem(itemId);

                        if (item != null)
                        {
                            Logger.DebugFormat("Adding equipment: {0} to {1}", item.Name, itemSlot);
                            Game.World.Insert(item);
                            AddEquipment(item, (byte)itemSlot, false);
                        }
                        Logger.DebugFormat("Equipment is {0}", itemId);
                    }
                }
            }
            return true;
        }
示例#6
0
文件: User.cs 项目: saroque/server
 /// <summary>
 /// Update a player's last logoff time in the database and the live object.
 /// </summary>
 public void UpdateLogoffTime()
 {
     using (var ctx = new hybrasylEntities(Constants.ConnectionString))
     {
         var playerquery = ctx.players.Where(player => player.name == Name).SingleOrDefault();
         if (playerquery == null)
         {
             // This means something very odd is happening; we might want to throw an exception
             // or do something else here
             return;
         }
         else
         {
             var now = DateTime.Now;
             LoginTime = now;
             ctx.Entry(playerquery).Property("last_logoff").CurrentValue = now;
             ctx.SaveChanges();
         }
     }
 }
示例#7
0
文件: Login.cs 项目: saroque/server
        // Chart for all error password-related error codes were provided by kojasou@ on
        // https://github.com/hybrasyl/server/pull/11.
        private void PacketHandler_0x26_ChangePassword(Client client, ClientPacket packet)
        {
            var name = packet.ReadString8();
            var currentPass = packet.ReadString8();
            // Clientside validation ensures that the same string is typed twice for the new
            // password, and the new password is only sent to the server once. We can assume
            // that they matched if 0x26 request is sent from the client.
            var newPass = packet.ReadString8();

            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {
                var player = ctx.players.Where(p => p.name == name).SingleOrDefault();

                // Check that `name` exists. If not, return a message indicating that to the user.
                if (player == null)
                {
                    client.LoginMessage(GetPasswordError(0x0E), 0x0E);
                    Logger.DebugFormat("Password change attempt on invalid player `{0}`", name);
                }
                // If the player does exist, validate the current and new passwords before updating.
                else
                {
                    // Check that the current password is correct and the new password is different
                    // than the current password.
                    if (VerifyPassword(currentPass, player))
                    {
                        // Check if the password is valid.
                        byte err = 0x00;
                        if (ValidPassword(newPass, out err))
                        {
                            player.password_hash = HashPassword(newPass);
                            ctx.SaveChanges();

                            // Let the user know the good news.
                            client.LoginMessage("Your password has been changed successfully.", 0x0);
                            Logger.InfoFormat("Password successfully changed for `{0}`", name);
                        }
                        else
                        {
                            client.LoginMessage(GetPasswordError(err), err);
                            Logger.ErrorFormat("Invalid new password proposed during password change attempt for `{0}`", name);
                        }
                    }
                    // The current password is incorrect. Don't allow any changes to happen.
                    else
                    {
                        client.LoginMessage(GetPasswordError(0x0F), 0x0F);
                        Logger.ErrorFormat("Invalid current password during password change attempt for `{0}`", name);
                    }
                }
            }
        }
示例#8
0
文件: Login.cs 项目: saroque/server
        private void PacketHandler_0x04_CreateB(Client client, ClientPacket packet)
        {
            if (string.IsNullOrEmpty(client.NewCharacterName) || string.IsNullOrEmpty(client.NewCharacterPassword))
                return;

            var hairStyle = packet.ReadByte();
            var sex = packet.ReadByte();
            var hairColor = packet.ReadByte();

            if (hairStyle < 1)
                hairStyle = 1;

            if (hairStyle > 17)
                hairStyle = 17;

            if (hairColor > 13)
                hairColor = 13;

            if (sex < 1)
                sex = 1;

            if (sex > 2)
                sex = 2;

            if (!Game.World.PlayerExists(client.NewCharacterName))
            {
                using (var ctx = new hybrasylEntities(Constants.ConnectionString))
                {
                    player newplayer = new player
                    {
                        name = client.NewCharacterName,
                        password_hash = client.NewCharacterPassword,
                        sex = (Sex) sex,
                        hairstyle = hairStyle,
                        haircolor = hairColor,
                        map_id = 136,
                        map_x = 10,
                        map_y = 10,
                        direction = 1,
                        class_type = 0,
                        level = 1,
                        exp = 0,
                        ab = 0,
                        gold = 0,
                        ab_exp = 0,
                        max_hp = 50,
                        max_mp = 50,
                        cur_hp = 50,
                        cur_mp = 35,
                        str = 3,
                        @int = 3,
                        wis = 3,
                        con = 3,
                        dex = 3,
                        inventory = "[]",
                        equipment = "[]",
                        created_at = DateTime.Now
                    };
                    try
                    {
                        ctx.players.Add(newplayer);
                        ctx.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("Error saving new player!");
                        Logger.ErrorFormat(e.ToString());
                        client.LoginMessage("Unknown error. Contact [email protected]", 3);
                    }
                    client.LoginMessage("\0", 0);
                }
            }
        }
示例#9
0
文件: Login.cs 项目: saroque/server
        private void PacketHandler_0x03_Login(Client client, ClientPacket packet)
        {
            var name = packet.ReadString8();
            var password = packet.ReadString8();
            Logger.DebugFormat("cid {0}: Login request for {1}", client.ConnectionId, name);

            using (var ctx = new hybrasylEntities(Constants.ConnectionString))
            {

                var result = ctx.players.Where(player => player.name == name).SingleOrDefault();

                if (result == null)
                {
                    client.LoginMessage("That character does not exist", 3);
                    Logger.InfoFormat("cid {0}: attempt to login as nonexistent character {1}", client.ConnectionId, name);
                }
                else
                {
                    if (VerifyPassword(password, result))
                    {
                        Logger.DebugFormat("cid {0}: password verified for {1}", client.ConnectionId, name);

                        if (Game.World.ActiveUsersByName.ContainsKey(name))
                        {
                            Logger.InfoFormat("cid {0}: {1} logging on again, disconnecting previous connection",
                                client.ConnectionId, name);
                            World.MessageQueue.Add(new HybrasylControlMessage(ControlOpcodes.LogoffUser, name));
                        }

                        Logger.DebugFormat("cid {0} ({1}): logging in", client.ConnectionId, name);
                        client.LoginMessage("\0", 0);
                        client.SendMessage("Welcome to Hybrasyl!", 3);
                        Logger.DebugFormat("cid {0} ({1}): sending redirect to world", client.ConnectionId, name);

                        var redirect = new Redirect(client, this, Game.World, name, client.EncryptionSeed,
                            client.EncryptionKey);
                        Logger.InfoFormat("cid {0} ({1}): login successful, redirecting to world server",
                            client.ConnectionId, name);
                        client.Redirect(redirect);
                    }
                    else
                    {
                        Logger.WarnFormat("cid {0} ({1}): password incorrect", client.ConnectionId, name);
                        client.LoginMessage("Incorrect password", 3);
                    }
                }
            }
        }