Add update detection

This commit is contained in:
BruceChen 2022-10-06 14:53:05 +08:00
parent 6f456cb1d7
commit bdcc22b465
18 changed files with 193 additions and 65 deletions

View file

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using MinecraftClient.Mapping;
using Tomlet.Attributes;

View file

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MinecraftClient.Inventory;
using MinecraftClient.Mapping;

View file

@ -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
{

View file

@ -1,5 +1,4 @@
using System;
using System.Text;
using Tomlet.Attributes;
namespace MinecraftClient.ChatBots

View file

@ -1,7 +1,6 @@
using System;
using System.IO;
using Tomlet.Attributes;
using static System.Net.WebRequestMethods;
namespace MinecraftClient.ChatBots
{

View file

@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Text;
using Tomlet.Attributes;

View file

@ -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;

View file

@ -273,15 +273,16 @@ namespace MinecraftClient {
/// <summary>
/// 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]&quot;;.
///mcc.offline=§8Yo [rest of string was truncated]&quot;;.
/// </summary>
internal static string Translation_en {
get {
@ -354,10 +355,11 @@ namespace MinecraftClient {
/// <summary>
/// Looks up a localized string similar to [mcc]
///# Messages from MCC itself
///mcc.help_us_translate=帮助我们翻译MCChttps://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]&quot;;.
///mcc.profile_key_valid=§8{0}的聊天签名密钥缓存仍然有效 [rest of string was truncated]&quot;;.
/// </summary>
internal static string Translation_zh_Hans {
get {

View file

@ -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
{

View file

@ -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
{

View file

@ -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<Thread, CancellationTokenSource>? offlinePrompt = null;
private static bool useMcVersionOnce = false;
private static string? settingsIniPath = null;
private static string settingsIniPath = "MinecraftClient.ini";
/// <summary>
/// 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<HttpResponseMessage>? 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
/// </summary>
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));
}
/// <summary>
/// Write-back settings
/// </summary>
public static void WriteBackSettings(bool enableBackup = true)
{
Settings.WriteToFile(settingsIniPath, enableBackup);
}
/// <summary>
@ -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(); }

View file

@ -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;

View file

@ -1,5 +1,4 @@
using System;
using System.Net.Sockets;
using System.Net.Sockets;
using Starksoft.Aspen.Proxy;
using Tomlet.Attributes;

View file

@ -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.

View file

@ -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# 对 MCCMinecraft 命令行客户端)不熟悉?请看 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# 对 MCCMinecraft 命令行客户端)不熟悉?请看这个文档https://mccteam.github.io/guide/configuration.html\n\n# 想升级到较新的版本吗?请访问 https://github.com/MCCTeam/Minecraft-Console-Client/#download
# Main.General
config.Main.General.account=Login请填写邮箱或玩家名称。若要以离线模式登录请使用"-"作为密码。若留空则使用交互式登录。

View file

@ -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
/// <returns>True if the server IP was valid and loaded, false otherwise</returns>
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

View file

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;

View file

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace MinecraftClient.WinAPI
{