From c2e87be8267e4d6cd5d36fe8bfbdd4dab4b52bcc Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 6 Apr 2020 22:51:07 +0800 Subject: [PATCH 01/39] add http/2 support --- pmcenter/BotCommands/CheckUpdateCommand.cs | 2 +- pmcenter/BotCommands/SwitchLangCodeCommand.cs | 26 ++++++------- pmcenter/BotCommands/SwitchLangCommand.cs | 9 ++--- pmcenter/BotCommands/UpdateCommand.cs | 39 +++++++++---------- pmcenter/CommandLines/UpdateCmdLine.cs | 34 ++++++++-------- .../Configurations/Conf.CheckForUpdates.cs | 18 --------- pmcenter/EventHandlers/CtrlCHandler.cs | 2 +- .../NetworkTest/Methods.TestConnectivity.cs | 13 ++++--- .../NetworkTest/Methods.TestLatency.cs | 19 ++++----- .../Threads/Methods.ThrUpdateChecker.cs | 2 +- pmcenter/Vars.cs | 7 ++++ pmcenter/pmcenter.csproj | 2 +- 12 files changed, 78 insertions(+), 95 deletions(-) delete mode 100644 pmcenter/Configurations/Conf.CheckForUpdates.cs diff --git a/pmcenter/BotCommands/CheckUpdateCommand.cs b/pmcenter/BotCommands/CheckUpdateCommand.cs index df8617f..33d4c7a 100644 --- a/pmcenter/BotCommands/CheckUpdateCommand.cs +++ b/pmcenter/BotCommands/CheckUpdateCommand.cs @@ -16,7 +16,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - var Latest = Conf.CheckForUpdates(); + var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); var CurrentLocalizedIndex = Conf.GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); if (Conf.IsNewerVersionAvailable(Latest)) { diff --git a/pmcenter/BotCommands/SwitchLangCodeCommand.cs b/pmcenter/BotCommands/SwitchLangCodeCommand.cs index 1859df8..dc4c26c 100644 --- a/pmcenter/BotCommands/SwitchLangCodeCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCodeCommand.cs @@ -1,11 +1,11 @@ using Newtonsoft.Json; using System; using System.IO; -using System.Net; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.H2Helper; namespace pmcenter.Commands { @@ -19,12 +19,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { string Reply; string ListJSONString; + Conf.LocaleList LocaleList; // try to get locale list - using (var ListDownloader = new WebClient()) - { - ListJSONString = await ListDownloader.DownloadStringTaskAsync(Vars.LocaleMapURL.Replace("$channel", Vars.CurrentConf.UpdateChannel)).ConfigureAwait(false); - } - Conf.LocaleList LocaleList = JsonConvert.DeserializeObject(ListJSONString); + ListJSONString = await GetStringAsync(new Uri(Vars.LocaleMapURL.Replace("$channel", Vars.CurrentConf.UpdateChannel))).ConfigureAwait(false); + LocaleList = JsonConvert.DeserializeObject(ListJSONString); if (!update.Message.Text.Contains(" ")) { var ListString = ""; @@ -44,14 +42,14 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) // update configurations Vars.CurrentConf.LangURL = Mirror.LocaleFileURL.Replace("$channel", Vars.CompileChannel); // start downloading - using (var Downloader = new WebClient()) - { - _ = await Conf.SaveConf(IsAutoSave: true).ConfigureAwait(false); - await Downloader.DownloadFileTaskAsync( - new Uri(Vars.CurrentConf.LangURL), - Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); - } + _ = await Conf.SaveConf(IsAutoSave: true).ConfigureAwait(false); + await DownloadFileAsync( + new Uri(Vars.CurrentConf.LangURL), + Path.Combine( + Vars.AppDirectory, + "pmcenter_locale.json" + ) + ).ConfigureAwait(false); // reload configurations _ = await Conf.ReadConf().ConfigureAwait(false); _ = await Lang.ReadLang().ConfigureAwait(false); diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index 860a582..8473cc3 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -5,7 +5,7 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; +using static pmcenter.Methods.H2Helper; namespace pmcenter.Commands { @@ -32,13 +32,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) Vars.CurrentConf.LangURL = LangURL; // save conf _ = await Conf.SaveConf(IsAutoSave: true); - using (var Downloader = new WebClient()) - { - await Downloader.DownloadFileTaskAsync( + await DownloadFileAsync( new Uri(LangURL), Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); - } + ).ConfigureAwait(false); // reload configurations _ = await Conf.ReadConf().ConfigureAwait(false); diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index d9a5f12..462dcf5 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -7,6 +7,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.H2Helper; namespace pmcenter.Commands { @@ -20,7 +21,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - var Latest = Conf.CheckForUpdates(); + var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); var CurrentLocalizedIndex = Conf.GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); if (Conf.IsNewerVersionAvailable(Latest)) { @@ -45,29 +46,27 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) // download compiled package Log("Starting update download... (pmcenter_update.zip)", "BOT"); Log($"From address: {Latest.UpdateCollection[CurrentLocalizedIndex].UpdateArchiveAddress}", "BOT"); - using (var Downloader = new WebClient()) + await DownloadFileAsync( + new Uri(Latest.UpdateCollection[CurrentLocalizedIndex].UpdateArchiveAddress), + Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") + ).ConfigureAwait(false); + Log("Download complete. Extracting...", "BOT"); + using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) { - await Downloader.DownloadFileTaskAsync( - new Uri(Latest.UpdateCollection[CurrentLocalizedIndex].UpdateArchiveAddress), - Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")).ConfigureAwait(false); - Log("Download complete. Extracting...", "BOT"); - using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) + foreach (ZipArchiveEntry Entry in Zip.Entries) { - foreach (ZipArchiveEntry Entry in Zip.Entries) - { - Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "BOT"); - Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); - } - } - if (Vars.CurrentConf.AutoLangUpdate) - { - Log("Starting automatic language file update...", "BOT"); - await Downloader.DownloadFileTaskAsync( - new Uri(Vars.CurrentConf.LangURL), - Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); + Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "BOT"); + Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); } } + if (Vars.CurrentConf.AutoLangUpdate) + { + Log("Starting automatic language file update...", "BOT"); + await DownloadFileAsync( + new Uri(Vars.CurrentConf.LangURL), + Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") + ).ConfigureAwait(false); + } Log("Cleaning up temporary files...", "BOT"); System.IO.File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); _ = await botClient.SendTextMessageAsync( diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index f390e9f..d3d90c8 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.IO.Compression; -using System.Net; using System.Threading.Tasks; +using static pmcenter.Methods.H2Helper; using static pmcenter.Methods; @@ -17,32 +17,30 @@ public async Task Process() Log($"Application version: {Vars.AppVer.ToString()}", "CMD"); Log("Checking for updates...", "CMD"); Log("Custom update channels and languages are currently unsupported in command line mode, will use \"master\" channel with English.", "CMD"); - var Latest = Conf.CheckForUpdates(); + var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); if (Conf.IsNewerVersionAvailable(Latest)) { Log($"Newer version found: {Latest.Latest}, main changes:\n{Latest.UpdateCollection[0].Details}", "CMD"); Log("Updating...", "CMD"); Log("Starting update download... (pmcenter_update.zip)", "CMD"); - using (var Downloader = new WebClient()) + await DownloadFileAsync( + new Uri(Vars.UpdateArchiveURL), + Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") + ).ConfigureAwait(false); + Log("Download complete. Extracting...", "CMD"); + using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) { - await Downloader.DownloadFileTaskAsync( - new Uri(Vars.UpdateArchiveURL), - Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")).ConfigureAwait(false); - Log("Download complete. Extracting...", "CMD"); - using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) + foreach (ZipArchiveEntry Entry in Zip.Entries) { - foreach (ZipArchiveEntry Entry in Zip.Entries) - { - Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "CMD"); - Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); - } + Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "CMD"); + Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); } - Log("Starting language file update...", "CMD"); - await Downloader.DownloadFileTaskAsync( - new Uri(Vars.CurrentConf.LangURL), - Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); } + Log("Starting language file update...", "CMD"); + await DownloadFileAsync( + new Uri(Vars.CurrentConf.LangURL), + Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") + ).ConfigureAwait(false); Log("Cleaning up temporary files...", "CMD"); File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); Log("Update complete.", "CMD"); diff --git a/pmcenter/Configurations/Conf.CheckForUpdates.cs b/pmcenter/Configurations/Conf.CheckForUpdates.cs deleted file mode 100644 index 59607c0..0000000 --- a/pmcenter/Configurations/Conf.CheckForUpdates.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Net; -using Newtonsoft.Json; - -namespace pmcenter -{ - public partial class Conf - { - public static Update2 CheckForUpdates() - { - using (var Downloader = new WebClient()) - { - var Response = Downloader.DownloadString(new Uri(Vars.UpdateInfo2URL.Replace("$channel", Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel))); - return JsonConvert.DeserializeObject(Response); - } - } - } -} \ No newline at end of file diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index ecefddd..3dd1a8e 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -21,7 +21,7 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) return; } Vars.IsCtrlCHandled = true; - Log("Interrupt! pmcenter is exiting..."); + Log("Interrupt! pmcenter is exiting...", Type: LogLevel.WARN); Log("If pmcenter was unresponsive, press Ctrl-C 3 more times."); ExitApp(130); } diff --git a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs index 942c485..b44ee73 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs @@ -6,19 +6,20 @@ namespace pmcenter { public partial class Methods { - public static async Task TestConnectivity(string Target, bool Ignore45 = false) + public static async Task TestConnectivity(string target, bool ignore45 = false) { try { - var Req = WebRequest.CreateHttp(Target); - Req.Timeout = 10000; - _ = await Req.GetResponseAsync().ConfigureAwait(false); + var req = WebRequest.CreateHttp(target); + req.ProtocolVersion = new Version(2, 0); + req.Timeout = 10000; + _ = await req.GetResponseAsync().ConfigureAwait(false); return true; } catch (WebException ex) { - if (ex.Status == WebExceptionStatus.ProtocolError && Ignore45) { return true; } - Log($"Connectivity to {Target} is unavailable: {ex.Message}"); + if (ex.Status == WebExceptionStatus.ProtocolError && ignore45) { return true; } + Log($"Connectivity to {target} is unavailable: {ex.Message}"); return false; } catch (Exception ex) diff --git a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs index 8f99b9a..6d500a9 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs @@ -7,25 +7,26 @@ namespace pmcenter { public partial class Methods { - public static async Task TestLatency(string Target) + public static async Task TestLatency(string target) { - var ReqSW = new Stopwatch(); + var reqSw = new Stopwatch(); try { - var Req = WebRequest.CreateHttp(Target); - ReqSW.Start(); - _ = await Req.GetResponseAsync().ConfigureAwait(false); - ReqSW.Stop(); - return ReqSW.Elapsed; + var req = WebRequest.CreateHttp(target); + reqSw.Start(); + _ = await req.GetResponseAsync().ConfigureAwait(false); + reqSw.Stop(); + return reqSw.Elapsed; } catch (WebException) { - ReqSW.Stop(); - return ReqSW.Elapsed; + reqSw.Stop(); + return reqSw.Elapsed; } catch (Exception ex) { Log($"Latency test failed: {ex.Message}"); + reqSw.Reset(); return new TimeSpan(0); } } diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index c6ba315..05d97df 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -15,7 +15,7 @@ public static async void ThrUpdateChecker() Vars.UpdateCheckerStatus = ThreadStatus.Working; try { - var Latest = Conf.CheckForUpdates(); + var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); var DisNotif = Vars.CurrentConf.DisableNotifications; // Identical with BotProcess.cs, L206. diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 06706c2..1dceae1 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -4,6 +4,8 @@ // Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). */ +//#define BUILT_FOR_GITHUB_RELEASES + using System; using System.Collections.Generic; using System.Diagnostics; @@ -30,6 +32,11 @@ public static class Vars public readonly static string CompileChannel = "master"; #else public readonly static string CompileChannel = "pmcenter-lazer"; +#endif +#if BUILT_FOR_GITHUB_RELEASES + public readonly static bool GitHubReleases = true; +#else + public readonly static bool GitHubReleases = false; #endif // public readonly static long AnonymousChannelID = -1001228946795; // public readonly static string AnonymousChannelTitle = "a user"; diff --git a/pmcenter/pmcenter.csproj b/pmcenter/pmcenter.csproj index 0267928..887903c 100644 --- a/pmcenter/pmcenter.csproj +++ b/pmcenter/pmcenter.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.1 + netcoreapp3.1 pmcenter.Program From 5cbfcefd323065ded3264d83bb4c0e4235678fa0 Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 6 Apr 2020 22:57:49 +0800 Subject: [PATCH 02/39] Oops --- .../Conf.CheckForUpdatesAsync.cs | 20 ++++++++++++++++++ .../Methods.H2Helper.DownloadFileAsync.cs | 19 +++++++++++++++++ .../Methods.H2Helper.GetBytesAsync.cs | 16 ++++++++++++++ .../Methods.H2Helper.GetHttpContentAsync.cs | 21 +++++++++++++++++++ .../Methods.H2Helper.GetStringAsync.cs | 16 ++++++++++++++ 5 files changed, 92 insertions(+) create mode 100644 pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs create mode 100644 pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs create mode 100644 pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs create mode 100644 pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs create mode 100644 pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs diff --git a/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs b/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs new file mode 100644 index 0000000..904600a --- /dev/null +++ b/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs @@ -0,0 +1,20 @@ +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using static pmcenter.Methods.H2Helper; + +namespace pmcenter +{ + public partial class Conf + { + public static async Task CheckForUpdatesAsync() + { + var response = await GetStringAsync( + new Uri( + Vars.UpdateInfo2URL.Replace("$channel", Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel) + ) + ); + return JsonConvert.DeserializeObject(response); + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs new file mode 100644 index 0000000..0eeeed3 --- /dev/null +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -0,0 +1,19 @@ +using System; +using System.IO; +using System.Threading.Tasks; + +namespace pmcenter +{ + public partial class Methods + { + public partial class H2Helper + { + public static async Task DownloadFileAsync(Uri uri, string filename) + { + var bytes = await GetBytesAsync(uri).ConfigureAwait(false); + var fileStream = File.OpenWrite(filename); + await fileStream.WriteAsync(bytes).ConfigureAwait(false); + } + } + } +} diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs new file mode 100644 index 0000000..c61a3af --- /dev/null +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -0,0 +1,16 @@ +using System; +using System.Threading.Tasks; + +namespace pmcenter +{ + public partial class Methods + { + public partial class H2Helper + { + public static async Task GetBytesAsync(Uri uri) + { + return await (await GetHttpContentAsync(uri).ConfigureAwait(false)).ReadAsByteArrayAsync().ConfigureAwait(false); + } + } + } +} diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs new file mode 100644 index 0000000..0dc91d7 --- /dev/null +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs @@ -0,0 +1,21 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; + +namespace pmcenter +{ + public partial class Methods + { + public partial class H2Helper + { + private static async Task GetHttpContentAsync(Uri uri) + { + var client = new HttpClient() { DefaultRequestVersion = new Version(2, 0) }; + using (var response = await client.GetAsync(uri).ConfigureAwait(false)) + { + return response.Content; + } + } + } + } +} diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs new file mode 100644 index 0000000..9bade0c --- /dev/null +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -0,0 +1,16 @@ +using System; +using System.Threading.Tasks; + +namespace pmcenter +{ + public partial class Methods + { + public partial class H2Helper + { + public static async Task GetStringAsync(Uri uri) + { + return await (await GetHttpContentAsync(uri).ConfigureAwait(false)).ReadAsStringAsync().ConfigureAwait(false); + } + } + } +} From 0e3016a345462a9bee39a6df518cbad7924b2e60 Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 6 Apr 2020 23:18:24 +0800 Subject: [PATCH 03/39] dices! (updated NuGet package too) --- pmcenter/BotCommands/InfoCommand.cs | 63 ++++++++++++++++------------- pmcenter/pmcenter.csproj | 2 +- 2 files changed, 36 insertions(+), 29 deletions(-) diff --git a/pmcenter/BotCommands/InfoCommand.cs b/pmcenter/BotCommands/InfoCommand.cs index 5c54720..4b28c10 100644 --- a/pmcenter/BotCommands/InfoCommand.cs +++ b/pmcenter/BotCommands/InfoCommand.cs @@ -18,80 +18,87 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { return false; } + var targetMessage = update.Message.ReplyToMessage; var sb = new StringBuilder("ℹ *Message Info*\n📩 *Sender*: ["); if (Vars.CurrentConf.UseUsernameInMsgInfo) { - sb.Append(update.Message.ReplyToMessage.ForwardFrom.FirstName); + sb.Append(targetMessage.ForwardFrom.FirstName); sb.Append(" "); - sb.Append(update.Message.ReplyToMessage.ForwardFrom.LastName); + sb.Append(targetMessage.ForwardFrom.LastName); } else { sb.Append("Here"); } sb.Append("](tg://user?id="); - sb.Append(update.Message.ReplyToMessage.ForwardFrom.Id); + sb.Append(targetMessage.ForwardFrom.Id); sb.Append(")\n👤 User ID: `"); - sb.Append(update.Message.ReplyToMessage.ForwardFrom.Id); + sb.Append(targetMessage.ForwardFrom.Id); sb.Append("`\n🌐 Language: `"); - sb.Append(update.Message.ReplyToMessage.ForwardFrom.LanguageCode); + sb.Append(targetMessage.ForwardFrom.LanguageCode); sb.Append("`\n⌚ Forward Time: `"); - sb.Append(update.Message.ReplyToMessage.ForwardDate.ToString()); + sb.Append(targetMessage.ForwardDate.ToString()); sb.Append("`\n🆔 Message ID: `"); - sb.Append(update.Message.ReplyToMessage.MessageId); + sb.Append(targetMessage.MessageId); sb.Append("`"); sb.Append("\n\n➕ *Additional Info*"); - sb.Append("\n📼 Message Type: " + update.Message.ReplyToMessage.Type.ToString()); - if (update.Message.ReplyToMessage.Document != null) + sb.Append("\n📼 Message Type: " + targetMessage.Type.ToString()); + if (targetMessage.Document != null) { sb.Append("\n📛 File Name: `"); - sb.Append(update.Message.ReplyToMessage.Document.FileName); + sb.Append(targetMessage.Document.FileName); sb.Append("`\n📄 File ID: `"); - sb.Append(update.Message.ReplyToMessage.Document.FileId); + sb.Append(targetMessage.Document.FileId); sb.Append("`\n🗜 File Size: `"); - sb.Append(update.Message.ReplyToMessage.Document.FileSize); + sb.Append(targetMessage.Document.FileSize); sb.Append("`\n📖 MIME Type: `"); - sb.Append(update.Message.ReplyToMessage.Document.MimeType); + sb.Append(targetMessage.Document.MimeType); sb.Append("`"); } - else if (update.Message.ReplyToMessage.Location != null) + else if (targetMessage.Location != null) { sb.Append("\n🌐 Latitude: `"); - sb.Append(update.Message.ReplyToMessage.Location.Latitude); + sb.Append(targetMessage.Location.Latitude); sb.Append("`\n🌐 Longitude: `"); - sb.Append(update.Message.ReplyToMessage.Location.Longitude); + sb.Append(targetMessage.Location.Longitude); sb.Append("`"); } - else if (update.Message.ReplyToMessage.Sticker != null) + else if (targetMessage.Sticker != null) { sb.Append("\n😶 Emoji: `"); - sb.Append(update.Message.ReplyToMessage.Sticker.Emoji); + sb.Append(targetMessage.Sticker.Emoji); sb.Append("`\n📄 File ID: `"); - sb.Append(update.Message.ReplyToMessage.Sticker.FileId); + sb.Append(targetMessage.Sticker.FileId); sb.Append("`"); } - else if (update.Message.ReplyToMessage.Audio != null) + else if (targetMessage.Audio != null) { sb.Append("\n📄 File ID: `"); - sb.Append(update.Message.ReplyToMessage.Audio.FileId); + sb.Append(targetMessage.Audio.FileId); sb.Append("`\n🗜 File Size: `"); - sb.Append(update.Message.ReplyToMessage.Audio.FileSize); + sb.Append(targetMessage.Audio.FileSize); sb.Append("`\n📖 MIME Type: `"); - sb.Append(update.Message.ReplyToMessage.Audio.MimeType); + sb.Append(targetMessage.Audio.MimeType); sb.Append("`\n⏳ Duration(secs): `"); - sb.Append(update.Message.ReplyToMessage.Audio.Duration); + sb.Append(targetMessage.Audio.Duration); sb.Append("`"); } - else if (update.Message.ReplyToMessage.Photo != null) + else if (targetMessage.Photo != null) { sb.Append("\n📄 File ID: `"); - sb.Append(update.Message.ReplyToMessage.Photo[0].FileId); + sb.Append(targetMessage.Photo[0].FileId); sb.Append("`\n🗜 File Size: `"); - sb.Append(update.Message.ReplyToMessage.Photo[0].FileSize); + sb.Append(targetMessage.Photo[0].FileSize); sb.Append("`"); } - sb.Append("\n\n_Additional information is available for a limited set of message types, including: Audios, Documents(Files), Locations, Photos and Stickers._"); + else if (targetMessage.Dice != null) + { + sb.Append("\n🎲 Dice: `"); + sb.Append(targetMessage.Dice.Value); + sb.Append("`"); + } + sb.Append("\n\n_Additional information is available for a limited set of message types, including: Audios, Documents(Files), Dices, Locations, Photos and Stickers._"); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, diff --git a/pmcenter/pmcenter.csproj b/pmcenter/pmcenter.csproj index 887903c..8eebe17 100644 --- a/pmcenter/pmcenter.csproj +++ b/pmcenter/pmcenter.csproj @@ -9,7 +9,7 @@ - + From b1104a83781df3a92a096e282c64dc1c115a493b Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 6 Apr 2020 23:37:30 +0800 Subject: [PATCH 04/39] fix h2 disposal issue --- .../Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs | 2 ++ pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs | 5 ++++- .../H2Helper/Methods.H2Helper.GetHttpContentAsync.cs | 6 ++---- .../Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs | 5 ++++- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs index 0eeeed3..faa860d 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -13,6 +13,8 @@ public static async Task DownloadFileAsync(Uri uri, string filename) var bytes = await GetBytesAsync(uri).ConfigureAwait(false); var fileStream = File.OpenWrite(filename); await fileStream.WriteAsync(bytes).ConfigureAwait(false); + await fileStream.FlushAsync(); + fileStream.Close(); } } } diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs index c61a3af..9586943 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -9,7 +9,10 @@ public partial class H2Helper { public static async Task GetBytesAsync(Uri uri) { - return await (await GetHttpContentAsync(uri).ConfigureAwait(false)).ReadAsByteArrayAsync().ConfigureAwait(false); + using (var content = await GetHttpContentAsync(uri).ConfigureAwait(false)) + { + return await content.ReadAsByteArrayAsync().ConfigureAwait(false); + } } } } diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs index 0dc91d7..91d3220 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs @@ -11,10 +11,8 @@ public partial class H2Helper private static async Task GetHttpContentAsync(Uri uri) { var client = new HttpClient() { DefaultRequestVersion = new Version(2, 0) }; - using (var response = await client.GetAsync(uri).ConfigureAwait(false)) - { - return response.Content; - } + var response = await client.GetAsync(uri).ConfigureAwait(false); + return response.Content; } } } diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs index 9bade0c..2ba0195 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -9,7 +9,10 @@ public partial class H2Helper { public static async Task GetStringAsync(Uri uri) { - return await (await GetHttpContentAsync(uri).ConfigureAwait(false)).ReadAsStringAsync().ConfigureAwait(false); + using (var content = await GetHttpContentAsync(uri).ConfigureAwait(false)) + { + return await content.ReadAsStringAsync().ConfigureAwait(false); + } } } } From 74c348bd9b9a5574f48f18d731c19730d31d4002 Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Tue, 7 Apr 2020 14:46:21 +0800 Subject: [PATCH 05/39] update log class --- pmcenter/EventHandlers/CtrlCHandler.cs | 6 +- .../Methods/Methods.CheckNetCoreVersion.cs | 6 +- pmcenter/Methods/Methods.GetNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.Log.cs | 72 +++++++------------ pmcenter/Methods/Methods.LogMode.cs | 14 ++++ pmcenter/Vars.cs | 2 +- 6 files changed, 47 insertions(+), 55 deletions(-) create mode 100644 pmcenter/Methods/Methods.LogMode.cs diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index 3dd1a8e..a3cab89 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -10,18 +10,18 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) Vars.CtrlCCounter++; if (Vars.CtrlCCounter > 3) { - Log("More than 3 interrupts has received, terminating...", Type: LogLevel.WARN); + Log("More than 3 interrupts has received, terminating...", LogLevel.WARN); Environment.Exit(137); } if (Vars.IsCtrlCHandled) return; if (Vars.CurrentConf.IgnoreKeyboardInterrupt) { - Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", Type: LogLevel.WARN); + Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", LogLevel.WARN); e.Cancel = true; return; } Vars.IsCtrlCHandled = true; - Log("Interrupt! pmcenter is exiting...", Type: LogLevel.WARN); + Log("Interrupt! pmcenter is exiting...", LogLevel.WARN); Log("If pmcenter was unresponsive, press Ctrl-C 3 more times."); ExitApp(130); } diff --git a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index b698aab..c241df2 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -8,9 +8,9 @@ public static bool CheckNetCoreVersion(Version version) { if (version.Major != 3 || version.Minor != 1) { - Log("pmcenter v2 or up wouldn't run on devices without .NET Core 3.1 (runtime) installed.", Type: LogLevel.WARN); - Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version.ToString()}.", Type: LogLevel.WARN); - Log("Consider updating your .NET Core runtime in order to run pmcenter v2 and receive further updates.", Type: LogLevel.WARN); + Log("pmcenter v2 or up wouldn't run on devices without .NET Core 3.1 (runtime) installed.", LogLevel.WARN); + Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version.ToString()}.", LogLevel.WARN); + Log("Consider updating your .NET Core runtime in order to run pmcenter v2 and receive further updates.", LogLevel.WARN); return false; } return true; diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index 160cee1..7fd5bce 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -37,7 +37,7 @@ public static Version GetNetCoreVersion() } catch (Exception ex) { - Log($"pmcenter is unable to detect your .NET Core installation: {ex.Message}, you need to have .NET Core 3.1 (runtime) installed in order to run pmcenter v2 or up.", Type: LogLevel.WARN); + Log($"pmcenter is unable to detect your .NET Core installation: {ex.Message}, you need to have .NET Core 3.1 (runtime) installed in order to run pmcenter v2 or up.", LogLevel.WARN); return new Version("0.0.0.0"); } } diff --git a/pmcenter/Methods/Methods.Log.cs b/pmcenter/Methods/Methods.Log.cs index 2dcc9b0..cecc94e 100644 --- a/pmcenter/Methods/Methods.Log.cs +++ b/pmcenter/Methods/Methods.Log.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; @@ -7,59 +8,36 @@ namespace pmcenter { public partial class Methods { - public static void Log(string Text, - string Module = "CORE", - LogLevel Type = LogLevel.INFO, + public static Dictionary LogTable = new Dictionary() + { + {LogLevel.INFO, new LogMode() {Color = ConsoleColor.Black, Prefix = "[INFO] ", Func = Console.WriteLine}}, + {LogLevel.WARN, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, + {LogLevel.ERROR, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} + }; // table-driven + + public static void Log(string text, LogLevel type) + { + Log(text, "CORE", type); + } + public static void Log(string text, + string module = "CORE", + LogLevel type = LogLevel.INFO, [CallerFilePath] string filePath = "file?", [CallerMemberName] string callerName = "method?", [CallerLineNumber] int lineNumber = 0) { if (Vars.CurrentConf?.LowPerformanceMode == true) return; - string file = $"/{((Environment.OSVersion.Platform == PlatformID.Unix) ? Path.GetFileName(filePath.Replace(@"\", "/")) : Path.GetFileName(filePath))}/{callerName}()@L{lineNumber}"; - var Output = - (Vars.CurrentConf?.DisableTimeDisplay != true ? - $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" - : - "" - ) - + "[" - + Module - + - (Vars.CurrentConf?.AdvancedLogging == true ? - file - : - "" - ) - + "]"; + + var file = $"/{(Path.GetFileName((Environment.OSVersion.Platform == PlatformID.Unix) ? filePath.Replace(@"\", "/") : filePath))}/{callerName}()@L{lineNumber}"; + var Output = Vars.CurrentConf?.DisableTimeDisplay != true + ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" + : ""; + Output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; + Output += LogTable[type].Prefix; + Output += text; + Console.ForegroundColor = LogTable[type].Color; Console.BackgroundColor = ConsoleColor.Black; - switch (Type) - { - case LogLevel.INFO: - Console.ForegroundColor = ConsoleColor.White; - Output += "[INFO] "; // Spacebars between prefixes and contents were already added here. - break; - case LogLevel.WARN: - Console.ForegroundColor = ConsoleColor.Yellow; - Output += "[WARN] "; - break; - case LogLevel.ERROR: - Console.ForegroundColor = ConsoleColor.Red; - Output += "[ERROR] "; - break; - default: - Console.ForegroundColor = ConsoleColor.Gray; - Output += "[UKNN] "; - break; - } - Output += Text; - if (Type == LogLevel.ERROR) - { - Console.Error.WriteLine(Output); - } - else - { - Console.WriteLine(Output); - } + LogTable[type].Func(Output); Console.ForegroundColor = ConsoleColor.White; } } diff --git a/pmcenter/Methods/Methods.LogMode.cs b/pmcenter/Methods/Methods.LogMode.cs new file mode 100644 index 0000000..bec8e6c --- /dev/null +++ b/pmcenter/Methods/Methods.LogMode.cs @@ -0,0 +1,14 @@ +using System; + +namespace pmcenter +{ + public partial class Methods + { + public class LogMode + { + public ConsoleColor Color; + public string Prefix; + public Action Func; + } + } +} \ No newline at end of file diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 1dceae1..c461b2a 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -21,7 +21,7 @@ public static class Vars public readonly static string ASCII = " __ \n ____ ____ ___ ________ ____ / /____ _____\n / __ \\/ __ `__ \\/ ___/ _ \\/ __ \\/ __/ _ \\/ ___/\n / /_/ / / / / / / /__/ __/ / / / /_/ __/ / \n / .___/_/ /_/ /_/\\___/\\___/_/ /_/\\__/\\___/_/ \n/_/ "; public readonly static Version AppVer = new Version("1.9.280.15"); public readonly static string AppExecutable = Assembly.GetExecutingAssembly().Location; - public readonly static string AppDirectory = (new FileInfo(AppExecutable)).DirectoryName; + public readonly static string AppDirectory = Path.GetDirectoryName(AppExecutable); public static string ConfFile = Path.Combine(AppDirectory, "pmcenter.json"); public static string LangFile = Path.Combine(AppDirectory, "pmcenter_locale.json"); public readonly static string UpdateArchiveURL = "https://see.wtf/pmcenter-update"; From db367b51a70c117cd821eef76c47a89f9e8ddb60 Mon Sep 17 00:00:00 2001 From: Elepover Date: Tue, 7 Apr 2020 15:07:23 +0800 Subject: [PATCH 06/39] refactor updates system --- pmcenter/BotCommands/CheckUpdateCommand.cs | 24 ++++----- pmcenter/BotCommands/UpdateCommand.cs | 49 +++++-------------- pmcenter/CommandLines/UpdateCmdLine.cs | 38 +++----------- .../Conf.CheckForUpdatesAsync.cs | 20 -------- .../Conf.GetUpdateInfoIndexByLocale.cs | 22 --------- .../Conf.IsNewerVersionAvailable.cs | 21 -------- pmcenter/Configurations/Conf.Update.cs | 22 --------- pmcenter/Configurations/Conf.Update2.cs | 20 -------- pmcenter/Configurations/Conf.UpdateLevel.cs | 13 ----- .../Methods.H2Helper.GetBytesAsync.cs | 6 +-- .../Methods.H2Helper.GetStringAsync.cs | 6 +-- pmcenter/Methods/Methods.GetUpdateLevel.cs | 2 +- .../Threads/Methods.ThrUpdateChecker.cs | 8 +-- ...thods.UpdateHelper.CheckForUpdatesAsync.cs | 23 +++++++++ .../Methods.UpdateHelper.DownloadLangAsync.cs | 23 +++++++++ ...ethods.UpdateHelper.DownloadUpdateAsync.cs | 42 ++++++++++++++++ ...UpdateHelper.GetUpdateInfoIndexByLocale.cs | 25 ++++++++++ ...ds.UpdateHelper.IsNewerVersionAvailable.cs | 24 +++++++++ .../Methods.UpdateHelper.Update.cs | 25 ++++++++++ .../Methods.UpdateHelper.Update2.cs | 23 +++++++++ .../Methods.UpdateHelper.UpdateLevel.cs | 16 ++++++ pmcenter/Vars.cs | 2 +- 22 files changed, 244 insertions(+), 210 deletions(-) delete mode 100644 pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs delete mode 100644 pmcenter/Configurations/Conf.GetUpdateInfoIndexByLocale.cs delete mode 100644 pmcenter/Configurations/Conf.IsNewerVersionAvailable.cs delete mode 100644 pmcenter/Configurations/Conf.Update.cs delete mode 100644 pmcenter/Configurations/Conf.Update2.cs delete mode 100644 pmcenter/Configurations/Conf.UpdateLevel.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs create mode 100644 pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs diff --git a/pmcenter/BotCommands/CheckUpdateCommand.cs b/pmcenter/BotCommands/CheckUpdateCommand.cs index 33d4c7a..4cfbd30 100644 --- a/pmcenter/BotCommands/CheckUpdateCommand.cs +++ b/pmcenter/BotCommands/CheckUpdateCommand.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.UpdateHelper; namespace pmcenter.Commands { @@ -12,21 +12,21 @@ internal class CheckUpdateCommand : ICommand public string Prefix => "chkupdate"; - public async Task ExecuteAsync(TelegramBotClient botClient, Update update) + public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) { try { - var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); - var CurrentLocalizedIndex = Conf.GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); - if (Conf.IsNewerVersionAvailable(Latest)) + var latest = await CheckForUpdatesAsync().ConfigureAwait(false); + var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + if (IsNewerVersionAvailable(latest)) { Vars.UpdatePending = true; - Vars.UpdateVersion = new Version(Latest.Latest); - Vars.UpdateLevel = Latest.UpdateLevel; + Vars.UpdateVersion = new Version(latest.Latest); + Vars.UpdateLevel = latest.UpdateLevel; var UpdateString = Vars.CurrentLang.Message_UpdateAvailable - .Replace("$1", Latest.Latest) - .Replace("$2", Latest.UpdateCollection[CurrentLocalizedIndex].Details) - .Replace("$3", Methods.GetUpdateLevel(Latest.UpdateLevel)); + .Replace("$1", latest.Latest) + .Replace("$2", latest.UpdateCollection[CurrentLocalizedIndex].Details) + .Replace("$3", Methods.GetUpdateLevel(latest.UpdateLevel)); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, UpdateString, @@ -41,9 +41,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_AlreadyUpToDate - .Replace("$1", Latest.Latest) + .Replace("$1", latest.Latest) .Replace("$2", Vars.AppVer.ToString()) - .Replace("$3", Latest.UpdateCollection[CurrentLocalizedIndex].Details), + .Replace("$3", latest.UpdateCollection[CurrentLocalizedIndex].Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index 462dcf5..1581e76 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -1,13 +1,9 @@ using System; -using System.IO; -using System.IO.Compression; -using System.Net; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; -using static pmcenter.Methods.H2Helper; +using static pmcenter.Methods.UpdateHelper; namespace pmcenter.Commands { @@ -17,25 +13,26 @@ internal class UpdateCommand : ICommand public string Prefix => "update"; - public async Task ExecuteAsync(TelegramBotClient botClient, Update update) + public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) { try { - var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); - var CurrentLocalizedIndex = Conf.GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); - if (Conf.IsNewerVersionAvailable(Latest)) + var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); + var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); + if (IsNewerVersionAvailable(Latest)) { var UpdateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", Latest.Latest) .Replace("$2", Latest.UpdateCollection[CurrentLocalizedIndex].Details) - .Replace("$3", Methods.GetUpdateLevel(Latest.UpdateLevel)); + .Replace("$3", GetUpdateLevel(Latest.UpdateLevel)); + // \ update available! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, UpdateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); - // where difference begins + // \ updating! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateProcessing, @@ -44,31 +41,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); // download compiled package - Log("Starting update download... (pmcenter_update.zip)", "BOT"); - Log($"From address: {Latest.UpdateCollection[CurrentLocalizedIndex].UpdateArchiveAddress}", "BOT"); - await DownloadFileAsync( - new Uri(Latest.UpdateCollection[CurrentLocalizedIndex].UpdateArchiveAddress), - Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") - ).ConfigureAwait(false); - Log("Download complete. Extracting...", "BOT"); - using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) - { - foreach (ZipArchiveEntry Entry in Zip.Entries) - { - Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "BOT"); - Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); - } - } - if (Vars.CurrentConf.AutoLangUpdate) - { - Log("Starting automatic language file update...", "BOT"); - await DownloadFileAsync( - new Uri(Vars.CurrentConf.LangURL), - Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); - } - Log("Cleaning up temporary files...", "BOT"); - System.IO.File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); + await DownloadUpdatesAsync(Latest, CurrentLocalizedIndex).ConfigureAwait(false); + // update languages + if (Vars.CurrentConf.AutoLangUpdate) await DownloadLangAsync().ConfigureAwait(false); + + // \ see you! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateFinalizing, diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index d3d90c8..6756824 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -1,8 +1,5 @@ -using System; -using System.IO; -using System.IO.Compression; -using System.Threading.Tasks; -using static pmcenter.Methods.H2Helper; +using System.Threading.Tasks; +using static pmcenter.Methods.UpdateHelper; using static pmcenter.Methods; @@ -14,40 +11,21 @@ internal class UpdateCmdLine : ICmdLine public bool ExitAfterExecution => true; public async Task Process() { - Log($"Application version: {Vars.AppVer.ToString()}", "CMD"); + Log($"Application version: {Vars.AppVer}", "CMD"); Log("Checking for updates...", "CMD"); Log("Custom update channels and languages are currently unsupported in command line mode, will use \"master\" channel with English.", "CMD"); - var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); - if (Conf.IsNewerVersionAvailable(Latest)) + var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); + if (IsNewerVersionAvailable(Latest)) { Log($"Newer version found: {Latest.Latest}, main changes:\n{Latest.UpdateCollection[0].Details}", "CMD"); Log("Updating...", "CMD"); - Log("Starting update download... (pmcenter_update.zip)", "CMD"); - await DownloadFileAsync( - new Uri(Vars.UpdateArchiveURL), - Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") - ).ConfigureAwait(false); - Log("Download complete. Extracting...", "CMD"); - using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) - { - foreach (ZipArchiveEntry Entry in Zip.Entries) - { - Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}", "CMD"); - Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); - } - } - Log("Starting language file update...", "CMD"); - await DownloadFileAsync( - new Uri(Vars.CurrentConf.LangURL), - Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") - ).ConfigureAwait(false); - Log("Cleaning up temporary files...", "CMD"); - File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); + await DownloadUpdatesAsync(Latest).ConfigureAwait(false); + await DownloadLangAsync().ConfigureAwait(false); Log("Update complete.", "CMD"); } else { - Log($"No newer version found.\nCurrently installed version: {Vars.AppVer.ToString()}\nThe latest version is: {Latest.Latest}", "CMD"); + Log($"No newer version found.\nCurrently installed version: {Vars.AppVer}\nThe latest version is: {Latest.Latest}", "CMD"); } return true; } diff --git a/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs b/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs deleted file mode 100644 index 904600a..0000000 --- a/pmcenter/Configurations/Conf.CheckForUpdatesAsync.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Threading.Tasks; -using Newtonsoft.Json; -using static pmcenter.Methods.H2Helper; - -namespace pmcenter -{ - public partial class Conf - { - public static async Task CheckForUpdatesAsync() - { - var response = await GetStringAsync( - new Uri( - Vars.UpdateInfo2URL.Replace("$channel", Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel) - ) - ); - return JsonConvert.DeserializeObject(response); - } - } -} \ No newline at end of file diff --git a/pmcenter/Configurations/Conf.GetUpdateInfoIndexByLocale.cs b/pmcenter/Configurations/Conf.GetUpdateInfoIndexByLocale.cs deleted file mode 100644 index 6a6f304..0000000 --- a/pmcenter/Configurations/Conf.GetUpdateInfoIndexByLocale.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; - -namespace pmcenter -{ - public partial class Conf - { - public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) - { - List indexes = new List(); - for (int i = 0; i < Update.UpdateCollection.Count; i++) - { - if (Update.UpdateCollection[i].LangCode.Contains(Locale)) indexes.Add(i); - } - if (indexes.Count == 0) return 0; - foreach (int i in indexes) - { - if (Update.UpdateCollection[i].UpdateChannel == Vars.CurrentConf.UpdateChannel) return i; - } - return indexes[0]; - } - } -} \ No newline at end of file diff --git a/pmcenter/Configurations/Conf.IsNewerVersionAvailable.cs b/pmcenter/Configurations/Conf.IsNewerVersionAvailable.cs deleted file mode 100644 index c1fa933..0000000 --- a/pmcenter/Configurations/Conf.IsNewerVersionAvailable.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace pmcenter -{ - public partial class Conf - { - public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) - { - var CurrentVersion = Vars.AppVer; - var CurrentLatest = new Version(CurrentUpdate.Latest); - if (CurrentLatest > CurrentVersion) - { - return true; - } - else - { - return false; - } - } - } -} \ No newline at end of file diff --git a/pmcenter/Configurations/Conf.Update.cs b/pmcenter/Configurations/Conf.Update.cs deleted file mode 100644 index ba5e310..0000000 --- a/pmcenter/Configurations/Conf.Update.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; - -namespace pmcenter -{ - public partial class Conf - { - public class Update - { - public Update() - { - Details = "(Load failed.)"; - LangCode = new List() { "en.integrated" }; - UpdateChannel = "master"; - UpdateArchiveAddress = "https://see.wtf/pmcenter-update"; - } - public string Details; - public List LangCode; - public string UpdateChannel; - public string UpdateArchiveAddress; - } - } -} \ No newline at end of file diff --git a/pmcenter/Configurations/Conf.Update2.cs b/pmcenter/Configurations/Conf.Update2.cs deleted file mode 100644 index 490df5c..0000000 --- a/pmcenter/Configurations/Conf.Update2.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; - -namespace pmcenter -{ - public partial class Conf - { - public class Update2 - { - public Update2() - { - Latest = "0.0.0.0"; - UpdateLevel = UpdateLevel.Optional; - UpdateCollection = new List(); - } - public string Latest; - public UpdateLevel UpdateLevel; - public List UpdateCollection; - } - } -} \ No newline at end of file diff --git a/pmcenter/Configurations/Conf.UpdateLevel.cs b/pmcenter/Configurations/Conf.UpdateLevel.cs deleted file mode 100644 index ad07b0e..0000000 --- a/pmcenter/Configurations/Conf.UpdateLevel.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace pmcenter -{ - public partial class Conf - { - public enum UpdateLevel - { - Optional = 0, - Recommended = 1, - Important = 2, - Urgent = 3, - } - } -} \ No newline at end of file diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs index 9586943..c0e63b4 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -9,10 +9,8 @@ public partial class H2Helper { public static async Task GetBytesAsync(Uri uri) { - using (var content = await GetHttpContentAsync(uri).ConfigureAwait(false)) - { - return await content.ReadAsByteArrayAsync().ConfigureAwait(false); - } + using var content = await GetHttpContentAsync(uri).ConfigureAwait(false); + return await content.ReadAsByteArrayAsync().ConfigureAwait(false); } } } diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs index 2ba0195..4de3feb 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -9,10 +9,8 @@ public partial class H2Helper { public static async Task GetStringAsync(Uri uri) { - using (var content = await GetHttpContentAsync(uri).ConfigureAwait(false)) - { - return await content.ReadAsStringAsync().ConfigureAwait(false); - } + using var content = await GetHttpContentAsync(uri).ConfigureAwait(false); + return await content.ReadAsStringAsync().ConfigureAwait(false); } } } diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index 2724262..0909b40 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -1,4 +1,4 @@ -using static pmcenter.Conf; +using static pmcenter.Methods.UpdateHelper; namespace pmcenter { diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index 05d97df..128d73a 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -1,7 +1,7 @@ using System; using System.Threading; using Telegram.Bot.Types.Enums; -using static pmcenter.Conf; +using static pmcenter.Methods.UpdateHelper; namespace pmcenter { @@ -15,11 +15,11 @@ public static async void ThrUpdateChecker() Vars.UpdateCheckerStatus = ThreadStatus.Working; try { - var Latest = await Conf.CheckForUpdatesAsync().ConfigureAwait(false); + var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); var DisNotif = Vars.CurrentConf.DisableNotifications; // Identical with BotProcess.cs, L206. - if (Conf.IsNewerVersionAvailable(Latest)) + if (IsNewerVersionAvailable(Latest)) { Vars.UpdatePending = true; Vars.UpdateVersion = new Version(Latest.Latest); @@ -43,7 +43,7 @@ public static async void ThrUpdateChecker() } catch (Exception ex) { - Log($"Error during update check: {ex.ToString()}", "UPDATER", LogLevel.ERROR); + Log($"Error during update check: {ex}", "UPDATER", LogLevel.ERROR); } Vars.UpdateCheckerStatus = ThreadStatus.Standby; try { Thread.Sleep(60000); } catch { } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs new file mode 100644 index 0000000..b39499b --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -0,0 +1,23 @@ +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using static pmcenter.Methods.H2Helper; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + public static async Task CheckForUpdatesAsync() + { + var response = await GetStringAsync( + new Uri( + Vars.UpdateInfo2URL.Replace("$channel", Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel) + ) + ); + return JsonConvert.DeserializeObject(response); + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs new file mode 100644 index 0000000..848aa28 --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs @@ -0,0 +1,23 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Threading.Tasks; +using static pmcenter.Methods.H2Helper; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + public static async Task DownloadLangAsync() + { + Log("Starting automatic language file update...", "BOT"); + await DownloadFileAsync( + new Uri(Vars.CurrentConf.LangURL), + Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") + ).ConfigureAwait(false); + } + } + } +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs new file mode 100644 index 0000000..f88ba7e --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Threading.Tasks; +using static pmcenter.Methods.H2Helper; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + /// + /// Download update to filesystem and extract. + /// You must run Conf.CheckForUpdatesAsync() in order to pass the latestUpdate argument. + /// + /// The information of the latest update + /// The target localization's index + /// + public static async Task DownloadUpdatesAsync(Update2 latestUpdate, int localizationIndex = 0) + { + Log("Starting update download... (pmcenter_update.zip)"); + Log($"From address: {latestUpdate.UpdateCollection[localizationIndex].UpdateArchiveAddress}"); + await DownloadFileAsync( + new Uri(latestUpdate.UpdateCollection[localizationIndex].UpdateArchiveAddress), + Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") + ).ConfigureAwait(false); + Log("Download complete. Extracting..."); + using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) + { + foreach (ZipArchiveEntry Entry in Zip.Entries) + { + Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}"); + Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); + } + } + Log("Cleaning up temporary files..."); + File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); + } + } + } +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs new file mode 100644 index 0000000..da1db50 --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) + { + List indexes = new List(); + for (int i = 0; i < Update.UpdateCollection.Count; i++) + { + if (Update.UpdateCollection[i].LangCode.Contains(Locale)) indexes.Add(i); + } + if (indexes.Count == 0) return 0; + foreach (int i in indexes) + { + if (Update.UpdateCollection[i].UpdateChannel == Vars.CurrentConf.UpdateChannel) return i; + } + return indexes[0]; + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs new file mode 100644 index 0000000..192f61f --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -0,0 +1,24 @@ +using System; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) + { + var CurrentVersion = Vars.AppVer; + var CurrentLatest = new Version(CurrentUpdate.Latest); + if (CurrentLatest > CurrentVersion) + { + return true; + } + else + { + return false; + } + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs new file mode 100644 index 0000000..48f224c --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; + +namespace pmcenter +{ + public static partial class Methods + { + public static partial class UpdateHelper + { + public class Update + { + public Update() + { + Details = "(Load failed.)"; + LangCode = new List() { "en.integrated" }; + UpdateChannel = "master"; + UpdateArchiveAddress = "https://see.wtf/pmcenter-update"; + } + public string Details; + public List LangCode; + public string UpdateChannel; + public string UpdateArchiveAddress; + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs new file mode 100644 index 0000000..587a7fb --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace pmcenter +{ + public static partial class Methods + { + public partial class UpdateHelper + { + public class Update2 + { + public Update2() + { + Latest = "0.0.0.0"; + UpdateLevel = UpdateLevel.Optional; + UpdateCollection = new List(); + } + public string Latest; + public UpdateLevel UpdateLevel; + public List UpdateCollection; + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs new file mode 100644 index 0000000..b969a87 --- /dev/null +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs @@ -0,0 +1,16 @@ +namespace pmcenter +{ + public partial class Methods + { + public partial class UpdateHelper + { + public enum UpdateLevel + { + Optional = 0, + Recommended = 1, + Important = 2, + Urgent = 3, + } + } + } +} \ No newline at end of file diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 1dceae1..ca7d3c7 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -50,7 +50,7 @@ public static class Vars public static int CtrlCCounter = 0; public static bool IsShuttingDown = false; public static bool ServiceMode = true; - public static Conf.UpdateLevel UpdateLevel; + public static Methods.UpdateHelper.UpdateLevel UpdateLevel; public static Version UpdateVersion; public static Stopwatch StartSW = new Stopwatch(); public static List RateLimits = new List(); From f79abfd3761d1559f8549bc0baf42828f3183e83 Mon Sep 17 00:00:00 2001 From: Elepover Date: Tue, 7 Apr 2020 15:11:55 +0800 Subject: [PATCH 07/39] remove excess static tag --- .../UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs | 2 +- .../UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs | 2 +- .../UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs | 2 +- .../Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs | 2 +- .../Methods.UpdateHelper.IsNewerVersionAvailable.cs | 2 +- pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs | 2 +- pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index b39499b..07bb14e 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -5,7 +5,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs index 848aa28..ecc07a1 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs index f88ba7e..eb8b1a4 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs index da1db50..36846c5 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index 192f61f..5a2986a 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs index 48f224c..815192a 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public static partial class UpdateHelper { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs index 587a7fb..60a3996 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public static partial class Methods + public partial class Methods { public partial class UpdateHelper { From c66f88cbce11443a6365d02d5806b3a7ef4b27a3 Mon Sep 17 00:00:00 2001 From: Elepooooover Date: Tue, 7 Apr 2020 15:12:30 +0800 Subject: [PATCH 08/39] Fix linebreak in the end --- pmcenter/Methods/Methods.LogMode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/Methods/Methods.LogMode.cs b/pmcenter/Methods/Methods.LogMode.cs index bec8e6c..dc1f340 100644 --- a/pmcenter/Methods/Methods.LogMode.cs +++ b/pmcenter/Methods/Methods.LogMode.cs @@ -11,4 +11,4 @@ public class LogMode public Action Func; } } -} \ No newline at end of file +} From 2bf23a1dc0388eed7ab0982a1c7f528d61847351 Mon Sep 17 00:00:00 2001 From: Elepover Date: Tue, 7 Apr 2020 15:25:04 +0800 Subject: [PATCH 09/39] remove warning and fix logging colors --- pmcenter/CommandLines/NonServiceModeCmdLine.cs | 2 ++ pmcenter/Methods/Methods.Log.cs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/pmcenter/CommandLines/NonServiceModeCmdLine.cs b/pmcenter/CommandLines/NonServiceModeCmdLine.cs index 1da71da..b5bb204 100644 --- a/pmcenter/CommandLines/NonServiceModeCmdLine.cs +++ b/pmcenter/CommandLines/NonServiceModeCmdLine.cs @@ -10,7 +10,9 @@ internal class NonServiceModeCmdLine : ICmdLine { public string Prefix => "noservice"; public bool ExitAfterExecution => false; +#pragma warning disable CS1998 public async Task Process() +#pragma warning restore CS1998 { Vars.ServiceMode = false; Log("Service mode disabled."); diff --git a/pmcenter/Methods/Methods.Log.cs b/pmcenter/Methods/Methods.Log.cs index cecc94e..f93344a 100644 --- a/pmcenter/Methods/Methods.Log.cs +++ b/pmcenter/Methods/Methods.Log.cs @@ -10,7 +10,7 @@ public partial class Methods { public static Dictionary LogTable = new Dictionary() { - {LogLevel.INFO, new LogMode() {Color = ConsoleColor.Black, Prefix = "[INFO] ", Func = Console.WriteLine}}, + {LogLevel.INFO, new LogMode() {Color = ConsoleColor.White, Prefix = "[INFO] ", Func = Console.WriteLine}}, {LogLevel.WARN, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, {LogLevel.ERROR, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} }; // table-driven From cc546585bfd7b077794c7d6fa9d964062e495088 Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Tue, 7 Apr 2020 15:31:38 +0800 Subject: [PATCH 10/39] use Camel-Case --- pmcenter/BotCommands/SwitchLangCodeCommand.cs | 2 +- pmcenter/BotCommands/SwitchLangCommand.cs | 2 +- pmcenter/Configurations/Conf.ReadConf.cs | 4 ++-- pmcenter/Configurations/Conf.SaveConf.cs | 6 +++--- pmcenter/Configurations/Lang.ReadLang.cs | 4 ++-- pmcenter/Configurations/Lang.SaveLang.cs | 4 ++-- pmcenter/Methods/Methods.GetRandomString.cs | 4 ++-- pmcenter/Methods/Methods.IsRegexMatch.cs | 4 ++-- pmcenter/Methods/Methods.Log.cs | 2 +- pmcenter/Methods/Methods.LogLevel.cs | 2 +- 10 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pmcenter/BotCommands/SwitchLangCodeCommand.cs b/pmcenter/BotCommands/SwitchLangCodeCommand.cs index dc4c26c..2fb5fbf 100644 --- a/pmcenter/BotCommands/SwitchLangCodeCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCodeCommand.cs @@ -42,7 +42,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) // update configurations Vars.CurrentConf.LangURL = Mirror.LocaleFileURL.Replace("$channel", Vars.CompileChannel); // start downloading - _ = await Conf.SaveConf(IsAutoSave: true).ConfigureAwait(false); + _ = await Conf.SaveConf(isAutoSave: true).ConfigureAwait(false); await DownloadFileAsync( new Uri(Vars.CurrentConf.LangURL), Path.Combine( diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index 8473cc3..43491d6 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -31,7 +31,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) var LangURL = update.Message.Text.Split(" ")[1]; Vars.CurrentConf.LangURL = LangURL; // save conf - _ = await Conf.SaveConf(IsAutoSave: true); + _ = await Conf.SaveConf(isAutoSave: true); await DownloadFileAsync( new Uri(LangURL), Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index 6d702f8..93f17a1 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -4,10 +4,10 @@ namespace pmcenter { public partial class Conf { - public static async Task ReadConf(bool Apply = true) + public static async Task ReadConf(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. var Temp = await GetConf(Vars.ConfFile).ConfigureAwait(false); - if (Apply) { Vars.CurrentConf = Temp; } + if (apply) { Vars.CurrentConf = Temp; } return true; } } diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index a5d39c6..dc72d3c 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -7,15 +7,15 @@ namespace pmcenter { public partial class Conf { - public static async Task SaveConf(bool IsInvalid = false, bool IsAutoSave = false) + public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. string Text = JsonConvert.SerializeObject(Vars.CurrentConf, Formatting.Indented); await System.IO.File.WriteAllTextAsync(Vars.ConfFile, Text).ConfigureAwait(false); - if (IsAutoSave) + if (isAutoSave) { Log("Autosave complete.", "CONF"); } - if (IsInvalid) + if (isInvalid) { Log("We've detected an invalid configurations file and have reset it.", "CONF", LogLevel.WARN); Log("Please reconfigure it and try to start pmcenter again.", "CONF", LogLevel.WARN); diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index a1969d8..5125840 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -6,11 +6,11 @@ namespace pmcenter { public partial class Lang { - public static async Task ReadLang(bool Apply = true) + public static async Task ReadLang(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. var SettingsText = await File.ReadAllTextAsync(Vars.LangFile).ConfigureAwait(false); var Temp = JsonConvert.DeserializeObject(SettingsText); - if (Apply) { Vars.CurrentLang = Temp; } + if (apply) { Vars.CurrentLang = Temp; } return true; } } diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index 8d16717..c42e90d 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -7,14 +7,14 @@ namespace pmcenter { public partial class Lang { - public static async Task SaveLang(bool IsInvalid = false) + public static async Task SaveLang(bool isInvalid = false) { // DO NOT HANDLE ERRORS HERE. var Text = JsonConvert.SerializeObject(Vars.CurrentLang, Formatting.Indented); var Writer = new StreamWriter(File.Create(Vars.LangFile), System.Text.Encoding.UTF8); await Writer.WriteAsync(Text).ConfigureAwait(false); await Writer.FlushAsync().ConfigureAwait(false); Writer.Close(); - if (IsInvalid) + if (isInvalid) { Log("We've detected an invalid language file and have reset it.", "LANG", LogLevel.WARN); Log("Please reconfigure it and try to start pmcenter again.", "LANG", LogLevel.WARN); diff --git a/pmcenter/Methods/Methods.GetRandomString.cs b/pmcenter/Methods/Methods.GetRandomString.cs index 0aad597..84ac5d6 100644 --- a/pmcenter/Methods/Methods.GetRandomString.cs +++ b/pmcenter/Methods/Methods.GetRandomString.cs @@ -5,10 +5,10 @@ namespace pmcenter { public partial class Methods { - public static string GetRandomString(int Length = 8) + public static string GetRandomString(int length = 8) { const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - return new string(Enumerable.Repeat(Chars, Length).Select(s => s[(new Random()).Next(s.Length)]).ToArray()); + return new string(Enumerable.Repeat(Chars, length).Select(s => s[(new Random()).Next(s.Length)]).ToArray()); } } } diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index 750d12e..eb88809 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -5,11 +5,11 @@ namespace pmcenter { public partial class Methods { - public static bool IsRegexMatch(string Source, string Expression) + public static bool IsRegexMatch(string source, string expression) { try { - if (Regex.IsMatch(Source, Expression, RegexOptions.None)) + if (Regex.IsMatch(source, expression, RegexOptions.None)) { return true; } diff --git a/pmcenter/Methods/Methods.Log.cs b/pmcenter/Methods/Methods.Log.cs index f93344a..d1ab0d0 100644 --- a/pmcenter/Methods/Methods.Log.cs +++ b/pmcenter/Methods/Methods.Log.cs @@ -41,4 +41,4 @@ public static void Log(string text, Console.ForegroundColor = ConsoleColor.White; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.LogLevel.cs b/pmcenter/Methods/Methods.LogLevel.cs index a0495e9..2678c1a 100644 --- a/pmcenter/Methods/Methods.LogLevel.cs +++ b/pmcenter/Methods/Methods.LogLevel.cs @@ -9,4 +9,4 @@ public enum LogLevel ERROR = 2, } } -} \ No newline at end of file +} From 3e8a1f5f0a982a2f6b28fabf499946f0a66c01c4 Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Tue, 7 Apr 2020 15:39:46 +0800 Subject: [PATCH 11/39] add linebreak --- pmcenter/CommandLineProcess.cs | 2 +- pmcenter/CommandLineRouter.cs | 2 +- pmcenter/CommandLines/BackupCmdLine.cs | 2 +- pmcenter/CommandLines/HelpCmdLine.cs | 2 +- pmcenter/CommandLines/InfoCmdLine.cs | 2 +- pmcenter/CommandLines/NonServiceModeCmdLine.cs | 2 +- pmcenter/CommandLines/ResetCmdLine.cs | 2 +- pmcenter/CommandLines/SetupWizardCmdLine.cs | 2 +- pmcenter/CommandLines/UpdateCmdLine.cs | 2 +- pmcenter/Configurations/Conf.BanObj.cs | 2 +- pmcenter/Configurations/Conf.ConfObj.New.cs | 2 +- pmcenter/Configurations/Conf.ConfObj.cs | 2 +- pmcenter/Configurations/Conf.GetConf.cs | 2 +- pmcenter/Configurations/Conf.InitConf.cs | 2 +- pmcenter/Configurations/Conf.KillIllegalChars.cs | 2 +- pmcenter/Configurations/Conf.LocaleList.cs | 2 +- pmcenter/Configurations/Conf.LocaleMirror.cs | 2 +- pmcenter/Configurations/Conf.MessageIDLink.cs | 2 +- pmcenter/Configurations/Conf.RateData.cs | 2 +- pmcenter/Configurations/Conf.ReadConf.cs | 2 +- pmcenter/Configurations/Conf.SaveConf.cs | 2 +- pmcenter/Configurations/Conf.Socks5Proxy.cs | 2 +- pmcenter/Configurations/Conf.Stats.cs | 2 +- pmcenter/Configurations/Conf.SwitchBlocking.cs | 2 +- pmcenter/Configurations/Conf.SwitchNotifications.cs | 2 +- pmcenter/Configurations/Conf.SwitchPaused.cs | 2 +- pmcenter/Configurations/Lang.InitLang.cs | 2 +- pmcenter/Configurations/Lang.Language.New.cs | 2 +- pmcenter/Configurations/Lang.Language.cs | 2 +- pmcenter/Configurations/Lang.ReadLang.cs | 2 +- pmcenter/Configurations/Lang.SaveLang.cs | 2 +- pmcenter/EventHandlers/CtrlCHandler.cs | 2 +- pmcenter/EventHandlers/GlobalErrorHandler.cs | 2 +- pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs | 2 +- .../Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs | 2 +- .../Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs | 2 +- .../Methods/Database/Checking/Methods.GetRateDataIndexByID.cs | 2 +- pmcenter/Methods/Database/Checking/Methods.IsBanned.cs | 2 +- pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs | 2 +- .../Database/Checking/Methods.IsOwnerRetractionAvailable.cs | 2 +- .../Methods/Database/Checking/Methods.IsRateDataTracking.cs | 2 +- .../Database/Checking/Methods.IsUserRetractionAvailable.cs | 2 +- pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs | 2 +- pmcenter/Methods/Database/Writing/Methods.BanUser.cs | 2 +- pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs | 2 +- pmcenter/Methods/Methods.BoolStr.cs | 2 +- pmcenter/Methods/Methods.CheckNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.CheckOpenSSLComp.cs | 2 +- pmcenter/Methods/Methods.FlipBool.cs | 2 +- pmcenter/Methods/Methods.GetNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.GetThreadStatus.cs | 2 +- pmcenter/Methods/Methods.GetThreadStatusString.cs | 2 +- pmcenter/Methods/Methods.GetUpdateLevel.cs | 2 +- pmcenter/Methods/Methods.IsRegexMatch.cs | 2 +- pmcenter/Methods/Methods.SerializeCurrentConf.cs | 2 +- pmcenter/Methods/Methods.StrChunk.cs | 2 +- pmcenter/Methods/Methods.ThreadStatus.cs | 2 +- pmcenter/Methods/NetworkTest/Methods.TestLatency.cs | 2 +- pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs | 2 +- pmcenter/Methods/Threads/Methods.ThrPerform.cs | 2 +- pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs | 2 +- pmcenter/Methods/Threads/Methods.ThrSyncConf.cs | 2 +- pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs | 2 +- .../UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs | 2 +- .../Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs | 2 +- .../Methods.UpdateHelper.IsNewerVersionAvailable.cs | 2 +- pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs | 2 +- pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs | 2 +- .../Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs | 2 +- pmcenter/Setup.cs | 2 +- pmcenter/Template.cs | 2 +- pmcenter/Vars.cs | 2 +- 72 files changed, 72 insertions(+), 72 deletions(-) diff --git a/pmcenter/CommandLineProcess.cs b/pmcenter/CommandLineProcess.cs index b9b8d0e..cd7d82f 100644 --- a/pmcenter/CommandLineProcess.cs +++ b/pmcenter/CommandLineProcess.cs @@ -28,4 +28,4 @@ public static async Task RunCommand(string CommandLine) _ = await CmdLineRouter.Execute(CommandLine).ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLineRouter.cs index 9e9fd18..780ed9c 100644 --- a/pmcenter/CommandLineRouter.cs +++ b/pmcenter/CommandLineRouter.cs @@ -74,4 +74,4 @@ public async Task Execute(string cmdLine) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/BackupCmdLine.cs b/pmcenter/CommandLines/BackupCmdLine.cs index 55c8948..df4ee23 100644 --- a/pmcenter/CommandLines/BackupCmdLine.cs +++ b/pmcenter/CommandLines/BackupCmdLine.cs @@ -21,4 +21,4 @@ public Task Process() return Task.FromResult(true); } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/HelpCmdLine.cs b/pmcenter/CommandLines/HelpCmdLine.cs index 8556fec..3c27047 100644 --- a/pmcenter/CommandLines/HelpCmdLine.cs +++ b/pmcenter/CommandLines/HelpCmdLine.cs @@ -17,4 +17,4 @@ public Task Process() return Task.FromResult(true); } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/InfoCmdLine.cs b/pmcenter/CommandLines/InfoCmdLine.cs index 3e39395..70d13e8 100644 --- a/pmcenter/CommandLines/InfoCmdLine.cs +++ b/pmcenter/CommandLines/InfoCmdLine.cs @@ -29,4 +29,4 @@ public async Task Process() return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/NonServiceModeCmdLine.cs b/pmcenter/CommandLines/NonServiceModeCmdLine.cs index b5bb204..3627ceb 100644 --- a/pmcenter/CommandLines/NonServiceModeCmdLine.cs +++ b/pmcenter/CommandLines/NonServiceModeCmdLine.cs @@ -19,4 +19,4 @@ public async Task Process() return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/ResetCmdLine.cs b/pmcenter/CommandLines/ResetCmdLine.cs index 5907369..f6eac32 100644 --- a/pmcenter/CommandLines/ResetCmdLine.cs +++ b/pmcenter/CommandLines/ResetCmdLine.cs @@ -21,4 +21,4 @@ public async Task Process() return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/SetupWizardCmdLine.cs b/pmcenter/CommandLines/SetupWizardCmdLine.cs index 7c64d18..cf0615d 100644 --- a/pmcenter/CommandLines/SetupWizardCmdLine.cs +++ b/pmcenter/CommandLines/SetupWizardCmdLine.cs @@ -18,4 +18,4 @@ public async Task Process() return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index 6756824..b00b4bb 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -30,4 +30,4 @@ public async Task Process() return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.BanObj.cs b/pmcenter/Configurations/Conf.BanObj.cs index 21c837e..75bb77d 100644 --- a/pmcenter/Configurations/Conf.BanObj.cs +++ b/pmcenter/Configurations/Conf.BanObj.cs @@ -11,4 +11,4 @@ public BanObj() public long UID { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index 78048a2..acafe53 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -49,4 +49,4 @@ public ConfObj() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index 46578cf..78aba7a 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -46,4 +46,4 @@ public partial class ConfObj public List MessageLinks; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index f6f5aba..68b06cf 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -11,4 +11,4 @@ public static async Task GetConf(string Filename) return JsonConvert.DeserializeObject(SettingsText); } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.InitConf.cs b/pmcenter/Configurations/Conf.InitConf.cs index c5cf80a..8ae26dc 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -33,4 +33,4 @@ public static async Task InitConf() Log("Integrity test finished!", "CONF"); } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.KillIllegalChars.cs b/pmcenter/Configurations/Conf.KillIllegalChars.cs index b053fc5..4b3dc05 100644 --- a/pmcenter/Configurations/Conf.KillIllegalChars.cs +++ b/pmcenter/Configurations/Conf.KillIllegalChars.cs @@ -7,4 +7,4 @@ public static string KillIllegalChars(string Input) return Input.Replace("/", "-").Replace("<", "-").Replace(">", "-").Replace(":", "-").Replace("\"", "-").Replace("/", "-").Replace("\\", "-").Replace("|", "-").Replace("?", "-").Replace("*", "-"); } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.LocaleList.cs b/pmcenter/Configurations/Conf.LocaleList.cs index 96a47b0..8618bf3 100644 --- a/pmcenter/Configurations/Conf.LocaleList.cs +++ b/pmcenter/Configurations/Conf.LocaleList.cs @@ -13,4 +13,4 @@ public LocaleList() public List Locales { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.LocaleMirror.cs b/pmcenter/Configurations/Conf.LocaleMirror.cs index a85ae9f..aab84c6 100644 --- a/pmcenter/Configurations/Conf.LocaleMirror.cs +++ b/pmcenter/Configurations/Conf.LocaleMirror.cs @@ -17,4 +17,4 @@ public LocaleMirror() public string LocaleNameNative { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.MessageIDLink.cs b/pmcenter/Configurations/Conf.MessageIDLink.cs index 0d5980d..23d97b5 100644 --- a/pmcenter/Configurations/Conf.MessageIDLink.cs +++ b/pmcenter/Configurations/Conf.MessageIDLink.cs @@ -22,4 +22,4 @@ public MessageIDLink() public bool IsFromOwner { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.RateData.cs b/pmcenter/Configurations/Conf.RateData.cs index 6866ae3..02de594 100644 --- a/pmcenter/Configurations/Conf.RateData.cs +++ b/pmcenter/Configurations/Conf.RateData.cs @@ -13,4 +13,4 @@ public RateData() public int MessageCount { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index 93f17a1..b3d859a 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -11,4 +11,4 @@ public static async Task ReadConf(bool apply = true) return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index dc72d3c..34b1138 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -24,4 +24,4 @@ public static async Task SaveConf(bool isInvalid = false, bool isAutoSave return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.Socks5Proxy.cs b/pmcenter/Configurations/Conf.Socks5Proxy.cs index 3004474..5138160 100644 --- a/pmcenter/Configurations/Conf.Socks5Proxy.cs +++ b/pmcenter/Configurations/Conf.Socks5Proxy.cs @@ -17,4 +17,4 @@ public Socks5Proxy() public string ProxyPass { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.Stats.cs b/pmcenter/Configurations/Conf.Stats.cs index 5332159..7cbd9a7 100644 --- a/pmcenter/Configurations/Conf.Stats.cs +++ b/pmcenter/Configurations/Conf.Stats.cs @@ -17,4 +17,4 @@ public Stats() public int TotalForwardedFromOwner { get; set; } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.SwitchBlocking.cs b/pmcenter/Configurations/Conf.SwitchBlocking.cs index 4790685..bf8295a 100644 --- a/pmcenter/Configurations/Conf.SwitchBlocking.cs +++ b/pmcenter/Configurations/Conf.SwitchBlocking.cs @@ -20,4 +20,4 @@ public static bool SwitchBlocking() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.SwitchNotifications.cs b/pmcenter/Configurations/Conf.SwitchNotifications.cs index d2bd8e3..3dd4813 100644 --- a/pmcenter/Configurations/Conf.SwitchNotifications.cs +++ b/pmcenter/Configurations/Conf.SwitchNotifications.cs @@ -20,4 +20,4 @@ public static bool SwitchNotifications() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Conf.SwitchPaused.cs b/pmcenter/Configurations/Conf.SwitchPaused.cs index f36c618..b2fd042 100644 --- a/pmcenter/Configurations/Conf.SwitchPaused.cs +++ b/pmcenter/Configurations/Conf.SwitchPaused.cs @@ -20,4 +20,4 @@ public static bool SwitchPaused() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Lang.InitLang.cs b/pmcenter/Configurations/Lang.InitLang.cs index 64f9c19..e4e1a56 100644 --- a/pmcenter/Configurations/Lang.InitLang.cs +++ b/pmcenter/Configurations/Lang.InitLang.cs @@ -34,4 +34,4 @@ public static async Task InitLang() Log("Integrity test finished!", "LANG"); } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index c4616ff..55104a2 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -81,4 +81,4 @@ public Language() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Lang.Language.cs b/pmcenter/Configurations/Lang.Language.cs index 20dee04..e016896 100644 --- a/pmcenter/Configurations/Lang.Language.cs +++ b/pmcenter/Configurations/Lang.Language.cs @@ -78,4 +78,4 @@ public partial class Language public string Message_NetCore31Required; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index 5125840..40072fc 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -14,4 +14,4 @@ public static async Task ReadLang(bool apply = true) return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index c42e90d..95b7962 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -23,4 +23,4 @@ public static async Task SaveLang(bool isInvalid = false) return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index a3cab89..36a6c06 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -26,4 +26,4 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) ExitApp(130); } } -} \ No newline at end of file +} diff --git a/pmcenter/EventHandlers/GlobalErrorHandler.cs b/pmcenter/EventHandlers/GlobalErrorHandler.cs index 6811a26..eb38cfc 100644 --- a/pmcenter/EventHandlers/GlobalErrorHandler.cs +++ b/pmcenter/EventHandlers/GlobalErrorHandler.cs @@ -46,4 +46,4 @@ private static void L(string log) Console.Error.WriteLine(log); } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs index 4573e5a..2e0f540 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs @@ -13,4 +13,4 @@ public static BanObj GetBanObjByID(long UID) return null; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs index e92474b..b839172 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs @@ -16,4 +16,4 @@ public static MessageIDLink GetLinkByOwnerMsgID(long OwnerSessionMsgID) return null; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs index 19a76cf..6fabd71 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs @@ -16,4 +16,4 @@ public static MessageIDLink GetLinkByUserMsgID(long UserSessionMsgID) return null; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs index b7cba41..e7fd08c 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -13,4 +13,4 @@ public static int GetRateDataIndexByID(long UID) return -1; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index d2450a0..e51e28e 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -13,4 +13,4 @@ public static bool IsBanned(long UID) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs index 96d0b04..5a65e27 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs @@ -20,4 +20,4 @@ public static bool IsKeywordBanned(string Sentence) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs index 7025a23..7e15d25 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -17,4 +17,4 @@ public static bool IsOwnerRetractionAvailable(int OwnerSessionMsgID) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs index 15f1bff..47e4634 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -13,4 +13,4 @@ public static bool IsRateDataTracking(long UID) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs index fc9265a..45bf343 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs @@ -17,4 +17,4 @@ public static bool IsUserRetractionAvailable(int UserSessionMsgID) return false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs index 691d495..c8a9fbb 100644 --- a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs +++ b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs @@ -22,4 +22,4 @@ public static void AddRateLimit(long UID) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs index 02b09af..54b3db6 100644 --- a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs @@ -16,4 +16,4 @@ public static void BanUser(long UID) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs index 07a237a..249878b 100644 --- a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs @@ -10,4 +10,4 @@ public static void UnbanUser(long UID) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.BoolStr.cs b/pmcenter/Methods/Methods.BoolStr.cs index 3b22502..42ad946 100644 --- a/pmcenter/Methods/Methods.BoolStr.cs +++ b/pmcenter/Methods/Methods.BoolStr.cs @@ -7,4 +7,4 @@ public static string BoolStr(bool Input) return Input ? "true" : "false"; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index c241df2..77f852d 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -16,4 +16,4 @@ public static bool CheckNetCoreVersion(Version version) return true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs index 0771924..d12c20f 100644 --- a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs +++ b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs @@ -25,4 +25,4 @@ public static void CheckOpenSSLComp(Exception ex) catch {} } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.FlipBool.cs b/pmcenter/Methods/Methods.FlipBool.cs index 7b9f9d6..e5f58c7 100644 --- a/pmcenter/Methods/Methods.FlipBool.cs +++ b/pmcenter/Methods/Methods.FlipBool.cs @@ -7,4 +7,4 @@ public static bool FlipBool(bool Input) return Input ? false : true; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index 7fd5bce..a581cac 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -42,4 +42,4 @@ public static Version GetNetCoreVersion() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.GetThreadStatus.cs b/pmcenter/Methods/Methods.GetThreadStatus.cs index 51d6aab..f2b7ea7 100644 --- a/pmcenter/Methods/Methods.GetThreadStatus.cs +++ b/pmcenter/Methods/Methods.GetThreadStatus.cs @@ -16,4 +16,4 @@ public static ThreadStatus GetThreadStatus(Thread Thread) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.GetThreadStatusString.cs b/pmcenter/Methods/Methods.GetThreadStatusString.cs index 118881b..324c7b1 100644 --- a/pmcenter/Methods/Methods.GetThreadStatusString.cs +++ b/pmcenter/Methods/Methods.GetThreadStatusString.cs @@ -19,4 +19,4 @@ public static string GetThreadStatusString(ThreadStatus Status) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index 0909b40..b85e865 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -22,4 +22,4 @@ public static string GetUpdateLevel(UpdateLevel Level) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index eb88809..68807e9 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -25,4 +25,4 @@ public static bool IsRegexMatch(string source, string expression) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.SerializeCurrentConf.cs b/pmcenter/Methods/Methods.SerializeCurrentConf.cs index 6f05e20..d86c585 100644 --- a/pmcenter/Methods/Methods.SerializeCurrentConf.cs +++ b/pmcenter/Methods/Methods.SerializeCurrentConf.cs @@ -9,4 +9,4 @@ public static string SerializeCurrentConf() return JsonConvert.SerializeObject(Vars.CurrentConf, Formatting.Indented); } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.StrChunk.cs b/pmcenter/Methods/Methods.StrChunk.cs index 430b6b9..a06a18b 100644 --- a/pmcenter/Methods/Methods.StrChunk.cs +++ b/pmcenter/Methods/Methods.StrChunk.cs @@ -10,4 +10,4 @@ public static List StrChunk(string str, int chunkSize) return Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize)).ToList(); } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Methods.ThreadStatus.cs b/pmcenter/Methods/Methods.ThreadStatus.cs index 6c732fb..d9a2488 100644 --- a/pmcenter/Methods/Methods.ThreadStatus.cs +++ b/pmcenter/Methods/Methods.ThreadStatus.cs @@ -11,4 +11,4 @@ public enum ThreadStatus Error = 4, } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs index 6d500a9..626eb96 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs @@ -31,4 +31,4 @@ public static async Task TestLatency(string target) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs index 5fef90d..23d23d5 100644 --- a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs +++ b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs @@ -14,4 +14,4 @@ public static void ThrDoResetConfCount() Vars.ConfResetTimerStatus = ThreadStatus.Stopped; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Threads/Methods.ThrPerform.cs b/pmcenter/Methods/Threads/Methods.ThrPerform.cs index f56a94d..86582be 100644 --- a/pmcenter/Methods/Threads/Methods.ThrPerform.cs +++ b/pmcenter/Methods/Threads/Methods.ThrPerform.cs @@ -15,4 +15,4 @@ public static void ThrPerform() Vars.IsPerformanceTestEndRequested = false; } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs index 6ad14e9..7475035 100644 --- a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs +++ b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs @@ -26,4 +26,4 @@ public static async void ThrRateLimiter() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 1c83150..6097c68 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -27,4 +27,4 @@ public static async void ThrSyncConf() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index 128d73a..82a1782 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -50,4 +50,4 @@ public static async void ThrUpdateChecker() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index 07bb14e..8df2a7c 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -20,4 +20,4 @@ public static async Task CheckForUpdatesAsync() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs index 36846c5..f513709 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -22,4 +22,4 @@ public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index 5a2986a..c06e6a5 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -21,4 +21,4 @@ public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs index 815192a..d4c4144 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -22,4 +22,4 @@ public Update() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs index 60a3996..9106d3c 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -20,4 +20,4 @@ public Update2() } } } -} \ No newline at end of file +} diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs index b969a87..c98dcaf 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs @@ -13,4 +13,4 @@ public enum UpdateLevel } } } -} \ No newline at end of file +} diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index a2252a5..9a27f06 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -227,4 +227,4 @@ private static void SetMessageLinks() Say(" Done!"); } } -} \ No newline at end of file +} diff --git a/pmcenter/Template.cs b/pmcenter/Template.cs index a8728c6..8c07c16 100644 --- a/pmcenter/Template.cs +++ b/pmcenter/Template.cs @@ -11,4 +11,4 @@ namespace pmcenter public class Template { } -} \ No newline at end of file +} diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index ff7e513..20b8b61 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -72,4 +72,4 @@ public static class Vars public static Methods.ThreadStatus UpdateCheckerStatus = Methods.ThreadStatus.Stopped; public static Thread SyncConf; } -} \ No newline at end of file +} From 203c0290e7e5bb63aa04f5ea9e604ffd07763952 Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Tue, 7 Apr 2020 15:59:28 +0800 Subject: [PATCH 12/39] Treatment OCD --- pmcenter/Methods/Methods.Log.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/Methods/Methods.Log.cs b/pmcenter/Methods/Methods.Log.cs index d1ab0d0..e4ac250 100644 --- a/pmcenter/Methods/Methods.Log.cs +++ b/pmcenter/Methods/Methods.Log.cs @@ -35,8 +35,8 @@ public static void Log(string text, Output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; Output += LogTable[type].Prefix; Output += text; - Console.ForegroundColor = LogTable[type].Color; Console.BackgroundColor = ConsoleColor.Black; + Console.ForegroundColor = LogTable[type].Color; LogTable[type].Func(Output); Console.ForegroundColor = ConsoleColor.White; } From c8b905831bc5f5c3f4c87f9711e934685559f47a Mon Sep 17 00:00:00 2001 From: Elepover Date: Fri, 10 Apr 2020 10:40:00 +0800 Subject: [PATCH 13/39] code refactor --- README.md | 2 +- README_zh.md | 2 +- pmcenter/.editorconfig | 8 +- pmcenter/BotCommands/BackupConfCommand.cs | 3 +- pmcenter/BotCommands/Chat.cs | 3 +- .../BotCommands/ClearMessageLinksCommand.cs | 2 +- pmcenter/BotCommands/EditConfCommand.cs | 1 + pmcenter/BotCommands/ResetConfCommand.cs | 8 +- pmcenter/BotCommands/StopChat.cs | 1 + pmcenter/BotCommands/TestNetwork.cs | 1 + pmcenter/BotCommands/UpdateCommand.cs | 1 + pmcenter/BotProcess.cs | 7 +- pmcenter/CommandLineRouter.cs | 5 +- pmcenter/CommandLines/BackupCmdLine.cs | 5 +- pmcenter/CommandLines/HelpCmdLine.cs | 6 +- pmcenter/CommandLines/InfoCmdLine.cs | 6 +- .../CommandLines/NonServiceModeCmdLine.cs | 7 +- pmcenter/CommandLines/ResetCmdLine.cs | 7 +- pmcenter/CommandLines/SetupWizardCmdLine.cs | 7 +- pmcenter/CommandLines/UpdateCmdLine.cs | 3 +- pmcenter/Configurations/Conf.BanObj.cs | 2 +- pmcenter/Configurations/Conf.ConfObj.New.cs | 4 +- pmcenter/Configurations/Conf.ConfObj.cs | 80 +++++----- pmcenter/Configurations/Conf.GetConf.cs | 2 +- pmcenter/Configurations/Conf.InitConf.cs | 6 +- .../Configurations/Conf.KillIllegalChars.cs | 2 +- pmcenter/Configurations/Conf.LocaleList.cs | 2 +- pmcenter/Configurations/Conf.LocaleMirror.cs | 2 +- pmcenter/Configurations/Conf.MessageIDLink.cs | 2 +- pmcenter/Configurations/Conf.RateData.cs | 2 +- pmcenter/Configurations/Conf.ReadConf.cs | 2 +- pmcenter/Configurations/Conf.SaveConf.cs | 5 +- pmcenter/Configurations/Conf.Socks5Proxy.cs | 2 +- pmcenter/Configurations/Conf.Stats.cs | 2 +- .../Configurations/Conf.SwitchBlocking.cs | 2 +- .../Conf.SwitchNotifications.cs | 2 +- pmcenter/Configurations/Conf.SwitchPaused.cs | 2 +- pmcenter/Configurations/Lang.InitLang.cs | 5 +- pmcenter/Configurations/Lang.Language.New.cs | 4 +- pmcenter/Configurations/Lang.Language.cs | 148 +++++++++--------- pmcenter/Configurations/Lang.ReadLang.cs | 2 +- pmcenter/Configurations/Lang.SaveLang.cs | 4 +- pmcenter/EventHandlers/CtrlCHandler.cs | 5 +- pmcenter/EventHandlers/GlobalErrorHandler.cs | 17 +- .../Checking/Methods.GetBanObjByID.cs | 2 +- .../Checking/Methods.GetLinkByOwnerMsgID.cs | 2 +- .../Checking/Methods.GetLinkByUserMsgID.cs | 2 +- .../Checking/Methods.GetRateDataIndexByID.cs | 2 +- .../Database/Checking/Methods.IsBanned.cs | 2 +- .../Checking/Methods.IsKeywordBanned.cs | 2 +- .../Methods.IsOwnerRetractionAvailable.cs | 2 +- .../Checking/Methods.IsRateDataTracking.cs | 2 +- .../Methods.IsUserRetractionAvailable.cs | 2 +- .../Database/Writing/Methods.AddRateLimit.cs | 2 +- .../Database/Writing/Methods.BanUser.cs | 2 +- .../Database/Writing/Methods.UnbanUser.cs | 2 +- .../Methods.H2Helper.DownloadFileAsync.cs | 4 +- .../Methods.H2Helper.GetBytesAsync.cs | 4 +- .../Methods.H2Helper.GetHttpContentAsync.cs | 4 +- .../Methods.H2Helper.GetStringAsync.cs | 4 +- pmcenter/Methods/Logging/Methods.Log.cs | 39 +++++ pmcenter/Methods/Logging/Methods.LogLevel.cs | 15 ++ pmcenter/Methods/Logging/Methods.LogMode.cs | 17 ++ pmcenter/Methods/Logging/Methods.LogTable.cs | 18 +++ pmcenter/Methods/Methods.BoolStr.cs | 2 +- .../Methods/Methods.CheckNetCoreVersion.cs | 5 +- pmcenter/Methods/Methods.CheckOpenSSLComp.cs | 4 +- pmcenter/Methods/Methods.ExitApp.cs | 3 +- pmcenter/Methods/Methods.FlipBool.cs | 2 +- pmcenter/Methods/Methods.GetDateTimeString.cs | 2 +- pmcenter/Methods/Methods.GetNetCoreVersion.cs | 4 +- pmcenter/Methods/Methods.GetRandomString.cs | 2 +- pmcenter/Methods/Methods.GetThreadStatus.cs | 2 +- .../Methods/Methods.GetThreadStatusString.cs | 21 +-- pmcenter/Methods/Methods.GetUpdateLevel.cs | 21 +-- pmcenter/Methods/Methods.IsRegexMatch.cs | 3 +- pmcenter/Methods/Methods.Log.cs | 44 ------ pmcenter/Methods/Methods.LogLevel.cs | 12 -- pmcenter/Methods/Methods.LogMode.cs | 14 -- .../Methods/Methods.SerializeCurrentConf.cs | 2 +- pmcenter/Methods/Methods.StrChunk.cs | 2 +- pmcenter/Methods/Methods.ThreadStatus.cs | 2 +- .../NetworkTest/Methods.TestConnectivity.cs | 3 +- .../NetworkTest/Methods.TestLatency.cs | 3 +- .../Threads/Methods.ThrDoResetConfCount.cs | 2 +- .../Methods/Threads/Methods.ThrPerform.cs | 2 +- .../Methods/Threads/Methods.ThrRateLimiter.cs | 3 +- .../Methods/Threads/Methods.ThrSyncConf.cs | 3 +- .../Threads/Methods.ThrUpdateChecker.cs | 3 +- ...thods.UpdateHelper.CheckForUpdatesAsync.cs | 4 +- .../Methods.UpdateHelper.DownloadLangAsync.cs | 6 +- ...ethods.UpdateHelper.DownloadUpdateAsync.cs | 7 +- ...UpdateHelper.GetUpdateInfoIndexByLocale.cs | 4 +- ...ds.UpdateHelper.IsNewerVersionAvailable.cs | 4 +- .../Methods.UpdateHelper.Update.cs | 4 +- .../Methods.UpdateHelper.Update2.cs | 4 +- .../Methods.UpdateHelper.UpdateLevel.cs | 4 +- pmcenter/Program.cs | 9 +- pmcenter/Setup.cs | 6 +- 99 files changed, 376 insertions(+), 362 deletions(-) create mode 100644 pmcenter/Methods/Logging/Methods.Log.cs create mode 100644 pmcenter/Methods/Logging/Methods.LogLevel.cs create mode 100644 pmcenter/Methods/Logging/Methods.LogMode.cs create mode 100644 pmcenter/Methods/Logging/Methods.LogTable.cs delete mode 100644 pmcenter/Methods/Methods.Log.cs delete mode 100644 pmcenter/Methods/Methods.LogLevel.cs delete mode 100644 pmcenter/Methods/Methods.LogMode.cs diff --git a/README.md b/README.md index e089dcd..dfa3184 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # pmcenter -[![build status](https://ci.appveyor.com/api/projects/status/gmbdiackw0563980?svg=true)](https://ci.appveyor.com/project/Elepover/pmcenter) [![CodeFactor](https://www.codefactor.io/repository/github/elepover/pmcenter/badge)](https://www.codefactor.io/repository/github/elepover/pmcenter) [![telegram channel](https://img.shields.io/badge/telegram-channel-blue.svg)](https://t.me/pmcenter_devlog) ![license](https://img.shields.io/github/license/elepover/pmcenter.svg) ![language rank](https://img.shields.io/github/languages/top/elepover/pmcenter.svg?color=brightgreen) ![repo size in bytes](https://img.shields.io/github/repo-size/elepover/pmcenter.svg) ![environment](https://img.shields.io/badge/dotnet-v2.1-blue.svg) ![last commit](https://img.shields.io/github/last-commit/elepover/pmcenter.svg) ![status](https://img.shields.io/badge/status-maintaining-success.svg) +[![build status](https://ci.appveyor.com/api/projects/status/gmbdiackw0563980?svg=true)](https://ci.appveyor.com/project/Elepover/pmcenter) [![CodeFactor](https://www.codefactor.io/repository/github/elepover/pmcenter/badge)](https://www.codefactor.io/repository/github/elepover/pmcenter) [![telegram channel](https://img.shields.io/badge/telegram-channel-blue.svg)](https://t.me/pmcenter_devlog) ![license](https://img.shields.io/github/license/elepover/pmcenter.svg) ![language rank](https://img.shields.io/github/languages/top/elepover/pmcenter.svg?color=brightgreen) ![repo size in bytes](https://img.shields.io/github/repo-size/elepover/pmcenter.svg) ![environment](https://img.shields.io/badge/dotnet-v3.1-blueviolet.svg) ![last commit](https://img.shields.io/github/last-commit/elepover/pmcenter.svg) ![status](https://img.shields.io/badge/status-maintaining-success.svg) A telegram bot helping you process private messages. diff --git a/README_zh.md b/README_zh.md index ce485d5..2eb113d 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,6 +1,6 @@ # pmcenter -[![build status](https://ci.appveyor.com/api/projects/status/gmbdiackw0563980?svg=true)](https://ci.appveyor.com/project/Elepover/pmcenter) [![CodeFactor](https://www.codefactor.io/repository/github/elepover/pmcenter/badge)](https://www.codefactor.io/repository/github/elepover/pmcenter) [![telegram channel](https://img.shields.io/badge/telegram-channel-blue.svg)](https://t.me/pmcenter_devlog) ![license](https://img.shields.io/github/license/elepover/pmcenter.svg) ![language rank](https://img.shields.io/github/languages/top/elepover/pmcenter.svg?color=brightgreen) ![repo size in bytes](https://img.shields.io/github/repo-size/elepover/pmcenter.svg) ![environment](https://img.shields.io/badge/dotnet-v2.1-blue.svg) ![last commit](https://img.shields.io/github/last-commit/elepover/pmcenter.svg) ![status](https://img.shields.io/badge/status-maintaining-success.svg) +[![build status](https://ci.appveyor.com/api/projects/status/gmbdiackw0563980?svg=true)](https://ci.appveyor.com/project/Elepover/pmcenter) [![CodeFactor](https://www.codefactor.io/repository/github/elepover/pmcenter/badge)](https://www.codefactor.io/repository/github/elepover/pmcenter) [![telegram channel](https://img.shields.io/badge/telegram-channel-blue.svg)](https://t.me/pmcenter_devlog) ![license](https://img.shields.io/github/license/elepover/pmcenter.svg) ![language rank](https://img.shields.io/github/languages/top/elepover/pmcenter.svg?color=brightgreen) ![repo size in bytes](https://img.shields.io/github/repo-size/elepover/pmcenter.svg) ![environment](https://img.shields.io/badge/dotnet-v3.1-blueviolet.svg) ![last commit](https://img.shields.io/github/last-commit/elepover/pmcenter.svg) ![status](https://img.shields.io/badge/status-maintaining-success.svg) 一个帮你处理私人聊天消息的 Telegram 机器人。 diff --git a/pmcenter/.editorconfig b/pmcenter/.editorconfig index 6f1602b..96e4170 100644 --- a/pmcenter/.editorconfig +++ b/pmcenter/.editorconfig @@ -1,13 +1,13 @@ [*.cs] # CA1303: Do not pass literals as localized parameters -dotnet_diagnostic.CA1303.severity = suggestion +dotnet_diagnostic.CA1303.severity = none # CA1031: Do not catch general exception types -dotnet_diagnostic.CA1031.severity = suggestion +dotnet_diagnostic.CA1031.severity = none # CA1307: Specify StringComparison -dotnet_diagnostic.CA1307.severity = suggestion +dotnet_diagnostic.CA1307.severity = none # CA1304: Specify CultureInfo dotnet_diagnostic.CA1304.severity = suggestion @@ -25,7 +25,7 @@ dotnet_diagnostic.CA1052.severity = suggestion dotnet_diagnostic.CA1056.severity = suggestion # CA1062: Validate arguments of public methods -dotnet_diagnostic.CA1062.severity = suggestion +dotnet_diagnostic.CA1062.severity = none # CA1707: Identifiers should not contain underscores dotnet_diagnostic.CA1707.severity = suggestion diff --git a/pmcenter/BotCommands/BackupConfCommand.cs b/pmcenter/BotCommands/BackupConfCommand.cs index 5520b7b..b5fe09e 100644 --- a/pmcenter/BotCommands/BackupConfCommand.cs +++ b/pmcenter/BotCommands/BackupConfCommand.cs @@ -5,6 +5,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { @@ -16,7 +17,7 @@ internal class BackupConfCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var RandomFilename = $"pmcenter.{DateTime.Now.ToString("yyyy-dd-M-HH-mm-ss")}#{GetRandomString(6)}.json"; + var RandomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; Log($"Backing up configurations, filename: {Path.Combine(Vars.AppDirectory, RandomFilename)}", "BOT"); System.IO.File.Copy(Vars.ConfFile, RandomFilename); _ = await botClient.SendTextMessageAsync( diff --git a/pmcenter/BotCommands/Chat.cs b/pmcenter/BotCommands/Chat.cs index eba0ff9..d2de934 100644 --- a/pmcenter/BotCommands/Chat.cs +++ b/pmcenter/BotCommands/Chat.cs @@ -4,6 +4,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { @@ -63,7 +64,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } catch (Exception ex) { - Log($"Failed to enable Continued Conversation: {ex.ToString()}", "BOT", LogLevel.ERROR); + Log($"Failed to enable Continued Conversation: {ex}", "BOT", LogLevel.ERROR); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), ParseMode.Default, diff --git a/pmcenter/BotCommands/ClearMessageLinksCommand.cs b/pmcenter/BotCommands/ClearMessageLinksCommand.cs index b1c7616..c759060 100644 --- a/pmcenter/BotCommands/ClearMessageLinksCommand.cs +++ b/pmcenter/BotCommands/ClearMessageLinksCommand.cs @@ -2,7 +2,7 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { diff --git a/pmcenter/BotCommands/EditConfCommand.cs b/pmcenter/BotCommands/EditConfCommand.cs index 6351961..63a4a0b 100644 --- a/pmcenter/BotCommands/EditConfCommand.cs +++ b/pmcenter/BotCommands/EditConfCommand.cs @@ -6,6 +6,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index d8ed91c..56d57fc 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -26,9 +26,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.MessageId).ConfigureAwait(false); var OwnerID = Vars.CurrentConf.OwnerUID; var APIKey = Vars.CurrentConf.APIKey; - Vars.CurrentConf = new Conf.ConfObj(); - Vars.CurrentConf.OwnerUID = OwnerID; - Vars.CurrentConf.APIKey = APIKey; + Vars.CurrentConf = new Conf.ConfObj + { + OwnerUID = OwnerID, + APIKey = APIKey + }; _ = await Conf.SaveConf(false, true).ConfigureAwait(false); Vars.CurrentLang = new Lang.Language(); _ = await Lang.SaveLang().ConfigureAwait(false); diff --git a/pmcenter/BotCommands/StopChat.cs b/pmcenter/BotCommands/StopChat.cs index a7c19e3..3103d05 100644 --- a/pmcenter/BotCommands/StopChat.cs +++ b/pmcenter/BotCommands/StopChat.cs @@ -3,6 +3,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { diff --git a/pmcenter/BotCommands/TestNetwork.cs b/pmcenter/BotCommands/TestNetwork.cs index db68663..7558c6c 100644 --- a/pmcenter/BotCommands/TestNetwork.cs +++ b/pmcenter/BotCommands/TestNetwork.cs @@ -4,6 +4,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index 1581e76..7ccbe76 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -3,6 +3,7 @@ using Telegram.Bot; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; using static pmcenter.Methods.UpdateHelper; namespace pmcenter.Commands diff --git a/pmcenter/BotProcess.cs b/pmcenter/BotProcess.cs index b335840..e398fe6 100644 --- a/pmcenter/BotProcess.cs +++ b/pmcenter/BotProcess.cs @@ -11,6 +11,7 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { @@ -64,7 +65,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) if (e == null) return; if (Vars.CurrentConf.DetailedMsgLogging) { - Log($"OnUpdate() triggered: UpdType: {e.Update.Type.ToString()} UpdID: {e.Update.Id} ChatId: {e.Update.Message.Chat.Id} Username: {e.Update.Message.Chat.Username} FromID: {e.Update.Message.From.Id} FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.INFO); + Log($"OnUpdate() triggered: UpdType: {e.Update.Type} UpdID: {e.Update.Id} ChatId: {e.Update.Message.Chat.Id} Username: {e.Update.Message.Chat.Username} FromID: {e.Update.Message.From.Id} FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.INFO); } var update = e.Update; if (update.Type != UpdateType.Message) return; @@ -89,7 +90,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) } catch (Exception ex) { - Log($"General error while processing incoming update: {ex.ToString()}", "BOT", LogLevel.ERROR); + Log($"General error while processing incoming update: {ex}", "BOT", LogLevel.ERROR); if (Vars.CurrentConf.CatchAllExceptions) { try @@ -102,7 +103,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) } catch (Exception iEx) { - Log($"Failed to catch exception to owner: {iEx.ToString()}", "BOT", LogLevel.ERROR); + Log($"Failed to catch exception to owner: {iEx}", "BOT", LogLevel.ERROR); } } } diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLineRouter.cs index 780ed9c..298cb61 100644 --- a/pmcenter/CommandLineRouter.cs +++ b/pmcenter/CommandLineRouter.cs @@ -8,8 +8,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { @@ -58,7 +57,7 @@ public async Task Execute(string cmdLine) } catch (Exception ex) { - Log($"Exception while executing commandline: {ex.ToString()}", "CMD", LogLevel.ERROR); + Log($"Exception while executing commandline: {ex}", "CMD", LogLevel.ERROR); Environment.Exit(1); } Log("Command finished.", "CMD"); diff --git a/pmcenter/CommandLines/BackupCmdLine.cs b/pmcenter/CommandLines/BackupCmdLine.cs index df4ee23..22333b7 100644 --- a/pmcenter/CommandLines/BackupCmdLine.cs +++ b/pmcenter/CommandLines/BackupCmdLine.cs @@ -1,9 +1,8 @@ using System; using System.IO; -using System.Runtime.InteropServices; using System.Threading.Tasks; - using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { @@ -14,7 +13,7 @@ internal class BackupCmdLine : ICmdLine public Task Process() { Log("Backing up...", "CMD"); - var RandomFilename = $"pmcenter.{DateTime.Now.ToString("yyyy-dd-M-HH-mm-ss")}#{GetRandomString(6)}.json"; + var RandomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; RandomFilename = Path.Combine(Vars.AppDirectory, RandomFilename); File.Copy(Vars.ConfFile, RandomFilename); Log($"Backup complete. Filename: {RandomFilename}", "CMD"); diff --git a/pmcenter/CommandLines/HelpCmdLine.cs b/pmcenter/CommandLines/HelpCmdLine.cs index 3c27047..646cf63 100644 --- a/pmcenter/CommandLines/HelpCmdLine.cs +++ b/pmcenter/CommandLines/HelpCmdLine.cs @@ -1,7 +1,5 @@ -using System; -using System.Threading.Tasks; - -using static pmcenter.Methods; +using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { diff --git a/pmcenter/CommandLines/InfoCmdLine.cs b/pmcenter/CommandLines/InfoCmdLine.cs index 70d13e8..efee1b9 100644 --- a/pmcenter/CommandLines/InfoCmdLine.cs +++ b/pmcenter/CommandLines/InfoCmdLine.cs @@ -1,8 +1,8 @@ using System; using System.Runtime.InteropServices; using System.Threading.Tasks; - using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { @@ -17,9 +17,9 @@ public async Task Process() var IsGitHubAccessible = await TestConnectivity("https://raw.githubusercontent.com/", true).ConfigureAwait(false); var IsCIAvailable = await TestConnectivity("https://ci.appveyor.com/", true).ConfigureAwait(false); Log("Application information", "CMD"); - Log($"CLR version: {Environment.Version.ToString()}", "CMD"); + Log($"CLR version: {Environment.Version}", "CMD"); Log($"Framework description: {RuntimeInformation.FrameworkDescription}", "CMD"); - Log($"Application version: {Vars.AppVer.ToString()}", "CMD"); + Log($"Application version: {Vars.AppVer}", "CMD"); Log($"Configurations filename: {Vars.ConfFile}", "CMD"); Log($"Language filename: {Vars.LangFile}", "CMD"); Log($"Is Telegram API accessible? {(IsTelegramAPIAccessible ? "yes" : "no")}", "CMD"); diff --git a/pmcenter/CommandLines/NonServiceModeCmdLine.cs b/pmcenter/CommandLines/NonServiceModeCmdLine.cs index 3627ceb..28add83 100644 --- a/pmcenter/CommandLines/NonServiceModeCmdLine.cs +++ b/pmcenter/CommandLines/NonServiceModeCmdLine.cs @@ -1,8 +1,5 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -using static pmcenter.Methods; +using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { diff --git a/pmcenter/CommandLines/ResetCmdLine.cs b/pmcenter/CommandLines/ResetCmdLine.cs index f6eac32..a3fc771 100644 --- a/pmcenter/CommandLines/ResetCmdLine.cs +++ b/pmcenter/CommandLines/ResetCmdLine.cs @@ -1,8 +1,5 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -using static pmcenter.Methods; +using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { diff --git a/pmcenter/CommandLines/SetupWizardCmdLine.cs b/pmcenter/CommandLines/SetupWizardCmdLine.cs index cf0615d..b262bd2 100644 --- a/pmcenter/CommandLines/SetupWizardCmdLine.cs +++ b/pmcenter/CommandLines/SetupWizardCmdLine.cs @@ -1,8 +1,5 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -using static pmcenter.Methods; +using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index b00b4bb..5317ba3 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; using static pmcenter.Methods.UpdateHelper; - -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.CommandLines { diff --git a/pmcenter/Configurations/Conf.BanObj.cs b/pmcenter/Configurations/Conf.BanObj.cs index 75bb77d..14b4c13 100644 --- a/pmcenter/Configurations/Conf.BanObj.cs +++ b/pmcenter/Configurations/Conf.BanObj.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class BanObj { diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index acafe53..cf97fa3 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { - public partial class ConfObj + public sealed partial class ConfObj { public ConfObj() { diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index 78aba7a..103dd09 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -2,48 +2,48 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { - public partial class ConfObj + public sealed partial class ConfObj { - public string APIKey; - public long OwnerUID; - public bool EnableCc; - public List Cc; - public bool AutoBan; - public int AutoBanThreshold; - public bool ForwardingPaused; - public bool KeywordBanning; - public bool KeywordAutoBan; - public bool EnableRegex; - public bool AutoLangUpdate; - public string LangURL; - public bool DisableNotifications; - public bool EnableRepliedConfirmation; - public bool EnableForwardedConfirmation; - public bool EnableAutoUpdateCheck; - public bool UseUsernameInMsgInfo; - public string DonateString; - public bool LowPerformanceMode; - public bool DetailedMsgLogging; - public bool UseProxy; - public bool ResolveHostnamesLocally; - public bool CatchAllExceptions; - public bool NoStartupMessage; - public long ContChatTarget; - public bool EnableMsgLink; - public bool AllowUserRetraction; - public int ConfSyncInterval; - public bool AdvancedLogging; - public bool DisableTimeDisplay; - public string UpdateChannel; - public bool IgnoreKeyboardInterrupt; - public bool DisableNetCore3Check; - public Stats Statistics; - public List Socks5Proxies; - public List BannedKeywords; - public List Banned; - public List MessageLinks; + public string APIKey { get; set; } + public long OwnerUID { get; set; } + public bool EnableCc { get; set; } + public List Cc { get; set; } + public bool AutoBan { get; set; } + public int AutoBanThreshold { get; set; } + public bool ForwardingPaused { get; set; } + public bool KeywordBanning { get; set; } + public bool KeywordAutoBan { get; set; } + public bool EnableRegex { get; set; } + public bool AutoLangUpdate { get; set; } + public string LangURL { get; set; } + public bool DisableNotifications { get; set; } + public bool EnableRepliedConfirmation { get; set; } + public bool EnableForwardedConfirmation { get; set; } + public bool EnableAutoUpdateCheck { get; set; } + public bool UseUsernameInMsgInfo { get; set; } + public string DonateString { get; set; } + public bool LowPerformanceMode { get; set; } + public bool DetailedMsgLogging { get; set; } + public bool UseProxy { get; set; } + public bool ResolveHostnamesLocally { get; set; } + public bool CatchAllExceptions { get; set; } + public bool NoStartupMessage { get; set; } + public long ContChatTarget { get; set; } + public bool EnableMsgLink { get; set; } + public bool AllowUserRetraction { get; set; } + public int ConfSyncInterval { get; set; } + public bool AdvancedLogging { get; set; } + public bool DisableTimeDisplay { get; set; } + public string UpdateChannel { get; set; } + public bool IgnoreKeyboardInterrupt { get; set; } + public bool DisableNetCore3Check { get; set; } + public Stats Statistics { get; set; } + public List Socks5Proxies { get; set; } + public List BannedKeywords { get; set; } + public List Banned { get; set; } + public List MessageLinks { get; set; } } } } diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index 68b06cf..dab0fd8 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public static async Task GetConf(string Filename) { diff --git a/pmcenter/Configurations/Conf.InitConf.cs b/pmcenter/Configurations/Conf.InitConf.cs index 8ae26dc..eb91246 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -1,10 +1,10 @@ using System; using System.Threading.Tasks; -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public static async Task InitConf() { @@ -23,7 +23,7 @@ public static async Task InitConf() } catch (Exception ex) { - Log($"Error! {ex.ToString()}", "CONF", LogLevel.ERROR); + Log($"Error! {ex}", "CONF", LogLevel.ERROR); Log("Moving old configurations file to \"pmcenter.json.bak\"...", "CONF", LogLevel.WARN); System.IO.File.Move(Vars.ConfFile, Vars.ConfFile + ".bak"); Vars.CurrentConf = new ConfObj(); diff --git a/pmcenter/Configurations/Conf.KillIllegalChars.cs b/pmcenter/Configurations/Conf.KillIllegalChars.cs index 4b3dc05..1b5e9ad 100644 --- a/pmcenter/Configurations/Conf.KillIllegalChars.cs +++ b/pmcenter/Configurations/Conf.KillIllegalChars.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public static string KillIllegalChars(string Input) { diff --git a/pmcenter/Configurations/Conf.LocaleList.cs b/pmcenter/Configurations/Conf.LocaleList.cs index 8618bf3..51ffeb8 100644 --- a/pmcenter/Configurations/Conf.LocaleList.cs +++ b/pmcenter/Configurations/Conf.LocaleList.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class LocaleList { diff --git a/pmcenter/Configurations/Conf.LocaleMirror.cs b/pmcenter/Configurations/Conf.LocaleMirror.cs index aab84c6..08b0f94 100644 --- a/pmcenter/Configurations/Conf.LocaleMirror.cs +++ b/pmcenter/Configurations/Conf.LocaleMirror.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class LocaleMirror { diff --git a/pmcenter/Configurations/Conf.MessageIDLink.cs b/pmcenter/Configurations/Conf.MessageIDLink.cs index 23d97b5..81d5067 100644 --- a/pmcenter/Configurations/Conf.MessageIDLink.cs +++ b/pmcenter/Configurations/Conf.MessageIDLink.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class MessageIDLink { diff --git a/pmcenter/Configurations/Conf.RateData.cs b/pmcenter/Configurations/Conf.RateData.cs index 02de594..02037ba 100644 --- a/pmcenter/Configurations/Conf.RateData.cs +++ b/pmcenter/Configurations/Conf.RateData.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class RateData { diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index b3d859a..1590f59 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public static async Task ReadConf(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index 34b1138..6edc926 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -1,11 +1,10 @@ -using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. diff --git a/pmcenter/Configurations/Conf.Socks5Proxy.cs b/pmcenter/Configurations/Conf.Socks5Proxy.cs index 5138160..17f6fa4 100644 --- a/pmcenter/Configurations/Conf.Socks5Proxy.cs +++ b/pmcenter/Configurations/Conf.Socks5Proxy.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class Socks5Proxy { diff --git a/pmcenter/Configurations/Conf.Stats.cs b/pmcenter/Configurations/Conf.Stats.cs index 7cbd9a7..8fa6fe9 100644 --- a/pmcenter/Configurations/Conf.Stats.cs +++ b/pmcenter/Configurations/Conf.Stats.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { public class Stats { diff --git a/pmcenter/Configurations/Conf.SwitchBlocking.cs b/pmcenter/Configurations/Conf.SwitchBlocking.cs index bf8295a..38edeb1 100644 --- a/pmcenter/Configurations/Conf.SwitchBlocking.cs +++ b/pmcenter/Configurations/Conf.SwitchBlocking.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { /// /// Switch 'blocking' status, returning current status. diff --git a/pmcenter/Configurations/Conf.SwitchNotifications.cs b/pmcenter/Configurations/Conf.SwitchNotifications.cs index 3dd4813..59edb9b 100644 --- a/pmcenter/Configurations/Conf.SwitchNotifications.cs +++ b/pmcenter/Configurations/Conf.SwitchNotifications.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { /// /// Switch 'disablenotifications' status, returning current status. diff --git a/pmcenter/Configurations/Conf.SwitchPaused.cs b/pmcenter/Configurations/Conf.SwitchPaused.cs index b2fd042..9871bf7 100644 --- a/pmcenter/Configurations/Conf.SwitchPaused.cs +++ b/pmcenter/Configurations/Conf.SwitchPaused.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Conf + public sealed partial class Conf { /// /// Switch 'forwarding' status, returning current status. diff --git a/pmcenter/Configurations/Lang.InitLang.cs b/pmcenter/Configurations/Lang.InitLang.cs index e4e1a56..beaabab 100644 --- a/pmcenter/Configurations/Lang.InitLang.cs +++ b/pmcenter/Configurations/Lang.InitLang.cs @@ -2,10 +2,11 @@ using System.IO; using System.Threading.Tasks; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Lang + public sealed partial class Lang { public static async Task InitLang() { @@ -24,7 +25,7 @@ public static async Task InitLang() } catch (Exception ex) { - Log($"Error! {ex.ToString()}", "LANG", LogLevel.ERROR); + Log($"Error! {ex}", "LANG", LogLevel.ERROR); Log("Moving old language file to \"pmcenter_locale.json.bak\"...", "LANG", LogLevel.WARN); File.Move(Vars.LangFile, Vars.LangFile + ".bak"); Vars.CurrentLang = new Language(); diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index 55104a2..80a1adc 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -1,8 +1,8 @@ namespace pmcenter { - public partial class Lang + public sealed partial class Lang { - public partial class Language + public sealed partial class Language { public Language() { diff --git a/pmcenter/Configurations/Lang.Language.cs b/pmcenter/Configurations/Lang.Language.cs index e016896..8a72201 100644 --- a/pmcenter/Configurations/Lang.Language.cs +++ b/pmcenter/Configurations/Lang.Language.cs @@ -1,81 +1,81 @@ namespace pmcenter { - public partial class Lang + public sealed partial class Lang { - public partial class Language + public sealed partial class Language { - public string TargetVersion; - public string LangCode; - public string LanguageNameInEnglish; - public string LanguageNameInNative; - public string Message_OwnerStart; - public string Message_UserStartDefault; - public string Message_ReplySuccessful; - public string Message_ForwardedToOwner; - public string Message_Help; - public string Message_UserBanned; - public string Message_UserPardoned; - public string Message_CommandNotReplying; - public string Message_CommandNotReplyingValidMessage; - public string Message_PingReply; - public string Message_ServicePaused; - public string Message_ServiceResumed; - public string Message_UserServicePaused; - public string Message_BotStarted; - public string Message_MessageBlockEnabled; - public string Message_MessageBlockDisabled; - public string Message_ConfigUpdated; - public string Message_ConfigReloaded; - public string Message_UptimeInfo; - public string Message_UpdateAvailable; - public string Message_UpdateProcessing; - public string Message_UpdateCheckFailed; - public string Message_AlreadyUpToDate; - public string Message_UpdateExtracting; - public string Message_UpdateFinalizing; - public string Message_CurrentConf; - public string Message_SysStatus_Header; - public string Message_SysStatus_RestartRequired; - public string Message_SysStatus_PendingUpdate; - public string Message_SysStatus_UpdateLevel_Template; - public string Message_SysStatus_UpdateLevel_Optional; - public string Message_SysStatus_UpdateLevel_Recommended; - public string Message_SysStatus_UpdateLevel_Important; - public string Message_SysStatus_UpdateLevel_Urgent; - public string Message_SysStatus_UpdateLevel_Unknown; - public string Message_SysStatus_NoOperationRequired; - public string Message_SysStatus_Summary; - public string Message_Restarting; - public string Message_NotificationsOff; - public string Message_NotificationsOn; - public string Message_SupportTextMessagesOnly; - public string Message_ForwarderNotReal; - public string Message_GeneralFailure; - public string Message_LangVerMismatch; - public string Message_SwitchingLang; - public string Message_LangSwitched; - public string Message_ThreadStatus_Unknown; - public string Message_ThreadStatus_Standby; - public string Message_ThreadStatus_Working; - public string Message_ThreadStatus_Stopped; - public string Message_ThreadStatus_Error; - public string Message_ConfReset_Inited; - public string Message_ConfReset_Started; - public string Message_ConfReset_Done; - public string Message_Performance_Inited; - public string Message_Performance_Results; - public string Message_BackupComplete; - public string Message_ConfAccess; - public string Message_APIKeyChanged; - public string Message_Connectivity; - public string Message_ContinuedChatEnabled; - public string Message_ContinuedChatDisabled; - public string Message_FeatureNotAvailable; - public string Message_Stats; - public string Message_Retracted; - public string Message_MsgLinksCleared; - public string Message_AvailableLang; - public string Message_NetCore31Required; + public string TargetVersion { get; set; } + public string LangCode { get; set; } + public string LanguageNameInEnglish { get; set; } + public string LanguageNameInNative { get; set; } + public string Message_OwnerStart { get; set; } + public string Message_UserStartDefault { get; set; } + public string Message_ReplySuccessful { get; set; } + public string Message_ForwardedToOwner { get; set; } + public string Message_Help { get; set; } + public string Message_UserBanned { get; set; } + public string Message_UserPardoned { get; set; } + public string Message_CommandNotReplying { get; set; } + public string Message_CommandNotReplyingValidMessage { get; set; } + public string Message_PingReply { get; set; } + public string Message_ServicePaused { get; set; } + public string Message_ServiceResumed { get; set; } + public string Message_UserServicePaused { get; set; } + public string Message_BotStarted { get; set; } + public string Message_MessageBlockEnabled { get; set; } + public string Message_MessageBlockDisabled { get; set; } + public string Message_ConfigUpdated { get; set; } + public string Message_ConfigReloaded { get; set; } + public string Message_UptimeInfo { get; set; } + public string Message_UpdateAvailable { get; set; } + public string Message_UpdateProcessing { get; set; } + public string Message_UpdateCheckFailed { get; set; } + public string Message_AlreadyUpToDate { get; set; } + public string Message_UpdateExtracting { get; set; } + public string Message_UpdateFinalizing { get; set; } + public string Message_CurrentConf { get; set; } + public string Message_SysStatus_Header { get; set; } + public string Message_SysStatus_RestartRequired { get; set; } + public string Message_SysStatus_PendingUpdate { get; set; } + public string Message_SysStatus_UpdateLevel_Template { get; set; } + public string Message_SysStatus_UpdateLevel_Optional { get; set; } + public string Message_SysStatus_UpdateLevel_Recommended { get; set; } + public string Message_SysStatus_UpdateLevel_Important { get; set; } + public string Message_SysStatus_UpdateLevel_Urgent { get; set; } + public string Message_SysStatus_UpdateLevel_Unknown { get; set; } + public string Message_SysStatus_NoOperationRequired { get; set; } + public string Message_SysStatus_Summary { get; set; } + public string Message_Restarting { get; set; } + public string Message_NotificationsOff { get; set; } + public string Message_NotificationsOn { get; set; } + public string Message_SupportTextMessagesOnly { get; set; } + public string Message_ForwarderNotReal { get; set; } + public string Message_GeneralFailure { get; set; } + public string Message_LangVerMismatch { get; set; } + public string Message_SwitchingLang { get; set; } + public string Message_LangSwitched { get; set; } + public string Message_ThreadStatus_Unknown { get; set; } + public string Message_ThreadStatus_Standby { get; set; } + public string Message_ThreadStatus_Working { get; set; } + public string Message_ThreadStatus_Stopped { get; set; } + public string Message_ThreadStatus_Error { get; set; } + public string Message_ConfReset_Inited { get; set; } + public string Message_ConfReset_Started { get; set; } + public string Message_ConfReset_Done { get; set; } + public string Message_Performance_Inited { get; set; } + public string Message_Performance_Results { get; set; } + public string Message_BackupComplete { get; set; } + public string Message_ConfAccess { get; set; } + public string Message_APIKeyChanged { get; set; } + public string Message_Connectivity { get; set; } + public string Message_ContinuedChatEnabled { get; set; } + public string Message_ContinuedChatDisabled { get; set; } + public string Message_FeatureNotAvailable { get; set; } + public string Message_Stats { get; set; } + public string Message_Retracted { get; set; } + public string Message_MsgLinksCleared { get; set; } + public string Message_AvailableLang { get; set; } + public string Message_NetCore31Required { get; set; } } } } diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index 40072fc..bc64d46 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public partial class Lang + public sealed partial class Lang { public static async Task ReadLang(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index 95b7962..981b860 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -1,11 +1,11 @@ using System.IO; using System.Threading.Tasks; using Newtonsoft.Json; -using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Lang + public sealed partial class Lang { public static async Task SaveLang(bool isInvalid = false) { // DO NOT HANDLE ERRORS HERE. diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index 36a6c06..a0a9595 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -1,9 +1,10 @@ using System; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class EventHandlers + public sealed partial class EventHandlers { public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) { @@ -17,7 +18,7 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) if (Vars.CurrentConf.IgnoreKeyboardInterrupt) { Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", LogLevel.WARN); - e.Cancel = true; + if (e != null) e.Cancel = true; return; } Vars.IsCtrlCHandled = true; diff --git a/pmcenter/EventHandlers/GlobalErrorHandler.cs b/pmcenter/EventHandlers/GlobalErrorHandler.cs index eb38cfc..30733a4 100644 --- a/pmcenter/EventHandlers/GlobalErrorHandler.cs +++ b/pmcenter/EventHandlers/GlobalErrorHandler.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public partial class EventHandlers + public sealed partial class EventHandlers { public static void GlobalErrorHandler(object sender, UnhandledExceptionEventArgs e) { @@ -14,10 +14,9 @@ public static void GlobalErrorHandler(object sender, UnhandledExceptionEventArgs L("pmcenter's global error handler has captured a critical error."); L("If you believe that this is a bug, feel free to open an issue with the details below on pmcenter's GitHub repository at:"); L("https://github.com/Elepover/pmcenter"); - L(e.IsTerminating ? "" : "This is not a catastrophic. pmcenter will keep running.\nIf you encounter more errors, please consider restarting pmcenter."); - var exception = (Exception) e.ExceptionObject; + var exception = e != null ? (Exception)e.ExceptionObject : new Exception("unknown error"); var fileName = Path.Combine(Environment.CurrentDirectory, $"pmcenter-error-{GetDateTimeString(true)}.log"); - L($"Exception details: {exception.ToString()}"); + L($"Exception details: {exception}"); L($"Attempting to write to {fileName}"); try { @@ -25,19 +24,15 @@ public static void GlobalErrorHandler(object sender, UnhandledExceptionEventArgs writer.WriteLine($"pmcenter critical error log @{GetDateTimeString()} (local time)"); writer.WriteLine($"Framework: {RuntimeInformation.FrameworkDescription}\nSystem: {RuntimeInformation.OSDescription}"); writer.WriteLine("If you believe that this is a bug, feel free to open an issue with the details below on pmcenter's GitHub repository at https://github.com/Elepover/pmcenter"); - writer.WriteLine($"==> HRESULT 0x{exception.HResult.ToString("x")} error details:"); + writer.WriteLine($"==> HRESULT 0x{exception.HResult:x} error details:"); writer.WriteLine(exception.ToString()); writer.Close(); } catch (Exception ex) { - L($"Unable to save error logs: {ex.ToString()}"); - } - if (e.IsTerminating) - { - L("Since it's a catastrophic error, pmcenter will exit now."); - Environment.Exit(Marshal.GetHRForException(exception)); + L($"Unable to save error logs: {ex}"); } + Environment.Exit(Marshal.GetHRForException(exception)); } private static void L(string log) diff --git a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs index 2e0f540..82157ec 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static BanObj GetBanObjByID(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs index b839172..e31e17c 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static MessageIDLink GetLinkByOwnerMsgID(long OwnerSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs index 6fabd71..716a5e4 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static MessageIDLink GetLinkByUserMsgID(long UserSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs index e7fd08c..81bec0d 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static int GetRateDataIndexByID(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index e51e28e..84c699c 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsBanned(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs index 5a65e27..a6e4469 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsKeywordBanned(string Sentence) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs index 7e15d25..dd9e17e 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsOwnerRetractionAvailable(int OwnerSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs index 47e4634..e06b101 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsRateDataTracking(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs index 45bf343..cd11708 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsUserRetractionAvailable(int UserSessionMsgID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs index c8a9fbb..e66c364 100644 --- a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs +++ b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void AddRateLimit(long UID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs index 54b3db6..6696917 100644 --- a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void BanUser(long UID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs index 249878b..954ec9e 100644 --- a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void UnbanUser(long UID) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs index faa860d..0ad86e1 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -4,9 +4,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class H2Helper + public sealed partial class H2Helper { public static async Task DownloadFileAsync(Uri uri, string filename) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs index c0e63b4..3e104be 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -3,9 +3,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class H2Helper + public sealed partial class H2Helper { public static async Task GetBytesAsync(Uri uri) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs index 91d3220..5be4303 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs @@ -4,9 +4,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class H2Helper + public sealed partial class H2Helper { private static async Task GetHttpContentAsync(Uri uri) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs index 4de3feb..3d34ece 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -3,9 +3,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class H2Helper + public sealed partial class H2Helper { public static async Task GetStringAsync(Uri uri) { diff --git a/pmcenter/Methods/Logging/Methods.Log.cs b/pmcenter/Methods/Logging/Methods.Log.cs new file mode 100644 index 0000000..51d9c79 --- /dev/null +++ b/pmcenter/Methods/Logging/Methods.Log.cs @@ -0,0 +1,39 @@ +using System; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; + +namespace pmcenter +{ + public sealed partial class Methods + { + public sealed partial class Logging + { + public static void Log(string text, LogLevel type) + { + Log(text, "CORE", type); + } + public static void Log(string text, + string module = "CORE", + LogLevel type = LogLevel.INFO, + [CallerFilePath] string filePath = "file?", + [CallerMemberName] string callerName = "method?", + [CallerLineNumber] int lineNumber = 0) + { + if (Vars.CurrentConf?.LowPerformanceMode == true) return; + + var file = $"/{(Path.GetFileName((Environment.OSVersion.Platform == PlatformID.Unix) ? filePath.Replace(@"\", "/") : filePath))}/{callerName}()@L{lineNumber}"; + var Output = Vars.CurrentConf?.DisableTimeDisplay != true + ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" + : ""; + Output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; + Output += LogTable[type].Prefix; + Output += text; + Console.BackgroundColor = ConsoleColor.Black; + Console.ForegroundColor = LogTable[type].Color; + LogTable[type].Func(Output); + Console.ForegroundColor = ConsoleColor.White; + } + } + } +} diff --git a/pmcenter/Methods/Logging/Methods.LogLevel.cs b/pmcenter/Methods/Logging/Methods.LogLevel.cs new file mode 100644 index 0000000..03eb750 --- /dev/null +++ b/pmcenter/Methods/Logging/Methods.LogLevel.cs @@ -0,0 +1,15 @@ +namespace pmcenter +{ + public sealed partial class Methods + { + public sealed partial class Logging + { + public enum LogLevel + { + INFO = 0, + WARN = 1, + ERROR = 2, + } + } + } +} diff --git a/pmcenter/Methods/Logging/Methods.LogMode.cs b/pmcenter/Methods/Logging/Methods.LogMode.cs new file mode 100644 index 0000000..251e650 --- /dev/null +++ b/pmcenter/Methods/Logging/Methods.LogMode.cs @@ -0,0 +1,17 @@ +using System; + +namespace pmcenter +{ + public sealed partial class Methods + { + public sealed partial class Logging + { + public class LogMode + { + public ConsoleColor Color; + public string Prefix; + public Action Func; + } + } + } +} diff --git a/pmcenter/Methods/Logging/Methods.LogTable.cs b/pmcenter/Methods/Logging/Methods.LogTable.cs new file mode 100644 index 0000000..99cdf0e --- /dev/null +++ b/pmcenter/Methods/Logging/Methods.LogTable.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; + +namespace pmcenter +{ + public sealed partial class Methods + { + public sealed partial class Logging + { + public static Dictionary LogTable = new Dictionary() + { + {LogLevel.INFO, new LogMode() {Color = ConsoleColor.White, Prefix = "[INFO] ", Func = Console.WriteLine}}, + {LogLevel.WARN, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, + {LogLevel.ERROR, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} + }; + } + } +} diff --git a/pmcenter/Methods/Methods.BoolStr.cs b/pmcenter/Methods/Methods.BoolStr.cs index 42ad946..60edc70 100644 --- a/pmcenter/Methods/Methods.BoolStr.cs +++ b/pmcenter/Methods/Methods.BoolStr.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string BoolStr(bool Input) { diff --git a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index 77f852d..111cdb3 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -1,15 +1,16 @@ using System; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool CheckNetCoreVersion(Version version) { if (version.Major != 3 || version.Minor != 1) { Log("pmcenter v2 or up wouldn't run on devices without .NET Core 3.1 (runtime) installed.", LogLevel.WARN); - Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version.ToString()}.", LogLevel.WARN); + Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version}.", LogLevel.WARN); Log("Consider updating your .NET Core runtime in order to run pmcenter v2 and receive further updates.", LogLevel.WARN); return false; } diff --git a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs index d12c20f..8584e05 100644 --- a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs +++ b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs @@ -1,13 +1,15 @@ using System; using System.Net.Http; using System.Security.Authentication; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void CheckOpenSSLComp(Exception ex) { + if (ex == null) return; try { if (ex.GetType() == typeof(HttpRequestException)) diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index f8aab50..e862bdf 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -1,10 +1,11 @@ using System; using System.Diagnostics; using System.Threading; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void ExitApp(int code) { diff --git a/pmcenter/Methods/Methods.FlipBool.cs b/pmcenter/Methods/Methods.FlipBool.cs index e5f58c7..064ee51 100644 --- a/pmcenter/Methods/Methods.FlipBool.cs +++ b/pmcenter/Methods/Methods.FlipBool.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool FlipBool(bool Input) { diff --git a/pmcenter/Methods/Methods.GetDateTimeString.cs b/pmcenter/Methods/Methods.GetDateTimeString.cs index 21c0398..d24433b 100644 --- a/pmcenter/Methods/Methods.GetDateTimeString.cs +++ b/pmcenter/Methods/Methods.GetDateTimeString.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string GetDateTimeString(bool removeInvalidChar = false) { diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index a581cac..c9291ec 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -1,10 +1,10 @@ using System; using System.Diagnostics; -using System.Text; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static Version GetNetCoreVersion() { diff --git a/pmcenter/Methods/Methods.GetRandomString.cs b/pmcenter/Methods/Methods.GetRandomString.cs index 84ac5d6..2f259ea 100644 --- a/pmcenter/Methods/Methods.GetRandomString.cs +++ b/pmcenter/Methods/Methods.GetRandomString.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string GetRandomString(int length = 8) { diff --git a/pmcenter/Methods/Methods.GetThreadStatus.cs b/pmcenter/Methods/Methods.GetThreadStatus.cs index f2b7ea7..0c97ef2 100644 --- a/pmcenter/Methods/Methods.GetThreadStatus.cs +++ b/pmcenter/Methods/Methods.GetThreadStatus.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static ThreadStatus GetThreadStatus(Thread Thread) { diff --git a/pmcenter/Methods/Methods.GetThreadStatusString.cs b/pmcenter/Methods/Methods.GetThreadStatusString.cs index 324c7b1..6516484 100644 --- a/pmcenter/Methods/Methods.GetThreadStatusString.cs +++ b/pmcenter/Methods/Methods.GetThreadStatusString.cs @@ -1,22 +1,17 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string GetThreadStatusString(ThreadStatus Status) { - switch (Status) + return Status switch { - case ThreadStatus.Working: - return Vars.CurrentLang.Message_ThreadStatus_Working; - case ThreadStatus.Standby: - return Vars.CurrentLang.Message_ThreadStatus_Standby; - case ThreadStatus.Stopped: - return Vars.CurrentLang.Message_ThreadStatus_Stopped; - case ThreadStatus.Error: - return Vars.CurrentLang.Message_ThreadStatus_Error; - default: - return Vars.CurrentLang.Message_ThreadStatus_Unknown; - } + ThreadStatus.Working => Vars.CurrentLang.Message_ThreadStatus_Working, + ThreadStatus.Standby => Vars.CurrentLang.Message_ThreadStatus_Standby, + ThreadStatus.Stopped => Vars.CurrentLang.Message_ThreadStatus_Stopped, + ThreadStatus.Error => Vars.CurrentLang.Message_ThreadStatus_Error, + _ => Vars.CurrentLang.Message_ThreadStatus_Unknown, + }; } } } diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index b85e865..f6ce880 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -2,24 +2,19 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string GetUpdateLevel(UpdateLevel Level) { string Processed = Vars.CurrentLang.Message_SysStatus_UpdateLevel_Template; - switch (Level) + return Level switch { - case UpdateLevel.Optional: - return Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Optional); - case UpdateLevel.Recommended: - return Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Recommended); - case UpdateLevel.Important: - return Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Important); - case UpdateLevel.Urgent: - return Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Urgent); - default: - return Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Unknown); - } + UpdateLevel.Optional => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Optional), + UpdateLevel.Recommended => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Recommended), + UpdateLevel.Important => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Important), + UpdateLevel.Urgent => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Urgent), + _ => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Unknown), + }; } } } diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index 68807e9..aa68f78 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -1,9 +1,10 @@ using System; using System.Text.RegularExpressions; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static bool IsRegexMatch(string source, string expression) { diff --git a/pmcenter/Methods/Methods.Log.cs b/pmcenter/Methods/Methods.Log.cs deleted file mode 100644 index e4ac250..0000000 --- a/pmcenter/Methods/Methods.Log.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; - -namespace pmcenter -{ - public partial class Methods - { - public static Dictionary LogTable = new Dictionary() - { - {LogLevel.INFO, new LogMode() {Color = ConsoleColor.White, Prefix = "[INFO] ", Func = Console.WriteLine}}, - {LogLevel.WARN, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, - {LogLevel.ERROR, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} - }; // table-driven - - public static void Log(string text, LogLevel type) - { - Log(text, "CORE", type); - } - public static void Log(string text, - string module = "CORE", - LogLevel type = LogLevel.INFO, - [CallerFilePath] string filePath = "file?", - [CallerMemberName] string callerName = "method?", - [CallerLineNumber] int lineNumber = 0) - { - if (Vars.CurrentConf?.LowPerformanceMode == true) return; - - var file = $"/{(Path.GetFileName((Environment.OSVersion.Platform == PlatformID.Unix) ? filePath.Replace(@"\", "/") : filePath))}/{callerName}()@L{lineNumber}"; - var Output = Vars.CurrentConf?.DisableTimeDisplay != true - ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" - : ""; - Output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; - Output += LogTable[type].Prefix; - Output += text; - Console.BackgroundColor = ConsoleColor.Black; - Console.ForegroundColor = LogTable[type].Color; - LogTable[type].Func(Output); - Console.ForegroundColor = ConsoleColor.White; - } - } -} diff --git a/pmcenter/Methods/Methods.LogLevel.cs b/pmcenter/Methods/Methods.LogLevel.cs deleted file mode 100644 index 2678c1a..0000000 --- a/pmcenter/Methods/Methods.LogLevel.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace pmcenter -{ - public partial class Methods - { - public enum LogLevel - { - INFO = 0, - WARN = 1, - ERROR = 2, - } - } -} diff --git a/pmcenter/Methods/Methods.LogMode.cs b/pmcenter/Methods/Methods.LogMode.cs deleted file mode 100644 index dc1f340..0000000 --- a/pmcenter/Methods/Methods.LogMode.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace pmcenter -{ - public partial class Methods - { - public class LogMode - { - public ConsoleColor Color; - public string Prefix; - public Action Func; - } - } -} diff --git a/pmcenter/Methods/Methods.SerializeCurrentConf.cs b/pmcenter/Methods/Methods.SerializeCurrentConf.cs index d86c585..1c836e4 100644 --- a/pmcenter/Methods/Methods.SerializeCurrentConf.cs +++ b/pmcenter/Methods/Methods.SerializeCurrentConf.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static string SerializeCurrentConf() { diff --git a/pmcenter/Methods/Methods.StrChunk.cs b/pmcenter/Methods/Methods.StrChunk.cs index a06a18b..f1d804f 100644 --- a/pmcenter/Methods/Methods.StrChunk.cs +++ b/pmcenter/Methods/Methods.StrChunk.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static List StrChunk(string str, int chunkSize) { diff --git a/pmcenter/Methods/Methods.ThreadStatus.cs b/pmcenter/Methods/Methods.ThreadStatus.cs index d9a2488..f1a851e 100644 --- a/pmcenter/Methods/Methods.ThreadStatus.cs +++ b/pmcenter/Methods/Methods.ThreadStatus.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public enum ThreadStatus { diff --git a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs index b44ee73..f1991fd 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs @@ -1,10 +1,11 @@ using System; using System.Net; using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static async Task TestConnectivity(string target, bool ignore45 = false) { diff --git a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs index 626eb96..f40f261 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs @@ -2,10 +2,11 @@ using System.Diagnostics; using System.Net; using System.Threading.Tasks; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static async Task TestLatency(string target) { diff --git a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs index 23d23d5..cdd7dd2 100644 --- a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs +++ b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void ThrDoResetConfCount() { diff --git a/pmcenter/Methods/Threads/Methods.ThrPerform.cs b/pmcenter/Methods/Threads/Methods.ThrPerform.cs index 86582be..15e8368 100644 --- a/pmcenter/Methods/Threads/Methods.ThrPerform.cs +++ b/pmcenter/Methods/Threads/Methods.ThrPerform.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static void ThrPerform() { diff --git a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs index 7475035..ddd4970 100644 --- a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs +++ b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs @@ -1,9 +1,10 @@ using System.Threading; using static pmcenter.Conf; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static async void ThrRateLimiter() { diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 6097c68..0830e2e 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -1,9 +1,10 @@ using System; using System.Threading; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static async void ThrSyncConf() { diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index 82a1782..477681f 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -1,11 +1,12 @@ using System; using System.Threading; using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; using static pmcenter.Methods.UpdateHelper; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { public static async void ThrUpdateChecker() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index 8df2a7c..31f07c4 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -5,9 +5,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { public static async Task CheckForUpdatesAsync() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs index ecc07a1..7d62131 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs @@ -1,14 +1,14 @@ using System; using System.IO; -using System.IO.Compression; using System.Threading.Tasks; using static pmcenter.Methods.H2Helper; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { public static async Task DownloadLangAsync() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs index eb8b1a4..944a074 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -3,12 +3,13 @@ using System.IO.Compression; using System.Threading.Tasks; using static pmcenter.Methods.H2Helper; +using static pmcenter.Methods.Logging; namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { /// /// Download update to filesystem and extract. @@ -20,7 +21,9 @@ public static partial class UpdateHelper public static async Task DownloadUpdatesAsync(Update2 latestUpdate, int localizationIndex = 0) { Log("Starting update download... (pmcenter_update.zip)"); +#pragma warning disable CA1062 // Validate arguments of public methods Log($"From address: {latestUpdate.UpdateCollection[localizationIndex].UpdateArchiveAddress}"); +#pragma warning restore CA1062 await DownloadFileAsync( new Uri(latestUpdate.UpdateCollection[localizationIndex].UpdateArchiveAddress), Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs index f513709..eac2c30 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index c06e6a5..30ff3c0 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs index d4c4144..41806d4 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public static partial class UpdateHelper + public sealed partial class UpdateHelper { public class Update { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs index 9106d3c..82df26b 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class UpdateHelper + public sealed partial class UpdateHelper { public class Update2 { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs index c98dcaf..3ba944d 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs @@ -1,8 +1,8 @@ namespace pmcenter { - public partial class Methods + public sealed partial class Methods { - public partial class UpdateHelper + public sealed partial class UpdateHelper { public enum UpdateLevel { diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index 78f98dd..5085e6e 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -16,6 +16,7 @@ using static pmcenter.EventHandlers; using static pmcenter.Lang; using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter { @@ -26,7 +27,7 @@ public static void Main(string[] args) Vars.StartSW.Start(); Console.WriteLine(Vars.ASCII); Log("Main delegator activated!", "DELEGATOR"); - Log($"Starting pmcenter, version {Vars.AppVer.ToString()}. Channel: \"{Vars.CompileChannel}\"", "DELEGATOR"); + Log($"Starting pmcenter, version {Vars.AppVer}. Channel: \"{Vars.CompileChannel}\"", "DELEGATOR"); var MainAsyncTask = MainAsync(args); MainAsyncTask.Wait(); Log("Main worker accidentally exited. Stopping...", "DELEGATOR", LogLevel.ERROR); @@ -76,7 +77,7 @@ public static async Task MainAsync(string[] args) } catch (Exception ex) { - Log($"Failed to read environment variables: {ex.ToString()}", "CORE", LogLevel.WARN); + Log($"Failed to read environment variables: {ex}", "CORE", LogLevel.WARN); } Log($"==> Using configurations file: {Vars.ConfFile}"); @@ -184,7 +185,7 @@ public static async Task MainAsync(string[] args) } catch (Exception ex) { - Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex.ToString()}", "BOT", LogLevel.WARN); + Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex}", "BOT", LogLevel.WARN); } try { @@ -235,7 +236,7 @@ public static async Task MainAsync(string[] args) catch (Exception ex) { CheckOpenSSLComp(ex); - Log($"Unexpected error during startup: {ex.ToString()}", "CORE", LogLevel.ERROR); + Log($"Unexpected error during startup: {ex}", "CORE", LogLevel.ERROR); Environment.Exit(1); } } diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index 9a27f06..b78414f 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -14,9 +14,9 @@ namespace pmcenter { - public class Setup + public sealed class Setup { - private static Conf.ConfObj NewConf = new Conf.ConfObj(); + private static readonly Conf.ConfObj NewConf = new Conf.ConfObj(); private static TelegramBotClient TestBot; private static bool IsUIDReceived = false; private static long ReceivedUID = -1; @@ -46,7 +46,7 @@ public static async Task SetupWizard() { Say(":) Welcome!"); Say(" This is the pmcenter setup wizard."); - Say($" App version: {Vars.AppVer.ToString()}"); + Say($" App version: {Vars.AppVer}"); Say(" Here to guide you through some *important* configurations of pmcenter."); SIn("=> Continue? [y/N]: "); if (Console.ReadLine().ToLower() != "y") From 67ab2586bb3eeffb9adc7d195c5e5a845fc90cad Mon Sep 17 00:00:00 2001 From: Elepover Date: Tue, 14 Apr 2020 23:16:40 +0800 Subject: [PATCH 14/39] add actions support! --- pmcenter/BotCommands/Chat.cs | 1 - .../BotCommands/DetectPermissionCommand.cs | 3 +- pmcenter/BotCommands/DonateCommand.cs | 4 +- pmcenter/BotCommands/PerformCommand.cs | 3 +- pmcenter/BotCommands/ResetConfCommand.cs | 3 +- pmcenter/BotCommands/RestartCommand.cs | 3 +- pmcenter/BotCommands/RetractCommand.cs | 6 +- pmcenter/BotCommands/StopChat.cs | 1 - pmcenter/BotCommands/SwitchLangCommand.cs | 1 - pmcenter/BotProcess.cs | 371 ------------------ .../BotProcess.CallbackQueryRoute.cs | 32 ++ .../BotProcess.GetKeyboardMarkup.cs | 30 ++ .../BotProcess/BotProcess.MessageRoute.cs | 34 ++ .../BotProcess/BotProcess.OwnerCommand.cs | 57 +++ pmcenter/BotProcess/BotProcess.OwnerLogic.cs | 20 + .../BotProcess/BotProcess.OwnerReplying.cs | 64 +++ pmcenter/BotProcess/BotProcess.RunCc.cs | 60 +++ pmcenter/BotProcess/BotProcess.UserLogic.cs | 131 +++++++ pmcenter/BotProcess/BotProcess.cs | 97 +++++ pmcenter/{ => BotProcess}/CommandRouter.cs | 0 pmcenter/CallbackActions/BanAction.cs | 23 ++ .../CallbackActions/CallbackActionResult.cs | 13 + pmcenter/CallbackActions/CallbackManager.cs | 37 ++ pmcenter/CallbackActions/CallbackProcess.cs | 43 ++ .../CallbackActions/ContinuedChatAction.cs | 23 ++ .../DisableContinuedChatAction.cs | 22 ++ pmcenter/CallbackActions/PardonAction.cs | 23 ++ pmcenter/CommandLineRouter.cs | 2 +- pmcenter/Configurations/Conf.BanObj.cs | 2 +- pmcenter/Configurations/Conf.ConfObj.New.cs | 3 +- pmcenter/Configurations/Conf.ConfObj.cs | 3 +- pmcenter/Configurations/Conf.GetConf.cs | 2 +- pmcenter/Configurations/Conf.InitConf.cs | 2 +- .../Configurations/Conf.KillIllegalChars.cs | 2 +- pmcenter/Configurations/Conf.LocaleList.cs | 2 +- pmcenter/Configurations/Conf.LocaleMirror.cs | 2 +- pmcenter/Configurations/Conf.MessageIDLink.cs | 4 +- pmcenter/Configurations/Conf.RateData.cs | 2 +- pmcenter/Configurations/Conf.ReadConf.cs | 2 +- pmcenter/Configurations/Conf.SaveConf.cs | 2 +- pmcenter/Configurations/Conf.Socks5Proxy.cs | 2 +- pmcenter/Configurations/Conf.Stats.cs | 2 +- .../Configurations/Conf.SwitchBlocking.cs | 2 +- .../Conf.SwitchNotifications.cs | 2 +- pmcenter/Configurations/Conf.SwitchPaused.cs | 2 +- pmcenter/Configurations/Lang.InitLang.cs | 3 +- pmcenter/Configurations/Lang.Language.New.cs | 12 +- pmcenter/Configurations/Lang.Language.cs | 12 +- pmcenter/Configurations/Lang.ReadLang.cs | 2 +- pmcenter/Configurations/Lang.SaveLang.cs | 2 +- pmcenter/EventHandlers/CtrlCHandler.cs | 2 +- pmcenter/EventHandlers/GlobalErrorHandler.cs | 2 +- pmcenter/Interfaces/ICallbackAction.cs | 12 + pmcenter/Interfaces/ICmdLine.cs | 2 - .../Checking/Methods.GetBanObjByID.cs | 2 +- .../Checking/Methods.GetLinkByOwnerMsgID.cs | 2 +- .../Checking/Methods.GetLinkByUserMsgID.cs | 2 +- .../Checking/Methods.GetRateDataIndexByID.cs | 2 +- .../Database/Checking/Methods.IsBanned.cs | 2 +- .../Checking/Methods.IsKeywordBanned.cs | 2 +- .../Methods.IsOwnerRetractionAvailable.cs | 2 +- .../Checking/Methods.IsRateDataTracking.cs | 2 +- .../Methods.IsUserRetractionAvailable.cs | 2 +- .../Database/Writing/Methods.AddRateLimit.cs | 2 +- .../Database/Writing/Methods.BanUser.cs | 2 +- .../Database/Writing/Methods.UnbanUser.cs | 2 +- .../Methods.H2Helper.DownloadFileAsync.cs | 4 +- .../Methods.H2Helper.GetBytesAsync.cs | 4 +- .../Methods.H2Helper.GetHttpContentAsync.cs | 4 +- .../Methods.H2Helper.GetStringAsync.cs | 4 +- pmcenter/Methods/Logging/Methods.Log.cs | 4 +- pmcenter/Methods/Logging/Methods.LogLevel.cs | 4 +- pmcenter/Methods/Logging/Methods.LogMode.cs | 4 +- pmcenter/Methods/Logging/Methods.LogTable.cs | 4 +- pmcenter/Methods/Methods.BoolStr.cs | 2 +- .../Methods/Methods.CheckNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.CheckOpenSSLComp.cs | 2 +- pmcenter/Methods/Methods.ExitApp.cs | 2 +- pmcenter/Methods/Methods.FlipBool.cs | 2 +- .../Methods/Methods.GetComposedUsername.cs | 23 ++ pmcenter/Methods/Methods.GetDateTimeString.cs | 2 +- pmcenter/Methods/Methods.GetNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.GetRandomString.cs | 2 +- pmcenter/Methods/Methods.GetThreadStatus.cs | 2 +- .../Methods/Methods.GetThreadStatusString.cs | 2 +- pmcenter/Methods/Methods.GetUpdateLevel.cs | 2 +- pmcenter/Methods/Methods.IsRegexMatch.cs | 2 +- .../Methods/Methods.SerializeCurrentConf.cs | 2 +- pmcenter/Methods/Methods.StrChunk.cs | 2 +- pmcenter/Methods/Methods.ThreadStatus.cs | 2 +- .../NetworkTest/Methods.TestConnectivity.cs | 2 +- .../NetworkTest/Methods.TestLatency.cs | 2 +- .../Threads/Methods.ThrDoResetConfCount.cs | 2 +- .../Methods/Threads/Methods.ThrPerform.cs | 2 +- .../Methods/Threads/Methods.ThrRateLimiter.cs | 2 +- .../Methods/Threads/Methods.ThrSyncConf.cs | 2 +- .../Threads/Methods.ThrUpdateChecker.cs | 2 +- ...thods.UpdateHelper.CheckForUpdatesAsync.cs | 4 +- .../Methods.UpdateHelper.DownloadLangAsync.cs | 4 +- ...ethods.UpdateHelper.DownloadUpdateAsync.cs | 4 +- ...UpdateHelper.GetUpdateInfoIndexByLocale.cs | 4 +- ...ds.UpdateHelper.IsNewerVersionAvailable.cs | 4 +- .../Methods.UpdateHelper.Update.cs | 4 +- .../Methods.UpdateHelper.Update2.cs | 4 +- .../Methods.UpdateHelper.UpdateLevel.cs | 4 +- pmcenter/Program.cs | 12 +- pmcenter/Setup.cs | 2 +- pmcenter/Template.cs | 2 - 108 files changed, 879 insertions(+), 486 deletions(-) delete mode 100644 pmcenter/BotProcess.cs create mode 100644 pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs create mode 100644 pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs create mode 100644 pmcenter/BotProcess/BotProcess.MessageRoute.cs create mode 100644 pmcenter/BotProcess/BotProcess.OwnerCommand.cs create mode 100644 pmcenter/BotProcess/BotProcess.OwnerLogic.cs create mode 100644 pmcenter/BotProcess/BotProcess.OwnerReplying.cs create mode 100644 pmcenter/BotProcess/BotProcess.RunCc.cs create mode 100644 pmcenter/BotProcess/BotProcess.UserLogic.cs create mode 100644 pmcenter/BotProcess/BotProcess.cs rename pmcenter/{ => BotProcess}/CommandRouter.cs (100%) create mode 100644 pmcenter/CallbackActions/BanAction.cs create mode 100644 pmcenter/CallbackActions/CallbackActionResult.cs create mode 100644 pmcenter/CallbackActions/CallbackManager.cs create mode 100644 pmcenter/CallbackActions/CallbackProcess.cs create mode 100644 pmcenter/CallbackActions/ContinuedChatAction.cs create mode 100644 pmcenter/CallbackActions/DisableContinuedChatAction.cs create mode 100644 pmcenter/CallbackActions/PardonAction.cs create mode 100644 pmcenter/Interfaces/ICallbackAction.cs create mode 100644 pmcenter/Methods/Methods.GetComposedUsername.cs diff --git a/pmcenter/BotCommands/Chat.cs b/pmcenter/BotCommands/Chat.cs index d2de934..ba6f601 100644 --- a/pmcenter/BotCommands/Chat.cs +++ b/pmcenter/BotCommands/Chat.cs @@ -3,7 +3,6 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; using static pmcenter.Methods.Logging; namespace pmcenter.Commands diff --git a/pmcenter/BotCommands/DetectPermissionCommand.cs b/pmcenter/BotCommands/DetectPermissionCommand.cs index ebbed12..9f69e29 100644 --- a/pmcenter/BotCommands/DetectPermissionCommand.cs +++ b/pmcenter/BotCommands/DetectPermissionCommand.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/pmcenter/BotCommands/DonateCommand.cs b/pmcenter/BotCommands/DonateCommand.cs index 54f8de7..84a8445 100644 --- a/pmcenter/BotCommands/DonateCommand.cs +++ b/pmcenter/BotCommands/DonateCommand.cs @@ -1,9 +1,7 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; namespace pmcenter.Commands { diff --git a/pmcenter/BotCommands/PerformCommand.cs b/pmcenter/BotCommands/PerformCommand.cs index da867e9..b536503 100644 --- a/pmcenter/BotCommands/PerformCommand.cs +++ b/pmcenter/BotCommands/PerformCommand.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index 56d57fc..9506b86 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/pmcenter/BotCommands/RestartCommand.cs b/pmcenter/BotCommands/RestartCommand.cs index 9ee97a5..029b59c 100644 --- a/pmcenter/BotCommands/RestartCommand.cs +++ b/pmcenter/BotCommands/RestartCommand.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/pmcenter/BotCommands/RetractCommand.cs b/pmcenter/BotCommands/RetractCommand.cs index b746b44..eaafd1f 100644 --- a/pmcenter/BotCommands/RetractCommand.cs +++ b/pmcenter/BotCommands/RetractCommand.cs @@ -22,7 +22,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { // owner retracting if (Methods.IsOwnerRetractionAvailable(SelectedMsgID)) { - Conf.MessageIDLink Link = Methods.GetLinkByOwnerMsgID(SelectedMsgID); + var Link = Methods.GetLinkByOwnerMsgID(SelectedMsgID); await botClient.DeleteMessageAsync(Link.TGUser.Id, Link.UserSessionMessageID).ConfigureAwait(false); } else @@ -40,8 +40,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { if (Methods.IsUserRetractionAvailable(SelectedMsgID)) { - Conf.MessageIDLink Link = Methods.GetLinkByUserMsgID(SelectedMsgID); + var Link = Methods.GetLinkByUserMsgID(SelectedMsgID); await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, Link.OwnerSessionMessageID).ConfigureAwait(false); + if (Vars.CurrentConf.EnableActions && Link.OwnerSessionActionMessageID != -1) + await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, Link.OwnerSessionActionMessageID).ConfigureAwait(false); } else { diff --git a/pmcenter/BotCommands/StopChat.cs b/pmcenter/BotCommands/StopChat.cs index 3103d05..b539abf 100644 --- a/pmcenter/BotCommands/StopChat.cs +++ b/pmcenter/BotCommands/StopChat.cs @@ -2,7 +2,6 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; using static pmcenter.Methods.Logging; namespace pmcenter.Commands diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index 43491d6..68b5fec 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Net; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/pmcenter/BotProcess.cs b/pmcenter/BotProcess.cs deleted file mode 100644 index e398fe6..0000000 --- a/pmcenter/BotProcess.cs +++ /dev/null @@ -1,371 +0,0 @@ -/* -// BotProcess.cs / pmcenter project / https://github.com/Elepover/pmcenter -// Main processing logic of pmcenter. -// Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). -*/ - -using pmcenter.Commands; -using System; -using System.Threading.Tasks; -using Telegram.Bot.Args; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using static pmcenter.Methods; -using static pmcenter.Methods.Logging; - -namespace pmcenter -{ - public static class BotProcess - { - private static readonly CommandRouter commandManager = new CommandRouter(); - - static BotProcess() - { - commandManager.RegisterCommand(new StartCommand()); - commandManager.RegisterCommand(new HelpCommand()); - - commandManager.RegisterCommand(new InfoCommand()); - commandManager.RegisterCommand(new BanCommand()); - commandManager.RegisterCommand(new PardonCommand()); - - commandManager.RegisterCommand(new BackupConfCommand()); - commandManager.RegisterCommand(new BanIdCommand()); - commandManager.RegisterCommand(new CatConfigCommand()); - commandManager.RegisterCommand(new ChatCommand()); - commandManager.RegisterCommand(new CheckUpdateCommand()); - commandManager.RegisterCommand(new ClearMessageLinksCommand()); - commandManager.RegisterCommand(new DetectPermissionCommand()); - commandManager.RegisterCommand(new DonateCommand()); - commandManager.RegisterCommand(new EditConfCommand()); - commandManager.RegisterCommand(new GetStatsCommand()); - commandManager.RegisterCommand(new PardonIdCommand()); - commandManager.RegisterCommand(new PerformCommand()); - commandManager.RegisterCommand(new PingCommand()); - commandManager.RegisterCommand(new ReadConfigCommand()); - commandManager.RegisterCommand(new ResetConfCommand()); - commandManager.RegisterCommand(new RestartCommand()); - commandManager.RegisterCommand(new RetractCommand()); - commandManager.RegisterCommand(new SaveConfigCommand()); - commandManager.RegisterCommand(new StatusCommand()); - commandManager.RegisterCommand(new StopChatCommand()); - commandManager.RegisterCommand(new SwitchBwCommand()); - commandManager.RegisterCommand(new SwitchFwCommand()); - commandManager.RegisterCommand(new SwitchLangCodeCommand()); - commandManager.RegisterCommand(new SwitchLangCommand()); - commandManager.RegisterCommand(new SwitchNotificationCommand()); - commandManager.RegisterCommand(new TestNetworkCommand()); - commandManager.RegisterCommand(new UpdateCommand()); - commandManager.RegisterCommand(new UptimeCommand()); - } - - public static async void OnUpdate(object sender, UpdateEventArgs e) - { - try - { - if (e == null) return; - if (Vars.CurrentConf.DetailedMsgLogging) - { - Log($"OnUpdate() triggered: UpdType: {e.Update.Type} UpdID: {e.Update.Id} ChatId: {e.Update.Message.Chat.Id} Username: {e.Update.Message.Chat.Username} FromID: {e.Update.Message.From.Id} FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.INFO); - } - var update = e.Update; - if (update.Type != UpdateType.Message) return; - if (update.Message.From.IsBot) return; - if (update.Message.Chat.Type != ChatType.Private) return; - - if (IsBanned(update.Message.From.Id)) - { - Log($"Restricting banned user from sending messages: {update.Message.From.FirstName} (@{update.Message.From.Username} / {(long)update.Message.From.Id})", "BOT"); - return; - } - - Vars.CurrentConf.Statistics.TotalMessagesReceived += 1; - if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) - { - await OwnerLogic(update).ConfigureAwait(false); - } - else - { - await UserLogic(update).ConfigureAwait(false); - } - } - catch (Exception ex) - { - Log($"General error while processing incoming update: {ex}", "BOT", LogLevel.ERROR); - if (Vars.CurrentConf.CatchAllExceptions) - { - try - { - _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), - ParseMode.Default, - false, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - } - catch (Exception iEx) - { - Log($"Failed to catch exception to owner: {iEx}", "BOT", LogLevel.ERROR); - } - } - } - } - - private static async Task UserLogic(Update update) - { - // is user - - if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) - { - return; - } - - Log($"Received message from \"{update.Message.From.FirstName}\" (@{update.Message.From.Username} / {update.Message.From.Id}), forwarding...", "BOT"); - - if (Vars.CurrentConf.ForwardingPaused) - { - Log("Stopped: forwarding is currently paused.", "BOT", LogLevel.INFO); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, - Vars.CurrentLang.Message_UserServicePaused, - ParseMode.Markdown, - false, - false, - update.Message.MessageId).ConfigureAwait(false); - return; - } - - // test text blacklist - if (!string.IsNullOrEmpty(update.Message.Text) && IsKeywordBanned(update.Message.Text)) - { - Log("Stopped: sentence contains blocked words.", "BOT", LogLevel.INFO); - if (Vars.CurrentConf.KeywordAutoBan) - { - BanUser(update.Message.From.Id); - } - return; - } - - // process owner - Log("Forwarding message to owner...", "BOT"); - var ForwardedMessage = await Vars.Bot.ForwardMessageAsync(Vars.CurrentConf.OwnerUID, - update.Message.From.Id, - update.Message.MessageId, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - Vars.CurrentConf.Statistics.TotalForwardedToOwner += 1; - if (Vars.CurrentConf.EnableMsgLink) - { - Log($"Recording message link: owner {ForwardedMessage.MessageId} <-> user {update.Message.MessageId} user: {update.Message.From.Id}", "BOT"); - Vars.CurrentConf.MessageLinks.Add( - new Conf.MessageIDLink() - { OwnerSessionMessageID = ForwardedMessage.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = false } - ); - // Conf.SaveConf(false, true); - } - // check for real message sender - // check if forwarded from channels - if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) - { - // is forwarded from channel - _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_ForwarderNotReal - .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - ForwardedMessage.MessageId).ConfigureAwait(false); - } - if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) - { - // is forwarded from chats - if (update.Message.ForwardFrom.Id != update.Message.From.Id) - { - _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_ForwarderNotReal - .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - ForwardedMessage.MessageId).ConfigureAwait(false); - } - } - - // process cc - if (Vars.CurrentConf.EnableCc) - { - await RunCC(update).ConfigureAwait(false); - } - if (Vars.CurrentConf.EnableForwardedConfirmation) - { - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, - Vars.CurrentLang.Message_ForwardedToOwner, - ParseMode.Markdown, - false, - false, - update.Message.MessageId).ConfigureAwait(false); - } - AddRateLimit(update.Message.From.Id); - } - - private static async Task RunCC(Update update) - { - Log("Cc enabled, forwarding...", "BOT"); - foreach (long Id in Vars.CurrentConf.Cc) - { - Log($"Forwarding message to cc: {Id}", "BOT"); - try - { - var ForwardedMessageCc = await Vars.Bot.ForwardMessageAsync(Id, - update.Message.From.Id, - update.Message.MessageId, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - // check if forwarded from channels - if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) - { - // is forwarded from channel - _ = await Vars.Bot.SendTextMessageAsync(Id, - Vars.CurrentLang.Message_ForwarderNotReal - .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - ForwardedMessageCc.MessageId).ConfigureAwait(false); - } - if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) - { - // is forwarded from chats - // check real message sender - if (update.Message.ForwardFrom.Id != update.Message.From.Id) - { - _ = await Vars.Bot.SendTextMessageAsync(Id, - Vars.CurrentLang.Message_ForwarderNotReal - .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - ForwardedMessageCc.MessageId).ConfigureAwait(false); - } - } - } - catch (Exception ex) - { - Log($"Unable to forward message to cc: {Id}, reason: {ex.Message}", "BOT", LogLevel.ERROR); - } - } - } - - private static async Task OwnerLogic(Update update) - { - if (update.Message.ReplyToMessage != null) - { - await OwnerReplying(update).ConfigureAwait(false); - } - else - { - await OwnerCommand(update).ConfigureAwait(false); - } - } - - private static async Task OwnerCommand(Update update) - { - // The owner is not even replying. - // start or help command? - if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) - { - Vars.CurrentConf.Statistics.TotalCommandsReceived += 1; - return; - } - // command mismatch - if (Vars.CurrentConf.ContChatTarget != -1) - { - // Is replying, replying to forwarded message AND not command. - var Forwarded = await Vars.Bot.ForwardMessageAsync( - Vars.CurrentConf.ContChatTarget, - update.Message.Chat.Id, - update.Message.MessageId, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - if (Vars.CurrentConf.EnableMsgLink) - { - Log($"Recording message link: {Forwarded.MessageId} -> {update.Message.MessageId} in {update.Message.From.Id}", "BOT"); - Vars.CurrentConf.MessageLinks.Add( - new Conf.MessageIDLink() - { OwnerSessionMessageID = Forwarded.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = true } - ); - // Conf.SaveConf(false, true); - } - // Process locale. - if (Vars.CurrentConf.EnableRepliedConfirmation) - { - var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; - ReplyToMessage = ReplyToMessage.Replace("$1", $"[{Vars.CurrentConf.ContChatTarget}](tg://user?id={Vars.CurrentConf.ContChatTarget})"); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); - } - Log($"Successfully passed owner's reply to UID: {Vars.CurrentConf.ContChatTarget}", "BOT"); - return; - } - - _ = await Vars.Bot.SendTextMessageAsync( - update.Message.From.Id, - Vars.CurrentLang.Message_CommandNotReplying, - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - update.Message.MessageId).ConfigureAwait(false); - } - - private static async Task OwnerReplying(Update update) - { - // check anonymous forward (5.5.0 new feature compatibility fix) - var Link = GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); - if (Link != null && !Link.IsFromOwner) - { - Log($"Selected message is forwarded anonymously from {Link.TGUser.Id}, fixing user information from database.", "BOT"); - update.Message.ReplyToMessage.ForwardFrom = Link.TGUser; - } - if (update.Message.ReplyToMessage.ForwardFrom == null && update.Message.Text.ToLower() != "/retract") - { - // The owner is replying to bot messages. (no forwardfrom) - _ = await Vars.Bot.SendTextMessageAsync( - update.Message.From.Id, - Vars.CurrentLang.Message_CommandNotReplyingValidMessage, - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - update.Message.MessageId).ConfigureAwait(false); - return; - } - - if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) - { - Vars.CurrentConf.Statistics.TotalCommandsReceived += 1; - return; - } - - // Is replying, replying to forwarded message AND not command. - var Forwarded = await Vars.Bot.ForwardMessageAsync( - update.Message.ReplyToMessage.ForwardFrom.Id, - update.Message.Chat.Id, - update.Message.MessageId, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - if (Vars.CurrentConf.EnableMsgLink) - { - Log($"Recording message link: user {Forwarded.MessageId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT"); - Vars.CurrentConf.MessageLinks.Add( - new Conf.MessageIDLink() - { OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = Forwarded.MessageId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true } - ); - // Conf.SaveConf(false, true); - } - Vars.CurrentConf.Statistics.TotalForwardedFromOwner += 1; - // Process locale. - if (Vars.CurrentConf.EnableRepliedConfirmation) - { - var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; - ReplyToMessage = ReplyToMessage.Replace("$1", $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); - } - Log($"Successfully passed owner's reply to {update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username} / {update.Message.ReplyToMessage.ForwardFrom.Id})", "BOT"); - } - } -} diff --git a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs new file mode 100644 index 0000000..a4df071 --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs @@ -0,0 +1,32 @@ +using pmcenter.CallbackActions; +using System; +using System.Threading.Tasks; +using Telegram.Bot.Args; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task CallbackQueryRoute(object sender, UpdateEventArgs e) + { + var update = e.Update; + if (update.CallbackQuery == null) return; + if (update.CallbackQuery.From.IsBot) return; + try + { + var result = await CallbackProcess.DoCallback(update.CallbackQuery.Data, GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId).TGUser, update.CallbackQuery.Message); + // prompt + await Vars.Bot.AnswerCallbackQueryAsync(update.CallbackQuery.Id, result.Status); + // update existing buttons + if (result.Succeeded) + await Vars.Bot.EditMessageReplyMarkupAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, GetKeyboardMarkup(update)); + } + catch (Exception ex) + { + Log($"Unable to process action {update.CallbackQuery.Data}: {ex}", "BOT", LogLevel.ERROR); + } + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs b/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs new file mode 100644 index 0000000..e3bf06a --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs @@ -0,0 +1,30 @@ +using pmcenter.CallbackActions; +using System.Collections.Generic; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; +using static pmcenter.Methods; + +namespace pmcenter +{ + public static partial class BotProcess + { + public static InlineKeyboardMarkup GetKeyboardMarkup(Update update) + { + var buttons = new List(); + bool isBanned = true; + if (update.Type == UpdateType.CallbackQuery) isBanned = IsBanned(GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId).TGUser.Id); + if (update.Type == UpdateType.Message) isBanned = IsBanned(update.Message.From.Id); + if (isBanned) + buttons.Add(new InlineKeyboardButton() { CallbackData = new PardonAction().Name, Text = Vars.CurrentLang.Message_Action_Pardon }); + else + buttons.Add(new InlineKeyboardButton() { CallbackData = new BanAction().Name, Text = Vars.CurrentLang.Message_Action_Ban }); + if (Vars.CurrentConf.ContChatTarget == -1) + buttons.Add(new InlineKeyboardButton() { CallbackData = new ContinuedChatAction().Name, Text = Vars.CurrentLang.Message_Action_Chat }); + else + buttons.Add(new InlineKeyboardButton() { CallbackData = new DisableContinuedChatAction().Name, Text = Vars.CurrentLang.Message_Action_StopChat }); + + return new InlineKeyboardMarkup(buttons); + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.MessageRoute.cs b/pmcenter/BotProcess/BotProcess.MessageRoute.cs new file mode 100644 index 0000000..ace5a3c --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.MessageRoute.cs @@ -0,0 +1,34 @@ +using System.Threading.Tasks; +using Telegram.Bot.Args; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task MessageRoute(object sender, UpdateEventArgs e) + { + var update = e.Update; + if (update.Message == null) return; + if (update.Message.From.IsBot) return; + if (update.Message.Chat.Type != ChatType.Private) return; + + if (Methods.IsBanned(update.Message.From.Id)) + { + Log($"Restricting banned user from sending messages: {update.Message.From.FirstName} (@{update.Message.From.Username} / {(long)update.Message.From.Id})", "BOT"); + return; + } + + Vars.CurrentConf.Statistics.TotalMessagesReceived += 1; + if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) + { + await OwnerLogic(update).ConfigureAwait(false); + } + else + { + await UserLogic(update).ConfigureAwait(false); + } + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs new file mode 100644 index 0000000..d167078 --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs @@ -0,0 +1,57 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task OwnerCommand(Update update) + { + // The owner is not even replying. + // start or help command? + if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) + { + Vars.CurrentConf.Statistics.TotalCommandsReceived += 1; + return; + } + // command mismatch + if (Vars.CurrentConf.ContChatTarget != -1) + { + // Is replying, replying to forwarded message AND not command. + var Forwarded = await Vars.Bot.ForwardMessageAsync( + Vars.CurrentConf.ContChatTarget, + update.Message.Chat.Id, + update.Message.MessageId, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + if (Vars.CurrentConf.EnableMsgLink) + { + Log($"Recording message link: {Forwarded.MessageId} -> {update.Message.MessageId} in {update.Message.From.Id}", "BOT"); + Vars.CurrentConf.MessageLinks.Add( + new Conf.MessageIDLink() + { OwnerSessionMessageID = Forwarded.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = true } + ); + // Conf.SaveConf(false, true); + } + // Process locale. + if (Vars.CurrentConf.EnableRepliedConfirmation) + { + var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; + ReplyToMessage = ReplyToMessage.Replace("$1", $"[{Vars.CurrentConf.ContChatTarget}](tg://user?id={Vars.CurrentConf.ContChatTarget})"); + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); + } + Log($"Successfully passed owner's reply to UID: {Vars.CurrentConf.ContChatTarget}", "BOT"); + return; + } + + _ = await Vars.Bot.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_CommandNotReplying, + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.OwnerLogic.cs b/pmcenter/BotProcess/BotProcess.OwnerLogic.cs new file mode 100644 index 0000000..b262e4e --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.OwnerLogic.cs @@ -0,0 +1,20 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task OwnerLogic(Update update) + { + if (update.Message.ReplyToMessage != null) + { + await OwnerReplying(update).ConfigureAwait(false); + } + else + { + await OwnerCommand(update).ConfigureAwait(false); + } + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs new file mode 100644 index 0000000..030096e --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -0,0 +1,64 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task OwnerReplying(Update update) + { + // check anonymous forward (5.5.0 new feature compatibility fix) + var Link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); + if (Link != null && !Link.IsFromOwner) + { + Log($"Selected message is forwarded anonymously from {Link.TGUser.Id}, fixing user information from database.", "BOT"); + update.Message.ReplyToMessage.ForwardFrom = Link.TGUser; + } + if (update.Message.ReplyToMessage.ForwardFrom == null && update.Message.Text.ToLower() != "/retract") + { + // The owner is replying to bot messages. (no forwardfrom) + _ = await Vars.Bot.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_CommandNotReplyingValidMessage, + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + return; + } + + if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) + { + Vars.CurrentConf.Statistics.TotalCommandsReceived += 1; + return; + } + + // Is replying, replying to forwarded message AND not command. + var Forwarded = await Vars.Bot.ForwardMessageAsync( + update.Message.ReplyToMessage.ForwardFrom.Id, + update.Message.Chat.Id, + update.Message.MessageId, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + if (Vars.CurrentConf.EnableMsgLink) + { + Log($"Recording message link: user {Forwarded.MessageId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT"); + Vars.CurrentConf.MessageLinks.Add( + new Conf.MessageIDLink() + { OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = Forwarded.MessageId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true } + ); + // Conf.SaveConf(false, true); + } + Vars.CurrentConf.Statistics.TotalForwardedFromOwner += 1; + // Process locale. + if (Vars.CurrentConf.EnableRepliedConfirmation) + { + var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; + ReplyToMessage = ReplyToMessage.Replace("$1", $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); + } + Log($"Successfully passed owner's reply to {update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username} / {update.Message.ReplyToMessage.ForwardFrom.Id})", "BOT"); + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.RunCc.cs b/pmcenter/BotProcess/BotProcess.RunCc.cs new file mode 100644 index 0000000..b05ad76 --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.RunCc.cs @@ -0,0 +1,60 @@ +using System; +using System.Threading.Tasks; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task RunCc(Update update) + { + Log("Cc enabled, forwarding...", "BOT"); + foreach (long Id in Vars.CurrentConf.Cc) + { + Log($"Forwarding message to cc: {Id}", "BOT"); + try + { + var ForwardedMessageCc = await Vars.Bot.ForwardMessageAsync(Id, + update.Message.From.Id, + update.Message.MessageId, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + // check if forwarded from channels + if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) + { + // is forwarded from channel + _ = await Vars.Bot.SendTextMessageAsync(Id, + Vars.CurrentLang.Message_ForwarderNotReal + .Replace("$2", update.Message.From.Id.ToString()) + .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + ForwardedMessageCc.MessageId).ConfigureAwait(false); + } + if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) + { + // is forwarded from chats + // check real message sender + if (update.Message.ForwardFrom.Id != update.Message.From.Id) + { + _ = await Vars.Bot.SendTextMessageAsync(Id, + Vars.CurrentLang.Message_ForwarderNotReal + .Replace("$2", update.Message.From.Id.ToString()) + .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + ForwardedMessageCc.MessageId).ConfigureAwait(false); + } + } + } + catch (Exception ex) + { + Log($"Unable to forward message to cc: {Id}, reason: {ex.Message}", "BOT", LogLevel.ERROR); + } + } + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs new file mode 100644 index 0000000..019f795 --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -0,0 +1,131 @@ +using pmcenter.CallbackActions; +using System.Collections.Generic; +using System.Threading.Tasks; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static async Task UserLogic(Update update) + { + // is user + + if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) + { + return; + } + + Log($"Received message from \"{update.Message.From.FirstName}\" (@{update.Message.From.Username} / {update.Message.From.Id}), forwarding...", "BOT"); + + if (Vars.CurrentConf.ForwardingPaused) + { + Log("Stopped: forwarding is currently paused.", "BOT", LogLevel.INFO); + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_UserServicePaused, + ParseMode.Markdown, + false, + false, + update.Message.MessageId).ConfigureAwait(false); + return; + } + + // test text blacklist + if (!string.IsNullOrEmpty(update.Message.Text) && IsKeywordBanned(update.Message.Text)) + { + Log("Stopped: sentence contains blocked words.", "BOT", LogLevel.INFO); + if (Vars.CurrentConf.KeywordAutoBan) + { + BanUser(update.Message.From.Id); + } + return; + } + + // process owner + Log("Forwarding message to owner...", "BOT"); + var ForwardedMessage = await Vars.Bot.ForwardMessageAsync(Vars.CurrentConf.OwnerUID, + update.Message.From.Id, + update.Message.MessageId, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + Vars.CurrentConf.Statistics.TotalForwardedToOwner += 1; + // preprocess message link + var link = new Conf.MessageIDLink() + { + OwnerSessionMessageID = ForwardedMessage.MessageId, + UserSessionMessageID = update.Message.MessageId, + TGUser = update.Message.From, + IsFromOwner = false + }; + // process actions + if (Vars.CurrentConf.EnableActions && Vars.CurrentConf.EnableMsgLink) + { + var markup = GetKeyboardMarkup(update); + link.OwnerSessionActionMessageID = (await Vars.Bot.SendTextMessageAsync( + Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_Action_ChooseAction, + ParseMode.Markdown, + false, + true, + ForwardedMessage.MessageId, + markup + ).ConfigureAwait(false)).MessageId; + } + // process message links + if (Vars.CurrentConf.EnableMsgLink) + { + Log($"Recording message link: owner {ForwardedMessage.MessageId} <-> user {update.Message.MessageId} user: {update.Message.From.Id}", "BOT"); + Vars.CurrentConf.MessageLinks.Add(link); + // Conf.SaveConf(false, true); + } + // check for real message sender + // check if forwarded from channels + if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) + { + // is forwarded from channel + _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_ForwarderNotReal + .Replace("$2", update.Message.From.Id.ToString()) + .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + ForwardedMessage.MessageId).ConfigureAwait(false); + } + if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) + { + // is forwarded from chats + if (update.Message.ForwardFrom.Id != update.Message.From.Id) + { + _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_ForwarderNotReal + .Replace("$2", update.Message.From.Id.ToString()) + .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + ForwardedMessage.MessageId).ConfigureAwait(false); + } + } + + // process cc + if (Vars.CurrentConf.EnableCc) + { + await RunCc(update).ConfigureAwait(false); + } + if (Vars.CurrentConf.EnableForwardedConfirmation) + { + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_ForwardedToOwner, + ParseMode.Markdown, + false, + false, + update.Message.MessageId).ConfigureAwait(false); + } + AddRateLimit(update.Message.From.Id); + } + } +} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.cs b/pmcenter/BotProcess/BotProcess.cs new file mode 100644 index 0000000..337936d --- /dev/null +++ b/pmcenter/BotProcess/BotProcess.cs @@ -0,0 +1,97 @@ +/* +// BotProcess.cs / pmcenter project / https://github.com/Elepover/pmcenter +// Main processing logic of pmcenter. +// Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). +*/ + +using pmcenter.Commands; +using System; +using Telegram.Bot.Args; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter +{ + public static partial class BotProcess + { + private static readonly CommandRouter commandManager = new CommandRouter(); + + static BotProcess() + { + commandManager.RegisterCommand(new StartCommand()); + commandManager.RegisterCommand(new HelpCommand()); + + commandManager.RegisterCommand(new InfoCommand()); + commandManager.RegisterCommand(new BanCommand()); + commandManager.RegisterCommand(new PardonCommand()); + + commandManager.RegisterCommand(new BackupConfCommand()); + commandManager.RegisterCommand(new BanIdCommand()); + commandManager.RegisterCommand(new CatConfigCommand()); + commandManager.RegisterCommand(new ChatCommand()); + commandManager.RegisterCommand(new CheckUpdateCommand()); + commandManager.RegisterCommand(new ClearMessageLinksCommand()); + commandManager.RegisterCommand(new DetectPermissionCommand()); + commandManager.RegisterCommand(new DonateCommand()); + commandManager.RegisterCommand(new EditConfCommand()); + commandManager.RegisterCommand(new GetStatsCommand()); + commandManager.RegisterCommand(new PardonIdCommand()); + commandManager.RegisterCommand(new PerformCommand()); + commandManager.RegisterCommand(new PingCommand()); + commandManager.RegisterCommand(new ReadConfigCommand()); + commandManager.RegisterCommand(new ResetConfCommand()); + commandManager.RegisterCommand(new RestartCommand()); + commandManager.RegisterCommand(new RetractCommand()); + commandManager.RegisterCommand(new SaveConfigCommand()); + commandManager.RegisterCommand(new StatusCommand()); + commandManager.RegisterCommand(new StopChatCommand()); + commandManager.RegisterCommand(new SwitchBwCommand()); + commandManager.RegisterCommand(new SwitchFwCommand()); + commandManager.RegisterCommand(new SwitchLangCodeCommand()); + commandManager.RegisterCommand(new SwitchLangCommand()); + commandManager.RegisterCommand(new SwitchNotificationCommand()); + commandManager.RegisterCommand(new TestNetworkCommand()); + commandManager.RegisterCommand(new UpdateCommand()); + commandManager.RegisterCommand(new UptimeCommand()); + } + + public static async void OnUpdate(object sender, UpdateEventArgs e) + { + try + { + if (e == null) return; + if (Vars.CurrentConf.DetailedMsgLogging) + Log($"OnUpdate() triggered: UpdType: {e.Update.Type}, UpdID: {e.Update.Id}, ChatId: {e.Update.Message.Chat.Id}, Username: {e.Update.Message.Chat.Username}, FromID: {e.Update.Message.From.Id}, FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.INFO); + + switch (e.Update.Type) + { + case UpdateType.Message: await MessageRoute(sender, e); break; + case UpdateType.CallbackQuery: await CallbackQueryRoute(sender, e); break; + default: + if (Vars.CurrentConf.DetailedMsgLogging) + Log($"Ditching unknown update type ({e.Update.Type})...", "BOT-DETAILED"); + return; + } + } + catch (Exception ex) + { + Log($"General error while processing incoming update: {ex}", "BOT", LogLevel.ERROR); + if (Vars.CurrentConf.CatchAllExceptions) + { + try + { + _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), + ParseMode.Default, + false, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + } + catch (Exception iEx) + { + Log($"Failed to catch exception to owner: {iEx}", "BOT", LogLevel.ERROR); + } + } + } + } + } +} diff --git a/pmcenter/CommandRouter.cs b/pmcenter/BotProcess/CommandRouter.cs similarity index 100% rename from pmcenter/CommandRouter.cs rename to pmcenter/BotProcess/CommandRouter.cs diff --git a/pmcenter/CallbackActions/BanAction.cs b/pmcenter/CallbackActions/BanAction.cs new file mode 100644 index 0000000..628d5cd --- /dev/null +++ b/pmcenter/CallbackActions/BanAction.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; + +namespace pmcenter.CallbackActions +{ + internal class BanAction : ICallbackAction + { + public string Name => "ban"; + public ICallbackAction Replacement => new PardonAction(); + +#pragma warning disable CS1998 + public async Task Action(User user, Message msg) +#pragma warning restore CS1998 + { + // attempt to ban the user + Log($"Attempting to ban user {user.Id} via callback actions...", "BOT"); + BanUser(user.Id); + return Vars.CurrentLang.Message_Action_Banned.Replace("$1", GetComposedUsername(user, false)); + } + } +} diff --git a/pmcenter/CallbackActions/CallbackActionResult.cs b/pmcenter/CallbackActions/CallbackActionResult.cs new file mode 100644 index 0000000..eab1a45 --- /dev/null +++ b/pmcenter/CallbackActions/CallbackActionResult.cs @@ -0,0 +1,13 @@ +namespace pmcenter.CallbackActions +{ + public class CallbackActionResult + { + public CallbackActionResult(string status, bool succeeded = true) + { + Status = status; + Succeeded = succeeded; + } + public string Status; + public bool Succeeded; + } +} diff --git a/pmcenter/CallbackActions/CallbackManager.cs b/pmcenter/CallbackActions/CallbackManager.cs new file mode 100644 index 0000000..183bb75 --- /dev/null +++ b/pmcenter/CallbackActions/CallbackManager.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Telegram.Bot.Types; + +namespace pmcenter.CallbackActions +{ + internal class CallbackManager + { + private readonly List callbacks = new List(); + + public CallbackManager() + { } + + public ICallbackAction this[string prefix] => callbacks.FirstOrDefault(x => x.Name.StartsWith(prefix)); + + public void RegisterAction(ICallbackAction action) + { + if (callbacks.Any(x => x.Name == action.Name)) + throw new ArgumentException($"An action named \"{action.Name}\" is already registered.", nameof(action)); + callbacks.Add(action); + } + + public async Task Execute(string actionName, User user, Message msg) + { + foreach (var action in callbacks) + { + if (action.Name == actionName) + { + return await action.Action(user, msg); + } + } + return null; + } + } +} diff --git a/pmcenter/CallbackActions/CallbackProcess.cs b/pmcenter/CallbackActions/CallbackProcess.cs new file mode 100644 index 0000000..8bb3268 --- /dev/null +++ b/pmcenter/CallbackActions/CallbackProcess.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading.Tasks; +using Telegram.Bot.Types; +using static pmcenter.Methods.Logging; + +namespace pmcenter.CallbackActions +{ + public static class CallbackProcess + { + private static readonly CallbackManager callbackManager = new CallbackManager(); + + static CallbackProcess() + { + callbackManager.RegisterAction(new BanAction()); + callbackManager.RegisterAction(new PardonAction()); + callbackManager.RegisterAction(new ContinuedChatAction()); + callbackManager.RegisterAction(new DisableContinuedChatAction()); + } + + /// + /// Do callback with given arguments + /// + /// The name of the action + /// The user who initiated the action + /// The corresponding message + /// + public static async Task DoCallback(string actionName, User user, Message msg) + { + try + { + var result = await callbackManager.Execute(actionName, user, msg); + if (result == null) + Log($"Callback {actionName} from user {user.Id} cannot be found.", "BOT", LogLevel.WARN); + return new CallbackActionResult(result, result != null); + } + catch (Exception ex) + { + Log($"Callback {actionName} could not be executed: {ex}", "BOT", LogLevel.ERROR); + return new CallbackActionResult(Vars.CurrentLang.Message_Action_Error, false); + } + } + } +} diff --git a/pmcenter/CallbackActions/ContinuedChatAction.cs b/pmcenter/CallbackActions/ContinuedChatAction.cs new file mode 100644 index 0000000..9017618 --- /dev/null +++ b/pmcenter/CallbackActions/ContinuedChatAction.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; + +namespace pmcenter.CallbackActions +{ + internal class ContinuedChatAction : ICallbackAction + { + public string Name => "chat"; + public ICallbackAction Replacement => new DisableContinuedChatAction(); + +#pragma warning disable CS1998 + public async Task Action(User user, Message msg) +#pragma warning restore CS1998 + { + Log("Enabling continued conversation via actions...", "BOT"); + Vars.CurrentConf.ContChatTarget = user.Id; + _ = await Conf.SaveConf(false, true).ConfigureAwait(false); + return Vars.CurrentLang.Message_Action_ContChatEnabled.Replace("$1", GetComposedUsername(user, false)); + } + } +} diff --git a/pmcenter/CallbackActions/DisableContinuedChatAction.cs b/pmcenter/CallbackActions/DisableContinuedChatAction.cs new file mode 100644 index 0000000..8e2da19 --- /dev/null +++ b/pmcenter/CallbackActions/DisableContinuedChatAction.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using static pmcenter.Methods.Logging; + +namespace pmcenter.CallbackActions +{ + internal class DisableContinuedChatAction : ICallbackAction + { + public string Name => "disablechat"; + public ICallbackAction Replacement => new ContinuedChatAction(); + +#pragma warning disable CS1998 + public async Task Action(User user, Message msg) +#pragma warning restore CS1998 + { + Log("Disabling continued conversation via actions...", "BOT"); + Vars.CurrentConf.ContChatTarget = -1; + _ = await Conf.SaveConf(false, true).ConfigureAwait(false); + return Vars.CurrentLang.Message_Action_ContChatDisabled; + } + } +} diff --git a/pmcenter/CallbackActions/PardonAction.cs b/pmcenter/CallbackActions/PardonAction.cs new file mode 100644 index 0000000..8608565 --- /dev/null +++ b/pmcenter/CallbackActions/PardonAction.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; + +namespace pmcenter.CallbackActions +{ + internal class PardonAction : ICallbackAction + { + public string Name => "pardon"; + public ICallbackAction Replacement => new BanAction(); + +#pragma warning disable CS1998 + public async Task Action(User user, Message msg) +#pragma warning restore CS1998 + { + // attempt to pardon the user + Log($"Attempting to pardon {user.Id} via callback actions...", "BOT"); + UnbanUser(user.Id); + return Vars.CurrentLang.Message_Action_Pardoned.Replace("$1", GetComposedUsername(user, false)); + } + } +} diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLineRouter.cs index 298cb61..cf5a575 100644 --- a/pmcenter/CommandLineRouter.cs +++ b/pmcenter/CommandLineRouter.cs @@ -46,7 +46,7 @@ public void RegisterCommand(ICmdLine command) public async Task Execute(string cmdLine) { Log("Processing commandlines...", "CMD"); - foreach (ICmdLine cmdProcess in commands) + foreach (var cmdProcess in commands) { if (cmdLine.Contains(globalPrefix + cmdProcess.Prefix)) { diff --git a/pmcenter/Configurations/Conf.BanObj.cs b/pmcenter/Configurations/Conf.BanObj.cs index 14b4c13..e6507ae 100644 --- a/pmcenter/Configurations/Conf.BanObj.cs +++ b/pmcenter/Configurations/Conf.BanObj.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class BanObj { diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index cf97fa3..9f330b3 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public sealed partial class ConfObj { @@ -41,6 +41,7 @@ public ConfObj() UpdateChannel = "master"; IgnoreKeyboardInterrupt = false; DisableNetCore3Check = false; + EnableActions = false; Statistics = new Stats(); Socks5Proxies = new List(); BannedKeywords = new List(); diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index 103dd09..db0a1e0 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public sealed partial class ConfObj { @@ -39,6 +39,7 @@ public sealed partial class ConfObj public string UpdateChannel { get; set; } public bool IgnoreKeyboardInterrupt { get; set; } public bool DisableNetCore3Check { get; set; } + public bool EnableActions { get; set; } public Stats Statistics { get; set; } public List Socks5Proxies { get; set; } public List BannedKeywords { get; set; } diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index dab0fd8..c11ed29 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public static async Task GetConf(string Filename) { diff --git a/pmcenter/Configurations/Conf.InitConf.cs b/pmcenter/Configurations/Conf.InitConf.cs index eb91246..a92ff88 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public static async Task InitConf() { diff --git a/pmcenter/Configurations/Conf.KillIllegalChars.cs b/pmcenter/Configurations/Conf.KillIllegalChars.cs index 1b5e9ad..d85ee34 100644 --- a/pmcenter/Configurations/Conf.KillIllegalChars.cs +++ b/pmcenter/Configurations/Conf.KillIllegalChars.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public static string KillIllegalChars(string Input) { diff --git a/pmcenter/Configurations/Conf.LocaleList.cs b/pmcenter/Configurations/Conf.LocaleList.cs index 51ffeb8..4b94735 100644 --- a/pmcenter/Configurations/Conf.LocaleList.cs +++ b/pmcenter/Configurations/Conf.LocaleList.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class LocaleList { diff --git a/pmcenter/Configurations/Conf.LocaleMirror.cs b/pmcenter/Configurations/Conf.LocaleMirror.cs index 08b0f94..bda44f4 100644 --- a/pmcenter/Configurations/Conf.LocaleMirror.cs +++ b/pmcenter/Configurations/Conf.LocaleMirror.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class LocaleMirror { diff --git a/pmcenter/Configurations/Conf.MessageIDLink.cs b/pmcenter/Configurations/Conf.MessageIDLink.cs index 81d5067..47208a7 100644 --- a/pmcenter/Configurations/Conf.MessageIDLink.cs +++ b/pmcenter/Configurations/Conf.MessageIDLink.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class MessageIDLink { @@ -10,6 +10,7 @@ public MessageIDLink() { TGUser = null; OwnerSessionMessageID = -1; + OwnerSessionActionMessageID = -1; UserSessionMessageID = -1; IsFromOwner = false; } @@ -18,6 +19,7 @@ public MessageIDLink() /// Message ID of the message in owner's session /// public int OwnerSessionMessageID { get; set; } + public int OwnerSessionActionMessageID { get; set; } public int UserSessionMessageID { get; set; } public bool IsFromOwner { get; set; } } diff --git a/pmcenter/Configurations/Conf.RateData.cs b/pmcenter/Configurations/Conf.RateData.cs index 02037ba..42f77dd 100644 --- a/pmcenter/Configurations/Conf.RateData.cs +++ b/pmcenter/Configurations/Conf.RateData.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class RateData { diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index 1590f59..c84f6a9 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public static async Task ReadConf(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index 6edc926..a3223bb 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. diff --git a/pmcenter/Configurations/Conf.Socks5Proxy.cs b/pmcenter/Configurations/Conf.Socks5Proxy.cs index 17f6fa4..0bb3491 100644 --- a/pmcenter/Configurations/Conf.Socks5Proxy.cs +++ b/pmcenter/Configurations/Conf.Socks5Proxy.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class Socks5Proxy { diff --git a/pmcenter/Configurations/Conf.Stats.cs b/pmcenter/Configurations/Conf.Stats.cs index 8fa6fe9..f0134dd 100644 --- a/pmcenter/Configurations/Conf.Stats.cs +++ b/pmcenter/Configurations/Conf.Stats.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { public class Stats { diff --git a/pmcenter/Configurations/Conf.SwitchBlocking.cs b/pmcenter/Configurations/Conf.SwitchBlocking.cs index 38edeb1..423f9a3 100644 --- a/pmcenter/Configurations/Conf.SwitchBlocking.cs +++ b/pmcenter/Configurations/Conf.SwitchBlocking.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { /// /// Switch 'blocking' status, returning current status. diff --git a/pmcenter/Configurations/Conf.SwitchNotifications.cs b/pmcenter/Configurations/Conf.SwitchNotifications.cs index 59edb9b..f859f1d 100644 --- a/pmcenter/Configurations/Conf.SwitchNotifications.cs +++ b/pmcenter/Configurations/Conf.SwitchNotifications.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { /// /// Switch 'disablenotifications' status, returning current status. diff --git a/pmcenter/Configurations/Conf.SwitchPaused.cs b/pmcenter/Configurations/Conf.SwitchPaused.cs index 9871bf7..a39b4f4 100644 --- a/pmcenter/Configurations/Conf.SwitchPaused.cs +++ b/pmcenter/Configurations/Conf.SwitchPaused.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Conf + public static partial class Conf { /// /// Switch 'forwarding' status, returning current status. diff --git a/pmcenter/Configurations/Lang.InitLang.cs b/pmcenter/Configurations/Lang.InitLang.cs index beaabab..c742244 100644 --- a/pmcenter/Configurations/Lang.InitLang.cs +++ b/pmcenter/Configurations/Lang.InitLang.cs @@ -1,12 +1,11 @@ using System; using System.IO; using System.Threading.Tasks; -using static pmcenter.Methods; using static pmcenter.Methods.Logging; namespace pmcenter { - public sealed partial class Lang + public static partial class Lang { public static async Task InitLang() { diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index 80a1adc..c9cb453 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Lang + public static partial class Lang { public sealed partial class Language { @@ -78,6 +78,16 @@ public Language() Message_MsgLinksCleared = "✅ All message links have been cleared."; Message_AvailableLang = "ℹ *Available languages*\n\n`$1`"; Message_NetCore31Required = "⚠ You need `.NET Core 3.1` (runtime) installed in order to receive pmcenter v2 and further updates.\n\nLatest .NET Core runtime version detected on your device: `$1`\n\nThis warning will only show once."; + Message_Action_Banned = "✅ User $1 has been banned!"; + Message_Action_Pardoned = "✅ User $1 has been pardoned!"; + Message_Action_ContChatEnabled = "✅ You're now chatting with $1!"; + Message_Action_ContChatDisabled = "✅ Continued chat disabled!"; + Message_Action_Error = "✖ Action failed. Check logs."; + Message_Action_ChooseAction = "❓ *What do you want to do with this message?*"; + Message_Action_Ban = "✖ Ban the user"; + Message_Action_Pardon = "✅ Pardon the user"; + Message_Action_Chat = "💬 Enter continued conversation"; + Message_Action_StopChat = "💬 Stop continued conversation"; } } } diff --git a/pmcenter/Configurations/Lang.Language.cs b/pmcenter/Configurations/Lang.Language.cs index 8a72201..9103232 100644 --- a/pmcenter/Configurations/Lang.Language.cs +++ b/pmcenter/Configurations/Lang.Language.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Lang + public static partial class Lang { public sealed partial class Language { @@ -76,6 +76,16 @@ public sealed partial class Language public string Message_MsgLinksCleared { get; set; } public string Message_AvailableLang { get; set; } public string Message_NetCore31Required { get; set; } + public string Message_Action_Banned { get; set; } + public string Message_Action_Pardoned { get; set; } + public string Message_Action_ContChatEnabled { get; set; } + public string Message_Action_ContChatDisabled { get; set; } + public string Message_Action_Error { get; set; } + public string Message_Action_ChooseAction { get; set; } + public string Message_Action_Ban { get; set; } + public string Message_Action_Pardon { get; set; } + public string Message_Action_Chat { get; set; } + public string Message_Action_StopChat { get; set; } } } } diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index bc64d46..2d523cb 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Lang + public static partial class Lang { public static async Task ReadLang(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index 981b860..34db746 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -5,7 +5,7 @@ namespace pmcenter { - public sealed partial class Lang + public static partial class Lang { public static async Task SaveLang(bool isInvalid = false) { // DO NOT HANDLE ERRORS HERE. diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index a0a9595..b412afc 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class EventHandlers + public static partial class EventHandlers { public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) { diff --git a/pmcenter/EventHandlers/GlobalErrorHandler.cs b/pmcenter/EventHandlers/GlobalErrorHandler.cs index 30733a4..6bd05f4 100644 --- a/pmcenter/EventHandlers/GlobalErrorHandler.cs +++ b/pmcenter/EventHandlers/GlobalErrorHandler.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public sealed partial class EventHandlers + public static partial class EventHandlers { public static void GlobalErrorHandler(object sender, UnhandledExceptionEventArgs e) { diff --git a/pmcenter/Interfaces/ICallbackAction.cs b/pmcenter/Interfaces/ICallbackAction.cs new file mode 100644 index 0000000..f7ed7aa --- /dev/null +++ b/pmcenter/Interfaces/ICallbackAction.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; + +namespace pmcenter +{ + internal interface ICallbackAction + { + string Name { get; } + ICallbackAction Replacement { get; } + Task Action(User user, Message msg); + } +} diff --git a/pmcenter/Interfaces/ICmdLine.cs b/pmcenter/Interfaces/ICmdLine.cs index d283075..d066389 100644 --- a/pmcenter/Interfaces/ICmdLine.cs +++ b/pmcenter/Interfaces/ICmdLine.cs @@ -5,8 +5,6 @@ */ using System.Threading.Tasks; -using Telegram.Bot; -using Telegram.Bot.Types; namespace pmcenter { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs index 82157ec..faf2101 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static BanObj GetBanObjByID(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs index e31e17c..8ea5991 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static MessageIDLink GetLinkByOwnerMsgID(long OwnerSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs index 716a5e4..abedfd8 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static MessageIDLink GetLinkByUserMsgID(long UserSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs index 81bec0d..aa48f53 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static int GetRateDataIndexByID(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index 84c699c..76e4ab6 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsBanned(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs index a6e4469..0e5de79 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsKeywordBanned(string Sentence) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs index dd9e17e..2107a2a 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsOwnerRetractionAvailable(int OwnerSessionMsgID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs index e06b101..5db21d8 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsRateDataTracking(long UID) { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs index cd11708..a919c5b 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsUserRetractionAvailable(int UserSessionMsgID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs index e66c364..e691a8e 100644 --- a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs +++ b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void AddRateLimit(long UID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs index 6696917..c3322d5 100644 --- a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void BanUser(long UID) { diff --git a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs index 954ec9e..403a376 100644 --- a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void UnbanUser(long UID) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs index 0ad86e1..5b6b4bf 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -4,9 +4,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class H2Helper + public static partial class H2Helper { public static async Task DownloadFileAsync(Uri uri, string filename) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs index 3e104be..61a074d 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -3,9 +3,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class H2Helper + public static partial class H2Helper { public static async Task GetBytesAsync(Uri uri) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs index 5be4303..33979f6 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs @@ -4,9 +4,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class H2Helper + public static partial class H2Helper { private static async Task GetHttpContentAsync(Uri uri) { diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs index 3d34ece..a0f3163 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -3,9 +3,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class H2Helper + public static partial class H2Helper { public static async Task GetStringAsync(Uri uri) { diff --git a/pmcenter/Methods/Logging/Methods.Log.cs b/pmcenter/Methods/Logging/Methods.Log.cs index 51d9c79..854305e 100644 --- a/pmcenter/Methods/Logging/Methods.Log.cs +++ b/pmcenter/Methods/Logging/Methods.Log.cs @@ -5,9 +5,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class Logging + public static partial class Logging { public static void Log(string text, LogLevel type) { diff --git a/pmcenter/Methods/Logging/Methods.LogLevel.cs b/pmcenter/Methods/Logging/Methods.LogLevel.cs index 03eb750..12faff5 100644 --- a/pmcenter/Methods/Logging/Methods.LogLevel.cs +++ b/pmcenter/Methods/Logging/Methods.LogLevel.cs @@ -1,8 +1,8 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class Logging + public static partial class Logging { public enum LogLevel { diff --git a/pmcenter/Methods/Logging/Methods.LogMode.cs b/pmcenter/Methods/Logging/Methods.LogMode.cs index 251e650..ac7d2f7 100644 --- a/pmcenter/Methods/Logging/Methods.LogMode.cs +++ b/pmcenter/Methods/Logging/Methods.LogMode.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class Logging + public static partial class Logging { public class LogMode { diff --git a/pmcenter/Methods/Logging/Methods.LogTable.cs b/pmcenter/Methods/Logging/Methods.LogTable.cs index 99cdf0e..2ea020c 100644 --- a/pmcenter/Methods/Logging/Methods.LogTable.cs +++ b/pmcenter/Methods/Logging/Methods.LogTable.cs @@ -3,9 +3,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class Logging + public static partial class Logging { public static Dictionary LogTable = new Dictionary() { diff --git a/pmcenter/Methods/Methods.BoolStr.cs b/pmcenter/Methods/Methods.BoolStr.cs index 60edc70..8ac1f1f 100644 --- a/pmcenter/Methods/Methods.BoolStr.cs +++ b/pmcenter/Methods/Methods.BoolStr.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string BoolStr(bool Input) { diff --git a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index 111cdb3..ff5c599 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool CheckNetCoreVersion(Version version) { diff --git a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs index 8584e05..a5e4037 100644 --- a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs +++ b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs @@ -5,7 +5,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void CheckOpenSSLComp(Exception ex) { diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index e862bdf..3a9f166 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -5,7 +5,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void ExitApp(int code) { diff --git a/pmcenter/Methods/Methods.FlipBool.cs b/pmcenter/Methods/Methods.FlipBool.cs index 064ee51..640ffac 100644 --- a/pmcenter/Methods/Methods.FlipBool.cs +++ b/pmcenter/Methods/Methods.FlipBool.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool FlipBool(bool Input) { diff --git a/pmcenter/Methods/Methods.GetComposedUsername.cs b/pmcenter/Methods/Methods.GetComposedUsername.cs new file mode 100644 index 0000000..301cfee --- /dev/null +++ b/pmcenter/Methods/Methods.GetComposedUsername.cs @@ -0,0 +1,23 @@ +using System.Text; +using Telegram.Bot.Types; + +namespace pmcenter +{ + public static partial class Methods + { + public static string GetComposedUsername(User user, bool includeUsername = true, bool includeId = false) + { + var sb = new StringBuilder(user.FirstName); + if (!(string.IsNullOrEmpty(user.LastName) || string.IsNullOrWhiteSpace(user.LastName))) + sb.Append($" {user.LastName}"); + if (!includeUsername && !includeId) return sb.ToString(); + if (includeUsername && !includeId && string.IsNullOrEmpty(user.Username)) return sb.ToString(); + sb.Append('('); + if (includeUsername && !string.IsNullOrEmpty(user.Username)) + sb.Append($"@{user.Username}"); + if (includeId) sb.Append($", {user.Id}"); + sb.Append(')'); + return sb.ToString(); + } + } +} diff --git a/pmcenter/Methods/Methods.GetDateTimeString.cs b/pmcenter/Methods/Methods.GetDateTimeString.cs index d24433b..e3b957a 100644 --- a/pmcenter/Methods/Methods.GetDateTimeString.cs +++ b/pmcenter/Methods/Methods.GetDateTimeString.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string GetDateTimeString(bool removeInvalidChar = false) { diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index c9291ec..9f2d6cb 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static Version GetNetCoreVersion() { diff --git a/pmcenter/Methods/Methods.GetRandomString.cs b/pmcenter/Methods/Methods.GetRandomString.cs index 2f259ea..c92dcdd 100644 --- a/pmcenter/Methods/Methods.GetRandomString.cs +++ b/pmcenter/Methods/Methods.GetRandomString.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string GetRandomString(int length = 8) { diff --git a/pmcenter/Methods/Methods.GetThreadStatus.cs b/pmcenter/Methods/Methods.GetThreadStatus.cs index 0c97ef2..16bdbb1 100644 --- a/pmcenter/Methods/Methods.GetThreadStatus.cs +++ b/pmcenter/Methods/Methods.GetThreadStatus.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static ThreadStatus GetThreadStatus(Thread Thread) { diff --git a/pmcenter/Methods/Methods.GetThreadStatusString.cs b/pmcenter/Methods/Methods.GetThreadStatusString.cs index 6516484..d992c28 100644 --- a/pmcenter/Methods/Methods.GetThreadStatusString.cs +++ b/pmcenter/Methods/Methods.GetThreadStatusString.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string GetThreadStatusString(ThreadStatus Status) { diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index f6ce880..461e372 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string GetUpdateLevel(UpdateLevel Level) { diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index aa68f78..20d189d 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static bool IsRegexMatch(string source, string expression) { diff --git a/pmcenter/Methods/Methods.SerializeCurrentConf.cs b/pmcenter/Methods/Methods.SerializeCurrentConf.cs index 1c836e4..90830a9 100644 --- a/pmcenter/Methods/Methods.SerializeCurrentConf.cs +++ b/pmcenter/Methods/Methods.SerializeCurrentConf.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static string SerializeCurrentConf() { diff --git a/pmcenter/Methods/Methods.StrChunk.cs b/pmcenter/Methods/Methods.StrChunk.cs index f1d804f..a4eeedf 100644 --- a/pmcenter/Methods/Methods.StrChunk.cs +++ b/pmcenter/Methods/Methods.StrChunk.cs @@ -3,7 +3,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static List StrChunk(string str, int chunkSize) { diff --git a/pmcenter/Methods/Methods.ThreadStatus.cs b/pmcenter/Methods/Methods.ThreadStatus.cs index f1a851e..0f27882 100644 --- a/pmcenter/Methods/Methods.ThreadStatus.cs +++ b/pmcenter/Methods/Methods.ThreadStatus.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public enum ThreadStatus { diff --git a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs index f1991fd..1bf24cb 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs @@ -5,7 +5,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static async Task TestConnectivity(string target, bool ignore45 = false) { diff --git a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs index f40f261..8d309b3 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static async Task TestLatency(string target) { diff --git a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs index cdd7dd2..cafbcf5 100644 --- a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs +++ b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs @@ -2,7 +2,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void ThrDoResetConfCount() { diff --git a/pmcenter/Methods/Threads/Methods.ThrPerform.cs b/pmcenter/Methods/Threads/Methods.ThrPerform.cs index 15e8368..8d2e9aa 100644 --- a/pmcenter/Methods/Threads/Methods.ThrPerform.cs +++ b/pmcenter/Methods/Threads/Methods.ThrPerform.cs @@ -1,6 +1,6 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static void ThrPerform() { diff --git a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs index ddd4970..98e0dae 100644 --- a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs +++ b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static async void ThrRateLimiter() { diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 0830e2e..4e34fd9 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -4,7 +4,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static async void ThrSyncConf() { diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index 477681f..19f78bd 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -6,7 +6,7 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { public static async void ThrUpdateChecker() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index 31f07c4..bbf7b09 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -5,9 +5,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public static async Task CheckForUpdatesAsync() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs index 7d62131..1c7b5f8 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadLangAsync.cs @@ -6,9 +6,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public static async Task DownloadLangAsync() { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs index 944a074..f4a7989 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -7,9 +7,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { /// /// Download update to filesystem and extract. diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs index eac2c30..295b0a1 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index 30ff3c0..71175d6 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs index 41806d4..04ba884 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public class Update { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs index 82df26b..b367afb 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -2,9 +2,9 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public class Update2 { diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs index 3ba944d..8b5b11e 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs @@ -1,8 +1,8 @@ namespace pmcenter { - public sealed partial class Methods + public static partial class Methods { - public sealed partial class UpdateHelper + public static partial class UpdateHelper { public enum UpdateLevel { diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index 5085e6e..ee9bda7 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -28,6 +28,8 @@ public static void Main(string[] args) Console.WriteLine(Vars.ASCII); Log("Main delegator activated!", "DELEGATOR"); Log($"Starting pmcenter, version {Vars.AppVer}. Channel: \"{Vars.CompileChannel}\"", "DELEGATOR"); + if (Vars.GitHubReleases) + Log("This image of pmcenter is built for GitHub releases. Will use a different updating mechanism.", "DELEGATOR"); var MainAsyncTask = MainAsync(args); MainAsyncTask.Wait(); Log("Main worker accidentally exited. Stopping...", "DELEGATOR", LogLevel.ERROR); @@ -47,7 +49,9 @@ public static async Task MainAsync(string[] args) await CmdLineProcess.RunCommand(Environment.CommandLine).ConfigureAwait(false); // everything (exits and/or errors) are handled above, please do not process. // detect environment variables - // including: $pmcenter_conf, $pmcenter_lang + // including: + // $pmcenter_conf + // $pmcenter_lang try { var ConfByEnviVar = Environment.GetEnvironmentVariable("pmcenter_conf"); @@ -168,7 +172,11 @@ public static async Task MainAsync(string[] args) Log("Hooking event processors..."); Vars.Bot.OnUpdate += BotProcess.OnUpdate; Log("Starting receiving..."); - Vars.Bot.StartReceiving(new[] { UpdateType.Message }); + Vars.Bot.StartReceiving(new[] + { + UpdateType.Message, + UpdateType.CallbackQuery + }); Log("==> Startup complete!"); Log("==> Running post-start operations..."); try diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index b78414f..1c8004b 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -14,7 +14,7 @@ namespace pmcenter { - public sealed class Setup + public static class Setup { private static readonly Conf.ConfObj NewConf = new Conf.ConfObj(); private static TelegramBotClient TestBot; diff --git a/pmcenter/Template.cs b/pmcenter/Template.cs index 8c07c16..9f581f5 100644 --- a/pmcenter/Template.cs +++ b/pmcenter/Template.cs @@ -4,8 +4,6 @@ // Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). */ -using System; - namespace pmcenter { public class Template From 2ac460ca3d325163df5c2987a032ebb635841f52 Mon Sep 17 00:00:00 2001 From: Elepover Date: Wed, 15 Apr 2020 08:42:56 +0800 Subject: [PATCH 15/39] refined inline keyboard markup --- .../BotProcess.CallbackQueryRoute.cs | 6 +++- .../BotProcess.GetKeyboardMarkup.cs | 30 ------------------- pmcenter/BotProcess/BotProcess.UserLogic.cs | 2 +- pmcenter/CallbackActions/BanAction.cs | 8 +++++ pmcenter/CallbackActions/CallbackManager.cs | 14 +++++++++ pmcenter/CallbackActions/CallbackProcess.cs | 4 +++ .../CallbackActions/ContinuedChatAction.cs | 7 +++++ .../DisableContinuedChatAction.cs | 7 +++++ pmcenter/CallbackActions/PardonAction.cs | 8 +++++ pmcenter/Interfaces/ICallbackAction.cs | 2 ++ .../Database/Checking/Methods.IsBanned.cs | 10 +++++++ 11 files changed, 66 insertions(+), 32 deletions(-) delete mode 100644 pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs diff --git a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs index a4df071..94e2091 100644 --- a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs +++ b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs @@ -2,6 +2,7 @@ using System; using System.Threading.Tasks; using Telegram.Bot.Args; +using Telegram.Bot.Types.ReplyMarkups; using static pmcenter.Methods; using static pmcenter.Methods.Logging; @@ -21,7 +22,10 @@ private static async Task CallbackQueryRoute(object sender, UpdateEventArgs e) await Vars.Bot.AnswerCallbackQueryAsync(update.CallbackQuery.Id, result.Status); // update existing buttons if (result.Succeeded) - await Vars.Bot.EditMessageReplyMarkupAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, GetKeyboardMarkup(update)); + await Vars.Bot.EditMessageReplyMarkupAsync( + update.CallbackQuery.Message.Chat.Id, + update.CallbackQuery.Message.MessageId, + new InlineKeyboardMarkup(CallbackProcess.GetAvailableButtons(update))); } catch (Exception ex) { diff --git a/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs b/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs deleted file mode 100644 index e3bf06a..0000000 --- a/pmcenter/BotProcess/BotProcess.GetKeyboardMarkup.cs +++ /dev/null @@ -1,30 +0,0 @@ -using pmcenter.CallbackActions; -using System.Collections.Generic; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; -using static pmcenter.Methods; - -namespace pmcenter -{ - public static partial class BotProcess - { - public static InlineKeyboardMarkup GetKeyboardMarkup(Update update) - { - var buttons = new List(); - bool isBanned = true; - if (update.Type == UpdateType.CallbackQuery) isBanned = IsBanned(GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId).TGUser.Id); - if (update.Type == UpdateType.Message) isBanned = IsBanned(update.Message.From.Id); - if (isBanned) - buttons.Add(new InlineKeyboardButton() { CallbackData = new PardonAction().Name, Text = Vars.CurrentLang.Message_Action_Pardon }); - else - buttons.Add(new InlineKeyboardButton() { CallbackData = new BanAction().Name, Text = Vars.CurrentLang.Message_Action_Ban }); - if (Vars.CurrentConf.ContChatTarget == -1) - buttons.Add(new InlineKeyboardButton() { CallbackData = new ContinuedChatAction().Name, Text = Vars.CurrentLang.Message_Action_Chat }); - else - buttons.Add(new InlineKeyboardButton() { CallbackData = new DisableContinuedChatAction().Name, Text = Vars.CurrentLang.Message_Action_StopChat }); - - return new InlineKeyboardMarkup(buttons); - } - } -} \ No newline at end of file diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 019f795..9785dba 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -63,7 +63,7 @@ private static async Task UserLogic(Update update) // process actions if (Vars.CurrentConf.EnableActions && Vars.CurrentConf.EnableMsgLink) { - var markup = GetKeyboardMarkup(update); + var markup = new InlineKeyboardMarkup(CallbackProcess.GetAvailableButtons(update)); link.OwnerSessionActionMessageID = (await Vars.Bot.SendTextMessageAsync( Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_Action_ChooseAction, diff --git a/pmcenter/CallbackActions/BanAction.cs b/pmcenter/CallbackActions/BanAction.cs index 628d5cd..b85d628 100644 --- a/pmcenter/CallbackActions/BanAction.cs +++ b/pmcenter/CallbackActions/BanAction.cs @@ -8,6 +8,7 @@ namespace pmcenter.CallbackActions internal class BanAction : ICallbackAction { public string Name => "ban"; + public string ButtonName => Vars.CurrentLang.Message_Action_Ban; public ICallbackAction Replacement => new PardonAction(); #pragma warning disable CS1998 @@ -17,7 +18,14 @@ public async Task Action(User user, Message msg) // attempt to ban the user Log($"Attempting to ban user {user.Id} via callback actions...", "BOT"); BanUser(user.Id); + Log($"User {user.Id} banned via callback actions...", "BOT"); return Vars.CurrentLang.Message_Action_Banned.Replace("$1", GetComposedUsername(user, false)); } + + public bool IsAvailable(Update update) + { + if (IsBanned(update)) return false; + return true; + } } } diff --git a/pmcenter/CallbackActions/CallbackManager.cs b/pmcenter/CallbackActions/CallbackManager.cs index 183bb75..b5de603 100644 --- a/pmcenter/CallbackActions/CallbackManager.cs +++ b/pmcenter/CallbackActions/CallbackManager.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; namespace pmcenter.CallbackActions { @@ -33,5 +34,18 @@ public async Task Execute(string actionName, User user, Message msg) } return null; } + + public List> GetAvailableButtons(Update update) + { + var result = new List>(); + foreach (var action in callbacks) + if (action.IsAvailable(update)) + { + var oneLineKeyboard = new List(); + oneLineKeyboard.Add(new InlineKeyboardButton() { CallbackData = action.Name, Text = action.ButtonName }); + result.Add(oneLineKeyboard); + } + return result; + } } } diff --git a/pmcenter/CallbackActions/CallbackProcess.cs b/pmcenter/CallbackActions/CallbackProcess.cs index 8bb3268..b3494bf 100644 --- a/pmcenter/CallbackActions/CallbackProcess.cs +++ b/pmcenter/CallbackActions/CallbackProcess.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; using static pmcenter.Methods.Logging; namespace pmcenter.CallbackActions @@ -39,5 +41,7 @@ public static async Task DoCallback(string actionName, Use return new CallbackActionResult(Vars.CurrentLang.Message_Action_Error, false); } } + + public static List> GetAvailableButtons(Update update) => callbackManager.GetAvailableButtons(update); } } diff --git a/pmcenter/CallbackActions/ContinuedChatAction.cs b/pmcenter/CallbackActions/ContinuedChatAction.cs index 9017618..b42af67 100644 --- a/pmcenter/CallbackActions/ContinuedChatAction.cs +++ b/pmcenter/CallbackActions/ContinuedChatAction.cs @@ -8,6 +8,7 @@ namespace pmcenter.CallbackActions internal class ContinuedChatAction : ICallbackAction { public string Name => "chat"; + public string ButtonName => Vars.CurrentLang.Message_Action_Chat; public ICallbackAction Replacement => new DisableContinuedChatAction(); #pragma warning disable CS1998 @@ -17,7 +18,13 @@ public async Task Action(User user, Message msg) Log("Enabling continued conversation via actions...", "BOT"); Vars.CurrentConf.ContChatTarget = user.Id; _ = await Conf.SaveConf(false, true).ConfigureAwait(false); + Log($"Continued conversation to {user.Id} enabled via actions.", "BOT"); return Vars.CurrentLang.Message_Action_ContChatEnabled.Replace("$1", GetComposedUsername(user, false)); } + + public bool IsAvailable(Update update) + { + return Vars.CurrentConf.ContChatTarget == -1; + } } } diff --git a/pmcenter/CallbackActions/DisableContinuedChatAction.cs b/pmcenter/CallbackActions/DisableContinuedChatAction.cs index 8e2da19..874964d 100644 --- a/pmcenter/CallbackActions/DisableContinuedChatAction.cs +++ b/pmcenter/CallbackActions/DisableContinuedChatAction.cs @@ -7,6 +7,7 @@ namespace pmcenter.CallbackActions internal class DisableContinuedChatAction : ICallbackAction { public string Name => "disablechat"; + public string ButtonName => Vars.CurrentLang.Message_Action_StopChat; public ICallbackAction Replacement => new ContinuedChatAction(); #pragma warning disable CS1998 @@ -16,7 +17,13 @@ public async Task Action(User user, Message msg) Log("Disabling continued conversation via actions...", "BOT"); Vars.CurrentConf.ContChatTarget = -1; _ = await Conf.SaveConf(false, true).ConfigureAwait(false); + Log("Continued conversation disabled via actions.", "BOT"); return Vars.CurrentLang.Message_Action_ContChatDisabled; } + + public bool IsAvailable(Update update) + { + return Vars.CurrentConf.ContChatTarget != -1; + } } } diff --git a/pmcenter/CallbackActions/PardonAction.cs b/pmcenter/CallbackActions/PardonAction.cs index 8608565..8a91085 100644 --- a/pmcenter/CallbackActions/PardonAction.cs +++ b/pmcenter/CallbackActions/PardonAction.cs @@ -8,6 +8,7 @@ namespace pmcenter.CallbackActions internal class PardonAction : ICallbackAction { public string Name => "pardon"; + public string ButtonName => Vars.CurrentLang.Message_Action_Pardon; public ICallbackAction Replacement => new BanAction(); #pragma warning disable CS1998 @@ -17,7 +18,14 @@ public async Task Action(User user, Message msg) // attempt to pardon the user Log($"Attempting to pardon {user.Id} via callback actions...", "BOT"); UnbanUser(user.Id); + Log($"User {user.Id} pardoned via callback actions...", "BOT"); return Vars.CurrentLang.Message_Action_Pardoned.Replace("$1", GetComposedUsername(user, false)); } + + public bool IsAvailable(Update update) + { + if (IsBanned(update)) return true; + return false; + } } } diff --git a/pmcenter/Interfaces/ICallbackAction.cs b/pmcenter/Interfaces/ICallbackAction.cs index f7ed7aa..da7bcaa 100644 --- a/pmcenter/Interfaces/ICallbackAction.cs +++ b/pmcenter/Interfaces/ICallbackAction.cs @@ -6,7 +6,9 @@ namespace pmcenter internal interface ICallbackAction { string Name { get; } + string ButtonName { get; } ICallbackAction Replacement { get; } Task Action(User user, Message msg); + bool IsAvailable(Update update); } } diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index 76e4ab6..0b86e25 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -1,3 +1,5 @@ +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using static pmcenter.Conf; namespace pmcenter @@ -12,5 +14,13 @@ public static bool IsBanned(long UID) } return false; } + + public static bool IsBanned(Update update) + { + bool isBanned = true; + if (update.Type == UpdateType.CallbackQuery) isBanned = IsBanned(GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId).TGUser.Id); + if (update.Type == UpdateType.Message) isBanned = IsBanned(update.Message.From.Id); + return isBanned; + } } } From 51c1851c8d0a733876f63c172db9ef98f631f925 Mon Sep 17 00:00:00 2001 From: Elepover Date: Wed, 15 Apr 2020 09:37:11 +0800 Subject: [PATCH 16/39] code refactoring --- pmcenter/BotCommands/BackupConfCommand.cs | 8 +-- pmcenter/BotCommands/Chat.cs | 28 ++++---- pmcenter/BotCommands/CheckUpdateCommand.cs | 15 +++-- .../BotCommands/ClearMessageLinksCommand.cs | 3 +- .../BotCommands/DetectPermissionCommand.cs | 8 +-- pmcenter/BotCommands/EditConfCommand.cs | 18 ++--- pmcenter/BotCommands/PerformCommand.cs | 4 +- pmcenter/BotCommands/ResetConfCommand.cs | 8 +-- pmcenter/BotCommands/RetractCommand.cs | 18 ++--- pmcenter/BotCommands/StatusCommand.cs | 24 +++---- pmcenter/BotCommands/SwitchBwCommand.cs | 4 +- pmcenter/BotCommands/SwitchFwCommand.cs | 4 +- pmcenter/BotCommands/SwitchLangCodeCommand.cs | 30 ++++----- pmcenter/BotCommands/SwitchLangCommand.cs | 6 +- .../BotCommands/SwitchNotificationCommand.cs | 4 +- pmcenter/BotCommands/TestNetwork.cs | 12 ++-- pmcenter/BotCommands/UpdateCommand.cs | 26 +++---- pmcenter/BotCommands/UptimeCommand.cs | 4 +- .../BotProcess.CallbackQueryRoute.cs | 6 +- .../BotProcess/BotProcess.MessageRoute.cs | 2 +- .../BotProcess/BotProcess.OwnerCommand.cs | 8 +-- pmcenter/BotProcess/BotProcess.OwnerLogic.cs | 2 +- .../BotProcess/BotProcess.OwnerReplying.cs | 22 +++--- pmcenter/BotProcess/BotProcess.RunCc.cs | 24 +++---- pmcenter/BotProcess/BotProcess.UserLogic.cs | 18 ++--- pmcenter/BotProcess/BotProcess.cs | 6 +- pmcenter/BotProcess/CommandRouter.cs | 4 +- pmcenter/CallbackActions/CallbackProcess.cs | 4 +- pmcenter/CommandLineRouter.cs | 2 +- pmcenter/CommandLines/BackupCmdLine.cs | 8 +-- pmcenter/CommandLines/InfoCmdLine.cs | 12 ++-- pmcenter/CommandLines/UpdateCmdLine.cs | 10 +-- pmcenter/Configurations/Conf.GetConf.cs | 6 +- pmcenter/Configurations/Conf.InitConf.cs | 6 +- .../Configurations/Conf.KillIllegalChars.cs | 4 +- pmcenter/Configurations/Conf.ReadConf.cs | 4 +- pmcenter/Configurations/Conf.SaveConf.cs | 8 +-- pmcenter/Configurations/Lang.InitLang.cs | 6 +- pmcenter/Configurations/Lang.ReadLang.cs | 6 +- pmcenter/Configurations/Lang.SaveLang.cs | 14 ++-- pmcenter/EventHandlers/CtrlCHandler.cs | 6 +- .../Checking/Methods.GetBanObjByID.cs | 6 +- .../Checking/Methods.GetLinkByOwnerMsgID.cs | 6 +- .../Checking/Methods.GetLinkByUserMsgID.cs | 6 +- .../Checking/Methods.GetRateDataIndexByID.cs | 6 +- .../Database/Checking/Methods.IsBanned.cs | 6 +- .../Checking/Methods.IsKeywordBanned.cs | 10 +-- .../Methods.IsOwnerRetractionAvailable.cs | 8 +-- .../Checking/Methods.IsRateDataTracking.cs | 6 +- .../Methods.IsUserRetractionAvailable.cs | 8 +-- .../Database/Writing/Methods.AddRateLimit.cs | 14 ++-- .../Database/Writing/Methods.BanUser.cs | 10 +-- .../Database/Writing/Methods.UnbanUser.cs | 6 +- pmcenter/Methods/Logging/Methods.Log.cs | 12 ++-- pmcenter/Methods/Logging/Methods.LogLevel.cs | 6 +- pmcenter/Methods/Logging/Methods.LogTable.cs | 6 +- pmcenter/Methods/Methods.BoolStr.cs | 4 +- .../Methods/Methods.CheckNetCoreVersion.cs | 6 +- pmcenter/Methods/Methods.CheckOpenSSLComp.cs | 2 +- pmcenter/Methods/Methods.FlipBool.cs | 4 +- pmcenter/Methods/Methods.GetNetCoreVersion.cs | 2 +- pmcenter/Methods/Methods.GetRandomString.cs | 4 +- pmcenter/Methods/Methods.GetThreadStatus.cs | 4 +- .../Methods/Methods.GetThreadStatusString.cs | 4 +- pmcenter/Methods/Methods.GetUpdateLevel.cs | 16 ++--- pmcenter/Methods/Methods.IsRegexMatch.cs | 12 +--- .../NetworkTest/Methods.TestConnectivity.cs | 2 +- .../Threads/Methods.ThrDoResetConfCount.cs | 2 +- .../Methods/Threads/Methods.ThrPerform.cs | 2 +- .../Methods/Threads/Methods.ThrRateLimiter.cs | 10 +-- .../Methods/Threads/Methods.ThrSyncConf.cs | 4 +- .../Threads/Methods.ThrUpdateChecker.cs | 26 +++---- ...ethods.UpdateHelper.DownloadUpdateAsync.cs | 8 +-- ...UpdateHelper.GetUpdateInfoIndexByLocale.cs | 4 +- ...ds.UpdateHelper.IsNewerVersionAvailable.cs | 6 +- pmcenter/Program.cs | 67 ++++++++----------- pmcenter/Setup.cs | 30 ++++----- 77 files changed, 367 insertions(+), 380 deletions(-) diff --git a/pmcenter/BotCommands/BackupConfCommand.cs b/pmcenter/BotCommands/BackupConfCommand.cs index b5fe09e..70e62c9 100644 --- a/pmcenter/BotCommands/BackupConfCommand.cs +++ b/pmcenter/BotCommands/BackupConfCommand.cs @@ -17,12 +17,12 @@ internal class BackupConfCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var RandomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; - Log($"Backing up configurations, filename: {Path.Combine(Vars.AppDirectory, RandomFilename)}", "BOT"); - System.IO.File.Copy(Vars.ConfFile, RandomFilename); + var randomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; + Log($"Backing up configurations, filename: {Path.Combine(Vars.AppDirectory, randomFilename)}", "BOT"); + System.IO.File.Copy(Vars.ConfFile, randomFilename); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - Vars.CurrentLang.Message_BackupComplete.Replace("$1", RandomFilename), + Vars.CurrentLang.Message_BackupComplete.Replace("$1", randomFilename), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/Chat.cs b/pmcenter/BotCommands/Chat.cs index ba6f601..0fc1895 100644 --- a/pmcenter/BotCommands/Chat.cs +++ b/pmcenter/BotCommands/Chat.cs @@ -19,42 +19,42 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { Log("Enabling Continued Conversation...", "BOT"); - long RealTarget; - bool IsArgumentMode; + long realTarget; + bool isArgumentMode; // try to use argument if (update.Message.Text.Contains(" ")) { - IsArgumentMode = true; + isArgumentMode = true; Log("Resolving arguments...", "BOT"); - RealTarget = long.Parse(update.Message.Text.Split(" ", 2)[1]); + realTarget = long.Parse(update.Message.Text.Split(" ", 2)[1]); } else { - IsArgumentMode = false; + isArgumentMode = false; // no argument detected / use reply message instead if (update.Message.ReplyToMessage.ForwardFrom == null) { throw (new ArgumentException("Cannot initiate Continued Conversation by channel posts.")); } - RealTarget = update.Message.ReplyToMessage.ForwardFrom.Id; + realTarget = update.Message.ReplyToMessage.ForwardFrom.Id; } - Log($"Continued Conversation enabled, target: {RealTarget}", "BOT"); - Vars.CurrentConf.ContChatTarget = RealTarget; + Log($"Continued Conversation enabled, target: {realTarget}", "BOT"); + Vars.CurrentConf.ContChatTarget = realTarget; _ = await Conf.SaveConf(false, true).ConfigureAwait(false); - string ReplaceText; - if (IsArgumentMode) + string replacementText; + if (isArgumentMode) { - ReplaceText = $"[{RealTarget}](tg://user?id={RealTarget})"; + replacementText = $"[{realTarget}](tg://user?id={realTarget})"; } else { - ReplaceText = $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={RealTarget})"; + replacementText = $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={realTarget})"; } _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - Vars.CurrentLang.Message_ContinuedChatEnabled.Replace("$1", ReplaceText), + Vars.CurrentLang.Message_ContinuedChatEnabled.Replace("$1", replacementText), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, @@ -63,7 +63,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } catch (Exception ex) { - Log($"Failed to enable Continued Conversation: {ex}", "BOT", LogLevel.ERROR); + Log($"Failed to enable Continued Conversation: {ex}", "BOT", LogLevel.Error); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), ParseMode.Default, diff --git a/pmcenter/BotCommands/CheckUpdateCommand.cs b/pmcenter/BotCommands/CheckUpdateCommand.cs index 4cfbd30..9a1c65e 100644 --- a/pmcenter/BotCommands/CheckUpdateCommand.cs +++ b/pmcenter/BotCommands/CheckUpdateCommand.cs @@ -17,19 +17,19 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T try { var latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); if (IsNewerVersionAvailable(latest)) { Vars.UpdatePending = true; Vars.UpdateVersion = new Version(latest.Latest); Vars.UpdateLevel = latest.UpdateLevel; - var UpdateString = Vars.CurrentLang.Message_UpdateAvailable + var updateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", latest.Latest) - .Replace("$2", latest.UpdateCollection[CurrentLocalizedIndex].Details) + .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) .Replace("$3", Methods.GetUpdateLevel(latest.UpdateLevel)); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - UpdateString, + updateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, @@ -43,7 +43,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T Vars.CurrentLang.Message_AlreadyUpToDate .Replace("$1", latest.Latest) .Replace("$2", Vars.AppVer.ToString()) - .Replace("$3", latest.UpdateCollection[CurrentLocalizedIndex].Details), + .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, @@ -53,10 +53,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T } catch (Exception ex) { - var ErrorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.Message); + var errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.Message); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - ErrorString, ParseMode.Markdown, + errorString, + ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); diff --git a/pmcenter/BotCommands/ClearMessageLinksCommand.cs b/pmcenter/BotCommands/ClearMessageLinksCommand.cs index c759060..2400b16 100644 --- a/pmcenter/BotCommands/ClearMessageLinksCommand.cs +++ b/pmcenter/BotCommands/ClearMessageLinksCommand.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; @@ -15,7 +16,7 @@ internal class ClearMessageLinksCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { Log("Clearing message links...", "BOT"); - Vars.CurrentConf.MessageLinks = new System.Collections.Generic.List(); + Vars.CurrentConf.MessageLinks = new List(); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_MsgLinksCleared, diff --git a/pmcenter/BotCommands/DetectPermissionCommand.cs b/pmcenter/BotCommands/DetectPermissionCommand.cs index 9f69e29..4871545 100644 --- a/pmcenter/BotCommands/DetectPermissionCommand.cs +++ b/pmcenter/BotCommands/DetectPermissionCommand.cs @@ -15,13 +15,13 @@ internal class DetectPermissionCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var ConfWritable = FlipBool((new FileInfo(Vars.ConfFile)).IsReadOnly); - var LangWritable = FlipBool((new FileInfo(Vars.LangFile)).IsReadOnly); + var confWritable = FlipBool((new FileInfo(Vars.ConfFile)).IsReadOnly); + var langWritable = FlipBool((new FileInfo(Vars.LangFile)).IsReadOnly); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfAccess - .Replace("$1", BoolStr(ConfWritable)) - .Replace("$2", BoolStr(LangWritable)) + .Replace("$1", BoolStr(confWritable)) + .Replace("$2", BoolStr(langWritable)) , ParseMode.Markdown, false, diff --git a/pmcenter/BotCommands/EditConfCommand.cs b/pmcenter/BotCommands/EditConfCommand.cs index 63a4a0b..846a415 100644 --- a/pmcenter/BotCommands/EditConfCommand.cs +++ b/pmcenter/BotCommands/EditConfCommand.cs @@ -20,12 +20,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - Log("Configurations received, applying...", "BOT", LogLevel.INFO); - var ConfStr = update.Message.Text.Split(" ", 2)[1]; - var Temp = JsonConvert.DeserializeObject(ConfStr); - if (Temp.APIKey != Vars.CurrentConf.APIKey) + Log("Configurations received, applying...", "BOT", LogLevel.Info); + var confStr = update.Message.Text.Split(" ", 2)[1]; + var temp = JsonConvert.DeserializeObject(confStr); + if (temp.APIKey != Vars.CurrentConf.APIKey) { - Log("API Key has changed! Please restart pmcenter to apply the change.", "BOT", LogLevel.WARN); + Log("API Key has changed! Please restart pmcenter to apply the change.", "BOT", LogLevel.Warning); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_APIKeyChanged, @@ -35,9 +35,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.MessageId).ConfigureAwait(false); Vars.RestartRequired = true; } - if (Temp.ConfSyncInterval == 0) + if (temp.ConfSyncInterval == 0) { - Log("ConfSync has been disabled, the worker thread will exit soon.", "BOT", LogLevel.WARN); + Log("ConfSync has been disabled, the worker thread will exit soon.", "BOT", LogLevel.Warning); } else if (Vars.CurrentConf.ConfSyncInterval == 0) { @@ -46,8 +46,8 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) Vars.SyncConf = new Thread(() => ThrSyncConf()); Vars.SyncConf.Start(); } - Vars.CurrentConf = Temp; - Log("Applied! Saving to local disk...", "BOT", LogLevel.INFO); + Vars.CurrentConf = temp; + Log("Applied! Saving to local disk...", "BOT", LogLevel.Info); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, diff --git a/pmcenter/BotCommands/PerformCommand.cs b/pmcenter/BotCommands/PerformCommand.cs index b536503..086b5c7 100644 --- a/pmcenter/BotCommands/PerformCommand.cs +++ b/pmcenter/BotCommands/PerformCommand.cs @@ -21,8 +21,8 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); - var PerformanceChecker = new Thread(() => Methods.ThrPerform()); - PerformanceChecker.Start(); + var performanceChecker = new Thread(() => Methods.ThrPerform()); + performanceChecker.Start(); Thread.Sleep(1000); Vars.IsPerformanceTestEndRequested = true; while (Vars.IsPerformanceTestExecuting) diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index 9506b86..b0dea67 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -23,12 +23,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); - var OwnerID = Vars.CurrentConf.OwnerUID; - var APIKey = Vars.CurrentConf.APIKey; + var ownerId = Vars.CurrentConf.OwnerUID; + var apiKey = Vars.CurrentConf.APIKey; Vars.CurrentConf = new Conf.ConfObj { - OwnerUID = OwnerID, - APIKey = APIKey + OwnerUID = ownerId, + APIKey = apiKey }; _ = await Conf.SaveConf(false, true).ConfigureAwait(false); Vars.CurrentLang = new Lang.Language(); diff --git a/pmcenter/BotCommands/RetractCommand.cs b/pmcenter/BotCommands/RetractCommand.cs index eaafd1f..9e64885 100644 --- a/pmcenter/BotCommands/RetractCommand.cs +++ b/pmcenter/BotCommands/RetractCommand.cs @@ -17,13 +17,13 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { return false; } - var SelectedMsgID = update.Message.ReplyToMessage.MessageId; + var selectedMsgId = update.Message.ReplyToMessage.MessageId; if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) { // owner retracting - if (Methods.IsOwnerRetractionAvailable(SelectedMsgID)) + if (Methods.IsOwnerRetractionAvailable(selectedMsgId)) { - var Link = Methods.GetLinkByOwnerMsgID(SelectedMsgID); - await botClient.DeleteMessageAsync(Link.TGUser.Id, Link.UserSessionMessageID).ConfigureAwait(false); + var link = Methods.GetLinkByOwnerMsgID(selectedMsgId); + await botClient.DeleteMessageAsync(link.TGUser.Id, link.UserSessionMessageID).ConfigureAwait(false); } else { @@ -38,12 +38,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } else // user retracting { - if (Methods.IsUserRetractionAvailable(SelectedMsgID)) + if (Methods.IsUserRetractionAvailable(selectedMsgId)) { - var Link = Methods.GetLinkByUserMsgID(SelectedMsgID); - await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, Link.OwnerSessionMessageID).ConfigureAwait(false); - if (Vars.CurrentConf.EnableActions && Link.OwnerSessionActionMessageID != -1) - await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, Link.OwnerSessionActionMessageID).ConfigureAwait(false); + var link = Methods.GetLinkByUserMsgID(selectedMsgId); + await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionMessageID).ConfigureAwait(false); + if (Vars.CurrentConf.EnableActions && link.OwnerSessionActionMessageID != -1) + await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionActionMessageID).ConfigureAwait(false); } else { diff --git a/pmcenter/BotCommands/StatusCommand.cs b/pmcenter/BotCommands/StatusCommand.cs index 8d2462d..d2e9a89 100644 --- a/pmcenter/BotCommands/StatusCommand.cs +++ b/pmcenter/BotCommands/StatusCommand.cs @@ -16,27 +16,27 @@ internal class StatusCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var MessageStr = Vars.CurrentLang.Message_SysStatus_Header + "\n\n"; + var messageStr = Vars.CurrentLang.Message_SysStatus_Header + "\n\n"; // process other headers - var NoActionRequired = true; + var noActionRequired = true; if (Vars.UpdatePending) { - MessageStr += Vars.CurrentLang.Message_SysStatus_PendingUpdate.Replace("$1", Vars.UpdateVersion.ToString()) + "\n"; - MessageStr += GetUpdateLevel(Vars.UpdateLevel) + "\n"; - NoActionRequired = false; + messageStr += Vars.CurrentLang.Message_SysStatus_PendingUpdate.Replace("$1", Vars.UpdateVersion.ToString()) + "\n"; + messageStr += GetUpdateLevel(Vars.UpdateLevel) + "\n"; + noActionRequired = false; } if (Vars.NonEmergRestartRequired) { - MessageStr += Vars.CurrentLang.Message_SysStatus_RestartRequired + "\n"; - NoActionRequired = false; + messageStr += Vars.CurrentLang.Message_SysStatus_RestartRequired + "\n"; + noActionRequired = false; } - if (NoActionRequired) + if (noActionRequired) { - MessageStr += Vars.CurrentLang.Message_SysStatus_NoOperationRequired + "\n"; + messageStr += Vars.CurrentLang.Message_SysStatus_NoOperationRequired + "\n"; } - MessageStr += "\n"; + messageStr += "\n"; // process summary - MessageStr += Vars.CurrentLang.Message_SysStatus_Summary + messageStr += Vars.CurrentLang.Message_SysStatus_Summary .Replace("$1", Environment.MachineName) .Replace("$2", Environment.OSVersion.ToString()) .Replace("$3", RuntimeInformation.OSDescription) @@ -56,7 +56,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - MessageStr, + messageStr, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/SwitchBwCommand.cs b/pmcenter/BotCommands/SwitchBwCommand.cs index e0b306f..72a61fa 100644 --- a/pmcenter/BotCommands/SwitchBwCommand.cs +++ b/pmcenter/BotCommands/SwitchBwCommand.cs @@ -13,11 +13,11 @@ internal class SwitchBwCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var IsEnabledNow = Conf.SwitchBlocking(); + var isEnabledNow = Conf.SwitchBlocking(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - IsEnabledNow ? + isEnabledNow ? Vars.CurrentLang.Message_MessageBlockEnabled : Vars.CurrentLang.Message_MessageBlockDisabled, ParseMode.Markdown, diff --git a/pmcenter/BotCommands/SwitchFwCommand.cs b/pmcenter/BotCommands/SwitchFwCommand.cs index e9e34ba..a2c3c88 100644 --- a/pmcenter/BotCommands/SwitchFwCommand.cs +++ b/pmcenter/BotCommands/SwitchFwCommand.cs @@ -13,10 +13,10 @@ internal class SwitchFwCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var IsPausedNow = Conf.SwitchPaused(); + var isPausedNow = Conf.SwitchPaused(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - IsPausedNow ? + isPausedNow ? Vars.CurrentLang.Message_ServicePaused : Vars.CurrentLang.Message_ServiceResumed, ParseMode.Markdown, diff --git a/pmcenter/BotCommands/SwitchLangCodeCommand.cs b/pmcenter/BotCommands/SwitchLangCodeCommand.cs index 2fb5fbf..34be983 100644 --- a/pmcenter/BotCommands/SwitchLangCodeCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCodeCommand.cs @@ -17,30 +17,30 @@ internal class SwitchLangCodeCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - string Reply; - string ListJSONString; - Conf.LocaleList LocaleList; + string reply; + string listJsonString; + Conf.LocaleList localeList; // try to get locale list - ListJSONString = await GetStringAsync(new Uri(Vars.LocaleMapURL.Replace("$channel", Vars.CurrentConf.UpdateChannel))).ConfigureAwait(false); - LocaleList = JsonConvert.DeserializeObject(ListJSONString); + listJsonString = await GetStringAsync(new Uri(Vars.LocaleMapURL.Replace("$channel", Vars.CurrentConf.UpdateChannel))).ConfigureAwait(false); + localeList = JsonConvert.DeserializeObject(listJsonString); if (!update.Message.Text.Contains(" ")) { - var ListString = ""; - foreach (Conf.LocaleMirror Mirror in LocaleList.Locales) + var listString = ""; + foreach (var mirror in localeList.Locales) { - ListString += $"{Mirror.LocaleCode} - {Mirror.LocaleNameNative} ({Mirror.LocaleNameEng})\n"; + listString += $"{mirror.LocaleCode} - {mirror.LocaleNameNative} ({mirror.LocaleNameEng})\n"; } - Reply = Vars.CurrentLang.Message_AvailableLang.Replace("$1", ListString); + reply = Vars.CurrentLang.Message_AvailableLang.Replace("$1", listString); } else { - var TargetCode = update.Message.Text.Split(" ")[1]; - foreach (Conf.LocaleMirror Mirror in LocaleList.Locales) + var targetCode = update.Message.Text.Split(" ")[1]; + foreach (var mirror in localeList.Locales) { - if (Mirror.LocaleCode == TargetCode) + if (mirror.LocaleCode == targetCode) { // update configurations - Vars.CurrentConf.LangURL = Mirror.LocaleFileURL.Replace("$channel", Vars.CompileChannel); + Vars.CurrentConf.LangURL = mirror.LocaleFileURL.Replace("$channel", Vars.CompileChannel); // start downloading _ = await Conf.SaveConf(isAutoSave: true).ConfigureAwait(false); await DownloadFileAsync( @@ -53,7 +53,7 @@ await DownloadFileAsync( // reload configurations _ = await Conf.ReadConf().ConfigureAwait(false); _ = await Lang.ReadLang().ConfigureAwait(false); - Reply = Vars.CurrentLang.Message_LangSwitched; + reply = Vars.CurrentLang.Message_LangSwitched; goto SendMsg; } } @@ -62,7 +62,7 @@ await DownloadFileAsync( SendMsg: _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - Reply, + reply, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index 68b5fec..9a97a5a 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -27,12 +27,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.MessageId).ConfigureAwait(false); // download file - var LangURL = update.Message.Text.Split(" ")[1]; - Vars.CurrentConf.LangURL = LangURL; + var langUrl = update.Message.Text.Split(" ")[1]; + Vars.CurrentConf.LangURL = langUrl; // save conf _ = await Conf.SaveConf(isAutoSave: true); await DownloadFileAsync( - new Uri(LangURL), + new Uri(langUrl), Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") ).ConfigureAwait(false); diff --git a/pmcenter/BotCommands/SwitchNotificationCommand.cs b/pmcenter/BotCommands/SwitchNotificationCommand.cs index 7a42d62..d78ebd3 100644 --- a/pmcenter/BotCommands/SwitchNotificationCommand.cs +++ b/pmcenter/BotCommands/SwitchNotificationCommand.cs @@ -13,10 +13,10 @@ internal class SwitchNotificationCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var IsDisabledNow = Conf.SwitchNotifications(); + var isDisabledNow = Conf.SwitchNotifications(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - IsDisabledNow ? + isDisabledNow ? Vars.CurrentLang.Message_NotificationsOff : Vars.CurrentLang.Message_NotificationsOn, ParseMode.Markdown, diff --git a/pmcenter/BotCommands/TestNetwork.cs b/pmcenter/BotCommands/TestNetwork.cs index 7558c6c..e4b6d6d 100644 --- a/pmcenter/BotCommands/TestNetwork.cs +++ b/pmcenter/BotCommands/TestNetwork.cs @@ -17,14 +17,14 @@ internal class TestNetworkCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { Log("Starting network test...", "BOT"); - var LatencyToGH = Math.Round((await TestLatency("https://github.com").ConfigureAwait(false)).TotalMilliseconds, 2); - var LatencyToTG = Math.Round((await TestLatency("https://api.telegram.org/bot").ConfigureAwait(false)).TotalMilliseconds, 2); - var LatencyToCI = Math.Round((await TestLatency("https://ci.appveyor.com").ConfigureAwait(false)).TotalMilliseconds, 2); + var latencyToGh = Math.Round((await TestLatency("https://github.com").ConfigureAwait(false)).TotalMilliseconds, 2); + var latencyToTg = Math.Round((await TestLatency("https://api.telegram.org/bot").ConfigureAwait(false)).TotalMilliseconds, 2); + var latencyToCi = Math.Round((await TestLatency("https://ci.appveyor.com").ConfigureAwait(false)).TotalMilliseconds, 2); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_Connectivity - .Replace("$1", LatencyToGH + "ms") - .Replace("$2", LatencyToTG + "ms") - .Replace("$3", LatencyToCI + "ms"), + .Replace("$1", latencyToGh + "ms") + .Replace("$2", latencyToTg + "ms") + .Replace("$3", latencyToCi + "ms"), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index 7ccbe76..05d4a3b 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -18,18 +18,18 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T { try { - var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); - if (IsNewerVersionAvailable(Latest)) + var latest = await CheckForUpdatesAsync().ConfigureAwait(false); + var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + if (IsNewerVersionAvailable(latest)) { - var UpdateString = Vars.CurrentLang.Message_UpdateAvailable - .Replace("$1", Latest.Latest) - .Replace("$2", Latest.UpdateCollection[CurrentLocalizedIndex].Details) - .Replace("$3", GetUpdateLevel(Latest.UpdateLevel)); + var updateString = Vars.CurrentLang.Message_UpdateAvailable + .Replace("$1", latest.Latest) + .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) + .Replace("$3", GetUpdateLevel(latest.UpdateLevel)); // \ update available! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - UpdateString, ParseMode.Markdown, + updateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); @@ -42,7 +42,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); // download compiled package - await DownloadUpdatesAsync(Latest, CurrentLocalizedIndex).ConfigureAwait(false); + await DownloadUpdatesAsync(latest, currentLocalizedIndex).ConfigureAwait(false); // update languages if (Vars.CurrentConf.AutoLangUpdate) await DownloadLangAsync().ConfigureAwait(false); @@ -64,9 +64,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_AlreadyUpToDate - .Replace("$1", Latest.Latest) + .Replace("$1", latest.Latest) .Replace("$2", Vars.AppVer.ToString()) - .Replace("$3", Latest.UpdateCollection[CurrentLocalizedIndex].Details), + .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, @@ -76,10 +76,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T } catch (Exception ex) { - string ErrorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.ToString()); + string errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.ToString()); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - ErrorString, + errorString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotCommands/UptimeCommand.cs b/pmcenter/BotCommands/UptimeCommand.cs index dd4aa67..f4d91d3 100644 --- a/pmcenter/BotCommands/UptimeCommand.cs +++ b/pmcenter/BotCommands/UptimeCommand.cs @@ -14,13 +14,13 @@ internal class UptimeCommand : ICommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var UptimeString = + var uptimeString = Vars.CurrentLang.Message_UptimeInfo .Replace("$1", (new TimeSpan(0, 0, 0, 0, Environment.TickCount)).ToString()) .Replace("$2", Vars.StartSW.Elapsed.ToString()); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - UptimeString, + uptimeString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, diff --git a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs index 94e2091..8d2a89c 100644 --- a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs +++ b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs @@ -22,15 +22,15 @@ private static async Task CallbackQueryRoute(object sender, UpdateEventArgs e) await Vars.Bot.AnswerCallbackQueryAsync(update.CallbackQuery.Id, result.Status); // update existing buttons if (result.Succeeded) - await Vars.Bot.EditMessageReplyMarkupAsync( + _ = await Vars.Bot.EditMessageReplyMarkupAsync( update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, new InlineKeyboardMarkup(CallbackProcess.GetAvailableButtons(update))); } catch (Exception ex) { - Log($"Unable to process action {update.CallbackQuery.Data}: {ex}", "BOT", LogLevel.ERROR); + Log($"Unable to process action {update.CallbackQuery.Data}: {ex}", "BOT", LogLevel.Error); } } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.MessageRoute.cs b/pmcenter/BotProcess/BotProcess.MessageRoute.cs index ace5a3c..2bff76c 100644 --- a/pmcenter/BotProcess/BotProcess.MessageRoute.cs +++ b/pmcenter/BotProcess/BotProcess.MessageRoute.cs @@ -31,4 +31,4 @@ private static async Task MessageRoute(object sender, UpdateEventArgs e) } } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs index d167078..445f733 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs @@ -20,17 +20,17 @@ private static async Task OwnerCommand(Update update) if (Vars.CurrentConf.ContChatTarget != -1) { // Is replying, replying to forwarded message AND not command. - var Forwarded = await Vars.Bot.ForwardMessageAsync( + var forwarded = await Vars.Bot.ForwardMessageAsync( Vars.CurrentConf.ContChatTarget, update.Message.Chat.Id, update.Message.MessageId, Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); if (Vars.CurrentConf.EnableMsgLink) { - Log($"Recording message link: {Forwarded.MessageId} -> {update.Message.MessageId} in {update.Message.From.Id}", "BOT"); + Log($"Recording message link: {forwarded.MessageId} -> {update.Message.MessageId} in {update.Message.From.Id}", "BOT"); Vars.CurrentConf.MessageLinks.Add( new Conf.MessageIDLink() - { OwnerSessionMessageID = Forwarded.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = true } + { OwnerSessionMessageID = forwarded.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = true } ); // Conf.SaveConf(false, true); } @@ -54,4 +54,4 @@ private static async Task OwnerCommand(Update update) update.Message.MessageId).ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.OwnerLogic.cs b/pmcenter/BotProcess/BotProcess.OwnerLogic.cs index b262e4e..2d10cc0 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerLogic.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerLogic.cs @@ -17,4 +17,4 @@ private static async Task OwnerLogic(Update update) } } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index 030096e..14811f6 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -10,11 +10,11 @@ public static partial class BotProcess private static async Task OwnerReplying(Update update) { // check anonymous forward (5.5.0 new feature compatibility fix) - var Link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); - if (Link != null && !Link.IsFromOwner) + var link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); + if (link != null && !link.IsFromOwner) { - Log($"Selected message is forwarded anonymously from {Link.TGUser.Id}, fixing user information from database.", "BOT"); - update.Message.ReplyToMessage.ForwardFrom = Link.TGUser; + Log($"Selected message is forwarded anonymously from {link.TGUser.Id}, fixing user information from database.", "BOT"); + update.Message.ReplyToMessage.ForwardFrom = link.TGUser; } if (update.Message.ReplyToMessage.ForwardFrom == null && update.Message.Text.ToLower() != "/retract") { @@ -36,17 +36,17 @@ private static async Task OwnerReplying(Update update) } // Is replying, replying to forwarded message AND not command. - var Forwarded = await Vars.Bot.ForwardMessageAsync( + var forwarded = await Vars.Bot.ForwardMessageAsync( update.Message.ReplyToMessage.ForwardFrom.Id, update.Message.Chat.Id, update.Message.MessageId, Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); if (Vars.CurrentConf.EnableMsgLink) { - Log($"Recording message link: user {Forwarded.MessageId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT"); + Log($"Recording message link: user {forwarded.MessageId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT"); Vars.CurrentConf.MessageLinks.Add( new Conf.MessageIDLink() - { OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = Forwarded.MessageId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true } + { OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = forwarded.MessageId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true } ); // Conf.SaveConf(false, true); } @@ -54,11 +54,11 @@ private static async Task OwnerReplying(Update update) // Process locale. if (Vars.CurrentConf.EnableRepliedConfirmation) { - var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; - ReplyToMessage = ReplyToMessage.Replace("$1", $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); + var replyToMessage = Vars.CurrentLang.Message_ReplySuccessful; + replyToMessage = replyToMessage.Replace("$1", $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, replyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); } Log($"Successfully passed owner's reply to {update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username} / {update.Message.ReplyToMessage.ForwardFrom.Id})", "BOT"); } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.RunCc.cs b/pmcenter/BotProcess/BotProcess.RunCc.cs index b05ad76..3c39441 100644 --- a/pmcenter/BotProcess/BotProcess.RunCc.cs +++ b/pmcenter/BotProcess/BotProcess.RunCc.cs @@ -11,27 +11,27 @@ public static partial class BotProcess private static async Task RunCc(Update update) { Log("Cc enabled, forwarding...", "BOT"); - foreach (long Id in Vars.CurrentConf.Cc) + foreach (var id in Vars.CurrentConf.Cc) { - Log($"Forwarding message to cc: {Id}", "BOT"); + Log($"Forwarding message to cc: {id}", "BOT"); try { - var ForwardedMessageCc = await Vars.Bot.ForwardMessageAsync(Id, - update.Message.From.Id, - update.Message.MessageId, - Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + var forwardedMessageCc = await Vars.Bot.ForwardMessageAsync(id, + update.Message.From.Id, + update.Message.MessageId, + Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); // check if forwarded from channels if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) { // is forwarded from channel - _ = await Vars.Bot.SendTextMessageAsync(Id, + _ = await Vars.Bot.SendTextMessageAsync(id, Vars.CurrentLang.Message_ForwarderNotReal .Replace("$2", update.Message.From.Id.ToString()) .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, - ForwardedMessageCc.MessageId).ConfigureAwait(false); + forwardedMessageCc.MessageId).ConfigureAwait(false); } if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) { @@ -39,22 +39,22 @@ private static async Task RunCc(Update update) // check real message sender if (update.Message.ForwardFrom.Id != update.Message.From.Id) { - _ = await Vars.Bot.SendTextMessageAsync(Id, + _ = await Vars.Bot.SendTextMessageAsync(id, Vars.CurrentLang.Message_ForwarderNotReal .Replace("$2", update.Message.From.Id.ToString()) .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, - ForwardedMessageCc.MessageId).ConfigureAwait(false); + forwardedMessageCc.MessageId).ConfigureAwait(false); } } } catch (Exception ex) { - Log($"Unable to forward message to cc: {Id}, reason: {ex.Message}", "BOT", LogLevel.ERROR); + Log($"Unable to forward message to cc: {id}, reason: {ex.Message}", "BOT", LogLevel.Error); } } } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 9785dba..9a3eadc 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -24,7 +24,7 @@ private static async Task UserLogic(Update update) if (Vars.CurrentConf.ForwardingPaused) { - Log("Stopped: forwarding is currently paused.", "BOT", LogLevel.INFO); + Log("Stopped: forwarding is currently paused.", "BOT", LogLevel.Info); _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_UserServicePaused, ParseMode.Markdown, @@ -37,7 +37,7 @@ private static async Task UserLogic(Update update) // test text blacklist if (!string.IsNullOrEmpty(update.Message.Text) && IsKeywordBanned(update.Message.Text)) { - Log("Stopped: sentence contains blocked words.", "BOT", LogLevel.INFO); + Log("Stopped: sentence contains blocked words.", "BOT", LogLevel.Info); if (Vars.CurrentConf.KeywordAutoBan) { BanUser(update.Message.From.Id); @@ -47,7 +47,7 @@ private static async Task UserLogic(Update update) // process owner Log("Forwarding message to owner...", "BOT"); - var ForwardedMessage = await Vars.Bot.ForwardMessageAsync(Vars.CurrentConf.OwnerUID, + var forwardedMessage = await Vars.Bot.ForwardMessageAsync(Vars.CurrentConf.OwnerUID, update.Message.From.Id, update.Message.MessageId, Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); @@ -55,7 +55,7 @@ private static async Task UserLogic(Update update) // preprocess message link var link = new Conf.MessageIDLink() { - OwnerSessionMessageID = ForwardedMessage.MessageId, + OwnerSessionMessageID = forwardedMessage.MessageId, UserSessionMessageID = update.Message.MessageId, TGUser = update.Message.From, IsFromOwner = false @@ -70,14 +70,14 @@ private static async Task UserLogic(Update update) ParseMode.Markdown, false, true, - ForwardedMessage.MessageId, + forwardedMessage.MessageId, markup ).ConfigureAwait(false)).MessageId; } // process message links if (Vars.CurrentConf.EnableMsgLink) { - Log($"Recording message link: owner {ForwardedMessage.MessageId} <-> user {update.Message.MessageId} user: {update.Message.From.Id}", "BOT"); + Log($"Recording message link: owner {forwardedMessage.MessageId} <-> user {update.Message.MessageId} user: {update.Message.From.Id}", "BOT"); Vars.CurrentConf.MessageLinks.Add(link); // Conf.SaveConf(false, true); } @@ -93,7 +93,7 @@ private static async Task UserLogic(Update update) ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, - ForwardedMessage.MessageId).ConfigureAwait(false); + forwardedMessage.MessageId).ConfigureAwait(false); } if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) { @@ -107,7 +107,7 @@ private static async Task UserLogic(Update update) ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, - ForwardedMessage.MessageId).ConfigureAwait(false); + forwardedMessage.MessageId).ConfigureAwait(false); } } @@ -128,4 +128,4 @@ private static async Task UserLogic(Update update) AddRateLimit(update.Message.From.Id); } } -} \ No newline at end of file +} diff --git a/pmcenter/BotProcess/BotProcess.cs b/pmcenter/BotProcess/BotProcess.cs index 337936d..e3e37d1 100644 --- a/pmcenter/BotProcess/BotProcess.cs +++ b/pmcenter/BotProcess/BotProcess.cs @@ -61,7 +61,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) { if (e == null) return; if (Vars.CurrentConf.DetailedMsgLogging) - Log($"OnUpdate() triggered: UpdType: {e.Update.Type}, UpdID: {e.Update.Id}, ChatId: {e.Update.Message.Chat.Id}, Username: {e.Update.Message.Chat.Username}, FromID: {e.Update.Message.From.Id}, FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.INFO); + Log($"OnUpdate() triggered: UpdType: {e.Update.Type}, UpdID: {e.Update.Id}, ChatId: {e.Update.Message.Chat.Id}, Username: {e.Update.Message.Chat.Username}, FromID: {e.Update.Message.From.Id}, FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.Info); switch (e.Update.Type) { @@ -75,7 +75,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) } catch (Exception ex) { - Log($"General error while processing incoming update: {ex}", "BOT", LogLevel.ERROR); + Log($"General error while processing incoming update: {ex}", "BOT", LogLevel.Error); if (Vars.CurrentConf.CatchAllExceptions) { try @@ -88,7 +88,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) } catch (Exception iEx) { - Log($"Failed to catch exception to owner: {iEx}", "BOT", LogLevel.ERROR); + Log($"Failed to catch exception to owner: {iEx}", "BOT", LogLevel.Error); } } } diff --git a/pmcenter/BotProcess/CommandRouter.cs b/pmcenter/BotProcess/CommandRouter.cs index cdcf9dd..706857b 100644 --- a/pmcenter/BotProcess/CommandRouter.cs +++ b/pmcenter/BotProcess/CommandRouter.cs @@ -48,8 +48,8 @@ public void RegisterCommand(ICommand command) /// processed by one command public async Task Execute(TelegramBotClient botClient, Update update) { - if (update.Message.Type != MessageType.Text) { return false; } - if (!update.Message.Text.StartsWith(globalPrefix)) { return false; } + if (update.Message.Type != MessageType.Text) return false; + if (!update.Message.Text.StartsWith(globalPrefix)) return false; var command = commands.FirstOrDefault(cmd => { diff --git a/pmcenter/CallbackActions/CallbackProcess.cs b/pmcenter/CallbackActions/CallbackProcess.cs index b3494bf..f4117bf 100644 --- a/pmcenter/CallbackActions/CallbackProcess.cs +++ b/pmcenter/CallbackActions/CallbackProcess.cs @@ -32,12 +32,12 @@ public static async Task DoCallback(string actionName, Use { var result = await callbackManager.Execute(actionName, user, msg); if (result == null) - Log($"Callback {actionName} from user {user.Id} cannot be found.", "BOT", LogLevel.WARN); + Log($"Callback {actionName} from user {user.Id} cannot be found.", "BOT", LogLevel.Warning); return new CallbackActionResult(result, result != null); } catch (Exception ex) { - Log($"Callback {actionName} could not be executed: {ex}", "BOT", LogLevel.ERROR); + Log($"Callback {actionName} could not be executed: {ex}", "BOT", LogLevel.Error); return new CallbackActionResult(Vars.CurrentLang.Message_Action_Error, false); } } diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLineRouter.cs index cf5a575..302502b 100644 --- a/pmcenter/CommandLineRouter.cs +++ b/pmcenter/CommandLineRouter.cs @@ -57,7 +57,7 @@ public async Task Execute(string cmdLine) } catch (Exception ex) { - Log($"Exception while executing commandline: {ex}", "CMD", LogLevel.ERROR); + Log($"Exception while executing commandline: {ex}", "CMD", LogLevel.Error); Environment.Exit(1); } Log("Command finished.", "CMD"); diff --git a/pmcenter/CommandLines/BackupCmdLine.cs b/pmcenter/CommandLines/BackupCmdLine.cs index 22333b7..5ff89e3 100644 --- a/pmcenter/CommandLines/BackupCmdLine.cs +++ b/pmcenter/CommandLines/BackupCmdLine.cs @@ -13,10 +13,10 @@ internal class BackupCmdLine : ICmdLine public Task Process() { Log("Backing up...", "CMD"); - var RandomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; - RandomFilename = Path.Combine(Vars.AppDirectory, RandomFilename); - File.Copy(Vars.ConfFile, RandomFilename); - Log($"Backup complete. Filename: {RandomFilename}", "CMD"); + var randomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; + randomFilename = Path.Combine(Vars.AppDirectory, randomFilename); + File.Copy(Vars.ConfFile, randomFilename); + Log($"Backup complete. Filename: {randomFilename}", "CMD"); return Task.FromResult(true); } } diff --git a/pmcenter/CommandLines/InfoCmdLine.cs b/pmcenter/CommandLines/InfoCmdLine.cs index efee1b9..25fa45f 100644 --- a/pmcenter/CommandLines/InfoCmdLine.cs +++ b/pmcenter/CommandLines/InfoCmdLine.cs @@ -13,18 +13,18 @@ internal class InfoCmdLine : ICmdLine public async Task Process() { Log("Gathering application information... This may take a while for there's some network activities.", "CMD"); - var IsTelegramAPIAccessible = await TestConnectivity("https://api.telegram.org/bot/", true).ConfigureAwait(false); - var IsGitHubAccessible = await TestConnectivity("https://raw.githubusercontent.com/", true).ConfigureAwait(false); - var IsCIAvailable = await TestConnectivity("https://ci.appveyor.com/", true).ConfigureAwait(false); + var isTelegramApiAccessible = await TestConnectivity("https://api.telegram.org/bot/", true).ConfigureAwait(false); + var isGitHubAccessible = await TestConnectivity("https://raw.githubusercontent.com/", true).ConfigureAwait(false); + var isCiAvailable = await TestConnectivity("https://ci.appveyor.com/", true).ConfigureAwait(false); Log("Application information", "CMD"); Log($"CLR version: {Environment.Version}", "CMD"); Log($"Framework description: {RuntimeInformation.FrameworkDescription}", "CMD"); Log($"Application version: {Vars.AppVer}", "CMD"); Log($"Configurations filename: {Vars.ConfFile}", "CMD"); Log($"Language filename: {Vars.LangFile}", "CMD"); - Log($"Is Telegram API accessible? {(IsTelegramAPIAccessible ? "yes" : "no")}", "CMD"); - Log($"Is GitHub accessible? {(IsGitHubAccessible ? "yes" : "no")}", "CMD"); - Log($"Is CI accessible? {(IsCIAvailable ? "yes" : "no")}", "CMD"); + Log($"Is Telegram API accessible? {(isTelegramApiAccessible ? "yes" : "no")}", "CMD"); + Log($"Is GitHub accessible? {(isGitHubAccessible ? "yes" : "no")}", "CMD"); + Log($"Is CI accessible? {(isCiAvailable ? "yes" : "no")}", "CMD"); return true; } diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index 5317ba3..8c9c284 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -13,18 +13,18 @@ public async Task Process() Log($"Application version: {Vars.AppVer}", "CMD"); Log("Checking for updates...", "CMD"); Log("Custom update channels and languages are currently unsupported in command line mode, will use \"master\" channel with English.", "CMD"); - var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); - if (IsNewerVersionAvailable(Latest)) + var latest = await CheckForUpdatesAsync().ConfigureAwait(false); + if (IsNewerVersionAvailable(latest)) { - Log($"Newer version found: {Latest.Latest}, main changes:\n{Latest.UpdateCollection[0].Details}", "CMD"); + Log($"Newer version found: {latest.Latest}, main changes:\n{latest.UpdateCollection[0].Details}", "CMD"); Log("Updating...", "CMD"); - await DownloadUpdatesAsync(Latest).ConfigureAwait(false); + await DownloadUpdatesAsync(latest).ConfigureAwait(false); await DownloadLangAsync().ConfigureAwait(false); Log("Update complete.", "CMD"); } else { - Log($"No newer version found.\nCurrently installed version: {Vars.AppVer}\nThe latest version is: {Latest.Latest}", "CMD"); + Log($"No newer version found.\nCurrently installed version: {Vars.AppVer}\nThe latest version is: {latest.Latest}", "CMD"); } return true; } diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index c11ed29..317901b 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -5,10 +5,10 @@ namespace pmcenter { public static partial class Conf { - public static async Task GetConf(string Filename) + public static async Task GetConf(string filename) { - var SettingsText = await System.IO.File.ReadAllTextAsync(Filename).ConfigureAwait(false); - return JsonConvert.DeserializeObject(SettingsText); + var settingsText = await System.IO.File.ReadAllTextAsync(filename).ConfigureAwait(false); + return JsonConvert.DeserializeObject(settingsText); } } } diff --git a/pmcenter/Configurations/Conf.InitConf.cs b/pmcenter/Configurations/Conf.InitConf.cs index a92ff88..82d4cad 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -11,7 +11,7 @@ public static async Task InitConf() Log("Checking configurations file's integrity...", "CONF"); if (!System.IO.File.Exists(Vars.ConfFile)) { // STEP 1, DETECT EXISTENCE. - Log("Configurations file not found. Creating...", "CONF", LogLevel.WARN); + Log("Configurations file not found. Creating...", "CONF", LogLevel.Warning); Vars.CurrentConf = new ConfObj(); _ = await SaveConf(true).ConfigureAwait(false); // Then the app will exit, do nothing. } @@ -23,8 +23,8 @@ public static async Task InitConf() } catch (Exception ex) { - Log($"Error! {ex}", "CONF", LogLevel.ERROR); - Log("Moving old configurations file to \"pmcenter.json.bak\"...", "CONF", LogLevel.WARN); + Log($"Error! {ex}", "CONF", LogLevel.Error); + Log("Moving old configurations file to \"pmcenter.json.bak\"...", "CONF", LogLevel.Warning); System.IO.File.Move(Vars.ConfFile, Vars.ConfFile + ".bak"); Vars.CurrentConf = new ConfObj(); _ = await SaveConf(true).ConfigureAwait(false); // Then the app will exit, do nothing. diff --git a/pmcenter/Configurations/Conf.KillIllegalChars.cs b/pmcenter/Configurations/Conf.KillIllegalChars.cs index d85ee34..8c437c4 100644 --- a/pmcenter/Configurations/Conf.KillIllegalChars.cs +++ b/pmcenter/Configurations/Conf.KillIllegalChars.cs @@ -2,9 +2,9 @@ namespace pmcenter { public static partial class Conf { - public static string KillIllegalChars(string Input) + public static string KillIllegalChars(string input) { - return Input.Replace("/", "-").Replace("<", "-").Replace(">", "-").Replace(":", "-").Replace("\"", "-").Replace("/", "-").Replace("\\", "-").Replace("|", "-").Replace("?", "-").Replace("*", "-"); + return input.Replace("/", "-").Replace("<", "-").Replace(">", "-").Replace(":", "-").Replace("\"", "-").Replace("/", "-").Replace("\\", "-").Replace("|", "-").Replace("?", "-").Replace("*", "-"); } } } diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index c84f6a9..36ab75f 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -6,8 +6,8 @@ public static partial class Conf { public static async Task ReadConf(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. - var Temp = await GetConf(Vars.ConfFile).ConfigureAwait(false); - if (apply) { Vars.CurrentConf = Temp; } + var temp = await GetConf(Vars.ConfFile).ConfigureAwait(false); + if (apply) { Vars.CurrentConf = temp; } return true; } } diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index a3223bb..89ef002 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -8,16 +8,16 @@ public static partial class Conf { public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. - string Text = JsonConvert.SerializeObject(Vars.CurrentConf, Formatting.Indented); - await System.IO.File.WriteAllTextAsync(Vars.ConfFile, Text).ConfigureAwait(false); + string text = JsonConvert.SerializeObject(Vars.CurrentConf, Formatting.Indented); + await System.IO.File.WriteAllTextAsync(Vars.ConfFile, text).ConfigureAwait(false); if (isAutoSave) { Log("Autosave complete.", "CONF"); } if (isInvalid) { - Log("We've detected an invalid configurations file and have reset it.", "CONF", LogLevel.WARN); - Log("Please reconfigure it and try to start pmcenter again.", "CONF", LogLevel.WARN); + Log("We've detected an invalid configurations file and have reset it.", "CONF", LogLevel.Warning); + Log("Please reconfigure it and try to start pmcenter again.", "CONF", LogLevel.Warning); Vars.RestartRequired = true; } return true; diff --git a/pmcenter/Configurations/Lang.InitLang.cs b/pmcenter/Configurations/Lang.InitLang.cs index c742244..8c56fe8 100644 --- a/pmcenter/Configurations/Lang.InitLang.cs +++ b/pmcenter/Configurations/Lang.InitLang.cs @@ -12,7 +12,7 @@ public static async Task InitLang() Log("Checking language file's integrity...", "LANG"); if (!File.Exists(Vars.LangFile)) { // STEP 1, DETECT EXISTENCE. - Log("Language file not found. Creating...", "LANG", LogLevel.WARN); + Log("Language file not found. Creating...", "LANG", LogLevel.Warning); Vars.CurrentLang = new Language(); _ = await SaveLang(true).ConfigureAwait(false); // Then the app will exit, do nothing. } @@ -24,8 +24,8 @@ public static async Task InitLang() } catch (Exception ex) { - Log($"Error! {ex}", "LANG", LogLevel.ERROR); - Log("Moving old language file to \"pmcenter_locale.json.bak\"...", "LANG", LogLevel.WARN); + Log($"Error! {ex}", "LANG", LogLevel.Error); + Log("Moving old language file to \"pmcenter_locale.json.bak\"...", "LANG", LogLevel.Warning); File.Move(Vars.LangFile, Vars.LangFile + ".bak"); Vars.CurrentLang = new Language(); _ = await SaveLang(true).ConfigureAwait(false); // Then the app will exit, do nothing. diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index 2d523cb..5e6fe5a 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -8,9 +8,9 @@ public static partial class Lang { public static async Task ReadLang(bool apply = true) { // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. - var SettingsText = await File.ReadAllTextAsync(Vars.LangFile).ConfigureAwait(false); - var Temp = JsonConvert.DeserializeObject(SettingsText); - if (apply) { Vars.CurrentLang = Temp; } + var langText = await File.ReadAllTextAsync(Vars.LangFile).ConfigureAwait(false); + var temp = JsonConvert.DeserializeObject(langText); + if (apply) { Vars.CurrentLang = temp; } return true; } } diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index 34db746..2f3f474 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -9,15 +9,15 @@ public static partial class Lang { public static async Task SaveLang(bool isInvalid = false) { // DO NOT HANDLE ERRORS HERE. - var Text = JsonConvert.SerializeObject(Vars.CurrentLang, Formatting.Indented); - var Writer = new StreamWriter(File.Create(Vars.LangFile), System.Text.Encoding.UTF8); - await Writer.WriteAsync(Text).ConfigureAwait(false); - await Writer.FlushAsync().ConfigureAwait(false); - Writer.Close(); + var text = JsonConvert.SerializeObject(Vars.CurrentLang, Formatting.Indented); + var writer = new StreamWriter(File.Create(Vars.LangFile), System.Text.Encoding.UTF8); + await writer.WriteAsync(text).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + writer.Close(); if (isInvalid) { - Log("We've detected an invalid language file and have reset it.", "LANG", LogLevel.WARN); - Log("Please reconfigure it and try to start pmcenter again.", "LANG", LogLevel.WARN); + Log("We've detected an invalid language file and have reset it.", "LANG", LogLevel.Warning); + Log("Please reconfigure it and try to start pmcenter again.", "LANG", LogLevel.Warning); Vars.RestartRequired = true; } return true; diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index b412afc..f079ea7 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -11,18 +11,18 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) Vars.CtrlCCounter++; if (Vars.CtrlCCounter > 3) { - Log("More than 3 interrupts has received, terminating...", LogLevel.WARN); + Log("More than 3 interrupts has received, terminating...", LogLevel.Warning); Environment.Exit(137); } if (Vars.IsCtrlCHandled) return; if (Vars.CurrentConf.IgnoreKeyboardInterrupt) { - Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", LogLevel.WARN); + Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", LogLevel.Warning); if (e != null) e.Cancel = true; return; } Vars.IsCtrlCHandled = true; - Log("Interrupt! pmcenter is exiting...", LogLevel.WARN); + Log("Interrupt! pmcenter is exiting...", LogLevel.Warning); Log("If pmcenter was unresponsive, press Ctrl-C 3 more times."); ExitApp(130); } diff --git a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs index faf2101..fc59a82 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs @@ -4,11 +4,11 @@ namespace pmcenter { public static partial class Methods { - public static BanObj GetBanObjByID(long UID) + public static BanObj GetBanObjByID(long uid) { - foreach (BanObj Banned in Vars.CurrentConf.Banned) + foreach (var banned in Vars.CurrentConf.Banned) { - if (Banned.UID == UID) { return Banned; } + if (banned.UID == uid) return banned; } return null; } diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs index 8ea5991..35920c2 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs @@ -4,13 +4,13 @@ namespace pmcenter { public static partial class Methods { - public static MessageIDLink GetLinkByOwnerMsgID(long OwnerSessionMsgID) + public static MessageIDLink GetLinkByOwnerMsgID(long ownerSessionMsgId) { lock (Vars.CurrentConf.MessageLinks) { - foreach (MessageIDLink Link in Vars.CurrentConf.MessageLinks) + foreach (var link in Vars.CurrentConf.MessageLinks) { - if (Link.OwnerSessionMessageID == OwnerSessionMsgID) { return Link; } + if (link.OwnerSessionMessageID == ownerSessionMsgId) return link; } } return null; diff --git a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs index abedfd8..2ede789 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs @@ -4,13 +4,13 @@ namespace pmcenter { public static partial class Methods { - public static MessageIDLink GetLinkByUserMsgID(long UserSessionMsgID) + public static MessageIDLink GetLinkByUserMsgID(long userSessionMsgId) { lock (Vars.CurrentConf.MessageLinks) { - foreach (MessageIDLink Link in Vars.CurrentConf.MessageLinks) + foreach (var link in Vars.CurrentConf.MessageLinks) { - if (Link.UserSessionMessageID == UserSessionMsgID) { return Link; } + if (link.UserSessionMessageID == userSessionMsgId) { return link; } } } return null; diff --git a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs index aa48f53..df73e1d 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -4,11 +4,11 @@ namespace pmcenter { public static partial class Methods { - public static int GetRateDataIndexByID(long UID) + public static int GetRateDataIndexByID(long uid) { - foreach (RateData Data in Vars.RateLimits) + foreach (var data in Vars.RateLimits) { - if (Data.UID == UID) { return Vars.RateLimits.IndexOf(Data); } + if (data.UID == uid) { return Vars.RateLimits.IndexOf(data); } } return -1; } diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index 0b86e25..2df238a 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -6,11 +6,11 @@ namespace pmcenter { public static partial class Methods { - public static bool IsBanned(long UID) + public static bool IsBanned(long uid) { - foreach (BanObj Banned in Vars.CurrentConf.Banned) + foreach (var banned in Vars.CurrentConf.Banned) { - if (Banned.UID == UID) { return true; } + if (banned.UID == uid) return true; } return false; } diff --git a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs index 0e5de79..1088b10 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs @@ -2,19 +2,19 @@ namespace pmcenter { public static partial class Methods { - public static bool IsKeywordBanned(string Sentence) + public static bool IsKeywordBanned(string sentence) { - if (!Vars.CurrentConf.KeywordBanning) { return false; } + if (!Vars.CurrentConf.KeywordBanning) return false; - foreach (string Blocked in Vars.CurrentConf.BannedKeywords) + foreach (var blocked in Vars.CurrentConf.BannedKeywords) { if (Vars.CurrentConf.EnableRegex) { - if (IsRegexMatch(Sentence, Blocked)) { return true; } + if (IsRegexMatch(sentence, blocked)) return true; } else { - if (Sentence.Contains(Blocked)) { return true; } + if (sentence.Contains(blocked)) return true; } } return false; diff --git a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs index 2107a2a..6cdaef3 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -4,14 +4,14 @@ namespace pmcenter { public static partial class Methods { - public static bool IsOwnerRetractionAvailable(int OwnerSessionMsgID) + public static bool IsOwnerRetractionAvailable(int ownerSessionMsgId) { - if (!Vars.CurrentConf.EnableMsgLink) { return false; } + if (!Vars.CurrentConf.EnableMsgLink) return false; lock (Vars.CurrentConf.MessageLinks) { - foreach (MessageIDLink Link in Vars.CurrentConf.MessageLinks) + foreach (var link in Vars.CurrentConf.MessageLinks) { - if (Link.OwnerSessionMessageID == OwnerSessionMsgID) { return true; } + if (link.OwnerSessionMessageID == ownerSessionMsgId) return true; } } return false; diff --git a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs index 5db21d8..c66faf5 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -4,11 +4,11 @@ namespace pmcenter { public static partial class Methods { - public static bool IsRateDataTracking(long UID) + public static bool IsRateDataTracking(long uid) { - foreach (RateData Data in Vars.RateLimits) + foreach (var data in Vars.RateLimits) { - if (Data.UID == UID) { return true; } + if (data.UID == uid) return true; } return false; } diff --git a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs index a919c5b..bc9b2d3 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs @@ -4,14 +4,14 @@ namespace pmcenter { public static partial class Methods { - public static bool IsUserRetractionAvailable(int UserSessionMsgID) + public static bool IsUserRetractionAvailable(int userSessionMsgId) { - if (!Vars.CurrentConf.EnableMsgLink) { return false; } + if (!Vars.CurrentConf.EnableMsgLink) return false; lock (Vars.CurrentConf.MessageLinks) { - foreach (MessageIDLink Link in Vars.CurrentConf.MessageLinks) + foreach (var link in Vars.CurrentConf.MessageLinks) { - if (Link.UserSessionMessageID == UserSessionMsgID) { return true; } + if (link.UserSessionMessageID == userSessionMsgId) return true; } } return false; diff --git a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs index e691a8e..79d03c6 100644 --- a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs +++ b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs @@ -4,21 +4,21 @@ namespace pmcenter { public static partial class Methods { - public static void AddRateLimit(long UID) + public static void AddRateLimit(long uid) { - if (IsRateDataTracking(UID)) + if (IsRateDataTracking(uid)) { - var DataID = GetRateDataIndexByID(UID); - Vars.RateLimits[DataID].MessageCount += 1; + var dataId = GetRateDataIndexByID(uid); + Vars.RateLimits[dataId].MessageCount += 1; } else { - var Data = new RateData + var data = new RateData { - UID = UID, + UID = uid, MessageCount = 1 }; - Vars.RateLimits.Add(Data); + Vars.RateLimits.Add(data); } } } diff --git a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs index c3322d5..f940d90 100644 --- a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs @@ -4,15 +4,15 @@ namespace pmcenter { public static partial class Methods { - public static void BanUser(long UID) + public static void BanUser(long uid) { - if (!IsBanned(UID)) + if (!IsBanned(uid)) { - var Banned = new BanObj + var banned = new BanObj { - UID = UID + UID = uid }; - Vars.CurrentConf.Banned.Add(Banned); + Vars.CurrentConf.Banned.Add(banned); } } } diff --git a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs index 403a376..7db6bbd 100644 --- a/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.UnbanUser.cs @@ -2,11 +2,11 @@ namespace pmcenter { public static partial class Methods { - public static void UnbanUser(long UID) + public static void UnbanUser(long uid) { - if (IsBanned(UID)) + if (IsBanned(uid)) { - _ = Vars.CurrentConf.Banned.Remove(GetBanObjByID(UID)); + _ = Vars.CurrentConf.Banned.Remove(GetBanObjByID(uid)); } } } diff --git a/pmcenter/Methods/Logging/Methods.Log.cs b/pmcenter/Methods/Logging/Methods.Log.cs index 854305e..7204aa5 100644 --- a/pmcenter/Methods/Logging/Methods.Log.cs +++ b/pmcenter/Methods/Logging/Methods.Log.cs @@ -15,7 +15,7 @@ public static void Log(string text, LogLevel type) } public static void Log(string text, string module = "CORE", - LogLevel type = LogLevel.INFO, + LogLevel type = LogLevel.Info, [CallerFilePath] string filePath = "file?", [CallerMemberName] string callerName = "method?", [CallerLineNumber] int lineNumber = 0) @@ -23,15 +23,15 @@ public static void Log(string text, if (Vars.CurrentConf?.LowPerformanceMode == true) return; var file = $"/{(Path.GetFileName((Environment.OSVersion.Platform == PlatformID.Unix) ? filePath.Replace(@"\", "/") : filePath))}/{callerName}()@L{lineNumber}"; - var Output = Vars.CurrentConf?.DisableTimeDisplay != true + var output = Vars.CurrentConf?.DisableTimeDisplay != true ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" : ""; - Output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; - Output += LogTable[type].Prefix; - Output += text; + output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; + output += LogTable[type].Prefix; + output += text; Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = LogTable[type].Color; - LogTable[type].Func(Output); + LogTable[type].Func(output); Console.ForegroundColor = ConsoleColor.White; } } diff --git a/pmcenter/Methods/Logging/Methods.LogLevel.cs b/pmcenter/Methods/Logging/Methods.LogLevel.cs index 12faff5..35ec806 100644 --- a/pmcenter/Methods/Logging/Methods.LogLevel.cs +++ b/pmcenter/Methods/Logging/Methods.LogLevel.cs @@ -6,9 +6,9 @@ public static partial class Logging { public enum LogLevel { - INFO = 0, - WARN = 1, - ERROR = 2, + Info = 0, + Warning = 1, + Error = 2, } } } diff --git a/pmcenter/Methods/Logging/Methods.LogTable.cs b/pmcenter/Methods/Logging/Methods.LogTable.cs index 2ea020c..52ab9f2 100644 --- a/pmcenter/Methods/Logging/Methods.LogTable.cs +++ b/pmcenter/Methods/Logging/Methods.LogTable.cs @@ -9,9 +9,9 @@ public static partial class Logging { public static Dictionary LogTable = new Dictionary() { - {LogLevel.INFO, new LogMode() {Color = ConsoleColor.White, Prefix = "[INFO] ", Func = Console.WriteLine}}, - {LogLevel.WARN, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, - {LogLevel.ERROR, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} + {LogLevel.Info, new LogMode() {Color = ConsoleColor.White, Prefix = "[INFO] ", Func = Console.WriteLine}}, + {LogLevel.Warning, new LogMode() {Color = ConsoleColor.Yellow, Prefix = "[WARN] ", Func = Console.WriteLine}}, + {LogLevel.Error, new LogMode() {Color = ConsoleColor.Red, Prefix = "[ERROR] ", Func = Console.Error.WriteLine}} }; } } diff --git a/pmcenter/Methods/Methods.BoolStr.cs b/pmcenter/Methods/Methods.BoolStr.cs index 8ac1f1f..fbf0b95 100644 --- a/pmcenter/Methods/Methods.BoolStr.cs +++ b/pmcenter/Methods/Methods.BoolStr.cs @@ -2,9 +2,9 @@ namespace pmcenter { public static partial class Methods { - public static string BoolStr(bool Input) + public static string BoolStr(bool input) { - return Input ? "true" : "false"; + return input ? "true" : "false"; } } } diff --git a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index ff5c599..5623d50 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -9,9 +9,9 @@ public static bool CheckNetCoreVersion(Version version) { if (version.Major != 3 || version.Minor != 1) { - Log("pmcenter v2 or up wouldn't run on devices without .NET Core 3.1 (runtime) installed.", LogLevel.WARN); - Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version}.", LogLevel.WARN); - Log("Consider updating your .NET Core runtime in order to run pmcenter v2 and receive further updates.", LogLevel.WARN); + Log("pmcenter v2 or up wouldn't run on devices without .NET Core 3.1 (runtime) installed.", LogLevel.Warning); + Log($"pmcenter has detected that the latest version installed on your device is .NET Core runtime {version}.", LogLevel.Warning); + Log("Consider updating your .NET Core runtime in order to run pmcenter v2 and receive further updates.", LogLevel.Warning); return false; } return true; diff --git a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs index a5e4037..5b5f8f0 100644 --- a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs +++ b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs @@ -18,7 +18,7 @@ public static void CheckOpenSSLComp(Exception ex) { if (ex.InnerException?.InnerException?.GetType() == typeof(TypeInitializationException)) { - Log("\n\n[!] pmcenter has detected a known issue.\n\nIt appears that your version of .NET Core runtime is incompatible with OpenSSL 1.1+ and therefore pmcenter will not be able to make TLS connections to necessary servers.\n\nTo learn more, open:\nhttps://github.com/Elepover/pmcenter#openssl-compatibility-problem\n\npmcenter will now quit.", "CORE", LogLevel.ERROR); + Log("\n\n[!] pmcenter has detected a known issue.\n\nIt appears that your version of .NET Core runtime is incompatible with OpenSSL 1.1+ and therefore pmcenter will not be able to make TLS connections to necessary servers.\n\nTo learn more, open:\nhttps://github.com/Elepover/pmcenter#openssl-compatibility-problem\n\npmcenter will now quit.", "CORE", LogLevel.Error); Environment.Exit(1); } } diff --git a/pmcenter/Methods/Methods.FlipBool.cs b/pmcenter/Methods/Methods.FlipBool.cs index 640ffac..cc07831 100644 --- a/pmcenter/Methods/Methods.FlipBool.cs +++ b/pmcenter/Methods/Methods.FlipBool.cs @@ -2,9 +2,9 @@ namespace pmcenter { public static partial class Methods { - public static bool FlipBool(bool Input) + public static bool FlipBool(bool input) { - return Input ? false : true; + return input ? false : true; } } } diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index 9f2d6cb..a4231c6 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -37,7 +37,7 @@ public static Version GetNetCoreVersion() } catch (Exception ex) { - Log($"pmcenter is unable to detect your .NET Core installation: {ex.Message}, you need to have .NET Core 3.1 (runtime) installed in order to run pmcenter v2 or up.", LogLevel.WARN); + Log($"pmcenter is unable to detect your .NET Core installation: {ex.Message}, you need to have .NET Core 3.1 (runtime) installed in order to run pmcenter v2 or up.", LogLevel.Warning); return new Version("0.0.0.0"); } } diff --git a/pmcenter/Methods/Methods.GetRandomString.cs b/pmcenter/Methods/Methods.GetRandomString.cs index c92dcdd..d1cf971 100644 --- a/pmcenter/Methods/Methods.GetRandomString.cs +++ b/pmcenter/Methods/Methods.GetRandomString.cs @@ -7,8 +7,8 @@ public static partial class Methods { public static string GetRandomString(int length = 8) { - const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - return new string(Enumerable.Repeat(Chars, length).Select(s => s[(new Random()).Next(s.Length)]).ToArray()); + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + return new string(Enumerable.Repeat(chars, length).Select(s => s[(new Random()).Next(s.Length)]).ToArray()); } } } diff --git a/pmcenter/Methods/Methods.GetThreadStatus.cs b/pmcenter/Methods/Methods.GetThreadStatus.cs index 16bdbb1..c1473d0 100644 --- a/pmcenter/Methods/Methods.GetThreadStatus.cs +++ b/pmcenter/Methods/Methods.GetThreadStatus.cs @@ -4,11 +4,11 @@ namespace pmcenter { public static partial class Methods { - public static ThreadStatus GetThreadStatus(Thread Thread) + public static ThreadStatus GetThreadStatus(Thread thread) { try { - return Thread.IsAlive ? ThreadStatus.Standby : ThreadStatus.Stopped; + return thread.IsAlive ? ThreadStatus.Standby : ThreadStatus.Stopped; } catch { diff --git a/pmcenter/Methods/Methods.GetThreadStatusString.cs b/pmcenter/Methods/Methods.GetThreadStatusString.cs index d992c28..55b36c6 100644 --- a/pmcenter/Methods/Methods.GetThreadStatusString.cs +++ b/pmcenter/Methods/Methods.GetThreadStatusString.cs @@ -2,9 +2,9 @@ namespace pmcenter { public static partial class Methods { - public static string GetThreadStatusString(ThreadStatus Status) + public static string GetThreadStatusString(ThreadStatus status) { - return Status switch + return status switch { ThreadStatus.Working => Vars.CurrentLang.Message_ThreadStatus_Working, ThreadStatus.Standby => Vars.CurrentLang.Message_ThreadStatus_Standby, diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index 461e372..846daa8 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -4,16 +4,16 @@ namespace pmcenter { public static partial class Methods { - public static string GetUpdateLevel(UpdateLevel Level) + public static string GetUpdateLevel(UpdateLevel level) { - string Processed = Vars.CurrentLang.Message_SysStatus_UpdateLevel_Template; - return Level switch + string processed = Vars.CurrentLang.Message_SysStatus_UpdateLevel_Template; + return level switch { - UpdateLevel.Optional => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Optional), - UpdateLevel.Recommended => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Recommended), - UpdateLevel.Important => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Important), - UpdateLevel.Urgent => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Urgent), - _ => Processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Unknown), + UpdateLevel.Optional => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Optional), + UpdateLevel.Recommended => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Recommended), + UpdateLevel.Important => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Important), + UpdateLevel.Urgent => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Urgent), + _ => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Unknown), }; } } diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index 20d189d..28b4160 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -10,18 +10,12 @@ public static bool IsRegexMatch(string source, string expression) { try { - if (Regex.IsMatch(source, expression, RegexOptions.None)) - { - return true; - } - else - { - return false; - } + if (Regex.IsMatch(source, expression, RegexOptions.None)) return true; + return false; } catch (Exception ex) { - Log($"Regex match failed: {ex.Message}, did you use a wrong regex?", "BOT", LogLevel.ERROR); + Log($"Regex match failed: {ex.Message}, did you use a wrong regex?", "BOT", LogLevel.Error); return false; } } diff --git a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs index 1bf24cb..82b82d6 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs @@ -19,7 +19,7 @@ public static async Task TestConnectivity(string target, bool ignore45 = f } catch (WebException ex) { - if (ex.Status == WebExceptionStatus.ProtocolError && ignore45) { return true; } + if (ex.Status == WebExceptionStatus.ProtocolError && ignore45) return true; Log($"Connectivity to {target} is unavailable: {ex.Message}"); return false; } diff --git a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs index cafbcf5..2aae84a 100644 --- a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs +++ b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs @@ -7,7 +7,7 @@ public static partial class Methods public static void ThrDoResetConfCount() { Vars.ConfResetTimerStatus = ThreadStatus.Working; - if (Vars.IsResetConfAvailable) { return; } + if (Vars.IsResetConfAvailable) return; Vars.IsResetConfAvailable = true; Thread.Sleep(30000); Vars.IsResetConfAvailable = false; diff --git a/pmcenter/Methods/Threads/Methods.ThrPerform.cs b/pmcenter/Methods/Threads/Methods.ThrPerform.cs index 8d2e9aa..a8f2a1b 100644 --- a/pmcenter/Methods/Threads/Methods.ThrPerform.cs +++ b/pmcenter/Methods/Threads/Methods.ThrPerform.cs @@ -4,7 +4,7 @@ public static partial class Methods { public static void ThrPerform() { - if (Vars.IsPerformanceTestExecuting) { return; } + if (Vars.IsPerformanceTestExecuting) return; Vars.IsPerformanceTestExecuting = true; Vars.PerformanceScore = 0; while (!(Vars.IsPerformanceTestEndRequested || Vars.IsShuttingDown)) diff --git a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs index 98e0dae..f9d27e5 100644 --- a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs +++ b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs @@ -12,15 +12,15 @@ public static async void ThrRateLimiter() while (!Vars.IsShuttingDown) { Vars.RateLimiterStatus = ThreadStatus.Working; - foreach (RateData Data in Vars.RateLimits) + foreach (var data in Vars.RateLimits) { - if (Data.MessageCount > Vars.CurrentConf.AutoBanThreshold && Vars.CurrentConf.AutoBan) + if (data.MessageCount > Vars.CurrentConf.AutoBanThreshold && Vars.CurrentConf.AutoBan) { - BanUser(Data.UID); + BanUser(data.UID); _ = await SaveConf(false, true).ConfigureAwait(false); - Log($"Banning user: {Data.UID}", "RATELIMIT"); + Log($"Banning user: {data.UID}", "RATELIMIT"); } - Data.MessageCount = 0; + data.MessageCount = 0; } Vars.RateLimiterStatus = ThreadStatus.Standby; try { Thread.Sleep(30000); } catch { } diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 4e34fd9..0233cf2 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -17,11 +17,11 @@ public static async void ThrSyncConf() } catch (Exception ex) { - Log($"Failed to write configurations to local disk: {ex.Message}", "CONFSYNC", LogLevel.ERROR); + Log($"Failed to write configurations to local disk: {ex.Message}", "CONFSYNC", LogLevel.Error); } if (Vars.CurrentConf.ConfSyncInterval == 0) { - Log("ConfSync disabled, stopping...", "CONFSYNC", LogLevel.WARN); + Log("ConfSync disabled, stopping...", "CONFSYNC", LogLevel.Warning); return; } try { Thread.Sleep(Vars.CurrentConf.ConfSyncInterval); } catch { } diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index 19f78bd..572b9a0 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -16,24 +16,24 @@ public static async void ThrUpdateChecker() Vars.UpdateCheckerStatus = ThreadStatus.Working; try { - var Latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var CurrentLocalizedIndex = GetUpdateInfoIndexByLocale(Latest, Vars.CurrentLang.LangCode); - var DisNotif = Vars.CurrentConf.DisableNotifications; + var latest = await CheckForUpdatesAsync().ConfigureAwait(false); + var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + var isNotificationDisabled = Vars.CurrentConf.DisableNotifications; // Identical with BotProcess.cs, L206. - if (IsNewerVersionAvailable(Latest)) + if (IsNewerVersionAvailable(latest)) { Vars.UpdatePending = true; - Vars.UpdateVersion = new Version(Latest.Latest); - Vars.UpdateLevel = Latest.UpdateLevel; - var UpdateString = Vars.CurrentLang.Message_UpdateAvailable - .Replace("$1", Latest.Latest) - .Replace("$2", Latest.UpdateCollection[CurrentLocalizedIndex].Details) - .Replace("$3", GetUpdateLevel(Latest.UpdateLevel)); + Vars.UpdateVersion = new Version(latest.Latest); + Vars.UpdateLevel = latest.UpdateLevel; + var updateString = Vars.CurrentLang.Message_UpdateAvailable + .Replace("$1", latest.Latest) + .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) + .Replace("$3", GetUpdateLevel(latest.UpdateLevel)); _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - UpdateString, + updateString, ParseMode.Markdown, false, - DisNotif).ConfigureAwait(false); + isNotificationDisabled).ConfigureAwait(false); return; // Since this thread wouldn't be useful any longer, exit. } else @@ -44,7 +44,7 @@ public static async void ThrUpdateChecker() } catch (Exception ex) { - Log($"Error during update check: {ex}", "UPDATER", LogLevel.ERROR); + Log($"Error during update check: {ex}", "UPDATER", LogLevel.Error); } Vars.UpdateCheckerStatus = ThreadStatus.Standby; try { Thread.Sleep(60000); } catch { } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs index f4a7989..d063559 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -29,12 +29,12 @@ await DownloadFileAsync( Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") ).ConfigureAwait(false); Log("Download complete. Extracting..."); - using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) + using (var zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) { - foreach (ZipArchiveEntry Entry in Zip.Entries) + foreach (var entry in zip.Entries) { - Log($"Extracting: {Path.Combine(Vars.AppDirectory, Entry.FullName)}"); - Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); + Log($"Extracting: {Path.Combine(Vars.AppDirectory, entry.FullName)}"); + entry.ExtractToFile(Path.Combine(Vars.AppDirectory, entry.FullName), true); } } Log("Cleaning up temporary files..."); diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs index 295b0a1..b5925bc 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -8,13 +8,13 @@ public static partial class UpdateHelper { public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) { - List indexes = new List(); + var indexes = new List(); for (int i = 0; i < Update.UpdateCollection.Count; i++) { if (Update.UpdateCollection[i].LangCode.Contains(Locale)) indexes.Add(i); } if (indexes.Count == 0) return 0; - foreach (int i in indexes) + foreach (var i in indexes) { if (Update.UpdateCollection[i].UpdateChannel == Vars.CurrentConf.UpdateChannel) return i; } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index 71175d6..c79f2e1 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -8,9 +8,9 @@ public static partial class UpdateHelper { public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) { - var CurrentVersion = Vars.AppVer; - var CurrentLatest = new Version(CurrentUpdate.Latest); - if (CurrentLatest > CurrentVersion) + var currentVersion = Vars.AppVer; + var currentLatest = new Version(CurrentUpdate.Latest); + if (currentLatest > currentVersion) { return true; } diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index ee9bda7..1488192 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -30,9 +30,9 @@ public static void Main(string[] args) Log($"Starting pmcenter, version {Vars.AppVer}. Channel: \"{Vars.CompileChannel}\"", "DELEGATOR"); if (Vars.GitHubReleases) Log("This image of pmcenter is built for GitHub releases. Will use a different updating mechanism.", "DELEGATOR"); - var MainAsyncTask = MainAsync(args); - MainAsyncTask.Wait(); - Log("Main worker accidentally exited. Stopping...", "DELEGATOR", LogLevel.ERROR); + var mainAsyncTask = MainAsync(args); + mainAsyncTask.Wait(); + Log("Main worker accidentally exited. Stopping...", "DELEGATOR", LogLevel.Error); Environment.Exit(1); } public static async Task MainAsync(string[] args) @@ -54,34 +54,34 @@ public static async Task MainAsync(string[] args) // $pmcenter_lang try { - var ConfByEnviVar = Environment.GetEnvironmentVariable("pmcenter_conf"); - var LangByEnviVar = Environment.GetEnvironmentVariable("pmcenter_lang"); - if (ConfByEnviVar != null) + var confByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_conf"); + var langByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_lang"); + if (confByEnvironmentVar != null) { - if (File.Exists(ConfByEnviVar)) + if (File.Exists(confByEnvironmentVar)) { - Vars.ConfFile = ConfByEnviVar; + Vars.ConfFile = confByEnvironmentVar; } else { - Log($"==> The following file was not found: {ConfByEnviVar}", "CORE", LogLevel.INFO); + Log($"==> The following file was not found: {confByEnvironmentVar}", "CORE", LogLevel.Info); } } - if (LangByEnviVar != null) + if (langByEnvironmentVar != null) { - if (File.Exists(LangByEnviVar)) + if (File.Exists(langByEnvironmentVar)) { - Vars.LangFile = LangByEnviVar; + Vars.LangFile = langByEnvironmentVar; } else { - Log($"==> The following file was not found: {LangByEnviVar}", "CORE", LogLevel.INFO); + Log($"==> The following file was not found: {langByEnvironmentVar}", "CORE", LogLevel.Info); } } } catch (Exception ex) { - Log($"Failed to read environment variables: {ex}", "CORE", LogLevel.WARN); + Log($"Failed to read environment variables: {ex}", "CORE", LogLevel.Warning); } Log($"==> Using configurations file: {Vars.ConfFile}"); @@ -103,8 +103,8 @@ public static async Task MainAsync(string[] args) { Log("This may be the first time that you use the pmcenter bot.", "CORE"); Log("Configuration guide could be found at https://see.wtf/feEJJ", "CORE"); - Log("Received restart requirement from settings system. Exiting...", "CORE", LogLevel.ERROR); - Log("You may need to check your settings and try again.", "CORE", LogLevel.INFO); + Log("Received restart requirement from settings system. Exiting...", "CORE", LogLevel.Error); + Log("You may need to check your settings and try again.", "CORE", LogLevel.Info); Environment.Exit(1); } @@ -147,21 +147,21 @@ public static async Task MainAsync(string[] args) if (Vars.CurrentConf.UseProxy) { Log("Activating SOCKS5 proxy..."); - List ProxyInfoList = new List(); - foreach (Socks5Proxy Info in Vars.CurrentConf.Socks5Proxies) + List proxyInfoList = new List(); + foreach (var proxyInfo in Vars.CurrentConf.Socks5Proxies) { - ProxyInfo ProxyInfo = new ProxyInfo(Info.ServerName, - Info.ServerPort, - Info.Username, - Info.ProxyPass); - ProxyInfoList.Add(ProxyInfo); + ProxyInfo ProxyInfo = new ProxyInfo(proxyInfo.ServerName, + proxyInfo.ServerPort, + proxyInfo.Username, + proxyInfo.ProxyPass); + proxyInfoList.Add(ProxyInfo); } - HttpToSocks5Proxy Proxy = new HttpToSocks5Proxy(ProxyInfoList.ToArray()) + var proxy = new HttpToSocks5Proxy(proxyInfoList.ToArray()) { ResolveHostnamesLocally = Vars.CurrentConf.ResolveHostnamesLocally }; Log("SOCKS5 proxy is enabled."); - Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, Proxy); + Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, proxy); } else { @@ -193,7 +193,7 @@ public static async Task MainAsync(string[] args) } catch (Exception ex) { - Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex}", "BOT", LogLevel.WARN); + Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex}", "BOT", LogLevel.Warning); } try { @@ -211,11 +211,11 @@ public static async Task MainAsync(string[] args) } catch (Exception ex) { - Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.WARN); + Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.Warning); } if (Vars.CurrentLang.TargetVersion != Vars.AppVer.ToString()) { - Log("Language version mismatch detected.", "CORE", LogLevel.WARN); + Log("Language version mismatch detected.", "CORE", LogLevel.Warning); _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_LangVerMismatch .Replace("$1", Vars.CurrentLang.TargetVersion) @@ -226,25 +226,16 @@ public static async Task MainAsync(string[] args) } Log("==> All finished!"); if (Vars.ServiceMode) - { while (true) - { Thread.Sleep(int.MaxValue); - } - } else - { while (true) - { Console.ReadKey(true); - } - } - } catch (Exception ex) { CheckOpenSSLComp(ex); - Log($"Unexpected error during startup: {ex}", "CORE", LogLevel.ERROR); + Log($"Unexpected error during startup: {ex}", "CORE", LogLevel.Error); Environment.Exit(1); } } diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index 1c8004b..9ce520a 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -34,13 +34,13 @@ private static void OnUpdate(object sender, UpdateEventArgs e) } } - private static void Say(string Input) + private static void Say(string input) { - Console.WriteLine(Input); + Console.WriteLine(input); } - private static void SIn(string Input) + private static void SIn(string input) { - Console.Write(Input); + Console.Write(input); } public static async Task SetupWizard() { @@ -71,8 +71,8 @@ public static async Task SetupWizard() Say(" All major configurations have been set!"); Say(""); SIn("=> Save configurations? [Y/n]: "); - string Choice = Console.ReadLine(); - if (Choice.ToLower() != "n") + var choice = Console.ReadLine(); + if (choice.ToLower() != "n") { if (File.Exists(Vars.ConfFile)) { @@ -131,11 +131,11 @@ private static async Task SetAPIKey() Say(""); EnterKey: SIn("=> Enter your API Key: "); - string Key = Console.ReadLine(); - SIn($".. Testing API Key: {Key}..."); + string key = Console.ReadLine(); + SIn($".. Testing API Key: {key}..."); try { - TestBot = new TelegramBotClient(Key); + TestBot = new TelegramBotClient(key); if (!await TestBot.TestApiAsync().ConfigureAwait(false)) { throw (new ArgumentException("API Key is not valid.")); @@ -147,7 +147,7 @@ private static async Task SetAPIKey() Say($" Invalid API Key: {ex.Message}"); goto EnterKey; } - NewConf.APIKey = Key; + NewConf.APIKey = key; Say(" Done!"); } private static async Task SetUID() @@ -158,8 +158,8 @@ private static async Task SetUID() Say(""); EnterUID: SIn("=> Enter your UID, or \"auto\" for automatic setup: "); - string UID = Console.ReadLine(); - if (UID.ToLower() == "auto") + string uid = Console.ReadLine(); + if (uid.ToLower() == "auto") { Say(".. Preparing for automatic UID detection..."); TestBot.OnUpdate += OnUpdate; @@ -179,9 +179,9 @@ private static async Task SetUID() { try { - long NewUID = long.Parse(UID); - SIn($".. Saving UID: {NewUID}..."); - NewConf.OwnerUID = NewUID; + long newUid = long.Parse(uid); + SIn($".. Saving UID: {newUid}..."); + NewConf.OwnerUID = newUid; Say(" Done!"); } catch (Exception ex) From b0bac15e4c7040b9c0de3ce09d034f6cbe580c54 Mon Sep 17 00:00:00 2001 From: Elepover Date: Wed, 15 Apr 2020 10:54:14 +0800 Subject: [PATCH 17/39] yet another refactoring --- pmcenter/BotCommands/RetractCommand.cs | 13 +++++++++---- pmcenter/CallbackActions/BanAction.cs | 6 +----- pmcenter/CallbackActions/ContinuedChatAction.cs | 5 +---- .../CallbackActions/DisableContinuedChatAction.cs | 5 +---- pmcenter/CallbackActions/PardonAction.cs | 6 +----- 5 files changed, 13 insertions(+), 22 deletions(-) diff --git a/pmcenter/BotCommands/RetractCommand.cs b/pmcenter/BotCommands/RetractCommand.cs index 9e64885..0b44faf 100644 --- a/pmcenter/BotCommands/RetractCommand.cs +++ b/pmcenter/BotCommands/RetractCommand.cs @@ -2,6 +2,8 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using static pmcenter.Methods; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { @@ -18,12 +20,14 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) return false; } var selectedMsgId = update.Message.ReplyToMessage.MessageId; + Log($"Retracting message for user {update.Message.From.Id}", "BOT"); if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) { // owner retracting - if (Methods.IsOwnerRetractionAvailable(selectedMsgId)) + if (IsOwnerRetractionAvailable(selectedMsgId)) { - var link = Methods.GetLinkByOwnerMsgID(selectedMsgId); + var link = GetLinkByOwnerMsgID(selectedMsgId); await botClient.DeleteMessageAsync(link.TGUser.Id, link.UserSessionMessageID).ConfigureAwait(false); + Log($"Successfully retracted message from {GetComposedUsername(link.TGUser, true, true)}.", "BOT"); } else { @@ -38,10 +42,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } else // user retracting { - if (Methods.IsUserRetractionAvailable(selectedMsgId)) + if (IsUserRetractionAvailable(selectedMsgId)) { - var link = Methods.GetLinkByUserMsgID(selectedMsgId); + var link = GetLinkByUserMsgID(selectedMsgId); await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionMessageID).ConfigureAwait(false); + Log($"Successfully retracted message from owner.", "BOT"); if (Vars.CurrentConf.EnableActions && link.OwnerSessionActionMessageID != -1) await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionActionMessageID).ConfigureAwait(false); } diff --git a/pmcenter/CallbackActions/BanAction.cs b/pmcenter/CallbackActions/BanAction.cs index b85d628..ecd0c17 100644 --- a/pmcenter/CallbackActions/BanAction.cs +++ b/pmcenter/CallbackActions/BanAction.cs @@ -22,10 +22,6 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_Banned.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) - { - if (IsBanned(update)) return false; - return true; - } + public bool IsAvailable(Update update) => !IsBanned(update); } } diff --git a/pmcenter/CallbackActions/ContinuedChatAction.cs b/pmcenter/CallbackActions/ContinuedChatAction.cs index b42af67..39124a9 100644 --- a/pmcenter/CallbackActions/ContinuedChatAction.cs +++ b/pmcenter/CallbackActions/ContinuedChatAction.cs @@ -22,9 +22,6 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_ContChatEnabled.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) - { - return Vars.CurrentConf.ContChatTarget == -1; - } + public bool IsAvailable(Update update) => Vars.CurrentConf.ContChatTarget == -1; } } diff --git a/pmcenter/CallbackActions/DisableContinuedChatAction.cs b/pmcenter/CallbackActions/DisableContinuedChatAction.cs index 874964d..9c1c8e1 100644 --- a/pmcenter/CallbackActions/DisableContinuedChatAction.cs +++ b/pmcenter/CallbackActions/DisableContinuedChatAction.cs @@ -21,9 +21,6 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_ContChatDisabled; } - public bool IsAvailable(Update update) - { - return Vars.CurrentConf.ContChatTarget != -1; - } + public bool IsAvailable(Update update) => Vars.CurrentConf.ContChatTarget != -1; } } diff --git a/pmcenter/CallbackActions/PardonAction.cs b/pmcenter/CallbackActions/PardonAction.cs index 8a91085..322d483 100644 --- a/pmcenter/CallbackActions/PardonAction.cs +++ b/pmcenter/CallbackActions/PardonAction.cs @@ -22,10 +22,6 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_Pardoned.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) - { - if (IsBanned(update)) return true; - return false; - } + public bool IsAvailable(Update update) => IsBanned(update); } } From 38158c320e41a684383a9b2ef3d263b35d0dd9fb Mon Sep 17 00:00:00 2001 From: Elepover Date: Wed, 15 Apr 2020 10:58:28 +0800 Subject: [PATCH 18/39] change inferface names --- pmcenter/BotCommands/BackupConfCommand.cs | 2 +- pmcenter/BotCommands/BanCommand.cs | 2 +- pmcenter/BotCommands/BanIdCommand.cs | 2 +- pmcenter/BotCommands/CatConfigCommand.cs | 2 +- pmcenter/BotCommands/Chat.cs | 2 +- pmcenter/BotCommands/CheckUpdateCommand.cs | 2 +- pmcenter/BotCommands/ClearMessageLinksCommand.cs | 2 +- pmcenter/BotCommands/DetectPermissionCommand.cs | 2 +- pmcenter/BotCommands/DonateCommand.cs | 2 +- pmcenter/BotCommands/EditConfCommand.cs | 2 +- pmcenter/BotCommands/GetStatsCommand.cs | 2 +- pmcenter/BotCommands/HelpCommand.cs | 2 +- pmcenter/BotCommands/InfoCommand.cs | 2 +- pmcenter/BotCommands/PardonCommand.cs | 2 +- pmcenter/BotCommands/PardonIdCommand.cs | 2 +- pmcenter/BotCommands/PerformCommand.cs | 2 +- pmcenter/BotCommands/PingCommand.cs | 2 +- pmcenter/BotCommands/ReadConfigCommand.cs | 2 +- pmcenter/BotCommands/ResetConfCommand.cs | 2 +- pmcenter/BotCommands/RestartCommand.cs | 2 +- pmcenter/BotCommands/RetractCommand.cs | 2 +- pmcenter/BotCommands/SaveConfigCommand.cs | 2 +- pmcenter/BotCommands/StartCommand.cs | 2 +- pmcenter/BotCommands/StatusCommand.cs | 2 +- pmcenter/BotCommands/StopChat.cs | 2 +- pmcenter/BotCommands/SwitchBwCommand.cs | 2 +- pmcenter/BotCommands/SwitchFwCommand.cs | 2 +- pmcenter/BotCommands/SwitchLangCodeCommand.cs | 2 +- pmcenter/BotCommands/SwitchLangCommand.cs | 2 +- pmcenter/BotCommands/SwitchNotificationCommand.cs | 2 +- pmcenter/BotCommands/TestNetwork.cs | 2 +- pmcenter/BotCommands/UpdateCommand.cs | 2 +- pmcenter/BotCommands/UptimeCommand.cs | 2 +- pmcenter/BotProcess/CommandRouter.cs | 6 +++--- pmcenter/CommandLineRouter.cs | 6 +++--- pmcenter/CommandLines/BackupCmdLine.cs | 2 +- pmcenter/CommandLines/HelpCmdLine.cs | 2 +- pmcenter/CommandLines/InfoCmdLine.cs | 2 +- pmcenter/CommandLines/NonServiceModeCmdLine.cs | 2 +- pmcenter/CommandLines/ResetCmdLine.cs | 2 +- pmcenter/CommandLines/SetupWizardCmdLine.cs | 2 +- pmcenter/CommandLines/UpdateCmdLine.cs | 2 +- pmcenter/Interfaces/{ICommand.cs => IBotCommand.cs} | 2 +- pmcenter/Interfaces/{ICmdLine.cs => ICommandLine.cs} | 2 +- 44 files changed, 48 insertions(+), 48 deletions(-) rename pmcenter/Interfaces/{ICommand.cs => IBotCommand.cs} (92%) rename pmcenter/Interfaces/{ICmdLine.cs => ICommandLine.cs} (91%) diff --git a/pmcenter/BotCommands/BackupConfCommand.cs b/pmcenter/BotCommands/BackupConfCommand.cs index 70e62c9..1faa7f1 100644 --- a/pmcenter/BotCommands/BackupConfCommand.cs +++ b/pmcenter/BotCommands/BackupConfCommand.cs @@ -9,7 +9,7 @@ namespace pmcenter.Commands { - internal class BackupConfCommand : ICommand + internal class BackupConfCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/BanCommand.cs b/pmcenter/BotCommands/BanCommand.cs index 66e1acb..57828df 100644 --- a/pmcenter/BotCommands/BanCommand.cs +++ b/pmcenter/BotCommands/BanCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class BanCommand : ICommand + internal class BanCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/BanIdCommand.cs b/pmcenter/BotCommands/BanIdCommand.cs index 2b3a4e5..61b0b5a 100644 --- a/pmcenter/BotCommands/BanIdCommand.cs +++ b/pmcenter/BotCommands/BanIdCommand.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class BanIdCommand : ICommand + internal class BanIdCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/CatConfigCommand.cs b/pmcenter/BotCommands/CatConfigCommand.cs index 617dce0..5698e67 100644 --- a/pmcenter/BotCommands/CatConfigCommand.cs +++ b/pmcenter/BotCommands/CatConfigCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class CatConfigCommand : ICommand + internal class CatConfigCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/Chat.cs b/pmcenter/BotCommands/Chat.cs index 0fc1895..bca7e8d 100644 --- a/pmcenter/BotCommands/Chat.cs +++ b/pmcenter/BotCommands/Chat.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class ChatCommand : ICommand + internal class ChatCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/CheckUpdateCommand.cs b/pmcenter/BotCommands/CheckUpdateCommand.cs index 9a1c65e..35da615 100644 --- a/pmcenter/BotCommands/CheckUpdateCommand.cs +++ b/pmcenter/BotCommands/CheckUpdateCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class CheckUpdateCommand : ICommand + internal class CheckUpdateCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/ClearMessageLinksCommand.cs b/pmcenter/BotCommands/ClearMessageLinksCommand.cs index 2400b16..d4a363c 100644 --- a/pmcenter/BotCommands/ClearMessageLinksCommand.cs +++ b/pmcenter/BotCommands/ClearMessageLinksCommand.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class ClearMessageLinksCommand : ICommand + internal class ClearMessageLinksCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/DetectPermissionCommand.cs b/pmcenter/BotCommands/DetectPermissionCommand.cs index 4871545..4c64f63 100644 --- a/pmcenter/BotCommands/DetectPermissionCommand.cs +++ b/pmcenter/BotCommands/DetectPermissionCommand.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class DetectPermissionCommand : ICommand + internal class DetectPermissionCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/DonateCommand.cs b/pmcenter/BotCommands/DonateCommand.cs index 84a8445..9fd8022 100644 --- a/pmcenter/BotCommands/DonateCommand.cs +++ b/pmcenter/BotCommands/DonateCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class DonateCommand : ICommand + internal class DonateCommand : IBotCommand { public bool OwnerOnly => false; diff --git a/pmcenter/BotCommands/EditConfCommand.cs b/pmcenter/BotCommands/EditConfCommand.cs index 846a415..80c4ce5 100644 --- a/pmcenter/BotCommands/EditConfCommand.cs +++ b/pmcenter/BotCommands/EditConfCommand.cs @@ -10,7 +10,7 @@ namespace pmcenter.Commands { - internal class EditConfCommand : ICommand + internal class EditConfCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/GetStatsCommand.cs b/pmcenter/BotCommands/GetStatsCommand.cs index 0003558..ddb21af 100644 --- a/pmcenter/BotCommands/GetStatsCommand.cs +++ b/pmcenter/BotCommands/GetStatsCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class GetStatsCommand : ICommand + internal class GetStatsCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/HelpCommand.cs b/pmcenter/BotCommands/HelpCommand.cs index 7371283..37228c7 100644 --- a/pmcenter/BotCommands/HelpCommand.cs +++ b/pmcenter/BotCommands/HelpCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class HelpCommand : ICommand + internal class HelpCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/InfoCommand.cs b/pmcenter/BotCommands/InfoCommand.cs index 4b28c10..f49959c 100644 --- a/pmcenter/BotCommands/InfoCommand.cs +++ b/pmcenter/BotCommands/InfoCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class InfoCommand : ICommand + internal class InfoCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/PardonCommand.cs b/pmcenter/BotCommands/PardonCommand.cs index 93a4a05..0b0d55b 100644 --- a/pmcenter/BotCommands/PardonCommand.cs +++ b/pmcenter/BotCommands/PardonCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class PardonCommand : ICommand + internal class PardonCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/PardonIdCommand.cs b/pmcenter/BotCommands/PardonIdCommand.cs index 52a13d4..c5639d0 100644 --- a/pmcenter/BotCommands/PardonIdCommand.cs +++ b/pmcenter/BotCommands/PardonIdCommand.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class PardonIdCommand : ICommand + internal class PardonIdCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/PerformCommand.cs b/pmcenter/BotCommands/PerformCommand.cs index 086b5c7..bd1fc9a 100644 --- a/pmcenter/BotCommands/PerformCommand.cs +++ b/pmcenter/BotCommands/PerformCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class PerformCommand : ICommand + internal class PerformCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/PingCommand.cs b/pmcenter/BotCommands/PingCommand.cs index 4031c99..e665982 100644 --- a/pmcenter/BotCommands/PingCommand.cs +++ b/pmcenter/BotCommands/PingCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class PingCommand : ICommand + internal class PingCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/ReadConfigCommand.cs b/pmcenter/BotCommands/ReadConfigCommand.cs index a2d1e9d..e7c6977 100644 --- a/pmcenter/BotCommands/ReadConfigCommand.cs +++ b/pmcenter/BotCommands/ReadConfigCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class ReadConfigCommand : ICommand + internal class ReadConfigCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index b0dea67..f48cdf6 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class ResetConfCommand : ICommand + internal class ResetConfCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/RestartCommand.cs b/pmcenter/BotCommands/RestartCommand.cs index 029b59c..3b8793b 100644 --- a/pmcenter/BotCommands/RestartCommand.cs +++ b/pmcenter/BotCommands/RestartCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class RestartCommand : ICommand + internal class RestartCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/RetractCommand.cs b/pmcenter/BotCommands/RetractCommand.cs index 0b44faf..6394dcf 100644 --- a/pmcenter/BotCommands/RetractCommand.cs +++ b/pmcenter/BotCommands/RetractCommand.cs @@ -7,7 +7,7 @@ namespace pmcenter.Commands { - internal class RetractCommand : ICommand + internal class RetractCommand : IBotCommand { public bool OwnerOnly => false; diff --git a/pmcenter/BotCommands/SaveConfigCommand.cs b/pmcenter/BotCommands/SaveConfigCommand.cs index 9277cc3..3e059f5 100644 --- a/pmcenter/BotCommands/SaveConfigCommand.cs +++ b/pmcenter/BotCommands/SaveConfigCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class SaveConfigCommand : ICommand + internal class SaveConfigCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/StartCommand.cs b/pmcenter/BotCommands/StartCommand.cs index 715cbb6..d5ef96f 100644 --- a/pmcenter/BotCommands/StartCommand.cs +++ b/pmcenter/BotCommands/StartCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class StartCommand : ICommand + internal class StartCommand : IBotCommand { public bool OwnerOnly => false; diff --git a/pmcenter/BotCommands/StatusCommand.cs b/pmcenter/BotCommands/StatusCommand.cs index d2e9a89..aa8b3a9 100644 --- a/pmcenter/BotCommands/StatusCommand.cs +++ b/pmcenter/BotCommands/StatusCommand.cs @@ -8,7 +8,7 @@ namespace pmcenter.Commands { - internal class StatusCommand : ICommand + internal class StatusCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/StopChat.cs b/pmcenter/BotCommands/StopChat.cs index b539abf..63b7df6 100644 --- a/pmcenter/BotCommands/StopChat.cs +++ b/pmcenter/BotCommands/StopChat.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class StopChatCommand : ICommand + internal class StopChatCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/SwitchBwCommand.cs b/pmcenter/BotCommands/SwitchBwCommand.cs index 72a61fa..07d8397 100644 --- a/pmcenter/BotCommands/SwitchBwCommand.cs +++ b/pmcenter/BotCommands/SwitchBwCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class SwitchBwCommand : ICommand + internal class SwitchBwCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/SwitchFwCommand.cs b/pmcenter/BotCommands/SwitchFwCommand.cs index a2c3c88..e71254c 100644 --- a/pmcenter/BotCommands/SwitchFwCommand.cs +++ b/pmcenter/BotCommands/SwitchFwCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class SwitchFwCommand : ICommand + internal class SwitchFwCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/SwitchLangCodeCommand.cs b/pmcenter/BotCommands/SwitchLangCodeCommand.cs index 34be983..3814dd2 100644 --- a/pmcenter/BotCommands/SwitchLangCodeCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCodeCommand.cs @@ -9,7 +9,7 @@ namespace pmcenter.Commands { - internal class SwitchLangCodeCommand : ICommand + internal class SwitchLangCodeCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index 9a97a5a..0bd525b 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -8,7 +8,7 @@ namespace pmcenter.Commands { - internal class SwitchLangCommand : ICommand + internal class SwitchLangCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/SwitchNotificationCommand.cs b/pmcenter/BotCommands/SwitchNotificationCommand.cs index d78ebd3..c5b4fc0 100644 --- a/pmcenter/BotCommands/SwitchNotificationCommand.cs +++ b/pmcenter/BotCommands/SwitchNotificationCommand.cs @@ -5,7 +5,7 @@ namespace pmcenter.Commands { - internal class SwitchNotificationCommand : ICommand + internal class SwitchNotificationCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/TestNetwork.cs b/pmcenter/BotCommands/TestNetwork.cs index e4b6d6d..bcd6931 100644 --- a/pmcenter/BotCommands/TestNetwork.cs +++ b/pmcenter/BotCommands/TestNetwork.cs @@ -8,7 +8,7 @@ namespace pmcenter.Commands { - internal class TestNetworkCommand : ICommand + internal class TestNetworkCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index 05d4a3b..e629a99 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -8,7 +8,7 @@ namespace pmcenter.Commands { - internal class UpdateCommand : ICommand + internal class UpdateCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotCommands/UptimeCommand.cs b/pmcenter/BotCommands/UptimeCommand.cs index f4d91d3..9281da0 100644 --- a/pmcenter/BotCommands/UptimeCommand.cs +++ b/pmcenter/BotCommands/UptimeCommand.cs @@ -6,7 +6,7 @@ namespace pmcenter.Commands { - internal class UptimeCommand : ICommand + internal class UptimeCommand : IBotCommand { public bool OwnerOnly => true; diff --git a/pmcenter/BotProcess/CommandRouter.cs b/pmcenter/BotProcess/CommandRouter.cs index 706857b..07800a7 100644 --- a/pmcenter/BotProcess/CommandRouter.cs +++ b/pmcenter/BotProcess/CommandRouter.cs @@ -18,13 +18,13 @@ internal class CommandRouter { private const char globalPrefix = '/'; - private readonly List commands = new List(); + private readonly List commands = new List(); public CommandRouter() { } - public ICommand this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); + public IBotCommand this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); /// /// Add a command to manager. @@ -32,7 +32,7 @@ public CommandRouter() /// /// the command /// - public void RegisterCommand(ICommand command) + public void RegisterCommand(IBotCommand command) { if (commands.Any(x => x.Prefix == command.Prefix)) { throw new ArgumentException($"A command with prefix \"{ command.Prefix }\" already exists.", nameof(command)); } diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLineRouter.cs index 302502b..b0ad819 100644 --- a/pmcenter/CommandLineRouter.cs +++ b/pmcenter/CommandLineRouter.cs @@ -16,13 +16,13 @@ internal class CommandLineRouter { private const string globalPrefix = "--"; - private readonly List commands = new List(); + private readonly List commands = new List(); public CommandLineRouter() { } - public ICmdLine this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); + public ICommandLine this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); /// /// Add a command to manager. @@ -30,7 +30,7 @@ public CommandLineRouter() /// /// the command /// - public void RegisterCommand(ICmdLine command) + public void RegisterCommand(ICommandLine command) { if (commands.Any(x => x.Prefix == command.Prefix)) { throw new ArgumentException($"A commandline with prefix \"{command.Prefix}\" already exists.", nameof(command)); } diff --git a/pmcenter/CommandLines/BackupCmdLine.cs b/pmcenter/CommandLines/BackupCmdLine.cs index 5ff89e3..4918674 100644 --- a/pmcenter/CommandLines/BackupCmdLine.cs +++ b/pmcenter/CommandLines/BackupCmdLine.cs @@ -6,7 +6,7 @@ namespace pmcenter.CommandLines { - internal class BackupCmdLine : ICmdLine + internal class BackupCmdLine : ICommandLine { public string Prefix => "backup"; public bool ExitAfterExecution => true; diff --git a/pmcenter/CommandLines/HelpCmdLine.cs b/pmcenter/CommandLines/HelpCmdLine.cs index 646cf63..747bc1e 100644 --- a/pmcenter/CommandLines/HelpCmdLine.cs +++ b/pmcenter/CommandLines/HelpCmdLine.cs @@ -3,7 +3,7 @@ namespace pmcenter.CommandLines { - internal class HelpCmdLine : ICmdLine + internal class HelpCmdLine : ICommandLine { public string Prefix => "help"; public bool ExitAfterExecution => true; diff --git a/pmcenter/CommandLines/InfoCmdLine.cs b/pmcenter/CommandLines/InfoCmdLine.cs index 25fa45f..09be9ff 100644 --- a/pmcenter/CommandLines/InfoCmdLine.cs +++ b/pmcenter/CommandLines/InfoCmdLine.cs @@ -6,7 +6,7 @@ namespace pmcenter.CommandLines { - internal class InfoCmdLine : ICmdLine + internal class InfoCmdLine : ICommandLine { public string Prefix => "info"; public bool ExitAfterExecution => true; diff --git a/pmcenter/CommandLines/NonServiceModeCmdLine.cs b/pmcenter/CommandLines/NonServiceModeCmdLine.cs index 28add83..66ea314 100644 --- a/pmcenter/CommandLines/NonServiceModeCmdLine.cs +++ b/pmcenter/CommandLines/NonServiceModeCmdLine.cs @@ -3,7 +3,7 @@ namespace pmcenter.CommandLines { - internal class NonServiceModeCmdLine : ICmdLine + internal class NonServiceModeCmdLine : ICommandLine { public string Prefix => "noservice"; public bool ExitAfterExecution => false; diff --git a/pmcenter/CommandLines/ResetCmdLine.cs b/pmcenter/CommandLines/ResetCmdLine.cs index a3fc771..d5873f1 100644 --- a/pmcenter/CommandLines/ResetCmdLine.cs +++ b/pmcenter/CommandLines/ResetCmdLine.cs @@ -3,7 +3,7 @@ namespace pmcenter.CommandLines { - internal class ResetCmdLine : ICmdLine + internal class ResetCmdLine : ICommandLine { public string Prefix => "reset"; public bool ExitAfterExecution => true; diff --git a/pmcenter/CommandLines/SetupWizardCmdLine.cs b/pmcenter/CommandLines/SetupWizardCmdLine.cs index b262bd2..993c13d 100644 --- a/pmcenter/CommandLines/SetupWizardCmdLine.cs +++ b/pmcenter/CommandLines/SetupWizardCmdLine.cs @@ -3,7 +3,7 @@ namespace pmcenter.CommandLines { - internal class SetupWizardCmdLine : ICmdLine + internal class SetupWizardCmdLine : ICommandLine { public string Prefix => "setup"; public bool ExitAfterExecution => true; diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index 8c9c284..7d3d3f4 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -4,7 +4,7 @@ namespace pmcenter.CommandLines { - internal class UpdateCmdLine : ICmdLine + internal class UpdateCmdLine : ICommandLine { public string Prefix => "update"; public bool ExitAfterExecution => true; diff --git a/pmcenter/Interfaces/ICommand.cs b/pmcenter/Interfaces/IBotCommand.cs similarity index 92% rename from pmcenter/Interfaces/ICommand.cs rename to pmcenter/Interfaces/IBotCommand.cs index 8b47096..b58ab18 100644 --- a/pmcenter/Interfaces/ICommand.cs +++ b/pmcenter/Interfaces/IBotCommand.cs @@ -10,7 +10,7 @@ namespace pmcenter { - internal interface ICommand + internal interface IBotCommand { bool OwnerOnly { get; } string Prefix { get; } diff --git a/pmcenter/Interfaces/ICmdLine.cs b/pmcenter/Interfaces/ICommandLine.cs similarity index 91% rename from pmcenter/Interfaces/ICmdLine.cs rename to pmcenter/Interfaces/ICommandLine.cs index d066389..2d54e87 100644 --- a/pmcenter/Interfaces/ICmdLine.cs +++ b/pmcenter/Interfaces/ICommandLine.cs @@ -8,7 +8,7 @@ namespace pmcenter { - internal interface ICmdLine + internal interface ICommandLine { string Prefix { get; } bool ExitAfterExecution { get; } From 04cf2a0010acc181afc457354156beeee40b8a34 Mon Sep 17 00:00:00 2001 From: Elepover Date: Wed, 15 Apr 2020 14:14:26 +0800 Subject: [PATCH 19/39] actions now check for message links, logs can be omitted --- README.md | 1 + README_zh.md | 1 + .../BotProcess/BotProcess.CallbackQueryRoute.cs | 14 +++++++++++--- .../CallbackActions/CallbackActionResult.cs | 4 +++- pmcenter/CallbackActions/CallbackManager.cs | 10 ++++++++-- pmcenter/CallbackActions/CallbackProcess.cs | 16 ++++++++++++++-- pmcenter/Configurations/Conf.ConfObj.New.cs | 1 + pmcenter/Configurations/Conf.ConfObj.cs | 1 + pmcenter/Configurations/Lang.Language.New.cs | 2 ++ pmcenter/Configurations/Lang.Language.cs | 2 ++ pmcenter/Methods/Logging/Methods.Log.cs | 1 + pmcenter/Program.cs | 17 ++++++++++++++++- pmcenter/Vars.cs | 5 +++++ 13 files changed, 66 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index dfa3184..34d8441 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ Or, use setup wizard: | `IgnoreKeyboardInterrupt` | `Boolean` | ✓ | Choose whether pmcenter should ignore Ctrl-C interrupts or not. | | `DisableNetCore3Check` | `Boolean` | ✓ | Turn this on to hide .NET Core Runtime version warnings. | | `Statistics` | `Stats` | ✕ | Statistics data. | +| `IgnoredLogModules` | `Array` | ✓ | List of ignored log modules. Selected modules will not generate output to console. | | `Socks5Proxies` | `Array` | ✓ | List of SOCKS5 proxies. | | `BannedKeywords` | `Array` | ✓ | Storage of banned keywords. | | `Banned` | `Array` | ✓ | Storage of banned users. | diff --git a/README_zh.md b/README_zh.md index 2eb113d..1c9994e 100644 --- a/README_zh.md +++ b/README_zh.md @@ -179,6 +179,7 @@ docker run -d -v $(pwd)/pmcenter.json:/opt/pmcenter/pmcenter.json --restart alwa | `IgnoreKeyboardInterrupt` | `Boolean` | ✓ | 是否忽略 Ctrl-C 中断 | | `DisableNetCore3Check` | `Boolean` | ✓ | 启用以忽略 .NET Core 运行时版本检查 | | `Statistics` | `Stats` | ✕ | 统计数据 | +| `IgnoredLogModules` | `Array` | ✓ | 忽略的日志模块列表,这些模块将不会输出信息到控制台 | | `Socks5Proxies` | `Array` | ✓ | SOCKS5 代理列表 | | `BannedKeywords` | `Array` | ✓ | 屏蔽的关键字存储 | | `Banned` | `Array` | ✓ | 封禁用户存储 | diff --git a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs index 8d2a89c..8a7a2ea 100644 --- a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs +++ b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs @@ -17,9 +17,11 @@ private static async Task CallbackQueryRoute(object sender, UpdateEventArgs e) if (update.CallbackQuery.From.IsBot) return; try { - var result = await CallbackProcess.DoCallback(update.CallbackQuery.Data, GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId).TGUser, update.CallbackQuery.Message); - // prompt - await Vars.Bot.AnswerCallbackQueryAsync(update.CallbackQuery.Id, result.Status); + var link = GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId); + if (link == null) throw new NullReferenceException(Vars.CurrentLang.Message_Action_LinkNotFound); + var result = await CallbackProcess.DoCallback(update.CallbackQuery.Data, link.TGUser, update.CallbackQuery.Message); + // prompt result + await Vars.Bot.AnswerCallbackQueryAsync(update.CallbackQuery.Id, result.Status, result.ShowAsAlert); // update existing buttons if (result.Succeeded) _ = await Vars.Bot.EditMessageReplyMarkupAsync( @@ -30,6 +32,12 @@ private static async Task CallbackQueryRoute(object sender, UpdateEventArgs e) catch (Exception ex) { Log($"Unable to process action {update.CallbackQuery.Data}: {ex}", "BOT", LogLevel.Error); + await Vars.Bot.AnswerCallbackQueryAsync + ( + update.CallbackQuery.Id, + Vars.CurrentLang.Message_Action_ErrorWithDetails.Replace("$1", ex.Message), + true + ); } } } diff --git a/pmcenter/CallbackActions/CallbackActionResult.cs b/pmcenter/CallbackActions/CallbackActionResult.cs index eab1a45..37ab725 100644 --- a/pmcenter/CallbackActions/CallbackActionResult.cs +++ b/pmcenter/CallbackActions/CallbackActionResult.cs @@ -2,12 +2,14 @@ { public class CallbackActionResult { - public CallbackActionResult(string status, bool succeeded = true) + public CallbackActionResult(string status, bool showAsAlert = false, bool succeeded = true) { Status = status; Succeeded = succeeded; + ShowAsAlert = showAsAlert; } public string Status; public bool Succeeded; + public bool ShowAsAlert; } } diff --git a/pmcenter/CallbackActions/CallbackManager.cs b/pmcenter/CallbackActions/CallbackManager.cs index b5de603..2d613f7 100644 --- a/pmcenter/CallbackActions/CallbackManager.cs +++ b/pmcenter/CallbackActions/CallbackManager.cs @@ -41,8 +41,14 @@ public List> GetAvailableButtons(Update update) foreach (var action in callbacks) if (action.IsAvailable(update)) { - var oneLineKeyboard = new List(); - oneLineKeyboard.Add(new InlineKeyboardButton() { CallbackData = action.Name, Text = action.ButtonName }); + var oneLineKeyboard = new List + { + new InlineKeyboardButton() + { + CallbackData = action.Name, + Text = action.ButtonName + } + }; result.Add(oneLineKeyboard); } return result; diff --git a/pmcenter/CallbackActions/CallbackProcess.cs b/pmcenter/CallbackActions/CallbackProcess.cs index f4117bf..932f2ff 100644 --- a/pmcenter/CallbackActions/CallbackProcess.cs +++ b/pmcenter/CallbackActions/CallbackProcess.cs @@ -9,6 +9,7 @@ namespace pmcenter.CallbackActions { public static class CallbackProcess { + private static readonly int callbackOutputThreshold = 50; private static readonly CallbackManager callbackManager = new CallbackManager(); static CallbackProcess() @@ -32,13 +33,24 @@ public static async Task DoCallback(string actionName, Use { var result = await callbackManager.Execute(actionName, user, msg); if (result == null) + { Log($"Callback {actionName} from user {user.Id} cannot be found.", "BOT", LogLevel.Warning); - return new CallbackActionResult(result, result != null); + result = Vars.CurrentLang.Message_Action_Error; + } + var useAlert = result.Length > callbackOutputThreshold; + if (useAlert) + Log($"Callback query result length {result.Length} exceeded limit ({callbackOutputThreshold}), using alert instead.", "BOT"); + return new CallbackActionResult + ( + result, + useAlert, + result != null + ); } catch (Exception ex) { Log($"Callback {actionName} could not be executed: {ex}", "BOT", LogLevel.Error); - return new CallbackActionResult(Vars.CurrentLang.Message_Action_Error, false); + return new CallbackActionResult(Vars.CurrentLang.Message_Action_Error, true, false); } } diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index 9f330b3..3fb44e8 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -43,6 +43,7 @@ public ConfObj() DisableNetCore3Check = false; EnableActions = false; Statistics = new Stats(); + IgnoredLogModules = new List(); Socks5Proxies = new List(); BannedKeywords = new List(); Banned = new List(); diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index db0a1e0..c7101b6 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -41,6 +41,7 @@ public sealed partial class ConfObj public bool DisableNetCore3Check { get; set; } public bool EnableActions { get; set; } public Stats Statistics { get; set; } + public List IgnoredLogModules { get; set; } public List Socks5Proxies { get; set; } public List BannedKeywords { get; set; } public List Banned { get; set; } diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index c9cb453..345eeb6 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -83,11 +83,13 @@ public Language() Message_Action_ContChatEnabled = "✅ You're now chatting with $1!"; Message_Action_ContChatDisabled = "✅ Continued chat disabled!"; Message_Action_Error = "✖ Action failed. Check logs."; + Message_Action_ErrorWithDetails = "✖ Action failed: $1"; Message_Action_ChooseAction = "❓ *What do you want to do with this message?*"; Message_Action_Ban = "✖ Ban the user"; Message_Action_Pardon = "✅ Pardon the user"; Message_Action_Chat = "💬 Enter continued conversation"; Message_Action_StopChat = "💬 Stop continued conversation"; + Message_Action_LinkNotFound = "Cannot find the corresponding message link, did you just clear the message links, or was the message links feature disabled?"; } } } diff --git a/pmcenter/Configurations/Lang.Language.cs b/pmcenter/Configurations/Lang.Language.cs index 9103232..c1091c5 100644 --- a/pmcenter/Configurations/Lang.Language.cs +++ b/pmcenter/Configurations/Lang.Language.cs @@ -81,11 +81,13 @@ public sealed partial class Language public string Message_Action_ContChatEnabled { get; set; } public string Message_Action_ContChatDisabled { get; set; } public string Message_Action_Error { get; set; } + public string Message_Action_ErrorWithDetails { get; set; } public string Message_Action_ChooseAction { get; set; } public string Message_Action_Ban { get; set; } public string Message_Action_Pardon { get; set; } public string Message_Action_Chat { get; set; } public string Message_Action_StopChat { get; set; } + public string Message_Action_LinkNotFound { get; set; } } } } diff --git a/pmcenter/Methods/Logging/Methods.Log.cs b/pmcenter/Methods/Logging/Methods.Log.cs index 7204aa5..9e16b94 100644 --- a/pmcenter/Methods/Logging/Methods.Log.cs +++ b/pmcenter/Methods/Logging/Methods.Log.cs @@ -20,6 +20,7 @@ public static void Log(string text, [CallerMemberName] string callerName = "method?", [CallerLineNumber] int lineNumber = 0) { + if (Vars.CurrentConf?.IgnoredLogModules.Contains(module) == true) return; if (Vars.CurrentConf?.LowPerformanceMode == true) return; var file = $"/{(Path.GetFileName((Environment.OSVersion.Platform == PlatformID.Unix) ? filePath.Replace(@"\", "/") : filePath))}/{callerName}()@L{lineNumber}"; diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index 1488192..bf6bd89 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -20,7 +20,7 @@ namespace pmcenter { - public partial class Program + public sealed partial class Program { public static void Main(string[] args) { @@ -108,6 +108,18 @@ public static async Task MainAsync(string[] args) Environment.Exit(1); } + // check if logs are being omitted + if (Vars.CurrentConf.IgnoredLogModules.Count > 0) + { + var tmp = Console.ForegroundColor; + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine("!!!!!!!!!! SOME LOG ENTRIES ARE HIDDEN ACCORDING TO CURRENT SETTINGS !!!!!!!!!!"); + Console.WriteLine("To revert this, clear the \"IgnoredLogModules\" field in pmcenter.json."); + Console.WriteLine("To disable all log output, turn on \"LowPerformanceMode\"."); + Console.WriteLine("This warning will appear every time pmcenter starts up with \"IgnoredLogModules\" set."); + Console.ForegroundColor = tmp; + } + Log("==> Initializing module - THREADS"); Log("Starting RateLimiter..."); Vars.RateLimiter = new Thread(() => ThrRateLimiter()); @@ -181,6 +193,7 @@ public static async Task MainAsync(string[] args) Log("==> Running post-start operations..."); try { + // prompt startup success if (!Vars.CurrentConf.NoStartupMessage) { _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, @@ -197,6 +210,7 @@ public static async Task MainAsync(string[] args) } try { + // check .net core runtime version var netCoreVersion = GetNetCoreVersion(); if (!CheckNetCoreVersion(netCoreVersion) && !Vars.CurrentConf.DisableNetCore3Check) { @@ -213,6 +227,7 @@ public static async Task MainAsync(string[] args) { Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.Warning); } + // check language mismatch if (Vars.CurrentLang.TargetVersion != Vars.AppVer.ToString()) { Log("Language version mismatch detected.", "CORE", LogLevel.Warning); diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 20b8b61..651897d 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -37,6 +37,11 @@ public static class Vars public readonly static bool GitHubReleases = true; #else public readonly static bool GitHubReleases = false; +#endif +#if SELFCONTAINED + public readonly static bool SelfContained = true; +#else + public readonly static bool SelfContained = false; #endif // public readonly static long AnonymousChannelID = -1001228946795; // public readonly static string AnonymousChannelTitle = "a user"; From 2e1e2cba3d115c98a171ff1d2a888cf73a637dcd Mon Sep 17 00:00:00 2001 From: Elepover Date: Thu, 23 Apr 2020 15:15:14 +0800 Subject: [PATCH 20/39] add startup time analysis, autosave switch and updated other translations --- README.md | 7 ++ README_zh.md | 7 ++ locales/pmcenter_locale_en.json | 20 ++++- locales/pmcenter_locale_zh.json | 18 ++++- locales/pmcenter_locale_zh.meow.json | 18 ++++- locales/pmcenter_locale_zh.tw.json | 18 ++++- pmcenter/BotCommands/AutoSaveCommand.cs | 74 +++++++++++++++++++ .../BotCommands/{Chat.cs => ChatCommand.cs} | 0 .../BotProcess/BotProcess.OwnerReplying.cs | 14 +++- pmcenter/BotProcess/BotProcess.UserLogic.cs | 5 +- pmcenter/BotProcess/BotProcess.cs | 1 + pmcenter/CommandLineProcess.cs | 18 ++--- pmcenter/Configurations/CheckPoint.cs | 13 ++++ pmcenter/Configurations/Conf.ConfObj.New.cs | 3 + pmcenter/Configurations/Conf.ConfObj.cs | 3 + pmcenter/Configurations/Lang.Language.New.cs | 8 +- pmcenter/Configurations/Lang.Language.cs | 4 + pmcenter/Methods/Methods.ExitApp.cs | 2 +- .../Methods/Threads/Methods.ThrSyncConf.cs | 1 + pmcenter/Program.cs | 43 ++++++++++- pmcenter/Vars.cs | 4 +- 21 files changed, 255 insertions(+), 26 deletions(-) create mode 100644 pmcenter/BotCommands/AutoSaveCommand.cs rename pmcenter/BotCommands/{Chat.cs => ChatCommand.cs} (100%) create mode 100644 pmcenter/Configurations/CheckPoint.cs diff --git a/README.md b/README.md index 34d8441..51dde57 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,10 @@ Or, use setup wizard: | `UpdateChannel` | `String` | ✓ | Choose which update channel you prefer to. | | `IgnoreKeyboardInterrupt` | `Boolean` | ✓ | Choose whether pmcenter should ignore Ctrl-C interrupts or not. | | `DisableNetCore3Check` | `Boolean` | ✓ | Turn this on to hide .NET Core Runtime version warnings. | +| `DisableMessageLinkTip` | `Boolean` | ✓ | Turn this on to hide message link tip prompts. | +| `AnalyzeStartupTime` | `Boolean` | ✓ | Turn this on to show detailed analysis of startup time. | +| `SkipAPIKeyVerification` | `Boolean` | ✓ | Turn this on to skip API Key verification on startup. | +| `EnableActions` | `Boolean` | ✓ | Turn this on to enable message actions. | | `Statistics` | `Stats` | ✕ | Statistics data. | | `IgnoredLogModules` | `Array` | ✓ | List of ignored log modules. Selected modules will not generate output to console. | | `Socks5Proxies` | `Array` | ✓ | List of SOCKS5 proxies. | @@ -247,6 +251,7 @@ You can write a `systemd service` to keep it running, even after the host machin | `/backup` | Owner | Backup configurations. | | `/editconf ` | Owner | Manually edit configurations and translations w/ JSON-formatted text. | | `/saveconf` | Owner | Manually save configurations and translations. Useful after upgrades. | +| `/autosave [off/interval]` | Owner | Enable/Disable autosave. Intervals are in milliseconds (1/1000 of a second). | | `/readconf` | Owner | Reload configurations without restarting bot. | | `/resetconf` | Owner | Reset configurations. | | `/uptime` | Owner | Get system uptime info. | @@ -302,6 +307,8 @@ pmcenter is planning to move to .NET Core 3.1, see [issue #25](https://github.co Please enable the `EnableMsgLink` option in pmcenter's configurations file. Only messages forwarded when `EnableMsgLink` option is turned on can be replied. +You can NOT reply to the messages that were forwarded when `EnableMsgLink` option was disabled since their corresponding message links were missing. + For more information, refer to the [configurations](#pmcenter-settings) part. ### Why pmcenter.json is too large? diff --git a/README_zh.md b/README_zh.md index 1c9994e..e9840dc 100644 --- a/README_zh.md +++ b/README_zh.md @@ -178,6 +178,10 @@ docker run -d -v $(pwd)/pmcenter.json:/opt/pmcenter/pmcenter.json --restart alwa | `UpdateChannel` | `String` | ✓ | 选择更新频道 | | `IgnoreKeyboardInterrupt` | `Boolean` | ✓ | 是否忽略 Ctrl-C 中断 | | `DisableNetCore3Check` | `Boolean` | ✓ | 启用以忽略 .NET Core 运行时版本检查 | +| `DisableMessageLinkTip` | `Boolean` | ✓ | 启用以忽略消息链接提示 | +| `AnalyzeStartupTime` | `Boolean` | ✓ | 启用以显示细化的启动时间分析 | +| `SkipAPIKeyVerification` | `Boolean` | ✓ | 启用以跳过启动时的 API 密钥校验 | +| `EnableActions` | `Boolean` | ✓ | 启动以启用消息操作面版 | | `Statistics` | `Stats` | ✕ | 统计数据 | | `IgnoredLogModules` | `Array` | ✓ | 忽略的日志模块列表,这些模块将不会输出信息到控制台 | | `Socks5Proxies` | `Array` | ✓ | SOCKS5 代理列表 | @@ -250,6 +254,7 @@ pmcenter_lang: pmcenter 语言文件路径。 | `/backup` | 所有者 | 备份配置文件 | | `/editconf ` | 所有者 | 手动保存 JSON 格式的配置及翻译 | | `/saveconf` | 所有者 | 手动保存配置及翻译,可用于更新后补齐缺少的配置项 | +| `/autosave [off/时间间隔]` | 所有者 | 启用或停用自动保存,时间间隔单位为毫秒(1/1000 秒) | | `/readconf` | 所有者 | 在不重启机器人的情况下,重新载入配置 | | `/resetconf` | 所有者 | 重置配置文件 | | `/uptime` | 所有者 | 获取系统在线时间信息 | @@ -305,6 +310,8 @@ pmcenter 正在准备转向 .NET Core 3.1,请参考 [issue #25](https://github 请在 pmcenter 设置文件中启用 `EnableMsgLink` 选项。只有在 `EnableMsgLink` 选项启用后的转发的消息可以被回复。 +您无法回复在此选项处于禁用状态时被转发的消息,因为对应的消息链接不存在。 + 如需更多信息,请参见[配置](#pmcenter-设置)部分。 ### 为什么 pmcenter.json 这么大? diff --git a/locales/pmcenter_locale_en.json b/locales/pmcenter_locale_en.json index 5974282..e4b64fd 100644 --- a/locales/pmcenter_locale_en.json +++ b/locales/pmcenter_locale_en.json @@ -7,7 +7,7 @@ "Message_UserStartDefault": "📨 *Hi!* To send anything to my owner, just send it here.\n⚠ To be informed: I'll *automatically* ban flooding users.", "Message_ReplySuccessful": "✅ Successfully replied to user $1!", "Message_ForwardedToOwner": "✅ Your message has been forwarded to my owner!", - "Message_Help": "❓ `pmcenter` *Bot Help*\n/start - Display welcome message.\n/info - Display the message's info.\n/ban - Restrict the user from contacting you.\n/banid - Restrict a user from contacting you with his/her ID.\n/pardon - Pardon the user.\n/pardonid - Pardon a user with his/her ID.\n/ping - Test if the bot is working.\n/switchfw - Pause/Resume message forwarding.\n/switchbw - Enable/Disable keyword banning.\n/switchnf - Enable/Disable notifications.\n/switchlang - Switch language file.\n/switchlangcode [Code] - Switch language with language code.\n/detectperm - Detect permissions.\n/backup - Backup configurations.\n/editconf - Manually edit settings w/ JSON-formatted text.\n/saveconf - Manually save all settings and translations. Especially useful after upgrades.\n/readconf - Reload configurations without restarting bot.\n/resetconf - Reset configurations.\n/uptime - Check system uptime information.\n/update - Check for updates and update bot.\n/chkupdate - Only check for updates.\n/catconf - Get your current configurations.\n/restart - Restart bot.\n/status - Get host device's status information.\n/perform - Run performance test.\n/testnetwork - Test latency to servers used by pmcenter.\n/chat - Enter Continued Conversation mode.\n/stopchat - Leave Continued Conversation mode.\n/retract - Retract a message.\n/clearmessagelinks - Clear message links.\n/getstats - Get statistics data.\n/help - Display this message.\n\nThank you for using `pmcenter`!", + "Message_Help": "❓ `pmcenter` *Bot Help*\n/start - Display welcome message.\n/info - Display the message's info.\n/ban - Restrict the user from contacting you.\n/banid - Restrict a user from contacting you with his/her ID.\n/pardon - Pardon the user.\n/pardonid - Pardon a user with his/her ID.\n/ping - Test if the bot is working.\n/switchfw - Pause/Resume message forwarding.\n/switchbw - Enable/Disable keyword banning.\n/switchnf - Enable/Disable notifications.\n/switchlang - Switch language file.\n/switchlangcode [Code] - Switch language with language code.\n/detectperm - Detect permissions.\n/backup - Backup configurations.\n/editconf - Manually edit settings w/ JSON-formatted text.\n/saveconf - Manually save all settings and translations. Especially useful after upgrades.\n/readconf - Reload configurations without restarting bot.\n/resetconf - Reset configurations.\n/uptime - Check system uptime information.\n/update - Check for updates and update bot.\n/chkupdate - Only check for updates.\n/catconf - Get your current configurations.\n/restart - Restart bot.\n/status - Get host device's status information.\n/perform - Run performance test.\n/testnetwork - Test latency to servers used by pmcenter.\n/chat - Enter Continued Conversation mode.\n/stopchat - Leave Continued Conversation mode.\n/retract - Retract a message.\n/clearmessagelinks - Clear message links.\n/getstats - Get statistics data.\n/autosave [off/interval] - Switch autosave status.\n/help - Display this message.\n\nThank you for using `pmcenter`!", "Message_UserBanned": "🚫 The user has been banned permanently.", "Message_UserPardoned": "✅ You've pardoned the user.", "Message_CommandNotReplying": "😶 Don't talk to me, spend time chatting with those who love you.", @@ -70,5 +70,21 @@ "Message_Retracted": "✅ This message has been retracted.", "Message_MsgLinksCleared": "✅ All message links have been cleared.", "Message_AvailableLang": "ℹ *Available languages*\n\n`$1`", - "Message_NetCore31Required": "⚠ You need `.NET Core 3.1` (runtime) installed in order to receive pmcenter v2 and further updates.\n\nLatest .NET Core runtime version detected on your device: `$1`\n\nThis warning will only show once." + "Message_NetCore31Required": "⚠ You need `.NET Core 3.1` (runtime) installed in order to receive pmcenter v2 and further updates.\n\nLatest .NET Core runtime version detected on your device: `$1`\n\nThis warning will only show once.", + "Message_MsgLinkTip": "ℹ Tip: You need to set `EnableMsgLink` option to `true` in pmcenter configurations in order to reply to anonymously forwarded messages.\nThis also happens when the message link for the message couldn't be found.\nDue to Telegram API's restrictions, it's impossible now to reply to that message.\nAfter you set `EnableMsgLink` to `true`, you'll be able to reply to this kind of messages.\n\nThis tip will only prompt once.", + "Message_AutoSaveEnabled": "✅ Autosave *enabled*, interval: `$1s`.", + "Message_AutoSaveIntervalTooShort": "⚠ The current autosave interval (`$1ms`) is *too short*! It may cause high CPU and disk usage as a result. *Disable it if you didn't intend to do that!*", + "Message_AutoSaveDisabled": "✅ Autosave *disabled*.", + "Message_Action_Banned": "✅ User $1 has been banned!", + "Message_Action_Pardoned": "✅ User $1 has been pardoned!", + "Message_Action_ContChatEnabled": "✅ You're now chatting with $1!", + "Message_Action_ContChatDisabled": "✅ Continued chat disabled!", + "Message_Action_Error": "✖ Action failed. Check logs.", + "Message_Action_ErrorWithDetails": "✖ Action failed: $1", + "Message_Action_ChooseAction": "❓ *What do you want to do with this message?*", + "Message_Action_Ban": "✖ Ban the user", + "Message_Action_Pardon": "✅ Pardon the user", + "Message_Action_Chat": "💬 Enter continued conversation", + "Message_Action_StopChat": "💬 Stop continued conversation", + "Message_Action_LinkNotFound": "✖ Cannot find the corresponding message link, did you just clear the message links, or was the message links feature disabled?" } \ No newline at end of file diff --git a/locales/pmcenter_locale_zh.json b/locales/pmcenter_locale_zh.json index 4c5085c..18a9a99 100644 --- a/locales/pmcenter_locale_zh.json +++ b/locales/pmcenter_locale_zh.json @@ -70,5 +70,21 @@ "Message_Retracted": "✅ 消息已撤回。", "Message_MsgLinksCleared": "✅ 所有消息链接已清空。", "Message_AvailableLang": "ℹ *可用语言*\n\n`$1`", - "Message_NetCore31Required": "⚠ 您的设备上需要安装 `.NET Core 3.1` (运行时) 以获取 pmcenter v2 或未来版本的更新。\n\n在您设备上检测到的最新 .NET Core 运行时版本为: `$1`\n\n此警告只会出现一次。" + "Message_NetCore31Required": "⚠ 您的设备上需要安装 `.NET Core 3.1` (运行时) 以获取 pmcenter v2 或未来版本的更新。\n\n在您设备上检测到的最新 .NET Core 运行时版本为: `$1`\n\n此警告只会出现一次。", + "Message_MsgLinkTip": "ℹ 提示: 您需要在 pmcenter 配置中设置 `EnableMsgLink` 选项为 `true` 以回复匿名转发的消息。\n此情况也会在无法找到对应的消息链接时发生。\n由于 Telegram API 限制,这条消息已经无法回复了。\n在您设置 `EnableMsgLink` 为 `true` 后,您就可以回复后续的匿名转发消息了。\n\n此提示只会出现一次。", + "Message_AutoSaveEnabled": "✅ 自动保存 *已启用*, 时间间隔: `$1s`", + "Message_AutoSaveIntervalTooShort": "⚠ 当前自动保存时间间隔 (`$1ms`) *太短了*! 这可能导致高 CPU 和硬盘占用, *如果您不是刻意为之,请尽快停用!*", + "Message_AutoSaveDisabled": "✅ 自动保存 *已停用*", + "Message_Action_Banned": "✅ 已封禁用户 $1!", + "Message_Action_Pardoned": "✅ 已解封用户 $1!", + "Message_Action_ContChatEnabled": "✅ 已进入与 $1 的持续对话!", + "Message_Action_ContChatDisabled": "✅ 持续对话模式已停用!", + "Message_Action_Error": "✖ 操作失败,请检查日志", + "Message_Action_ErrorWithDetails": "✖ 操作失败: $1", + "Message_Action_ChooseAction": "❓ *你想对这条消息做什么?*", + "Message_Action_Ban": "✖ 封禁该用户", + "Message_Action_Pardon": "✅ 解封该用户", + "Message_Action_Chat": "💬 进入持续对话模式", + "Message_Action_StopChat": "💬 退出持续对话模式", + "Message_Action_LinkNotFound": "✖ 无法找到对应的消息链接, 您是否刚刚清除或者禁用了消息链接?" } \ No newline at end of file diff --git a/locales/pmcenter_locale_zh.meow.json b/locales/pmcenter_locale_zh.meow.json index 421f4ae..ea84f15 100644 --- a/locales/pmcenter_locale_zh.meow.json +++ b/locales/pmcenter_locale_zh.meow.json @@ -70,5 +70,21 @@ "Message_Retracted": "✅ 消息已经从主人那边撤回啦~", "Message_MsgLinksCleared": "✅ 所有消息链接都清理掉啦~", "Message_AvailableLang": "ℹ *可用语言*\n\n`$1`", - "Message_NetCore31Required": "⚠ 您的设备上需要安装 `.NET Core 3.1` (运行时) 以获取 pmcenter v2 或未来版本的更新。\n\n在您设备上检测到的最新 .NET Core 运行时版本为: `$1`\n\n此警告只会出现一次。" + "Message_NetCore31Required": "⚠ 您的设备上需要安装 `.NET Core 3.1` (运行时) 以获取 pmcenter v2 或未来版本的更新。\n\n在您设备上检测到的最新 .NET Core 运行时版本为: `$1`\n\n此警告只会出现一次。", + "Message_MsgLinkTip": "ℹ 提示: 您需要在 pmcenter 配置中设置 `EnableMsgLink` 选项为 `true` 以回复匿名转发的消息。\n此情况也会在无法找到对应的消息链接时发生。\n由于 Telegram API 限制,这条消息已经回复不了惹。\n设置 `EnableMsgLink` 为 `true` 后,就可以回复后续的匿名转发消息啦。\n\n咱只骚扰咱家主人一次的喵!。", + "Message_AutoSaveEnabled": "✅ 自动保存 *已启用*, 时间间隔: `$1s`", + "Message_AutoSaveIntervalTooShort": "⚠ 现在的自动保存时间间隔 (`$1ms`) *太短了*! 这可能导致高 CPU 和硬盘占用, 主人是手滑了吗(挠", + "Message_AutoSaveDisabled": "✅ 自动保存 *已停用*", + "Message_Action_Banned": "✅ 已搞定用户 $1!", + "Message_Action_Pardoned": "✅ 已解封用户 $1!", + "Message_Action_ContChatEnabled": "✅ 已进入与 $1 的持续对话!", + "Message_Action_ContChatDisabled": "✅ 持续对话模式已停用!", + "Message_Action_Error": "✖ 操作失败啦OAO,看一下日志吧", + "Message_Action_ErrorWithDetails": "✖ 操作失败: $1", + "Message_Action_ChooseAction": "❓ *想做什么呢(盯*", + "Message_Action_Ban": "✖ 拍扁该用户", + "Message_Action_Pardon": "✅ 解封该用户", + "Message_Action_Chat": "💬 进入持续对话模式", + "Message_Action_StopChat": "💬 退出持续对话模式", + "Message_Action_LinkNotFound": "✖ 咱找不到对应的消息链接耶, 主人是不是刚刚清除或者禁用了消息链接?" } \ No newline at end of file diff --git a/locales/pmcenter_locale_zh.tw.json b/locales/pmcenter_locale_zh.tw.json index 0f4e478..ee85181 100644 --- a/locales/pmcenter_locale_zh.tw.json +++ b/locales/pmcenter_locale_zh.tw.json @@ -70,5 +70,21 @@ "Message_Retracted": "✅ 訊息已撤銷。", "Message_MsgLinksCleared": "✅ 所有訊息鏈接已清空。", "Message_AvailableLang": "ℹ *可用語言*\n\n`$1`", - "Message_NetCore31Required": "⚠ 您的設備上需要安裝 `.NET Core 3.1` (運行時) 以獲取 pmcenter v2 或更新版本更新。\n\n在您的設備上識別到的最新 .NET Core 運行時版本為: `$1`\n\n此警告僅會出現一次。" + "Message_NetCore31Required": "⚠ 您的設備上需要安裝 `.NET Core 3.1` (運行時) 以獲取 pmcenter v2 或更新版本更新。\n\n在您的設備上識別到的最新 .NET Core 運行時版本為: `$1`\n\n此警告僅會出現一次。", + "Message_MsgLinkTip": "ℹ 提示: 您需要於 pmcenter 設定中設定 `EnableMsgLink` 選項爲 `true` 以回覆匿名轉傳的訊息。\n此情況也會於無法搜尋到對應的訊息連結時發生。\n由於 Telegram API 限制,這條訊息已經無法回覆了。\n在您設定 `EnableMsgLink` 爲 `true` 後,您即可回覆後續的匿名轉傳訊息了。\n\n此提示僅會出現一次。", + "Message_AutoSaveEnabled": "✅ 自動儲存 *已啓用*, 時間間隔: `$1s`", + "Message_AutoSaveIntervalTooShort": "⚠ 目前自動儲存時間間隔 (`$1ms`) *過短*! 這可能導致高 CPU 和硬碟佔用, *若您非刻意爲之,請儘快停用!*", + "Message_AutoSaveDisabled": "✅ 自動儲存 *已停用*", + "Message_Action_Banned": "✅ 已封鎖用戶 $1!", + "Message_Action_Pardoned": "✅ 已解除封鎖用戶 $1!", + "Message_Action_ContChatEnabled": "✅ 已進入與 $1 的持續對話!", + "Message_Action_ContChatDisabled": "✅ 持續對話模式已停用!", + "Message_Action_Error": "✖ 操作失敗,請檢查日誌", + "Message_Action_ErrorWithDetails": "✖ 操作失敗: $1", + "Message_Action_ChooseAction": "❓ *你想對這條訊息做甚麼?*", + "Message_Action_Ban": "✖ 封鎖该用戶", + "Message_Action_Pardon": "✅ 解除封鎖该用戶", + "Message_Action_Chat": "💬 進入持續對話模式", + "Message_Action_StopChat": "💬 退出持續對話模式", + "Message_Action_LinkNotFound": "✖ 無法找到對應的訊息連結, 您是否剛剛清除或停用了訊息連結?" } \ No newline at end of file diff --git a/pmcenter/BotCommands/AutoSaveCommand.cs b/pmcenter/BotCommands/AutoSaveCommand.cs new file mode 100644 index 0000000..170be68 --- /dev/null +++ b/pmcenter/BotCommands/AutoSaveCommand.cs @@ -0,0 +1,74 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; + +namespace pmcenter.Commands +{ + internal class AutoSaveCommand : IBotCommand + { + public bool OwnerOnly => true; + + public string Prefix => "autosave"; + + public async Task ExecuteAsync(TelegramBotClient botClient, Update update) + { + try + { + var text = update.Message.Text; + var interval = 30000; + if (text.Contains(" ")) + { + var command = text.Split(' ', 2)[1]; + if (command.ToLower() == "off") + { + Vars.CurrentConf.ConfSyncInterval = 0; + _ = await botClient.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_AutoSaveDisabled, + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + if (Vars.SyncConf != null) Vars.SyncConf.Interrupt(); + return true; + } + interval = int.Parse(command); + } + Vars.CurrentConf.ConfSyncInterval = interval; + _ = await botClient.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_AutoSaveEnabled.Replace("$1", (interval / 1000).ToString()), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + if (interval < 5000) + _ = await botClient.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_AutoSaveIntervalTooShort.Replace("$1", interval.ToString()), + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + if ((Vars.SyncConf == null) || !Vars.SyncConf.IsAlive) + { + Vars.SyncConf = new Thread(() => Methods.ThrSyncConf()); + Vars.SyncConf.Start(); + } + return true; + } + catch (Exception ex) + { + Log($"Failed to process autosave command: {ex}", "BOT", LogLevel.Error); + _ = await botClient.SendTextMessageAsync(update.Message.From.Id, + Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), + ParseMode.Default, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + return true; + } + } + } +} diff --git a/pmcenter/BotCommands/Chat.cs b/pmcenter/BotCommands/ChatCommand.cs similarity index 100% rename from pmcenter/BotCommands/Chat.cs rename to pmcenter/BotCommands/ChatCommand.cs diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index 14811f6..fef7976 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -16,7 +16,7 @@ private static async Task OwnerReplying(Update update) Log($"Selected message is forwarded anonymously from {link.TGUser.Id}, fixing user information from database.", "BOT"); update.Message.ReplyToMessage.ForwardFrom = link.TGUser; } - if (update.Message.ReplyToMessage.ForwardFrom == null && update.Message.Text.ToLower() != "/retract") + if ((update.Message.ReplyToMessage.ForwardFrom == null) && (update.Message.Text.ToLower() != "/retract")) { // The owner is replying to bot messages. (no forwardfrom) _ = await Vars.Bot.SendTextMessageAsync( @@ -26,6 +26,18 @@ private static async Task OwnerReplying(Update update) false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); + // The message is forwarded anonymously + if ((update.Message.ReplyToMessage.ForwardFromChat?.Id == Vars.AnonymousChannelId) && !Vars.CurrentConf.DisableMessageLinkTip) + { + _ = await Vars.Bot.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_MsgLinkTip, + ParseMode.Markdown, + false, + Vars.CurrentConf.DisableNotifications, + update.Message.MessageId).ConfigureAwait(false); + Vars.CurrentConf.DisableMessageLinkTip = true; + } return; } diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 9a3eadc..01ba31a 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -15,10 +15,7 @@ private static async Task UserLogic(Update update) { // is user - if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) - { - return; - } + if (await commandManager.Execute(Vars.Bot, update).ConfigureAwait(false)) return; Log($"Received message from \"{update.Message.From.FirstName}\" (@{update.Message.From.Username} / {update.Message.From.Id}), forwarding...", "BOT"); diff --git a/pmcenter/BotProcess/BotProcess.cs b/pmcenter/BotProcess/BotProcess.cs index e3e37d1..aa68059 100644 --- a/pmcenter/BotProcess/BotProcess.cs +++ b/pmcenter/BotProcess/BotProcess.cs @@ -25,6 +25,7 @@ static BotProcess() commandManager.RegisterCommand(new BanCommand()); commandManager.RegisterCommand(new PardonCommand()); + commandManager.RegisterCommand(new AutoSaveCommand()); commandManager.RegisterCommand(new BackupConfCommand()); commandManager.RegisterCommand(new BanIdCommand()); commandManager.RegisterCommand(new CatConfigCommand()); diff --git a/pmcenter/CommandLineProcess.cs b/pmcenter/CommandLineProcess.cs index cd7d82f..d384f6b 100644 --- a/pmcenter/CommandLineProcess.cs +++ b/pmcenter/CommandLineProcess.cs @@ -10,22 +10,22 @@ namespace pmcenter { public static class CmdLineProcess { - private static readonly CommandLineRouter CmdLineRouter = new CommandLineRouter(); + private static readonly CommandLineRouter cmdLineRouter = new CommandLineRouter(); static CmdLineProcess() { - CmdLineRouter.RegisterCommand(new CommandLines.HelpCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.InfoCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.NonServiceModeCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.SetupWizardCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.ResetCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.BackupCmdLine()); - CmdLineRouter.RegisterCommand(new CommandLines.UpdateCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.HelpCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.InfoCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.NonServiceModeCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.SetupWizardCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.ResetCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.BackupCmdLine()); + cmdLineRouter.RegisterCommand(new CommandLines.UpdateCmdLine()); } public static async Task RunCommand(string CommandLine) { - _ = await CmdLineRouter.Execute(CommandLine).ConfigureAwait(false); + _ = await cmdLineRouter.Execute(CommandLine).ConfigureAwait(false); } } } diff --git a/pmcenter/Configurations/CheckPoint.cs b/pmcenter/Configurations/CheckPoint.cs new file mode 100644 index 0000000..ca8caef --- /dev/null +++ b/pmcenter/Configurations/CheckPoint.cs @@ -0,0 +1,13 @@ +namespace pmcenter +{ + public class CheckPoint + { + public CheckPoint(long tick = 0, string name = "Unspecified") + { + Tick = tick; + Name = name; + } + public long Tick; + public string Name; + } +} diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index 3fb44e8..9022b51 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -41,6 +41,9 @@ public ConfObj() UpdateChannel = "master"; IgnoreKeyboardInterrupt = false; DisableNetCore3Check = false; + DisableMessageLinkTip = false; + AnalyzeStartupTime = false; + SkipAPIKeyVerification = false; EnableActions = false; Statistics = new Stats(); IgnoredLogModules = new List(); diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index c7101b6..a2dfd51 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -39,6 +39,9 @@ public sealed partial class ConfObj public string UpdateChannel { get; set; } public bool IgnoreKeyboardInterrupt { get; set; } public bool DisableNetCore3Check { get; set; } + public bool DisableMessageLinkTip { get; set; } + public bool AnalyzeStartupTime { get; set; } + public bool SkipAPIKeyVerification { get; set; } public bool EnableActions { get; set; } public Stats Statistics { get; set; } public List IgnoredLogModules { get; set; } diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index 345eeb6..8514592 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -12,7 +12,7 @@ public Language() LanguageNameInNative = "English"; Message_CommandNotReplying = "😶 Don't talk to me, spend time chatting with those who love you."; Message_CommandNotReplyingValidMessage = "😐 Speaking to me makes no sense."; - Message_Help = "❓ `pmcenter` *Bot Help*\n/start - Display welcome message.\n/info - Display the message's info.\n/ban - Restrict the user from contacting you.\n/banid - Restrict a user from contacting you with his/her ID.\n/pardon - Pardon the user.\n/pardonid - Pardon a user with his/her ID.\n/ping - Test if the bot is working.\n/switchfw - Pause/Resume message forwarding.\n/switchbw - Enable/Disable keyword banning.\n/switchnf - Enable/Disable notifications.\n/switchlang - Switch language file.\n/switchlangcode [Code] - Switch language with language code.\n/detectperm - Detect permissions.\n/backup - Backup configurations.\n/editconf - Manually edit settings w/ JSON-formatted text.\n/saveconf - Manually save all settings and translations. Especially useful after upgrades.\n/readconf - Reload configurations without restarting bot.\n/resetconf - Reset configurations.\n/uptime - Check system uptime information.\n/update - Check for updates and update bot.\n/chkupdate - Only check for updates.\n/catconf - Get your current configurations.\n/restart - Restart bot.\n/status - Get host device's status information.\n/perform - Run performance test.\n/testnetwork - Test latency to servers used by pmcenter.\n/chat - Enter Continued Conversation mode.\n/stopchat - Leave Continued Conversation mode.\n/retract - Retract a message.\n/clearmessagelinks - Clear message links.\n/getstats - Get statistics data.\n/help - Display this message.\n\nThank you for using `pmcenter`!"; + Message_Help = "❓ `pmcenter` *Bot Help*\n/start - Display welcome message.\n/info - Display the message's info.\n/ban - Restrict the user from contacting you.\n/banid - Restrict a user from contacting you with his/her ID.\n/pardon - Pardon the user.\n/pardonid - Pardon a user with his/her ID.\n/ping - Test if the bot is working.\n/switchfw - Pause/Resume message forwarding.\n/switchbw - Enable/Disable keyword banning.\n/switchnf - Enable/Disable notifications.\n/switchlang - Switch language file.\n/switchlangcode [Code] - Switch language with language code.\n/detectperm - Detect permissions.\n/backup - Backup configurations.\n/editconf - Manually edit settings w/ JSON-formatted text.\n/saveconf - Manually save all settings and translations. Especially useful after upgrades.\n/readconf - Reload configurations without restarting bot.\n/resetconf - Reset configurations.\n/uptime - Check system uptime information.\n/update - Check for updates and update bot.\n/chkupdate - Only check for updates.\n/catconf - Get your current configurations.\n/restart - Restart bot.\n/status - Get host device's status information.\n/perform - Run performance test.\n/testnetwork - Test latency to servers used by pmcenter.\n/chat - Enter Continued Conversation mode.\n/stopchat - Leave Continued Conversation mode.\n/retract - Retract a message.\n/clearmessagelinks - Clear message links.\n/getstats - Get statistics data.\n/autosave [off/interval] - Switch autosave status.\n/help - Display this message.\n\nThank you for using `pmcenter`!"; Message_OwnerStart = "😊 *Hi!* I'm your `pmcenter` bot, and I work just for you.\nThis message means that you've set up the bot successfully.\nTo reply to any forwarded messages, just directly reply to them here.\n\nThank you for using the `pmcenter` bot!"; Message_ReplySuccessful = "✅ Successfully replied to user $1!"; Message_ForwardedToOwner = "✅ Your message has been forwarded to my owner!"; @@ -78,6 +78,10 @@ public Language() Message_MsgLinksCleared = "✅ All message links have been cleared."; Message_AvailableLang = "ℹ *Available languages*\n\n`$1`"; Message_NetCore31Required = "⚠ You need `.NET Core 3.1` (runtime) installed in order to receive pmcenter v2 and further updates.\n\nLatest .NET Core runtime version detected on your device: `$1`\n\nThis warning will only show once."; + Message_MsgLinkTip = "ℹ Tip: You need to set `EnableMsgLink` option to `true` in pmcenter configurations in order to reply to anonymously forwarded messages.\nThis also happens when the message link for the message couldn't be found.\nDue to Telegram API's restrictions, it's impossible now to reply to that message.\nAfter you set `EnableMsgLink` to `true`, you'll be able to reply to this kind of messages.\n\nThis tip will only prompt once."; + Message_AutoSaveEnabled = "✅ Autosave *enabled*, interval: `$1s`."; + Message_AutoSaveIntervalTooShort = "⚠ The current autosave interval (`$1ms`) is *too short*! It may cause high CPU and disk usage as a result. *Disable it if you didn't intend to do that!*"; + Message_AutoSaveDisabled = "✅ Autosave *disabled*."; Message_Action_Banned = "✅ User $1 has been banned!"; Message_Action_Pardoned = "✅ User $1 has been pardoned!"; Message_Action_ContChatEnabled = "✅ You're now chatting with $1!"; @@ -89,7 +93,7 @@ public Language() Message_Action_Pardon = "✅ Pardon the user"; Message_Action_Chat = "💬 Enter continued conversation"; Message_Action_StopChat = "💬 Stop continued conversation"; - Message_Action_LinkNotFound = "Cannot find the corresponding message link, did you just clear the message links, or was the message links feature disabled?"; + Message_Action_LinkNotFound = "✖ Cannot find the corresponding message link, did you just clear the message links, or was the message links feature disabled?"; } } } diff --git a/pmcenter/Configurations/Lang.Language.cs b/pmcenter/Configurations/Lang.Language.cs index c1091c5..8349cd0 100644 --- a/pmcenter/Configurations/Lang.Language.cs +++ b/pmcenter/Configurations/Lang.Language.cs @@ -76,6 +76,10 @@ public sealed partial class Language public string Message_MsgLinksCleared { get; set; } public string Message_AvailableLang { get; set; } public string Message_NetCore31Required { get; set; } + public string Message_MsgLinkTip { get; set; } + public string Message_AutoSaveEnabled { get; set; } + public string Message_AutoSaveIntervalTooShort { get; set; } + public string Message_AutoSaveDisabled { get; set; } public string Message_Action_Banned { get; set; } public string Message_Action_Pardoned { get; set; } public string Message_Action_ContChatEnabled { get; set; } diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index 3a9f166..455c54b 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -32,7 +32,7 @@ public static void ExitApp(int code) Vars.ConfValidator, Vars.UpdateChecker, Vars.RateLimiter, - Vars.BannedSweepper, + Vars.BannedSweeper, Vars.SyncConf }; diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 0233cf2..11f4b1f 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -8,6 +8,7 @@ public static partial class Methods { public static async void ThrSyncConf() { + Log("Autosave thread online!", "CONFSYNC"); while (!Vars.IsShuttingDown) { try diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index bf6bd89..ee9f535 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -22,6 +22,15 @@ namespace pmcenter { public sealed partial class Program { + private static readonly List _checkPoints = new List(); + private static void Check(string name) => _checkPoints.Add(new CheckPoint(Vars.StartSW.ElapsedTicks, name)); + private static void PrintCheckPoints() + { + Log("Check points recorded during startup:"); + for (int i = 1; i < _checkPoints.Count; i++) + Log($"#{i}: {(double)(_checkPoints[i].Tick - _checkPoints[i - 1].Tick) / 10000}ms: {_checkPoints[i].Name} at {(double)_checkPoints[i].Tick / 10000}ms"); + } + public static void Main(string[] args) { Vars.StartSW.Start(); @@ -39,14 +48,17 @@ public static async Task MainAsync(string[] args) { try { + Check("Initial checkpoint"); // mark initial checkpoint Log("==> Running pre-start operations..."); // hook global errors (final failsafe) AppDomain.CurrentDomain.UnhandledException += GlobalErrorHandler; Log("Global error handler is armed and ready!"); // hook ctrl-c events Console.CancelKeyPress += CtrlCHandler; + Check("Event handlers armed"); // process commandlines await CmdLineProcess.RunCommand(Environment.CommandLine).ConfigureAwait(false); + Check("Command line arguments processed"); // everything (exits and/or errors) are handled above, please do not process. // detect environment variables // including: @@ -83,7 +95,8 @@ public static async Task MainAsync(string[] args) { Log($"Failed to read environment variables: {ex}", "CORE", LogLevel.Warning); } - + Check("Environment variables processed"); + Log($"==> Using configurations file: {Vars.ConfFile}"); Log($"==> Using language file: {Vars.LangFile}"); @@ -91,8 +104,10 @@ public static async Task MainAsync(string[] args) Log("==> Initializing module - CONF"); // BY DEFAULT CONF & LANG ARE NULL! PROCEED BEFORE DOING ANYTHING. <- well anyway we have default values await InitConf().ConfigureAwait(false); _ = await ReadConf().ConfigureAwait(false); + Check("Configurations loaded"); await InitLang().ConfigureAwait(false); _ = await ReadLang().ConfigureAwait(false); + Check("Custom locale loaded"); if (Vars.CurrentLang == null) { @@ -119,6 +134,7 @@ public static async Task MainAsync(string[] args) Console.WriteLine("This warning will appear every time pmcenter starts up with \"IgnoredLogModules\" set."); Console.ForegroundColor = tmp; } + Check("Warnings displayed"); Log("==> Initializing module - THREADS"); Log("Starting RateLimiter..."); @@ -129,6 +145,8 @@ public static async Task MainAsync(string[] args) { Thread.Sleep(100); } + Check("Rate limiter online"); + Log("Starting UpdateChecker..."); if (Vars.CurrentConf.EnableAutoUpdateCheck) { @@ -145,6 +163,8 @@ public static async Task MainAsync(string[] args) Vars.UpdateCheckerStatus = ThreadStatus.Stopped; Log("Skipped."); } + Check("Update checker ready"); + Log("Starting SyncConf..."); Vars.SyncConf = new Thread(() => ThrSyncConf()); Vars.SyncConf.Start(); @@ -153,6 +173,7 @@ public static async Task MainAsync(string[] args) { Thread.Sleep(100); } + Check("Configurations autosaver online"); Log("==> Initializing module - BOT"); Log("Initializing bot instance..."); @@ -179,8 +200,12 @@ public static async Task MainAsync(string[] args) { Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey); } + Check("Bot initialized"); + Log("Validating API Key..."); - _ = await Vars.Bot.TestApiAsync().ConfigureAwait(false); + if (!Vars.CurrentConf.SkipAPIKeyVerification) _ = await Vars.Bot.TestApiAsync().ConfigureAwait(false); + Check("API Key test passed"); + Log("Hooking event processors..."); Vars.Bot.OnUpdate += BotProcess.OnUpdate; Log("Starting receiving..."); @@ -189,6 +214,8 @@ public static async Task MainAsync(string[] args) UpdateType.Message, UpdateType.CallbackQuery }); + Check("Update receiving started"); + Log("==> Startup complete!"); Log("==> Running post-start operations..."); try @@ -208,6 +235,8 @@ public static async Task MainAsync(string[] args) { Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex}", "BOT", LogLevel.Warning); } + Check("Startup message sent"); + try { // check .net core runtime version @@ -227,6 +256,8 @@ public static async Task MainAsync(string[] args) { Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.Warning); } + Check(".NET Core version check complete"); + // check language mismatch if (Vars.CurrentLang.TargetVersion != Vars.AppVer.ToString()) { @@ -239,6 +270,14 @@ public static async Task MainAsync(string[] args) false, false).ConfigureAwait(false); } + Check("Language version mismatch checked"); + Check("Complete"); + if (Vars.CurrentConf.AnalyzeStartupTime) + { + Log("Advanced startup time analysis is on, printing startup checkpoints..."); + PrintCheckPoints(); + } + Log("==> All finished!"); if (Vars.ServiceMode) while (true) diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 651897d..1690589 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -43,7 +43,7 @@ public static class Vars #else public readonly static bool SelfContained = false; #endif - // public readonly static long AnonymousChannelID = -1001228946795; + public readonly static long AnonymousChannelId = -1001228946795; // public readonly static string AnonymousChannelTitle = "a user"; // public readonly static string AnonymousChannelUsername = "HiddenSender"; @@ -68,7 +68,7 @@ public static class Vars public static bool IsPerformanceTestEndRequested = false; public static double PerformanceScore = 0; - public static Thread BannedSweepper; + public static Thread BannedSweeper; public static Thread ConfValidator; public static Methods.ThreadStatus ConfResetTimerStatus = Methods.ThreadStatus.Stopped; public static Thread RateLimiter; From 6d4952f02b90798556b4d5d5e91b80e54f7beafa Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 27 Apr 2020 12:48:58 +0800 Subject: [PATCH 21/39] updated forwarding logics, pmcenter now prefers enabling message links by default --- FILE_STRUCTURE.md | 16 +++++++--- README.md | 3 +- README_zh.md | 3 +- pmcenter/BotCommands/InfoCommand.cs | 2 +- .../BotProcess/BotProcess.OwnerReplying.cs | 6 ++-- pmcenter/BotProcess/BotProcess.UserLogic.cs | 32 ++++++++----------- pmcenter/Configurations/Conf.ConfObj.New.cs | 2 +- pmcenter/EventHandlers/CtrlCHandler.cs | 4 +-- pmcenter/Methods/Methods.ExitApp.cs | 5 ++- 9 files changed, 41 insertions(+), 32 deletions(-) diff --git a/FILE_STRUCTURE.md b/FILE_STRUCTURE.md index 0ba0e3d..deb976f 100644 --- a/FILE_STRUCTURE.md +++ b/FILE_STRUCTURE.md @@ -4,11 +4,15 @@ File structure of pmcenter's source code: |- pmcenter - Source code main directory |- BotCommands - Every bot command's processing logic | |- ... + |- BotProcess - Bot's message routing logics + | |- ... + |- CallbackActions - Every inline keyboard command's processing logic + | |- ... |- CommandLines - Every commandline's processing logic | |- ... |- Configurations - Configurations' processing logics | |- ... - |- Enums - pmcenter's self-defined enums + |- EventHandlers - Global error handler and Ctrl-C handler | |- ... |- Interfaces - pmcenter's self-defined interfaces | |- ... @@ -18,15 +22,19 @@ File structure of pmcenter's source code: | | | |- ... | | |- Writing - For writing things to database | | | |- ... + | |- H2Helper - http/2 helper + | | |- ... + | |- Logging - Logging module + | | |- ... | |- NetworkTest - Testing network quality, used by some commands | | |- ... | |- Threads - Threads' logics | | |- ... + | |- UpdateHelper - pmcenter updates helper + | | |- ... | |- ... - |- BotProcess.cs - Bot's master logic + |- CommandLineProcess.cs - Loading commandlines to memory |- CommandLineRouter.cs - Commandlines' router - |- CommandLines.cs - Loading commandlines to memory - |- CommandManager.cs - Bot commands' router |- Program.cs - Main entry of pmcenter |- Setup.cs - Setup wizard's processing logic |- Template.cs - As its name diff --git a/README.md b/README.md index 51dde57..8ec62fa 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,8 @@ Tip: After upgrades, you can send `/saveconf` command to the bot to fix missing - **Emojis** are supported, and were used by default. - Currently the response of the `/info` command is unchangeable. - Familiar with another language? Pull requests are welcome! -- Please think twice before turning on `EnableMsgLink`, it makes it possible for you to reply to messages that are forwarded anonymously or from channels, however, it will cost more and more of your storage space and memory as the storage grows and makes it slower for pmcenter to process configuration files. +- ~~Please think twice before turning on `EnableMsgLink`, it makes it possible for you to reply to messages that are forwarded anonymously or from channels, however, it will cost more and more of your storage space and memory as the storage grows and makes it slower for pmcenter to process configuration files.~~ +- Now Message Links play an important role in pmcenter's basic functions. Turning it off is NOT recommended. #### Changing File Location diff --git a/README_zh.md b/README_zh.md index e9840dc..5ee19b8 100644 --- a/README_zh.md +++ b/README_zh.md @@ -207,7 +207,8 @@ docker run -d -v $(pwd)/pmcenter.json:/opt/pmcenter/pmcenter.json --restart alwa - 目前 `/info` 命令的回复尚且无法更改。 - 欢迎 Pull Requests. - 切换中文语言包,只需发送 `/switchlang https://raw.githubusercontent.com/Elepover/pmcenter/master/locales/pmcenter_locale_zh.json` -- 在启用 `EnableMsgLink` 前请三思:虽然此功能允许您回复匿名转发消息及频道消息,但 pmcenter 的存储和内存占用将随消息量增长而增加,并将拖慢 pmcenter 操作配置文件时的速度。 +- ~~在启用 `EnableMsgLink` 前请三思:虽然此功能允许您回复匿名转发消息及频道消息,但 pmcenter 的存储和内存占用将随消息量增长而增加,并将拖慢 pmcenter 操作配置文件时的速度。~~ +- 现在消息链接在 pmcenter 正常功能中起着重要作用,我们不推荐将其禁用。 #### 改变文件位置 diff --git a/pmcenter/BotCommands/InfoCommand.cs b/pmcenter/BotCommands/InfoCommand.cs index f49959c..2bf0457 100644 --- a/pmcenter/BotCommands/InfoCommand.cs +++ b/pmcenter/BotCommands/InfoCommand.cs @@ -94,7 +94,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } else if (targetMessage.Dice != null) { - sb.Append("\n🎲 Dice: `"); + sb.Append("\n🎲 Dice/Dart: `"); sb.Append(targetMessage.Dice.Value); sb.Append("`"); } diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index fef7976..c1a9c90 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -27,7 +27,7 @@ private static async Task OwnerReplying(Update update) Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); // The message is forwarded anonymously - if ((update.Message.ReplyToMessage.ForwardFromChat?.Id == Vars.AnonymousChannelId) && !Vars.CurrentConf.DisableMessageLinkTip) + if (!string.IsNullOrEmpty(update.Message.ReplyToMessage.ForwardSenderName) && !Vars.CurrentConf.DisableMessageLinkTip) { _ = await Vars.Bot.SendTextMessageAsync( update.Message.From.Id, @@ -67,10 +67,10 @@ private static async Task OwnerReplying(Update update) if (Vars.CurrentConf.EnableRepliedConfirmation) { var replyToMessage = Vars.CurrentLang.Message_ReplySuccessful; - replyToMessage = replyToMessage.Replace("$1", $"[{update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username})](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); + replyToMessage = replyToMessage.Replace("$1", $"[{Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom)}](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, replyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); } - Log($"Successfully passed owner's reply to {update.Message.ReplyToMessage.ForwardFrom.FirstName} (@{update.Message.ReplyToMessage.ForwardFrom.Username} / {update.Message.ReplyToMessage.ForwardFrom.Id})", "BOT"); + Log($"Successfully passed owner's reply to {Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom, true, true)}", "BOT"); } } } diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 01ba31a..2133d18 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -80,33 +80,29 @@ private static async Task UserLogic(Update update) } // check for real message sender // check if forwarded from channels + bool forwarderNotReal = false; if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) - { // is forwarded from channel + forwarderNotReal = true; + + if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) + // is forwarded from chats, but the forwarder is not the message sender + if (update.Message.ForwardFrom.Id != update.Message.From.Id) + forwarderNotReal = true; + + if (!string.IsNullOrEmpty(update.Message.ForwardSenderName) || !string.IsNullOrEmpty(forwardedMessage.ForwardSenderName)) + // is anonymously forwarded + forwarderNotReal = true; + + if (forwarderNotReal) _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_ForwarderNotReal .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), + .Replace("$1", $"[{GetComposedUsername(update.Message.From)}](tg://user?id={update.Message.From.Id})"), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, forwardedMessage.MessageId).ConfigureAwait(false); - } - if (update.Message.ForwardFrom != null && update.Message.ForwardFromChat == null) - { - // is forwarded from chats - if (update.Message.ForwardFrom.Id != update.Message.From.Id) - { - _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_ForwarderNotReal - .Replace("$2", update.Message.From.Id.ToString()) - .Replace("$1", "[" + update.Message.From.FirstName + " " + update.Message.From.LastName + "](tg://user?id=" + update.Message.From.Id + ")"), - ParseMode.Markdown, - false, - Vars.CurrentConf.DisableNotifications, - forwardedMessage.MessageId).ConfigureAwait(false); - } - } // process cc if (Vars.CurrentConf.EnableCc) diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index 9022b51..faa4bef 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -33,7 +33,7 @@ public ConfObj() CatchAllExceptions = false; NoStartupMessage = false; ContChatTarget = -1; - EnableMsgLink = false; + EnableMsgLink = true; AllowUserRetraction = false; ConfSyncInterval = 30000; AdvancedLogging = false; diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index f079ea7..ea162b0 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -6,7 +6,7 @@ namespace pmcenter { public static partial class EventHandlers { - public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) + public static async void CtrlCHandler(object sender, ConsoleCancelEventArgs e) { Vars.CtrlCCounter++; if (Vars.CtrlCCounter > 3) @@ -24,7 +24,7 @@ public static void CtrlCHandler(object sender, ConsoleCancelEventArgs e) Vars.IsCtrlCHandled = true; Log("Interrupt! pmcenter is exiting...", LogLevel.Warning); Log("If pmcenter was unresponsive, press Ctrl-C 3 more times."); - ExitApp(130); + await ExitApp(130); } } } diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index 455c54b..3fca1ca 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -1,13 +1,14 @@ using System; using System.Diagnostics; using System.Threading; +using System.Threading.Tasks; using static pmcenter.Methods.Logging; namespace pmcenter { public static partial class Methods { - public static void ExitApp(int code) + public static async Task ExitApp(int code) { Log("Attempting to exit gracefully..."); Log("Stopping bot message receiving..."); @@ -17,6 +18,8 @@ public static void ExitApp(int code) sw.Start(); Vars.IsShuttingDown = true; + Log("Saving configurations..."); + await Conf.SaveConf(); if (Vars.IsPerformanceTestExecuting) { while (!Vars.IsPerformanceTestExecuting) From f2ed0dfbeac41cb9165cd7c25f798668d051330b Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 27 Apr 2020 12:51:59 +0800 Subject: [PATCH 22/39] fix await --- FILE_STRUCTURE.md | 2 -- pmcenter/BotCommands/ResetConfCommand.cs | 2 +- pmcenter/BotCommands/RestartCommand.cs | 2 +- pmcenter/BotCommands/UpdateCommand.cs | 2 +- pmcenter/{ => CommandLines}/CommandLineProcess.cs | 0 pmcenter/{ => CommandLines}/CommandLineRouter.cs | 0 6 files changed, 3 insertions(+), 5 deletions(-) rename pmcenter/{ => CommandLines}/CommandLineProcess.cs (100%) rename pmcenter/{ => CommandLines}/CommandLineRouter.cs (100%) diff --git a/FILE_STRUCTURE.md b/FILE_STRUCTURE.md index deb976f..4659fab 100644 --- a/FILE_STRUCTURE.md +++ b/FILE_STRUCTURE.md @@ -33,8 +33,6 @@ File structure of pmcenter's source code: | |- UpdateHelper - pmcenter updates helper | | |- ... | |- ... - |- CommandLineProcess.cs - Loading commandlines to memory - |- CommandLineRouter.cs - Commandlines' router |- Program.cs - Main entry of pmcenter |- Setup.cs - Setup wizard's processing logic |- Template.cs - As its name diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index f48cdf6..f668342 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -40,7 +40,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); - Methods.ExitApp(0); + await Methods.ExitApp(0); return true; } else diff --git a/pmcenter/BotCommands/RestartCommand.cs b/pmcenter/BotCommands/RestartCommand.cs index 3b8793b..3005a3c 100644 --- a/pmcenter/BotCommands/RestartCommand.cs +++ b/pmcenter/BotCommands/RestartCommand.cs @@ -22,7 +22,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); Thread.Sleep(5000); - Methods.ExitApp(0); + await Methods.ExitApp(0); return true; } } diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index e629a99..357c2db 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -55,7 +55,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T Vars.CurrentConf.DisableNotifications, update.Message.MessageId).ConfigureAwait(false); Log("Exiting program... (Let the daemon do the restart job)", "BOT"); - ExitApp(0); + await ExitApp(0); return true; // end of difference } diff --git a/pmcenter/CommandLineProcess.cs b/pmcenter/CommandLines/CommandLineProcess.cs similarity index 100% rename from pmcenter/CommandLineProcess.cs rename to pmcenter/CommandLines/CommandLineProcess.cs diff --git a/pmcenter/CommandLineRouter.cs b/pmcenter/CommandLines/CommandLineRouter.cs similarity index 100% rename from pmcenter/CommandLineRouter.cs rename to pmcenter/CommandLines/CommandLineRouter.cs From 3d6f57ff701cfaf71c86a6387246a31316797187 Mon Sep 17 00:00:00 2001 From: Elepover Date: Mon, 27 Apr 2020 13:06:18 +0800 Subject: [PATCH 23/39] add an option to minify configurations JSON --- README.md | 1 + README_zh.md | 1 + pmcenter/BotProcess/BotProcess.OwnerReplying.cs | 2 +- pmcenter/Configurations/Conf.ConfObj.New.cs | 1 + pmcenter/Configurations/Conf.ConfObj.cs | 1 + pmcenter/Configurations/Conf.SaveConf.cs | 2 +- 6 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8ec62fa..a6d6401 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ Or, use setup wizard: | Key | Type | User Editable | Description | | :---- | :---- | :---- | ----:| +| `Minify` | `Boolean`| ✓ | To minify pmcenter configurations or not. | | `APIKey` | `String`| ✓ | Your Telegram bot's API key. | | `OwnerID` | `Long` | ✓ | The owner's Telegram user ID. | | `EnableCc` | `Boolean` | ✓ | Decides whether cc feature is enabled or not. | diff --git a/README_zh.md b/README_zh.md index 5ee19b8..2083c51 100644 --- a/README_zh.md +++ b/README_zh.md @@ -144,6 +144,7 @@ docker run -d -v $(pwd)/pmcenter.json:/opt/pmcenter/pmcenter.json --restart alwa | 项目 | 类型 | 用户可编辑 | 描述 | | :---- | :---- | :---- | ----:| +| `Minify` | `Boolean`| ✓ | 是否精简化 pmcenter 配置 | | `APIKey` | `String` | ✓ | 你的 Telegram 机器人 API 密钥 | | `OwnerID` | `Long` | ✓ | 使用者的 Telegram ID | | `EnableCc` | `Boolean` | ✓ | 是否启用 Cc 功能 | diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index c1a9c90..ce2837a 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -13,7 +13,7 @@ private static async Task OwnerReplying(Update update) var link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); if (link != null && !link.IsFromOwner) { - Log($"Selected message is forwarded anonymously from {link.TGUser.Id}, fixing user information from database.", "BOT"); + Log($"Found corresponding message link for message #{update.Message.ReplyToMessage.MessageId}, which was actually forwarded from {link.TGUser.Id}, patching user information from database...", "BOT"); update.Message.ReplyToMessage.ForwardFrom = link.TGUser; } if ((update.Message.ReplyToMessage.ForwardFrom == null) && (update.Message.Text.ToLower() != "/retract")) diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index faa4bef..dbfaae0 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -8,6 +8,7 @@ public sealed partial class ConfObj { public ConfObj() { + Minify = false; APIKey = ""; OwnerUID = -1; EnableCc = false; diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index a2dfd51..2b81f77 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -6,6 +6,7 @@ public static partial class Conf { public sealed partial class ConfObj { + public bool Minify { get; set; } public string APIKey { get; set; } public long OwnerUID { get; set; } public bool EnableCc { get; set; } diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index 89ef002..320b526 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -8,7 +8,7 @@ public static partial class Conf { public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. - string text = JsonConvert.SerializeObject(Vars.CurrentConf, Formatting.Indented); + string text = JsonConvert.SerializeObject(Vars.CurrentConf, Vars.CurrentConf.Minify ? Formatting.None : Formatting.Indented); await System.IO.File.WriteAllTextAsync(Vars.ConfFile, text).ConfigureAwait(false); if (isAutoSave) { From 512bc4d9413251e85ed0c4ea4f5f30474a757f55 Mon Sep 17 00:00:00 2001 From: Elepover Date: Tue, 28 Apr 2020 22:41:26 +0800 Subject: [PATCH 24/39] fix lowercase culture problem, and some refactoring --- .../BotProcess/BotProcess.OwnerReplying.cs | 2 +- pmcenter/Configurations/Conf.GetConf.cs | 3 +- pmcenter/Configurations/Conf.InitConf.cs | 5 +- pmcenter/Configurations/Conf.SaveConf.cs | 3 +- pmcenter/Program.cs | 8 +-- pmcenter/Setup.cs | 50 +++++++++---------- 6 files changed, 38 insertions(+), 33 deletions(-) diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index ce2837a..4910dee 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -16,7 +16,7 @@ private static async Task OwnerReplying(Update update) Log($"Found corresponding message link for message #{update.Message.ReplyToMessage.MessageId}, which was actually forwarded from {link.TGUser.Id}, patching user information from database...", "BOT"); update.Message.ReplyToMessage.ForwardFrom = link.TGUser; } - if ((update.Message.ReplyToMessage.ForwardFrom == null) && (update.Message.Text.ToLower() != "/retract")) + if ((update.Message.ReplyToMessage.ForwardFrom == null) && (update.Message.Text.ToLowerInvariant() != "/retract")) { // The owner is replying to bot messages. (no forwardfrom) _ = await Vars.Bot.SendTextMessageAsync( diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index 317901b..eb2b90d 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Threading.Tasks; using Newtonsoft.Json; @@ -7,7 +8,7 @@ public static partial class Conf { public static async Task GetConf(string filename) { - var settingsText = await System.IO.File.ReadAllTextAsync(filename).ConfigureAwait(false); + var settingsText = await File.ReadAllTextAsync(filename).ConfigureAwait(false); return JsonConvert.DeserializeObject(settingsText); } } diff --git a/pmcenter/Configurations/Conf.InitConf.cs b/pmcenter/Configurations/Conf.InitConf.cs index 82d4cad..55d6d33 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Threading.Tasks; using static pmcenter.Methods.Logging; @@ -9,7 +10,7 @@ public static partial class Conf public static async Task InitConf() { Log("Checking configurations file's integrity...", "CONF"); - if (!System.IO.File.Exists(Vars.ConfFile)) + if (!File.Exists(Vars.ConfFile)) { // STEP 1, DETECT EXISTENCE. Log("Configurations file not found. Creating...", "CONF", LogLevel.Warning); Vars.CurrentConf = new ConfObj(); @@ -25,7 +26,7 @@ public static async Task InitConf() { Log($"Error! {ex}", "CONF", LogLevel.Error); Log("Moving old configurations file to \"pmcenter.json.bak\"...", "CONF", LogLevel.Warning); - System.IO.File.Move(Vars.ConfFile, Vars.ConfFile + ".bak"); + File.Move(Vars.ConfFile, Vars.ConfFile + ".bak"); Vars.CurrentConf = new ConfObj(); _ = await SaveConf(true).ConfigureAwait(false); // Then the app will exit, do nothing. } diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index 320b526..0a12926 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Threading.Tasks; using Newtonsoft.Json; using static pmcenter.Methods.Logging; @@ -9,7 +10,7 @@ public static partial class Conf public static async Task SaveConf(bool isInvalid = false, bool isAutoSave = false) { // DO NOT HANDLE ERRORS HERE. string text = JsonConvert.SerializeObject(Vars.CurrentConf, Vars.CurrentConf.Minify ? Formatting.None : Formatting.Indented); - await System.IO.File.WriteAllTextAsync(Vars.ConfFile, text).ConfigureAwait(false); + await File.WriteAllTextAsync(Vars.ConfFile, text).ConfigureAwait(false); if (isAutoSave) { Log("Autosave complete.", "CONF"); diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index ee9f535..d844860 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -183,11 +183,11 @@ public static async Task MainAsync(string[] args) List proxyInfoList = new List(); foreach (var proxyInfo in Vars.CurrentConf.Socks5Proxies) { - ProxyInfo ProxyInfo = new ProxyInfo(proxyInfo.ServerName, + var newProxyInfo = new ProxyInfo(proxyInfo.ServerName, proxyInfo.ServerPort, proxyInfo.Username, proxyInfo.ProxyPass); - proxyInfoList.Add(ProxyInfo); + proxyInfoList.Add(newProxyInfo); } var proxy = new HttpToSocks5Proxy(proxyInfoList.ToArray()) { @@ -225,7 +225,7 @@ public static async Task MainAsync(string[] args) { _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_BotStarted - .Replace("$1", Math.Round(Vars.StartSW.Elapsed.TotalSeconds, 2) + "s"), + .Replace("$1", $"{Math.Round(Vars.StartSW.Elapsed.TotalSeconds, 2)}s"), ParseMode.Markdown, false, false).ConfigureAwait(false); @@ -250,6 +250,7 @@ public static async Task MainAsync(string[] args) false, false).ConfigureAwait(false); Vars.CurrentConf.DisableNetCore3Check = true; + _ = await SaveConf(false, true); } } catch (Exception ex) @@ -276,6 +277,7 @@ public static async Task MainAsync(string[] args) { Log("Advanced startup time analysis is on, printing startup checkpoints..."); PrintCheckPoints(); + _checkPoints.Clear(); } Log("==> All finished!"); diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index 9ce520a..37058af 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -16,21 +16,21 @@ namespace pmcenter { public static class Setup { - private static readonly Conf.ConfObj NewConf = new Conf.ConfObj(); - private static TelegramBotClient TestBot; - private static bool IsUIDReceived = false; - private static long ReceivedUID = -1; - private static string Nickname = ""; + private static readonly Conf.ConfObj newConf = new Conf.ConfObj(); + private static TelegramBotClient testBot; + private static bool isUidReceived = false; + private static long receivedUid = -1; + private static string nickname = ""; private static void OnUpdate(object sender, UpdateEventArgs e) { Say("Update received."); Say(".. Processing..."); - if (!IsUIDReceived) + if (!isUidReceived) { - IsUIDReceived = true; - ReceivedUID = e.Update.Message.From.Id; - Nickname = string.IsNullOrEmpty(e.Update.Message.From.LastName) ? e.Update.Message.From.FirstName : $"{e.Update.Message.From.FirstName} {e.Update.Message.From.LastName}"; - TestBot.StopReceiving(); + isUidReceived = true; + receivedUid = e.Update.Message.From.Id; + nickname = string.IsNullOrEmpty(e.Update.Message.From.LastName) ? e.Update.Message.From.FirstName : $"{e.Update.Message.From.FirstName} {e.Update.Message.From.LastName}"; + testBot.StopReceiving(); } } @@ -87,7 +87,7 @@ public static async Task SetupWizard() Say(" Done!"); } SIn($"Saving configurations to {Vars.ConfFile}..."); - Vars.CurrentConf = NewConf; + Vars.CurrentConf = newConf; _ = await Conf.SaveConf().ConfigureAwait(false); Say(" Done!"); if (File.Exists(Vars.LangFile)) @@ -135,8 +135,8 @@ private static async Task SetAPIKey() SIn($".. Testing API Key: {key}..."); try { - TestBot = new TelegramBotClient(key); - if (!await TestBot.TestApiAsync().ConfigureAwait(false)) + testBot = new TelegramBotClient(key); + if (!await testBot.TestApiAsync().ConfigureAwait(false)) { throw (new ArgumentException("API Key is not valid.")); } @@ -147,7 +147,7 @@ private static async Task SetAPIKey() Say($" Invalid API Key: {ex.Message}"); goto EnterKey; } - NewConf.APIKey = key; + newConf.APIKey = key; Say(" Done!"); } private static async Task SetUID() @@ -162,17 +162,17 @@ private static async Task SetUID() if (uid.ToLower() == "auto") { Say(".. Preparing for automatic UID detection..."); - TestBot.OnUpdate += OnUpdate; - TestBot.StartReceiving(new UpdateType[] { UpdateType.Message }); + testBot.OnUpdate += OnUpdate; + testBot.StartReceiving(new UpdateType[] { UpdateType.Message }); Say("Say something to your bot on Telegram. We'll detect your UID automatically."); - while (!IsUIDReceived) + while (!isUidReceived) { Thread.Sleep(200); } - _ = await TestBot.SendTextMessageAsync(ReceivedUID, $"👋 *Hello my owner!* Your UID `{ReceivedUID}` is now being saved.", ParseMode.Markdown); - Say($"Hello, [{Nickname}]! Your UID has been detected as {ReceivedUID}."); - SIn($".. Saving UID: {ReceivedUID}..."); - NewConf.OwnerUID = ReceivedUID; + _ = await testBot.SendTextMessageAsync(receivedUid, $"👋 *Hello my owner!* Your UID `{receivedUid}` is now being saved.", ParseMode.Markdown); + Say($"Hello, [{nickname}]! Your UID has been detected as {receivedUid}."); + SIn($".. Saving UID: {receivedUid}..."); + newConf.OwnerUID = receivedUid; Say(" Done!"); } else @@ -181,7 +181,7 @@ private static async Task SetUID() { long newUid = long.Parse(uid); SIn($".. Saving UID: {newUid}..."); - NewConf.OwnerUID = newUid; + newConf.OwnerUID = newUid; Say(" Done!"); } catch (Exception ex) @@ -199,7 +199,7 @@ private static void SetNotifPrefs() SIn("=> Mute notifications? [y/N]: "); string muteNotif = Console.ReadLine(); SIn(".. Saving..."); - NewConf.DisableNotifications = muteNotif.ToLower() != "y" ? true : false; + newConf.DisableNotifications = muteNotif.ToLower() != "y" ? true : false; Say(" Done!"); } private static void SetAutoBanPrefs() @@ -210,7 +210,7 @@ private static void SetAutoBanPrefs() SIn("=> Automatically ban flooding users? [Y/n]: "); string autoBan = Console.ReadLine(); SIn(".. Saving..."); - NewConf.AutoBan = autoBan.ToLower() != "n" ? true : false; + newConf.AutoBan = autoBan.ToLower() != "n" ? true : false; Say(" Done!"); } private static void SetMessageLinks() @@ -223,7 +223,7 @@ private static void SetMessageLinks() SIn("=> Enable message links? [Y/n]: "); string enableMsgLinks = Console.ReadLine(); SIn(".. Saving..."); - NewConf.EnableMsgLink = enableMsgLinks.ToLower() != "n" ? true : false; + newConf.EnableMsgLink = enableMsgLinks.ToLower() != "n" ? true : false; Say(" Done!"); } } From ae5d06caf46ccc3277172364354b254aafdfe5cf Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 18:47:01 +0800 Subject: [PATCH 25/39] automatic updates are currently not available through GitHub releases --- .../Methods.UpdateHelper.IsNewerVersionAvailable.cs | 6 ++++++ pmcenter/Vars.cs | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index c79f2e1..b92e133 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -1,4 +1,5 @@ using System; +using static pmcenter.Methods.Logging; namespace pmcenter { @@ -8,6 +9,11 @@ public static partial class UpdateHelper { public static bool IsNewerVersionAvailable(Update2 CurrentUpdate) { + if (Vars.GitHubReleases) + { + Log("This distribution of pmcenter is released via GitHub releases. Automatic updates are not supported yet.", LogLevel.Warning); + return false; + } var currentVersion = Vars.AppVer; var currentLatest = new Version(CurrentUpdate.Latest); if (currentLatest > currentVersion) diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 1690589..47b16fa 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -5,6 +5,7 @@ */ //#define BUILT_FOR_GITHUB_RELEASES +//#define SELFCONTAINED using System; using System.Collections.Generic; @@ -43,7 +44,7 @@ public static class Vars #else public readonly static bool SelfContained = false; #endif - public readonly static long AnonymousChannelId = -1001228946795; + // public readonly static long AnonymousChannelId = -1001228946795; // public readonly static string AnonymousChannelTitle = "a user"; // public readonly static string AnonymousChannelUsername = "HiddenSender"; From 67d3713f37066d63885bb367a13571ccf97fd0d7 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 19:18:18 +0800 Subject: [PATCH 26/39] add R2R image option in csproj --- pmcenter/pmcenter.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pmcenter/pmcenter.csproj b/pmcenter/pmcenter.csproj index 8eebe17..36c3a6c 100644 --- a/pmcenter/pmcenter.csproj +++ b/pmcenter/pmcenter.csproj @@ -4,7 +4,9 @@ Exe netcoreapp3.1 pmcenter.Program + true + From 828ef60d08af14ba952067d08267654afc47c825 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 19:27:12 +0800 Subject: [PATCH 27/39] revert R2R --- pmcenter/pmcenter.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/pmcenter/pmcenter.csproj b/pmcenter/pmcenter.csproj index 36c3a6c..bc377f6 100644 --- a/pmcenter/pmcenter.csproj +++ b/pmcenter/pmcenter.csproj @@ -4,7 +4,6 @@ Exe netcoreapp3.1 pmcenter.Program - true From c990b5d3adcdff162165d081a0152292524cb639 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 20:15:39 +0800 Subject: [PATCH 28/39] fix null exception when detailed logging is on --- pmcenter/BotProcess/BotProcess.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/BotProcess/BotProcess.cs b/pmcenter/BotProcess/BotProcess.cs index aa68059..b3bf1df 100644 --- a/pmcenter/BotProcess/BotProcess.cs +++ b/pmcenter/BotProcess/BotProcess.cs @@ -61,7 +61,7 @@ public static async void OnUpdate(object sender, UpdateEventArgs e) try { if (e == null) return; - if (Vars.CurrentConf.DetailedMsgLogging) + if (Vars.CurrentConf.DetailedMsgLogging && e.Update.Type == UpdateType.Message) Log($"OnUpdate() triggered: UpdType: {e.Update.Type}, UpdID: {e.Update.Id}, ChatId: {e.Update.Message.Chat.Id}, Username: {e.Update.Message.Chat.Username}, FromID: {e.Update.Message.From.Id}, FromUsername: {e.Update.Message.From.Username}", "BOT-DETAILED", LogLevel.Info); switch (e.Update.Type) From 65d74043fcd716247cdda564bebdb903054c572f Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 20:29:22 +0800 Subject: [PATCH 29/39] update checkpoint time calculation --- pmcenter/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index d844860..deae8b4 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -28,7 +28,7 @@ private static void PrintCheckPoints() { Log("Check points recorded during startup:"); for (int i = 1; i < _checkPoints.Count; i++) - Log($"#{i}: {(double)(_checkPoints[i].Tick - _checkPoints[i - 1].Tick) / 10000}ms: {_checkPoints[i].Name} at {(double)_checkPoints[i].Tick / 10000}ms"); + Log($"#{i}: {new TimeSpan(_checkPoints[i].Tick - _checkPoints[i - 1].Tick).TotalMilliseconds}ms: {_checkPoints[i].Name} at {new TimeSpan(_checkPoints[i].Tick).TotalMilliseconds}ms"); } public static void Main(string[] args) From 5667188967faa2b49bdac4f187f8609fffc7989a Mon Sep 17 00:00:00 2001 From: Elepover Date: Sat, 2 May 2020 21:05:50 +0800 Subject: [PATCH 30/39] fix hangup problem when exiting --- pmcenter/EventHandlers/CtrlCHandler.cs | 2 +- pmcenter/Methods/Methods.ExitApp.cs | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/pmcenter/EventHandlers/CtrlCHandler.cs b/pmcenter/EventHandlers/CtrlCHandler.cs index ea162b0..8c9dd63 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -8,6 +8,7 @@ public static partial class EventHandlers { public static async void CtrlCHandler(object sender, ConsoleCancelEventArgs e) { + if (e != null) e.Cancel = true; Vars.CtrlCCounter++; if (Vars.CtrlCCounter > 3) { @@ -18,7 +19,6 @@ public static async void CtrlCHandler(object sender, ConsoleCancelEventArgs e) if (Vars.CurrentConf.IgnoreKeyboardInterrupt) { Log("Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", LogLevel.Warning); - if (e != null) e.Cancel = true; return; } Vars.IsCtrlCHandled = true; diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index 3fca1ca..7d9e25c 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -20,13 +20,10 @@ public static async Task ExitApp(int code) Vars.IsShuttingDown = true; Log("Saving configurations..."); await Conf.SaveConf(); - if (Vars.IsPerformanceTestExecuting) + while (Vars.IsPerformanceTestExecuting) { - while (!Vars.IsPerformanceTestExecuting) - { - if (sw.ElapsedMilliseconds >= 10000) Environment.Exit(16); - Thread.Sleep(50); - } + if (sw.ElapsedMilliseconds >= 10000) Environment.Exit(16); + Thread.Sleep(50); } Log("[OK] Shut down performance tester."); From 4b9d0c0165e72b9e89ebbc9da3f38a858140c6ec Mon Sep 17 00:00:00 2001 From: Elepover Date: Thu, 7 May 2020 10:44:46 +0800 Subject: [PATCH 31/39] add an option to disable language version mismatch check --- README.md | 1 + README_zh.md | 1 + pmcenter/BotCommands/ReadConfigCommand.cs | 2 ++ pmcenter/Configurations/Conf.ConfObj.New.cs | 1 + pmcenter/Configurations/Conf.ConfObj.cs | 1 + pmcenter/Program.cs | 28 +++++++++++---------- 6 files changed, 21 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a6d6401..b69ca62 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Or, use setup wizard: | `AnalyzeStartupTime` | `Boolean` | ✓ | Turn this on to show detailed analysis of startup time. | | `SkipAPIKeyVerification` | `Boolean` | ✓ | Turn this on to skip API Key verification on startup. | | `EnableActions` | `Boolean` | ✓ | Turn this on to enable message actions. | +| `CheckLangVersionMismatch` | `Boolean` | ✓ | Check language version and send alert on startup. | | `Statistics` | `Stats` | ✕ | Statistics data. | | `IgnoredLogModules` | `Array` | ✓ | List of ignored log modules. Selected modules will not generate output to console. | | `Socks5Proxies` | `Array` | ✓ | List of SOCKS5 proxies. | diff --git a/README_zh.md b/README_zh.md index 2083c51..91c0c36 100644 --- a/README_zh.md +++ b/README_zh.md @@ -183,6 +183,7 @@ docker run -d -v $(pwd)/pmcenter.json:/opt/pmcenter/pmcenter.json --restart alwa | `AnalyzeStartupTime` | `Boolean` | ✓ | 启用以显示细化的启动时间分析 | | `SkipAPIKeyVerification` | `Boolean` | ✓ | 启用以跳过启动时的 API 密钥校验 | | `EnableActions` | `Boolean` | ✓ | 启动以启用消息操作面版 | +| `CheckLangVersionMismatch` | `Boolean` | ✓ | 在启动时检测语言文件版本 | | `Statistics` | `Stats` | ✕ | 统计数据 | | `IgnoredLogModules` | `Array` | ✓ | 忽略的日志模块列表,这些模块将不会输出信息到控制台 | | `Socks5Proxies` | `Array` | ✓ | SOCKS5 代理列表 | diff --git a/pmcenter/BotCommands/ReadConfigCommand.cs b/pmcenter/BotCommands/ReadConfigCommand.cs index e7c6977..3b1746b 100644 --- a/pmcenter/BotCommands/ReadConfigCommand.cs +++ b/pmcenter/BotCommands/ReadConfigCommand.cs @@ -2,6 +2,7 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using static pmcenter.Methods.Logging; namespace pmcenter.Commands { @@ -15,6 +16,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { _ = await Conf.ReadConf().ConfigureAwait(false); _ = await Lang.ReadLang().ConfigureAwait(false); + Log("Configurations and locale files have been reloaded from disk", "BOT"); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfigReloaded, diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index dbfaae0..3cc02ef 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -46,6 +46,7 @@ public ConfObj() AnalyzeStartupTime = false; SkipAPIKeyVerification = false; EnableActions = false; + CheckLangVersionMismatch = true; Statistics = new Stats(); IgnoredLogModules = new List(); Socks5Proxies = new List(); diff --git a/pmcenter/Configurations/Conf.ConfObj.cs b/pmcenter/Configurations/Conf.ConfObj.cs index 2b81f77..2cae1e0 100644 --- a/pmcenter/Configurations/Conf.ConfObj.cs +++ b/pmcenter/Configurations/Conf.ConfObj.cs @@ -44,6 +44,7 @@ public sealed partial class ConfObj public bool AnalyzeStartupTime { get; set; } public bool SkipAPIKeyVerification { get; set; } public bool EnableActions { get; set; } + public bool CheckLangVersionMismatch { get; set; } public Stats Statistics { get; set; } public List IgnoredLogModules { get; set; } public List Socks5Proxies { get; set; } diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index deae8b4..d6341a5 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -110,9 +110,7 @@ public static async Task MainAsync(string[] args) Check("Custom locale loaded"); if (Vars.CurrentLang == null) - { throw new InvalidOperationException("Language file is empty."); - } if (Vars.RestartRequired) { @@ -203,10 +201,13 @@ public static async Task MainAsync(string[] args) Check("Bot initialized"); Log("Validating API Key..."); - if (!Vars.CurrentConf.SkipAPIKeyVerification) _ = await Vars.Bot.TestApiAsync().ConfigureAwait(false); + if (Vars.CurrentConf.SkipAPIKeyVerification) + Log("API Key validation skipped", LogLevel.Warning); + else + _ = await Vars.Bot.TestApiAsync().ConfigureAwait(false); Check("API Key test passed"); - Log("Hooking event processors..."); + Log("Hooking message processors..."); Vars.Bot.OnUpdate += BotProcess.OnUpdate; Log("Starting receiving..."); Vars.Bot.StartReceiving(new[] @@ -257,19 +258,20 @@ public static async Task MainAsync(string[] args) { Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.Warning); } - Check(".NET Core version check complete"); + Check(".NET Core runtime version check complete"); // check language mismatch if (Vars.CurrentLang.TargetVersion != Vars.AppVer.ToString()) { - Log("Language version mismatch detected.", "CORE", LogLevel.Warning); - _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_LangVerMismatch - .Replace("$1", Vars.CurrentLang.TargetVersion) - .Replace("$2", Vars.AppVer.ToString()), - ParseMode.Markdown, - false, - false).ConfigureAwait(false); + Log("Language version mismatch detected", "CORE", LogLevel.Warning); + if (Vars.CurrentConf.CheckLangVersionMismatch) + _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_LangVerMismatch + .Replace("$1", Vars.CurrentLang.TargetVersion) + .Replace("$2", Vars.AppVer.ToString()), + ParseMode.Markdown, + false, + false).ConfigureAwait(false); } Check("Language version mismatch checked"); Check("Complete"); From 73f41510cac1ef795fc11fe9d3ef6eaf75dc3587 Mon Sep 17 00:00:00 2001 From: Elepover Date: Thu, 7 May 2020 11:52:10 +0800 Subject: [PATCH 32/39] change banning logics to prevent owner from being banned --- pmcenter/BotProcess/BotProcess.MessageRoute.cs | 6 ------ pmcenter/BotProcess/BotProcess.UserLogic.cs | 6 ++++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pmcenter/BotProcess/BotProcess.MessageRoute.cs b/pmcenter/BotProcess/BotProcess.MessageRoute.cs index 2bff76c..2f266cd 100644 --- a/pmcenter/BotProcess/BotProcess.MessageRoute.cs +++ b/pmcenter/BotProcess/BotProcess.MessageRoute.cs @@ -14,12 +14,6 @@ private static async Task MessageRoute(object sender, UpdateEventArgs e) if (update.Message.From.IsBot) return; if (update.Message.Chat.Type != ChatType.Private) return; - if (Methods.IsBanned(update.Message.From.Id)) - { - Log($"Restricting banned user from sending messages: {update.Message.From.FirstName} (@{update.Message.From.Username} / {(long)update.Message.From.Id})", "BOT"); - return; - } - Vars.CurrentConf.Statistics.TotalMessagesReceived += 1; if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) { diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 2133d18..e490056 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -31,6 +31,12 @@ private static async Task UserLogic(Update update) return; } + if (Methods.IsBanned(update.Message.From.Id)) + { + Log($"Restricting banned user from sending messages: {update.Message.From.FirstName} (@{update.Message.From.Username} / {(long)update.Message.From.Id})", "BOT"); + return; + } + // test text blacklist if (!string.IsNullOrEmpty(update.Message.Text) && IsKeywordBanned(update.Message.Text)) { From 89533e63dcc57305309cadc8d059b8db771d96e1 Mon Sep 17 00:00:00 2001 From: Elepover Date: Thu, 7 May 2020 12:04:47 +0800 Subject: [PATCH 33/39] some using refactoring --- pmcenter/BotCommands/EditConfCommand.cs | 2 +- pmcenter/BotProcess/BotProcess.MessageRoute.cs | 1 - pmcenter/BotProcess/BotProcess.UserLogic.cs | 1 - pmcenter/CommandLines/UpdateCmdLine.cs | 2 +- pmcenter/Configurations/Conf.GetConf.cs | 2 +- pmcenter/Configurations/Conf.SaveConf.cs | 2 +- pmcenter/Configurations/Lang.ReadLang.cs | 2 +- pmcenter/Configurations/Lang.SaveLang.cs | 2 +- .../Methods/Database/Checking/Methods.GetRateDataIndexByID.cs | 2 -- pmcenter/Methods/Database/Checking/Methods.IsBanned.cs | 1 - .../Database/Checking/Methods.IsOwnerRetractionAvailable.cs | 2 -- .../Methods/Database/Checking/Methods.IsRateDataTracking.cs | 2 -- .../UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs | 2 +- pmcenter/Program.cs | 4 ++-- pmcenter/Vars.cs | 4 ++-- 15 files changed, 11 insertions(+), 20 deletions(-) diff --git a/pmcenter/BotCommands/EditConfCommand.cs b/pmcenter/BotCommands/EditConfCommand.cs index 80c4ce5..1675385 100644 --- a/pmcenter/BotCommands/EditConfCommand.cs +++ b/pmcenter/BotCommands/EditConfCommand.cs @@ -1,7 +1,7 @@ +using Newtonsoft.Json; using System; using System.Threading; using System.Threading.Tasks; -using Newtonsoft.Json; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/pmcenter/BotProcess/BotProcess.MessageRoute.cs b/pmcenter/BotProcess/BotProcess.MessageRoute.cs index 2f266cd..c5d2373 100644 --- a/pmcenter/BotProcess/BotProcess.MessageRoute.cs +++ b/pmcenter/BotProcess/BotProcess.MessageRoute.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; using Telegram.Bot.Args; using Telegram.Bot.Types.Enums; -using static pmcenter.Methods.Logging; namespace pmcenter { diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index e490056..10bb554 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -1,5 +1,4 @@ using pmcenter.CallbackActions; -using System.Collections.Generic; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index 7d3d3f4..fd73875 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -using static pmcenter.Methods.UpdateHelper; using static pmcenter.Methods.Logging; +using static pmcenter.Methods.UpdateHelper; namespace pmcenter.CommandLines { diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index eb2b90d..985c356 100644 --- a/pmcenter/Configurations/Conf.GetConf.cs +++ b/pmcenter/Configurations/Conf.GetConf.cs @@ -1,6 +1,6 @@ +using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; -using Newtonsoft.Json; namespace pmcenter { diff --git a/pmcenter/Configurations/Conf.SaveConf.cs b/pmcenter/Configurations/Conf.SaveConf.cs index 0a12926..1a35dbc 100644 --- a/pmcenter/Configurations/Conf.SaveConf.cs +++ b/pmcenter/Configurations/Conf.SaveConf.cs @@ -1,6 +1,6 @@ +using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; -using Newtonsoft.Json; using static pmcenter.Methods.Logging; namespace pmcenter diff --git a/pmcenter/Configurations/Lang.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index 5e6fe5a..a9f5bfb 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -1,6 +1,6 @@ +using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; -using Newtonsoft.Json; namespace pmcenter { diff --git a/pmcenter/Configurations/Lang.SaveLang.cs b/pmcenter/Configurations/Lang.SaveLang.cs index 2f3f474..30d95ba 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -1,6 +1,6 @@ +using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; -using Newtonsoft.Json; using static pmcenter.Methods.Logging; namespace pmcenter diff --git a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs index df73e1d..0edb11c 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -1,5 +1,3 @@ -using static pmcenter.Conf; - namespace pmcenter { public static partial class Methods diff --git a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs index 2df238a..29bd75d 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -1,6 +1,5 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using static pmcenter.Conf; namespace pmcenter { diff --git a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs index 6cdaef3..a274430 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -1,5 +1,3 @@ -using static pmcenter.Conf; - namespace pmcenter { public static partial class Methods diff --git a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs index c66faf5..d89f5ea 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -1,5 +1,3 @@ -using static pmcenter.Conf; - namespace pmcenter { public static partial class Methods diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index bbf7b09..e954cda 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs @@ -1,6 +1,6 @@ +using Newtonsoft.Json; using System; using System.Threading.Tasks; -using Newtonsoft.Json; using static pmcenter.Methods.H2Helper; namespace pmcenter diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index d6341a5..974fdec 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -4,12 +4,12 @@ // Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). */ +using MihaZupan; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; -using MihaZupan; using Telegram.Bot; using Telegram.Bot.Types.Enums; using static pmcenter.Conf; @@ -34,7 +34,7 @@ private static void PrintCheckPoints() public static void Main(string[] args) { Vars.StartSW.Start(); - Console.WriteLine(Vars.ASCII); + Console.WriteLine(Vars.AsciiArt); Log("Main delegator activated!", "DELEGATOR"); Log($"Starting pmcenter, version {Vars.AppVer}. Channel: \"{Vars.CompileChannel}\"", "DELEGATOR"); if (Vars.GitHubReleases) diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index 47b16fa..dbc0337 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -19,8 +19,8 @@ namespace pmcenter { public static class Vars { - public readonly static string ASCII = " __ \n ____ ____ ___ ________ ____ / /____ _____\n / __ \\/ __ `__ \\/ ___/ _ \\/ __ \\/ __/ _ \\/ ___/\n / /_/ / / / / / / /__/ __/ / / / /_/ __/ / \n / .___/_/ /_/ /_/\\___/\\___/_/ /_/\\__/\\___/_/ \n/_/ "; - public readonly static Version AppVer = new Version("1.9.280.15"); + public readonly static string AsciiArt = " __ \n ____ ____ ___ ________ ____ / /____ _____\n / __ \\/ __ `__ \\/ ___/ _ \\/ __ \\/ __/ _ \\/ ___/\n / /_/ / / / / / / /__/ __/ / / / /_/ __/ / \n / .___/_/ /_/ /_/\\___/\\___/_/ /_/\\__/\\___/_/ \n/_/ "; + public readonly static Version AppVer = new Version("2.0.721.35"); public readonly static string AppExecutable = Assembly.GetExecutingAssembly().Location; public readonly static string AppDirectory = Path.GetDirectoryName(AppExecutable); public static string ConfFile = Path.Combine(AppDirectory, "pmcenter.json"); From c469fc734f2c4a8179bc326a1850fe5b62d9ea9b Mon Sep 17 00:00:00 2001 From: Elepover Date: Sun, 10 May 2020 13:03:37 +0800 Subject: [PATCH 34/39] fix switchlangcode resolving exception --- pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs index 5b6b4bf..51d59c7 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -11,7 +11,7 @@ public static partial class H2Helper public static async Task DownloadFileAsync(Uri uri, string filename) { var bytes = await GetBytesAsync(uri).ConfigureAwait(false); - var fileStream = File.OpenWrite(filename); + var fileStream = File.Create(filename); await fileStream.WriteAsync(bytes).ConfigureAwait(false); await fileStream.FlushAsync(); fileStream.Close(); From 5411ed3b4d860e65efca7ab99d8d63b80110c575 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sun, 10 May 2020 13:45:55 +0800 Subject: [PATCH 35/39] update updating manifest --- locales/pmcenter_locale_en.json | 2 +- locales/pmcenter_locale_zh.json | 2 +- locales/pmcenter_locale_zh.meow.json | 2 +- locales/pmcenter_locale_zh.tw.json | 2 +- updateinfo.json | 2 +- updateinfo2.json | 16 ++++++++-------- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/locales/pmcenter_locale_en.json b/locales/pmcenter_locale_en.json index e4b64fd..b95649e 100644 --- a/locales/pmcenter_locale_en.json +++ b/locales/pmcenter_locale_en.json @@ -1,5 +1,5 @@ { - "TargetVersion": "1.9.280.15", + "TargetVersion": "2.0.2.0", "LangCode": "en.imported", "LanguageNameInEnglish": "English", "LanguageNameInNative": "English", diff --git a/locales/pmcenter_locale_zh.json b/locales/pmcenter_locale_zh.json index 18a9a99..23df2fc 100644 --- a/locales/pmcenter_locale_zh.json +++ b/locales/pmcenter_locale_zh.json @@ -1,5 +1,5 @@ { - "TargetVersion": "1.9.280.15", + "TargetVersion": "2.0.2.0", "LangCode": "zh.simplified", "LanguageNameInEnglish": "Chinese (Simplified)", "LanguageNameInNative": "简体中文", diff --git a/locales/pmcenter_locale_zh.meow.json b/locales/pmcenter_locale_zh.meow.json index ea84f15..5f8d39d 100644 --- a/locales/pmcenter_locale_zh.meow.json +++ b/locales/pmcenter_locale_zh.meow.json @@ -1,5 +1,5 @@ { - "TargetVersion": "1.9.280.15", + "TargetVersion": "2.0.2.0", "LangCode": "zh.meow", "LanguageNameInEnglish": "Chinese (Meow)", "LanguageNameInNative": "喵体中文", diff --git a/locales/pmcenter_locale_zh.tw.json b/locales/pmcenter_locale_zh.tw.json index ee85181..ecda77e 100644 --- a/locales/pmcenter_locale_zh.tw.json +++ b/locales/pmcenter_locale_zh.tw.json @@ -1,5 +1,5 @@ { - "TargetVersion": "1.9.280.15", + "TargetVersion": "2.0.2.0", "LangCode": "zh.tw", "LanguageNameInEnglish": "Chinese (Traditional, Taiwan)", "LanguageNameInNative": "繁體中文(台灣)", diff --git a/updateinfo.json b/updateinfo.json index 7f5e4ee..9bf363e 100644 --- a/updateinfo.json +++ b/updateinfo.json @@ -1,5 +1,5 @@ { - "Latest": "1.9.1.271", + "Latest": "2.0.2.0", "Details": "`If you're using pmcenter `1.7.93.230` or older, you would only see this update message in the future but you could still upgrade to the latest version at any time.`", "UpdateLevel": 1 } \ No newline at end of file diff --git a/updateinfo2.json b/updateinfo2.json index 3402047..de4ad79 100644 --- a/updateinfo2.json +++ b/updateinfo2.json @@ -1,9 +1,9 @@ { - "Latest": "1.9.280.15", + "Latest": "2.0.2.0", "UpdateLevel": 1, "UpdateCollection": [ { - "Details": "[i] This is the final update before pmcenter v2 arrives.\n[+] Added .NET Core Runtime version check.\n[+] Added Ctrl-C event handler.\n[/] Updated Setup Wizard.\n[+] Updated exiting mechanism.", + "Details": "`*Welcome to pmcenter 2.0!*\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n`[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable`", "LangCode": [ "en.imported", "en.integrated" @@ -12,7 +12,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "[i] 这是 pmcenter v2 更新前的最后一次更新。\n[+] 添加 .NET Core 运行时版本检查。\n[+] 添加 Ctrl-C 事件处理器。\n[/] 更新了设置向导。\n[+] 全新的退出机制。", + "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", "LangCode": [ "zh.simplified" ], @@ -20,7 +20,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "[i] 这是 pmcenter v2 更新前的最后一次更新。\n[+] 添加 .NET Core 运行时版本检查。\n[+] 添加 Ctrl-C 事件处理器。\n[/] 更新了设置向导。\n[+] 全新的退出机制。", + "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", "LangCode": [ "zh.meow" ], @@ -28,7 +28,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "[i] 這是 pmcenter v2 更新前的最後一次更新。\n[+] 新增 .NET Core 運行時版本檢查。\n[+] 新增 Ctrl-C 事件處理器。\n[/] 更新了設置向導。\n[+] 全新的退出機制。", + "Details": "`*歡迎使用 pmcenter 2.0!*\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n`[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告`", "LangCode": [ "zh.tw" ], @@ -36,7 +36,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "[i] This is the final update before pmcenter v2 arrives.\n[+] Added .NET Core Runtime version check.\n[+] Added Ctrl-C event handler.\n[/] Updated Setup Wizard.\n[+] Updated exiting mechanism.", + "Details": "`*Welcome to pmcenter 2.0!*\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n`[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable`", "LangCode": [ "en.imported", "en.integrated" @@ -45,7 +45,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-lazer-update" }, { - "Details": "[i] 这是 pmcenter v2 更新前的最后一次更新。\n[+] 添加 .NET Core 运行时版本检查。\n[+] 添加 Ctrl-C 事件处理器。\n[/] 更新了设置向导。\n[+] 全新的退出机制。", + "Details": "`*歡迎使用 pmcenter 2.0!*\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n`[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告`", "LangCode": [ "zh.simplified" ], @@ -53,7 +53,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-lazer-update" }, { - "Details": "[i] 这是 pmcenter v2 更新前的最后一次更新。\n[+] 添加 .NET Core 运行时版本检查。\n[+] 添加 Ctrl-C 事件处理器。\n[/] 更新了设置向导。\n[+] 全新的退出机制。", + "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", "LangCode": [ "zh.meow" ], From febe615056a6c270c3e895e24345801892f06b91 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sun, 10 May 2020 13:55:39 +0800 Subject: [PATCH 36/39] update manifesrt --- updateinfo2.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/updateinfo2.json b/updateinfo2.json index de4ad79..fdd52a3 100644 --- a/updateinfo2.json +++ b/updateinfo2.json @@ -3,7 +3,7 @@ "UpdateLevel": 1, "UpdateCollection": [ { - "Details": "`*Welcome to pmcenter 2.0!*\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n`[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable`", + "Details": "Welcome to pmcenter 2.0!\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable", "LangCode": [ "en.imported", "en.integrated" @@ -12,7 +12,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", + "Details": "欢迎使用 pmcenter 2.0!\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告", "LangCode": [ "zh.simplified" ], @@ -20,7 +20,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", + "Details": "欢迎使用 pmcenter 2.0!\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告", "LangCode": [ "zh.meow" ], @@ -28,7 +28,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "`*歡迎使用 pmcenter 2.0!*\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n`[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告`", + "Details": "歡迎使用 pmcenter 2.0!\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告", "LangCode": [ "zh.tw" ], @@ -36,7 +36,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-update" }, { - "Details": "`*Welcome to pmcenter 2.0!*\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n`[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable`", + "Details": "Welcome to pmcenter 2.0!\n\npmcenter now depends on .NET Core 3.1, with these enhancements and new features:\n[/] Backend code refactor\n[/] Now pmcenter turns on Message Links by default\n[+] NuGet package updates\n[+] HTTP/2 protocol support\n[+] Dices & darts support\n[+] Inline keyboard actions support\n[+] R2R + AOT packages available via GitHub releases\n[+] Startup time analysis\n[+] Toggleable autosave\n[+] Better forwarding logics\n[+] JSON configuration files can be minified\n[+] Language version mismatch check is now toggleable", "LangCode": [ "en.imported", "en.integrated" @@ -45,7 +45,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-lazer-update" }, { - "Details": "`*歡迎使用 pmcenter 2.0!*\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n`[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告`", + "Details": "欢迎使用 pmcenter 2.0!\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告", "LangCode": [ "zh.simplified" ], @@ -53,7 +53,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-lazer-update" }, { - "Details": "`*欢迎使用 pmcenter 2.0!*\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n`[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告`", + "Details": "欢迎使用 pmcenter 2.0!\n\npmcenter 现依赖于 .NET Core 3.1,伴有以下更新内容:\n[/] 后端代码重构\n[/] 现在 pmcenter 默认启用消息链接\n[+] NuGet 包更新\n[+] HTTP/2 协议支持\n[+] 骰子 & 飞镖支持\n[+] 内联键盘操作支持\n[+] R2R + AOT 包现可通过 GitHub releases 获取\n[+] 启动时间分析\n[+] 自动保存命令\n[+] 优化的转发逻辑\n[+] JSON 配置文件现可最小化\n[+] 可开关语言文件版本匹配警告", "LangCode": [ "zh.meow" ], @@ -61,7 +61,7 @@ "UpdateArchiveAddress": "https://see.wtf/pmcenter-lazer-update" }, { - "Details": "[i] 這是 pmcenter v2 更新前的最後一次更新。\n[+] 新增 .NET Core 運行時版本檢查。\n[+] 新增 Ctrl-C 事件處理器。\n[/] 更新了設置向導。\n[+] 全新的退出機制。", + "Details": "歡迎使用 pmcenter 2.0!\n\npmcenter 現依賴於 .NET Core 3.1,隨附以下更新內容:\n[/] 後端程式碼重構\n[/] 默認啟用訊息連結\n[+] NuGet 軟件包更新\n[+] HTTP/2 協議支援\n[+] 骰子 & 飛鏢支援\n[+] 內聯鍵盤操作支援\n[+] R2R + AOT 包可透過 GitHub releases 獲取\n[+] 啟動時間分析\n[+] 自動儲存命令\n[+] 優化的轉發邏輯\n[+] JSON 配置文件現可最小化\n[+] 可開關語言文件版本匹配警告", "LangCode": [ "zh.tw" ], From 0c6885e0701afc69d155e64306cf1c00249da5b8 Mon Sep 17 00:00:00 2001 From: Elepover Date: Sun, 10 May 2020 14:01:32 +0800 Subject: [PATCH 37/39] update app version --- pmcenter/Vars.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index dbc0337..e461b47 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -20,7 +20,7 @@ namespace pmcenter public static class Vars { public readonly static string AsciiArt = " __ \n ____ ____ ___ ________ ____ / /____ _____\n / __ \\/ __ `__ \\/ ___/ _ \\/ __ \\/ __/ _ \\/ ___/\n / /_/ / / / / / / /__/ __/ / / / /_/ __/ / \n / .___/_/ /_/ /_/\\___/\\___/_/ /_/\\__/\\___/_/ \n/_/ "; - public readonly static Version AppVer = new Version("2.0.721.35"); + public readonly static Version AppVer = new Version("2.0.2.0"); public readonly static string AppExecutable = Assembly.GetExecutingAssembly().Location; public readonly static string AppDirectory = Path.GetDirectoryName(AppExecutable); public static string ConfFile = Path.Combine(AppDirectory, "pmcenter.json"); From 53db2297749d45885ac85172d3e1dc73ee8bbeaf Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Sun, 10 May 2020 15:00:18 +0800 Subject: [PATCH 38/39] fix variable naming --- pmcenter/BotProcess/BotProcess.OwnerCommand.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs index 445f733..73e72ed 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs @@ -37,9 +37,9 @@ private static async Task OwnerCommand(Update update) // Process locale. if (Vars.CurrentConf.EnableRepliedConfirmation) { - var ReplyToMessage = Vars.CurrentLang.Message_ReplySuccessful; - ReplyToMessage = ReplyToMessage.Replace("$1", $"[{Vars.CurrentConf.ContChatTarget}](tg://user?id={Vars.CurrentConf.ContChatTarget})"); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, ReplyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); + var replyToMessage = Vars.CurrentLang.Message_ReplySuccessful; + replyToMessage = replyToMessage.Replace("$1", $"[{Vars.CurrentConf.ContChatTarget}](tg://user?id={Vars.CurrentConf.ContChatTarget})"); + _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, replyToMessage, ParseMode.Markdown, false, false, update.Message.MessageId).ConfigureAwait(false); } Log($"Successfully passed owner's reply to UID: {Vars.CurrentConf.ContChatTarget}", "BOT"); return; From 3e0875826ffdeee47bd8572d41f11289ff303d12 Mon Sep 17 00:00:00 2001 From: U2FsdGVkX1 Date: Sun, 10 May 2020 18:02:13 +0800 Subject: [PATCH 39/39] update Permission --- pmcenter/BotCommands/DetectPermissionCommand.cs | 11 ++++++----- pmcenter/Methods/Methods.BoolStr.cs | 10 ---------- pmcenter/Methods/Methods.FlipBool.cs | 10 ---------- 3 files changed, 6 insertions(+), 25 deletions(-) delete mode 100644 pmcenter/Methods/Methods.BoolStr.cs delete mode 100644 pmcenter/Methods/Methods.FlipBool.cs diff --git a/pmcenter/BotCommands/DetectPermissionCommand.cs b/pmcenter/BotCommands/DetectPermissionCommand.cs index 4c64f63..9dab011 100644 --- a/pmcenter/BotCommands/DetectPermissionCommand.cs +++ b/pmcenter/BotCommands/DetectPermissionCommand.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; @@ -15,13 +16,13 @@ internal class DetectPermissionCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var confWritable = FlipBool((new FileInfo(Vars.ConfFile)).IsReadOnly); - var langWritable = FlipBool((new FileInfo(Vars.LangFile)).IsReadOnly); + var confWritable = !(new FileInfo(Vars.ConfFile)).IsReadOnly; + var langWritable = !(new FileInfo(Vars.LangFile)).IsReadOnly; _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfAccess - .Replace("$1", BoolStr(confWritable)) - .Replace("$2", BoolStr(langWritable)) + .Replace("$1", confWritable.ToString()) + .Replace("$2", langWritable.ToString()) , ParseMode.Markdown, false, diff --git a/pmcenter/Methods/Methods.BoolStr.cs b/pmcenter/Methods/Methods.BoolStr.cs deleted file mode 100644 index fbf0b95..0000000 --- a/pmcenter/Methods/Methods.BoolStr.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace pmcenter -{ - public static partial class Methods - { - public static string BoolStr(bool input) - { - return input ? "true" : "false"; - } - } -} diff --git a/pmcenter/Methods/Methods.FlipBool.cs b/pmcenter/Methods/Methods.FlipBool.cs deleted file mode 100644 index cc07831..0000000 --- a/pmcenter/Methods/Methods.FlipBool.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace pmcenter -{ - public static partial class Methods - { - public static bool FlipBool(bool input) - { - return input ? false : true; - } - } -}