Advertisement
Guest User

Untitled

a guest
Feb 14th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.68 KB | None | 0 0
  1. using Butterfly.Core;
  2. using Butterfly.HabboHotel;
  3. using Butterfly.HabboHotel.GameClients;
  4. using Butterfly.HabboHotel.Users;
  5. using Butterfly.HabboHotel.Users.UserData;
  6. using Butterfly.Net;
  7. using Butterfly.Database;
  8. using Butterfly.Database.Interfaces;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.Text;
  13. using Buttefly.Communication.Encryption;
  14. using Buttefly.Communication.Encryption.Keys;
  15. using Butterfly.Core.FigureData;
  16. using ConnectionManager;
  17. using System.Collections.Concurrent;
  18. using Butterfly.Communication.WebSocket;
  19. using System.Reflection;
  20. using System.Threading;
  21. using Butterfly.Communication.Packets.Outgoing;
  22.  
  23. namespace Butterfly
  24. {
  25.     public static class ButterflyEnvironment
  26.     {
  27.         private static ConfigurationData _configuration;
  28.         private static ConnectionHandeling _connectionManager;
  29.         private static WebSocketManager _webSocketManager;
  30.         private static Game _game;
  31.         private static DatabaseManager _datebasemanager;
  32.         private static RCONSocket _rcon;
  33.         private static FigureDataManager _figureManager;
  34.         private static LanguageManager _languageManager;
  35.  
  36.         private static ConcurrentDictionary<int, Habbo> _usersCached = new ConcurrentDictionary<int, Habbo>();
  37.  
  38.         public static DateTime ServerStarted;
  39.         public static bool StaticEvents;
  40.         public static string PatchDir;
  41.  
  42.         public static Random Random = new Random();
  43.         public static int onlineUsersFr = 0;
  44.         public static int onlineUsersEn = 0;
  45.         public static int onlineUsersBr = 0;
  46.         public static int InfectionTime = 120;
  47.         public static bool ZombieInfectionMode = false;
  48.         private static readonly List<char> Allowedchars = new List<char>(new[]
  49.             {
  50.                 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  51.                 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
  52.                 'y', 'z',
  53.                 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
  54.                 '-', '.', '=', '?', '!', ':',
  55.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
  56.                 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  57.                 'Y', 'Z'
  58.             });
  59.  
  60.         public static void Initialize()
  61.         {
  62.             Console.Clear();
  63.  
  64.             ServerStarted = DateTime.Now;
  65.  
  66.             Console.ForegroundColor = ConsoleColor.Gray;
  67.  
  68.             PatchDir = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/";
  69.  
  70.             Console.Title = "Butterfly Emulator";
  71.  
  72.             try
  73.             {
  74.                 _configuration = new ConfigurationData(PatchDir + "Settings/configuration.ini", false);
  75.                 _datebasemanager = new DatabaseManager(uint.Parse(GetConfig().data["db.pool.maxsize"]), uint.Parse(GetConfig().data["db.pool.minsize"]), GetConfig().data["db.hostname"], uint.Parse(GetConfig().data["db.port"]), GetConfig().data["db.username"], GetConfig().data["db.password"], GetConfig().data["db.name"]);
  76.  
  77.  
  78.                 int TryCount = 0;
  79.                 while(!_datebasemanager.IsConnected())
  80.                 {
  81.                     TryCount++;
  82.                     Thread.Sleep(5000); //sleep 5sec
  83.  
  84.                     if (TryCount > 10)
  85.                     {
  86.                         Logging.WriteLine("Failed to connect to the specified MySQL server.");
  87.                         Console.ReadKey(true);
  88.                         Environment.Exit(1);
  89.                         return;
  90.                     }
  91.                 }
  92.                
  93.                 HabboEncryptionV2.Initialize(new RSAKeys());
  94.  
  95.                 _languageManager = new LanguageManager();
  96.                 _languageManager.Init();
  97.  
  98.                 _game = new Game();
  99.                 _game.StartGameLoop();
  100.  
  101.                 _figureManager = new FigureDataManager();
  102.                 _figureManager.Init();
  103.  
  104.                 if(_configuration.data["Websocketenable"] == "true")
  105.                     _webSocketManager = new WebSocketManager(2053, int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conlimit"]));
  106.  
  107.                 _connectionManager = new ConnectionHandeling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]));
  108.  
  109.                 if (_configuration.data["Musenable"] == "true")
  110.                     _rcon = new RCONSocket(int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(new char[1] { ';' }));
  111.  
  112.                 StaticEvents = _configuration.data["static.events"] == "true";
  113.                
  114.                 Logging.WriteLine("ENVIRONMENT -> READY!");
  115.  
  116.                 if (Debugger.IsAttached)
  117.                 {
  118.                     Console.ForegroundColor = ConsoleColor.Yellow;
  119.                     Logging.WriteLine("Server is debugging: Console writing enabled");
  120.                     Console.ForegroundColor = ConsoleColor.White;
  121.                 }
  122.                 else
  123.                 {
  124.                     Logging.WriteLine("Server is not debugging: Console writing disabled");
  125.                     Logging.DisablePrimaryWriting(false);
  126.                 }
  127.             }
  128.             catch (KeyNotFoundException ex)
  129.             {
  130.                 Logging.WriteLine("Please check your configuration file - some values appear to be missing.");
  131.                 Logging.WriteLine("Press any key to shut down ...");
  132.                 Logging.WriteLine((ex).ToString());
  133.                 Console.ReadKey(true);
  134.             }
  135.             catch (InvalidOperationException ex)
  136.             {
  137.                 Logging.WriteLine("Failed to initialize ButterflyEmulator: " + ex.Message);
  138.                 Logging.WriteLine("Press any key to shut down ...");
  139.                 Console.ReadKey(true);
  140.             }
  141.             catch (Exception ex)
  142.             {
  143.                 Console.WriteLine("Fatal error during startup: " + (ex).ToString());
  144.                 Console.WriteLine("Press a key to exit");
  145.                 Console.ReadKey();
  146.                 Environment.Exit(1);
  147.             }
  148.         }
  149.  
  150.         public static bool EnumToBool(string Enum)
  151.         {
  152.             return Enum == "1";
  153.         }
  154.  
  155.         public static string BoolToEnum(bool Bool)
  156.         {
  157.             return Bool ? "1" : "0";
  158.         }
  159.  
  160.         public static int GetRandomNumber(int Min, int Max)
  161.         {
  162.             return Random.Next(Min, Max + 1);
  163.         }
  164.  
  165.         public static int GetUnixTimestamp()
  166.         {
  167.             return (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
  168.         }
  169.  
  170.         public static FigureDataManager GetFigureManager()
  171.         {
  172.             return _figureManager;
  173.         }
  174.  
  175.         private static bool isValid(char character)
  176.         {
  177.             return Allowedchars.Contains(character);
  178.         }
  179.  
  180.         public static bool IsValidAlphaNumeric(string inputStr)
  181.         {
  182.             if (string.IsNullOrEmpty(inputStr))
  183.                 return false;
  184.             for (int index = 0; index < inputStr.Length; ++index)
  185.             {
  186.                 if (!isValid(inputStr[index]))
  187.                     return false;
  188.             }
  189.             return true;
  190.         }
  191.  
  192.         public static bool usernameExists(string username)
  193.         {
  194.             int integer;
  195.             using (IQueryAdapter queryreactor = GetDatabaseManager().GetQueryReactor())
  196.             {
  197.                 queryreactor.SetQuery("SELECT id FROM users WHERE username = @username LIMIT 1");
  198.                 queryreactor.AddParameter("username", username);
  199.                 integer = queryreactor.GetInteger();
  200.             }
  201.             if (integer <= 0)
  202.                 return false;
  203.  
  204.             return true;
  205.         }
  206.  
  207.         public static string GetUsernameById(int UserId)
  208.         {
  209.             string Name = "Unknown User";
  210.  
  211.             GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  212.             if (Client != null && Client.GetHabbo() != null)
  213.                 return Client.GetHabbo().Username;
  214.  
  215.  
  216.             if (_usersCached.ContainsKey(UserId))
  217.                 return _usersCached[UserId].Username;
  218.  
  219.             using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  220.             {
  221.                 dbClient.SetQuery("SELECT `username` FROM `users` WHERE `id` = @id LIMIT 1");
  222.                 dbClient.AddParameter("id", UserId);
  223.                 Name = dbClient.GetString();
  224.             }
  225.  
  226.             if (string.IsNullOrEmpty(Name))
  227.                 Name = "Unknown User";
  228.  
  229.             return Name;
  230.         }
  231.  
  232.         public static Habbo GetHabboByUsername(string UserName)
  233.         {
  234.             try
  235.             {
  236.                 using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  237.                 {
  238.                     dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
  239.                     dbClient.AddParameter("user", UserName);
  240.                     int id = dbClient.GetInteger();
  241.                     if (id > 0)
  242.                         return GetHabboById(Convert.ToInt32(id));
  243.                 }
  244.                 return null;
  245.             }
  246.             catch { return null; }
  247.         }
  248.  
  249.         public static Habbo GetHabboById(int UserId)
  250.         {
  251.             try
  252.             {
  253.                 GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  254.                 if (Client != null)
  255.                 {
  256.                     Habbo User = Client.GetHabbo();
  257.                     if (User != null && User.Id > 0)
  258.                     {
  259.                         if (_usersCached.ContainsKey(UserId))
  260.                             _usersCached.TryRemove(UserId, out User);
  261.  
  262.                         return User;
  263.                     }
  264.                 }
  265.                 else
  266.                 {
  267.                     try
  268.                     {
  269.                         if (_usersCached.ContainsKey(UserId))
  270.                             return _usersCached[UserId];
  271.                         else
  272.                         {
  273.                             UserData data = UserDataFactory.GetUserData(UserId);
  274.                             if (data != null)
  275.                             {
  276.                                 Habbo Generated = data.user;
  277.                                 if (Generated != null)
  278.                                 {
  279.                                     _usersCached.TryAdd(UserId, Generated);
  280.                                     return Generated;
  281.                                 }
  282.                             }
  283.                         }
  284.                     }
  285.                     catch { return null; }
  286.                 }
  287.                 return null;
  288.             }
  289.             catch
  290.             {
  291.                 return null;
  292.             }
  293.         }
  294.  
  295.         public static LanguageManager GetLanguageManager()
  296.         {
  297.             return _languageManager;
  298.         }
  299.  
  300.         public static ConfigurationData GetConfig()
  301.         {
  302.             return _configuration;
  303.         }
  304.  
  305.         public static ConnectionHandeling GetConnectionManager()
  306.         {
  307.             return _connectionManager;
  308.         }
  309.  
  310.         public static RCONSocket GetRCONSocket()
  311.         {
  312.             return _rcon;
  313.         }
  314.  
  315.         public static Game GetGame()
  316.         {
  317.             return _game;
  318.         }
  319.  
  320.         public static DatabaseManager GetDatabaseManager()
  321.         {
  322.             return _datebasemanager;
  323.         }
  324.  
  325.         public static void PreformShutDown()
  326.         {
  327.             PreformShutDown(true);
  328.         }
  329.  
  330.         public static void PreformShutDown(bool ExitWhenDone)
  331.         {
  332.             StringBuilder builder = new StringBuilder();
  333.  
  334.             DateTime now1 = DateTime.Now;
  335.  
  336.             DateTime now2 = DateTime.Now;
  337.  
  338.             ServerPacket message = new ServerPacket(ServerPacketHeader.BroadcastMessageAlertMessageComposer);
  339.             message.WriteString("L'hôtel subit un redémarrage d'entretien, nous revenons dans quelques instants, nous nous excusons pour la gêne occasionnée !");
  340.             GetGame().GetClientManager().SendMessage(message);
  341.  
  342.             Thread.Sleep(10000);
  343.  
  344.             AppendTimeStampWithComment(ref builder, now2, "Hotel pre-warning");
  345.  
  346.             _game.StopGameLoop();
  347.             Console.Write("Game loop stopped");
  348.  
  349.             DateTime now3 = DateTime.Now;
  350.             Console.WriteLine("Server shutting down...");
  351.             Console.Title = "<<- SERVER SHUTDOWN ->>";
  352.  
  353.             GetConnectionManager().Destroy();
  354.             AppendTimeStampWithComment(ref builder, now3, "Socket close");
  355.  
  356.             DateTime now5 = DateTime.Now;
  357.             Console.WriteLine("<<- SERVER SHUTDOWN ->> ROOM SAVE");
  358.             _game.GetRoomManager().RemoveAllRooms();
  359.             AppendTimeStampWithComment(ref builder, now5, "Room destructor");
  360.  
  361.             DateTime now4 = DateTime.Now;
  362.             GetGame().GetClientManager().CloseAll();
  363.             AppendTimeStampWithComment(ref builder, now4, "Furni pre-save and connection close");
  364.  
  365.             //ButterflyEnvironment.Game.GetPromotedRooms().executeUpdates();
  366.  
  367.             DateTime now7 = DateTime.Now;
  368.             if(_connectionManager != null)
  369.                 _connectionManager.Destroy();
  370.             if(_webSocketManager != null)
  371.                 _webSocketManager.Destroy();
  372.  
  373.             AppendTimeStampWithComment(ref builder, now7, "Connection shutdown");
  374.  
  375.             DateTime now8 = DateTime.Now;
  376.             _game.Destroy();
  377.             AppendTimeStampWithComment(ref builder, now8, "Game destroy");
  378.  
  379.             DateTime now9 = DateTime.Now;
  380.  
  381.             TimeSpan span = DateTime.Now - now1;
  382.             builder.AppendLine("Total time on shutdown " + TimeSpanToString(span));
  383.             builder.AppendLine("You have reached ==> [END OF SESSION]");
  384.             builder.AppendLine();
  385.             builder.AppendLine();
  386.             builder.AppendLine();
  387.             Logging.LogShutdown(builder);
  388.             Console.WriteLine("System disposed, goodbye!");
  389.             if (!ExitWhenDone)
  390.                 return;
  391.             Environment.Exit(Environment.ExitCode);
  392.         }
  393.  
  394.         public static string TimeSpanToString(TimeSpan span)
  395.         {
  396.             return string.Concat(new object[4]
  397.       {
  398.          span.Seconds,
  399.          " s, ",
  400.          span.Milliseconds,
  401.          " ms"
  402.       });
  403.         }
  404.  
  405.         public static void AppendTimeStampWithComment(ref StringBuilder builder, DateTime time, string text)
  406.         {
  407.             builder.AppendLine(text + " =>[" + TimeSpanToString(DateTime.Now - time) + "]");
  408.         }
  409.     }
  410. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement