From bdcc22b465d30d3a0cf04471a2d93f5ccadfbdf1 Mon Sep 17 00:00:00 2001 From: BruceChen Date: Thu, 6 Oct 2022 14:53:05 +0800 Subject: [PATCH] Add update detection --- MinecraftClient/ChatBots/AutoAttack.cs | 1 - MinecraftClient/ChatBots/AutoCraft.cs | 1 - MinecraftClient/ChatBots/AutoFishing.cs | 1 - MinecraftClient/ChatBots/AutoRelog.cs | 1 - MinecraftClient/ChatBots/ChatLog.cs | 1 - MinecraftClient/ChatBots/PlayerListLogger.cs | 1 - MinecraftClient/ChatBots/ScriptScheduler.cs | 5 - .../DefaultConfigResource.Designer.cs | 12 +- MinecraftClient/Inventory/Item.cs | 4 +- MinecraftClient/Mapping/RaycastHelper.cs | 6 - MinecraftClient/Program.cs | 78 ++++++++--- .../Protocol/ProfileKey/KeysCache.cs | 1 - MinecraftClient/Proxy/ProxyHandler.cs | 3 +- MinecraftClient/Resources/lang/en.ini | 5 +- MinecraftClient/Resources/lang/zh-Hans.ini | 7 +- MinecraftClient/Settings.cs | 129 +++++++++++++++--- MinecraftClient/Translations.cs | 1 - MinecraftClient/WinAPI/ExitCleanUp.cs | 1 - 18 files changed, 193 insertions(+), 65 deletions(-) diff --git a/MinecraftClient/ChatBots/AutoAttack.cs b/MinecraftClient/ChatBots/AutoAttack.cs index 522a8202..ab5a6b64 100644 --- a/MinecraftClient/ChatBots/AutoAttack.cs +++ b/MinecraftClient/ChatBots/AutoAttack.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using MinecraftClient.Mapping; using Tomlet.Attributes; diff --git a/MinecraftClient/ChatBots/AutoCraft.cs b/MinecraftClient/ChatBots/AutoCraft.cs index 5ecf060f..bf3dac79 100644 --- a/MinecraftClient/ChatBots/AutoCraft.cs +++ b/MinecraftClient/ChatBots/AutoCraft.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using MinecraftClient.Inventory; using MinecraftClient.Mapping; diff --git a/MinecraftClient/ChatBots/AutoFishing.cs b/MinecraftClient/ChatBots/AutoFishing.cs index 2c8719b8..7c1a5c72 100644 --- a/MinecraftClient/ChatBots/AutoFishing.cs +++ b/MinecraftClient/ChatBots/AutoFishing.cs @@ -3,7 +3,6 @@ using MinecraftClient.Inventory; using MinecraftClient.Mapping; using Tomlet.Attributes; using static MinecraftClient.ChatBots.AutoFishing.Configs; -using static MinecraftClient.ChatBots.AutoFishing.Configs.LocationConfig; namespace MinecraftClient.ChatBots { diff --git a/MinecraftClient/ChatBots/AutoRelog.cs b/MinecraftClient/ChatBots/AutoRelog.cs index 90ec350c..d47f04f5 100644 --- a/MinecraftClient/ChatBots/AutoRelog.cs +++ b/MinecraftClient/ChatBots/AutoRelog.cs @@ -1,5 +1,4 @@ using System; -using System.Text; using Tomlet.Attributes; namespace MinecraftClient.ChatBots diff --git a/MinecraftClient/ChatBots/ChatLog.cs b/MinecraftClient/ChatBots/ChatLog.cs index 7031255d..041b58cb 100644 --- a/MinecraftClient/ChatBots/ChatLog.cs +++ b/MinecraftClient/ChatBots/ChatLog.cs @@ -1,7 +1,6 @@ using System; using System.IO; using Tomlet.Attributes; -using static System.Net.WebRequestMethods; namespace MinecraftClient.ChatBots { diff --git a/MinecraftClient/ChatBots/PlayerListLogger.cs b/MinecraftClient/ChatBots/PlayerListLogger.cs index 3ab8364d..e1266d92 100644 --- a/MinecraftClient/ChatBots/PlayerListLogger.cs +++ b/MinecraftClient/ChatBots/PlayerListLogger.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Text; using Tomlet.Attributes; diff --git a/MinecraftClient/ChatBots/ScriptScheduler.cs b/MinecraftClient/ChatBots/ScriptScheduler.cs index 21c22551..a977874d 100644 --- a/MinecraftClient/ChatBots/ScriptScheduler.cs +++ b/MinecraftClient/ChatBots/ScriptScheduler.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading.Tasks; using Tomlet.Attributes; using static MinecraftClient.ChatBots.ScriptScheduler.Configs; diff --git a/MinecraftClient/DefaultConfigResource.Designer.cs b/MinecraftClient/DefaultConfigResource.Designer.cs index 39a2ddf8..4293b373 100644 --- a/MinecraftClient/DefaultConfigResource.Designer.cs +++ b/MinecraftClient/DefaultConfigResource.Designer.cs @@ -273,15 +273,16 @@ namespace MinecraftClient { /// /// Looks up a localized string similar to [mcc] ///# Messages from MCC itself - ///mcc.help_us_translate=Help us translate MCC: https://mccteam.github.io/guide/translation.html + ///mcc.help_us_translate=Help us translate MCC: {0} ///mcc.run_with_default_settings=\nMCC is running with default settings. ///mcc.settings_generated=§cSettings file MinecraftClient.ini has been generated. + ///mcc.has_update=§eNew version of MCC available: {0} ///mcc.login=Login : ///mcc.login_basic_io=Please type the username or email of your choice. ///mcc.password=Password : ///mcc.password_basic_io=Please type the password for {0}. ///mcc.password_hidden=Password : {0} - ///mcc.offline=§8You chose [rest of string was truncated]";. + ///mcc.offline=§8Yo [rest of string was truncated]";. /// internal static string Translation_en { get { @@ -354,10 +355,11 @@ namespace MinecraftClient { /// /// Looks up a localized string similar to [mcc] ///# Messages from MCC itself - ///mcc.help_us_translate=帮助我们翻译MCC:https://mccteam.github.io/guide/translation.html + ///mcc.help_us_translate=帮助我们翻译MCC:{0} ///mcc.run_with_default_settings=\nMCC正在使用默认配置运行。 ///mcc.settings_generated=§c配置文件 MinecraftClient.ini 已经生成。 - ///mcc.login=登录: + ///mcc.has_update=§e新版本的MCC已经推出:{0} + ///mcc.login=账户名: ///mcc.login_basic_io=请输入用户名或邮箱。 ///mcc.password=密码: ///mcc.password_basic_io=请输入{0}的密码。 @@ -366,7 +368,7 @@ namespace MinecraftClient { ///mcc.session_invalid=§8缓存无效或已过期。 ///mcc.session_valid=§8{0}的缓存仍然有效。 ///mcc.profile_key_invalid=§8缓存的聊天签名密钥需要刷新。 - ///mcc.profile_key_valid=§8{0}的聊天 [rest of string was truncated]";. + ///mcc.profile_key_valid=§8{0}的聊天签名密钥缓存仍然有效 [rest of string was truncated]";. /// internal static string Translation_zh_Hans { get { diff --git a/MinecraftClient/Inventory/Item.cs b/MinecraftClient/Inventory/Item.cs index 6d21a5fb..37e72017 100644 --- a/MinecraftClient/Inventory/Item.cs +++ b/MinecraftClient/Inventory/Item.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using System.Text; -using System.Linq; using System.Globalization; +using System.Linq; +using System.Text; namespace MinecraftClient.Inventory { diff --git a/MinecraftClient/Mapping/RaycastHelper.cs b/MinecraftClient/Mapping/RaycastHelper.cs index 764d55e1..a1afecef 100644 --- a/MinecraftClient/Mapping/RaycastHelper.cs +++ b/MinecraftClient/Mapping/RaycastHelper.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using MinecraftClient.Protocol; namespace MinecraftClient.Mapping { diff --git a/MinecraftClient/Program.cs b/MinecraftClient/Program.cs index 7b8aea5c..734fd420 100644 --- a/MinecraftClient/Program.cs +++ b/MinecraftClient/Program.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Text; @@ -18,11 +19,9 @@ using MinecraftClient.Protocol.Keys; using MinecraftClient.Protocol.Session; using MinecraftClient.WinAPI; using Tomlet; -using Tomlet.Models; using static MinecraftClient.Settings; -using static MinecraftClient.Settings.MainConfigHealper.MainConfig.GeneralConfig; using static MinecraftClient.Settings.MainConfigHealper.MainConfig.AdvancedConfig; -using static System.Net.Mime.MediaTypeNames; +using static MinecraftClient.Settings.MainConfigHealper.MainConfig.GeneralConfig; namespace MinecraftClient { @@ -49,11 +48,10 @@ namespace MinecraftClient public const string MCLowestVersion = "1.4.6"; public const string MCHighestVersion = "1.19.2"; public static readonly string? BuildInfo = null; - private const string TranslationUrl = "https://mccteam.github.io/guide/contibuting.html#translations"; private static Tuple? offlinePrompt = null; private static bool useMcVersionOnce = false; - private static string? settingsIniPath = null; + private static string settingsIniPath = "MinecraftClient.ini"; /// /// The main entry point of Minecraft Console Client @@ -114,7 +112,6 @@ namespace MinecraftClient //Process ini configuration file bool needWriteDefaultSetting, newlyGenerated = false; - settingsIniPath = "MinecraftClient.ini"; if (args.Length >= 1 && File.Exists(args[0]) && Settings.ToLowerIfNeed(Path.GetExtension(args[0])) == ".ini") { needWriteDefaultSetting = Settings.LoadFromFile(args[0]); @@ -140,7 +137,7 @@ namespace MinecraftClient (string gameLanguage, string[] langList) = Translations.GetTranslationPriority(); Translations.LoadTranslationFile(langList); Config.Main.Advanced.Language = gameLanguage; - Settings.WriteToFile("MinecraftClient.ini", false); + WriteBackSettings(false); if (newlyGenerated) ConsoleIO.WriteLineFormatted(Translations.TryGet("mcc.settings_generated")); ConsoleIO.WriteLine(Translations.TryGet("mcc.run_with_default_settings")); @@ -150,8 +147,15 @@ namespace MinecraftClient //Load external translation file. Should be called AFTER settings loaded Translations.LoadTranslationFile(Translations.GetTranslationPriority(Config.Main.Advanced.Language)); if (!Config.Main.Advanced.Language.StartsWith("en")) - ConsoleIO.WriteLine(Translations.TryGet("mcc.help_us_translate", TranslationUrl)); - Settings.WriteToFile("MinecraftClient.ini", true); // format + ConsoleIO.WriteLine(Translations.TryGet("mcc.help_us_translate", Settings.TranslationDocUrl)); + WriteBackSettings(true); // format + } + + bool needPromptUpdate = true; + if (Settings.CheckUpdate(Config.Head.CurrentVersion, Config.Head.LatestVersion)) + { + needPromptUpdate = false; + ConsoleIO.WriteLineFormatted(Translations.TryGet("mcc.has_update", Settings.GithubLatestReleaseUrl)); } //Other command-line arguments @@ -256,6 +260,41 @@ namespace MinecraftClient } } + // Check for updates + Task.Run(() => + { + HttpClientHandler httpClientHandler = new() { AllowAutoRedirect = false }; + HttpClient httpClient = new(httpClientHandler); + Task? httpWebRequest = null; + try + { + httpWebRequest = httpClient.GetAsync(Settings.GithubLatestReleaseUrl, HttpCompletionOption.ResponseHeadersRead); + httpWebRequest.Wait(); + HttpResponseMessage res = httpWebRequest.Result; + if (res.Headers.Location != null) + { + Match match = Regex.Match(res.Headers.Location.ToString(), Settings.GithubReleaseUrl + @"/tag/(\d{4})(\d{2})(\d{2})-(\d+)"); + if (match.Success && match.Groups.Count == 5) + { + string year = match.Groups[1].Value, month = match.Groups[2].Value, day = match.Groups[3].Value, run = match.Groups[4].Value; + string latestVersion = string.Format("GitHub build {0}, built on {1}-{2}-{3}", run, year, month, day); + if (needPromptUpdate) + if (Settings.CheckUpdate(Config.Head.CurrentVersion, Config.Head.LatestVersion)) + ConsoleIO.WriteLineFormatted(Translations.TryGet("mcc.has_update", Settings.GithubLatestReleaseUrl)); + if (latestVersion != Config.Head.LatestVersion) + { + Config.Head.LatestVersion = latestVersion; + WriteBackSettings(false); + } + } + } + } + catch (Exception) { } + finally { httpWebRequest?.Dispose(); } + httpClient.Dispose(); + httpClientHandler.Dispose(); + }); + if (Config.Main.Advanced.ConsoleTitle != "") { InternalConfig.Username = "New Window"; @@ -573,9 +612,16 @@ namespace MinecraftClient /// public static void ReloadSettings() { - if (settingsIniPath != null) - if(Settings.LoadFromFile(settingsIniPath)) - ConsoleIO.WriteLine(Translations.TryGet("config.loading", settingsIniPath)); + if(Settings.LoadFromFile(settingsIniPath)) + ConsoleIO.WriteLine(Translations.TryGet("config.loading", settingsIniPath)); + } + + /// + /// Write-back settings + /// + public static void WriteBackSettings(bool enableBackup = true) + { + Settings.WriteToFile(settingsIniPath, enableBackup); } /// @@ -602,11 +648,9 @@ namespace MinecraftClient public static void DoExit(int exitcode = 0) { - if (settingsIniPath != null) - { - Settings.WriteToFile(settingsIniPath, true); - ConsoleIO.WriteLineFormatted(Translations.TryGet("config.saving", settingsIniPath)); - } + WriteBackSettings(true); + ConsoleIO.WriteLineFormatted(Translations.TryGet("config.saving", settingsIniPath)); + if (client != null) { client.Disconnect(); ConsoleIO.Reset(); } if (offlinePrompt != null) { offlinePrompt.Item2.Cancel(); offlinePrompt.Item1.Join(); offlinePrompt = null; ConsoleIO.Reset(); } if (Config.Main.Advanced.PlayerHeadAsIcon) { ConsoleIcon.RevertToMCCIcon(); } diff --git a/MinecraftClient/Protocol/ProfileKey/KeysCache.cs b/MinecraftClient/Protocol/ProfileKey/KeysCache.cs index c11ed0aa..b9bfc7f3 100644 --- a/MinecraftClient/Protocol/ProfileKey/KeysCache.cs +++ b/MinecraftClient/Protocol/ProfileKey/KeysCache.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Timers; -using MinecraftClient.Protocol.Session; using static MinecraftClient.Settings; using static MinecraftClient.Settings.MainConfigHealper.MainConfig.AdvancedConfig; diff --git a/MinecraftClient/Proxy/ProxyHandler.cs b/MinecraftClient/Proxy/ProxyHandler.cs index 5d703dad..9bbf56eb 100644 --- a/MinecraftClient/Proxy/ProxyHandler.cs +++ b/MinecraftClient/Proxy/ProxyHandler.cs @@ -1,5 +1,4 @@ -using System; -using System.Net.Sockets; +using System.Net.Sockets; using Starksoft.Aspen.Proxy; using Tomlet.Attributes; diff --git a/MinecraftClient/Resources/lang/en.ini b/MinecraftClient/Resources/lang/en.ini index 3176e207..3bc150ef 100644 --- a/MinecraftClient/Resources/lang/en.ini +++ b/MinecraftClient/Resources/lang/en.ini @@ -3,6 +3,7 @@ mcc.help_us_translate=Help us translate MCC: {0} mcc.run_with_default_settings=\nMCC is running with default settings. mcc.settings_generated=§cSettings file MinecraftClient.ini has been generated. +mcc.has_update=§eNew version of MCC available: {0} mcc.login=Login : mcc.login_basic_io=Please type the username or email of your choice. mcc.password=Password : @@ -654,10 +655,12 @@ bot.testBot.said=Bot: {0} said : {1} config.load=Settings have been loaded from {0} config.load.fail=§cFailed to load settings:§r +config.write.fail=§cFailed to write to settings file {0}§r +config.backup.fail=§cFailed to write to backup file {0}§r config.saving=§aThe current setting is saved as {0} # Head -config.Head=Startup Config File\n\n# New to Minecraft Console Client? See README and sample configuration files here:\n# https://github.com/MCCTeam/Minecraft-Console-Client/tree/master/MinecraftClient/config\n\n# Want to upgrade to a newer version? See https://github.com/MCCTeam/Minecraft-Console-Client/#download +config.Head=Startup Config File\n\n# New to Minecraft Console Client? Check out this document: https://mccteam.github.io/guide/configuration.html\n\n# Want to upgrade to a newer version? See https://github.com/MCCTeam/Minecraft-Console-Client/#download # Main.General config.Main.General.account=Login=Email or Name. Use "-" as password for offline mode. Leave blank to prompt user on startup. diff --git a/MinecraftClient/Resources/lang/zh-Hans.ini b/MinecraftClient/Resources/lang/zh-Hans.ini index c4a249df..c13d96f1 100644 --- a/MinecraftClient/Resources/lang/zh-Hans.ini +++ b/MinecraftClient/Resources/lang/zh-Hans.ini @@ -3,7 +3,8 @@ mcc.help_us_translate=帮助我们翻译MCC:{0} mcc.run_with_default_settings=\nMCC正在使用默认配置运行。 mcc.settings_generated=§c配置文件 MinecraftClient.ini 已经生成。 -mcc.login=登录: +mcc.has_update=§e新版本的MCC已经推出:{0} +mcc.login=账户名: mcc.login_basic_io=请输入用户名或邮箱。 mcc.password=密码: mcc.password_basic_io=请输入{0}的密码。 @@ -536,10 +537,12 @@ bot.testBot.said=Bot:{0}说:{1} config.load=已从 {0} 加载设置。 config.load.fail=§c加载设置时出错:§r +config.write.fail=§保存备份文件({0})时出错:§r +config.backup.fail=§c写入设置文件({0})时出错:§r config.saving=§a当前设置已保存至 {0} # Head -config.Head=启动配置文件\n\n# 对 MCC(Minecraft 命令行客户端)不熟悉?请看 README 和示例配置文件:\n# https://github.com/MCCTeam/Minecraft-Console-Client/tree/master/MinecraftClient/config\n\n# 想升级到较新的版本吗?请访问 https://github.com/MCCTeam/Minecraft-Console-Client/#download +config.Head=启动配置文件\n\n# 对 MCC(Minecraft 命令行客户端)不熟悉?请看这个文档:https://mccteam.github.io/guide/configuration.html\n\n# 想升级到较新的版本吗?请访问 https://github.com/MCCTeam/Minecraft-Console-Client/#download # Main.General config.Main.General.account=Login请填写邮箱或玩家名称。若要以离线模式登录请使用"-"作为密码。若留空则使用交互式登录。 diff --git a/MinecraftClient/Settings.cs b/MinecraftClient/Settings.cs index 51daeb85..aabc6833 100644 --- a/MinecraftClient/Settings.cs +++ b/MinecraftClient/Settings.cs @@ -3,11 +3,9 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; -using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; -using System.Threading; using MinecraftClient.Protocol; using MinecraftClient.Proxy; using Tomlet; @@ -16,6 +14,7 @@ using Tomlet.Models; using static MinecraftClient.Settings.AppVarConfigHelper; using static MinecraftClient.Settings.ChatBotConfigHealper; using static MinecraftClient.Settings.ChatFormatConfigHelper; +using static MinecraftClient.Settings.HeadCommentHealper; using static MinecraftClient.Settings.LoggingConfigHealper; using static MinecraftClient.Settings.MainConfigHealper; using static MinecraftClient.Settings.MainConfigHealper.MainConfig.AdvancedConfig; @@ -27,12 +26,17 @@ namespace MinecraftClient public static class Settings { private const int CommentsAlignPosition = 45; + private readonly static Regex CommentRegex = new(@"^(.*)\s?#\s\$([\w\.]+)\$\s*$$", RegexOptions.Compiled); //Other Settings public static string TranslationsFile_FromMCDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\.minecraft\assets\objects\48\482e0dae05abfa35ab5cb076e41fda77b4fb9a08"; //MC 1.19 en_GB.lang public static string TranslationsFile_Website_Index = "https://piston-meta.mojang.com/v1/packages/b5c7548ddb9e584e84a5f762da5b78211c715a63/1.19.json"; public static string TranslationsFile_Website_Download = "http://resources.download.minecraft.net"; + public const string TranslationDocUrl = "https://mccteam.github.io/guide/contibuting.html#translations"; + public const string GithubReleaseUrl = "https://github.com/MCCTeam/Minecraft-Console-Client/releases"; + public const string GithubLatestReleaseUrl = GithubReleaseUrl + "/latest"; + public static GlobalConfig Config = new(); public static class InternalConfig @@ -54,7 +58,12 @@ namespace MinecraftClient public class GlobalConfig { - public HeadComment Head = new(); + [TomlPrecedingComment("$config.Head$")] + public HeadComment Head + { + get { return HeadCommentHealper.Config; } + set { HeadCommentHealper.Config = value; HeadCommentHealper.Config.OnSettingUpdate(); } + } public MainConfig Main { @@ -110,13 +119,6 @@ namespace MinecraftClient set { ChatBotConfigHealper.Config = value; } } - [TomlDoNotInlineObject] - public class HeadComment - { - [TomlPrecedingComment("$config.Head$")] - [TomlProperty("Current Version (Do not edit this)")] - public string Version { get; set; } = Program.BuildInfo ?? Program.MCHighestVersion; - } } public static bool LoadFromFile(string filepath) @@ -159,10 +161,10 @@ namespace MinecraftClient StringBuilder newConfig = new(); foreach (string line in tomlList) { - Match match = Regex.Match(line, @"^(.*)\s?#\s\$(.+)\$\s*$"); - if (match.Success && match.Groups.Count == 3) + Match matchComment = CommentRegex.Match(line); + if (matchComment.Success && matchComment.Groups.Count == 3) { - string config = match.Groups[1].Value, comment = match.Groups[2].Value; + string config = matchComment.Groups[1].Value, comment = matchComment.Groups[2].Value; if (config.Length > 0) newConfig.Append(config).Append(' ', Math.Max(1, CommentsAlignPosition - config.Length) - 1); newConfig.Append("# ").AppendLine(Translations.TryGet(comment).ReplaceLineEndings()); @@ -188,9 +190,28 @@ namespace MinecraftClient if (needUpdate) { + bool backupSuccessed = true; if (backupOldFile && File.Exists(filepath)) - File.Copy(filepath, Path.ChangeExtension(filepath, ".backup.ini"), true); - File.WriteAllText(filepath, newConfigStr); + { + string backupFilePath = Path.ChangeExtension(filepath, ".backup.ini"); + try { File.Copy(filepath, backupFilePath, true); } + catch (Exception ex) + { + backupSuccessed = false; + ConsoleIO.WriteLineFormatted(Translations.TryGet("config.backup.fail", backupFilePath)); + ConsoleIO.WriteLine(ex.Message); + } + } + + if (backupSuccessed) + { + try { File.WriteAllText(filepath, newConfigStr); } + catch (Exception ex) + { + ConsoleIO.WriteLineFormatted(Translations.TryGet("config.write.fail", filepath)); + ConsoleIO.WriteLine(ex.Message); + } + } } } @@ -239,6 +260,27 @@ namespace MinecraftClient } } + public static class HeadCommentHealper + { + public static HeadComment Config = new(); + + [TomlDoNotInlineObject] + public class HeadComment + { + [TomlProperty("Current Version")] + public string CurrentVersion { get; set; } = Program.BuildInfo ?? Program.MCHighestVersion; + + [TomlProperty("Latest Version")] + public string LatestVersion { get; set; } = "Unknown"; + + public void OnSettingUpdate() + { + CurrentVersion = Program.BuildInfo ?? Program.MCHighestVersion; + LatestVersion ??= "Unknown"; + } + } + } + public static class MainConfigHealper { public static MainConfig Config = new(); @@ -273,7 +315,7 @@ namespace MinecraftClient /// True if the server IP was valid and loaded, false otherwise public bool SetServerIP(ServerInfoConfig serverInfo, bool checkAlias) { - string serverStr = serverInfo.Host.ToLower(); + string serverStr = ToLowerIfNeed(serverInfo.Host); string[] sip = serverStr.Split(new[] { ":", ":" }, StringSplitOptions.None); string host = sip[0]; ushort port = 25565; @@ -1069,6 +1111,61 @@ namespace MinecraftClient return str; } } + + public static bool CheckUpdate(string? current, string? latest) + { + if (current == null || latest == null) + return false; + Regex reg = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s(\d{4})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{2}).*"); + Regex reg2 = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s\w+\s(\d{2})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{4}).*"); + + DateTime? curTime = null, latestTime = null; + + Match curMatch = reg.Match(current); + if (curMatch.Success && curMatch.Groups.Count == 5) + { + try { curTime = new(int.Parse(curMatch.Groups[2].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[4].Value)); } + catch { curTime = null; } + } + if (curTime == null) + { + curMatch = reg2.Match(current); + try { curTime = new(int.Parse(curMatch.Groups[4].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[2].Value)); } + catch { curTime = null; } + } + if (curTime == null) + return false; + + Match latestMatch = reg.Match(latest); + if (latestMatch.Success && latestMatch.Groups.Count == 5) + { + try { latestTime = new(int.Parse(latestMatch.Groups[2].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[4].Value)); } + catch { latestTime = null; } + } + if (latestTime == null) + { + latestMatch = reg2.Match(latest); + try { latestTime = new(int.Parse(latestMatch.Groups[4].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[2].Value)); } + catch { latestTime = null; } + } + if (latestTime == null) + return false; + + int curBuildId, latestBuildId; + try + { + curBuildId = int.Parse(curMatch.Groups[1].Value); + latestBuildId = int.Parse(latestMatch.Groups[1].Value); + } + catch { return false; } + + if (latestTime > curTime) + return true; + else if (latestTime >= curTime && latestBuildId > curBuildId) + return true; + else + return false; + } } public static class InternalCmdCharTypeExtensions diff --git a/MinecraftClient/Translations.cs b/MinecraftClient/Translations.cs index 81776efb..3d79003e 100644 --- a/MinecraftClient/Translations.cs +++ b/MinecraftClient/Translations.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; diff --git a/MinecraftClient/WinAPI/ExitCleanUp.cs b/MinecraftClient/WinAPI/ExitCleanUp.cs index 0c68d04c..98f93fe1 100644 --- a/MinecraftClient/WinAPI/ExitCleanUp.cs +++ b/MinecraftClient/WinAPI/ExitCleanUp.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Threading; namespace MinecraftClient.WinAPI {