Advertisement
Guest User

Untitled

a guest
May 2nd, 2018
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.21 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.Windows.Forms;
  8. using System.Reflection;
  9. using MySql.Data.MySqlClient;
  10. using Bios.Core;
  11. using Bios.HabboHotel;
  12. using Bios.HabboHotel.GameClients;
  13. using Bios.HabboHotel.Users;
  14. using Bios.HabboHotel.Users.UserData;
  15. using Bios.Communication.RCON;
  16. using Bios.Communication.ConnectionManager;
  17. using Bios.Utilities;
  18. using log4net;
  19. using System.Collections.Concurrent;
  20. using Bios.Communication.Packets.Outgoing.Moderation;
  21. using Bios.Communication.Encryption.Keys;
  22. using Bios.Communication.Encryption;
  23. using Bios.Database.Interfaces;
  24. using Bios.HabboHotel.Cache.Type;
  25. using Bios.Database;
  26.  
  27. namespace Bios
  28. {
  29. public static class PlusEnvironment
  30. {
  31. private static readonly ILog log = LogManager.GetLogger("Bios.BiosEmuThiago");
  32. public static string HotelName;
  33. public static string Licenseto;
  34. public static bool IsLive;
  35. public static string CurrentTime = DateTime.Now.ToString("hh:mm:ss tt" + "- [SaturnEMU] ");
  36. public const string PrettyVersion = "Saturn Emulador ";
  37. public const string PrettyBuild = " 1.1.2 ";
  38. public const string ServerVersion = " 1.1.1 ";
  39. public const string VersionBios = "";
  40. public const string LastUpdate = " 02/09/2017 ";
  41.  
  42. private static Encoding _defaultEncoding;
  43. public static CultureInfo CultureInfo;
  44.  
  45. internal static object UnixTimeStampToDateTime(double timestamp)
  46. {
  47. throw new NotImplementedException();
  48. }
  49.  
  50. private static Game _game;
  51. private static ConfigurationData _configuration;
  52. private static ConnectionHandling _connectionManager;
  53. private static DatabaseManager _manager;
  54. private static RCONSocket _rcon;
  55.  
  56. // TODO: Get rid?
  57. public static bool Event = false;
  58. public static DateTime lastEvent;
  59. public static DateTime ServerStarted;
  60.  
  61. private static readonly List<char> Allowedchars = new List<char>(new[]
  62. {
  63. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  64. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
  65. 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '.'
  66. });
  67.  
  68. private static ConcurrentDictionary<int, Habbo> _usersCached = new ConcurrentDictionary<int, Habbo>();
  69. public static string SWFRevision = "";
  70. public static int Quartovip;
  71. public static int Prisao;
  72.  
  73. public static void Initialize()
  74. {
  75. ServerStarted = DateTime.Now;
  76. Console.ForegroundColor = ConsoleColor.Gray;
  77. Console.WriteLine("");
  78. Console.ForegroundColor = ConsoleColor.DarkCyan;
  79. Console.WriteLine(@" _______ __ _______ ___ ___ ___ ___ ");
  80. Console.WriteLine(@" | _ | .---.-. | |_ .--.--. .----. .-----. | _ | | Y | | Y |");
  81. Console.WriteLine(@" | 1___| | _ | | _| | | | | _| | | |. 1___| |. | |. | | ");
  82. Console.WriteLine(@" |____ | |___._| |____| |_____| |__| |__|__| |. __)_ |. \_/ | |. | | ");
  83. Console.WriteLine(@" |: 1 | |: 1 | |: | | |: 1 | ");
  84. Console.WriteLine(@" |::.. . | |::.. . | |::.|:. | |::.. . | ");
  85. Console.WriteLine(@" `-------' `-------' `--- ---' `-------' ");
  86. Console.WriteLine("");
  87. Console.WriteLine(@" © 2018 - Todos direitos reservado. SaturnEMU (Baseado no Cloud)");
  88. Console.ForegroundColor = ConsoleColor.DarkCyan;
  89. Console.WriteLine(
  90. Console.LargestWindowWidth > 30? @"...................................................................................................................... ": @"");
  91. Console.WriteLine("");
  92. Console.ForegroundColor = ConsoleColor.Gray;
  93.  
  94. Console.Title = "Saturn Emulador | Carregando...";
  95. CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
  96. try
  97. {
  98. _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"rSaturn/Config.ini"));
  99.  
  100. var connectionString = new MySqlConnectionStringBuilder
  101. {
  102. ConnectionTimeout = 10,
  103. Database = GetConfig().data["db.name"],
  104. DefaultCommandTimeout = 30,
  105. Logging = false,
  106. MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]),
  107. MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]),
  108. Password = GetConfig().data["db.password"],
  109. Pooling = true,
  110. Port = uint.Parse(GetConfig().data["db.port"]),
  111. Server = GetConfig().data["db.hostname"],
  112. UserID = GetConfig().data["db.username"],
  113. AllowZeroDateTime = true,
  114. ConvertZeroDateTime = true,
  115. };
  116.  
  117. _manager = new DatabaseManager(connectionString.ToString());
  118.  
  119. if (!_manager.IsConnected())
  120. {
  121. log.Warn("» Existe uma conexão com o banco de dados já existente ou há um problema para se conectar a ele.");
  122. Console.ReadKey(true);
  123. Environment.Exit(1);
  124. return;
  125. }
  126.  
  127. log.Info("» Conectado ao banco de dados!");
  128.  
  129. #region Add 2016
  130. HotelName = Convert.ToString(GetConfig().data["hotel.name"]);
  131. Licenseto = Convert.ToString(GetConfig().data["license"]);
  132. #endregion Add 2016
  133.  
  134. //Reset our statistics first.
  135. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  136. {
  137. dbClient.runFastQuery("TRUNCATE `catalog_marketplace_data`");
  138. dbClient.runFastQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0'");
  139. dbClient.runFastQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'");
  140. dbClient.runFastQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0', `status` = '1'");
  141. }
  142.  
  143. _game = new Game();
  144. _game.ContinueLoading();
  145.  
  146. //Have our encryption ready.
  147. HabboEncryptionV2.Initialize(new RSAKeys());
  148.  
  149. //Make sure MUS is working.
  150. _rcon = new RCONSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(";")));
  151.  
  152. //Accept connections.
  153. _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");
  154. _connectionManager.Init();
  155.  
  156. //_game.StartGameLoop();
  157. TimeSpan TimeUsed = DateTime.Now - ServerStarted;
  158.  
  159. Quartovip = int.Parse(GetConfig().data["Quartovip"]);
  160. Prisao = int.Parse(GetConfig().data["Prisao"]);
  161.  
  162. Console.WriteLine();
  163.  
  164. Console.ForegroundColor = ConsoleColor.Green;
  165. log.Info("» Saturn Emulador -> LISTO!! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
  166. Console.ResetColor();
  167. IsLive = true;
  168.  
  169. Console.ForegroundColor = ConsoleColor.DarkCyan;
  170. Console.WriteLine("");
  171. Console.WriteLine(
  172. Console.LargestWindowWidth > 30 ? @"...................................................................................................................... " : @"");
  173. Console.ForegroundColor = ConsoleColor.Gray;
  174.  
  175. }
  176. catch (KeyNotFoundException e)
  177. {
  178. log.ErrorFormat("Verifique o seu arquivo de configuração - alguns valores parecem estar faltando.", ConsoleColor.Red);
  179. log.Error("Pressione qualquer tecla para desligar ...");
  180. ExceptionLogger.LogException(e);
  181. Console.ReadKey(true);
  182. Environment.Exit(1);
  183. return;
  184. }
  185. catch (InvalidOperationException e)
  186. {
  187. log.Error("Falha ao inicializar Saturn Emulador:" + e.Message);
  188. log.Error("Pressione qualquer tecla para desligar ...");
  189. Console.ReadKey(true);
  190. Environment.Exit(1);
  191. return;
  192. }
  193. catch (Exception e)
  194. {
  195. log.Error("Erro fatal durante a inicialização:" + e);
  196. log.Error("Pressione uma tecla para sair");
  197.  
  198. Console.ReadKey();
  199. Environment.Exit(1);
  200. }
  201. }
  202.  
  203. public static bool EnumToBool(string Enum)
  204. {
  205. return (Enum == "1");
  206. }
  207.  
  208. public static string BoolToEnum(bool Bool)
  209. {
  210. return (Bool == true ? "1" : "0");
  211. }
  212.  
  213. public static int GetRandomNumber(int Min, int Max)
  214. {
  215. return RandomNumber.GenerateNewRandom(Min, Max);
  216. }
  217.  
  218. public static string Rainbow()
  219. {
  220. int numColors = 1000;
  221. var colors = new List<string>();
  222. var random = new Random();
  223. for (int i = 0; i < numColors; i++)
  224. {
  225. colors.Add(String.Format("#{0:X2}{1:X2}00", i, random.Next(0x1000000) - i));
  226. }
  227.  
  228. int index = 0;
  229. string rainbow = colors[index];
  230.  
  231. if (index > numColors)
  232. index = 0;
  233. else
  234. index++;
  235.  
  236. return rainbow;
  237. }
  238.  
  239. public static string RainbowT()
  240. {
  241. int numColorst = 1000;
  242. var colorst = new List<string>();
  243. var randomt = new Random();
  244. for (int i = 0; i < numColorst; i++)
  245. {
  246. colorst.Add(String.Format("#{0:X6}", randomt.Next(0x1000000)));
  247. }
  248.  
  249. int indext = 0;
  250. string rainbowt = colorst[indext];
  251.  
  252. if (indext > numColorst)
  253. indext = 0;
  254. else
  255. indext++;
  256.  
  257. return rainbowt;
  258. }
  259.  
  260. public static double GetUnixTimestamp()
  261. {
  262. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  263. return ts.TotalSeconds;
  264. }
  265.  
  266. internal static int GetIUnixTimestamp()
  267. {
  268. var ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  269. var unixTime = ts.TotalSeconds;
  270. return Convert.ToInt32(unixTime);
  271. }
  272.  
  273. private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  274.  
  275. public static long CurrentTimeMillis()
  276. {
  277. return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
  278. }
  279.  
  280.  
  281. public static long Now()
  282. {
  283. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  284. double unixTime = ts.TotalMilliseconds;
  285. return (long)unixTime;
  286. }
  287.  
  288. public static string FilterFigure(string figure)
  289. {
  290. foreach (char character in figure)
  291. {
  292. if (!IsValid(character))
  293. 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";
  294. }
  295.  
  296. return figure;
  297. }
  298.  
  299. private static bool IsValid(char character)
  300. {
  301. return Allowedchars.Contains(character);
  302. }
  303.  
  304. public static bool IsValidAlphaNumeric(string inputStr)
  305. {
  306. inputStr = inputStr.ToLower();
  307. if (string.IsNullOrEmpty(inputStr))
  308. {
  309. return false;
  310. }
  311.  
  312. for (int i = 0; i < inputStr.Length; i++)
  313. {
  314. if (!IsValid(inputStr[i]))
  315. {
  316. return false;
  317. }
  318. }
  319.  
  320. return true;
  321. }
  322.  
  323. public static string GetUsernameById(int UserId)
  324. {
  325. string Name = "Unknown User";
  326.  
  327. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  328. if (Client != null && Client.GetHabbo() != null)
  329. return Client.GetHabbo().Username;
  330.  
  331. UserCache User = GetGame().GetCacheManager().GenerateUser(UserId);
  332. if (User != null)
  333. return User.Username;
  334.  
  335. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  336. {
  337. dbClient.SetQuery("SELECT `username` FROM `users` WHERE id = @id LIMIT 1");
  338. dbClient.AddParameter("id", UserId);
  339. Name = dbClient.getString();
  340. }
  341.  
  342. if (string.IsNullOrEmpty(Name))
  343. Name = "Unknown User";
  344.  
  345. return Name;
  346. }
  347.  
  348. public static bool ShutdownStarted { get; set; }
  349.  
  350. public static Habbo GetHabboById(int UserId)
  351. {
  352. try
  353. {
  354. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  355. if (Client != null)
  356. {
  357. Habbo User = Client.GetHabbo();
  358. if (User != null && User.Id > 0)
  359. {
  360. if (_usersCached.ContainsKey(UserId))
  361. _usersCached.TryRemove(UserId, out User);
  362. return User;
  363. }
  364. }
  365. else
  366. {
  367. try
  368. {
  369. if (_usersCached.ContainsKey(UserId))
  370. return _usersCached[UserId];
  371. else
  372. {
  373. UserData data = UserDataFactory.GetUserData(UserId);
  374. if (data != null)
  375. {
  376. Habbo Generated = data.user;
  377. if (Generated != null)
  378. {
  379. Generated.InitInformation(data);
  380. _usersCached.TryAdd(UserId, Generated);
  381. return Generated;
  382. }
  383. }
  384. }
  385. }
  386. catch { return null; }
  387. }
  388. return null;
  389. }
  390. catch
  391. {
  392. return null;
  393. }
  394. }
  395.  
  396. public static Habbo GetHabboByUsername(String UserName)
  397. {
  398. try
  399. {
  400. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  401. {
  402. dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
  403. dbClient.AddParameter("user", UserName);
  404. int id = dbClient.getInteger();
  405. if (id > 0)
  406. return GetHabboById(Convert.ToInt32(id));
  407. }
  408. return null;
  409. }
  410. catch { return null; }
  411. }
  412.  
  413.  
  414.  
  415. public static void PerformShutDown()
  416. {
  417. PerformShutDown(false);
  418. }
  419.  
  420. public static void PerformRestart()
  421. {
  422. PerformShutDown(true);
  423. using (IQueryAdapter dbClient = _manager.GetQueryReactor())
  424. {
  425. dbClient.runFastQuery("UPDATE `server_status` SET `status` = '1'");
  426. }
  427. }
  428.  
  429. public static void PerformShutDown(bool restart)
  430. {
  431. Console.Clear();
  432. log.Info("Desligando o servidor...");
  433. Console.Title = "Saturn Emulador: DESLIGANDO!";
  434.  
  435. ShutdownStarted = true;
  436.  
  437. GetGame().GetClientManager().SendMessage(new BroadcastMessageAlertComposer(GetGame().GetLanguageManager().TryGetValue("server.shutdown.message")));
  438. GetGame().StopGameLoop();
  439. System.Threading.Thread.Sleep(2500);
  440. GetConnectionManager().Destroy();//Stop listening.
  441. GetGame().GetPacketManager().UnregisterAll();//Unregister the packets.
  442. GetGame().GetPacketManager().WaitForAllToComplete();
  443. GetGame().GetClientManager().CloseAll();//Close all connections
  444. GetGame().GetRoomManager().Dispose();//Stop the game loop.
  445.  
  446. GetConnectionManager().Destroy();
  447.  
  448. using (IQueryAdapter dbClient = _manager.GetQueryReactor())
  449. {
  450. dbClient.runFastQuery("TRUNCATE `catalog_marketplace_data`");
  451. dbClient.runFastQuery("UPDATE `users` SET online = '0', `auth_ticket` = NULL");
  452. dbClient.runFastQuery("UPDATE `rooms` SET `users_now` = '0'");
  453. }
  454.  
  455. _connectionManager.Destroy();
  456. _game.Destroy();
  457.  
  458. log.Info("Saturn Emulador foi desligado com exito.");
  459.  
  460. if (!restart)
  461. log.WarnFormat("Desligado Completo. Presione una tecla para continuar...", ConsoleColor.DarkCyan);
  462.  
  463. if (!restart)
  464. Console.ReadKey();
  465.  
  466. IsLive = false;
  467.  
  468. if (restart)
  469. Process.Start(Assembly.GetEntryAssembly().Location);
  470.  
  471. if (restart)
  472. Console.WriteLine("Reiniciando...");
  473. else
  474. Console.WriteLine("Finalizando...");
  475.  
  476. System.Threading.Thread.Sleep(1000);
  477. Environment.Exit(0);
  478. }
  479.  
  480. public static ConfigurationData GetConfig()
  481. {
  482. return _configuration;
  483. }
  484.  
  485. public static Encoding GetDefaultEncoding()
  486. {
  487. return _defaultEncoding;
  488. }
  489.  
  490. public static ConnectionHandling GetConnectionManager()
  491. {
  492. return _connectionManager;
  493. }
  494.  
  495. public static Game GetGame()
  496. {
  497. return _game;
  498. }
  499.  
  500. public static RCONSocket GetRCONSocket()
  501. {
  502. return _rcon;
  503. }
  504.  
  505. public static DatabaseManager GetDatabaseManager()
  506. {
  507. return _manager;
  508. }
  509.  
  510. public static ICollection<Habbo> GetUsersCached()
  511. {
  512. return _usersCached.Values;
  513. }
  514.  
  515. public static bool RemoveFromCache(int Id, out Habbo Data)
  516. {
  517. return _usersCached.TryRemove(Id, out Data);
  518. }
  519. }
  520. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement