Esempio n. 1
0
        /// <summary>
        /// Called when [new friendship].
        /// </summary>
        /// <param name="friendId">The friend identifier.</param>
        internal void OnNewFriendship(uint friendId)
        {
            var            clientByUserId = Plus.GetGame().GetClientManager().GetClientByUserId(friendId);
            MessengerBuddy messengerBuddy;

            if (clientByUserId == null || clientByUserId.GetHabbo() == null)
            {
                DataRow row;
                using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.SetQuery(
                        string.Format(
                            "SELECT id,username,motto,look,last_online,hide_inroom,hide_online FROM users WHERE id = {0}",
                            friendId));
                    row = queryReactor.GetRow();
                }
                messengerBuddy = new MessengerBuddy(friendId, (string)row["Username"], (string)row["look"],
                                                    (string)row["motto"], (int)row["last_online"], Plus.EnumToBool(row["hide_online"].ToString()),
                                                    Plus.EnumToBool(row["hide_inroom"].ToString()));
            }
            else
            {
                var habbo = clientByUserId.GetHabbo();
                messengerBuddy = new MessengerBuddy(friendId, habbo.UserName, habbo.Look, habbo.Motto, 0,
                                                    habbo.AppearOffline, habbo.HideInRoom);
                messengerBuddy.UpdateUser();
            }
            if (!Friends.ContainsKey(friendId))
            {
                Friends.Add(friendId, messengerBuddy);
            }
            GetClient().SendMessage(SerializeUpdate(messengerBuddy));
        }
Esempio n. 2
0
        /// <summary>
        /// Loads the new model.
        /// </summary>
        /// <param name="model">The model.</param>
        internal void LoadNewModel(string model)
        {
            if (_roomModels.Contains(model))
            {
                _roomModels.Remove(model);
            }

            using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery(
                    "SELECT id,door_x,door_y,door_z,door_dir,heightmap,public_items,club_only,poolmap FROM rooms_models WHERE id = @model");
                queryReactor.AddParameter("model", model);
                var table = queryReactor.GetTable();
                if (table == null)
                {
                    return;
                }
                foreach (DataRow row in table.Rows)
                {
                    var staticFurniMap = (string)row["public_items"];
                    _roomModels.Add(model,
                                    new RoomModel((int)row["door_x"], (int)row["door_y"], (double)row["door_z"],
                                                  (int)row["door_dir"], (string)row["heightmap"], staticFurniMap,
                                                  Plus.EnumToBool(row["club_only"].ToString()), (string)row["poolmap"]));
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserPreferences"/> class.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        internal UserPreferences(uint userId)
        {
            _userId = userId;
            DataRow row;

            using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery("SELECT * FROM users_preferences WHERE userid = " + _userId);
                queryReactor.AddParameter("userid", _userId);
                row = queryReactor.GetRow();

                if (row == null)
                {
                    queryReactor.RunFastQuery("REPLACE INTO users_preferences (userid, volume) VALUES (" + _userId + ", '100,100,100')");
                    return;
                }
            }
            PreferOldChat       = Plus.EnumToBool((string)row["prefer_old_chat"]);
            IgnoreRoomInvite    = Plus.EnumToBool((string)row["ignore_room_invite"]);
            DisableCameraFollow = Plus.EnumToBool((string)row["disable_camera_follow"]);
            Volume        = (string)row["volume"];
            NewnaviX      = Convert.ToInt32(row["newnavi_x"]);
            NewnaviY      = Convert.ToInt32(row["newnavi_y"]);
            NewnaviWidth  = Convert.ToInt32(row["newnavi_width"]);
            NewnaviHeight = Convert.ToInt32(row["newnavi_height"]);
        }
Esempio n. 4
0
        /// <summary>
        /// Initializes the specified database client.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        public void Initialize(IQueryAdapter dbClient)
        {
            dbClient.SetQuery("SELECT * FROM navigator_flatcats WHERE enabled = '2'");
            var table = dbClient.GetTable();

            dbClient.SetQuery("SELECT * FROM navigator_publics");
            var table2 = dbClient.GetTable();

            dbClient.SetQuery("SELECT * FROM navigator_pubcats");
            var table3 = dbClient.GetTable();

            dbClient.SetQuery("SELECT * FROM navigator_promocats");
            var table4 = dbClient.GetTable();

            if (table4 != null)
            {
                PromoCategories.Clear();
                foreach (DataRow dataRow in table4.Rows)
                {
                    PromoCategories.Add((int)dataRow["id"],
                                        new PromoCat((int)dataRow["id"], (string)dataRow["caption"], (int)dataRow["min_rank"],
                                                     Plus.EnumToBool((string)dataRow["visible"])));
                }
            }
            if (table != null)
            {
                PrivateCategories.Clear();
                foreach (DataRow dataRow in table.Rows)
                {
                    PrivateCategories.Add((int)dataRow["id"],
                                          new FlatCat((int)dataRow["id"], (string)dataRow["caption"], (int)dataRow["min_rank"]));
                }
            }
            if (table2 != null)
            {
                _publicItems.Clear();
                foreach (DataRow row in table2.Rows)
                {
                    _publicItems.Add(Convert.ToUInt32(row["id"]),
                                     new PublicItem((int)row["id"], int.Parse(row["bannertype"].ToString()), (string)row["caption"],
                                                    (string)row["description"], (string)row["image"],
                                                    row["image_type"].ToString().ToLower() == "internal"
                                ? PublicImageType.Internal
                                : PublicImageType.External, (uint)row["room_id"], 0, (int)row["category_parent_id"],
                                                    row["recommended"].ToString() == "1", (int)row["typeofdata"], string.Empty));
                }
            }
            if (table3 != null)
            {
                InCategories.Clear();
                foreach (DataRow dataRow in table3.Rows)
                {
                    InCategories.Add((int)dataRow["id"], (string)dataRow["caption"]);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Generates the preset.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>MoodlightPreset.</returns>
        internal static MoodlightPreset GeneratePreset(string data)
        {
            var array = data.Split(',');

            if (!IsValidColor(array[0]))
            {
                array[0] = "#000000";
            }

            return(new MoodlightPreset(array[0], int.Parse(array[1]), Plus.EnumToBool(array[2])));
        }
Esempio n. 6
0
        /// <summary>
        /// Loads the models.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        internal void LoadModels(IQueryAdapter dbClient)
        {
            _roomModels.Clear();
            dbClient.SetQuery(
                "SELECT id,door_x,door_y,door_z,door_dir,heightmap,public_items,club_only,poolmap FROM rooms_models");
            var table = dbClient.GetTable();

            if (table == null)
            {
                return;
            }
            foreach (DataRow dataRow in table.Rows)
            {
                var key = (string)dataRow["id"];
                if (key.StartsWith("model_floorplan_"))
                {
                    continue;
                }
                var staticFurniMap = (string)dataRow["public_items"];
                _roomModels.Add(key,
                                new RoomModel((int)dataRow["door_x"], (int)dataRow["door_y"], (double)dataRow["door_z"],
                                              (int)dataRow["door_dir"], (string)dataRow["heightmap"], staticFurniMap,
                                              Plus.EnumToBool(dataRow["club_only"].ToString()), (string)dataRow["poolmap"]));
            }
            dbClient.SetQuery("SELECT roomid,door_x,door_y,door_z,door_dir,heightmap FROM rooms_models_customs");
            var dataCustom = dbClient.GetTable();

            if (dataCustom == null)
            {
                return;
            }

            foreach (DataRow row in dataCustom.Rows)
            {
                var modelName = string.Format("custom_{0}", row["roomid"]);
                _roomModels.Add(modelName,
                                new RoomModel((int)row["door_x"], (int)row["door_y"], (double)row["door_z"],
                                              (int)row["door_dir"],
                                              (string)row["heightmap"], "", false, ""));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MoodlightData"/> class.
        /// </summary>
        /// <param name="itemId">The item identifier.</param>
        /// <exception cref="System.NullReferenceException">No moodlightdata found in the database</exception>
        internal MoodlightData(uint itemId)
        {
            ItemId = itemId;
            DataRow row;

            using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery(string.Format(format: "SELECT enabled,current_preset,preset_one,preset_two,preset_three FROM items_moodlight WHERE item_id='{0}'", arg0: itemId));
                row = queryReactor.GetRow();
            }
            if (row != null)
            {
                Enabled       = Plus.EnumToBool(row["enabled"].ToString());
                CurrentPreset = (int)row["current_preset"];
                Presets       = new List <MoodlightPreset> {
                    GeneratePreset((string)row["preset_one"]),
                    GeneratePreset((string)row["preset_two"]),
                    GeneratePreset((string)row["preset_three"])
                };
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Fills the specified row.
        /// </summary>
        /// <param name="row">The row.</param>
        internal void Fill(DataRow row)
        {
            try
            {
                Id          = Convert.ToUInt32(row["id"]);
                Name        = (string)row["caption"];
                PassWord    = (string)row["password"];
                Description = (string)row["description"];
                Type        = (string)row["roomtype"];
                Owner       = (string)row["owner"];
                OwnerId     = 0;
                RoomChat    = new List <Chatlog>();
                WordFilter  = new List <string>();

                using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.SetQuery("SELECT id FROM users WHERE username = @name");
                    queryReactor.AddParameter("name", Owner);
                    uint integer = Convert.ToUInt32(queryReactor.GetInteger());

                    OwnerId = integer != uint.MinValue ? Convert.ToInt32(integer) : 0;

                    /*queryReactor.SetQuery(string.Format("SELECT user_id, message, timestamp FROM users_chatlogs WHERE room_id= '{0}' ORDER BY timestamp ASC LIMIT 350", Id));
                     * var table = queryReactor.GetTable();
                     * foreach (DataRow dataRow in table.Rows)
                     * {
                     *  RoomChat.Add(new Chatlog((uint)dataRow[0], (string)dataRow[1], Plus.UnixToDateTime(int.Parse(dataRow[2].ToString())), false));
                     * }*/

                    queryReactor.SetQuery(string.Format("SELECT word FROM rooms_wordfilter WHERE room_id = '{0}'", Id));
                    var tableFilter = queryReactor.GetTable();

                    foreach (DataRow dataRow in tableFilter.Rows)
                    {
                        WordFilter.Add(dataRow["word"].ToString());
                    }
                }
                var roomState = row["state"].ToString().ToLower();

                switch (roomState)
                {
                case "locked":
                    State = 1;
                    break;

                case "password":
                    State = 2;
                    break;

                case "open":
                default:
                    State = 0;
                    break;
                }

                ModelName = (string)row["model_name"];
                WallPaper = (string)row["wallpaper"];
                Floor     = (string)row["floor"];
                LandScape = (string)row["landscape"];
                CCTs      = (string)row["public_ccts"];

                int.TryParse(row["trade_state"].ToString(), out TradeState);
                int.TryParse(row["category"].ToString(), out Category);
                int.TryParse(row["walls_height"].ToString(), out WallHeight);
                int.TryParse(row["score"].ToString(), out Score);
                int.TryParse(row["floorthick"].ToString(), out FloorThickness);
                int.TryParse(row["wallthick"].ToString(), out WallThickness);
                int.TryParse(row["chat_type"].ToString(), out ChatType);
                int.TryParse(row["game_id"].ToString(), out GameId);
                int.TryParse(row["mute_settings"].ToString(), out WhoCanMute);
                int.TryParse(row["kick_settings"].ToString(), out WhoCanKick);
                int.TryParse(row["ban_settings"].ToString(), out WhoCanBan);

                uint.TryParse(row["users_now"].ToString(), out UsersNow);
                uint.TryParse(row["users_max"].ToString(), out UsersMax);
                uint.TryParse(row["group_id"].ToString(), out GroupId);
                uint.TryParse(row["chat_balloon"].ToString(), out ChatBalloon);
                uint.TryParse(row["chat_speed"].ToString(), out ChatSpeed);
                uint.TryParse(row["chat_max_distance"].ToString(), out ChatMaxDistance);
                uint.TryParse(row["chat_flood_protection"].ToString(), out ChatFloodProtection);

                AllowPets        = Plus.EnumToBool(row["allow_pets"].ToString());
                AllowPetsEating  = Plus.EnumToBool(row["allow_pets_eat"].ToString());
                AllowWalkThrough = Plus.EnumToBool(row["allow_walkthrough"].ToString());
                HideWall         = Plus.EnumToBool(row["hidewall"].ToString());

                AllowRightsOverride = false;

                Group             = Plus.GetGame().GetGroupManager().GetGroup(GroupId);
                Event             = Plus.GetGame().GetRoomEvents().GetEvent(Id);
                _model            = Plus.GetGame().GetRoomManager().GetModel(ModelName, Id);
                CompetitionStatus = 0;

                Tags = new List <string>();

                if (row.IsNull("tags") || !string.IsNullOrEmpty(row["tags"].ToString()))
                {
                    return;
                }

                foreach (var item in row["tags"].ToString().Split(','))
                {
                    Tags.Add(item);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException("Exception on RoomData Loading (Fill Void): " + ex);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Requests the buddy.
        /// </summary>
        /// <param name="userQuery">The user query.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        internal bool RequestBuddy(string userQuery)
        {
            var  clientByUsername = Plus.GetGame().GetClientManager().GetClientByUserName(userQuery);
            uint num;
            bool flag;

            if (GetClient().GetRoleplay().Phone == 0)
            {
                GetClient().SendNotif("You do not have a phone to add contacts!");
                return(true);
            }

            if (clientByUsername == null)
            {
                DataRow dataRow;
                using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.SetQuery("SELECT id,block_newfriends FROM users WHERE Username = @query");
                    queryReactor.AddParameter("query", userQuery.ToLower());
                    dataRow = queryReactor.GetRow();
                }
                if (dataRow == null)
                {
                    return(false);
                }
                num  = Convert.ToUInt32(dataRow["id"]);
                flag = Plus.EnumToBool(dataRow["block_newfriends"].ToString());
            }
            else
            {
                num  = clientByUsername.GetHabbo().Id;
                flag = clientByUsername.GetHabbo().HasFriendRequestsDisabled;
            }
            if (flag && GetClient().GetHabbo().Rank < 4u)
            {
                GetClient()
                .GetMessageHandler()
                .GetResponse()
                .Init(LibraryParser.OutgoingRequest("NotAcceptingRequestsMessageComposer"));
                GetClient().GetMessageHandler().GetResponse().AppendInteger(39);
                GetClient().GetMessageHandler().GetResponse().AppendInteger(3);
                GetClient().GetMessageHandler().SendResponse();
                return(false);
            }
            var num2 = num;

            if (RequestExists(num2))
            {
                GetClient().SendNotif("Ya le has enviado una petición anteriormente.");
                return(true);
            }
            using (var queryreactor2 = Plus.GetDatabaseManager().GetQueryReactor())
                queryreactor2.RunFastQuery(string.Concat(new object[]
                {
                    "REPLACE INTO messenger_requests (from_id,to_id) VALUES (",
                    _userId,
                    ",",
                    num2,
                    ")"
                }));
            Plus.GetGame().GetQuestManager().ProgressUserQuest(GetClient(), QuestType.AddFriends, 0u);
            var clientByUserId = Plus.GetGame().GetClientManager().GetClientByUserId(num2);

            if (clientByUserId == null || clientByUserId.GetHabbo() == null)
            {
                return(true);
            }
            var messengerRequest = new MessengerRequest(num2, _userId,
                                                        Plus.GetGame().GetClientManager().GetNameById(_userId));

            clientByUserId.GetHabbo().GetMessenger().OnNewRequest(_userId);
            var serverMessage =
                new ServerMessage(LibraryParser.OutgoingRequest("ConsoleSendFriendRequestMessageComposer"));

            messengerRequest.Serialize(serverMessage);
            clientByUserId.SendMessage(serverMessage);
            Requests.Add(num2, messengerRequest);
            return(true);
        }
Esempio n. 10
0
        /// <summary>
        /// Loads the items.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        internal void LoadItems(IQueryAdapter dbClient)
        {
            Items = new Dictionary <uint, Item>();
            Items.Clear();
            GiftWrappers.Clear();

            dbClient.SetQuery("SELECT * FROM catalog_furnis");
            var table = dbClient.GetTable();

            if (table == null)
            {
                return;
            }
            List <double> heights = null;

            foreach (DataRow dataRow in table.Rows)
            {
                try
                {
                    var    id             = Convert.ToUInt32(dataRow["id"]);
                    var    type           = Convert.ToChar(dataRow["type"]);
                    var    name           = Convert.ToString(dataRow["item_name"]);
                    var    flatId         = Convert.ToInt32(dataRow["flat_id"]);
                    var    stackHeightStr = dataRow["stack_height"].ToString();
                    double stackHeight;
                    uint   modes;
                    uint.TryParse(dataRow["interaction_modes_count"].ToString(), out modes);
                    var    vendingIds           = (string)dataRow["vending_ids"];
                    string variableheights      = Convert.ToString(dataRow["variable_heights"]);
                    var    sub                  = Plus.EnumToBool(dataRow["subscriber"].ToString());
                    var    effect               = (int)dataRow["effectid"];
                    var    stackable            = Convert.ToInt32(dataRow["can_stack"]) == 1;
                    var    allowRecycle         = Convert.ToInt32(dataRow["allow_recycle"]) == 1;
                    var    allowTrade           = Convert.ToInt32(dataRow["allow_trade"]) == 1;
                    var    allowMarketplaceSell = Convert.ToInt32(dataRow["allow_marketplace_sell"]) == 1;
                    var    allowGift            = Convert.ToInt32(dataRow["allow_gift"]) == 1;
                    var    allowInventoryStack  = Convert.ToInt32(dataRow["allow_inventory_stack"]) == 1;
                    var    typeFromString       = InteractionTypes.GetTypeFromString((string)dataRow["interaction_type"]);

                    var sprite = Convert.ToInt32(dataRow["sprite_id"]);

                    int  x = Convert.ToInt32(dataRow["width"]), y = Convert.ToInt32(dataRow["length"]);
                    var  publicName = Convert.ToString(dataRow["item_name"]);
                    bool canWalk = Convert.ToInt32(dataRow["is_walkable"]) == 1, canSit = Convert.ToInt32(dataRow["can_sit"]) == 1, stackMultiple = Plus.EnumToBool(dataRow["stack_multiplier"].ToString());

                    if (name.StartsWith("external_image_wallitem_poster"))
                    {
                        PhotoId = id;
                    }
                    // Special Types of Furnis

                    /*if (name == "landscape" || name == "floor" || name == "wallpaper")
                     * {
                     *  sprite = FurniDataParser.WallItems[name].Id;
                     *  x = 1;
                     *  y = 1;
                     * }
                     * else if (type == 's' && FurniDataParser.FloorItems.ContainsKey(name))
                     * {
                     *  sprite = FurniDataParser.FloorItems[name].Id;
                     *  publicName = FurniDataParser.FloorItems[name].Name;
                     *  x = FurniDataParser.FloorItems[name].X;
                     *  y = FurniDataParser.FloorItems[name].Y;
                     *  canWalk = FurniDataParser.FloorItems[name].CanWalk;
                     *  canSit = FurniDataParser.FloorItems[name].CanSit;
                     * }
                     * else if (type == 'i' && FurniDataParser.WallItems.ContainsKey(name))
                     * {
                     *  sprite = FurniDataParser.WallItems[name].Id;
                     *  publicName = FurniDataParser.WallItems[name].Name;
                     * }
                     * else if (name.StartsWith("a0 pet", StringComparison.InvariantCulture))
                     * {
                     *  x = 1;
                     *  y = 1;
                     *  publicName = name;
                     * }
                     * else if (type != 'e' && type != 'h' && type != 'r' && type != 'b') continue;*/

                    if (name.StartsWith("present_gen"))
                    {
                        GiftWrappers.AddOld((short)sprite);
                    }
                    else if (name.StartsWith("present_wrap*"))
                    {
                        GiftWrappers.Add((short)sprite);
                    }

                    // Stack Height Values
                    if (stackHeightStr.Contains(';'))
                    {
                        var heightsStr = stackHeightStr.Split(';');
                        heights =
                            heightsStr.Select(heightStr => double.Parse(heightStr, CultureInfo.InvariantCulture))
                            .ToList();
                        stackHeight   = heights[0];
                        stackMultiple = true;
                    }
                    else
                    {
                        stackHeight = double.Parse(stackHeightStr, CultureInfo.InvariantCulture);
                    }

                    // If Can Walk
                    if (InteractionTypes.AreFamiliar(GlobalInteractions.Gate, typeFromString) ||
                        typeFromString == Interaction.BanzaiPyramid || name.StartsWith("hole"))
                    {
                        canWalk = false;
                    }

                    // Add Item
                    var value = new Item(id, (int)sprite, publicName, name, type, x, y, stackHeight, stackable, canWalk,
                                         canSit, allowRecycle, allowTrade, allowMarketplaceSell, allowGift, allowInventoryStack,
                                         typeFromString, modes, vendingIds, sub, effect, stackMultiple,
                                         (heights == null ? null : heights.ToArray()), flatId, variableheights);
                    Items.Add(id, value);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.ReadKey();
                    Out.WriteLine(
                        string.Format("Could not load item #{0}, please verify the data is okay.",
                                      Convert.ToUInt32(dataRow[0])), "Plus.Items", ConsoleColor.DarkRed);
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Generates the habbo.
        /// </summary>
        /// <param name="dRow">The d row.</param>
        /// <param name="mRow">The m row.</param>
        /// <param name="group">The group.</param>
        /// <returns>Habbo.</returns>
        internal static Habbo GenerateHabbo(DataRow dRow, DataRow mRow, HashSet <GroupUser> group)
        {
            var id                       = uint.Parse(dRow["id"].ToString());
            var userName                 = (string)dRow["username"];
            var realName                 = (string)dRow["real_name"];
            var ras                      = uint.Parse(dRow["rank"].ToString());
            var motto                    = (string)dRow["motto"];
            var look                     = (string)dRow["look"];
            var gender                   = (string)dRow["gender"];
            var lastOnline               = int.Parse(dRow["last_online"].ToString());
            var credits                  = (int)dRow["credits"];
            var activityPoints           = (int)dRow["activity_points"];
            var lastActivityPointsUpdate = Convert.ToDouble(dRow["activity_points_lastupdate"]);
            var muted                    = Plus.EnumToBool(dRow["is_muted"].ToString());
            var homeRoom                 = Convert.ToUInt32(dRow["home_room"]);

            int  respect = 0, dailyRespectPoints = 3, dailyPetRespectPoints = 3, currentQuestProgress = 0, achievementPoints = 0, dailyCompetitionVotes = 3;
            uint currentQuestId = 0, favId = 0;

            try
            {
                respect               = (int)mRow["respect"];
                dailyRespectPoints    = (int)mRow["daily_respect_points"];
                dailyPetRespectPoints = (int)mRow["daily_pet_respect_points"];
                currentQuestId        = Convert.ToUInt32(mRow["quest_id"]);
                currentQuestProgress  = (int)mRow["quest_progress"];
                achievementPoints     = (int)mRow["achievement_score"];
                favId = uint.Parse(mRow["favourite_group"].ToString());
                dailyCompetitionVotes = (int)mRow["daily_competition_votes"];
            }
            catch (Exception)
            {
            }

            var hasFriendRequestsDisabled = Plus.EnumToBool(dRow["block_newfriends"].ToString());
            var appearOffline             = Plus.EnumToBool(dRow["hide_online"].ToString());
            var hideInRoom                = Plus.EnumToBool(dRow["hide_inroom"].ToString());
            var vip             = Plus.EnumToBool(dRow["vip"].ToString());
            var createDate      = Convert.ToDouble(dRow["account_created"]);
            var online          = Plus.EnumToBool(dRow["online"].ToString());
            var citizenship     = dRow["talent_status"].ToString();
            var belCredits      = int.Parse(dRow["seasonal_currency"].ToString());
            var lastChange      = (int)dRow["last_name_change"];
            var regTimestamp    = int.Parse(dRow["account_created"].ToString());
            var tradeLocked     = Plus.EnumToBool(dRow["trade_lock"].ToString());
            var tradeLockExpire = int.Parse(dRow["trade_lock_expire"].ToString());
            var nuxPassed       = Plus.EnumToBool(dRow["nux_passed"].ToString());

            /* builders club */
            var buildersExpire    = (int)dRow["builders_expire"];
            var buildersItemsMax  = (int)dRow["builders_items_max"];
            var buildersItemsUsed = (int)dRow["builders_items_used"];
            var releaseVersion    = (int)dRow["release_version"];
            var onDuty            = Convert.ToBoolean(dRow["OnDuty"]);

            var navilogs      = new Dictionary <int, NaviLogs>();
            var navilogstring = (string)dRow["navilogs"];

            if (navilogstring.Length > 0)
            {
                foreach (
                    var naviLogs in
                    navilogstring.Split(';')
                    .Where(value => navilogstring.Contains(","))
                    .Select(
                        value =>
                        new NaviLogs(int.Parse(value.Split(',')[0]), value.Split(',')[1],
                                     value.Split(',')[2]))
                    .Where(naviLogs => !navilogs.ContainsKey(naviLogs.Id)))
                {
                    navilogs.Add(naviLogs.Id, naviLogs);
                }
            }

            var newNavigator = dRow["navigator"].ToString() == "1";

            return(new Habbo(id, userName, realName, ras, motto, look, gender, credits, activityPoints,
                             lastActivityPointsUpdate, muted, homeRoom, respect, dailyRespectPoints, dailyPetRespectPoints,
                             hasFriendRequestsDisabled, currentQuestId, currentQuestProgress, achievementPoints, regTimestamp,
                             lastOnline, appearOffline, hideInRoom, vip, createDate, online, citizenship, belCredits, group, favId,
                             lastChange, tradeLocked, tradeLockExpire, nuxPassed, buildersExpire, buildersItemsMax,
                             buildersItemsUsed, releaseVersion, onDuty, navilogs, newNavigator, dailyCompetitionVotes));
        }
Esempio n. 12
0
        /// <summary>
        /// Gets the user data.
        /// </summary>
        /// <param name="sessionTicket">The session ticket.</param>
        /// <param name="ip">The ip.</param>
        /// <param name="errorCode">The error code.</param>
        /// <returns>UserData.</returns>
        /// <exception cref="UserDataNotFoundException"></exception>
        internal static UserData GetUserData(string sessionTicket, out uint errorCode)
        {
            uint userid = 0, miniMailCount = 0;

            errorCode = 1;

            DataTable groupsTable;
            DataRow   dataRow;
            DataTable achievementsTable;
            DataTable talentsTable;
            DataRow   statsTable;
            DataTable favoritesTable;
            DataTable ignoresTable;
            DataTable tagsTable;
            DataRow   subscriptionsRow;
            DataTable badgesTable;
            DataTable itemsTable;
            DataTable effectsTable;
            DataTable pollsTable;
            DataTable friendsTable;
            DataTable friendsRequestsTable;
            DataTable myRoomsTable;
            DataTable petsTable;
            DataTable questsTable;
            DataTable botsTable;
            DataTable relationShipsTable;

            try
            {
                using (var queryReactor = Plus.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.SetQuery("SELECT * FROM users WHERE auth_ticket = @ticket");
                    queryReactor.AddParameter("ticket", sessionTicket);
                    dataRow = queryReactor.GetRow();
                    if (dataRow == null)
                    {
                        return(null);
                    }

                    errorCode = 0;
                    userid    = Convert.ToUInt32(dataRow["id"]);

                    //queryReactor.RunFastQuery(string.Format("UPDATE users SET online = '1' WHERE id = '{0}'", userid));
                    if (Plus.GetGame().GetClientManager().GetClientByUserId(userid) != null)
                    {
                        if (Plus.GetGame().GetClientManager().GetClientByUserId(userid).LoggingOut)
                        {
                            //Plus.GetGame().GetClientManager().GetClientByUserId(userid).Disconnect("Force logout");
                            return(null);
                        }
                        else
                        {
                            Plus.GetGame().GetClientManager().GetClientByUserId(userid).Disconnect("User connected in other place");
                        }
                    }

                    queryReactor.SetQuery(string.Format("SELECT `group`, `level`, progress FROM users_achievements WHERE userid = {0}", Convert.ToUInt32(userid)));
                    achievementsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT talent_id, talent_state FROM users_talents WHERE userid = {0}", Convert.ToUInt32(userid)));
                    talentsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT COUNT(*) FROM users_stats WHERE id = {0}", Convert.ToUInt32(userid)));
                    if (int.Parse(queryReactor.GetString()) == 0)
                    {
                        queryReactor.RunFastQuery(string.Format("INSERT INTO users_stats (id) VALUES ({0})", Convert.ToUInt32(userid)));
                    }

                    queryReactor.SetQuery(string.Format("SELECT room_id FROM users_favorites WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    favoritesTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT ignore_id FROM users_ignores WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    ignoresTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT tag FROM users_tags WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    tagsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT subscription_id, timestamp_activated, timestamp_expire, timestamp_lastgift FROM users_subscriptions WHERE user_id = {0} AND timestamp_expire > UNIX_TIMESTAMP() ORDER BY subscription_id DESC LIMIT 1", Convert.ToUInt32(userid)));
                    subscriptionsRow = queryReactor.GetRow();

                    queryReactor.SetQuery(string.Format("SELECT * FROM users_badges WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    badgesTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT `items_rooms`.* , COALESCE(`items_groups`.`group_id`, 0) AS group_id FROM `items_rooms` LEFT OUTER JOIN `items_groups` ON `items_rooms`.`id` = `items_groups`.`id` WHERE room_id='0' AND user_id={0} LIMIT 8000", Convert.ToUInt32(userid)));
                    itemsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT * FROM users_effects WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    effectsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT poll_id FROM users_polls WHERE user_id = {0} GROUP BY poll_id;", Convert.ToUInt32(userid)));
                    pollsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_one_id WHERE messenger_friendships.user_two_id = {0} UNION ALL SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_two_id WHERE messenger_friendships.user_one_id = {0}", Convert.ToUInt32(userid)));
                    friendsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT * FROM users_stats WHERE id = {0}", Convert.ToUInt32(userid)));
                    statsTable = queryReactor.GetRow();

                    queryReactor.SetQuery(string.Format("SELECT messenger_requests.from_id,messenger_requests.to_id,users.Username FROM users JOIN messenger_requests ON users.id = messenger_requests.from_id WHERE messenger_requests.to_id = {0}", Convert.ToUInt32(userid)));
                    friendsRequestsTable = queryReactor.GetTable();

                    queryReactor.SetQuery("SELECT * FROM rooms_data WHERE owner = @name LIMIT 150");
                    queryReactor.AddParameter("name", dataRow["username"]);
                    myRoomsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT * FROM bots WHERE user_id = {0} AND room_id = 0 AND ai_type = 'fightpet'", Convert.ToUInt32(userid)));
                    petsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT quest_id, progress FROM users_quests_data WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    questsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT * FROM bots WHERE user_id = {0} AND room_id=0 AND ai_type !='pet' AND ai_type != 'fightpet'", Convert.ToUInt32(userid)));
                    botsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("SELECT group_id,rank FROM groups_members WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    groupsTable = queryReactor.GetTable();

                    queryReactor.SetQuery(string.Format("UPDATE users_info SET login_timestamp = '{1}' WHERE user_id = {0}", Convert.ToUInt32(userid), Plus.GetUnixTimeStamp()));
                    queryReactor.RunQuery();

                    queryReactor.SetQuery(string.Format("SELECT * FROM users_relationships WHERE user_id = {0}", Convert.ToUInt32(userid)));
                    relationShipsTable = queryReactor.GetTable();

                    queryReactor.RunFastQuery(string.Format("UPDATE users SET online='1' WHERE id = {0} LIMIT 1", Convert.ToUInt32(userid)));
                }

                var achievements = new Dictionary <string, UserAchievement>();
                foreach (DataRow row in achievementsTable.Rows)
                {
                    var text     = (string)row["group"];
                    var level    = (int)row["level"];
                    var progress = (int)row["progress"];
                    var value    = new UserAchievement(text, level, progress);
                    achievements.Add(text, value);
                }

                var talents = new Dictionary <int, UserTalent>();
                foreach (DataRow row in talentsTable.Rows)
                {
                    var num2   = (int)row["talent_id"];
                    var state  = (int)row["talent_state"];
                    var value2 = new UserTalent(num2, state);
                    talents.Add(num2, value2);
                }

                var favorites     = (from DataRow row in favoritesTable.Rows select(uint) row["room_id"]).ToList();
                var ignoreUsers   = (from DataRow row in ignoresTable.Rows select(uint) row["ignore_id"]).ToList();
                var tags          = (from DataRow row in tagsTable.Rows select row["tag"].ToString().Replace(" ", "")).ToList();
                var inventoryBots =
                    (from DataRow row2 in botsTable.Rows select BotManager.GenerateBotFromRow(row2)).ToDictionary(
                        roomBot => roomBot.BotId);
                var badges =
                    (from DataRow dataRow8 in badgesTable.Rows
                     select new Badge((string)dataRow8["badge_id"], (int)dataRow8["badge_slot"])).ToList();

                Subscription subscriptions = null;
                if (subscriptionsRow != null)
                {
                    subscriptions = new Subscription((int)subscriptionsRow["subscription_id"],
                                                     (int)subscriptionsRow["timestamp_activated"], (int)subscriptionsRow["timestamp_expire"],
                                                     (int)subscriptionsRow["timestamp_lastgift"]);
                }

                var items = new List <UserItem>();
                foreach (DataRow row in itemsTable.Rows)
                {
                    var id     = Convert.ToUInt32(row[0]);
                    var itemId = Convert.ToUInt32(row[3]);

                    if (!Plus.GetGame().GetItemManager().ContainsItem(itemId))
                    {
                        continue;
                    }

                    var extraData = !DBNull.Value.Equals(row[4]) ? (string)row[4] : string.Empty;

                    var group    = Convert.ToUInt32(row["group_id"]);
                    var songCode = (string)row["songcode"];
                    items.Add(new UserItem(id, itemId, extraData, group, songCode));
                }

                var effects = (from DataRow row in effectsTable.Rows
                               let effectId = (int)row["effect_id"]
                                              let totalDuration = (int)row["total_duration"]
                                                                  let activated = Plus.EnumToBool((string)row["is_activated"])
                                                                                  let activateTimestamp = (double)row["activated_stamp"]
                                                                                                          let type = Convert.ToInt16(row["type"])
                                                                                                                     select new AvatarEffect(effectId, totalDuration, activated, activateTimestamp, type)).ToList();

                var pollSuggested = new HashSet <uint>();
                foreach (uint pId in from DataRow row in pollsTable.Rows select(uint) row["poll_id"])
                {
                    pollSuggested.Add(pId);
                }

                var friends = new Dictionary <uint, MessengerBuddy>();
                var limit   = (friendsTable.Rows.Count - 10000);

                if (limit > 0)
                {
                    using (var queryreactor2 = Plus.GetDatabaseManager().GetQueryReactor())
                    {
                        queryreactor2.RunFastQuery(string.Concat("DELETE FROM messenger_friendships WHERE user_one_id=", userid, " OR user_two_id=", userid, " LIMIT ", limit));
                        queryreactor2.SetQuery(string.Concat("SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_one_id WHERE messenger_friendships.user_two_id = ", userid, " UNION ALL SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_two_id WHERE messenger_friendships.user_one_id = ", userid));
                        friendsTable = queryreactor2.GetTable();
                    }
                }

                foreach (DataRow row in friendsTable.Rows)
                {
                    var num4           = Convert.ToUInt32(row["id"]);
                    var pUsername      = (string)row["username"];
                    var pLook          = (string)row["look"];
                    var pMotto         = (string)row["motto"];
                    var pLastOnline    = Convert.ToInt32(row["last_online"]);
                    var pAppearOffline = Plus.EnumToBool(row["hide_online"].ToString());
                    var pHideInroom    = Plus.EnumToBool(row["hide_inroom"].ToString());
                    if (num4 != userid && !friends.ContainsKey(num4))
                    {
                        friends.Add(num4,
                                    new MessengerBuddy(num4, pUsername, pLook, pMotto, pLastOnline, pAppearOffline, pHideInroom));
                    }
                }

                var friendsRequests = new Dictionary <uint, MessengerRequest>();
                foreach (DataRow row in friendsRequestsTable.Rows)
                {
                    var num5       = Convert.ToUInt32(row["from_id"]);
                    var num6       = Convert.ToUInt32(row["to_id"]);
                    var pUsername2 = (string)row["Username"];
                    if (num5 != userid)
                    {
                        if (!friendsRequests.ContainsKey(num5))
                        {
                            friendsRequests.Add(num5, new MessengerRequest(userid, num5, pUsername2));
                        }
                        else if (!friendsRequests.ContainsKey(num6))
                        {
                            friendsRequests.Add(num6, new MessengerRequest(userid, num6, pUsername2));
                        }
                    }
                }

                var myRooms = new HashSet <RoomData>();
                foreach (DataRow row in myRoomsTable.Rows)
                {
                    var roomId = Convert.ToUInt32(row["id"]);
                    myRooms.Add(Plus.GetGame().GetRoomManager().FetchRoomData(roomId, row));
                }

                var pets = new Dictionary <uint, Pet>();
                foreach (DataRow row in petsTable.Rows)
                {
                    using (var queryreactor3 = Plus.GetDatabaseManager().GetQueryReactor())
                    {
                        queryreactor3.SetQuery(string.Format("SELECT * FROM pets_data WHERE id={0} LIMIT 1", row[0]));
                        var row3 = queryreactor3.GetRow();
                        if (row3 == null)
                        {
                            continue;
                        }
                        var pet = Catalog.GeneratePetFromRow(row, row3);
                        pets.Add(pet.PetId, pet);
                    }
                }

                var quests = new Dictionary <uint, int>();
                foreach (DataRow row in questsTable.Rows)
                {
                    var key    = Convert.ToUInt32(row["quest_id"]);
                    var value3 = (int)row["progress"];
                    if (quests.ContainsKey(key))
                    {
                        quests.Remove(key);
                    }
                    quests.Add(key, value3);
                }

                var groups = new HashSet <GroupUser>();
                foreach (DataRow row in groupsTable.Rows)
                {
                    groups.Add(new GroupUser(userid, (uint)row[0], Convert.ToInt16(row[1])));
                }

                var relationShips = relationShipsTable.Rows.Cast <DataRow>()
                                    .ToDictionary(row => (int)row[0],
                                                  row => new Relationship((int)row[0], (int)row[2], Convert.ToInt32(row[3].ToString())));

                var user = HabboFactory.GenerateHabbo(dataRow, statsTable, groups);
                dataRow              = null;
                achievementsTable    = null;
                favoritesTable       = null;
                ignoresTable         = null;
                tagsTable            = null;
                subscriptionsRow     = null;
                badgesTable          = null;
                itemsTable           = null;
                effectsTable         = null;
                friendsTable         = null;
                friendsRequestsTable = null;
                myRoomsTable         = null;
                petsTable            = null;
                botsTable            = null;
                relationShipsTable   = null;
                pollsTable           = null;

                errorCode = 0;
                if (user.Rank >= Plus.StaffAlertMinRank)
                {
                    friends.Add(0, new MessengerBuddy(0, "Staff Chat", "hr-831-45.fa-1206-91.sh-290-1331.ha-3129-100.hd-180-2.cc-3039-73.ch-3215-92.lg-270-73", string.Empty, 0, false, true));
                }
                //if (user.Rank >= 2)
                //    friends.Add(999999999, new MessengerBuddy(999999999, "VIP Chat", "hr-831-45.fa-1206-91.sh-290-1331.ha-3129-100.hd-180-2.cc-3039-73.ch-3215-92.lg-270-73", string.Empty, 999999999, false, true));

                return(new UserData(userid, achievements, talents, favorites, ignoreUsers, tags, subscriptions, badges,
                                    items, effects, friends, friendsRequests, myRooms, pets, quests, user, inventoryBots, relationShips,
                                    pollSuggested, miniMailCount));
            }
            catch (Exception e)
            {
                errorCode = 1;
                Out.WriteLine("An error occured when trying to login a user, could be possibly a error within the MySQL query.\n\n" + e.StackTrace, "", ConsoleColor.DarkRed);
                return(null);
            }
        }