Advertisement
Guest User

Untitled

a guest
Feb 6th, 2018
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.42 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MinecraftClient.Protocol;
  6. using System.Reflection;
  7. using System.Threading;
  8. using MinecraftClient.Protocol.Handlers.Forge;
  9. using MinecraftClient.Protocol.SessionCache;
  10.  
  11. namespace MinecraftClient
  12. {
  13. /// <summary>
  14. /// Minecraft Console Client by ORelio and Contributors (c) 2012-2017.
  15. /// Allows to connect to any Minecraft server, send and receive text, automated scripts.
  16. /// This source code is released under the CDDL 1.0 License.
  17. /// </summary>
  18.  
  19. public class Program
  20. {
  21. private static McTcpClient Client;
  22. public static string[] startupargs;
  23.  
  24. public const string Version = "1.12.2 DEV";
  25. public const string MCLowestVersion = "1.4.6";
  26. public const string MCHighestVersion = "1.12.2";
  27.  
  28. private static Thread offlinePrompt = null;
  29. private static bool useMcVersionOnce = false;
  30.  
  31. /// <summary>
  32. /// The main entry point of Minecraft Console Client
  33. /// </summary>
  34. /// <summary>
  35. /// The main entry point of Minecraft Console Client
  36. /// </summary>
  37.  
  38. private static void Main(string[] args)
  39. {
  40.  
  41. Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);
  42.  
  43. //Debug input ?
  44. if (args.Length == 1 && args[0] == "--keyboard-debug")
  45. {
  46. Console.WriteLine("Keyboard debug mode: Press any key to display info");
  47. ConsoleIO.DebugReadInput();
  48. }
  49.  
  50. //Basic Input/Output ?
  51. if (args.Length >= 1 && args[args.Length - 1] == "BasicIO")
  52. {
  53. ConsoleIO.basicIO = true;
  54. args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
  55. }
  56. Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
  57.  
  58. //Process ini configuration file
  59. if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
  60. {
  61. Settings.LoadSettings(args[0]);
  62.  
  63. //remove ini configuration file from arguments array
  64. List<string> args_tmp = args.ToList<string>();
  65. args_tmp.RemoveAt(0);
  66. args = args_tmp.ToArray();
  67. }
  68. else if (System.IO.File.Exists("MinecraftClient.ini"))
  69. {
  70. Settings.LoadSettings("MinecraftClient.ini");
  71. }
  72. else Settings.WriteDefaultSettings("MinecraftClient.ini");
  73.  
  74. //Other command-line arguments
  75. if (args.Length >= 1)
  76. {
  77. Settings.Login = args[0];
  78. if (args.Length >= 2)
  79. {
  80. Settings.Password = args[1];
  81. if (args.Length >= 3)
  82. {
  83. Settings.SetServerIP(args[2]);
  84.  
  85. //Single command?
  86. if (args.Length >= 4)
  87. {
  88. Settings.SingleCommand = args[3];
  89. }
  90. }
  91. }
  92. }
  93.  
  94. if (Settings.ConsoleTitle != "")
  95. {
  96. Settings.Username = "New Window";
  97. Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
  98. }
  99.  
  100. //Load cached sessions from disk if necessary
  101. if (Settings.SessionCaching == CacheType.Disk)
  102. {
  103. bool cacheLoaded = SessionCache.InitializeDiskCache();
  104. if (Settings.DebugMessages)
  105. ConsoleIO.WriteLineFormatted(cacheLoaded ? "§8Session cache has been successfully loaded from disk." : "§8Cached sessions could not be loaded from disk");
  106. }
  107.  
  108. //Asking the user to type in missing data such as Username and Password
  109.  
  110. if (Settings.Login == "")
  111. {
  112. Console.Write(ConsoleIO.basicIO ? "Please type the username or email of your choice.\n" : "Login : ");
  113. Settings.Login = Console.ReadLine();
  114. }
  115. if (Settings.Password == "" && (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())))
  116. {
  117. RequestPassword();
  118. }
  119.  
  120. startupargs = args;
  121. new Thread(() =>
  122. {
  123. Thread.CurrentThread.IsBackground = true;
  124. /* run your code here */
  125. ConsoleIO.WriteLine("Starting Discord");
  126. DiscordBot bot = new DiscordBot();
  127. bot.RunBotAsync().GetAwaiter().GetResult();
  128.  
  129. }).Start();
  130. startupargs = args;
  131. InitializeClient();
  132.  
  133. }
  134.  
  135. /// <summary>
  136. /// Reduest user to submit password.
  137. /// </summary>
  138. private static void RequestPassword()
  139. {
  140. Console.Write(ConsoleIO.basicIO ? "Please type the password for " + Settings.Login + ".\n" : "Password : ");
  141. Settings.Password = ConsoleIO.basicIO ? Console.ReadLine() : ConsoleIO.ReadPassword();
  142. if (Settings.Password == "") { Settings.Password = "-"; }
  143. if (!ConsoleIO.basicIO)
  144. {
  145. //Hide password length
  146. Console.CursorTop--; Console.Write("Password : <******>");
  147. for (int i = 19; i < Console.BufferWidth; i++) { Console.Write(' '); }
  148. }
  149. }
  150.  
  151. /// <summary>
  152. /// Start a new Client
  153. /// </summary>
  154. private static void InitializeClient()
  155. {
  156. SessionToken session = new SessionToken();
  157.  
  158. ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;
  159.  
  160. if (Settings.Password == "-")
  161. {
  162. ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode.");
  163. result = ProtocolHandler.LoginResult.Success;
  164. session.PlayerID = "0";
  165. session.PlayerName = Settings.Login;
  166. }
  167. else
  168. {
  169. // Validate cached session or login new session.
  170. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower()))
  171. {
  172. session = SessionCache.Get(Settings.Login.ToLower());
  173. result = ProtocolHandler.GetTokenValidation(session);
  174. if (result != ProtocolHandler.LoginResult.Success)
  175. {
  176. ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired.");
  177. if (Settings.Password == "")
  178. RequestPassword();
  179. }
  180. else ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.');
  181. }
  182.  
  183. if (result != ProtocolHandler.LoginResult.Success)
  184. {
  185. Console.WriteLine("Connecting to Minecraft.net...");
  186. result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session);
  187.  
  188. if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None)
  189. {
  190. SessionCache.Store(Settings.Login.ToLower(), session);
  191. }
  192. }
  193.  
  194. }
  195.  
  196. if (result == ProtocolHandler.LoginResult.Success)
  197. {
  198. Settings.Username = session.PlayerName;
  199.  
  200. if (Settings.ConsoleTitle != "")
  201. Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
  202.  
  203. if (Settings.playerHeadAsIcon)
  204. ConsoleIcon.setPlayerIconAsync(Settings.Username);
  205.  
  206. if (Settings.DebugMessages)
  207. Console.WriteLine("Success. (session ID: " + session.ID + ')');
  208.  
  209. //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE
  210.  
  211. if (Settings.ServerIP == "")
  212. {
  213. Console.Write("Server IP : ");
  214. Settings.SetServerIP(Console.ReadLine());
  215. }
  216.  
  217. //Get server version
  218. int protocolversion = 0;
  219. ForgeInfo forgeInfo = null;
  220.  
  221. if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
  222. {
  223. protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);
  224.  
  225. if (protocolversion != 0)
  226. {
  227. ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')');
  228. }
  229. else ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode.");
  230.  
  231. if (useMcVersionOnce)
  232. {
  233. useMcVersionOnce = false;
  234. Settings.ServerVersion = "";
  235. }
  236. }
  237.  
  238. if (protocolversion == 0)
  239. {
  240. Console.WriteLine("Retrieving Server Info...");
  241. if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
  242. {
  243. HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
  244. return;
  245. }
  246. }
  247.  
  248. if (protocolversion != 0)
  249. {
  250. try
  251. {
  252. //Start the main TCP client
  253. if (Settings.SingleCommand != "")
  254. {
  255. Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
  256. }
  257. else Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
  258.  
  259. //Update console title
  260. if (Settings.ConsoleTitle != "")
  261. Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
  262. }
  263. catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); }
  264. }
  265. else HandleFailure("Failed to determine server version.", true);
  266. }
  267. else
  268. {
  269. Console.ForegroundColor = ConsoleColor.Gray;
  270. string failureMessage = "Minecraft Login failed : ";
  271. switch (result)
  272. {
  273. case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break;
  274. case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break;
  275. case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password."; break;
  276. case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break;
  277. case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break;
  278. case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break;
  279. default: failureMessage += "Unknown Error."; break;
  280. }
  281. if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
  282. {
  283. ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program."
  284. + '\n' + "The first time, you have to import HTTPS certificates using:"
  285. + '\n' + "mozroots --import --ask-remove");
  286. return;
  287. }
  288. HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
  289. }
  290. }
  291.  
  292. /// <summary>
  293. /// Disconnect the current client from the server and restart it
  294. /// </summary>
  295. /// <param name="delay">Optional delay, in seconds, before restarting</param>
  296. public static void Restart(int delaySeconds = 0)
  297. {
  298. new Thread(new ThreadStart(delegate
  299. {
  300. if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); }
  301. if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); }
  302. if (delaySeconds > 0)
  303. {
  304. Console.WriteLine("Waiting " + delaySeconds + " seconds before restarting...");
  305. System.Threading.Thread.Sleep(delaySeconds * 1000);
  306. }
  307. Console.WriteLine("Restarting Minecraft Console Client...");
  308. InitializeClient();
  309. })).Start();
  310. }
  311.  
  312. /// <summary>
  313. /// Disconnect the current client from the server and exit the app
  314. /// </summary>
  315. public static void Exit()
  316. {
  317. new Thread(new ThreadStart(delegate
  318. {
  319. if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); }
  320. if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); }
  321. if (Settings.playerHeadAsIcon) { ConsoleIcon.revertToCMDIcon(); }
  322. Environment.Exit(0);
  323. })).Start();
  324. }
  325.  
  326. /// <summary>
  327. /// Handle fatal errors such as ping failure, login failure, server disconnection, and so on.
  328. /// Allows AutoRelog to perform on fatal errors, prompt for server version, and offline commands.
  329. /// </summary>
  330. /// <param name="errorMessage">Error message to display and optionally pass to AutoRelog bot</param>
  331. /// <param name="versionError">Specify if the error is related to an incompatible or unkown server version</param>
  332. /// <param name="disconnectReason">If set, the error message will be processed by the AutoRelog bot</param>
  333. public static void HandleFailure(string errorMessage = null, bool versionError = false, ChatBots.AutoRelog.DisconnectReason? disconnectReason = null)
  334. {
  335. if (!String.IsNullOrEmpty(errorMessage))
  336. {
  337. ConsoleIO.Reset();
  338. while (Console.KeyAvailable)
  339. Console.ReadKey(true);
  340. Console.WriteLine(errorMessage);
  341.  
  342. if (disconnectReason.HasValue)
  343. {
  344. if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage))
  345. return; //AutoRelog is triggering a restart of the client
  346. }
  347. }
  348.  
  349. if (Settings.interactiveMode)
  350. {
  351. if (versionError)
  352. {
  353. Console.Write("Server version : ");
  354. Settings.ServerVersion = Console.ReadLine();
  355. if (Settings.ServerVersion != "")
  356. {
  357. useMcVersionOnce = true;
  358. Restart();
  359. return;
  360. }
  361. }
  362.  
  363. if (offlinePrompt == null)
  364. {
  365. offlinePrompt = new Thread(new ThreadStart(delegate
  366. {
  367. string command = " ";
  368. ConsoleIO.WriteLineFormatted("Not connected to any server. Use '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "help' for help.");
  369. ConsoleIO.WriteLineFormatted("Or press Enter to exit Minecraft Console Client.");
  370. while (command.Length > 0)
  371. {
  372. if (!ConsoleIO.basicIO) { ConsoleIO.Write('>'); }
  373. command = ConsoleIO.ReadLine().Trim();
  374. if (command.Length > 0)
  375. {
  376. string message = "";
  377.  
  378. if (Settings.internalCmdChar != ' '
  379. && command[0] == Settings.internalCmdChar)
  380. command = command.Substring(1);
  381.  
  382. if (command.StartsWith("reco"))
  383. {
  384. message = new Commands.Reco().Run(null, Settings.ExpandVars(command));
  385. }
  386. else if (command.StartsWith("connect"))
  387. {
  388. message = new Commands.Connect().Run(null, Settings.ExpandVars(command));
  389. }
  390. else if (command.StartsWith("exit") || command.StartsWith("quit"))
  391. {
  392. message = new Commands.Exit().Run(null, Settings.ExpandVars(command));
  393. }
  394. else if (command.StartsWith("help"))
  395. {
  396. ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Reco().CMDDesc);
  397. ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Connect().CMDDesc);
  398. }
  399. else ConsoleIO.WriteLineFormatted("§8Unknown command '" + command.Split(' ')[0] + "'.");
  400.  
  401. if (message != "")
  402. ConsoleIO.WriteLineFormatted("§8MCC: " + message);
  403. }
  404. }
  405. }));
  406. offlinePrompt.Start();
  407. }
  408. }
  409. else Exit();
  410. }
  411.  
  412. /// <summary>
  413. /// Detect if the user is running Minecraft Console Client through Mono
  414. /// </summary>
  415. public static bool isUsingMono
  416. {
  417. get
  418. {
  419. return Type.GetType("Mono.Runtime") != null;
  420. }
  421. }
  422.  
  423. /// <summary>
  424. /// Enumerate types in namespace through reflection
  425. /// </summary>
  426. /// <param name="nameSpace">Namespace to process</param>
  427. /// <param name="assembly">Assembly to use. Default is Assembly.GetExecutingAssembly()</param>
  428. /// <returns></returns>
  429. public static Type[] GetTypesInNamespace(string nameSpace, Assembly assembly = null)
  430. {
  431. if (assembly == null) { assembly = Assembly.GetExecutingAssembly(); }
  432. return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
  433. }
  434. }
  435. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement