Advertisement
Guest User

Chris, do as i say

a guest
Aug 15th, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.76 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.Blue;
  72. Console.WriteLine();
  73. Console.WriteLine(" ██████╗ ██████╗ ███╗ ███╗███████╗████████╗ ██████╗ ███████╗██╗ ██╗");
  74. Console.WriteLine(" ██╔════╝██╔═══██╗████╗ ████║██╔════╝╚══██╔══╝ ██╔══██╗██╔════╝██║ ██║");
  75. Console.WriteLine(" ██║ ██║ ██║██╔████╔██║█████╗ ██║ ██║ ██║█████╗ ██║ ██║");
  76. Console.WriteLine(" █║ ██║ ██ ██║╚██╔╝██║██╔══╝ ██║ ██║ ██║██╔══╝ ╚██╗ ██╔╝");
  77. Console.WriteLine(" ██████╗╚██████╔╝ ██║ ╚═╝ ██║███████╗ ██║ ██████╔╝███████╗ ╚████╔╝ ");
  78. Console.WriteLine(" ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═══╝ \n Comet was here\n Shawn enjoys coding c#\n (y) was chris here??");
  79.  
  80.  
  81. Console.ForegroundColor = ConsoleColor.Blue;
  82.  
  83. Console.WriteLine(" " + PrettyVersion + " <Build " + PrettyBuild + ">");
  84. Console.WriteLine(" http://PlusIndustry.com");
  85.  
  86. Console.WriteLine("");
  87. Console.Title = "Loading Emulator";
  88. _defaultEncoding = Encoding.Default;
  89.  
  90. Console.WriteLine("");
  91. Console.WriteLine("");
  92.  
  93. CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
  94.  
  95.  
  96. try
  97. {
  98.  
  99. _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"config.ini"));
  100.  
  101. var connectionString = new MySqlConnectionStringBuilder
  102. {
  103. ConnectionTimeout = 10,
  104. Database = GetConfig().data["db.name"],
  105. DefaultCommandTimeout = 30,
  106. Logging = false,
  107. MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]),
  108. MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]),
  109. Password = GetConfig().data["db.password"],
  110. Pooling = true,
  111. Port = uint.Parse(GetConfig().data["db.port"]),
  112. Server = GetConfig().data["db.hostname"],
  113. UserID = GetConfig().data["db.username"],
  114. AllowZeroDateTime = true,
  115. ConvertZeroDateTime = true,
  116. };
  117.  
  118. _manager = new DatabaseManager(connectionString.ToString());
  119.  
  120. if (!_manager.IsConnected())
  121. {
  122. log.Error("Failed to connect to the database, make sure the information in config is correct..");
  123. Console.ReadKey(true);
  124. Environment.Exit(1);
  125. return;
  126. }
  127.  
  128. log.Info("Connected to database successfully");
  129.  
  130. //Reset our statistics first.
  131. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  132. {
  133. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  134. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';");
  135. dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'");
  136. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  137. }
  138.  
  139. //Get the configuration & Game set.
  140. ConfigData = new ConfigData();
  141. _game = new Game();
  142.  
  143. //Have our encryption ready.
  144. HabboEncryptionV2.Initialize(new RSAKeys());
  145.  
  146. //Make sure MUS is working.
  147. MusSystem = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";")), 0);
  148.  
  149. //Accept connections.
  150. _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");
  151. _connectionManager.init();
  152.  
  153. _game.StartGameLoop();
  154.  
  155. TimeSpan TimeUsed = DateTime.Now - ServerStarted;
  156.  
  157. Console.WriteLine();
  158.  
  159. log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
  160. }
  161. catch (KeyNotFoundException e)
  162. {
  163. Logging.WriteLine("Something is definitely not right here! - please check your configuration file.", ConsoleColor.Red);
  164. Logging.WriteLine("Press any key to shut down ...");
  165. Logging.WriteLine(e.ToString());
  166. Console.ReadKey(true);
  167. Environment.Exit(1);
  168. return;
  169. }
  170. catch (InvalidOperationException e)
  171. {
  172. Logging.WriteLine("Failed to succesfull initialize Emulator: " + e.Message, ConsoleColor.Red);
  173. Logging.WriteLine("Press any key to shut down ...");
  174. Console.ReadKey(true);
  175. Environment.Exit(1);
  176. return;
  177. }
  178. catch (Exception e)
  179. {
  180. Logging.WriteLine("Fatal error during startup: " + e, ConsoleColor.Red);
  181. Logging.WriteLine("Press a key to exit");
  182.  
  183. Console.ReadKey();
  184. Environment.Exit(1);
  185. }
  186. }
  187.  
  188. public static bool EnumToBool(string Enum)
  189. {
  190. return (Enum == "1");
  191. }
  192.  
  193. public static string BoolToEnum(bool Bool)
  194. {
  195. return (Bool == true ? "1" : "0");
  196. }
  197.  
  198. public static int GetRandomNumber(int Min, int Max)
  199. {
  200. return RandomNumber.GenerateNewRandom(Min, Max);
  201. }
  202.  
  203. public static double GetUnixTimestamp()
  204. {
  205. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  206. return ts.TotalSeconds;
  207. }
  208.  
  209. public static long Now()
  210. {
  211. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  212. double unixTime = ts.TotalMilliseconds;
  213. return (long)unixTime;
  214. }
  215.  
  216. public static string FilterFigure(string figure)
  217. {
  218. foreach (char character in figure)
  219. {
  220. if (!isValid(character))
  221. 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";
  222. }
  223.  
  224. return figure;
  225. }
  226.  
  227. private static bool isValid(char character)
  228. {
  229. return Allowedchars.Contains(character);
  230. }
  231.  
  232. public static bool IsValidAlphaNumeric(string inputStr)
  233. {
  234. inputStr = inputStr.ToLower();
  235. if (string.IsNullOrEmpty(inputStr))
  236. {
  237. return false;
  238. }
  239.  
  240. for (int i = 0; i < inputStr.Length; i++)
  241. {
  242. if (!isValid(inputStr[i]))
  243. {
  244. return false;
  245. }
  246. }
  247.  
  248. return true;
  249. }
  250.  
  251. public static string GetUsernameById(int UserId)
  252. {
  253. string Name = "Unknown User";
  254.  
  255. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  256. if (Client != null && Client.GetHabbo() != null)
  257. return Client.GetHabbo().Username;
  258.  
  259. UserCache User = PlusEnvironment.GetGame().GetCacheManager().GenerateUser(UserId);
  260. if (User != null)
  261. return User.Username;
  262.  
  263. using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
  264. {
  265. dbClient.SetQuery("SELECT `username` FROM `users` WHERE id = @id LIMIT 1");
  266. dbClient.AddParameter("id", UserId);
  267. Name = dbClient.getString();
  268. }
  269.  
  270. if (string.IsNullOrEmpty(Name))
  271. Name = "Unknown User";
  272.  
  273. return Name;
  274. }
  275.  
  276. public static Habbo GetHabboById(int UserId)
  277. {
  278. try
  279. {
  280. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  281. if (Client != null)
  282. {
  283. Habbo User = Client.GetHabbo();
  284. if (User != null && User.Id > 0)
  285. {
  286. if (_usersCached.ContainsKey(UserId))
  287. _usersCached.TryRemove(UserId, out User);
  288. return User;
  289. }
  290. }
  291. else
  292. {
  293. try
  294. {
  295. if (_usersCached.ContainsKey(UserId))
  296. return _usersCached[UserId];
  297. else
  298. {
  299. UserData data = UserDataFactory.GetUserData(UserId);
  300. if (data != null)
  301. {
  302. Habbo Generated = data.user;
  303. if (Generated != null)
  304. {
  305. Generated.InitInformation(data);
  306. _usersCached.TryAdd(UserId, Generated);
  307. return Generated;
  308. }
  309. }
  310. }
  311. }
  312. catch { return null; }
  313. }
  314. return null;
  315. }
  316. catch
  317. {
  318. return null;
  319. }
  320. }
  321.  
  322. public static Habbo GetHabboByUsername(String UserName)
  323. {
  324. try
  325. {
  326. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  327. {
  328. dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
  329. dbClient.AddParameter("user", UserName);
  330. int id = dbClient.getInteger();
  331. if (id > 0)
  332. return GetHabboById(Convert.ToInt32(id));
  333. }
  334. return null;
  335. }
  336. catch { return null; }
  337. }
  338.  
  339.  
  340.  
  341. public static void PerformShutDown()
  342. {
  343. Console.Clear();
  344. log.Info("Server shutting down...");
  345. Console.Title = "SHUTTING DOWN!";
  346.  
  347. PlusEnvironment.GetGame().GetClientManager().SendMessage(new BroadcastMessageAlertComposer(PlusEnvironment.GetGame().GetLanguageLocale().TryGetValue("shutdown_alert")));
  348. GetGame().StopGameLoop();
  349. Thread.Sleep(2500);
  350. GetConnectionManager().Destroy();//Stop listening.
  351. GetGame().GetPacketManager().UnregisterAll();//Unregister the packets.
  352. GetGame().GetPacketManager().WaitForAllToComplete();
  353. GetGame().GetClientManager().CloseAll();//Close all connections
  354. GetGame().GetRoomManager().Dispose();//Stop the game loop.
  355.  
  356. using (IQueryAdapter dbClient = _manager.GetQueryReactor())
  357. {
  358. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  359. dbClient.RunQuery("UPDATE `users` SET online = '0', `auth_ticket` = NULL");
  360. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0'");
  361. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  362. }
  363.  
  364. log.Info("Plus Emulator has successfully shutdown.");
  365.  
  366. Thread.Sleep(1000);
  367. Environment.Exit(0);
  368. }
  369.  
  370. public static ConfigurationData GetConfig()
  371. {
  372. return _configuration;
  373. }
  374.  
  375. public static ConfigData GetDBConfig()
  376. {
  377. return ConfigData;
  378. }
  379.  
  380. public static Encoding GetDefaultEncoding()
  381. {
  382. return _defaultEncoding;
  383. }
  384.  
  385. public static ConnectionHandling GetConnectionManager()
  386. {
  387. return _connectionManager;
  388. }
  389.  
  390. public static Game GetGame()
  391. {
  392. return _game;
  393. }
  394.  
  395. public static DatabaseManager GetDatabaseManager()
  396. {
  397. return _manager;
  398. }
  399.  
  400. public static ICollection<Habbo> GetUsersCached()
  401. {
  402. return _usersCached.Values;
  403. }
  404.  
  405. public static bool RemoveFromCache(int Id, out Habbo Data)
  406. {
  407. return _usersCached.TryRemove(Id, out Data);
  408. }
  409. }
  410. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement