Advertisement
Guest User

Untitled

a guest
Oct 29th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.79 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Windows.Forms;
  9. using MySql.Data.MySqlClient;
  10. using Plus.Core;
  11.  
  12. using Plus.HabboHotel;
  13. using Plus.HabboHotel.GameClients;
  14. using Plus.HabboHotel.Rooms.AI;
  15. using Plus.HabboHotel.Users;
  16. using Plus.HabboHotel.Users.Messenger;
  17. using Plus.HabboHotel.Users.UserDataManagement;
  18. using Plus.Communication.Packets.Incoming;
  19.  
  20. using Plus.Net;
  21. using Plus.Utilities;
  22. using log4net;
  23.  
  24. using System.Data;
  25. using System.Security.Cryptography;
  26. using System.Collections.Concurrent;
  27. using Plus.Communication.Packets.Outgoing.Moderation;
  28. using Plus.Communication.Encryption.Keys;
  29. using Plus.Communication.Encryption;
  30.  
  31. using Plus.Database.Interfaces;
  32. using Plus.HabboHotel.Cache;
  33. using Plus.Database;
  34.  
  35. namespace Plus
  36. {
  37. public static class PlusEnvironment
  38. {
  39. private static readonly ILog log = LogManager.GetLogger("Plus.PlusEnvironment");
  40.  
  41. public const string PrettyVersion = "Plus Emulator";
  42. public const string PrettyBuild = "3.4.3.0";
  43.  
  44. private static ConfigurationData _configuration;
  45. private static Encoding _defaultEncoding;
  46. private static ConnectionHandling _connectionManager;
  47. private static Game _game;
  48. private static DatabaseManager _manager;
  49. public static ConfigData ConfigData;
  50. public static MusSocket MusSystem;
  51. public static CultureInfo CultureInfo;
  52.  
  53. public static bool Event = false;
  54. public static DateTime lastEvent;
  55. public static DateTime ServerStarted;
  56.  
  57. private static readonly List<char> Allowedchars = new List<char>(new[]
  58. {
  59. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  60. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
  61. 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '.'
  62. });
  63.  
  64. private static ConcurrentDictionary<int, Habbo> _usersCached = new ConcurrentDictionary<int, Habbo>();
  65.  
  66. public static string SWFRevision = "";
  67.  
  68. public static void Initialize()
  69. {
  70. ServerStarted = DateTime.Now;
  71. Console.ForegroundColor = ConsoleColor.DarkGreen;
  72. Console.WriteLine();
  73. Console.WriteLine(" ____ __ ________ _____ __");
  74. Console.WriteLine(@" / __ \/ /_ _______/ ____/ |/ / / / /");
  75. Console.WriteLine(" / /_/ / / / / / ___/ __/ / /|_/ / / / / ");
  76. Console.WriteLine(" / ____/ / /_/ (__ ) /___/ / / / /_/ / ");
  77. Console.WriteLine(@" /_/ /_/\__,_/____/_____/_/ /_/\____/ ");
  78.  
  79. Console.ForegroundColor = ConsoleColor.Green;
  80.  
  81. Console.WriteLine(" " + PrettyVersion + " <Build " + PrettyBuild + ">");
  82. Console.WriteLine(" http://sabbo.me");
  83.  
  84. Console.WriteLine("");
  85. Console.Title = "Loading Plus Emulator";
  86. _defaultEncoding = Encoding.Default;
  87.  
  88. Console.WriteLine("");
  89. Console.WriteLine("");
  90.  
  91. CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
  92.  
  93.  
  94. try
  95. {
  96.  
  97. _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"config.ini"));
  98.  
  99. var connectionString = new MySqlConnectionStringBuilder
  100. {
  101. ConnectionTimeout = 10,
  102. Database = GetConfig().data["db.name"],
  103. DefaultCommandTimeout = 30,
  104. Logging = false,
  105. MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]),
  106. MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]),
  107. Password = GetConfig().data["db.password"],
  108. Pooling = true,
  109. Port = uint.Parse(GetConfig().data["db.port"]),
  110. Server = GetConfig().data["db.hostname"],
  111. UserID = GetConfig().data["db.username"],
  112. AllowZeroDateTime = true,
  113. ConvertZeroDateTime = true,
  114. };
  115.  
  116. _manager = new DatabaseManager(connectionString.ToString());
  117.  
  118. if (!_manager.IsConnected())
  119. {
  120. log.Error("Failed to connect to the specified MySQL server.");
  121. Console.ReadKey(true);
  122. Environment.Exit(1);
  123. return;
  124. }
  125.  
  126. log.Info("Connected to Database!");
  127.  
  128. //Reset our statistics first.
  129. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  130. {
  131. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  132. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';");
  133. dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'");
  134. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  135. }
  136.  
  137. //Get the configuration & Game set.
  138. ConfigData = new ConfigData();
  139. _game = new Game();
  140.  
  141. //Have our encryption ready.
  142. HabboEncryptionV2.Initialize(new RSAKeys());
  143.  
  144. //Make sure MUS is working.
  145. MusSystem = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";")), 0);
  146.  
  147. //Accept connections.
  148. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
  149. _connectionManager.init();
  150.  
  151. _game.StartGameLoop();
  152.  
  153. TimeSpan TimeUsed = DateTime.Now - ServerStarted;
  154.  
  155. Console.WriteLine();
  156.  
  157. log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
  158. }
  159. catch (KeyNotFoundException e)
  160. {
  161. Logging.WriteLine("Please check your configuration file - some values appear to be missing.", ConsoleColor.Red);
  162. Logging.WriteLine("Press any key to shut down ...");
  163. Logging.WriteLine(e.ToString());
  164. Console.ReadKey(true);
  165. Environment.Exit(1);
  166. return;
  167. }
  168. catch (InvalidOperationException e)
  169. {
  170. Logging.WriteLine("Failed to initialize PlusEmulator: " + e.Message, ConsoleColor.Red);
  171. Logging.WriteLine("Press any key to shut down ...");
  172. Console.ReadKey(true);
  173. Environment.Exit(1);
  174. return;
  175. }
  176. catch (Exception e)
  177. {
  178. Logging.WriteLine("Fatal error during startup: " + e, ConsoleColor.Red);
  179. Logging.WriteLine("Press a key to exit");
  180.  
  181. Console.ReadKey();
  182. Environment.Exit(1);
  183. }
  184. }
  185.  
  186. public static bool EnumToBool(string Enum)
  187. {
  188. return (Enum == "1");
  189. }
  190.  
  191. public static string BoolToEnum(bool Bool)
  192. {
  193. return (Bool == true ? "1" : "0");
  194. }
  195.  
  196. public static int GetRandomNumber(int Min, int Max)
  197. {
  198. return RandomNumber.GenerateNewRandom(Min, Max);
  199. }
  200.  
  201. public static double GetUnixTimestamp()
  202. {
  203. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  204. return ts.TotalSeconds;
  205. }
  206.  
  207. public static long Now()
  208. {
  209. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  210. double unixTime = ts.TotalMilliseconds;
  211. return (long)unixTime;
  212. }
  213.  
  214. public static string FilterFigure(string figure)
  215. {
  216. foreach (char character in figure)
  217. {
  218. if (!isValid(character))
  219. return "sh-3338-93.ea-1406-62.hr-831-49.ha-3331-92.hd-180-7.ch-3334-93-1408.lg-3337-92.ca-1813-62";
  220. }
  221.  
  222. return figure;
  223. }
  224.  
  225. private static bool isValid(char character)
  226. {
  227. return Allowedchars.Contains(character);
  228. }
  229.  
  230. public static bool IsValidAlphaNumeric(string inputStr)
  231. {
  232. inputStr = inputStr.ToLower();
  233. if (string.IsNullOrEmpty(inputStr))
  234. {
  235. return false;
  236. }
  237.  
  238. for (int i = 0; i < inputStr.Length; i++)
  239. {
  240. if (!isValid(inputStr[i]))
  241. {
  242. return false;
  243. }
  244. }
  245.  
  246. return true;
  247. }
  248.  
  249. public static string GetUsernameById(int UserId)
  250. {
  251. string Name = "Unknown User";
  252.  
  253. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  254. if (Client != null && Client.GetHabbo() != null)
  255. return Client.GetHabbo().Username;
  256.  
  257. UserCache User = PlusEnvironment.GetGame().GetCacheManager().GenerateUser(UserId);
  258. if (User != null)
  259. return User.Username;
  260.  
  261. using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
  262. {
  263. dbClient.SetQuery("SELECT `username` FROM `users` WHERE id = @id LIMIT 1");
  264. dbClient.AddParameter("id", UserId);
  265. Name = dbClient.getString();
  266. }
  267.  
  268. if (string.IsNullOrEmpty(Name))
  269. Name = "Unknown User";
  270.  
  271. return Name;
  272. }
  273.  
  274. public static Habbo GetHabboById(int UserId)
  275. {
  276. try
  277. {
  278. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  279. if (Client != null)
  280. {
  281. Habbo User = Client.GetHabbo();
  282. if (User != null && User.Id > 0)
  283. {
  284. if (_usersCached.ContainsKey(UserId))
  285. _usersCached.TryRemove(UserId, out User);
  286. return User;
  287. }
  288. }
  289. else
  290. {
  291. try
  292. {
  293. if (_usersCached.ContainsKey(UserId))
  294. return _usersCached[UserId];
  295. else
  296. {
  297. UserData data = UserDataFactory.GetUserData(UserId);
  298. if (data != null)
  299. {
  300. Habbo Generated = data.user;
  301. if (Generated != null)
  302. {
  303. Generated.InitInformation(data);
  304. _usersCached.TryAdd(UserId, Generated);
  305. return Generated;
  306. }
  307. }
  308. }
  309. }
  310. catch { return null; }
  311. }
  312. return null;
  313. }
  314. catch
  315. {
  316. return null;
  317. }
  318. }
  319.  
  320. public static Habbo GetHabboByUsername(String UserName)
  321. {
  322. try
  323. {
  324. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  325. {
  326. dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
  327. dbClient.AddParameter("user", UserName);
  328. int id = dbClient.getInteger();
  329. if (id > 0)
  330. return GetHabboById(Convert.ToInt32(id));
  331. }
  332. return null;
  333. }
  334. catch { return null; }
  335. }
  336.  
  337.  
  338.  
  339. public static void PerformShutDown()
  340. {
  341. Console.Clear();
  342. log.Info("Server shutting down...");
  343. Console.Title = "PLUS EMULATOR: SHUTTING DOWN!";
  344.  
  345. PlusEnvironment.GetGame().GetClientManager().SendMessage(new BroadcastMessageAlertComposer(PlusEnvironment.GetGame().GetLanguageLocale().TryGetValue("shutdown_alert")));
  346. GetGame().StopGameLoop();
  347. Thread.Sleep(2500);
  348. GetConnectionManager().Destroy();//Stop listening.
  349. GetGame().GetPacketManager().UnregisterAll();//Unregister the packets.
  350. GetGame().GetPacketManager().WaitForAllToComplete();
  351. GetGame().GetClientManager().CloseAll();//Close all connections
  352. GetGame().GetRoomManager().Dispose();//Stop the game loop.
  353.  
  354. using (IQueryAdapter dbClient = _manager.GetQueryReactor())
  355. {
  356. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  357. dbClient.RunQuery("TRUNCATE `user_auth_ticket`");
  358. dbClient.RunQuery("UPDATE `users` SET online = '0'");
  359. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0'");
  360. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  361. }
  362.  
  363. log.Info("Plus Emulator has successfully shutdown.");
  364.  
  365. Thread.Sleep(1000);
  366. Environment.Exit(0);
  367. }
  368.  
  369. public static ConfigurationData GetConfig()
  370. {
  371. return _configuration;
  372. }
  373.  
  374. public static ConfigData GetDBConfig()
  375. {
  376. return ConfigData;
  377. }
  378.  
  379. public static Encoding GetDefaultEncoding()
  380. {
  381. return _defaultEncoding;
  382. }
  383.  
  384. public static ConnectionHandling GetConnectionManager()
  385. {
  386. return _connectionManager;
  387. }
  388.  
  389. public static Game GetGame()
  390. {
  391. return _game;
  392. }
  393.  
  394. public static DatabaseManager GetDatabaseManager()
  395. {
  396. return _manager;
  397. }
  398.  
  399. public static ICollection<Habbo> GetUsersCached()
  400. {
  401. return _usersCached.Values;
  402. }
  403.  
  404. public static bool RemoveFromCache(int Id, out Habbo Data)
  405. {
  406. return _usersCached.TryRemove(Id, out Data);
  407. }
  408. }
  409. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement