Updated docs and cleaned up.

This commit is contained in:
Justin Slauson 2016-03-02 18:16:19 -07:00
parent 57c53be09f
commit fec1687cb7
3 changed files with 563 additions and 557 deletions

View file

@ -1,139 +1,149 @@
using MinecraftClient.Protocol; using MinecraftClient.Protocol;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Runtime.Serialization;
using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography; namespace MinecraftClient.Cache
using System.Text; {
/// <summary>
namespace MinecraftClient.Cache /// Handle sessions caching and storage.
{ /// </summary>
public static class SessionCache
{ public static class SessionCache
const string filename = "cache.bin"; {
private static Dictionary<string, SessionToken> sessions = new Dictionary<string, SessionToken>(); const string filename = "cache.bin";
private static FileSystemWatcher cachemonitor = new FileSystemWatcher(); private static Dictionary<string, SessionToken> sessions = new Dictionary<string, SessionToken>();
private static FileSystemWatcher cachemonitor = new FileSystemWatcher();
private static BinaryFormatter formatter = new BinaryFormatter();
private static BinaryFormatter formatter = new BinaryFormatter();
public static bool Contains(string login)
{ /// <summary>
return sessions.ContainsKey(login); /// Retrieve whether SessionCache contains a session for the given login.
} /// </summary>
/// <param name="login">User login used with Minecraft.net</param>
public static void Store(string login, SessionToken session) /// <returns>TRUE if session is available</returns>
{
if (Contains(login)) public static bool Contains(string login)
{ {
sessions[login] = session; return sessions.ContainsKey(login);
} }
else
{ /// <summary>
sessions.Add(login, session); /// Store a session and save it to disk if required.
} /// </summary>
/// <param name="login">User login used with Minecraft.net</param>
if (Settings.CacheType == CacheType.DISK) /// <param name="session">User session token used with Minecraft.net</param>
{
SaveToDisk(); public static void Store(string login, SessionToken session)
} {
} if (Contains(login))
{
public static SessionToken Get(string login) sessions[login] = session;
{ }
return sessions[login]; else
} {
sessions.Add(login, session);
public static bool LoadFromDisk() }
{
cachemonitor.Path = AppDomain.CurrentDomain.BaseDirectory; if (Settings.CacheType == CacheType.DISK)
cachemonitor.IncludeSubdirectories = false; {
cachemonitor.Filter = filename; SaveToDisk();
cachemonitor.NotifyFilter = NotifyFilters.LastWrite; }
cachemonitor.Changed += new FileSystemEventHandler(OnChanged); }
cachemonitor.EnableRaisingEvents = true;
/// <summary>
return ReadCacheFile(); /// Retrieve a session token for the given login.
} /// </summary>
/// <param name="login">User login used with Minecraft.net</param>
public static void OnChanged(object source, FileSystemEventArgs e) /// <returns>SessionToken for given login</returns>
{
ReadCacheFile(); public static SessionToken Get(string login)
} {
return sessions[login];
private static bool ReadCacheFile() }
{
if (File.Exists(filename)) /// <summary>
{ /// Initialize cache monitoring to keep cache updated with external changes.
try /// </summary>
{ /// <returns>TRUE if session tokens are seeded from file</returns>
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{ public static bool InitializeDiskCache()
sessions = (Dictionary<string, SessionToken>)formatter.Deserialize(fs); {
return true; cachemonitor.Path = AppDomain.CurrentDomain.BaseDirectory;
} cachemonitor.IncludeSubdirectories = false;
} cachemonitor.Filter = filename;
catch (IOException ex) cachemonitor.NotifyFilter = NotifyFilters.LastWrite;
{ cachemonitor.Changed += new FileSystemEventHandler(OnChanged);
Console.WriteLine("Error reading cached sessions from disk: " + ex.Message); cachemonitor.EnableRaisingEvents = true;
}
catch (SerializationException) return LoadFromDisk();
{ }
Console.WriteLine("Error getting sessions from cache file ");
} /// <summary>
} /// Reloads cache on external cache file change.
return false; /// </summary>
} /// <param name="source">Sender</param>
/// <param name="e">Event data</param>
public static void SaveToDisk()
{ private static void OnChanged(object source, FileSystemEventArgs e)
bool fileexists = File.Exists(filename); {
LoadFromDisk();
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) }
{
cachemonitor.EnableRaisingEvents = false; /// <summary>
if (fileexists) /// Reads cache file and loads SessionTokens into SessionCache.
{ /// </summary>
fs.SetLength(0); /// <returns>True if data is successfully loaded</returns>
fs.Flush();
} private static bool LoadFromDisk()
{
formatter.Serialize(fs, sessions); if (File.Exists(filename))
cachemonitor.EnableRaisingEvents = true; {
} try
{
} using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
private static byte[] GetHash(FileStream fs, bool resetposition = true) sessions = (Dictionary<string, SessionToken>)formatter.Deserialize(fs);
{ return true;
using (var md5 = MD5.Create()) }
{ }
long pos = fs.Position; catch (IOException ex)
byte[] hash = md5.ComputeHash(fs); {
Console.WriteLine("Error reading cached sessions from disk: " + ex.Message);
fs.Position = resetposition ? pos : fs.Position; }
return hash; catch (SerializationException)
} {
} Console.WriteLine("Malformed sessions from cache file ");
}
private static bool HashesEqual(byte[] hash1, byte[] hash2) }
{ return false;
if (hash1.Length != hash2.Length) }
{
return false; /// <summary>
} /// Saves SessionToken's from SessionCache into cache file.
/// </summary>
for (int i = 0; i < hash1.Length; i++)
{ private static void SaveToDisk()
if (hash1[i] != hash2[i]) {
{ bool fileexists = File.Exists(filename);
return false;
} using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
} {
cachemonitor.EnableRaisingEvents = false;
return true;
} // delete existing file contents
if (fileexists)
} {
} fs.SetLength(0);
fs.Flush();
}
formatter.Serialize(fs, sessions);
cachemonitor.EnableRaisingEvents = true;
}
}
}
}

View file

@ -1,414 +1,414 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using MinecraftClient.Protocol; using MinecraftClient.Protocol;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
using MinecraftClient.Protocol.Handlers.Forge; using MinecraftClient.Protocol.Handlers.Forge;
namespace MinecraftClient namespace MinecraftClient
{ {
/// <summary> /// <summary>
/// Minecraft Console Client by ORelio (c) 2012-2014. /// Minecraft Console Client by ORelio (c) 2012-2014.
/// Allows to connect to any Minecraft server, send and receive text, automated scripts. /// Allows to connect to any Minecraft server, send and receive text, automated scripts.
/// This source code is released under the CDDL 1.0 License. /// This source code is released under the CDDL 1.0 License.
/// </summary> /// </summary>
static class Program static class Program
{ {
private static McTcpClient Client; private static McTcpClient Client;
public static string[] startupargs; public static string[] startupargs;
public const string Version = "1.8.2"; public const string Version = "1.8.2";
public const string MCLowestVersion = "1.4.6"; public const string MCLowestVersion = "1.4.6";
public const string MCHighestVersion = "1.8.8"; public const string MCHighestVersion = "1.8.8";
private static Thread offlinePrompt = null; private static Thread offlinePrompt = null;
private static bool useMcVersionOnce = false; private static bool useMcVersionOnce = false;
/// <summary> /// <summary>
/// The main entry point of Minecraft Console Client /// The main entry point of Minecraft Console Client
/// </summary> /// </summary>
static void Main(string[] args) static void Main(string[] args)
{ {
Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version); Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);
//Basic Input/Output ? //Basic Input/Output ?
if (args.Length >= 1 && args[args.Length - 1] == "BasicIO") if (args.Length >= 1 && args[args.Length - 1] == "BasicIO")
{ {
ConsoleIO.basicIO = true; ConsoleIO.basicIO = true;
Console.OutputEncoding = Console.InputEncoding = Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage); Console.OutputEncoding = Console.InputEncoding = Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray(); args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
} }
//Process ini configuration file //Process ini configuration file
if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini") if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
{ {
Settings.LoadSettings(args[0]); Settings.LoadSettings(args[0]);
//remove ini configuration file from arguments array //remove ini configuration file from arguments array
List<string> args_tmp = args.ToList<string>(); List<string> args_tmp = args.ToList<string>();
args_tmp.RemoveAt(0); args_tmp.RemoveAt(0);
args = args_tmp.ToArray(); args = args_tmp.ToArray();
} }
else if (System.IO.File.Exists("MinecraftClient.ini")) else if (System.IO.File.Exists("MinecraftClient.ini"))
{ {
Settings.LoadSettings("MinecraftClient.ini"); Settings.LoadSettings("MinecraftClient.ini");
} }
else Settings.WriteDefaultSettings("MinecraftClient.ini"); else Settings.WriteDefaultSettings("MinecraftClient.ini");
//Other command-line arguments //Other command-line arguments
if (args.Length >= 1) if (args.Length >= 1)
{ {
Settings.Login = args[0]; Settings.Login = args[0];
if (args.Length >= 2) if (args.Length >= 2)
{ {
Settings.Password = args[1]; Settings.Password = args[1];
if (args.Length >= 3) if (args.Length >= 3)
{ {
Settings.SetServerIP(args[2]); Settings.SetServerIP(args[2]);
//Single command? //Single command?
if (args.Length >= 4) if (args.Length >= 4)
{ {
Settings.SingleCommand = args[3]; Settings.SingleCommand = args[3];
} }
} }
} }
} }
if (Settings.ConsoleTitle != "") if (Settings.ConsoleTitle != "")
{ {
Settings.Username = "New Window"; Settings.Username = "New Window";
Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
} }
//Load cached sessions from disk if necessary //Load cached sessions from disk if necessary
if (Settings.CacheType == Cache.CacheType.DISK) if (Settings.CacheType == Cache.CacheType.DISK)
{ {
ConsoleIO.WriteLineFormatted(Cache.SessionCache.LoadFromDisk() ? "Cached sessions loaded." : "§8Cached sessions could not be loaded from disk"); Console.WriteLine(Cache.SessionCache.InitializeDiskCache() ? "Cached sessions loaded." : "§8Cached sessions could not be loaded from disk");
} }
//Asking the user to type in missing data such as Username and Password //Asking the user to type in missing data such as Username and Password
if (Settings.Login == "") if (Settings.Login == "")
{ {
Console.Write(ConsoleIO.basicIO ? "Please type the username of your choice.\n" : "Username : "); Console.Write(ConsoleIO.basicIO ? "Please type the username of your choice.\n" : "Username : ");
Settings.Login = Console.ReadLine(); Settings.Login = Console.ReadLine();
} }
if (Settings.Password == "" && (Settings.CacheType == Cache.CacheType.NONE || !Cache.SessionCache.Contains(Settings.Login))) if (Settings.Password == "" && (Settings.CacheType == Cache.CacheType.NONE || !Cache.SessionCache.Contains(Settings.Login)))
{ {
RequestPassword(); RequestPassword();
} }
startupargs = args; startupargs = args;
InitializeClient(); InitializeClient();
} }
/// <summary> /// <summary>
/// Reduest user to submit password. /// Reduest user to submit password.
/// </summary> /// </summary>
private static void RequestPassword() private static void RequestPassword()
{ {
Console.Write(ConsoleIO.basicIO ? "Please type the password for " + Settings.Login + ".\n" : "Password : "); Console.Write(ConsoleIO.basicIO ? "Please type the password for " + Settings.Login + ".\n" : "Password : ");
Settings.Password = ConsoleIO.basicIO ? Console.ReadLine() : ConsoleIO.ReadPassword(); Settings.Password = ConsoleIO.basicIO ? Console.ReadLine() : ConsoleIO.ReadPassword();
if (Settings.Password == "") { Settings.Password = "-"; } if (Settings.Password == "") { Settings.Password = "-"; }
if (!ConsoleIO.basicIO) if (!ConsoleIO.basicIO)
{ {
//Hide password length //Hide password length
Console.CursorTop--; Console.Write("Password : <******>"); Console.CursorTop--; Console.Write("Password : <******>");
for (int i = 19; i < Console.BufferWidth; i++) { Console.Write(' '); } for (int i = 19; i < Console.BufferWidth; i++) { Console.Write(' '); }
} }
} }
/// <summary> /// <summary>
/// Start a new Client /// Start a new Client
/// </summary> /// </summary>
private static void InitializeClient() private static void InitializeClient()
{ {
SessionToken session = new SessionToken(); SessionToken session = new SessionToken();
ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;
if (Settings.Password == "-") if (Settings.Password == "-")
{ {
ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode."); ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode.");
result = ProtocolHandler.LoginResult.Success; result = ProtocolHandler.LoginResult.Success;
session.PlayerID = "0"; session.PlayerID = "0";
session.PlayerName = Settings.Login; session.PlayerName = Settings.Login;
} }
else else
{ {
// Validate cached session or login new session. // Validate cached session or login new session.
if (Settings.CacheType != Cache.CacheType.NONE && Cache.SessionCache.Contains(Settings.Login)) if (Settings.CacheType != Cache.CacheType.NONE && Cache.SessionCache.Contains(Settings.Login))
{ {
session = Cache.SessionCache.Get(Settings.Login); session = Cache.SessionCache.Get(Settings.Login);
result = ProtocolHandler.GetTokenValidation(session); result = ProtocolHandler.GetTokenValidation(session);
if (result != ProtocolHandler.LoginResult.Success && Settings.Password == "") if (result != ProtocolHandler.LoginResult.Success && Settings.Password == "")
{ {
RequestPassword(); RequestPassword();
} }
Console.WriteLine("Cached session is " + (result == ProtocolHandler.LoginResult.Success ? "valid." : "invalid.")); Console.WriteLine("Cached session is " + (result == ProtocolHandler.LoginResult.Success ? "valid." : "invalid."));
} }
if (result != ProtocolHandler.LoginResult.Success) if (result != ProtocolHandler.LoginResult.Success)
{ {
Console.WriteLine("Connecting to Minecraft.net..."); Console.WriteLine("Connecting to Minecraft.net...");
result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session);
if (result == ProtocolHandler.LoginResult.Success && Settings.CacheType != Cache.CacheType.NONE) if (result == ProtocolHandler.LoginResult.Success && Settings.CacheType != Cache.CacheType.NONE)
{ {
Cache.SessionCache.Store(Settings.Login, session); Cache.SessionCache.Store(Settings.Login, session);
} }
} }
} }
if (result == ProtocolHandler.LoginResult.Success) if (result == ProtocolHandler.LoginResult.Success)
{ {
Settings.Username = session.PlayerName; Settings.Username = session.PlayerName;
if (Settings.ConsoleTitle != "") if (Settings.ConsoleTitle != "")
Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
if (Settings.playerHeadAsIcon) if (Settings.playerHeadAsIcon)
ConsoleIcon.setPlayerIconAsync(Settings.Username); ConsoleIcon.setPlayerIconAsync(Settings.Username);
Console.WriteLine("Success. (session ID: " + session.ID + ')'); Console.WriteLine("Success. (session ID: " + session.ID + ')');
//ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE
if (Settings.ServerIP == "") if (Settings.ServerIP == "")
{ {
Console.Write("Server IP : "); Console.Write("Server IP : ");
Settings.SetServerIP(Console.ReadLine()); Settings.SetServerIP(Console.ReadLine());
} }
//Get server version //Get server version
int protocolversion = 0; int protocolversion = 0;
ForgeInfo forgeInfo = null; ForgeInfo forgeInfo = null;
if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
{ {
protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);
if (protocolversion != 0) if (protocolversion != 0)
{ {
ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')'); ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')');
} }
else ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode."); else ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode.");
if (useMcVersionOnce) if (useMcVersionOnce)
{ {
useMcVersionOnce = false; useMcVersionOnce = false;
Settings.ServerVersion = ""; Settings.ServerVersion = "";
} }
} }
if (protocolversion == 0) if (protocolversion == 0)
{ {
Console.WriteLine("Retrieving Server Info..."); Console.WriteLine("Retrieving Server Info...");
if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
{ {
HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
return; return;
} }
} }
if (forgeInfo != null && !forgeInfo.Mods.Any()) if (forgeInfo != null && !forgeInfo.Mods.Any())
{ {
forgeInfo = null; forgeInfo = null;
} }
if (protocolversion != 0) if (protocolversion != 0)
{ {
try try
{ {
//Start the main TCP client //Start the main TCP client
if (Settings.SingleCommand != "") if (Settings.SingleCommand != "")
{ {
Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand); Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
} }
else Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort); else Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
//Update console title //Update console title
if (Settings.ConsoleTitle != "") if (Settings.ConsoleTitle != "")
Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
} }
catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); } catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); }
} }
else HandleFailure("Failed to determine server version.", true); else HandleFailure("Failed to determine server version.", true);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
string failureMessage = "Minecraft Login failed : "; string failureMessage = "Minecraft Login failed : ";
switch (result) switch (result)
{ {
case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break; case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break;
case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break; case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break;
case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password."; break; case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password."; break;
case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break; case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break;
case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break; case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break;
case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break; case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break;
default: failureMessage += "Unknown Error."; break; default: failureMessage += "Unknown Error."; break;
} }
if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
{ {
ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program." ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program."
+ '\n' + "The first time, you have to import HTTPS certificates using:" + '\n' + "The first time, you have to import HTTPS certificates using:"
+ '\n' + "mozroots --import --ask-remove"); + '\n' + "mozroots --import --ask-remove");
return; return;
} }
HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
} }
} }
/// <summary> /// <summary>
/// Disconnect the current client from the server and restart it /// Disconnect the current client from the server and restart it
/// </summary> /// </summary>
public static void Restart() public static void Restart()
{ {
new Thread(new ThreadStart(delegate new Thread(new ThreadStart(delegate
{ {
if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); } if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); }
if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); } if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); }
Console.WriteLine("Restarting Minecraft Console Client..."); Console.WriteLine("Restarting Minecraft Console Client...");
InitializeClient(); InitializeClient();
})).Start(); })).Start();
} }
/// <summary> /// <summary>
/// Disconnect the current client from the server and exit the app /// Disconnect the current client from the server and exit the app
/// </summary> /// </summary>
public static void Exit() public static void Exit()
{ {
new Thread(new ThreadStart(delegate new Thread(new ThreadStart(delegate
{ {
if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); } if (Client != null) { Client.Disconnect(); ConsoleIO.Reset(); }
if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); } if (offlinePrompt != null) { offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset(); }
if (Settings.playerHeadAsIcon) { ConsoleIcon.revertToCMDIcon(); } if (Settings.playerHeadAsIcon) { ConsoleIcon.revertToCMDIcon(); }
Environment.Exit(0); Environment.Exit(0);
})).Start(); })).Start();
} }
/// <summary> /// <summary>
/// Handle fatal errors such as ping failure, login failure, server disconnection, and so on. /// Handle fatal errors such as ping failure, login failure, server disconnection, and so on.
/// Allows AutoRelog to perform on fatal errors, prompt for server version, and offline commands. /// Allows AutoRelog to perform on fatal errors, prompt for server version, and offline commands.
/// </summary> /// </summary>
/// <param name="errorMessage">Error message to display and optionally pass to AutoRelog bot</param> /// <param name="errorMessage">Error message to display and optionally pass to AutoRelog bot</param>
/// <param name="versionError">Specify if the error is related to an incompatible or unkown server version</param> /// <param name="versionError">Specify if the error is related to an incompatible or unkown server version</param>
/// <param name="disconnectReason">If set, the error message will be processed by the AutoRelog bot</param> /// <param name="disconnectReason">If set, the error message will be processed by the AutoRelog bot</param>
public static void HandleFailure(string errorMessage = null, bool versionError = false, ChatBots.AutoRelog.DisconnectReason? disconnectReason = null) public static void HandleFailure(string errorMessage = null, bool versionError = false, ChatBots.AutoRelog.DisconnectReason? disconnectReason = null)
{ {
if (!String.IsNullOrEmpty(errorMessage)) if (!String.IsNullOrEmpty(errorMessage))
{ {
ConsoleIO.Reset(); ConsoleIO.Reset();
while (Console.KeyAvailable) while (Console.KeyAvailable)
Console.ReadKey(true); Console.ReadKey(true);
Console.WriteLine(errorMessage); Console.WriteLine(errorMessage);
if (disconnectReason.HasValue) if (disconnectReason.HasValue)
{ {
if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage)) if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage))
return; //AutoRelog is triggering a restart of the client return; //AutoRelog is triggering a restart of the client
} }
} }
if (Settings.interactiveMode) if (Settings.interactiveMode)
{ {
if (versionError) if (versionError)
{ {
Console.Write("Server version : "); Console.Write("Server version : ");
Settings.ServerVersion = Console.ReadLine(); Settings.ServerVersion = Console.ReadLine();
if (Settings.ServerVersion != "") if (Settings.ServerVersion != "")
{ {
useMcVersionOnce = true; useMcVersionOnce = true;
Restart(); Restart();
return; return;
} }
} }
if (offlinePrompt == null) if (offlinePrompt == null)
{ {
offlinePrompt = new Thread(new ThreadStart(delegate offlinePrompt = new Thread(new ThreadStart(delegate
{ {
string command = " "; string command = " ";
ConsoleIO.WriteLineFormatted("Not connected to any server. Use '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "help' for help."); ConsoleIO.WriteLineFormatted("Not connected to any server. Use '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "help' for help.");
ConsoleIO.WriteLineFormatted("Or press Enter to exit Minecraft Console Client."); ConsoleIO.WriteLineFormatted("Or press Enter to exit Minecraft Console Client.");
while (command.Length > 0) while (command.Length > 0)
{ {
if (!ConsoleIO.basicIO) { ConsoleIO.Write('>'); } if (!ConsoleIO.basicIO) { ConsoleIO.Write('>'); }
command = Console.ReadLine().Trim(); command = Console.ReadLine().Trim();
if (command.Length > 0) if (command.Length > 0)
{ {
string message = ""; string message = "";
if (Settings.internalCmdChar != ' ' if (Settings.internalCmdChar != ' '
&& command[0] == Settings.internalCmdChar) && command[0] == Settings.internalCmdChar)
command = command.Substring(1); command = command.Substring(1);
if (command.StartsWith("reco")) if (command.StartsWith("reco"))
{ {
message = new Commands.Reco().Run(null, Settings.ExpandVars(command)); message = new Commands.Reco().Run(null, Settings.ExpandVars(command));
} }
else if (command.StartsWith("connect")) else if (command.StartsWith("connect"))
{ {
message = new Commands.Connect().Run(null, Settings.ExpandVars(command)); message = new Commands.Connect().Run(null, Settings.ExpandVars(command));
} }
else if (command.StartsWith("exit") || command.StartsWith("quit")) else if (command.StartsWith("exit") || command.StartsWith("quit"))
{ {
message = new Commands.Exit().Run(null, Settings.ExpandVars(command)); message = new Commands.Exit().Run(null, Settings.ExpandVars(command));
} }
else if (command.StartsWith("help")) else if (command.StartsWith("help"))
{ {
ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Reco().CMDDesc); ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Reco().CMDDesc);
ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Connect().CMDDesc); ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Connect().CMDDesc);
} }
else ConsoleIO.WriteLineFormatted("§8Unknown command '" + command.Split(' ')[0] + "'."); else ConsoleIO.WriteLineFormatted("§8Unknown command '" + command.Split(' ')[0] + "'.");
if (message != "") if (message != "")
ConsoleIO.WriteLineFormatted("§8MCC: " + message); ConsoleIO.WriteLineFormatted("§8MCC: " + message);
} }
} }
})); }));
offlinePrompt.Start(); offlinePrompt.Start();
} }
} }
} }
/// <summary> /// <summary>
/// Detect if the user is running Minecraft Console Client through Mono /// Detect if the user is running Minecraft Console Client through Mono
/// </summary> /// </summary>
public static bool isUsingMono public static bool isUsingMono
{ {
get get
{ {
return Type.GetType("Mono.Runtime") != null; return Type.GetType("Mono.Runtime") != null;
} }
} }
/// <summary> /// <summary>
/// Enumerate types in namespace through reflection /// Enumerate types in namespace through reflection
/// </summary> /// </summary>
/// <param name="nameSpace">Namespace to process</param> /// <param name="nameSpace">Namespace to process</param>
/// <param name="assembly">Assembly to use. Default is Assembly.GetExecutingAssembly()</param> /// <param name="assembly">Assembly to use. Default is Assembly.GetExecutingAssembly()</param>
/// <returns></returns> /// <returns></returns>
public static Type[] GetTypesInNamespace(string nameSpace, Assembly assembly = null) public static Type[] GetTypesInNamespace(string nameSpace, Assembly assembly = null)
{ {
if (assembly == null) { assembly = Assembly.GetExecutingAssembly(); } if (assembly == null) { assembly = Assembly.GetExecutingAssembly(); }
return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray(); return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
} }
} }
} }

View file

@ -216,8 +216,6 @@ namespace MinecraftClient.Protocol
} }
} }
public enum ValidationResult { Validated, NewTokenRequired, Error };
/// <summary> /// <summary>
/// Validates whether accessToken must be refreshed /// Validates whether accessToken must be refreshed
/// </summary> /// </summary>
@ -250,8 +248,6 @@ namespace MinecraftClient.Protocol
return LoginResult.OtherError; return LoginResult.OtherError;
} }
} }
public enum NewTokenResult { Success, InvalidToken, NullError, OtherError }
/// <summary> /// <summary>
/// Refreshes invalid token /// Refreshes invalid token