Exemplo n.º 1
0
        /// <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.");
            }
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
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.");
            }
        }
Exemplo n.º 4
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.");
            }
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Closes all.
        /// </summary>
        internal void CloseAll()
        {
            YupiWriterManager.WriteLine("Saving Inventary Content....", "Yupi.Boot", ConsoleColor.DarkCyan);

            foreach (GameClient current2 in Clients.Values.Where(current2 => current2.GetHabbo() != null))
            {
                current2.GetHabbo().GetInventoryComponent().RunDbUpdate();

                current2.GetHabbo().RunDbUpdate();
            }

            YupiWriterManager.WriteLine("Inventary Content Saved!", "Yupi.Boot", ConsoleColor.DarkCyan);

            try
            {
                YupiWriterManager.WriteLine("Closing Connection YupiDatabaseManager...", "Yupi.Boot", ConsoleColor.DarkMagenta);

                foreach (GameClient current3 in Clients.Values.Where(current3 => current3.GetConnection() != null))
                {
                    current3.GetConnection().Dispose();

                    Console.ForegroundColor = ConsoleColor.DarkMagenta;

                    YupiWriterManager.WriteLine("Connection YupiDatabaseManager Closed!", "Yupi.Boot", ConsoleColor.DarkMagenta);
                }
            }
            catch (Exception ex)
            {
                YupiLogManager.LogCriticalException(ex, "Failed Closing Connection YupiDatabaseManager.");
            }

            Clients.Clear();

            YupiWriterManager.WriteLine("Connections closed", "Yupi.Conn", ConsoleColor.DarkYellow);
        }
Exemplo n.º 7
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();
                }
            }
        }
Exemplo n.º 8
0
        /// <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.");
            }
        }
Exemplo n.º 9
0
 /// <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.");
     }
 }
Exemplo n.º 10
0
 /// <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.");
     }
 }
Exemplo n.º 11
0
        private void RemoveUnusedConnections(bool removeAllCalled = false)
        {
            try
            {
                if (removeAllCalled)
                {
                    lock (_databaseClients)
                    {
                        if (_databaseClients.Count > 0)
                        {
                            foreach (DatabaseClient databaseClient in _databaseClients)
                            {
                                if (databaseClient == null)
                                {
                                    continue;
                                }

                                lock (databaseClient)
                                {
                                    if (databaseClient.IsAvailable())
                                    {
                                        databaseClient.Disconnect();
                                    }

                                    databaseClient.Dispose();
                                }
                            }

                            _databaseClients.Clear();
                        }
                    }
                }
                else
                {
                    lock (_databaseClients)
                    {
                        if (_databaseClients.Count > 0)
                        {
                            foreach (DatabaseClient databaseClient in _databaseClients.Where(c => !c.IsAvailable()))
                            {
                                lock (databaseClient)
                                    databaseClient.Dispose();
                            }

                            _databaseClients.RemoveAll(c => !c.IsAvailable());
                        }
                    }
                }
            }
            catch
            {
                YupiLogManager.LogWarning("Failed Removing Database Unused Connection.", "Yupi.Data");
            }
        }
Exemplo n.º 12
0
 /// <summary>
 ///     Finnitoes this instance.
 /// </summary>
 private void Finnito()
 {
     try
     {
         DeliverItems();
         CloseTradeClean();
     }
     catch (Exception ex)
     {
         YupiLogManager.LogException(ex, "Failed Trading with User.");
     }
 }
Exemplo n.º 13
0
        /// <summary>
        ///     Shutdown the Emulator
        /// </summary>
        /// <param name="restart">if set to <c>true</c> [restart].</param>
        /// Set a Different Message in Hotel
        internal static void PerformShutDown(bool restart)
        {
            DateTime now = DateTime.Now;

            CacheManager.StopProcess();

            ShutdownStarted = true;

            Console.Title = "Yupi Emulator | Shutting down...";

            GetGame().StopGameLoop();
            GetGame().GetRoomManager().RemoveAllRooms();

            GetGame().GetClientManager().CloseAll();

            GetConnectionManager().Destroy();

            foreach (Group group in GetGame().GetGroupManager().Groups.Values)
            {
                group.UpdateForum();
            }

            using (IQueryAdapter queryReactor = YupiDatabaseManager.GetQueryReactor())
            {
                queryReactor.RunFastQuery("UPDATE users SET online = '0'");
                queryReactor.RunFastQuery("UPDATE rooms_data SET users_now = 0");
                queryReactor.RunFastQuery("TRUNCATE TABLE users_rooms_visits");
            }

            GetConnectionManager().Destroy();

            GetGame().Destroy();

            YupiLogManager.Stop();

            YupiWriterManager.WriteLine(" destroyed", "Yupi.Game", ConsoleColor.DarkYellow);

            TimeSpan span = DateTime.Now - now;

            YupiWriterManager.WriteLine("Elapsed " + TimeSpanToString(span) + "ms on Shutdown Proccess", "Yupi.Life", ConsoleColor.DarkYellow);

            IsLive = false;

            if (restart)
            {
                Process.Start(Assembly.GetEntryAssembly().Location);
            }

            Console.WriteLine("Closing...");

            Environment.Exit(0);
        }
Exemplo n.º 14
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.");
            }
        }
Exemplo n.º 15
0
        private static string GetRsaStringEncrypted(string message)
        {
            try
            {
                byte[] m = Encoding.Default.GetBytes(message);
                byte[] c = Rsa.Sign(m);

                return(Converter.BytesToHexString(c));
            }
            catch (Exception e)
            {
                YupiLogManager.LogCriticalException(e, "Encryption System Crashed.", "Yupi.Users");

                return(null);
            }
        }
Exemplo n.º 16
0
        public static BigInteger CalculateDiffieHellmanSharedKey(string publicKey)
        {
            try
            {
                byte[] bytes     = BigInteger.Parse('0' + publicKey, NumberStyles.HexNumber).ToByteArray();
                byte[] keyBytes  = Rsa.Verify(bytes);
                string keyString = Encoding.Default.GetString(keyBytes);

                return(DiffieHellman.CalculateSharedKey(BigInteger.Parse(keyString)));
            }
            catch (Exception e)
            {
                YupiLogManager.LogCriticalException(e, "Encryption System Crashed.", "Yupi.Users");

                return(0);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        ///     Mains the game loop.
        /// </summary>
        private void MainGameLoop()
        {
            while (GameLoopActiveExt)
            {
                try
                {
                    ServerCpuLowPriorityWorker.Process();

                    RoomManagerCycleEnded   = false;
                    ClientManagerCycleEnded = false;

                    GetRoomManager().OnCycle();
                    GetClientManager().OnCycle();
                }
                catch (Exception ex)
                {
                    YupiLogManager.LogCriticalException(ex, "Registered HabboHotel Loop Exception.", "Yupi.Users");
                }

                Thread.Sleep(GameLoopSleepTimeExt);
            }
        }
Exemplo n.º 18
0
        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");
            }
        }
Exemplo n.º 19
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.");
            }
        }
Exemplo n.º 20
0
        /// <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");
            }
        }
Exemplo n.º 21
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="RoomModel" /> class.
        /// </summary>
        /// <param name="doorX">The door x.</param>
        /// <param name="doorY">The door y.</param>
        /// <param name="doorZ">The door z.</param>
        /// <param name="doorOrientation">The door orientation.</param>
        /// <param name="heightmap">The heightmap.</param>
        /// <param name="staticFurniMap">The static furni map.</param>
        /// <param name="clubOnly">if set to <c>true</c> [club only].</param>
        /// <param name="poolmap">The poolmap.</param>
        internal RoomModel(int doorX, int doorY, double doorZ, int doorOrientation, string heightmap,
                           string staticFurniMap, bool clubOnly, string poolmap)
        {
            try
            {
                DoorX           = doorX;
                DoorY           = doorY;
                DoorZ           = doorZ;
                DoorOrientation = doorOrientation;
                Heightmap       = heightmap.ToLower();
                StaticFurniMap  = staticFurniMap;

                GotPublicPool = !string.IsNullOrEmpty(poolmap);

                heightmap = heightmap.Replace($"{Convert.ToChar(10)}", string.Empty);

                string[] array = heightmap.Split(Convert.ToChar(13));

                MapSizeX = array[0].Length;
                MapSizeY = array.Length;
                ClubOnly = clubOnly;

                SqState = new SquareState[MapSizeX][];

                for (int i = 0; i < MapSizeX; i++)
                {
                    SqState[i] = new SquareState[MapSizeY];
                }

                SqFloorHeight = new short[MapSizeX][];

                for (int i = 0; i < MapSizeX; i++)
                {
                    SqFloorHeight[i] = new short[MapSizeY];
                }

                SqSeatRot = new byte[MapSizeX][];

                for (int i = 0; i < MapSizeX; i++)
                {
                    SqSeatRot[i] = new byte[MapSizeY];
                }

                SqChar = new char[MapSizeX][];

                for (int i = 0; i < MapSizeX; i++)
                {
                    SqChar[i] = new char[MapSizeY];
                }

                if (GotPublicPool)
                {
                    MRoomModelfx = new byte[MapSizeX][];

                    for (int i = 0; i < MapSizeX; i++)
                    {
                        MRoomModelfx[i] = new byte[MapSizeY];
                    }
                }

                for (int y = 0; y < MapSizeY; y++)
                {
                    string text2 = array[y].Replace($"{Convert.ToChar(13)}", string.Empty)
                                   .Replace($"{Convert.ToChar(10)}", string.Empty);

                    for (int x = 0; x < MapSizeX; x++)
                    {
                        char c = 'x';

                        if (x < text2.Length)
                        {
                            c = text2[x];
                        }

                        if (x == doorX && y == doorY)
                        {
                            SqFloorHeight[x][y] = (short)DoorZ;
                            SqState[x][y]       = SquareState.Open;

                            if (SqFloorHeight[x][y] > 9)
                            {
                                SqChar[x][y] = Letters[SqFloorHeight[x][y] - 10];
                            }
                            else
                            {
                                SqChar[x][y] = char.Parse(DoorZ.ToString(CultureInfo.InvariantCulture));
                            }
                        }
                        else
                        {
                            if (c.Equals('x'))
                            {
                                SqFloorHeight[x][y] = -1;
                                SqState[x][y]       = SquareState.Blocked;
                                SqChar[x][y]        = c;
                            }
                            else if (char.IsLetterOrDigit(c))
                            {
                                SqFloorHeight[x][y] = char.IsDigit(c)
                                    ? short.Parse(c.ToString())
                                    : Convert.ToInt16(Letters.IndexOf(char.ToLower(c)) + 10);
                                SqState[x][y] = SquareState.Open;
                                SqChar[x][y]  = c;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                YupiLogManager.LogCriticalException(e, "Registered Room Serialization Exception.");
            }
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        /// <summary>
        ///     Invokes the command.
        /// </summary>
        /// <param name="inputData">The input data.</param>
        internal static void InvokeCommand(string inputData)
        {
            if (string.IsNullOrEmpty(inputData) && YupiWriterManager.DisabledState)
            {
                return;
            }

            try
            {
                if (inputData == null)
                {
                    return;
                }

                string firstArgument = inputData, secondArgument = string.Empty;

                if (inputData.Contains(" "))
                {
                    string[] strArguments = inputData.Split(' ');

                    firstArgument  = strArguments[0];
                    secondArgument = strArguments[1];
                }

                switch (firstArgument)
                {
                case "shutdown":
                    YupiLogManager.LogMessage($"Server Shutdowning at {DateTime.Now}.");

                    YupiWriterManager.DisablePrimaryWriting(true);

                    YupiWriterManager.WriteLine("Shutdown Initalized", "Yupi.Life", ConsoleColor.DarkYellow);

                    Yupi.PerformShutDown();

                    Console.WriteLine();
                    break;

                case "restart":
                    YupiLogManager.LogMessage($"Server Restarting at {DateTime.Now}.");

                    YupiWriterManager.DisablePrimaryWriting(true);

                    YupiWriterManager.WriteLine("Restart Initialized", "Yupi.Life", ConsoleColor.DarkYellow);

                    Yupi.PerformRestart();
                    Console.WriteLine();
                    break;

                case "reload":
                    switch (secondArgument)
                    {
                    case "database":
                        Console.WriteLine("Database destroyed");
                        Console.WriteLine();
                        break;

                    case "packets":
                        LibraryParser.ReloadDictionarys();
                        Console.WriteLine("> Packets Reloaded Suceffuly...");
                        Console.WriteLine();
                        break;

                    case "catalogue":
                        FurnitureDataManager.SetCache();

                        using (IQueryAdapter adapter = Yupi.GetDatabaseManager().GetQueryReactor())
                            GetGame().GetCatalogManager().Init(adapter);

                        FurnitureDataManager.Clear();

                        GetGame()
                        .GetClientManager()
                        .QueueBroadcaseMessage(
                            new ServerMessage(LibraryParser.OutgoingRequest("PublishShopMessageComposer")));
                        Console.WriteLine("Catalogue was re-loaded.");
                        Console.WriteLine();
                        break;

                    case "modeldata":
                        using (IQueryAdapter adapter2 = Yupi.GetDatabaseManager().GetQueryReactor())
                            GetGame().GetRoomManager().LoadModels(adapter2);

                        Console.WriteLine("Room models were re-loaded.");
                        Console.WriteLine();
                        break;

                    case "bans":
                        using (IQueryAdapter adapter3 = Yupi.GetDatabaseManager().GetQueryReactor())
                            GetGame().GetBanManager().LoadBans(adapter3);

                        Console.WriteLine("Bans were re-loaded");
                        Console.WriteLine();
                        break;

                    case "filter":
                        UserChatInputFilter.Reload();
                        BlackWordsManager.Reload();
                        break;

                    default:
                        UnknownCommand(inputData);
                        Console.WriteLine();
                        break;
                    }
                    break;

                case "clear":
                    Console.Clear();
                    break;

                case "status":
                    TimeSpan uptime = DateTime.Now - Yupi.YupiServerStartDateTime;

                    Console.WriteLine("Server status:");
                    Console.WriteLine();
                    Console.WriteLine("Uptime:");
                    Console.WriteLine("\tDays:    {0}", uptime.Days);
                    Console.WriteLine("\tHours:   {0}", uptime.Hours);
                    Console.WriteLine("\tMinutes: {0}", uptime.Minutes);
                    Console.WriteLine();
                    Console.WriteLine("Stats:");
                    Console.WriteLine("\tAccepted Connections: {0}",
                                      Yupi.GetConnectionManager().Manager.AcceptedConnections);
                    Console.WriteLine("\tActive Threads: {0}", Process.GetCurrentProcess().Threads.Count);
                    Console.WriteLine();
                    Console.WriteLine();
                    break;

                case "gcinfo":
                {
                    Console.WriteLine("Mode: " + GCSettings.LatencyMode);
                    Console.WriteLine("Is server GC: " + GCSettings.IsServerGC);

                    break;
                }

                case "memstat":
                {
                    Console.WriteLine("GC status:");
                    Console.WriteLine("\tGeneration supported: " + GC.MaxGeneration);
                    Console.WriteLine("\tLatency mode: " + GCSettings.LatencyMode);
                    Console.WriteLine("\tIs server GC: " + GCSettings.IsServerGC);
                    Console.WriteLine();
                    break;
                }

                case "memory":
                {
                    GC.Collect();
                    Console.WriteLine("Memory flushed");

                    break;
                }

                case "help":
                    Console.WriteLine("shutdown");
                    Console.WriteLine("clear");
                    Console.WriteLine("memory");
                    Console.WriteLine("status");
                    Console.WriteLine("restart");
                    Console.WriteLine("memstat");
                    Console.WriteLine("reload catalogue");
                    Console.WriteLine("reload modeldata");
                    Console.WriteLine("reload bans");
                    Console.WriteLine("reload packets");
                    Console.WriteLine("reload filter");
                    Console.WriteLine("reload packets");
                    Console.WriteLine("reload database");
                    Console.WriteLine();
                    break;

                default:
                    UnknownCommand(inputData);
                    break;
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
Exemplo n.º 24
0
        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);
        }
Exemplo n.º 25
0
 public static ILog GetLogManager() => YupiLogManager.GetLogManager();
Exemplo n.º 26
0
        /// <summary>
        ///     Main Void, Initializes the Emulator.
        /// </summary>
        internal static void Initialize()
        {
            Console.Title = "Yupi Emulator | Starting [...]";

            YupiServerStartDateTime = DateTime.Now;
            YupiServerTextEncoding  = Encoding.Default;
            MutedUsersByFilter      = new Dictionary <uint, uint>();

            ChatEmotions.Initialize();

            CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");

            YupiRootDirectory = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;

            YupiVariablesDirectory = Path.Combine(YupiRootDirectory, "Variables");

            try
            {
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/main.ini"));
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/Welcome/settings.ini"), true);

                if (uint.Parse(ServerConfigurationSettings.Data["db.pool.maxsize"]) > MaxRecommendedMySqlConnections)
                {
                    YupiWriterManager.WriteLine("MySQL Max Conn is High!, Recommended Value: " + MaxRecommendedMySqlConnections, "Yupi.Data", ConsoleColor.DarkYellow);
                }

                MySqlConnectionStringBuilder mySqlConnectionStringBuilder = new MySqlConnectionStringBuilder
                {
                    Server                = ServerConfigurationSettings.Data["db.hostname"],
                    Port                  = uint.Parse(ServerConfigurationSettings.Data["db.port"]),
                    UserID                = ServerConfigurationSettings.Data["db.username"],
                    Password              = ServerConfigurationSettings.Data["db.password"],
                    Database              = ServerConfigurationSettings.Data["db.name"],
                    MinimumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.minsize"]),
                    MaximumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.maxsize"]),
                    Pooling               = true,
                    AllowZeroDateTime     = true,
                    ConvertZeroDateTime   = true,
                    DefaultCommandTimeout = 300,
                    ConnectionTimeout     = 10
                };

                YupiDatabaseManager = new BasicDatabaseManager(mySqlConnectionStringBuilder);

                using (IQueryAdapter queryReactor = GetDatabaseManager().GetQueryReactor())
                {
                    DatabaseSettings = new ServerDatabaseSettings(queryReactor);
                    PetCommandHandler.Init(queryReactor);
                    PetLocale.Init(queryReactor);
                    OfflineMessages = new Dictionary <uint, List <OfflineMessage> >();
                    OfflineMessage.InitOfflineMessages(queryReactor);
                }

                YupiLogManager.Init(MethodBase.GetCurrentMethod().DeclaringType);

                ConsoleCleanTimeInterval = int.Parse(ServerConfigurationSettings.Data["console.clear.time"]);
                ConsoleTimerOn           = bool.Parse(ServerConfigurationSettings.Data["console.clear.enabled"]);
                FriendRequestLimit       = (uint)int.Parse(ServerConfigurationSettings.Data["client.maxrequests"]);

                LibraryParser.Incoming = new Dictionary <int, LibraryParser.StaticRequestHandler>();
                LibraryParser.Library  = new Dictionary <string, string>();
                LibraryParser.Outgoing = new Dictionary <string, int>();
                LibraryParser.Config   = new Dictionary <string, string>();

                LibraryParser.ReleaseName = ServerConfigurationSettings.Data["client.build"];

                LibraryParser.RegisterLibrary();
                LibraryParser.RegisterOutgoing();
                LibraryParser.RegisterIncoming();
                LibraryParser.RegisterConfig();

                Plugins = new Dictionary <string, IPlugin>();

                ICollection <IPlugin> plugins = LoadPlugins();

                if (plugins != null)
                {
                    foreach (IPlugin item in plugins.Where(item => item != null))
                    {
                        Plugins.Add(item.PluginName, item);

                        YupiWriterManager.WriteLine("Loaded Plugin: " + item.PluginName + " ServerVersion: " + item.PluginVersion, "Yupi.Plugins", ConsoleColor.DarkBlue);
                    }
                }

                ServerExtraSettings.RunExtraSettings();
                FurnitureDataManager.SetCache();
                CrossDomainSettings.Set();

                GameServer = new HabboHotel(int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]));

                GameServer.ContinueLoading();

                FurnitureDataManager.Clear();

                if (ServerConfigurationSettings.Data.ContainsKey("server.lang"))
                {
                    ServerLanguage = ServerConfigurationSettings.Data["server.lang"];
                }

                ServerLanguageVariables = new ServerLanguageSettings(ServerLanguage);

                YupiWriterManager.WriteLine("Loaded " + ServerLanguageVariables.Count() + " Languages Vars", "Yupi.Boot");

                if (plugins != null)
                {
                    foreach (IPlugin plugin in plugins)
                    {
                        plugin?.message_void();
                    }
                }

                if (ConsoleTimerOn)
                {
                    YupiWriterManager.WriteLine("Console Clear ConsoleRefreshTimer is Enabled, with " + ConsoleCleanTimeInterval + " Seconds.", "Yupi.Boot");
                }

                ClientMessageFactory.Init();

                YupiUserConnectionManager = new ConnectionHandler(int.Parse(ServerConfigurationSettings.Data["game.tcp.port"]),
                                                                  int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]),
                                                                  int.Parse(ServerConfigurationSettings.Data["game.tcp.conperip"]),
                                                                  ServerConfigurationSettings.Data["game.tcp.antiddos"].ToLower() == "true",
                                                                  ServerConfigurationSettings.Data["game.tcp.enablenagles"].ToLower() == "true");

                YupiWriterManager.WriteLine("Server Started at Port "
                                            + ServerConfigurationSettings.Data["game.tcp.port"] + " and Address "
                                            + ServerConfigurationSettings.Data["game.tcp.bindip"], "Yupi.Boot");

                if (LibraryParser.Config["Crypto.Enabled"] == "true")
                {
                    Handler.Initialize(LibraryParser.Config["Crypto.RSA.N"], LibraryParser.Config["Crypto.RSA.D"], LibraryParser.Config["Crypto.RSA.E"]);

                    YupiWriterManager.WriteLine("Started RSA crypto service", "Yupi.Crypto");
                }
                else
                {
                    YupiWriterManager.WriteLine("The encryption system is disabled.", "Yupi.Crypto", ConsoleColor.DarkYellow);
                }

                LibraryParser.Initialize();

                if (ConsoleTimerOn)
                {
                    ConsoleRefreshTimer = new Timer {
                        Interval = ConsoleCleanTimeInterval
                    };
                    ConsoleRefreshTimer.Elapsed += ConsoleRefreshTimerElapsed;
                    ConsoleRefreshTimer.Start();
                }

                if (ServerConfigurationSettings.Data.ContainsKey("game.multithread.enabled"))
                {
                    SeparatedTasksInMainLoops = ServerConfigurationSettings.Data["game.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("client.multithread.enabled"))
                {
                    SeparatedTasksInGameClientManager = ServerConfigurationSettings.Data["client.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("debug.packet"))
                {
                    PacketDebugMode = ServerConfigurationSettings.Data["debug.packet"] == "true";
                }

                YupiWriterManager.WriteLine("Yupi Emulator ready.", "Yupi.Boot");

                IsLive = true;
            }
            catch (Exception e)
            {
                YupiWriterManager.WriteLine("Error When Starting Yupi Environment!" + Environment.NewLine + e.Message, "Yupi.Boot", ConsoleColor.Red);
                YupiWriterManager.WriteLine("Please press Y to get more details or press other Key to Exit", "Yupi.Boot", ConsoleColor.Red);

                ConsoleKeyInfo key = Console.ReadKey();

                if (key.Key == ConsoleKey.Y)
                {
                    Console.WriteLine();

                    YupiWriterManager.WriteLine(
                        Environment.NewLine + "[Message] Error Details: " + Environment.NewLine + e.StackTrace +
                        Environment.NewLine + e.InnerException + Environment.NewLine + e.TargetSite +
                        Environment.NewLine + "[Message] Press Any Key To Exit", "Yupi.Boot", ConsoleColor.Red);

                    Console.ReadKey();
                }

                Environment.Exit(1);
            }
        }
Exemplo n.º 27
0
        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.");
            }
        }
Exemplo n.º 28
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}.");
                }
            }
        }