public MinecraftProtocol(TcpClient tcp, int protocolver, IMinecraftCom Handler, ForgeInfo forge) { client = tcp; protocolversion = protocolver; forgeInfo = forge; handler = Handler; }
public MCClient(string host, ushort port, string login, string password) { _serverPort = port; _hostname = host; var session = new SessionToken(); var loginResult = ProtocolHandler.GetLogin(login, password, out session); if (loginResult != ProtocolHandler.LoginResult.Success) { throw new Exception(); } _userUuid = session.PlayerID; _sessionId = session.ID; _username = session.PlayerName; var protocolversion = 0; ForgeInfo forgeInfo = null; ProtocolHandler.GetServerInfo(host, port, ref protocolversion, ref forgeInfo); var tcpClient = new TcpClient(host, port); tcpClient.ReceiveBufferSize = 1024 * 1024; var handler = ProtocolHandler.GetProtocolHandler(tcpClient, protocolversion, forgeInfo, this); handler.Login(); handler.SendChatMessage("hello"); Thread.Sleep(2000); Console.WriteLine(String.Join(", ", GetOnlinePlayers())); }
/// <summary> /// Server Info: Check for For Forge on a Minecraft server Ping result /// </summary> /// <param name="jsonData">JSON data returned by the server</param> /// <param name="forgeInfo">ForgeInfo to populate</param> public static void ServerInfoCheckForge(Json.JSONData jsonData, ref ForgeInfo forgeInfo) { if (jsonData.Properties.ContainsKey("modinfo") && jsonData.Properties["modinfo"].Type == Json.JSONData.DataType.Object) { Json.JSONData modData = jsonData.Properties["modinfo"]; if (modData.Properties.ContainsKey("type") && modData.Properties["type"].StringValue == "FML") { forgeInfo = new ForgeInfo(modData); if (forgeInfo.Mods.Any()) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8Server is running Forge. Mod list:"); foreach (ForgeInfo.ForgeMod mod in forgeInfo.Mods) { ConsoleIO.WriteLineFormatted("§8 " + mod.ToString()); } } else { ConsoleIO.WriteLineFormatted("§8Server is running Forge."); } } else { forgeInfo = null; } } } }
public MinecraftProtocol(TcpClient tcp, int protocolVersion, tBotsTask_b.MinecraftBot minecraftBot, ForgeInfo forgeInfo) { this.tcp = tcp; protocolversion = protocolVersion; this.minecraftBot = minecraftBot; this.forgeInfo = forgeInfo; }
public static bool Reforge_Execute(CtrlForge __instance) { if (isReforgeMode) { var t = Traverse.Create(__instance); int categoryIndex = t.Field("categoryIndex").GetValue <int>(); int equipIndex = t.Field("equipIndex").GetValue <int>(); var array = t.Field("sort").Field("array").GetValue() as List <ForgeInfo>[]; ForgeInfo forgeInfo = array[categoryIndex][equipIndex]; Console.WriteLine("重铸"); string id = forgeInfo.Equip.Id; Props item = Game.Data.Get <Props>(id); int price = GetReforgePrice(item); Console.WriteLine("id=" + id); string sourceId = ModExtensionSaveData.GetUniqueSourceId(id); Console.WriteLine("sourceId=" + sourceId); Props source = Game.Data.Get <Props>(sourceId); Console.WriteLine("sourceName=" + source.Name); int.TryParse(item.Remark, out int value); value = Math.Max(5, value + UnityEngine.Random.Range(-10, 20)); Props newProps = GlobalLib.CreateUniquePropsByValue(sourceId, value); newProps.Name = source.Name + "+"; // mark as reforged newProps.Remark = value.ToString(); // use remark to save value Game.GameData.Inventory.Add(newProps.Id, 1); Game.GameData.Inventory.Remove(id, 1); if (id != sourceId) { ModExtensionSaveData.RemoveUniqueItem <Props>(id); } Game.GameData.Money -= price; ForgeInfo newForgeInfo = new ForgeInfo { Id = newProps.Id, IsConditionPass = true }; Traverse.Create(newForgeInfo).Property("Item").SetValue(new Forge() { Id = newProps.Id, PropsId = newProps.Id, }); Traverse.Create(newForgeInfo).Property("Equip").SetValue(newProps); InventoryData inventoryData = Game.GameData.Inventory[id]; if (inventoryData != null) { array[categoryIndex].Add(newForgeInfo); } else { array[categoryIndex][equipIndex] = newForgeInfo; } t.Field("view").GetValue <UIForge>().UpdateEquip(array[categoryIndex].Count, false, true); t.Field("view").GetValue <UIForge>().UpdateMoney(Game.GameData.Money.ToString()); return(false); } return(true); }
/// <summary> /// Initialize a new Forge protocol handler /// </summary> /// <param name="forgeInfo">Forge Server Information</param> /// <param name="protocolVersion">Minecraft protocol version</param> /// <param name="dataTypes">Minecraft data types handler</param> public Protocol18Forge(ForgeInfo forgeInfo, int protocolVersion, DataTypes dataTypes, Protocol18Handler protocol18, IMinecraftComHandler mcHandler) { this.forgeInfo = forgeInfo; this.protocolversion = protocolVersion; this.dataTypes = dataTypes; this.protocol18 = protocol18; this.mcHandler = mcHandler; }
internal MinecraftBot(TcpClient tcp, string host, int port, int protocolver, ForgeInfo forge, tBotsTask_b s) { this.Tcp = tcp; ProtocolVersion = protocolver; Host = host; Port = port; forgeInfo = forge; bots = s; }
internal MinecraftBot(string host, int port, string username, int protocolver, ForgeInfo forge, tBotsTask_a s) { ProtocolVersion = protocolver; Host = host; Port = port; forgeInfo = forge; bots = s; if (username != null) { playername = username.Replace("%RANDOM%", randomName()); } }
/// <summary> /// Server Info: Check for For Forge on a Minecraft server Ping result (Handles FML and FML2 /// </summary> /// <param name="jsonData">JSON data returned by the server</param> /// <param name="forgeInfo">ForgeInfo to populate</param> /// <param name="fmlVersion">Forge protocol version</param> /// <returns>True if the server is running Forge</returns> private static bool ServerInfoCheckForgeSub(Json.JSONData jsonData, ref ForgeInfo forgeInfo, FMLVersion fmlVersion) { string forgeDataTag; string versionField; string versionString; switch (fmlVersion) { case FMLVersion.FML: forgeDataTag = "modinfo"; versionField = "type"; versionString = "FML"; break; case FMLVersion.FML2: forgeDataTag = "forgeData"; versionField = "fmlNetworkVersion"; versionString = "2"; break; default: throw new NotImplementedException("FMLVersion '" + fmlVersion + "' not implemented!"); } if (jsonData.Properties.ContainsKey(forgeDataTag) && jsonData.Properties[forgeDataTag].Type == Json.JSONData.DataType.Object) { Json.JSONData modData = jsonData.Properties[forgeDataTag]; if (modData.Properties.ContainsKey(versionField) && modData.Properties[versionField].StringValue == versionString) { forgeInfo = new ForgeInfo(modData, fmlVersion); if (forgeInfo.Mods.Any()) { ConsoleIO.WriteLineFormatted(Translations.Get("forge.with_mod", forgeInfo.Mods.Count)); if (Settings.DebugMessages) { Translations.WriteLineFormatted("forge.mod_list"); foreach (ForgeInfo.ForgeMod mod in forgeInfo.Mods) { ConsoleIO.WriteLineFormatted("§8 " + mod.ToString()); } } return(true); } else { Translations.WriteLineFormatted("forge.no_mod"); forgeInfo = null; } } } return(false); }
public static bool Reforge_UpdateEquipBtn(CtrlForge __instance, IScrollItme item) { if (isReforgeMode) { var t = Traverse.Create(__instance); int categoryIndex = t.Field("categoryIndex").GetValue <int>(); var array = t.Field("sort").Field("array").GetValue() as List <ForgeInfo>[]; ForgeInfo forgeInfo = array[categoryIndex][item.Index]; Forge item2 = forgeInfo.Item; Props equip = forgeInfo.Equip; forgeInfo.Dialog.Clear(); int price = GetReforgePrice(equip); if (Game.GameData.Money < price) { forgeInfo.IsConditionPass = false; for (int j = 1; j < 3; j++) { forgeInfo.Dialog.Add(string.Format("SecondaryInterface031{0}", j)); } } InventoryData inventoryData = Game.GameData.Inventory[equip.Id]; if (forgeInfo.Dialog.Count <= 0) { forgeInfo.IsConditionPass = true; for (int l = 1; l < 3; l++) { forgeInfo.Dialog.Add(string.Format("SecondaryInterface034{0}", l)); } } ForgeScrollInfo forgeScrollInfo = new ForgeScrollInfo { ItemName = equip.Name, ItemIcon = Game.Resource.Load <Sprite>(string.Format(GameConfig.PropsCategoryPath, (int)equip.PropsCategory)), Remark = price.ToString(), IsNew = false, IsShowSign = item2.IsSpecial, IsConditionPass = forgeInfo.IsConditionPass }; if (item != null) { item.UpdateWidget(new object[] { forgeScrollInfo }); } return(false); } return(true); }
/// <summary> /// Retrieve information about a Minecraft server /// </summary> /// <param name="serverIP">Server IP to ping</param> /// <param name="serverPort">Server Port to ping</param> /// <param name="protocolversion">Will contain protocol version, if ping successful</param> /// <returns>TRUE if ping was successful</returns> public static bool GetServerInfo(string serverIP, ushort serverPort, ref int protocolversion, ref ForgeInfo forgeInfo) { bool success = false; int protocolversionTmp = 0; ForgeInfo forgeInfoTmp = null; if (AutoTimeout.Perform(() => { try { if (Protocol16Handler.doPing(serverIP, serverPort, ref protocolversionTmp) || Protocol18Handler.doPing(serverIP, serverPort, ref protocolversionTmp, ref forgeInfoTmp)) { success = true; } else { Translations.WriteLineFormatted("error.unexpect_response"); } } catch (Exception e) { ConsoleIO.WriteLineFormatted(String.Format("§8{0}: {1}", e.GetType().FullName, e.Message)); } }, TimeSpan.FromSeconds(Settings.ResolveSrvRecordsShortTimeout ? 10 : 30))) { if (protocolversion != 0 && protocolversion != protocolversionTmp) { Translations.WriteLineFormatted("error.version_different"); } if (protocolversion == 0 && protocolversionTmp <= 1) { Translations.WriteLineFormatted("error.no_version_report"); } if (protocolversion == 0) { protocolversion = protocolversionTmp; } forgeInfo = forgeInfoTmp; return(success); } else { Translations.WriteLineFormatted("error.connection_timeout"); return(false); } }
/// <summary> /// Retrieve information about a Minecraft server /// </summary> /// <param name="serverIP">Server IP to ping</param> /// <param name="serverPort">Server Port to ping</param> /// <param name="protocolversion">Will contain protocol version, if ping successful</param> /// <returns>TRUE if ping was successful</returns> public static bool GetServerInfo(string serverIP, ushort serverPort, ref int protocolversion, ref ForgeInfo forgeInfo) { bool success = false; int protocolversionTmp = 0; ForgeInfo forgeInfoTmp = null; if (AutoTimeout.Perform(() => { try { if (Protocol16Handler.doPing(serverIP, serverPort, ref protocolversionTmp) || Protocol18Handler.doPing(serverIP, serverPort, ref protocolversionTmp, ref forgeInfoTmp)) { success = true; } else { ConsoleIO.WriteLineFormatted("§8Unexpected response from the server (is that a Minecraft server?)"); } } catch (Exception e) { ConsoleIO.WriteLineFormatted(String.Format("§8{0}: {1}", e.GetType().FullName, e.Message)); } }, TimeSpan.FromSeconds(Settings.ResolveSrvRecordsShortTimeout ? 10 : 30))) { if (protocolversion != 0 && protocolversion != protocolversionTmp) { ConsoleIO.WriteLineFormatted("§8Server reports a different version than manually set. Login may not work."); } if (protocolversion == 0 && protocolversionTmp <= 1) { ConsoleIO.WriteLineFormatted("§8Server does not report its protocol version, autodetection will not work."); } if (protocolversion == 0) { protocolversion = protocolversionTmp; } forgeInfo = forgeInfoTmp; return(success); } else { ConsoleIO.WriteLineFormatted("§8A timeout occured while attempting to connect to this IP."); return(false); } }
/// <summary> /// Retrieve information about a Minecraft server /// </summary> /// <param name="serverIP">Server IP to ping</param> /// <param name="serverPort">Server Port to ping</param> /// <param name="protocolversion">Will contain protocol version, if ping successful</param> /// <returns>TRUE if ping was successful</returns> public static bool GetServerInfo(string serverIP, ushort serverPort, ref int protocolversion, ref ForgeInfo forgeInfo) { bool success = false; int protocolversionTmp = 0; ForgeInfo forgeInfoTmp = null; if (AutoTimeout.Perform(() => { try { if (Protocol16Handler.doPing(serverIP, serverPort, ref protocolversionTmp) || Protocol18Handler.doPing(serverIP, serverPort, ref protocolversionTmp, ref forgeInfoTmp)) { success = true; } else { ConsoleIO.WriteLineFormatted("§c[警告]§8无法连接至非Minecraft服务器之外的服务器!"); } } catch (Exception e) { ConsoleIO.WriteLineFormatted(String.Format("§e[信息]§8{0}: {1}", e.GetType().FullName, e.Message)); } }, TimeSpan.FromSeconds(Settings.ResolveSrvRecordsShortTimeout ? 10 : 30))) { if (protocolversion != 0 && protocolversion != protocolversionTmp) { ConsoleIO.WriteLineFormatted("§e[信息]§8服务器发送了不同的版本,可能无法登入,请手动输入版本."); } if (protocolversion == 0 && protocolversionTmp <= 1) { ConsoleIO.WriteLineFormatted("§e[信息]§8服务器未通知协议版本,可能会无法登入,请手动输入版本."); } if (protocolversion == 0) { protocolversion = protocolversionTmp; } forgeInfo = forgeInfoTmp; return(success); } else { ConsoleIO.WriteLineFormatted("§c[错误]§8连接超时."); return(false); } }
public McTcpClient(SessionToken session) { //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; if (Settings.ServerConnectionInfo.ServerVersion != "" && Settings.ServerConnectionInfo.ServerVersion.ToLower() != "auto") { protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerConnectionInfo.ServerVersion); if (protocolversion != 0) { ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerConnectionInfo.ServerVersion + " (protocol v" + protocolversion + ')'); } else { ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerConnectionInfo.ServerVersion + "'.\nSwitching to autodetection mode."); } } if (protocolversion == 0) { Console.WriteLine("Retrieving Server Info..."); if (!ProtocolHandler.GetServerInfo(Settings.ServerConnectionInfo.ServerIP, Settings.ServerConnectionInfo.ServerPort, ref protocolversion, ref forgeInfo)) { //HandleFailure("Failed to ping this IP.", true, DisconnectReason.ConnectionLost); return; } } if (protocolversion != 0) { try { StartClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, Settings.ServerConnectionInfo.ServerIP, Settings.ServerConnectionInfo.ServerPort, forgeInfo); //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { /* HandleFailure("Cannot connect to the server : This version is not supported !", true); */ } } //else HandleFailure("Failed to determine server version.", true); }
internal MinecraftBot(string host, int port, string username, int protocolver, ForgeInfo forge, string socks, StressTask s) { string[] proxyip = socks.Split(':'); if (proxyip.Length == 2) { ProxyIP = proxyip[0]; ProxyPort = int.Parse(proxyip[1]); } else { ProxyIP = proxyip[0]; ProxyPort = 8080; } ProtocolVersion = protocolver; Host = host; Port = port; forgeInfo = forge; bots = s; playername = username.Replace("%RANDOM%", randomName()); }
/// <summary> /// Retrieve information about a Minecraft server /// </summary> /// <param name="serverIP">Server IP to ping</param> /// <param name="serverPort">Server Port to ping</param> /// <param name="protocolversion">Will contain protocol version, if ping successful</param> /// <returns>TRUE if ping was successful</returns> public static bool GetServerInfo(string serverIP, ushort serverPort, ref int protocolversion, ref ForgeInfo forgeInfo) { bool success = false; int protocolversionTmp = 0; ForgeInfo forgeInfoTmp = null; if (AutoTimeout.Perform(() => { try { if (Protocol16Handler.doPing(serverIP, serverPort, ref protocolversionTmp) || Protocol18Handler.doPing(serverIP, serverPort, ref protocolversionTmp, ref forgeInfoTmp)) { success = true; } else { ConsoleIO.WriteLineFormatted("§8Unexpected response from the server (is that a Minecraft server?)"); } } catch (Exception e) { //ConsoleIO.WriteLineFormatted("ProtocolHandler:82"); //ConsoleIO.WriteLineFormatted(String.Format("§8{0}: {1}", e.GetType().FullName, e.Message)); } }, TimeSpan.FromSeconds(Settings.ResolveSrvRecordsShortTimeout ? 10 : 30))) { protocolversion = protocolversionTmp; forgeInfo = forgeInfoTmp; return(success); } else { //ConsoleIO.WriteLineFormatted("§8A timeout occured while attempting to connect to this IP."); return(false); } }
/// <summary> /// Get a protocol handler for the specified Minecraft version /// </summary> /// <param name="Client">Tcp Client connected to the server</param> /// <param name="ProtocolVersion">Protocol version to handle</param> /// <param name="Handler">Handler with the appropriate callbacks</param> /// <returns></returns> public static IMinecraftCom GetProtocolHandler(TcpClient Client, int ProtocolVersion, ForgeInfo forgeInfo, IMinecraftComHandler Handler) { int[] supportedVersions_Protocol16 = { 51, 60, 61, 72, 73, 74, 78 }; if (Array.IndexOf(supportedVersions_Protocol16, ProtocolVersion) > -1) { return(new Protocol16Handler(Client, ProtocolVersion, Handler)); } int[] supportedVersions_Protocol18 = { 4, 5, 47, 107, 108, 109, 110, 210, 315, 316, 335, 338, 340, 393, 401, 404, 477, 480, 485, 490, 498, 573, 575, 578, 735, 736, 751, 753, 754 }; if (Array.IndexOf(supportedVersions_Protocol18, ProtocolVersion) > -1) { return(new Protocol18Handler(Client, ProtocolVersion, Handler, forgeInfo)); } throw new NotSupportedException(Translations.Get("exception.version_unsupport", ProtocolVersion)); }
/// <summary> /// Start a new Client /// </summary> private static void InitializeClient() { SessionToken session = new SessionToken(); ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; if (Settings.Password == "-") { ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode."); result = ProtocolHandler.LoginResult.Success; session.PlayerID = "0"; session.PlayerName = Settings.Login; } else { // Validate cached session or login new session. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower())) { session = SessionCache.Get(Settings.Login.ToLower()); result = ProtocolHandler.GetTokenValidation(session); if (result != ProtocolHandler.LoginResult.Success) { ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired."); if (Settings.Password == "") { RequestPassword(); } } else { ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.'); } } if (result != ProtocolHandler.LoginResult.Success) { Console.WriteLine("Connecting to Minecraft.net..."); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session); if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None) { SessionCache.Store(Settings.Login.ToLower(), session); } } } if (result == ProtocolHandler.LoginResult.Success) { Settings.Username = session.PlayerName; if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } if (Settings.playerHeadAsIcon) { ConsoleIcon.setPlayerIconAsync(Settings.Username); } if (Settings.DebugMessages) { Console.WriteLine("Success. (session ID: " + session.ID + ')'); } //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE if (Settings.ServerIP == "") { Console.Write("Server IP : "); Settings.SetServerIP(Console.ReadLine()); } //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") { protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); if (protocolversion != 0) { 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."); } if (useMcVersionOnce) { useMcVersionOnce = false; Settings.ServerVersion = ""; } } if (protocolversion == 0) { Console.WriteLine("Retrieving Server Info..."); if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) { HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } if (protocolversion != 0) { try { //Start the main TCP client if (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); } //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); } } else { HandleFailure("Failed to determine server version.", true); } } else { Console.ForegroundColor = ConsoleColor.Gray; string failureMessage = "Minecraft Login failed : "; switch (result) { 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.WrongPassword: failureMessage += "Incorrect password."; break; case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break; case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break; case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break; default: failureMessage += "Unknown Error."; break; } if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) { 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' + "mozroots --import --ask-remove"); return; } HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); } }
/// <summary> /// Start a new Client /// </summary> private static void InitializeClient() { SessionToken session = new SessionToken(); ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; if (Settings.Password == "-") { Translations.WriteLineFormatted("mcc.offline"); result = ProtocolHandler.LoginResult.Success; session.PlayerID = "0"; session.PlayerName = Settings.Login; } else { // Validate cached session or login new session. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower())) { session = SessionCache.Get(Settings.Login.ToLower()); result = ProtocolHandler.GetTokenValidation(session); if (result != ProtocolHandler.LoginResult.Success) { Translations.WriteLineFormatted("mcc.session_invalid"); if (Settings.Password == "") { RequestPassword(); } } else { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.session_valid", session.PlayerName)); } } if (result != ProtocolHandler.LoginResult.Success) { Translations.WriteLine("mcc.connecting", Settings.AccountType == ProtocolHandler.AccountType.Mojang ? "Minecraft.net" : "Microsoft"); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, Settings.AccountType, out session); if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None) { SessionCache.Store(Settings.Login.ToLower(), session); } } } if (result == ProtocolHandler.LoginResult.Success) { Settings.Username = session.PlayerName; bool isRealms = false; if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } if (Settings.playerHeadAsIcon) { ConsoleIcon.setPlayerIconAsync(Settings.Username); } if (Settings.DebugMessages) { Translations.WriteLine("debug.session_id", session.ID); } List <string> availableWorlds = new List <string>(); if (Settings.MinecraftRealmsEnabled && !String.IsNullOrEmpty(session.ID)) { availableWorlds = ProtocolHandler.RealmsListWorlds(Settings.Username, session.PlayerID, session.ID); } if (Settings.ServerIP == "") { Translations.Write("mcc.ip"); string addressInput = Console.ReadLine(); if (addressInput.StartsWith("realms:")) { if (Settings.MinecraftRealmsEnabled) { if (availableWorlds.Count == 0) { HandleFailure(Translations.Get("error.realms.access_denied"), false, ChatBot.DisconnectReason.LoginRejected); return; } int worldIndex = 0; string worldId = addressInput.Split(':')[1]; if (!availableWorlds.Contains(worldId) && int.TryParse(worldId, out worldIndex) && worldIndex < availableWorlds.Count) { worldId = availableWorlds[worldIndex]; } if (availableWorlds.Contains(worldId)) { string RealmsAddress = ProtocolHandler.GetRealmsWorldServerAddress(worldId, Settings.Username, session.PlayerID, session.ID); if (RealmsAddress != "") { addressInput = RealmsAddress; isRealms = true; Settings.ServerVersion = MCHighestVersion; } else { HandleFailure(Translations.Get("error.realms.server_unavailable"), false, ChatBot.DisconnectReason.LoginRejected); return; } } else { HandleFailure(Translations.Get("error.realms.server_id"), false, ChatBot.DisconnectReason.LoginRejected); return; } } else { HandleFailure(Translations.Get("error.realms.disabled"), false, null); return; } } Settings.SetServerIP(addressInput); } //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") { protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); if (protocolversion != 0) { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", Settings.ServerVersion, protocolversion)); } else { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.unknown_version", Settings.ServerVersion)); } if (useMcVersionOnce) { useMcVersionOnce = false; Settings.ServerVersion = ""; } } //Retrieve server info if version is not manually set OR if need to retrieve Forge information if (!isRealms && (protocolversion == 0 || Settings.ServerAutodetectForge || (Settings.ServerForceForge && !ProtocolHandler.ProtocolMayForceForge(protocolversion)))) { if (protocolversion != 0) { Translations.WriteLine("mcc.forge"); } else { Translations.WriteLine("mcc.retrieve"); } if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) { HandleFailure(Translations.Get("error.ping"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } //Force-enable Forge support? if (!isRealms && Settings.ServerForceForge && forgeInfo == null) { if (ProtocolHandler.ProtocolMayForceForge(protocolversion)) { Translations.WriteLine("mcc.forgeforce"); forgeInfo = ProtocolHandler.ProtocolForceForge(protocolversion); } else { HandleFailure(Translations.Get("error.forgeforce"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } //Proceed to server login if (protocolversion != 0) { try { //Start the main TCP client if (Settings.SingleCommand != "") { client = new McClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand); } else { client = new McClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort); } //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { HandleFailure(Translations.Get("error.unsupported"), true); } } else { HandleFailure(Translations.Get("error.determine"), true); } } else { string failureMessage = Translations.Get("error.login"); string failureReason = ""; switch (result) { case ProtocolHandler.LoginResult.AccountMigrated: failureReason = "error.login.migrated"; break; case ProtocolHandler.LoginResult.ServiceUnavailable: failureReason = "error.login.server"; break; case ProtocolHandler.LoginResult.WrongPassword: failureReason = "error.login.blocked"; break; case ProtocolHandler.LoginResult.InvalidResponse: failureReason = "error.login.response"; break; case ProtocolHandler.LoginResult.NotPremium: failureReason = "error.login.premium"; break; case ProtocolHandler.LoginResult.OtherError: failureReason = "error.login.network"; break; case ProtocolHandler.LoginResult.SSLError: failureReason = "error.login.ssl"; break; case ProtocolHandler.LoginResult.UserCancel: failureReason = "error.login.cancel"; break; default: failureReason = "error.login.unknown"; break; } failureMessage += Translations.Get(failureReason); if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) { Translations.WriteLineFormatted("error.login.ssl_help"); return; } HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); } }
/// <summary> /// Starts the main chat client /// </summary> /// <param name="username">The chosen username of a premium Minecraft Account</param> /// <param name="uuid">The player's UUID for online-mode authentication</param> /// <param name="sessionID">A valid sessionID obtained after logging in</param> /// <param name="server_ip">The server IP</param> /// <param name="port">The server port to use</param> /// <param name="protocolversion">Minecraft protocol version to use</param> public McTcpClient(string username, string uuid, string sessionID, int protocolversion, ForgeInfo forgeInfo, string server_ip, ushort port) { StartClient(username, uuid, sessionID, server_ip, port, protocolversion, forgeInfo, false, ""); }
/// <summary> /// Starts the main chat client, wich will login to the server using the MinecraftCom class. /// </summary> /// <param name="user">The chosen username of a premium Minecraft Account</param> /// <param name="sessionID">A valid sessionID obtained with MinecraftCom.GetLogin()</param> /// <param name="server_ip">The server IP</param> /// <param name="port">The server port to use</param> /// <param name="protocolversion">Minecraft protocol version to use</param> /// <param name="uuid">The player's UUID for online-mode authentication</param> /// <param name="singlecommand">If set to true, the client will send a single command and then disconnect from the server</param> /// <param name="command">The text or command to send. Will only be sent if singlecommand is set to true.</param> private void StartClient(string user, string uuid, string sessionID, string server_ip, ushort port, int protocolversion, ForgeInfo forgeInfo, bool singlecommand, string command) { terrainAndMovementsEnabled = Settings.TerrainAndMovements; bool retry = false; this.sessionid = sessionID; this.uuid = uuid; this.username = user; this.host = server_ip; this.port = port; if (!singlecommand) { if (botsOnHold.Count == 0) { if (Settings.AntiAFK_Enabled) { BotLoad(new ChatBots.AntiAFK(Settings.AntiAFK_Delay)); } if (Settings.Hangman_Enabled) { BotLoad(new ChatBots.HangmanGame(Settings.Hangman_English)); } if (Settings.Alerts_Enabled) { BotLoad(new ChatBots.Alerts()); } if (Settings.ChatLog_Enabled) { BotLoad(new ChatBots.ChatLog(Settings.ExpandVars(Settings.ChatLog_File), Settings.ChatLog_Filter, Settings.ChatLog_DateTime)); } if (Settings.PlayerLog_Enabled) { BotLoad(new ChatBots.PlayerListLogger(Settings.PlayerLog_Delay, Settings.ExpandVars(Settings.PlayerLog_File))); } if (Settings.AutoRelog_Enabled) { BotLoad(new ChatBots.AutoRelog(Settings.AutoRelog_Delay, Settings.AutoRelog_Retries)); } if (Settings.ScriptScheduler_Enabled) { BotLoad(new ChatBots.ScriptScheduler(Settings.ExpandVars(Settings.ScriptScheduler_TasksFile))); } if (Settings.RemoteCtrl_Enabled) { BotLoad(new ChatBots.RemoteControl()); } if (Settings.AutoRespond_Enabled) { BotLoad(new ChatBots.AutoRespond(Settings.AutoRespond_Matches)); } //Add your ChatBot here by uncommenting and adapting //BotLoad(new ChatBots.YourBot()); } } try { client = ProxyHandler.newTcpClient(host, port); client.ReceiveBufferSize = 1024 * 1024; handler = Protocol.ProtocolHandler.GetProtocolHandler(client, protocolversion, forgeInfo, this); Console.WriteLine("Version is supported.\nLogging in..."); try { if (handler.Login()) { if (singlecommand) { handler.SendChatMessage(command); ConsoleIO.WriteLineFormatted("§7Command §8" + command + "§7 sent."); Thread.Sleep(5000); handler.Disconnect(); Thread.Sleep(1000); } else { foreach (ChatBot bot in botsOnHold) { BotLoad(bot, false); } botsOnHold.Clear(); Console.WriteLine("Server was successfully joined.\nType '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "quit' to leave the server."); cmdprompt = new Thread(new ThreadStart(CommandPrompt)); cmdprompt.Name = "MCC Command prompt"; cmdprompt.Start(); } } } catch (Exception e) { ConsoleIO.WriteLineFormatted("§8" + e.Message); Console.WriteLine("Failed to join this server."); retry = true; } } catch (SocketException e) { ConsoleIO.WriteLineFormatted("§8" + e.Message); Console.WriteLine("Failed to connect to this IP."); retry = true; } if (retry) { if (ReconnectionAttemptsLeft > 0) { ConsoleIO.WriteLogLine("Waiting 5 seconds (" + ReconnectionAttemptsLeft + " attempts left)..."); Thread.Sleep(5000); ReconnectionAttemptsLeft--; Program.Restart(); } else if (!singlecommand && Settings.interactiveMode) { Program.HandleFailure(); } } }
/// <summary> /// Start a new Client /// </summary> private static void InitializeClient() { vars.logInTimestamp = Telegram.data.getTimestamp() + 60; SessionToken session = new SessionToken(); ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; if (Settings.Password == "-") { //ConsoleIO.WriteLineFormatted("§8Iniciando no modo OffLine."); result = ProtocolHandler.LoginResult.Success; session.PlayerID = "0"; session.PlayerName = Settings.Login; } else { // Validate cached session or login new session. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower())) { session = SessionCache.Get(Settings.Login.ToLower()); result = ProtocolHandler.GetTokenValidation(session); if (result != ProtocolHandler.LoginResult.Success) { ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired."); if (Settings.Password == "") { RequestPassword(); } } else { ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.'); } } if (result != ProtocolHandler.LoginResult.Success) { Console.WriteLine("Connecting to Minecraft.net..."); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session); if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None) { SessionCache.Store(Settings.Login.ToLower(), session); } } } if (result == ProtocolHandler.LoginResult.Success) { Settings.Username = "******"; if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } if (Settings.playerHeadAsIcon) { ConsoleIcon.setPlayerIconAsync(Settings.Username); } if (Settings.DebugMessages) { Console.WriteLine("Success. (session ID: " + session.ID + ')'); } //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE if (Settings.ServerIP == "") { Console.Write("Server IP : "); Settings.SetServerIP(Console.ReadLine()); } //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; //if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") if (true) { //protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion("1.8"); if (protocolversion != 0) { ConsoleIO.WriteLineFormatted("§8Usando a versão " + Settings.ServerVersion + " (protocolo v" + protocolversion + ')'); } else { ConsoleIO.WriteLineFormatted("§8A versão '" + Settings.ServerVersion + "' é desconhecida ou não suportada :/\nDetectando versão compativel automaticamente!"); } if (useMcVersionOnce) { useMcVersionOnce = false; Settings.ServerVersion = ""; } } if (protocolversion == 0) { //Console.WriteLine("Obtendo informações do servidor..."); if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) { //HandleFailure("Falha ao conectar :/", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } if (protocolversion != 0) { try { //Start the main TCP client if (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); } //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { HandleFailure("Não foi possivel conectar-se ao servidor : Versão nao suportada !", true); } } else { HandleFailure("Falha ao determinar a versão do servidor.", true); } } else { string failureMessage = "Minecraft Login failed : "; switch (result) { 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.WrongPassword: failureMessage += "Incorrect password, blacklisted IP or too many logins."; break; case ProtocolHandler.LoginResult.InvalidResponse: failureMessage += "Invalid server response."; break; case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break; case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break; case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break; default: failureMessage += "Unknown Error."; break; } if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) { 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' + "mozroots --import --ask-remove"); return; } HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); } }
/// <summary> /// Start a new Client /// </summary> private static void InitializeClient() { SessionToken session = new SessionToken(); ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; if (Settings.Password == "-") { Translations.WriteLineFormatted("mcc.offline"); result = ProtocolHandler.LoginResult.Success; session.PlayerID = "0"; session.PlayerName = Settings.Login; } else { // Validate cached session or login new session. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower())) { session = SessionCache.Get(Settings.Login.ToLower()); result = ProtocolHandler.GetTokenValidation(session); if (result != ProtocolHandler.LoginResult.Success) { Translations.WriteLineFormatted("mcc.session_invalid"); if (Settings.Password == "") { RequestPassword(); } } else { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.session_valid", session.PlayerName)); } } if (result != ProtocolHandler.LoginResult.Success) { Translations.WriteLine("mcc.connecting"); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session); if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None) { SessionCache.Store(Settings.Login.ToLower(), session); } } } if (result == ProtocolHandler.LoginResult.Success) { Settings.Username = session.PlayerName; if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } if (Settings.playerHeadAsIcon) { ConsoleIcon.setPlayerIconAsync(Settings.Username); } if (Settings.DebugMessages) { Translations.WriteLine("debug.session_id", session.ID); } //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE if (Settings.ServerIP == "") { Translations.Write("mcc.ip"); Settings.SetServerIP(Console.ReadLine()); } //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") { protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); if (protocolversion != 0) { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", Settings.ServerVersion, protocolversion)); } else { ConsoleIO.WriteLineFormatted(Translations.Get("mcc.unknown_version", Settings.ServerVersion)); } if (useMcVersionOnce) { useMcVersionOnce = false; Settings.ServerVersion = ""; } } if (protocolversion == 0 || Settings.ServerMayHaveForge) { if (protocolversion != 0) { Translations.WriteLine("mcc.forge"); } else { Translations.WriteLine("mcc.retrieve"); } if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) { HandleFailure(Translations.Get("error.ping"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } if (protocolversion != 0) { try { //Start the main TCP client if (Settings.SingleCommand != "") { client = new McClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand); } else { client = new McClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort); } //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { HandleFailure(Translations.Get("error.unsupported"), true); } } else { HandleFailure(Translations.Get("error.determine"), true); } } else { string failureMessage = Translations.Get("error.login"); string failureReason = ""; switch (result) { case ProtocolHandler.LoginResult.AccountMigrated: failureReason = "error.login.migrated"; break; case ProtocolHandler.LoginResult.ServiceUnavailable: failureReason = "error.login.server"; break; case ProtocolHandler.LoginResult.WrongPassword: failureReason = "error.login.blocked"; break; case ProtocolHandler.LoginResult.InvalidResponse: failureReason = "error.login.response"; break; case ProtocolHandler.LoginResult.NotPremium: failureReason = "error.login.premium"; break; case ProtocolHandler.LoginResult.OtherError: failureReason = "error.login.network"; break; case ProtocolHandler.LoginResult.SSLError: failureReason = "error.login.ssl"; break; default: failureReason = "error.login.unknown"; break; } failureMessage += Translations.Get(failureReason); if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) { Translations.WriteLineFormatted("error.login.ssl_help"); return; } HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); } }
public static void Reforge_OnShow(CtrlForge __instance) { if (isReforgeMode) { var array = Traverse.Create(__instance).Field("sort").Field("array").GetValue() as List <ForgeInfo>[]; for (int i = 0; i < array.Length; i++) { if (array[i] != null) { array[i].Clear(); } else { array[i] = new List <ForgeInfo>(); } } List <string> showed = new List <string>(); Game.GameData.Inventory.GetDictionary(); foreach (var key in Game.GameData.Inventory.Keys) { Props props = Game.Data.Get <Props>(key); if (props == null) { continue; } PropsCategory propsCategory = props.PropsCategory; int index = -1; switch (propsCategory) { case PropsCategory.Fist: case PropsCategory.Leg: index = 0; break; case PropsCategory.Sword: case PropsCategory.Blade: index = 1; break; case PropsCategory.Long: case PropsCategory.Short: index = 2; break; case PropsCategory.DualWielding: case PropsCategory.Special: index = 3; break; case PropsCategory.Armor: index = 4; break; } if (index >= 0) { ForgeInfo forgeInfo = new ForgeInfo { Id = key, IsConditionPass = true }; Traverse.Create(forgeInfo).Property("Item").SetValue(new Forge() { Id = key, PropsId = key, }); Traverse.Create(forgeInfo).Property("Equip").SetValue(props); array[index].Add(forgeInfo); } } } }
/// <summary> /// Server Info: Check for For Forge versions 1 and 2 on a Minecraft server Ping result /// </summary> /// <param name="jsonData">JSON data returned by the server</param> /// <param name="forgeInfo">ForgeInfo to populate</param> /// <returns>True if the server is running Forge</returns> public static bool ServerInfoCheckForge(Json.JSONData jsonData, ref ForgeInfo forgeInfo) { return(ServerInfoCheckForgeSub(jsonData, ref forgeInfo, FMLVersion.FML) || // MC 1.12 and lower ServerInfoCheckForgeSub(jsonData, ref forgeInfo, FMLVersion.FML2)); // MC 1.13 and greater }
/// <summary> /// Ping a Minecraft server to get information about the server /// </summary> /// <returns>True if ping was successful</returns> public static bool doPing(string host, int port, ref int protocolversion, ref ForgeInfo forgeInfo) { string version = ""; TcpClient tcp = ProxyHandler.newTcpClient(host, port); tcp.ReceiveBufferSize = 1024 * 1024; SocketWrapper socketWrapper = new SocketWrapper(tcp); DataTypes dataTypes = new DataTypes(MC18Version); byte[] packet_id = dataTypes.GetVarInt(0); byte[] protocol_version = dataTypes.GetVarInt(-1); byte[] server_port = BitConverter.GetBytes((ushort)port); Array.Reverse(server_port); byte[] next_state = dataTypes.GetVarInt(1); byte[] packet = dataTypes.ConcatBytes(packet_id, protocol_version, dataTypes.GetString(host), server_port, next_state); byte[] tosend = dataTypes.ConcatBytes(dataTypes.GetVarInt(packet.Length), packet); socketWrapper.SendDataRAW(tosend); byte[] status_request = dataTypes.GetVarInt(0); byte[] request_packet = dataTypes.ConcatBytes(dataTypes.GetVarInt(status_request.Length), status_request); socketWrapper.SendDataRAW(request_packet); int packetLength = dataTypes.ReadNextVarIntRAW(socketWrapper); if (packetLength > 0) //Read Response length { List <byte> packetData = new List <byte>(socketWrapper.ReadDataRAW(packetLength)); if (dataTypes.ReadNextVarInt(packetData) == 0x00) //Read Packet ID { string result = dataTypes.ReadNextString(packetData); //Get the Json data if (!String.IsNullOrEmpty(result) && result.StartsWith("{") && result.EndsWith("}")) { Json.JSONData jsonData = Json.ParseJson(result); if (jsonData.Type == Json.JSONData.DataType.Object && jsonData.Properties.ContainsKey("version")) { Json.JSONData versionData = jsonData.Properties["version"]; //Retrieve display name of the Minecraft version if (versionData.Properties.ContainsKey("name")) { version = versionData.Properties["name"].StringValue; } //Retrieve protocol version number for handling this server if (versionData.Properties.ContainsKey("protocol")) { protocolversion = dataTypes.Atoi(versionData.Properties["protocol"].StringValue); } // Check for forge on the server. Protocol18Forge.ServerInfoCheckForge(jsonData, ref forgeInfo); ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + (forgeInfo != null ? ", with Forge)." : ").")); return(true); } } } } return(false); }
public Protocol18Handler(TcpClient Client, int protocolVersion, IMinecraftComHandler handler, ForgeInfo forgeInfo) { ConsoleIO.SetAutoCompleteEngine(this); ChatParser.InitTranslations(); this.socketWrapper = new SocketWrapper(Client); this.dataTypes = new DataTypes(protocolVersion); this.protocolversion = protocolVersion; this.handler = handler; this.pForge = new Protocol18Forge(forgeInfo, protocolVersion, dataTypes, this, handler); this.pTerrain = new Protocol18Terrain(protocolVersion, dataTypes, handler); if (protocolversion >= MC113Version) { if (protocolVersion > MC114Version && handler.GetTerrainEnabled()) { throw new NotImplementedException("Please update block types handling for this Minecraft version. See Material.cs"); } if (protocolVersion >= MC114Version) { Block.Palette = new Palette114(); } else { Block.Palette = new Palette113(); } } else { Block.Palette = new Palette112(); } if (handler.GetTerrainEnabled() && protocolversion > MC114Version) { ConsoleIO.WriteLineFormatted("§8Terrain & Movements currently not handled for that MC version."); handler.SetTerrainEnabled(false); } }
/// <summary> /// Starts the main chat client in single command sending mode /// </summary> /// <param name="username">The chosen username of a premium Minecraft Account</param> /// <param name="uuid">The player's UUID for online-mode authentication</param> /// <param name="sessionID">A valid sessionID obtained after logging in</param> /// <param name="server_ip">The server IP</param> /// <param name="port">The server port to use</param> /// <param name="protocolversion">Minecraft protocol version to use</param> /// <param name="command">The text or command to send.</param> public McTcpClient(string username, string uuid, string sessionID, string server_ip, ushort port, int protocolversion, ForgeInfo forgeInfo, string command) { StartClient(username, uuid, sessionID, server_ip, port, protocolversion, forgeInfo, true, command); }
/// <summary> /// Get a protocol handler for the specified Minecraft version /// </summary> /// <param name="Client">Tcp Client connected to the server</param> /// <param name="ProtocolVersion">Protocol version to handle</param> /// <param name="Handler">Handler with the appropriate callbacks</param> /// <returns></returns> public static IMinecraftCom GetProtocolHandler(TcpClient Client, int ProtocolVersion, ForgeInfo forgeInfo, IMinecraftComHandler Handler) { int[] supportedVersions_Protocol16 = { 51, 60, 61, 72, 73, 74, 78 }; if (Array.IndexOf(supportedVersions_Protocol16, ProtocolVersion) > -1) { return(new Protocol16Handler(Client, ProtocolVersion, Handler)); } int[] supportedVersions_Protocol18 = { 4, 5, 47, 107, 108, 109, 110, 210, 315, 316, 335, 338, 340, 393, 401, 404, 477, 480, 485 }; if (Array.IndexOf(supportedVersions_Protocol18, ProtocolVersion) > -1) { return(new Protocol18Handler(Client, ProtocolVersion, Handler, forgeInfo)); } throw new NotSupportedException("The protocol version no." + ProtocolVersion + " is not supported."); }
public Protocol18Handler(TcpClient Client, int protocolVersion, IMinecraftComHandler handler, ForgeInfo forgeInfo, Player player) { this.player = player; ConsoleIO.SetAutoCompleteEngine(this); ChatParser.InitTranslations(); connectionInfo = new ConnectionInfo(new SocketWrapper(Client), 0); this.dataTypes = new DataTypes(protocolVersion); this.protocolversion = protocolVersion; this.handler = handler; this.pForge = new Protocol18Forge(forgeInfo, protocolVersion, dataTypes, this, handler); this.pTerrain = new Protocol18Terrain(protocolVersion, dataTypes, handler); if (protocolversion > (int)McVersion.V1142) { ConsoleIO.WriteLineFormatted("§8Terrain & Movements currently not handled for that MC version."); //Modify client pool for terrain? } if (player.GetInventoryEnabled() && protocolversion > (int)McVersion.V114) { ConsoleIO.WriteLineFormatted("§8Inventories are currently not handled for that MC version."); player.SetInventoryEnabled(false); } if (protocolversion >= (int)McVersion.V18) { if (protocolVersion >= (int)McVersion.V114) { Block.Palette = new Palette114(); } else { Block.Palette = new Palette113(); } } else { Block.Palette = new Palette112(); } packetReadWriter = new Protocol18PacketReadWriter(connectionInfo, dataTypes, protocolVersion); packetHandler = new Protocol18PacketHandler(protocolVersion, dataTypes, handler, packetReadWriter, pTerrain, pForge, worldInfo, this, player); pForge.packetReadWriter = packetReadWriter; }