コード例 #1
0
        /// <summary>
        ///     Processes the specified caller.
        /// </summary>
        internal static void Process()
        {
            if (_lowPriorityStopWatch.ElapsedMilliseconds >= 10000 || !_isExecuted)
            {
                try
                {
                    int clientCount = Yupi.GetGame().GetClientManager().ClientCount();

                    int loadedRoomsCount = Yupi.GetGame().GetRoomManager().LoadedRoomsCount;

                    DateTime dateTime = new DateTime((DateTime.Now - Yupi.YupiServerStartDateTime).Ticks);

                    Console.Title = string.Concat("Yupi | Time: ", int.Parse(dateTime.ToString("dd")) - 1, "d:",
                                                  dateTime.ToString("HH"), "h:", dateTime.ToString("mm"), "m | Users: ",
                                                  clientCount, " | Rooms: ", loadedRoomsCount);

                    Yupi.GetGame().GetNavigator().LoadNewPublicRooms();

                    _isExecuted = true;

                    _lowPriorityStopWatch.Restart();
                }
                catch (Exception e)
                {
                    YupiLogManager.LogException(e, "Failed Processing LowPriorityWorker.");

                    _isExecuted = true;

                    _lowPriorityStopWatch.Restart();
                }
            }
        }
コード例 #2
0
ファイル: WiredHandler.cs プロジェクト: xXSicilyXx/Yupi
        public bool ExecuteWired(Interaction type, params object[] stuff)
        {
            try
            {
                if (!IsTrigger(type) || stuff == null)
                {
                    return(false);
                }

                if (type == Interaction.TriggerCollision)
                {
                    foreach (IWiredItem wiredItem in _wiredItems.Where(wiredItem => wiredItem != null && wiredItem.Type == type))
                    {
                        wiredItem.Execute(stuff);
                    }
                }
                else if (_wiredItems.Any(current => current != null && current.Type == type && current.Execute(stuff)))
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                YupiLogManager.LogException(e, "Registered Wired Handling Exception.", "Yupi.Wired");
            }

            return(false);
        }
コード例 #3
0
        /// <summary>
        ///     Handles the disconnect.
        /// </summary>
        /// <param name="socketError">The socket error.</param>
        /// <param name="exception">The exception.</param>
        private void HandleDisconnect(SocketError socketError, Exception exception)
        {
            try
            {
                if (_socket != null && _socket.Connected)
                {
                    try
                    {
                        _socket.Shutdown(SocketShutdown.Both);
                        _socket.Close();
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                _connected = false;
                Parser.Dispose();

                SocketConnectionCheck.FreeConnection(GetIp());

                DisconnectAction(this, exception);
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Failed Receiving Connection Data.");
            }
        }
コード例 #4
0
        /// <summary>
        ///     Broadcasts the packets.
        /// </summary>
        private void BroadcastPackets()
        {
            try
            {
                if (!_broadcastQueue.Any())
                {
                    return;
                }

                DateTime now = DateTime.Now;
                byte[]   bytes;

                _broadcastQueue.TryDequeue(out bytes);

                foreach (GameClient current in Clients.Values.Where(current => current?.GetConnection() != null))
                {
                    current.GetConnection().SendData(bytes);
                }

                TimeSpan timeSpan = DateTime.Now - now;

                if (timeSpan.TotalSeconds > 3.0)
                {
                    Console.WriteLine("GameClientManager.BroadcastPackets spent: {0} seconds in working.", timeSpan.TotalSeconds);
                }
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered HabboHotel Thread Exception.");
            }
        }
コード例 #5
0
ファイル: BanUserIp.cs プロジェクト: xXSicilyXx/Yupi
        public override bool Execute(GameClient session, string[] pms)
        {
            GameClient user = Yupi.GetGame().GetClientManager().GetClientByUserName(pms[0]);

            if (user == null)
            {
                session.SendWhisper(Yupi.GetLanguage().GetVar("user_not_found"));
                return(true);
            }
            if (user.GetHabbo().Rank >= session.GetHabbo().Rank)
            {
                session.SendWhisper(Yupi.GetLanguage().GetVar("user_is_higher_rank"));
                return(true);
            }
            try
            {
                Yupi.GetGame()
                .GetBanManager()
                .BanUser(user, session.GetHabbo().UserName, 788922000.0, string.Join(" ", pms.Skip(2)),
                         true, false);
            }
            catch
            {
                YupiLogManager.LogException($"An error occurred when {session.GetHabbo().UserName} tried to ban {user.GetHabbo().UserName}", "Failed Banning User.", "Yupi.Users");
            }

            return(true);
        }
コード例 #6
0
ファイル: ExchangeManager.cs プロジェクト: xXSicilyXx/Yupi
        /// <summary>
        ///     Gives the coins.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="e">The <see cref="ElapsedEventArgs" /> instance containing the event data.</param>
        internal void GiveCoins(object source, ElapsedEventArgs e)
        {
            try
            {
                ICollection <GameClient> clients = Yupi.GetGame().GetClientManager().Clients.Values;

                foreach (GameClient client in clients.Where(client => client?.GetHabbo() != null))
                {
                    client.GetHabbo().Credits += (uint)ServerExtraSettings.CreditsToGive;
                    client.GetHabbo().UpdateCreditsBalance();
                    client.GetHabbo().Duckets += (uint)ServerExtraSettings.PixelsToGive;

                    if (ServerExtraSettings.DiamondsLoopEnabled && ServerExtraSettings.DiamondsVipOnly)
                    {
                        client.GetHabbo().Diamonds += client.GetHabbo().Vip || client.GetHabbo().Rank >= 6
                            ? (uint)ServerExtraSettings.DiamondsToGive
                            : (uint)ServerExtraSettings.DiamondsToGive;
                    }

                    client.GetHabbo().UpdateSeasonalCurrencyBalance();
                }
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered Exchange System Exception.");
            }
        }
コード例 #7
0
ファイル: RoomManager.cs プロジェクト: xXSicilyXx/Yupi
        /// <summary>
        ///     Called when [cycle].
        /// </summary>
        internal void OnCycle()
        {
            try
            {
                bool flag  = WorkActiveRoomsAddQueue();
                bool flag2 = WorkActiveRoomsRemoveQueue();
                bool flag3 = WorkActiveRoomsUpdateQueue();

                if (flag || flag2 || flag3)
                {
                    SortActiveRooms();
                }

                bool flag4 = WorkVotedRoomsAddQueue();
                bool flag5 = WorkVotedRoomsRemoveQueue();

                if (flag4 || flag5)
                {
                    SortVotedRooms();
                }

                Yupi.GetGame().RoomManagerCycleEnded = true;
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered Room YupiDatabaseManager Crashing.");
            }
        }
コード例 #8
0
ファイル: ConnectionHandler.cs プロジェクト: xXSicilyXx/Yupi
 /// <summary>
 ///     Managers the connection event.
 /// </summary>
 /// <param name="connection">The connection.</param>
 private static void OnClientConnected(ConnectionData connection)
 {
     try
     {
         Yupi.GetGame().GetClientManager().CreateAndStartClient(connection.GetConnectionId(), connection);
     }
     catch (Exception ex)
     {
         YupiLogManager.LogException(ex, "Failed Handling New Connection.");
     }
 }
コード例 #9
0
ファイル: ConnectionHandler.cs プロジェクト: xXSicilyXx/Yupi
 /// <summary>
 ///     Closes the connection.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="exception"></param>
 private static void OnClientDisconnected(ConnectionData connection, Exception exception)
 {
     try
     {
         Yupi.GetGame().GetClientManager().DisposeConnection(connection.GetConnectionId());
     }
     catch (Exception ex)
     {
         YupiLogManager.LogException(ex, "Failed Releasing Old Connection.");
     }
 }
コード例 #10
0
ファイル: Trade.cs プロジェクト: xXSicilyXx/Yupi
 /// <summary>
 ///     Finnitoes this instance.
 /// </summary>
 private void Finnito()
 {
     try
     {
         DeliverItems();
         CloseTradeClean();
     }
     catch (Exception ex)
     {
         YupiLogManager.LogException(ex, "Failed Trading with User.");
     }
 }
コード例 #11
0
        /// <summary>
        ///     Called when [cycle].
        /// </summary>
        internal void OnCycle()
        {
            try
            {
                AddClients();
                RemoveClients();
                GiveBadges();
                BroadcastPackets();

                Yupi.GetGame().ClientManagerCycleEnded = true;
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered HabboHotel Thread Exception.");
            }
        }
コード例 #12
0
ファイル: WiredHandler.cs プロジェクト: xXSicilyXx/Yupi
        public void OnCycle()
        {
            try
            {
                Queue queue = new Queue();

                lock (_cycleItems.SyncRoot)
                {
                    while (_cycleItems.Count > 0)
                    {
                        IWiredItem wiredItem = (IWiredItem)_cycleItems.Dequeue();

                        IWiredCycler item = wiredItem as IWiredCycler;

                        if (item == null)
                        {
                            continue;
                        }

                        IWiredCycler wiredCycler = item;

                        if (!wiredCycler.OnCycle())
                        {
                            if (!queue.Contains(item))
                            {
                                queue.Enqueue(item);
                            }
                        }
                    }
                }

                _cycleItems = queue;
            }
            catch (Exception e)
            {
                YupiLogManager.LogException(e, "Registered Wired Handling Exception.", "Yupi.Wired");
            }
        }
コード例 #13
0
        /// <summary>
        ///     Gives the badges.
        /// </summary>
        private void GiveBadges()
        {
            try
            {
                DateTime now = DateTime.Now;

                if (_badgeQueue.Count > 0)
                {
                    lock (_badgeQueue.SyncRoot)
                    {
                        while (_badgeQueue.Count > 0)
                        {
                            string badge = (string)_badgeQueue.Dequeue();

                            foreach (GameClient current in Clients.Values.Where(current => current.GetHabbo() != null))
                            {
                                current.GetHabbo().GetBadgeComponent().GiveBadge(badge, true, current);
                                current.SendNotif(Yupi.GetLanguage().GetVar("user_earn_badge"));
                            }
                        }
                    }
                }

                TimeSpan timeSpan = DateTime.Now - now;

                if (timeSpan.TotalSeconds > 3.0)
                {
                    Console.WriteLine("GameClientManager.GiveBadges spent: {0} seconds in working.",
                                      timeSpan.TotalSeconds);
                }
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered HabboHotel Thread Exception.");
            }
        }
コード例 #14
0
ファイル: RoomData.cs プロジェクト: xXSicilyXx/Yupi
        /// <summary>
        ///     Fills the specified row.
        /// </summary>
        /// <param name="row">The row.</param>
        internal void Fill(DataRow row)
        {
            try
            {
                Id          = (uint)row["id"];
                Name        = (string)row["caption"];
                PassWord    = (string)row["password"];
                Description = (string)row["description"];
                Type        = (string)row["roomtype"];
                Owner       = string.Empty;
                OwnerId     = (uint)row["owner"];
                RoomChat    = new ConcurrentStack <Chatlog>();
                WordFilter  = new List <string>();

                using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.SetQuery("SELECT username FROM users WHERE id = @userId");
                    queryReactor.AddParameter("userId", OwnerId);

                    Owner = queryReactor.GetString();

                    queryReactor.SetQuery($"SELECT user_id, message, timestamp FROM users_chatlogs WHERE room_id = '{Id}' ORDER BY timestamp ASC LIMIT 150");

                    DataTable table = queryReactor.GetTable();

                    if (table != null)
                    {
                        foreach (DataRow dataRow in table.Rows)
                        {
                            RoomChat.Push(new Chatlog((uint)dataRow[0], (string)dataRow[1], Yupi.UnixToDateTime(int.Parse(dataRow[2].ToString())), false));
                        }
                    }

                    queryReactor.SetQuery($"SELECT word FROM rooms_wordfilter WHERE room_id = '{Id}'");

                    DataTable tableFilter = queryReactor.GetTable();

                    if (tableFilter != null)
                    {
                        foreach (DataRow dataRow in tableFilter.Rows)
                        {
                            WordFilter.Add(dataRow["word"].ToString());
                        }
                    }
                }

                string roomState = row["state"].ToString().ToLower();

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

                case "password":
                    State = 2;
                    break;

                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        = Yupi.EnumToBool(row["allow_pets"].ToString());
                AllowPetsEating  = Yupi.EnumToBool(row["allow_pets_eat"].ToString());
                AllowWalkThrough = Yupi.EnumToBool(row["allow_walkthrough"].ToString());
                HideWall         = Yupi.EnumToBool(row["hidewall"].ToString());

                AllowRightsOverride = false;

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

                Tags = new List <string>();

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

                foreach (string item in row["tags"].ToString().Split(','))
                {
                    Tags.Add(item);
                }
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered Room Serialization Exception.", "Yupi.Rooms");
            }
        }
コード例 #15
0
        /// <summary>
        ///     Tries the login.
        /// </summary>
        /// <param name="authTicket">The authentication ticket.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        internal bool TryLogin(string authTicket)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(authTicket))
                {
                    return(false);
                }

                string ip = GetConnection().GetIp();

                if (string.IsNullOrEmpty(ip))
                {
                    return(false);
                }

                uint errorCode;

                UserData userData = UserDataFactory.GetUserData(authTicket, out errorCode);

                if (userData?.User == null)
                {
                    return(false);
                }

                if (errorCode == 1 || errorCode == 2)
                {
                    return(false);
                }

                Yupi.GetGame().GetClientManager().RegisterClient(this, userData.UserId, userData.User.UserName);

                _habbo = userData.User;

                userData.User.LoadData(userData);

                bool isBanned = Yupi.GetGame().GetBanManager().CheckIfIsBanned(userData.User.UserName, ip, MachineId);

                if (isBanned)
                {
                    string banReason = Yupi.GetGame().GetBanManager().GetBanReason(userData.User.UserName, ip, MachineId);

                    SendNotifWithScroll(banReason);

                    using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                    {
                        queryReactor.SetQuery($"SELECT ip_last FROM users WHERE id = {GetHabbo().Id} LIMIT 1");

                        string supaString = queryReactor.GetString();

                        queryReactor.SetQuery($"SELECT COUNT(0) FROM users_bans_access WHERE user_id={_habbo.Id} LIMIT 1");
                        int integer = queryReactor.GetInteger();

                        if (integer > 0)
                        {
                            queryReactor.RunFastQuery("UPDATE users_bans_access SET attempts = attempts + 1, ip='" + supaString + "' WHERE user_id=" + GetHabbo().Id + " LIMIT 1");
                        }
                        else
                        {
                            queryReactor.RunFastQuery("INSERT INTO users_bans_access (user_id, ip) VALUES (" + GetHabbo().Id + ", '" + supaString + "')");
                        }
                    }

                    return(false);
                }

                using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                    queryReactor.RunFastQuery($"UPDATE users SET ip_last='{ip}' WHERE id={GetHabbo().Id}");

                userData.User.Init(this, userData);

                QueuedServerMessage queuedServerMessage = new QueuedServerMessage(_connection);

                ServerMessage serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("UniqueMachineIDMessageComposer"));

                serverMessage.AppendString(MachineId);
                queuedServerMessage.AppendResponse(serverMessage);

                queuedServerMessage.AppendResponse(
                    new ServerMessage(LibraryParser.OutgoingRequest("AuthenticationOKMessageComposer")));

                ServerMessage serverMessage2 = new ServerMessage(LibraryParser.OutgoingRequest("HomeRoomMessageComposer"));

                serverMessage2.AppendInteger(_habbo.HomeRoom);
                serverMessage2.AppendInteger(_habbo.HomeRoom);
                queuedServerMessage.AppendResponse(serverMessage2);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("MinimailCountMessageComposer"));

                serverMessage.AppendInteger(_habbo.MinimailUnreadMessages);
                queuedServerMessage.AppendResponse(serverMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("FavouriteRoomsMessageComposer"));

                serverMessage.AppendInteger(30);

                if (userData.User.FavoriteRooms == null || !userData.User.FavoriteRooms.Any())
                {
                    serverMessage.AppendInteger(0);
                }
                else
                {
                    serverMessage.AppendInteger(userData.User.FavoriteRooms.Count);

                    foreach (uint i in userData.User.FavoriteRooms)
                    {
                        serverMessage.AppendInteger(i);
                    }
                }

                queuedServerMessage.AppendResponse(serverMessage);

                ServerMessage rightsMessage = new ServerMessage(LibraryParser.OutgoingRequest("UserClubRightsMessageComposer"));

                rightsMessage.AppendInteger(userData.User.GetSubscriptionManager().HasSubscription ? 2 : 0);
                rightsMessage.AppendInteger(userData.User.Rank);
                rightsMessage.AppendInteger(0);
                queuedServerMessage.AppendResponse(rightsMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("EnableNotificationsMessageComposer"));
                serverMessage.AppendBool(true); //isOpen
                serverMessage.AppendBool(false);
                queuedServerMessage.AppendResponse(serverMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("EnableTradingMessageComposer"));
                serverMessage.AppendBool(true);
                queuedServerMessage.AppendResponse(serverMessage);
                userData.User.UpdateCreditsBalance();

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("ActivityPointsMessageComposer"));
                serverMessage.AppendInteger(2);
                serverMessage.AppendInteger(0);
                serverMessage.AppendInteger(userData.User.Duckets);
                serverMessage.AppendInteger(5);
                serverMessage.AppendInteger(userData.User.Diamonds);
                queuedServerMessage.AppendResponse(serverMessage);

                if (userData.User.HasFuse("fuse_mod"))
                {
                    queuedServerMessage.AppendResponse(Yupi.GetGame().GetModerationTool().SerializeTool(this));
                }

                queuedServerMessage.AppendResponse(Yupi.GetGame().GetAchievementManager().AchievementDataCached);

                queuedServerMessage.AppendResponse(GetHabbo().GetAvatarEffectsInventoryComponent().GetPacket());
                queuedServerMessage.SendResponse();

                Yupi.GetGame().GetAchievementManager().TryProgressHabboClubAchievements(this);
                Yupi.GetGame().GetAchievementManager().TryProgressRegistrationAchievements(this);
                Yupi.GetGame().GetAchievementManager().TryProgressLoginAchievements(this);

                return(true);
            }
            catch (Exception ex)
            {
                YupiLogManager.LogException(ex, "Registered Login Exception.", "Yupi.Users");
            }

            return(false);
        }
コード例 #16
0
ファイル: ItemsCoincide.cs プロジェクト: xXSicilyXx/Yupi
        public bool Execute(params object[] stuff)
        {
            if (!Items.Any())
            {
                return(true);
            }

            bool useExtradata, useRot, usePos;

            Dictionary <uint, string[]> itemsOriginalData;

            try
            {
                if (string.IsNullOrWhiteSpace(OtherString) || !OtherString.Contains(",") ||
                    !OtherExtraString.Contains("|"))
                {
                    return(false);
                }

                string[] booleans = OtherString.ToLower().Split(',');

                useExtradata = booleans[0] == "true";
                useRot       = booleans[1] == "true";
                usePos       = booleans[2] == "true";

                itemsOriginalData =
                    OtherExtraString.Split('/')
                    .Select(data => data.Split('|'))
                    .ToDictionary(array => uint.Parse(array[0]), array => array.Skip(1).ToArray());
            }
            catch (Exception e)
            {
                YupiLogManager.LogException(e, "Registered Wired Handling Exception.");

                return(false);
            }

            foreach (RoomItem current in Items)
            {
                if (current == null || !itemsOriginalData.ContainsKey(current.Id))
                {
                    return(false);
                }

                string[] originalData = itemsOriginalData[current.Id];

                if (useRot)
                {
                    if (current.Rot != int.Parse(originalData[1]))
                    {
                        return(false);
                    }
                }

                if (useExtradata)
                {
                    if (current.ExtraData == string.Empty)
                    {
                        current.ExtraData = "0";
                    }

                    if (current.ExtraData != (originalData[0] == string.Empty ? "0" : originalData[0]))
                    {
                        return(false);
                    }
                }

                if (!usePos)
                {
                    continue;
                }

                string[] originalPos = originalData[2].Split(',');

                if ((current.X != int.Parse(originalPos[0])) || (current.Y != int.Parse(originalPos[1])))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #17
0
        /// <summary>
        ///     Handles the packet data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="length">The length.</param>
        public void HandlePacketData(byte[] data, int length)
        {
            if (length > 0 && _currentClient != null)
            {
                short messageId = 0;

                try
                {
                    int pos;

                    for (pos = 0; pos < length;)
                    {
                        if (_currentPacketLength == -1)
                        {
                            if (length < IntSize)
                            {
                                BufferCopy(data, length);
                                break;
                            }

                            _currentPacketLength = HabboEncoding.DecodeInt32(data, ref pos);
                        }

                        if (_currentPacketLength < 2 || _currentPacketLength > 4096)
                        {
                            _currentPacketLength = -1;

                            break;
                        }

                        if (_currentPacketLength == length - pos + _bufferPos)
                        {
                            if (_bufferPos != 0)
                            {
                                BufferCopy(data, length, pos);

                                pos = 0;

                                messageId = HabboEncoding.DecodeInt16(_bufferedData, ref pos);

                                HandleMessage(messageId, _bufferedData, 2, _currentPacketLength);
                            }
                            else
                            {
                                messageId = HabboEncoding.DecodeInt16(data, ref pos);
                                HandleMessage(messageId, data, pos, _currentPacketLength);
                            }

                            pos = length;
                            _currentPacketLength = -1;
                        }
                        else
                        {
                            int remainder = length - pos - (_currentPacketLength - _bufferPos);

                            if (_bufferPos != 0)
                            {
                                int toCopy = remainder - _bufferPos;

                                BufferCopy(data, toCopy, pos);

                                int zero = 0;

                                messageId = HabboEncoding.DecodeInt16(_bufferedData, ref zero);

                                HandleMessage(messageId, _bufferedData, 2, _currentPacketLength);
                            }
                            else
                            {
                                messageId = HabboEncoding.DecodeInt16(data, ref pos);

                                HandleMessage(messageId, data, pos, _currentPacketLength);

                                // ReSharper disable once RedundantAssignment
                                pos -= 2;
                            }

                            _currentPacketLength = -1;

                            pos = length - remainder;
                        }
                    }
                }
                catch (Exception exception)
                {
                    YupiLogManager.LogException(exception, $"Failed Parsee Packet #{messageId}.");
                }
            }
        }
コード例 #18
0
ファイル: GenericBot.cs プロジェクト: xXSicilyXx/Yupi
        internal override void OnChatTick()
        {
            if (GetBotData() == null || GetRoomUser() == null || GetBotData().WasPicked ||
                GetBotData().RandomSpeech == null || !GetBotData().RandomSpeech.Any())
            {
                StopTimerTick();
                return;
            }

            if (GetRoom() != null && GetRoom().MutedBots)
            {
                return;
            }

            string randomSpeech = GetBotData().GetRandomSpeech(GetBotData().MixPhrases);

            try
            {
                switch (randomSpeech)
                {
                case ":sit":
                {
                    RoomUser user = GetRoomUser();

                    if (user.RotBody % 2 != 0)
                    {
                        user.RotBody--;
                    }

                    user.Z = GetRoom().GetGameMap().SqAbsoluteHeight(user.X, user.Y);

                    if (!user.Statusses.ContainsKey("sit"))
                    {
                        user.UpdateNeeded = true;
                        user.Statusses.Add("sit", "0.55");
                    }

                    user.IsSitting = true;

                    return;
                }

                case ":stand":
                {
                    RoomUser user = GetRoomUser();

                    if (user.IsSitting)
                    {
                        user.Statusses.Remove("sit");
                        user.IsSitting    = false;
                        user.UpdateNeeded = true;
                    }
                    else if (user.IsLyingDown)
                    {
                        user.Statusses.Remove("lay");
                        user.IsLyingDown  = false;
                        user.UpdateNeeded = true;
                    }

                    return;
                }
                }

                if (GetRoom() != null)
                {
                    randomSpeech = randomSpeech.Replace("%user_count%",
                                                        GetRoom().GetRoomUserManager().GetRoomUserCount().ToString());
                    randomSpeech = randomSpeech.Replace("%item_count%",
                                                        GetRoom().GetRoomItemHandler().TotalItems.ToString());
                    randomSpeech = randomSpeech.Replace("%floor_item_count%",
                                                        GetRoom().GetRoomItemHandler().FloorItems.Keys.Count.ToString());
                    randomSpeech = randomSpeech.Replace("%wall_item_count%",
                                                        GetRoom().GetRoomItemHandler().WallItems.Keys.Count.ToString());

                    if (GetRoom().RoomData != null)
                    {
                        randomSpeech = randomSpeech.Replace("%roomname%", GetRoom().RoomData.Name);
                        randomSpeech = randomSpeech.Replace("%owner%", GetRoom().RoomData.Owner);
                    }
                }

                if (GetBotData() != null)
                {
                    randomSpeech = randomSpeech.Replace("%name%", GetBotData().Name);
                }

                GetRoomUser().Chat(null, randomSpeech, false, 0);
            }
            catch (Exception e)
            {
                YupiLogManager.LogException(e, "Registered Bot Execution Exception.");
            }
        }