diff --git a/pmcenter/.editorconfig b/pmcenter/.editorconfig index 5ec8616..abf6c5b 100644 --- a/pmcenter/.editorconfig +++ b/pmcenter/.editorconfig @@ -62,31 +62,31 @@ dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.non_field_members.required_modifiers = # 命名样式 dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case csharp_using_directive_placement = outside_namespace:silent csharp_style_expression_bodied_methods = false:silent @@ -161,31 +161,31 @@ dotnet_naming_rule.非字段成员_should_be_帕斯卡拼写法.style = 帕斯 dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.类型.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.类型.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.类型.required_modifiers = +dotnet_naming_symbols.类型.required_modifiers = dotnet_naming_symbols.非字段成员.applicable_kinds = property, event, method dotnet_naming_symbols.非字段成员.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected -dotnet_naming_symbols.非字段成员.required_modifiers = +dotnet_naming_symbols.非字段成员.required_modifiers = # 命名样式 dotnet_naming_style.以_i_开始.required_prefix = I -dotnet_naming_style.以_i_开始.required_suffix = -dotnet_naming_style.以_i_开始.word_separator = +dotnet_naming_style.以_i_开始.required_suffix = +dotnet_naming_style.以_i_开始.word_separator = dotnet_naming_style.以_i_开始.capitalization = pascal_case -dotnet_naming_style.帕斯卡拼写法.required_prefix = -dotnet_naming_style.帕斯卡拼写法.required_suffix = -dotnet_naming_style.帕斯卡拼写法.word_separator = +dotnet_naming_style.帕斯卡拼写法.required_prefix = +dotnet_naming_style.帕斯卡拼写法.required_suffix = +dotnet_naming_style.帕斯卡拼写法.word_separator = dotnet_naming_style.帕斯卡拼写法.capitalization = pascal_case -dotnet_naming_style.帕斯卡拼写法.required_prefix = -dotnet_naming_style.帕斯卡拼写法.required_suffix = -dotnet_naming_style.帕斯卡拼写法.word_separator = +dotnet_naming_style.帕斯卡拼写法.required_prefix = +dotnet_naming_style.帕斯卡拼写法.required_suffix = +dotnet_naming_style.帕斯卡拼写法.word_separator = dotnet_naming_style.帕斯卡拼写法.capitalization = pascal_case [*.{cs,vb}] diff --git a/pmcenter/BotCommands/AutoSaveCommand.cs b/pmcenter/BotCommands/AutoSaveCommand.cs index e52c4a4..75a4947 100644 --- a/pmcenter/BotCommands/AutoSaveCommand.cs +++ b/pmcenter/BotCommands/AutoSaveCommand.cs @@ -18,11 +18,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - var text = update.Message.Text; - var interval = 30000; + string text = update.Message.Text; + int interval = 30000; if (text.Contains(" ")) { - var command = text.Split(' ', 2)[1]; + string command = text.Split(' ', 2)[1]; if (command.ToLower() == "off") { Vars.CurrentConf.ConfSyncInterval = 0; @@ -32,30 +32,40 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) linkPreviewOptions: false, disableNotification: Vars.CurrentConf.DisableNotifications, replyParameters: update.Message.MessageId).ConfigureAwait(false); - if (Vars.SyncConf != null) Vars.SyncConf.Interrupt(); + 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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); if (interval < 5000) + { _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - Vars.CurrentLang.Message_AutoSaveIntervalTooShort.Replace("$1", interval.ToString()), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - if ((Vars.SyncConf == null) || !Vars.SyncConf.IsAlive) + Vars.CurrentLang.Message_AutoSaveIntervalTooShort.Replace("$1", interval.ToString()), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: 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) @@ -64,9 +74,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/BackupConfCommand.cs b/pmcenter/BotCommands/BackupConfCommand.cs index 4ea61e4..055af53 100644 --- a/pmcenter/BotCommands/BackupConfCommand.cs +++ b/pmcenter/BotCommands/BackupConfCommand.cs @@ -6,6 +6,7 @@ using Telegram.Bot.Types.Enums; using static pmcenter.Methods; using static pmcenter.Methods.Logging; +using File = System.IO.File; namespace pmcenter.Commands { @@ -17,16 +18,16 @@ internal class BackupConfCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var randomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; + string 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); + File.Copy(Vars.ConfFile, randomFilename); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_BackupComplete.Replace("$1", randomFilename), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/BanCommand.cs b/pmcenter/BotCommands/BanCommand.cs index ae66da3..56f9536 100644 --- a/pmcenter/BotCommands/BanCommand.cs +++ b/pmcenter/BotCommands/BanCommand.cs @@ -14,7 +14,10 @@ internal class BanCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - if (update.Message.ReplyToMessage == null || update.Message.ReplyToMessage.ForwardFrom == null) return false; + if (update.Message.ReplyToMessage == null || update.Message.ReplyToMessage.ForwardFrom == null) + { + return false; + } BanUser(update.Message.ReplyToMessage.ForwardFrom.Id); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); @@ -22,9 +25,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_UserBanned, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/BanIdCommand.cs b/pmcenter/BotCommands/BanIdCommand.cs index 45e17f4..fd64505 100644 --- a/pmcenter/BotCommands/BanIdCommand.cs +++ b/pmcenter/BotCommands/BanIdCommand.cs @@ -23,9 +23,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_UserBanned, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } catch (Exception ex) { @@ -33,10 +33,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.Message), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + return true; } } diff --git a/pmcenter/BotCommands/CatConfigCommand.cs b/pmcenter/BotCommands/CatConfigCommand.cs index 7af8218..d96350e 100644 --- a/pmcenter/BotCommands/CatConfigCommand.cs +++ b/pmcenter/BotCommands/CatConfigCommand.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -14,40 +15,39 @@ internal class CatConfigCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var text = SerializeCurrentConf(); - var texts = StrChunk(text, 1024); + string text = SerializeCurrentConf(); + List texts = StrChunk(text, 1024); if (texts.Count == 1) { _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_CurrentConf.Replace("$1", text), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } - else + + _ = await botClient.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_CurrentConf.Replace("$1", texts[0]), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + for (int i = 1; i < texts.Count; i++) { _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - Vars.CurrentLang.Message_CurrentConf.Replace("$1", texts[0]), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - for (int i = 1; i < texts.Count; i++) - { - _ = await botClient.SendTextMessageAsync( - update.Message.From.Id, - ($"`{texts[i]}`"), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - } - return true; + $"`{texts[i]}`", + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + + return true; } } } diff --git a/pmcenter/BotCommands/ChatCommand.cs b/pmcenter/BotCommands/ChatCommand.cs index 9c4aab1..34fa47e 100644 --- a/pmcenter/BotCommands/ChatCommand.cs +++ b/pmcenter/BotCommands/ChatCommand.cs @@ -34,8 +34,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) // no argument detected / use reply message instead if (update.Message.ReplyToMessage.ForwardFrom == null) { - throw (new ArgumentException("Cannot initiate Continued Conversation by channel posts.")); + throw new ArgumentException("Cannot initiate Continued Conversation by channel posts."); } + realTarget = update.Message.ReplyToMessage.ForwardFrom.Id; } @@ -50,15 +51,16 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) } else { - replacementText = $"[{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", replacementText), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + Vars.CurrentLang.Message_ContinuedChatEnabled.Replace("$1", replacementText), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } catch (Exception ex) @@ -67,9 +69,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/CheckUpdateCommand.cs b/pmcenter/BotCommands/CheckUpdateCommand.cs index 210f9a1..46a76a8 100644 --- a/pmcenter/BotCommands/CheckUpdateCommand.cs +++ b/pmcenter/BotCommands/CheckUpdateCommand.cs @@ -3,6 +3,7 @@ using Telegram.Bot; using Telegram.Bot.Types.Enums; using static pmcenter.Methods.UpdateHelper; +using Update = Telegram.Bot.Types.Update; namespace pmcenter.Commands { @@ -12,18 +13,18 @@ internal class CheckUpdateCommand : IBotCommand public string Prefix => "chkupdate"; - public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) + public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - var latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + Update2 latest = await CheckForUpdatesAsync().ConfigureAwait(false); + int 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 + string updateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", latest.Latest) .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) .Replace("$3", Methods.GetUpdateLevel(latest.UpdateLevel)); @@ -31,9 +32,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T update.Message.From.Id, updateString, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } else { @@ -45,22 +46,23 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T .Replace("$2", Vars.AppVer.ToString()) .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + return true; } catch (Exception ex) { - var errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.Message); + string errorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.Message); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, errorString, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/ClearMessageLinksCommand.cs b/pmcenter/BotCommands/ClearMessageLinksCommand.cs index dae3e46..78df1ef 100644 --- a/pmcenter/BotCommands/ClearMessageLinksCommand.cs +++ b/pmcenter/BotCommands/ClearMessageLinksCommand.cs @@ -21,9 +21,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_MsgLinksCleared, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/DetectPermissionCommand.cs b/pmcenter/BotCommands/DetectPermissionCommand.cs index eda05bd..82bf707 100644 --- a/pmcenter/BotCommands/DetectPermissionCommand.cs +++ b/pmcenter/BotCommands/DetectPermissionCommand.cs @@ -14,8 +14,8 @@ internal class DetectPermissionCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var confWritable = !(new FileInfo(Vars.ConfFile)).IsReadOnly; - var langWritable = !(new FileInfo(Vars.LangFile)).IsReadOnly; + bool confWritable = !new FileInfo(Vars.ConfFile).IsReadOnly; + bool langWritable = !new FileInfo(Vars.LangFile).IsReadOnly; _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfAccess @@ -23,9 +23,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) .Replace("$2", langWritable.ToString()) , parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/DonateCommand.cs b/pmcenter/BotCommands/DonateCommand.cs index 5aa6093..6e5cdc2 100644 --- a/pmcenter/BotCommands/DonateCommand.cs +++ b/pmcenter/BotCommands/DonateCommand.cs @@ -17,13 +17,14 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { return false; } + _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentConf.DonateString, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/EditConfCommand.cs b/pmcenter/BotCommands/EditConfCommand.cs index 64ab6db..74d373c 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; @@ -20,9 +20,9 @@ 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); + Log("Configurations received, applying...", "BOT"); + string confStr = update.Message.Text.Split(" ", 2)[1]; + Conf.ConfObj temp = JsonConvert.DeserializeObject(confStr); if (temp.APIKey != Vars.CurrentConf.APIKey) { Log("API Key has changed! Please restart pmcenter to apply the change.", "BOT", LogLevel.Warning); @@ -30,11 +30,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_APIKeyChanged, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); Vars.RestartRequired = true; } + if (temp.ConfSyncInterval == 0) { Log("ConfSync has been disabled, the worker thread will exit soon.", "BOT", LogLevel.Warning); @@ -42,20 +43,25 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) else if (Vars.CurrentConf.ConfSyncInterval == 0) { Log("The ConfSync feature has been enabled via configurations. Restarting thread...", "BOT"); - while (Vars.SyncConf.IsAlive) Thread.Sleep(100); + while (Vars.SyncConf.IsAlive) + { + Thread.Sleep(100); + } + Vars.SyncConf = new Thread(() => ThrSyncConf()); Vars.SyncConf.Start(); } + Vars.CurrentConf = temp; - Log("Applied! Saving to local disk...", "BOT", LogLevel.Info); + Log("Applied! Saving to local disk...", "BOT"); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfigUpdated, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } catch (Exception ex) { @@ -63,10 +69,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.Message), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + return true; } } diff --git a/pmcenter/BotCommands/GetStatsCommand.cs b/pmcenter/BotCommands/GetStatsCommand.cs index 9155a92..16e4978 100644 --- a/pmcenter/BotCommands/GetStatsCommand.cs +++ b/pmcenter/BotCommands/GetStatsCommand.cs @@ -15,14 +15,15 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - Vars.CurrentLang.Message_Stats.Replace("$1", Vars.CurrentConf.Statistics.TotalMessagesReceived.ToString()) - .Replace("$2", Vars.CurrentConf.Statistics.TotalForwardedToOwner.ToString()) - .Replace("$3", Vars.CurrentConf.Statistics.TotalForwardedFromOwner.ToString()) - .Replace("$4", Vars.CurrentConf.Statistics.TotalCommandsReceived.ToString()), + Vars.CurrentLang.Message_Stats + .Replace("$1", Vars.CurrentConf.Statistics.TotalMessagesReceived.ToString()) + .Replace("$2", Vars.CurrentConf.Statistics.TotalForwardedToOwner.ToString()) + .Replace("$3", Vars.CurrentConf.Statistics.TotalForwardedFromOwner.ToString()) + .Replace("$4", Vars.CurrentConf.Statistics.TotalCommandsReceived.ToString()), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/HelpCommand.cs b/pmcenter/BotCommands/HelpCommand.cs index ca9d9e5..4622676 100644 --- a/pmcenter/BotCommands/HelpCommand.cs +++ b/pmcenter/BotCommands/HelpCommand.cs @@ -17,9 +17,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_Help, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/InfoCommand.cs b/pmcenter/BotCommands/InfoCommand.cs index 1578b63..bc79a10 100644 --- a/pmcenter/BotCommands/InfoCommand.cs +++ b/pmcenter/BotCommands/InfoCommand.cs @@ -18,8 +18,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { return false; } - var targetMessage = update.Message.ReplyToMessage; - var sb = new StringBuilder("ℹ *Message Info*\n📩 *Sender*: ["); + + Message targetMessage = update.Message.ReplyToMessage; + StringBuilder sb = new StringBuilder("ℹ *Message Info*\n📩 *Sender*: ["); if (Vars.CurrentConf.UseUsernameInMsgInfo) { sb.Append(targetMessage.ForwardFrom.FirstName); @@ -30,6 +31,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { sb.Append("Here"); } + sb.Append("](tg://user?id="); sb.Append(targetMessage.ForwardFrom.Id); sb.Append(")\n👤 User ID: `"); @@ -43,7 +45,7 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) sb.Append("`"); sb.Append("\n\n➕ *Additional Info*"); - sb.Append("\n📼 Message Type: " + targetMessage.Type.ToString()); + sb.Append("\n📼 Message Type: " + targetMessage.Type); if (targetMessage.Document != null) { sb.Append("\n📛 File Name: `"); @@ -98,15 +100,17 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) 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._"); + + 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, sb.ToString(), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/PardonCommand.cs b/pmcenter/BotCommands/PardonCommand.cs index 767f097..89b2f9a 100644 --- a/pmcenter/BotCommands/PardonCommand.cs +++ b/pmcenter/BotCommands/PardonCommand.cs @@ -25,9 +25,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_UserPardoned, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/PardonIdCommand.cs b/pmcenter/BotCommands/PardonIdCommand.cs index 2428b52..8fb26e9 100644 --- a/pmcenter/BotCommands/PardonIdCommand.cs +++ b/pmcenter/BotCommands/PardonIdCommand.cs @@ -22,21 +22,22 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UserPardoned, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } catch (Exception ex) { _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.Message), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + return true; } } diff --git a/pmcenter/BotCommands/PerformCommand.cs b/pmcenter/BotCommands/PerformCommand.cs index 78a0f6e..aa92875 100644 --- a/pmcenter/BotCommands/PerformCommand.cs +++ b/pmcenter/BotCommands/PerformCommand.cs @@ -18,10 +18,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_Performance_Inited, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - var performanceChecker = new Thread(() => Methods.ThrPerform()); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + Thread performanceChecker = new Thread(() => Methods.ThrPerform()); performanceChecker.Start(); Thread.Sleep(1000); Vars.IsPerformanceTestEndRequested = true; @@ -29,14 +29,15 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { Thread.Sleep(500); } + Vars.PerformanceScore /= 1000000; _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_Performance_Results.Replace("$1", (Vars.PerformanceScore / 5) + "Mop/s"), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/PingCommand.cs b/pmcenter/BotCommands/PingCommand.cs index cab2a53..b06de01 100644 --- a/pmcenter/BotCommands/PingCommand.cs +++ b/pmcenter/BotCommands/PingCommand.cs @@ -16,9 +16,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_PingReply, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/ReadConfigCommand.cs b/pmcenter/BotCommands/ReadConfigCommand.cs index e30ea28..5d3fe94 100644 --- a/pmcenter/BotCommands/ReadConfigCommand.cs +++ b/pmcenter/BotCommands/ReadConfigCommand.cs @@ -21,9 +21,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_ConfigReloaded, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/ResetConfCommand.cs b/pmcenter/BotCommands/ResetConfCommand.cs index 9abb89a..3a326c6 100644 --- a/pmcenter/BotCommands/ResetConfCommand.cs +++ b/pmcenter/BotCommands/ResetConfCommand.cs @@ -20,11 +20,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_ConfReset_Started, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - var ownerId = Vars.CurrentConf.OwnerUID; - var apiKey = Vars.CurrentConf.APIKey; + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + long ownerId = Vars.CurrentConf.OwnerUID; + string apiKey = Vars.CurrentConf.APIKey; Vars.CurrentConf = new Conf.ConfObj { OwnerUID = ownerId, @@ -37,25 +37,23 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_ConfReset_Done, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); await Methods.ExitApp(0); return true; } - else - { - _ = await botClient.SendTextMessageAsync( - update.Message.From.Id, - Vars.CurrentLang.Message_ConfReset_Inited, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - Vars.ConfValidator = new Thread(() => Methods.ThrDoResetConfCount()); - Vars.ConfValidator.Start(); - return true; - } + + _ = await botClient.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_ConfReset_Inited, + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + Vars.ConfValidator = new Thread(() => Methods.ThrDoResetConfCount()); + Vars.ConfValidator.Start(); + return true; } } } diff --git a/pmcenter/BotCommands/RestartCommand.cs b/pmcenter/BotCommands/RestartCommand.cs index 3c530d7..34c17f7 100644 --- a/pmcenter/BotCommands/RestartCommand.cs +++ b/pmcenter/BotCommands/RestartCommand.cs @@ -18,9 +18,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_Restarting, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); Thread.Sleep(5000); await Methods.ExitApp(0); return true; diff --git a/pmcenter/BotCommands/RetractCommand.cs b/pmcenter/BotCommands/RetractCommand.cs index f8d9560..404148e 100644 --- a/pmcenter/BotCommands/RetractCommand.cs +++ b/pmcenter/BotCommands/RetractCommand.cs @@ -19,13 +19,15 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { return false; } - var selectedMsgId = update.Message.ReplyToMessage.MessageId; + + int 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 + { + // owner retracting if (IsOwnerRetractionAvailable(selectedMsgId)) { - var link = GetLinkByOwnerMsgID(selectedMsgId); + Conf.MessageIDLink link = GetLinkByOwnerMsgID(selectedMsgId); await botClient.DeleteMessageAsync(link.TGUser.Id, link.UserSessionMessageID).ConfigureAwait(false); Log($"Successfully retracted message from {GetComposedUsername(link.TGUser, true, true)}.", "BOT"); } @@ -34,9 +36,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_FeatureNotAvailable, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } @@ -44,29 +46,34 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { if (IsUserRetractionAvailable(selectedMsgId)) { - var link = GetLinkByUserMsgID(selectedMsgId); - await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionMessageID).ConfigureAwait(false); - Log($"Successfully retracted message from owner.", "BOT"); + Conf.MessageIDLink 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); + { + await botClient.DeleteMessageAsync(Vars.CurrentConf.OwnerUID, link.OwnerSessionActionMessageID) + .ConfigureAwait(false); + } } else { _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_FeatureNotAvailable, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } + _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_Retracted, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/SaveConfigCommand.cs b/pmcenter/BotCommands/SaveConfigCommand.cs index d825dd2..d221003 100644 --- a/pmcenter/BotCommands/SaveConfigCommand.cs +++ b/pmcenter/BotCommands/SaveConfigCommand.cs @@ -18,10 +18,10 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_ConfigUpdated, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/StartCommand.cs b/pmcenter/BotCommands/StartCommand.cs index 81fa490..db4322b 100644 --- a/pmcenter/BotCommands/StartCommand.cs +++ b/pmcenter/BotCommands/StartCommand.cs @@ -19,9 +19,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_OwnerStart, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } else { @@ -29,10 +29,11 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_UserStartDefault, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + return true; } } diff --git a/pmcenter/BotCommands/StatusCommand.cs b/pmcenter/BotCommands/StatusCommand.cs index 02cd997..7a93366 100644 --- a/pmcenter/BotCommands/StatusCommand.cs +++ b/pmcenter/BotCommands/StatusCommand.cs @@ -16,31 +16,36 @@ internal class StatusCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var messageStr = Vars.CurrentLang.Message_SysStatus_Header + "\n\n"; + string messageStr = Vars.CurrentLang.Message_SysStatus_Header + "\n\n"; // process other headers - var noActionRequired = true; + bool noActionRequired = true; if (Vars.UpdatePending) { - messageStr += Vars.CurrentLang.Message_SysStatus_PendingUpdate.Replace("$1", Vars.UpdateVersion.ToString()) + "\n"; + 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; } + if (noActionRequired) { messageStr += Vars.CurrentLang.Message_SysStatus_NoOperationRequired + "\n"; } + messageStr += "\n"; // process summary messageStr += Vars.CurrentLang.Message_SysStatus_Summary .Replace("$1", Environment.MachineName) .Replace("$2", Environment.OSVersion.ToString()) .Replace("$3", RuntimeInformation.OSDescription) - .Replace("$4", (new TimeSpan(0, 0, 0, 0, Environment.TickCount)).ToString()) + .Replace("$4", new TimeSpan(0, 0, 0, 0, Environment.TickCount).ToString()) .Replace("$5", Vars.StartSW.Elapsed.ToString()) .Replace("$6", $"{DateTime.UtcNow.ToShortDateString()} / {DateTime.UtcNow.ToShortTimeString()}") .Replace("$7", Environment.Version.ToString()) @@ -58,9 +63,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, messageStr, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/StopChat.cs b/pmcenter/BotCommands/StopChat.cs index 5a67069..b15fc15 100644 --- a/pmcenter/BotCommands/StopChat.cs +++ b/pmcenter/BotCommands/StopChat.cs @@ -19,9 +19,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) _ = await botClient.SendTextMessageAsync(update.Message.From.Id, Vars.CurrentLang.Message_ContinuedChatDisabled, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/SwitchBwCommand.cs b/pmcenter/BotCommands/SwitchBwCommand.cs index 17247ea..3908cae 100644 --- a/pmcenter/BotCommands/SwitchBwCommand.cs +++ b/pmcenter/BotCommands/SwitchBwCommand.cs @@ -13,17 +13,17 @@ internal class SwitchBwCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var isEnabledNow = Conf.SwitchBlocking(); + bool isEnabledNow = Conf.SwitchBlocking(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync( update.Message.From.Id, - isEnabledNow ? - Vars.CurrentLang.Message_MessageBlockEnabled : - Vars.CurrentLang.Message_MessageBlockDisabled, + isEnabledNow + ? Vars.CurrentLang.Message_MessageBlockEnabled + : Vars.CurrentLang.Message_MessageBlockDisabled, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } diff --git a/pmcenter/BotCommands/SwitchFwCommand.cs b/pmcenter/BotCommands/SwitchFwCommand.cs index 71aaf08..a78bd1c 100644 --- a/pmcenter/BotCommands/SwitchFwCommand.cs +++ b/pmcenter/BotCommands/SwitchFwCommand.cs @@ -13,16 +13,14 @@ internal class SwitchFwCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var isPausedNow = Conf.SwitchPaused(); + bool isPausedNow = Conf.SwitchPaused(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - isPausedNow ? - Vars.CurrentLang.Message_ServicePaused : - Vars.CurrentLang.Message_ServiceResumed, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + isPausedNow ? Vars.CurrentLang.Message_ServicePaused : Vars.CurrentLang.Message_ServiceResumed, + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } diff --git a/pmcenter/BotCommands/SwitchLangCodeCommand.cs b/pmcenter/BotCommands/SwitchLangCodeCommand.cs index 34ca84d..d8339f8 100644 --- a/pmcenter/BotCommands/SwitchLangCodeCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCodeCommand.cs @@ -1,7 +1,7 @@ -using Newtonsoft.Json; using System; using System.IO; using System.Threading.Tasks; +using Newtonsoft.Json; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -21,21 +21,24 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) string listJsonString; Conf.LocaleList localeList; // try to get locale list - listJsonString = await GetStringAsync(new Uri(Vars.LocaleMapURL.Replace("$channel", Vars.CurrentConf.UpdateChannel))).ConfigureAwait(false); + 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 (var mirror in localeList.Locales) + string listString = ""; + foreach (Conf.LocaleMirror mirror in localeList.Locales) { listString += $"{mirror.LocaleCode} - {mirror.LocaleNameNative} ({mirror.LocaleNameEng})\n"; } + reply = Vars.CurrentLang.Message_AvailableLang.Replace("$1", listString); } else { - var targetCode = update.Message.Text.Split(" ")[1]; - foreach (var mirror in localeList.Locales) + string targetCode = update.Message.Text.Split(" ")[1]; + foreach (Conf.LocaleMirror mirror in localeList.Locales) { if (mirror.LocaleCode == targetCode) { @@ -57,16 +60,18 @@ await DownloadFileAsync( goto SendMsg; } } + throw new ArgumentException("Language not found."); } - SendMsg: + + SendMsg: _ = await botClient.SendTextMessageAsync( update.Message.From.Id, reply, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/SwitchLangCommand.cs b/pmcenter/BotCommands/SwitchLangCommand.cs index ff969b1..8a0c59b 100644 --- a/pmcenter/BotCommands/SwitchLangCommand.cs +++ b/pmcenter/BotCommands/SwitchLangCommand.cs @@ -22,12 +22,12 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Update update) update.Message.From.Id, Vars.CurrentLang.Message_SwitchingLang, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); // download file - var langUrl = update.Message.Text.Split(" ")[1]; + string langUrl = update.Message.Text.Split(" ")[1]; Vars.CurrentConf.LangURL = langUrl; // save conf _ = await Conf.SaveConf(isAutoSave: true); @@ -45,9 +45,9 @@ await DownloadFileAsync( update.Message.From.Id, Vars.CurrentLang.Message_LangSwitched, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } diff --git a/pmcenter/BotCommands/SwitchNotificationCommand.cs b/pmcenter/BotCommands/SwitchNotificationCommand.cs index ae8c09c..5e77596 100644 --- a/pmcenter/BotCommands/SwitchNotificationCommand.cs +++ b/pmcenter/BotCommands/SwitchNotificationCommand.cs @@ -13,16 +13,14 @@ internal class SwitchNotificationCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var isDisabledNow = Conf.SwitchNotifications(); + bool isDisabledNow = Conf.SwitchNotifications(); _ = await Conf.SaveConf(false, true).ConfigureAwait(false); _ = await botClient.SendTextMessageAsync(update.Message.From.Id, - isDisabledNow ? - Vars.CurrentLang.Message_NotificationsOff : - Vars.CurrentLang.Message_NotificationsOn, + isDisabledNow ? Vars.CurrentLang.Message_NotificationsOff : Vars.CurrentLang.Message_NotificationsOn, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } diff --git a/pmcenter/BotCommands/TestNetwork.cs b/pmcenter/BotCommands/TestNetwork.cs index fc08d4d..a5dedc0 100644 --- a/pmcenter/BotCommands/TestNetwork.cs +++ b/pmcenter/BotCommands/TestNetwork.cs @@ -17,18 +17,22 @@ internal class TestNetworkCommand : IBotCommand 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); + double latencyToGh = + Math.Round((await TestLatency("https://github.com").ConfigureAwait(false)).TotalMilliseconds, 2); + double latencyToTg = + Math.Round((await TestLatency("https://api.telegram.org/bot").ConfigureAwait(false)).TotalMilliseconds, + 2); + double 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"), parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/UpdateCommand.cs b/pmcenter/BotCommands/UpdateCommand.cs index f12ba14..aa5dc47 100644 --- a/pmcenter/BotCommands/UpdateCommand.cs +++ b/pmcenter/BotCommands/UpdateCommand.cs @@ -5,6 +5,7 @@ using static pmcenter.Methods; using static pmcenter.Methods.Logging; using static pmcenter.Methods.UpdateHelper; +using Update = Telegram.Bot.Types.Update; namespace pmcenter.Commands { @@ -14,15 +15,15 @@ internal class UpdateCommand : IBotCommand public string Prefix => "update"; - public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.Types.Update update) + public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { try { - var latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + Update2 latest = await CheckForUpdatesAsync().ConfigureAwait(false); + int currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); if (IsNewerVersionAvailable(latest)) { - var updateString = Vars.CurrentLang.Message_UpdateAvailable + string updateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", latest.Latest) .Replace("$2", latest.UpdateCollection[currentLocalizedIndex].Details) .Replace("$3", GetUpdateLevel(latest.UpdateLevel)); @@ -31,49 +32,50 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T update.Message.From.Id, updateString, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); // \ updating! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateProcessing, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); // download compiled package await DownloadUpdatesAsync(latest, currentLocalizedIndex).ConfigureAwait(false); // update languages - if (Vars.CurrentConf.AutoLangUpdate) await DownloadLangAsync().ConfigureAwait(false); + if (Vars.CurrentConf.AutoLangUpdate) + { + await DownloadLangAsync().ConfigureAwait(false); + } // \ see you! / _ = await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateFinalizing, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); Log("Exiting program... (Let the daemon do the restart job)", "BOT"); await ExitApp(0); return true; // end of difference } - else - { - _ = await botClient.SendTextMessageAsync( - update.Message.From.Id, - Vars.CurrentLang.Message_AlreadyUpToDate - .Replace("$1", latest.Latest) - .Replace("$2", Vars.AppVer.ToString()) - .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); - return true; - } + + _ = await botClient.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_AlreadyUpToDate + .Replace("$1", latest.Latest) + .Replace("$2", Vars.AppVer.ToString()) + .Replace("$3", latest.UpdateCollection[currentLocalizedIndex].Details), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + return true; } catch (Exception ex) { @@ -82,9 +84,9 @@ public async Task ExecuteAsync(TelegramBotClient botClient, Telegram.Bot.T update.Message.From.Id, errorString, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotCommands/UptimeCommand.cs b/pmcenter/BotCommands/UptimeCommand.cs index 796367d..92bc21e 100644 --- a/pmcenter/BotCommands/UptimeCommand.cs +++ b/pmcenter/BotCommands/UptimeCommand.cs @@ -14,17 +14,17 @@ internal class UptimeCommand : IBotCommand public async Task ExecuteAsync(TelegramBotClient botClient, Update update) { - var uptimeString = + string uptimeString = Vars.CurrentLang.Message_UptimeInfo - .Replace("$1", (new TimeSpan(0, 0, 0, 0, Environment.TickCount)).ToString()) - .Replace("$2", Vars.StartSW.Elapsed.ToString()); + .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, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); return true; } } diff --git a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs index 7131460..ed881b0 100644 --- a/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs +++ b/pmcenter/BotProcess/BotProcess.CallbackQueryRoute.cs @@ -1,6 +1,6 @@ -using pmcenter.CallbackActions; -using System; +using System; using System.Threading.Tasks; +using pmcenter.CallbackActions; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; @@ -13,21 +13,36 @@ public static partial class BotProcess { private static async Task CallbackQueryRoute(Update update) { - if (update.CallbackQuery == null) return; - if (update.CallbackQuery.From.IsBot) return; + if (update.CallbackQuery == null) + { + return; + } + + if (update.CallbackQuery.From.IsBot) + { + return; + } + try { - 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); + Conf.MessageIDLink link = GetLinkByOwnerMsgID(update.CallbackQuery.Message.ReplyToMessage.MessageId); + if (link == null) + { + throw new NullReferenceException(Vars.CurrentLang.Message_Action_LinkNotFound); + } + + CallbackActionResult 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( update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, new InlineKeyboardMarkup(CallbackProcess.GetAvailableButtons(update))); + } } catch (Exception ex) { diff --git a/pmcenter/BotProcess/BotProcess.MessageRoute.cs b/pmcenter/BotProcess/BotProcess.MessageRoute.cs index e017c19..52769c0 100644 --- a/pmcenter/BotProcess/BotProcess.MessageRoute.cs +++ b/pmcenter/BotProcess/BotProcess.MessageRoute.cs @@ -8,9 +8,20 @@ public static partial class BotProcess { private static async Task MessageRoute(Update update) { - if (update.Message == null) return; - if (update.Message.From.IsBot) return; - if (update.Message.Chat.Type != ChatType.Private) return; + if (update.Message == null) + { + return; + } + + if (update.Message.From.IsBot) + { + return; + } + + if (update.Message.Chat.Type != ChatType.Private) + { + return; + } Vars.CurrentConf.Statistics.TotalMessagesReceived += 1; if (update.Message.From.Id == Vars.CurrentConf.OwnerUID) diff --git a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs index eeb3898..38a502b 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerCommand.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerCommand.cs @@ -17,34 +17,45 @@ private static async Task OwnerCommand(Update update) 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, - disableNotification: Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + Message forwarded = await Vars.Bot.ForwardMessageAsync( + Vars.CurrentConf.ContChatTarget, + update.Message.Chat.Id, + update.Message.MessageId, + disableNotification: 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 } + 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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + string 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: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + Log($"Successfully passed owner's reply to UID: {Vars.CurrentConf.ContChatTarget}", "BOT"); return; } @@ -53,9 +64,9 @@ private static async Task OwnerCommand(Update update) update.Message.From.Id, Vars.CurrentLang.Message_CommandNotReplying, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } } } diff --git a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs index 7e8f19d..417300a 100644 --- a/pmcenter/BotProcess/BotProcess.OwnerReplying.cs +++ b/pmcenter/BotProcess/BotProcess.OwnerReplying.cs @@ -11,35 +11,40 @@ 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); + Conf.MessageIDLink link = Methods.GetLinkByOwnerMsgID(update.Message.ReplyToMessage.MessageId); User? forwardFrom = null; if (link != null && !link.IsFromOwner) { - 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"); + 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"); forwardFrom = link.TGUser; } - if ((forwardFrom == null) && (update.Message.Text.ToLowerInvariant() != "/retract")) + + if (forwardFrom == null && update.Message.Text.ToLowerInvariant() != "/retract") { // The owner is replying to bot messages. (no forwardfrom) _ = await Vars.Bot.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_CommandNotReplyingValidMessage, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); // The message is forwarded anonymously - if (!string.IsNullOrEmpty(update.Message.ReplyToMessage.ForwardSenderName) && !Vars.CurrentConf.DisableMessageLinkTip) + if (!string.IsNullOrEmpty(update.Message.ReplyToMessage.ForwardSenderName) && + !Vars.CurrentConf.DisableMessageLinkTip) { _ = await Vars.Bot.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_MsgLinkTip, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); Vars.CurrentConf.DisableMessageLinkTip = true; } + return; } @@ -67,27 +72,46 @@ private static async Task OwnerReplying(Update update) update.Message.MessageId, disableNotification: Vars.CurrentConf.DisableNotifications).ConfigureAwait(false)).MessageId; } + + // Cc owner's reply. + if (Vars.CurrentConf.EnableCc) + { + await RunCc(update); + } + + if (Vars.CurrentConf.EnableMsgLink) { - Log($"Recording message link: user {replyToMsgId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", "BOT"); + Log( + $"Recording message link: user {replyToMsgId} <-> owner {update.Message.MessageId}, user: {update.Message.ReplyToMessage.ForwardFrom.Id}", + "BOT"); Vars.CurrentConf.MessageLinks.Add( - new Conf.MessageIDLink() - { OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = replyToMsgId, TGUser = update.Message.ReplyToMessage.ForwardFrom, IsFromOwner = true } + new Conf.MessageIDLink + { + OwnerSessionMessageID = update.Message.MessageId, UserSessionMessageID = replyToMsgId, + 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", $"[{Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom)}](tg://user?id={update.Message.ReplyToMessage.ForwardFrom.Id})"); - _ = await Vars.Bot.SendTextMessageAsync(update.Message.From.Id, replyToMessage, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + string replyToMessage = Vars.CurrentLang.Message_ReplySuccessful; + 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: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } - Log($"Successfully passed owner's reply to {Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom, true, true)}", "BOT"); + + Log( + $"Successfully passed owner's reply to {Methods.GetComposedUsername(update.Message.ReplyToMessage.ForwardFrom, true, true)}", + "BOT"); } } } diff --git a/pmcenter/BotProcess/BotProcess.RunCc.cs b/pmcenter/BotProcess/BotProcess.RunCc.cs index 75fc73b..49fdc13 100644 --- a/pmcenter/BotProcess/BotProcess.RunCc.cs +++ b/pmcenter/BotProcess/BotProcess.RunCc.cs @@ -12,49 +12,60 @@ public static partial class BotProcess private static async Task RunCc(Update update) { Log("Cc enabled, forwarding...", "BOT"); - foreach (var id in Vars.CurrentConf.Cc) + foreach (long id in Vars.CurrentConf.Cc) { - Log($"Forwarding message to cc: {id}", "BOT"); - try + if (update.Message.From.Id != id) { - var forwardedMessageCc = await Vars.Bot.ForwardMessageAsync(id, - update.Message.From.Id, - update.Message.MessageId, - disableNotification: Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); - // check if forwarded from channels - if (update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null) + Log($"Forwarding message to cc: {id}", "BOT"); + try { - // 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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.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) + Message forwardedMessageCc = await Vars.Bot.ForwardMessageAsync(id, + update.Message.From.Id, + update.Message.MessageId, + disableNotification: 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: ParseMode.Markdown, + 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: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId).ConfigureAwait(false); + } - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: - 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: ParseMode.Markdown, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: + forwardedMessageCc.MessageId).ConfigureAwait(false); + } } } + catch (Exception ex) + { + Log($"Unable to forward message to cc: {id}, reason: {ex.Message}", "BOT", LogLevel.Error); + } } - catch (Exception ex) + else { - Log($"Unable to forward message to cc: {id}, reason: {ex.Message}", "BOT", LogLevel.Error); + Log($"Current message is sent by cc user: {id}, skipped."); } } } diff --git a/pmcenter/BotProcess/BotProcess.UserLogic.cs b/pmcenter/BotProcess/BotProcess.UserLogic.cs index 575dcb3..e20f482 100644 --- a/pmcenter/BotProcess/BotProcess.UserLogic.cs +++ b/pmcenter/BotProcess/BotProcess.UserLogic.cs @@ -1,5 +1,5 @@ -using pmcenter.CallbackActions; -using System.Threading.Tasks; +using System.Threading.Tasks; +using pmcenter.CallbackActions; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -15,48 +15,60 @@ 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"); + 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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + Log("Stopped: forwarding is currently paused.", "BOT"); + _ = await Vars.Bot.SendTextMessageAsync( + update.Message.From.Id, + Vars.CurrentLang.Message_UserServicePaused, + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: update.Message.MessageId + ).ConfigureAwait(false); return; } - if (Methods.IsBanned(update.Message.From.Id)) + 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"); + Log( + $"Restricting banned user from sending messages: {update.Message.From.FirstName} (@{update.Message.From.Username} / {update.Message.From.Id})", + "BOT"); return; } // 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"); 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, - disableNotification: Vars.CurrentConf.DisableNotifications).ConfigureAwait(false); + Message forwardedMessage = await Vars.Bot.ForwardMessageAsync( + Vars.CurrentConf.OwnerUID, + update.Message.From.Id, + update.Message.MessageId, + disableNotification: Vars.CurrentConf.DisableNotifications + ).ConfigureAwait(false); Vars.CurrentConf.Statistics.TotalForwardedToOwner += 1; // preprocess message link - var link = new Conf.MessageIDLink() + Conf.MessageIDLink link = new() { OwnerSessionMessageID = forwardedMessage.MessageId, UserSessionMessageID = update.Message.MessageId, @@ -66,64 +78,101 @@ private static async Task UserLogic(Update update) // process actions if (Vars.CurrentConf.EnableActions && Vars.CurrentConf.EnableMsgLink) { - var markup = new InlineKeyboardMarkup(CallbackProcess.GetAvailableButtons(update)); + InlineKeyboardMarkup markup = new(CallbackProcess.GetAvailableButtons(update)); link.OwnerSessionActionMessageID = (await Vars.Bot.SendTextMessageAsync( Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_Action_ChooseAction, parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: true, - replyParameters: forwardedMessage.MessageId, + linkPreviewOptions: false, + disableNotification: true, + replyParameters: forwardedMessage.MessageId, replyMarkup: markup - ).ConfigureAwait(false)).MessageId; + ).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); } + // 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; + bool forwarderNotReal = update.Message.ForwardFrom == null && update.Message.ForwardFromChat != null; 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)) + 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", $"[{GetComposedUsername(update.Message.From)}](tg://user?id={update.Message.From.Id})"), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: Vars.CurrentConf.DisableNotifications, - replyParameters: forwardedMessage.MessageId).ConfigureAwait(false); + Vars.CurrentLang.Message_ForwarderNotReal + .Replace("$2", update.Message.From.Id.ToString()) + .Replace("$1", + $"[{GetComposedUsername(update.Message.From)}](tg://user?id={update.Message.From.Id})"), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: Vars.CurrentConf.DisableNotifications, + replyParameters: forwardedMessage.MessageId).ConfigureAwait(false); + + // HACK: do a hack to allow cc to reply with target user + if (Vars.CurrentConf.EnableCc && Vars.CurrentConf.Cc.Contains(update.Message.From.Id) && + update.Message.ReplyToMessage != null && update.Message.ReplyToMessage.ForwardFrom != null) + { + if (Vars.CurrentConf.EnableOwnerReplyCopyMessage) + { + _ = await Vars.Bot.CopyMessageAsync( + update.Message.ReplyToMessage.ForwardFrom.Id, + update.Message.From.Id, + update.Message.MessageId, + disableNotification: Vars.CurrentConf.DisableNotifications + ).ConfigureAwait(false); + } + else + { + _ = await Vars.Bot.ForwardMessageAsync( + update.Message.ReplyToMessage.ForwardFrom.Id, + update.Message.Chat.Id, + update.Message.MessageId, + disableNotification: Vars.CurrentConf.DisableNotifications + ).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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: false, - replyParameters: update.Message.MessageId).ConfigureAwait(false); + Vars.CurrentLang.Message_ForwardedToOwner, + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: false, + replyParameters: update.Message.MessageId).ConfigureAwait(false); } + AddRateLimit(update.Message.From.Id); } } diff --git a/pmcenter/BotProcess/BotProcess.cs b/pmcenter/BotProcess/BotProcess.cs index 3b7e7c8..f524124 100644 --- a/pmcenter/BotProcess/BotProcess.cs +++ b/pmcenter/BotProcess/BotProcess.cs @@ -4,9 +4,9 @@ // Copyright (C) The pmcenter authors. Licensed under the Apache License (Version 2.0). */ -using pmcenter.Commands; using System; using System.Threading.Tasks; +using pmcenter.Commands; using Telegram.Bot; using Telegram.Bot.Polling; using Telegram.Bot.Types; @@ -17,7 +17,7 @@ namespace pmcenter { public static partial class BotProcess { - private static readonly CommandRouter commandManager = new CommandRouter(); + private static readonly CommandRouter commandManager = new(); static BotProcess() { @@ -64,15 +64,26 @@ public static async Task OnUpdate(Update update) try { if (Vars.CurrentConf.DetailedMsgLogging && update.Type == UpdateType.Message) - Log($"OnUpdate() triggered: UpdType: {update.Type}, UpdID: {update.Id}, ChatId: {update.Message.Chat.Id}, Username: {update.Message.Chat.Username}, FromID: {update.Message.From.Id}, FromUsername: {update.Message.From.Username}", "BOT-DETAILED", LogLevel.Info); + { + Log( + $"OnUpdate() triggered: UpdType: {update.Type}, UpdID: {update.Id}, ChatId: {update.Message.Chat.Id}, Username: {update.Message.Chat.Username}, FromID: {update.Message.From.Id}, FromUsername: {update.Message.From.Username}", + "BOT-DETAILED"); + } switch (update.Type) { - case UpdateType.Message: await MessageRoute(update); break; - case UpdateType.CallbackQuery: await CallbackQueryRoute(update); break; + case UpdateType.Message: + await MessageRoute(update); + break; + case UpdateType.CallbackQuery: + await CallbackQueryRoute(update); + break; default: if (Vars.CurrentConf.DetailedMsgLogging) + { Log($"Ditching unknown update type ({update.Type})...", "BOT-DETAILED"); + } + return; } } @@ -83,10 +94,9 @@ public static async Task OnUpdate(Update update) { try { - _ = await Vars.Bot.SendTextMessageAsync( - chatId: Vars.CurrentConf.OwnerUID, - text: Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), + Vars.CurrentConf.OwnerUID, + Vars.CurrentLang.Message_GeneralFailure.Replace("$1", ex.ToString()), parseMode: ParseMode.Markdown, linkPreviewOptions: false, disableNotification: Vars.CurrentConf.DisableNotifications diff --git a/pmcenter/BotProcess/CommandRouter.cs b/pmcenter/BotProcess/CommandRouter.cs index 1d5dd0a..08a73e5 100644 --- a/pmcenter/BotProcess/CommandRouter.cs +++ b/pmcenter/BotProcess/CommandRouter.cs @@ -18,46 +18,53 @@ internal class CommandRouter { private const char globalPrefix = '/'; - private readonly List commands = new List(); - - public CommandRouter() - { - } + private readonly List commands = new(); public IBotCommand this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); /// - /// Add a command to manager. - /// Throws when a command with same prefix exists. + /// Add a command to manager. + /// Throws when a command with same prefix exists. /// /// the 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)); } + { + throw new ArgumentException($"A command with prefix \"{command.Prefix}\" already exists.", + nameof(command)); + } commands.Add(command); } /// - /// Try run a message as command + /// Try run a message as 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; + } - var command = commands.FirstOrDefault(cmd => + if (!update.Message.Text.StartsWith(globalPrefix)) + { + return false; + } + + IBotCommand command = commands.FirstOrDefault(cmd => { // can run = cmd is not owner only command, OR sender id equals owner id - bool adminRunnable = !cmd.OwnerOnly || (update.Message.From.Id == Vars.CurrentConf.OwnerUID); + bool adminRunnable = !cmd.OwnerOnly || update.Message.From.Id == Vars.CurrentConf.OwnerUID; // can run = remove global prefix fist, then if starts with cmd.Prefix - bool prefixMatch = update.Message.Text.TrimStart(globalPrefix).StartsWith(cmd.Prefix, StringComparison.InvariantCultureIgnoreCase); + bool prefixMatch = update.Message.Text.TrimStart(globalPrefix) + .StartsWith(cmd.Prefix, StringComparison.InvariantCultureIgnoreCase); return adminRunnable && prefixMatch; }); @@ -66,10 +73,8 @@ public async Task Execute(TelegramBotClient botClient, Update update) { return false; } - else - { - return await command.ExecuteAsync(botClient, update).ConfigureAwait(false); - } + + return await command.ExecuteAsync(botClient, update).ConfigureAwait(false); } } } diff --git a/pmcenter/CallbackActions/BanAction.cs b/pmcenter/CallbackActions/BanAction.cs index ecd0c17..e42b237 100644 --- a/pmcenter/CallbackActions/BanAction.cs +++ b/pmcenter/CallbackActions/BanAction.cs @@ -22,6 +22,9 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_Banned.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) => !IsBanned(update); + public bool IsAvailable(Update update) + { + return !IsBanned(update); + } } } diff --git a/pmcenter/CallbackActions/CallbackActionResult.cs b/pmcenter/CallbackActions/CallbackActionResult.cs index 37ab725..2ce5f00 100644 --- a/pmcenter/CallbackActions/CallbackActionResult.cs +++ b/pmcenter/CallbackActions/CallbackActionResult.cs @@ -2,14 +2,15 @@ { public class CallbackActionResult { + public bool ShowAsAlert; + public string Status; + public bool Succeeded; + 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 2d613f7..ed1adba 100644 --- a/pmcenter/CallbackActions/CallbackManager.cs +++ b/pmcenter/CallbackActions/CallbackManager.cs @@ -9,41 +9,44 @@ namespace pmcenter.CallbackActions { internal class CallbackManager { - private readonly List callbacks = new List(); - - public CallbackManager() - { } + private readonly List callbacks = new(); 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)); + { + 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) + foreach (ICallbackAction action in callbacks) { if (action.Name == actionName) { return await action.Action(user, msg); } } + return null; } public List> GetAvailableButtons(Update update) { - var result = new List>(); - foreach (var action in callbacks) + List> result = new(); + foreach (ICallbackAction action in callbacks) + { if (action.IsAvailable(update)) { - var oneLineKeyboard = new List + List oneLineKeyboard = new List { - new InlineKeyboardButton() + new() { CallbackData = action.Name, Text = action.ButtonName @@ -51,6 +54,8 @@ public List> GetAvailableButtons(Update update) }; result.Add(oneLineKeyboard); } + } + return result; } } diff --git a/pmcenter/CallbackActions/CallbackProcess.cs b/pmcenter/CallbackActions/CallbackProcess.cs index 932f2ff..a0751a5 100644 --- a/pmcenter/CallbackActions/CallbackProcess.cs +++ b/pmcenter/CallbackActions/CallbackProcess.cs @@ -10,7 +10,7 @@ namespace pmcenter.CallbackActions public static class CallbackProcess { private static readonly int callbackOutputThreshold = 50; - private static readonly CallbackManager callbackManager = new CallbackManager(); + private static readonly CallbackManager callbackManager = new(); static CallbackProcess() { @@ -21,7 +21,7 @@ static CallbackProcess() } /// - /// Do callback with given arguments + /// Do callback with given arguments /// /// The name of the action /// The user who initiated the action @@ -31,15 +31,21 @@ public static async Task DoCallback(string actionName, Use { try { - var result = await callbackManager.Execute(actionName, user, msg); + string result = await callbackManager.Execute(actionName, user, msg); if (result == null) { Log($"Callback {actionName} from user {user.Id} cannot be found.", "BOT", LogLevel.Warning); result = Vars.CurrentLang.Message_Action_Error; } - var useAlert = result.Length > callbackOutputThreshold; + + bool useAlert = result.Length > callbackOutputThreshold; if (useAlert) - Log($"Callback query result length {result.Length} exceeded limit ({callbackOutputThreshold}), using alert instead.", "BOT"); + { + Log( + $"Callback query result length {result.Length} exceeded limit ({callbackOutputThreshold}), using alert instead.", + "BOT"); + } + return new CallbackActionResult ( result, @@ -54,6 +60,9 @@ public static async Task DoCallback(string actionName, Use } } - public static List> GetAvailableButtons(Update update) => callbackManager.GetAvailableButtons(update); + public static List> GetAvailableButtons(Update update) + { + return callbackManager.GetAvailableButtons(update); + } } } diff --git a/pmcenter/CallbackActions/ContinuedChatAction.cs b/pmcenter/CallbackActions/ContinuedChatAction.cs index 39124a9..b42af67 100644 --- a/pmcenter/CallbackActions/ContinuedChatAction.cs +++ b/pmcenter/CallbackActions/ContinuedChatAction.cs @@ -22,6 +22,9 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_ContChatEnabled.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) => Vars.CurrentConf.ContChatTarget == -1; + public bool IsAvailable(Update update) + { + return Vars.CurrentConf.ContChatTarget == -1; + } } } diff --git a/pmcenter/CallbackActions/DisableContinuedChatAction.cs b/pmcenter/CallbackActions/DisableContinuedChatAction.cs index 9c1c8e1..874964d 100644 --- a/pmcenter/CallbackActions/DisableContinuedChatAction.cs +++ b/pmcenter/CallbackActions/DisableContinuedChatAction.cs @@ -21,6 +21,9 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_ContChatDisabled; } - public bool IsAvailable(Update update) => Vars.CurrentConf.ContChatTarget != -1; + public bool IsAvailable(Update update) + { + return Vars.CurrentConf.ContChatTarget != -1; + } } } diff --git a/pmcenter/CallbackActions/PardonAction.cs b/pmcenter/CallbackActions/PardonAction.cs index 322d483..0b36f01 100644 --- a/pmcenter/CallbackActions/PardonAction.cs +++ b/pmcenter/CallbackActions/PardonAction.cs @@ -22,6 +22,9 @@ public async Task Action(User user, Message msg) return Vars.CurrentLang.Message_Action_Pardoned.Replace("$1", GetComposedUsername(user, false)); } - public bool IsAvailable(Update update) => IsBanned(update); + public bool IsAvailable(Update update) + { + return IsBanned(update); + } } } diff --git a/pmcenter/CommandLines/BackupCmdLine.cs b/pmcenter/CommandLines/BackupCmdLine.cs index 4918674..e21eb74 100644 --- a/pmcenter/CommandLines/BackupCmdLine.cs +++ b/pmcenter/CommandLines/BackupCmdLine.cs @@ -10,10 +10,11 @@ internal class BackupCmdLine : ICommandLine { public string Prefix => "backup"; public bool ExitAfterExecution => true; + public Task Process() { Log("Backing up...", "CMD"); - var randomFilename = $"pmcenter.{DateTime.Now:yyyy-dd-M-HH-mm-ss}#{GetRandomString(6)}.json"; + string 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/CommandLineProcess.cs b/pmcenter/CommandLines/CommandLineProcess.cs index d384f6b..7a6d7ac 100644 --- a/pmcenter/CommandLines/CommandLineProcess.cs +++ b/pmcenter/CommandLines/CommandLineProcess.cs @@ -5,22 +5,23 @@ */ using System.Threading.Tasks; +using pmcenter.CommandLines; namespace pmcenter { public static class CmdLineProcess { - private static readonly CommandLineRouter cmdLineRouter = new CommandLineRouter(); + private static readonly CommandLineRouter cmdLineRouter = new(); 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 HelpCmdLine()); + cmdLineRouter.RegisterCommand(new InfoCmdLine()); + cmdLineRouter.RegisterCommand(new NonServiceModeCmdLine()); + cmdLineRouter.RegisterCommand(new SetupWizardCmdLine()); + cmdLineRouter.RegisterCommand(new ResetCmdLine()); + cmdLineRouter.RegisterCommand(new BackupCmdLine()); + cmdLineRouter.RegisterCommand(new UpdateCmdLine()); } public static async Task RunCommand(string CommandLine) diff --git a/pmcenter/CommandLines/CommandLineRouter.cs b/pmcenter/CommandLines/CommandLineRouter.cs index b0ad819..ba89229 100644 --- a/pmcenter/CommandLines/CommandLineRouter.cs +++ b/pmcenter/CommandLines/CommandLineRouter.cs @@ -16,37 +16,36 @@ internal class CommandLineRouter { private const string globalPrefix = "--"; - private readonly List commands = new List(); - - public CommandLineRouter() - { - } + private readonly List commands = new(); public ICommandLine this[string prefix] => commands.FirstOrDefault(command => command.Prefix == prefix); /// - /// Add a command to manager. - /// Throws when a command with same prefix exists. + /// Add a command to manager. + /// Throws when a command with same prefix exists. /// /// the 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)); } + { + throw new ArgumentException($"A commandline with prefix \"{command.Prefix}\" already exists.", + nameof(command)); + } commands.Add(command); } /// - /// Try to find matching commandline and execute it. + /// Try to find matching commandline and execute it. /// /// Original full commandline. /// public async Task Execute(string cmdLine) { Log("Processing commandlines...", "CMD"); - foreach (var cmdProcess in commands) + foreach (ICommandLine cmdProcess in commands) { if (cmdLine.Contains(globalPrefix + cmdProcess.Prefix)) { @@ -60,15 +59,18 @@ public async Task Execute(string cmdLine) Log($"Exception while executing commandline: {ex}", "CMD", LogLevel.Error); Environment.Exit(1); } + Log("Command finished.", "CMD"); if (cmdProcess.ExitAfterExecution) { Log("I am leaving...", "CMD"); Environment.Exit(0); } + return true; } } + Log("No matching commandline found, or no commandline specified.", "CMD"); return false; } diff --git a/pmcenter/CommandLines/HelpCmdLine.cs b/pmcenter/CommandLines/HelpCmdLine.cs index 747bc1e..e77c4fc 100644 --- a/pmcenter/CommandLines/HelpCmdLine.cs +++ b/pmcenter/CommandLines/HelpCmdLine.cs @@ -5,9 +5,12 @@ namespace pmcenter.CommandLines { internal class HelpCmdLine : ICommandLine { + private static string HelpString => + "pmcenter commandline help\n--help: Display this message.\n--info: Get application information.\n--update: Update application manually.\n--backup: Backup configurations.\n--setup: Run setup wizard.\n--reset: Reset everything (use carefully).\n--noservice: Disable service mode, making pmcenter appear as always waiting for user inputs."; + public string Prefix => "help"; public bool ExitAfterExecution => true; - private static string HelpString => "pmcenter commandline help\n--help: Display this message.\n--info: Get application information.\n--update: Update application manually.\n--backup: Backup configurations.\n--setup: Run setup wizard.\n--reset: Reset everything (use carefully).\n--noservice: Disable service mode, making pmcenter appear as always waiting for user inputs."; + public Task Process() { Log("Printing commandline help...", "CMD"); diff --git a/pmcenter/CommandLines/InfoCmdLine.cs b/pmcenter/CommandLines/InfoCmdLine.cs index 09be9ff..519b86b 100644 --- a/pmcenter/CommandLines/InfoCmdLine.cs +++ b/pmcenter/CommandLines/InfoCmdLine.cs @@ -10,12 +10,16 @@ internal class InfoCmdLine : ICommandLine { public string Prefix => "info"; public bool ExitAfterExecution => true; + 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); + Log("Gathering application information... This may take a while for there's some network activities.", + "CMD"); + bool isTelegramApiAccessible = + await TestConnectivity("https://api.telegram.org/bot/", true).ConfigureAwait(false); + bool isGitHubAccessible = + await TestConnectivity("https://raw.githubusercontent.com/", true).ConfigureAwait(false); + bool 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"); diff --git a/pmcenter/CommandLines/ResetCmdLine.cs b/pmcenter/CommandLines/ResetCmdLine.cs index d5873f1..6817e94 100644 --- a/pmcenter/CommandLines/ResetCmdLine.cs +++ b/pmcenter/CommandLines/ResetCmdLine.cs @@ -7,6 +7,7 @@ internal class ResetCmdLine : ICommandLine { public string Prefix => "reset"; public bool ExitAfterExecution => true; + public async Task Process() { Log("Resetting configurations...", "CMD"); diff --git a/pmcenter/CommandLines/SetupWizardCmdLine.cs b/pmcenter/CommandLines/SetupWizardCmdLine.cs index 993c13d..a700fde 100644 --- a/pmcenter/CommandLines/SetupWizardCmdLine.cs +++ b/pmcenter/CommandLines/SetupWizardCmdLine.cs @@ -7,6 +7,7 @@ internal class SetupWizardCmdLine : ICommandLine { public string Prefix => "setup"; public bool ExitAfterExecution => true; + public async Task Process() { Log("Launching setup wizard...", "CMD"); diff --git a/pmcenter/CommandLines/UpdateCmdLine.cs b/pmcenter/CommandLines/UpdateCmdLine.cs index fd73875..5fd02b4 100644 --- a/pmcenter/CommandLines/UpdateCmdLine.cs +++ b/pmcenter/CommandLines/UpdateCmdLine.cs @@ -8,15 +8,19 @@ internal class UpdateCmdLine : ICommandLine { public string Prefix => "update"; public bool ExitAfterExecution => true; + 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); + Log( + "Custom update channels and languages are currently unsupported in command line mode, will use \"master\" channel with English.", + "CMD"); + Update2 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 DownloadLangAsync().ConfigureAwait(false); @@ -24,8 +28,11 @@ public async Task Process() } 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/CheckPoint.cs b/pmcenter/Configurations/CheckPoint.cs index ca8caef..7bf58f4 100644 --- a/pmcenter/Configurations/CheckPoint.cs +++ b/pmcenter/Configurations/CheckPoint.cs @@ -2,12 +2,13 @@ { public class CheckPoint { + public string Name; + public long Tick; + public CheckPoint(long tick = 0, string name = "Unspecified") { Tick = tick; Name = name; } - public long Tick; - public string Name; } } diff --git a/pmcenter/Configurations/Conf.BanObj.cs b/pmcenter/Configurations/Conf.BanObj.cs index e6507ae..5f3e490 100644 --- a/pmcenter/Configurations/Conf.BanObj.cs +++ b/pmcenter/Configurations/Conf.BanObj.cs @@ -8,6 +8,7 @@ public BanObj() { UID = -1; } + public long UID { get; set; } } } diff --git a/pmcenter/Configurations/Conf.ConfObj.New.cs b/pmcenter/Configurations/Conf.ConfObj.New.cs index 616c14c..d5748ec 100644 --- a/pmcenter/Configurations/Conf.ConfObj.New.cs +++ b/pmcenter/Configurations/Conf.ConfObj.New.cs @@ -54,7 +54,7 @@ public ConfObj() BannedKeywords = new List(); Banned = new List(); MessageLinks = new List(); - EnableOwnerReplyCopyMessage = false ; + EnableOwnerReplyCopyMessage = false; } } } diff --git a/pmcenter/Configurations/Conf.GetConf.cs b/pmcenter/Configurations/Conf.GetConf.cs index 985c356..c15bd9c 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 { @@ -8,7 +8,7 @@ public static partial class Conf { public static async Task GetConf(string filename) { - var settingsText = await File.ReadAllTextAsync(filename).ConfigureAwait(false); + string 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 55d6d33..357aad6 100644 --- a/pmcenter/Configurations/Conf.InitConf.cs +++ b/pmcenter/Configurations/Conf.InitConf.cs @@ -11,13 +11,15 @@ public static async Task InitConf() { Log("Checking configurations file's integrity...", "CONF"); if (!File.Exists(Vars.ConfFile)) - { // STEP 1, DETECT EXISTENCE. + { + // STEP 1, DETECT EXISTENCE. 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. } else - { // STEP 2, READ TEST. + { + // STEP 2, READ TEST. try { _ = await ReadConf(false).ConfigureAwait(false); // Read but don't apply. @@ -31,6 +33,7 @@ public static async Task InitConf() _ = await SaveConf(true).ConfigureAwait(false); // Then the app will exit, do nothing. } } + Log("Integrity test finished!", "CONF"); } } diff --git a/pmcenter/Configurations/Conf.KillIllegalChars.cs b/pmcenter/Configurations/Conf.KillIllegalChars.cs index 8c437c4..7c37fda 100644 --- a/pmcenter/Configurations/Conf.KillIllegalChars.cs +++ b/pmcenter/Configurations/Conf.KillIllegalChars.cs @@ -4,7 +4,8 @@ public static partial class Conf { 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.LocaleList.cs b/pmcenter/Configurations/Conf.LocaleList.cs index 4b94735..22ba8ec 100644 --- a/pmcenter/Configurations/Conf.LocaleList.cs +++ b/pmcenter/Configurations/Conf.LocaleList.cs @@ -10,6 +10,7 @@ public LocaleList() { Locales = new List(); } + public List Locales { get; set; } } } diff --git a/pmcenter/Configurations/Conf.LocaleMirror.cs b/pmcenter/Configurations/Conf.LocaleMirror.cs index bda44f4..d5fd34c 100644 --- a/pmcenter/Configurations/Conf.LocaleMirror.cs +++ b/pmcenter/Configurations/Conf.LocaleMirror.cs @@ -11,6 +11,7 @@ public LocaleMirror() LocaleNameEng = ""; LocaleNameNative = ""; } + public string LocaleFileURL { get; set; } public string LocaleCode { get; set; } public string LocaleNameEng { get; set; } diff --git a/pmcenter/Configurations/Conf.MessageIDLink.cs b/pmcenter/Configurations/Conf.MessageIDLink.cs index 47208a7..fa95996 100644 --- a/pmcenter/Configurations/Conf.MessageIDLink.cs +++ b/pmcenter/Configurations/Conf.MessageIDLink.cs @@ -14,11 +14,14 @@ public MessageIDLink() UserSessionMessageID = -1; IsFromOwner = false; } + public User TGUser { get; set; } + /// - /// Message ID of the message in owner's session + /// 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 42f77dd..5b223f1 100644 --- a/pmcenter/Configurations/Conf.RateData.cs +++ b/pmcenter/Configurations/Conf.RateData.cs @@ -9,6 +9,7 @@ public RateData() UID = -1; MessageCount = 0; } + public long UID { get; set; } public int MessageCount { get; set; } } diff --git a/pmcenter/Configurations/Conf.ReadConf.cs b/pmcenter/Configurations/Conf.ReadConf.cs index 36ab75f..53390c2 100644 --- a/pmcenter/Configurations/Conf.ReadConf.cs +++ b/pmcenter/Configurations/Conf.ReadConf.cs @@ -5,9 +5,14 @@ namespace pmcenter 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; } + { + // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. + ConfObj 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 1a35dbc..e45b813 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 @@ -8,19 +8,23 @@ namespace pmcenter 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); + { + // DO NOT HANDLE ERRORS HERE. + string text = JsonConvert.SerializeObject(Vars.CurrentConf, + Vars.CurrentConf.Minify ? Formatting.None : Formatting.Indented); await 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.Warning); Log("Please reconfigure it and try to start pmcenter again.", "CONF", LogLevel.Warning); Vars.RestartRequired = true; } + return true; } } diff --git a/pmcenter/Configurations/Conf.Socks5Proxy.cs b/pmcenter/Configurations/Conf.Socks5Proxy.cs index 2703a0e..3fde3fe 100644 --- a/pmcenter/Configurations/Conf.Socks5Proxy.cs +++ b/pmcenter/Configurations/Conf.Socks5Proxy.cs @@ -11,6 +11,7 @@ public Socks5Proxy() Username = null; ProxyPass = null; } + public string ServerName { get; set; } public int ServerPort { get; set; } public string? Username { get; set; } diff --git a/pmcenter/Configurations/Conf.Stats.cs b/pmcenter/Configurations/Conf.Stats.cs index f0134dd..a086adc 100644 --- a/pmcenter/Configurations/Conf.Stats.cs +++ b/pmcenter/Configurations/Conf.Stats.cs @@ -11,6 +11,7 @@ public Stats() TotalForwardedToOwner = 0; TotalForwardedFromOwner = 0; } + public int TotalMessagesReceived { get; set; } public int TotalCommandsReceived { get; set; } public int TotalForwardedToOwner { get; set; } diff --git a/pmcenter/Configurations/Conf.SwitchBlocking.cs b/pmcenter/Configurations/Conf.SwitchBlocking.cs index 423f9a3..f1385aa 100644 --- a/pmcenter/Configurations/Conf.SwitchBlocking.cs +++ b/pmcenter/Configurations/Conf.SwitchBlocking.cs @@ -3,7 +3,7 @@ namespace pmcenter public static partial class Conf { /// - /// Switch 'blocking' status, returning current status. + /// Switch 'blocking' status, returning current status. /// /// public static bool SwitchBlocking() @@ -13,11 +13,9 @@ public static bool SwitchBlocking() Vars.CurrentConf.KeywordBanning = false; return false; } - else - { - Vars.CurrentConf.KeywordBanning = true; - return true; - } + + Vars.CurrentConf.KeywordBanning = true; + return true; } } } diff --git a/pmcenter/Configurations/Conf.SwitchNotifications.cs b/pmcenter/Configurations/Conf.SwitchNotifications.cs index f859f1d..037caee 100644 --- a/pmcenter/Configurations/Conf.SwitchNotifications.cs +++ b/pmcenter/Configurations/Conf.SwitchNotifications.cs @@ -3,7 +3,7 @@ namespace pmcenter public static partial class Conf { /// - /// Switch 'disablenotifications' status, returning current status. + /// Switch 'disablenotifications' status, returning current status. /// /// public static bool SwitchNotifications() @@ -13,11 +13,9 @@ public static bool SwitchNotifications() Vars.CurrentConf.DisableNotifications = false; return false; } - else - { - Vars.CurrentConf.DisableNotifications = true; - return true; - } + + Vars.CurrentConf.DisableNotifications = true; + return true; } } } diff --git a/pmcenter/Configurations/Conf.SwitchPaused.cs b/pmcenter/Configurations/Conf.SwitchPaused.cs index a39b4f4..8106e02 100644 --- a/pmcenter/Configurations/Conf.SwitchPaused.cs +++ b/pmcenter/Configurations/Conf.SwitchPaused.cs @@ -3,7 +3,7 @@ namespace pmcenter public static partial class Conf { /// - /// Switch 'forwarding' status, returning current status. + /// Switch 'forwarding' status, returning current status. /// /// public static bool SwitchPaused() @@ -13,11 +13,9 @@ public static bool SwitchPaused() Vars.CurrentConf.ForwardingPaused = false; return false; } - else - { - Vars.CurrentConf.ForwardingPaused = true; - return true; - } + + Vars.CurrentConf.ForwardingPaused = true; + return true; } } } diff --git a/pmcenter/Configurations/Lang.InitLang.cs b/pmcenter/Configurations/Lang.InitLang.cs index 8c56fe8..9f870de 100644 --- a/pmcenter/Configurations/Lang.InitLang.cs +++ b/pmcenter/Configurations/Lang.InitLang.cs @@ -11,13 +11,15 @@ public static async Task InitLang() { Log("Checking language file's integrity...", "LANG"); if (!File.Exists(Vars.LangFile)) - { // STEP 1, DETECT EXISTENCE. + { + // STEP 1, DETECT EXISTENCE. 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. } else - { // STEP 2, READ TEST. + { + // STEP 2, READ TEST. try { _ = await ReadLang(false).ConfigureAwait(false); // Read but don't apply. @@ -31,6 +33,7 @@ public static async Task InitLang() _ = await SaveLang(true).ConfigureAwait(false); // Then the app will exit, do nothing. } } + Log("Integrity test finished!", "LANG"); } } diff --git a/pmcenter/Configurations/Lang.Language.New.cs b/pmcenter/Configurations/Lang.Language.New.cs index 8514592..48777cf 100644 --- a/pmcenter/Configurations/Lang.Language.New.cs +++ b/pmcenter/Configurations/Lang.Language.New.cs @@ -12,13 +12,16 @@ 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/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_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!"; Message_UserBanned = "🚫 The user has been banned permanently."; Message_UserPardoned = "✅ You've pardoned the user."; - Message_UserStartDefault = "📨 *Hi!* To send anything to my owner, just send it here.\n⚠ To be informed: I'll *automatically* ban flooding users."; + Message_UserStartDefault = + "📨 *Hi!* To send anything to my owner, just send it here.\n⚠ To be informed: I'll *automatically* ban flooding users."; Message_PingReply = "📶 Pong!"; Message_ServicePaused = "📴 Message forwarding has been *paused*."; Message_ServiceResumed = "📲 Messsage forwarding has been *resumed*."; @@ -29,10 +32,12 @@ public Language() Message_ConfigUpdated = "🔄 Settings have been updated!"; Message_ConfigReloaded = "🔄 Settings reloaded!"; Message_UptimeInfo = "🚀 *Uptime Information*:\nSystem uptime: `$1`\nBot uptime: `$2`"; - Message_UpdateAvailable = "🔄 *Update available!*\n\n$3\nNew version: `$1`\nWhat's new:\n`$2`\n\nExecute /update to perform automatic update."; + Message_UpdateAvailable = + "🔄 *Update available!*\n\n$3\nNew version: `$1`\nWhat's new:\n`$2`\n\nExecute /update to perform automatic update."; Message_UpdateProcessing = "💠 Preparing to update..."; Message_UpdateCheckFailed = "⚠ Update failed: `$1`"; - Message_AlreadyUpToDate = "✅ *Already up to date*!\nLatest version: `$1`\nCurrently installed: `$2`\nUpdate details:\n`$3`"; + Message_AlreadyUpToDate = + "✅ *Already up to date*!\nLatest version: `$1`\nCurrently installed: `$2`\nUpdate details:\n`$3`"; Message_UpdateExtracting = "📤 Extracting update files..."; Message_UpdateFinalizing = "✅ Files patching complete! Trying to restart..."; Message_CurrentConf = "💾 *Your current configurations*: \n`$1`"; @@ -46,14 +51,18 @@ public Language() Message_SysStatus_UpdateLevel_Urgent = "⚠ Urgent"; Message_SysStatus_UpdateLevel_Unknown = "❓ Unknown"; Message_SysStatus_RestartRequired = "🔄 *Bot restart required to apply changes.*"; - Message_SysStatus_Summary = "📝 *Device name*: `$1`\n💿 *Operating System*: `$2`\nℹ *OS description*: `$3`\n⌛ *Server uptime*: `$4`\n🕓 *Bot uptime*: `$5`\n📅 *Server time (UTC)*: `$6`\n📐 *Runtime version*: `$7`\nℹ *Runtime description*: `$8`\n📏 *Application version*: `$9`\n💠 *Processor count*: `$a`\n📖 *Language code*: `$b`\n🛫 *Update channel (current)*: `$f`\n🛬 *Update channel (target)*: `$g`\n🔄 *Update checker*: `$c`\n🔄 *Rate limit processor*: `$d`\n🔄 *Configuration reset verifier*: `$e`"; + Message_SysStatus_Summary = + "📝 *Device name*: `$1`\n💿 *Operating System*: `$2`\nℹ *OS description*: `$3`\n⌛ *Server uptime*: `$4`\n🕓 *Bot uptime*: `$5`\n📅 *Server time (UTC)*: `$6`\n📐 *Runtime version*: `$7`\nℹ *Runtime description*: `$8`\n📏 *Application version*: `$9`\n💠 *Processor count*: `$a`\n📖 *Language code*: `$b`\n🛫 *Update channel (current)*: `$f`\n🛬 *Update channel (target)*: `$g`\n🔄 *Update checker*: `$c`\n🔄 *Rate limit processor*: `$d`\n🔄 *Configuration reset verifier*: `$e`"; Message_Restarting = "🔄 Restarting...\n\n_It only works with systemd-like daemons._"; Message_NotificationsOff = "📳 Notifications are *OFF*."; Message_NotificationsOn = "📲 Notifications are *ON*."; - Message_SupportTextMessagesOnly = "📋 Sorry... Only text messages can be forwarded in Anonymous Forward mode."; - Message_ForwarderNotReal = "ℹ The actual sender of this message is $1, whose UID is `$2`.\n\nYou can also ban this user by sending this following command:\n\n`/banid $2`\n\nTo undo this, send this command:\n\n`/pardonid $2`"; + Message_SupportTextMessagesOnly = + "📋 Sorry... Only text messages can be forwarded in Anonymous Forward mode."; + Message_ForwarderNotReal = + "ℹ The actual sender of this message is $1, whose UID is `$2`.\n\nYou can also ban this user by sending this following command:\n\n`/banid $2`\n\nTo undo this, send this command:\n\n`/pardonid $2`"; Message_GeneralFailure = "✖ Error processing request: $1"; - Message_LangVerMismatch = "⚠ Language file (`$1`) is not for current version (`$2`), consider updating language file?"; + Message_LangVerMismatch = + "⚠ Language file (`$1`) is not for current version (`$2`), consider updating language file?"; Message_SwitchingLang = "💠 Switching language..."; Message_LangSwitched = "🚀 Language switched!"; Message_ThreadStatus_Unknown = "Unknown"; @@ -61,26 +70,34 @@ public Language() Message_ThreadStatus_Working = "Working"; Message_ThreadStatus_Stopped = "Stopped"; Message_ThreadStatus_Error = "Error"; - Message_ConfReset_Inited = "❓ *Are you sure you want to reset configurations?*\n\nThis will reset everything to default value (except API Key and Owner ID) and is irrevertable!\nBot will restart after resetting configurations.\n\nSend /resetconf again in 30s to continue."; + Message_ConfReset_Inited = + "❓ *Are you sure you want to reset configurations?*\n\nThis will reset everything to default value (except API Key and Owner ID) and is irrevertable!\nBot will restart after resetting configurations.\n\nSend /resetconf again in 30s to continue."; Message_ConfReset_Started = "💠 Resetting..."; Message_ConfReset_Done = "🔄 Configurations have been reset! Restarting..."; Message_Performance_Inited = "🔄 Performance test started."; Message_Performance_Results = "✅ *Performance test complete*\n\nScore: `$1`."; Message_BackupComplete = "✅ Backup complete! File name: `$1`"; Message_ConfAccess = "ℹ *Access Info*\n\nConfigurations: `$1`\nLanguage: `$2`"; - Message_APIKeyChanged = "⚠ We've detected an API Key change. Please restart pmcenter to apply this change."; - Message_Connectivity = "📡 *Connectivity Information*\n\nLatency to GitHub: $1\nLatency to Telegram API: $2\nLatency to CI (updates): $3"; - Message_ContinuedChatEnabled = "💬 *Continued Conversation* mode is now `active`! All your messages (except commands and replys) will be forwarded to $1"; + Message_APIKeyChanged = + "⚠ We've detected an API Key change. Please restart pmcenter to apply this change."; + Message_Connectivity = + "📡 *Connectivity Information*\n\nLatency to GitHub: $1\nLatency to Telegram API: $2\nLatency to CI (updates): $3"; + Message_ContinuedChatEnabled = + "💬 *Continued Conversation* mode is now `active`! All your messages (except commands and replys) will be forwarded to $1"; Message_ContinuedChatDisabled = "✅ *Continued Conversation* is now `disabled`."; Message_FeatureNotAvailable = "⚠ *This feature is unavailable or disabled*."; - Message_Stats = "📝 *Statistics*\n\n💬 Received messages: `$1`\n🔄 Forwarded to owner: `$2`\n🔄 Forwarded from owner: `$3`\n🚀 Commands received: `$4`"; + Message_Stats = + "📝 *Statistics*\n\n💬 Received messages: `$1`\n🔄 Forwarded to owner: `$2`\n🔄 Forwarded from owner: `$3`\n🚀 Commands received: `$4`"; 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_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_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_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!"; @@ -93,7 +110,8 @@ 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.ReadLang.cs b/pmcenter/Configurations/Lang.ReadLang.cs index a9f5bfb..b0f173d 100644 --- a/pmcenter/Configurations/Lang.ReadLang.cs +++ b/pmcenter/Configurations/Lang.ReadLang.cs @@ -1,16 +1,21 @@ -using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; +using Newtonsoft.Json; namespace pmcenter { 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 langText = await File.ReadAllTextAsync(Vars.LangFile).ConfigureAwait(false); - var temp = JsonConvert.DeserializeObject(langText); - if (apply) { Vars.CurrentLang = temp; } + { + // DO NOT HANDLE ERRORS HERE. THE CALLING METHOD WILL HANDLE THEM. + string langText = await File.ReadAllTextAsync(Vars.LangFile).ConfigureAwait(false); + Language 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 30d95ba..b99061c 100644 --- a/pmcenter/Configurations/Lang.SaveLang.cs +++ b/pmcenter/Configurations/Lang.SaveLang.cs @@ -1,6 +1,7 @@ -using Newtonsoft.Json; using System.IO; +using System.Text; using System.Threading.Tasks; +using Newtonsoft.Json; using static pmcenter.Methods.Logging; namespace pmcenter @@ -8,9 +9,10 @@ namespace pmcenter 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); + { + // DO NOT HANDLE ERRORS HERE. + string text = JsonConvert.SerializeObject(Vars.CurrentLang, Formatting.Indented); + StreamWriter writer = new StreamWriter(File.Create(Vars.LangFile), Encoding.UTF8); await writer.WriteAsync(text).ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); writer.Close(); @@ -20,6 +22,7 @@ public static async Task SaveLang(bool isInvalid = false) 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 8c9dd63..ab2efbc 100644 --- a/pmcenter/EventHandlers/CtrlCHandler.cs +++ b/pmcenter/EventHandlers/CtrlCHandler.cs @@ -8,19 +8,31 @@ public static partial class EventHandlers { public static async void CtrlCHandler(object sender, ConsoleCancelEventArgs e) { - if (e != null) e.Cancel = true; + if (e != null) + { + e.Cancel = true; + } + Vars.CtrlCCounter++; if (Vars.CtrlCCounter > 3) { Log("More than 3 interrupts has received, terminating...", LogLevel.Warning); Environment.Exit(137); } - if (Vars.IsCtrlCHandled) return; + + 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.Warning); + Log( + "Keyboard interrupt is currently being ignored. To change this behavior, set \"IgnoreKeyboardInterrupt\" key to \"false\" in pmcenter configurations.", + LogLevel.Warning); return; } + Vars.IsCtrlCHandled = true; Log("Interrupt! pmcenter is exiting...", LogLevel.Warning); Log("If pmcenter was unresponsive, press Ctrl-C 3 more times."); diff --git a/pmcenter/EventHandlers/GlobalErrorHandler.cs b/pmcenter/EventHandlers/GlobalErrorHandler.cs index 294a591..1b8704a 100644 --- a/pmcenter/EventHandlers/GlobalErrorHandler.cs +++ b/pmcenter/EventHandlers/GlobalErrorHandler.cs @@ -12,23 +12,32 @@ public static void GlobalErrorHandler(object sender, UnhandledExceptionEventArgs { void L(string log) { - if (string.IsNullOrEmpty(log)) return; + if (string.IsNullOrEmpty(log)) + { + return; + } + Console.Error.WriteLine(log); } + L("[!] Critical error occurred, falling back to basic logging."); 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( + "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"); - var exception = e != null ? (Exception)e.ExceptionObject : new Exception("unknown error"); - var fileName = Path.Combine(Environment.CurrentDirectory, $"pmcenter-error-{GetDateTimeString(true)}.log"); + Exception exception = e != null ? (Exception)e.ExceptionObject : new Exception("unknown error"); + string fileName = Path.Combine(Environment.CurrentDirectory, + $"pmcenter-error-{GetDateTimeString(true)}.log"); L($"Exception details: {exception}"); L($"Attempting to write to {fileName}"); try { - var writer = new StreamWriter(fileName, false, Encoding.UTF8) { AutoFlush = true }; + StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8) { AutoFlush = true }; 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( + $"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:x} error details:"); writer.WriteLine(exception.ToString()); writer.Close(); @@ -37,6 +46,7 @@ void L(string log) { L($"Unable to save error logs: {ex}"); } + Environment.Exit(Marshal.GetHRForException(exception)); } } diff --git a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs index fc59a82..f55823c 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetBanObjByID.cs @@ -6,10 +6,14 @@ public static partial class Methods { public static BanObj GetBanObjByID(long uid) { - foreach (var banned in Vars.CurrentConf.Banned) + foreach (BanObj 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 35920c2..c92c943 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByOwnerMsgID.cs @@ -8,11 +8,15 @@ public static MessageIDLink GetLinkByOwnerMsgID(long ownerSessionMsgId) { lock (Vars.CurrentConf.MessageLinks) { - foreach (var link in Vars.CurrentConf.MessageLinks) + foreach (MessageIDLink 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 2ede789..5ec7dc3 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetLinkByUserMsgID.cs @@ -8,11 +8,15 @@ public static MessageIDLink GetLinkByUserMsgID(long userSessionMsgId) { lock (Vars.CurrentConf.MessageLinks) { - foreach (var link in Vars.CurrentConf.MessageLinks) + foreach (MessageIDLink 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 0edb11c..ad3bfa6 100644 --- a/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs +++ b/pmcenter/Methods/Database/Checking/Methods.GetRateDataIndexByID.cs @@ -4,10 +4,14 @@ public static partial class Methods { public static int GetRateDataIndexByID(long uid) { - foreach (var data in Vars.RateLimits) + foreach (Conf.RateData 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 29bd75d..44e50a2 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsBanned.cs @@ -7,18 +7,31 @@ public static partial class Methods { public static bool IsBanned(long uid) { - foreach (var banned in Vars.CurrentConf.Banned) + foreach (Conf.BanObj banned in Vars.CurrentConf.Banned) { - if (banned.UID == uid) return true; + if (banned.UID == uid) + { + return true; + } } + 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); + 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; } } diff --git a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs index 1088b10..2c92963 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsKeywordBanned.cs @@ -4,19 +4,29 @@ public static partial class Methods { public static bool IsKeywordBanned(string sentence) { - if (!Vars.CurrentConf.KeywordBanning) return false; + if (!Vars.CurrentConf.KeywordBanning) + { + return false; + } - foreach (var blocked in Vars.CurrentConf.BannedKeywords) + foreach (string 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 a274430..e0abb14 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsOwnerRetractionAvailable.cs @@ -4,14 +4,22 @@ public static partial class Methods { public static bool IsOwnerRetractionAvailable(int ownerSessionMsgId) { - if (!Vars.CurrentConf.EnableMsgLink) return false; + if (!Vars.CurrentConf.EnableMsgLink) + { + return false; + } + lock (Vars.CurrentConf.MessageLinks) { - foreach (var link in Vars.CurrentConf.MessageLinks) + foreach (Conf.MessageIDLink 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 d89f5ea..e1a0c16 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsRateDataTracking.cs @@ -4,10 +4,14 @@ public static partial class Methods { public static bool IsRateDataTracking(long uid) { - foreach (var data in Vars.RateLimits) + foreach (Conf.RateData 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 a820020..5b28200 100644 --- a/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs +++ b/pmcenter/Methods/Database/Checking/Methods.IsUserRetractionAvailable.cs @@ -4,14 +4,22 @@ public static partial class Methods { public static bool IsUserRetractionAvailable(int userSessionMsgId) { - if (!Vars.CurrentConf.EnableMsgLink) return false; + if (!Vars.CurrentConf.EnableMsgLink) + { + return false; + } + lock (Vars.CurrentConf.MessageLinks) { - foreach (var link in Vars.CurrentConf.MessageLinks) + foreach (Conf.MessageIDLink 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 79d03c6..575e22e 100644 --- a/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs +++ b/pmcenter/Methods/Database/Writing/Methods.AddRateLimit.cs @@ -8,12 +8,12 @@ public static void AddRateLimit(long uid) { if (IsRateDataTracking(uid)) { - var dataId = GetRateDataIndexByID(uid); + int dataId = GetRateDataIndexByID(uid); Vars.RateLimits[dataId].MessageCount += 1; } else { - var data = new RateData + RateData data = new RateData { UID = uid, MessageCount = 1 diff --git a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs index f940d90..fd8862c 100644 --- a/pmcenter/Methods/Database/Writing/Methods.BanUser.cs +++ b/pmcenter/Methods/Database/Writing/Methods.BanUser.cs @@ -8,7 +8,7 @@ public static void BanUser(long uid) { if (!IsBanned(uid)) { - var banned = new BanObj + BanObj banned = new BanObj { UID = uid }; diff --git a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs index 51d59c7..66686d7 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.DownloadFileAsync.cs @@ -10,8 +10,8 @@ public static partial class H2Helper { public static async Task DownloadFileAsync(Uri uri, string filename) { - var bytes = await GetBytesAsync(uri).ConfigureAwait(false); - var fileStream = File.Create(filename); + byte[] bytes = await GetBytesAsync(uri).ConfigureAwait(false); + FileStream fileStream = File.Create(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 61a074d..79bb557 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetBytesAsync.cs @@ -1,4 +1,5 @@ using System; +using System.Net.Http; using System.Threading.Tasks; namespace pmcenter @@ -9,7 +10,7 @@ public static partial class H2Helper { public static async Task GetBytesAsync(Uri uri) { - using var content = await GetHttpContentAsync(uri).ConfigureAwait(false); + using HttpContent 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 33979f6..d579951 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetHttpContentAsync.cs @@ -10,8 +10,8 @@ public static partial class H2Helper { private static async Task GetHttpContentAsync(Uri uri) { - var client = new HttpClient() { DefaultRequestVersion = new Version(2, 0) }; - var response = await client.GetAsync(uri).ConfigureAwait(false); + HttpClient client = new HttpClient { DefaultRequestVersion = new Version(2, 0) }; + HttpResponseMessage 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 a0f3163..3b3351a 100644 --- a/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs +++ b/pmcenter/Methods/H2Helper/Methods.H2Helper.GetStringAsync.cs @@ -1,4 +1,5 @@ using System; +using System.Net.Http; using System.Threading.Tasks; namespace pmcenter @@ -9,7 +10,7 @@ public static partial class H2Helper { public static async Task GetStringAsync(Uri uri) { - using var content = await GetHttpContentAsync(uri).ConfigureAwait(false); + using HttpContent content = await GetHttpContentAsync(uri).ConfigureAwait(false); return await content.ReadAsStringAsync().ConfigureAwait(false); } } diff --git a/pmcenter/Methods/Logging/Methods.Log.cs b/pmcenter/Methods/Logging/Methods.Log.cs index 9e16b94..9e46a71 100644 --- a/pmcenter/Methods/Logging/Methods.Log.cs +++ b/pmcenter/Methods/Logging/Methods.Log.cs @@ -13,20 +13,29 @@ 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) + string module = "CORE", + LogLevel type = LogLevel.Info, + [CallerFilePath] string filePath = "file?", + [CallerMemberName] string callerName = "method?", + [CallerLineNumber] int lineNumber = 0) { - if (Vars.CurrentConf?.IgnoredLogModules.Contains(module) == true) return; - if (Vars.CurrentConf?.LowPerformanceMode == true) return; + 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}"; - var output = Vars.CurrentConf?.DisableTimeDisplay != true - ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" - : ""; + string file = + $"/{Path.GetFileName(Environment.OSVersion.Platform == PlatformID.Unix ? filePath.Replace(@"\", "/") : filePath)}/{callerName}()@L{lineNumber}"; + string output = Vars.CurrentConf?.DisableTimeDisplay != true + ? $"[{DateTime.Now.ToString("o", CultureInfo.InvariantCulture)}]" + : ""; output += $"[{module}{(Vars.CurrentConf?.AdvancedLogging == true ? file : "")}]"; output += LogTable[type].Prefix; output += text; diff --git a/pmcenter/Methods/Logging/Methods.LogLevel.cs b/pmcenter/Methods/Logging/Methods.LogLevel.cs index 35ec806..414c2b7 100644 --- a/pmcenter/Methods/Logging/Methods.LogLevel.cs +++ b/pmcenter/Methods/Logging/Methods.LogLevel.cs @@ -8,7 +8,7 @@ public enum LogLevel { Info = 0, Warning = 1, - Error = 2, + Error = 2 } } } diff --git a/pmcenter/Methods/Logging/Methods.LogMode.cs b/pmcenter/Methods/Logging/Methods.LogMode.cs index ac7d2f7..4736158 100644 --- a/pmcenter/Methods/Logging/Methods.LogMode.cs +++ b/pmcenter/Methods/Logging/Methods.LogMode.cs @@ -9,8 +9,8 @@ public static partial class Logging public class LogMode { public ConsoleColor Color; - public string Prefix; public Action Func; + public string Prefix; } } } diff --git a/pmcenter/Methods/Logging/Methods.LogTable.cs b/pmcenter/Methods/Logging/Methods.LogTable.cs index 52ab9f2..5ff91bd 100644 --- a/pmcenter/Methods/Logging/Methods.LogTable.cs +++ b/pmcenter/Methods/Logging/Methods.LogTable.cs @@ -7,11 +7,20 @@ public static partial class Methods { public static partial class Logging { - public static Dictionary LogTable = new Dictionary() + public static Dictionary LogTable = new() { - {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}} + { + 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.CheckNetCoreVersion.cs b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs index 5623d50..6704fc9 100644 --- a/pmcenter/Methods/Methods.CheckNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.CheckNetCoreVersion.cs @@ -9,11 +9,16 @@ 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.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); + 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 716747c..a513a5a 100644 --- a/pmcenter/Methods/Methods.CheckOpenSSLComp.cs +++ b/pmcenter/Methods/Methods.CheckOpenSSLComp.cs @@ -9,7 +9,11 @@ public static partial class Methods { public static void CheckOpenSSLComp(Exception ex) { - if (ex == null) return; + if (ex == null) + { + return; + } + try { if (ex.GetType() == typeof(HttpRequestException)) @@ -18,13 +22,17 @@ 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); } } } } - catch { } + catch + { + } } } } diff --git a/pmcenter/Methods/Methods.ExitApp.cs b/pmcenter/Methods/Methods.ExitApp.cs index 116b71e..d8dd9ab 100644 --- a/pmcenter/Methods/Methods.ExitApp.cs +++ b/pmcenter/Methods/Methods.ExitApp.cs @@ -15,7 +15,7 @@ public static async Task ExitApp(int code) Vars.Bot.OnUpdate -= BotProcess.OnUpdate; Vars.Bot.OnError -= BotProcess.OnError; Log("Waiting for background workers to exit (timeout: 10s)..."); - var sw = new Stopwatch(); + Stopwatch sw = new Stopwatch(); sw.Start(); Vars.IsShuttingDown = true; @@ -23,9 +23,14 @@ public static async Task ExitApp(int code) await Conf.SaveConf(); while (Vars.IsPerformanceTestExecuting) { - if (sw.ElapsedMilliseconds >= 10000) Environment.Exit(16); + if (sw.ElapsedMilliseconds >= 10000) + { + Environment.Exit(16); + } + Thread.Sleep(50); } + Log("[OK] Shut down performance tester."); Thread[] threads = @@ -48,16 +53,21 @@ public static async Task ExitApp(int code) for (int i = 0; i < threads.Length; i++) { - var thread = threads[i]; + Thread thread = threads[i]; if (thread != null && thread.IsAlive) { thread.Interrupt(); while (thread.IsAlive) { - if (sw.ElapsedMilliseconds >= 10000) Environment.Exit(16); + if (sw.ElapsedMilliseconds >= 10000) + { + Environment.Exit(16); + } + Thread.Sleep(50); } } + Log($"[OK] Shut down {threadNames[i]}."); } diff --git a/pmcenter/Methods/Methods.GetComposedUsername.cs b/pmcenter/Methods/Methods.GetComposedUsername.cs index 301cfee..ad96d33 100644 --- a/pmcenter/Methods/Methods.GetComposedUsername.cs +++ b/pmcenter/Methods/Methods.GetComposedUsername.cs @@ -7,15 +7,33 @@ public static partial class Methods { public static string GetComposedUsername(User user, bool includeUsername = true, bool includeId = false) { - var sb = new StringBuilder(user.FirstName); + StringBuilder 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(); + } + + 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}"); + } + + 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 e3b957a..b080f6b 100644 --- a/pmcenter/Methods/Methods.GetDateTimeString.cs +++ b/pmcenter/Methods/Methods.GetDateTimeString.cs @@ -7,12 +7,17 @@ public static partial class Methods { public static string GetDateTimeString(bool removeInvalidChar = false) { - var result = DateTime.Now.ToString("o"); - if (!removeInvalidChar) return result; - foreach (var c in Path.GetInvalidFileNameChars()) + string result = DateTime.Now.ToString("o"); + if (!removeInvalidChar) + { + return result; + } + + foreach (char c in Path.GetInvalidFileNameChars()) { result = result.Replace(c, '-'); } + return result; } } diff --git a/pmcenter/Methods/Methods.GetNetCoreVersion.cs b/pmcenter/Methods/Methods.GetNetCoreVersion.cs index a4231c6..b08fd8e 100644 --- a/pmcenter/Methods/Methods.GetNetCoreVersion.cs +++ b/pmcenter/Methods/Methods.GetNetCoreVersion.cs @@ -8,18 +8,22 @@ public static partial class Methods { public static Version GetNetCoreVersion() { - var newVersionInDotnet3 = Environment.Version; - if (newVersionInDotnet3.Major == 3) return newVersionInDotnet3; + Version newVersionInDotnet3 = Environment.Version; + if (newVersionInDotnet3.Major == 3) + { + return newVersionInDotnet3; + } + try { - var searchPattern = "Microsoft.NETCore.App "; - var proc = new Process(); + string searchPattern = "Microsoft.NETCore.App "; + Process proc = new Process(); proc.StartInfo.FileName = "dotnet"; proc.StartInfo.Arguments = "--list-runtimes"; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.Start(); - var output = proc.StandardOutput.ReadToEnd(); + string output = proc.StandardOutput.ReadToEnd(); // search pattern: Microsoft.NETCore.App 2.1.7 [/home/user/dotnet/shared/Microsoft.NETCore.App] int index = output.IndexOf(searchPattern); Version version; @@ -27,17 +31,28 @@ public static Version GetNetCoreVersion() { int indexOfStartingSpace = index + searchPattern.Length - 1; int indexOfEndingSpace = output.IndexOf(" ", index + searchPattern.Length); - var versionString = output.Substring(indexOfStartingSpace + 1, indexOfEndingSpace - indexOfStartingSpace - 1); + string versionString = output.Substring(indexOfStartingSpace + 1, + indexOfEndingSpace - indexOfStartingSpace - 1); version = new Version(versionString); - if (version.Major == 3 && version.Minor == 1) return version; + if (version.Major == 3 && version.Minor == 1) + { + return version; + } + index = output.IndexOf(searchPattern, indexOfEndingSpace); - if (index == -1) break; + if (index == -1) + { + break; + } } + return version; } 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.Warning); + 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 d1cf971..d8402b4 100644 --- a/pmcenter/Methods/Methods.GetRandomString.cs +++ b/pmcenter/Methods/Methods.GetRandomString.cs @@ -8,7 +8,7 @@ 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()); + return new string(Enumerable.Repeat(chars, length).Select(s => s[new Random().Next(s.Length)]).ToArray()); } } } diff --git a/pmcenter/Methods/Methods.GetThreadStatusString.cs b/pmcenter/Methods/Methods.GetThreadStatusString.cs index 55b36c6..d3f58b2 100644 --- a/pmcenter/Methods/Methods.GetThreadStatusString.cs +++ b/pmcenter/Methods/Methods.GetThreadStatusString.cs @@ -10,7 +10,7 @@ public static string GetThreadStatusString(ThreadStatus status) 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, + _ => Vars.CurrentLang.Message_ThreadStatus_Unknown }; } } diff --git a/pmcenter/Methods/Methods.GetUpdateLevel.cs b/pmcenter/Methods/Methods.GetUpdateLevel.cs index 846daa8..121132a 100644 --- a/pmcenter/Methods/Methods.GetUpdateLevel.cs +++ b/pmcenter/Methods/Methods.GetUpdateLevel.cs @@ -9,11 +9,14 @@ public static string GetUpdateLevel(UpdateLevel level) 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.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), + _ => processed.Replace("$1", Vars.CurrentLang.Message_SysStatus_UpdateLevel_Unknown) }; } } diff --git a/pmcenter/Methods/Methods.IsRegexMatch.cs b/pmcenter/Methods/Methods.IsRegexMatch.cs index 28b4160..d72b570 100644 --- a/pmcenter/Methods/Methods.IsRegexMatch.cs +++ b/pmcenter/Methods/Methods.IsRegexMatch.cs @@ -10,7 +10,11 @@ public static bool IsRegexMatch(string source, string expression) { try { - if (Regex.IsMatch(source, expression, RegexOptions.None)) return true; + if (Regex.IsMatch(source, expression, RegexOptions.None)) + { + return true; + } + return false; } catch (Exception ex) diff --git a/pmcenter/Methods/Methods.StrChunk.cs b/pmcenter/Methods/Methods.StrChunk.cs index a4eeedf..b9c8cd3 100644 --- a/pmcenter/Methods/Methods.StrChunk.cs +++ b/pmcenter/Methods/Methods.StrChunk.cs @@ -7,7 +7,8 @@ public static partial class Methods { public static List StrChunk(string str, int chunkSize) { - return Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize)).ToList(); + return Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize)) + .ToList(); } } } diff --git a/pmcenter/Methods/Methods.ThreadStatus.cs b/pmcenter/Methods/Methods.ThreadStatus.cs index 0f27882..57274ef 100644 --- a/pmcenter/Methods/Methods.ThreadStatus.cs +++ b/pmcenter/Methods/Methods.ThreadStatus.cs @@ -8,7 +8,7 @@ public enum ThreadStatus Standby = 1, Working = 2, Stopped = 3, - Error = 4, + Error = 4 } } } diff --git a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs index c07718d..a9fe7d1 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestConnectivity.cs @@ -17,13 +17,14 @@ public static async Task TestConnectivity(string target, bool ignore45 = f Timeout = TimeSpan.FromMilliseconds(10000) }; client.DefaultRequestVersion = new Version(2, 0); - var response = await client.GetAsync(target).ConfigureAwait(false); + HttpResponseMessage response = await client.GetAsync(target).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return true; } - catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Forbidden && ignore45) + catch (HttpRequestException ex) when + (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Forbidden && ignore45) { - // 4xx 5xx Ӧ󣬸 ignore45 true + // ���� 4xx �� 5xx ����Ӧ���󣬸��� ignore45 ���� true return true; } catch (WebException ex) diff --git a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs index d463347..567b92c 100644 --- a/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs +++ b/pmcenter/Methods/NetworkTest/Methods.TestLatency.cs @@ -10,12 +10,12 @@ public static partial class Methods { public static async Task TestLatency(string target) { - var reqSw = new Stopwatch(); + Stopwatch reqSw = new Stopwatch(); try { - var client = new HttpClient(); + HttpClient client = new HttpClient(); reqSw.Start(); - var response = await client.GetAsync(target).ConfigureAwait(false); + HttpResponseMessage response = await client.GetAsync(target).ConfigureAwait(false); response.EnsureSuccessStatusCode(); reqSw.Stop(); return reqSw.Elapsed; diff --git a/pmcenter/Methods/Proxy/Methods.LatencyBasedProxy.cs b/pmcenter/Methods/Proxy/Methods.LatencyBasedProxy.cs index d594fe2..385fb94 100644 --- a/pmcenter/Methods/Proxy/Methods.LatencyBasedProxy.cs +++ b/pmcenter/Methods/Proxy/Methods.LatencyBasedProxy.cs @@ -39,22 +39,25 @@ public Uri GetProxy(Uri destination) } // 判断代理是否被绕过(此处直接返回 false,表示所有请求都走代理) - public bool IsBypassed(Uri host) => false; + public bool IsBypassed(Uri host) + { + return false; + } private async Task GetFastestProxyAsync() { WebProxy fastestProxy = null; long lowestLatency = long.MaxValue; - foreach (var proxy in _proxies) + foreach (WebProxy proxy in _proxies) { - var stopwatch = Stopwatch.StartNew(); + Stopwatch stopwatch = Stopwatch.StartNew(); try { - var handler = new HttpClientHandler { Proxy = proxy }; - using (var client = new HttpClient(handler)) + HttpClientHandler handler = new HttpClientHandler { Proxy = proxy }; + using (HttpClient client = new HttpClient(handler)) { - var response = await client.GetAsync(_testUrl); + HttpResponseMessage response = await client.GetAsync(_testUrl); stopwatch.Stop(); if (response.IsSuccessStatusCode && stopwatch.ElapsedMilliseconds < lowestLatency) @@ -74,7 +77,7 @@ private async Task GetFastestProxyAsync() { throw new Exception( "No proxy is available. Please check your proxy list and network connectivity." - ); + ); } return fastestProxy; diff --git a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs index 2aae84a..1b0797e 100644 --- a/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs +++ b/pmcenter/Methods/Threads/Methods.ThrDoResetConfCount.cs @@ -7,7 +7,11 @@ 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 a8f2a1b..516a4be 100644 --- a/pmcenter/Methods/Threads/Methods.ThrPerform.cs +++ b/pmcenter/Methods/Threads/Methods.ThrPerform.cs @@ -4,13 +4,18 @@ 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)) { Vars.PerformanceScore += 1; } + Vars.IsPerformanceTestExecuting = false; Vars.IsPerformanceTestEndRequested = false; } diff --git a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs index f9d27e5..b415f04 100644 --- a/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs +++ b/pmcenter/Methods/Threads/Methods.ThrRateLimiter.cs @@ -12,7 +12,7 @@ public static async void ThrRateLimiter() while (!Vars.IsShuttingDown) { Vars.RateLimiterStatus = ThreadStatus.Working; - foreach (var data in Vars.RateLimits) + foreach (RateData data in Vars.RateLimits) { if (data.MessageCount > Vars.CurrentConf.AutoBanThreshold && Vars.CurrentConf.AutoBan) { @@ -20,10 +20,18 @@ public static async void ThrRateLimiter() _ = await SaveConf(false, true).ConfigureAwait(false); Log($"Banning user: {data.UID}", "RATELIMIT"); } + data.MessageCount = 0; } + Vars.RateLimiterStatus = ThreadStatus.Standby; - try { Thread.Sleep(30000); } catch { } + try + { + Thread.Sleep(30000); + } + catch + { + } } } } diff --git a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs index 11f4b1f..52570ff 100644 --- a/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs +++ b/pmcenter/Methods/Threads/Methods.ThrSyncConf.cs @@ -20,12 +20,20 @@ public static async void ThrSyncConf() { Log($"Failed to write configurations to local disk: {ex.Message}", "CONFSYNC", LogLevel.Error); } + if (Vars.CurrentConf.ConfSyncInterval == 0) { Log("ConfSync disabled, stopping...", "CONFSYNC", LogLevel.Warning); return; } - try { Thread.Sleep(Vars.CurrentConf.ConfSyncInterval); } catch { } + + try + { + Thread.Sleep(Vars.CurrentConf.ConfSyncInterval); + } + catch + { + } } } } diff --git a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs index f41cf8f..5e0d864 100644 --- a/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs +++ b/pmcenter/Methods/Threads/Methods.ThrUpdateChecker.cs @@ -17,38 +17,43 @@ public static async void ThrUpdateChecker() Vars.UpdateCheckerStatus = ThreadStatus.Working; try { - var latest = await CheckForUpdatesAsync().ConfigureAwait(false); - var currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); - var isNotificationDisabled = Vars.CurrentConf.DisableNotifications; + Update2 latest = await CheckForUpdatesAsync().ConfigureAwait(false); + int currentLocalizedIndex = GetUpdateInfoIndexByLocale(latest, Vars.CurrentLang.LangCode); + bool isNotificationDisabled = Vars.CurrentConf.DisableNotifications; // Identical with BotProcess.cs, L206. if (IsNewerVersionAvailable(latest)) { Vars.UpdatePending = true; Vars.UpdateVersion = new Version(latest.Latest); Vars.UpdateLevel = latest.UpdateLevel; - var updateString = Vars.CurrentLang.Message_UpdateAvailable + string 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, - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: isNotificationDisabled).ConfigureAwait(false); + updateString, + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: isNotificationDisabled).ConfigureAwait(false); return; // Since this thread wouldn't be useful any longer, exit. } - else - { - Vars.UpdatePending = false; - // This part has been cut out. - } + + Vars.UpdatePending = false; + // This part has been cut out. } catch (Exception ex) { Log($"Error during update check: {ex}", "UPDATER", LogLevel.Error); } + Vars.UpdateCheckerStatus = ThreadStatus.Standby; - try { Thread.Sleep(60000); } catch { } + try + { + Thread.Sleep(60000); + } + catch + { + } } } } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.CheckForUpdatesAsync.cs index e954cda..305b915 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 @@ -11,9 +11,10 @@ public static partial class UpdateHelper { public static async Task CheckForUpdatesAsync() { - var response = await GetStringAsync( + string response = await GetStringAsync( new Uri( - Vars.UpdateInfo2URL.Replace("$channel", Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel) + Vars.UpdateInfo2URL.Replace("$channel", + Vars.CurrentConf == null ? "master" : Vars.CurrentConf.UpdateChannel) ) ); return JsonConvert.DeserializeObject(response); diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs index d063559..0edb259 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.DownloadUpdateAsync.cs @@ -12,8 +12,8 @@ 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. + /// 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 @@ -29,14 +29,15 @@ await DownloadFileAsync( Path.Combine(Vars.AppDirectory, "pmcenter_update.zip") ).ConfigureAwait(false); Log("Download complete. Extracting..."); - using (var zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) + using (ZipArchive zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) { - foreach (var entry in zip.Entries) + 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 index b5925bc..d35ef48 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.GetUpdateInfoIndexByLocale.cs @@ -8,16 +8,28 @@ public static partial class UpdateHelper { public static int GetUpdateInfoIndexByLocale(Update2 Update, string Locale) { - var indexes = new List(); + List indexes = new List(); for (int i = 0; i < Update.UpdateCollection.Count; i++) { - if (Update.UpdateCollection[i].LangCode.Contains(Locale)) indexes.Add(i); + if (Update.UpdateCollection[i].LangCode.Contains(Locale)) + { + indexes.Add(i); + } } - if (indexes.Count == 0) return 0; - foreach (var i in indexes) + + if (indexes.Count == 0) { - if (Update.UpdateCollection[i].UpdateChannel == Vars.CurrentConf.UpdateChannel) return i; + return 0; } + + foreach (int i in indexes) + { + if (Update.UpdateCollection[i].UpdateChannel == Vars.CurrentConf.UpdateChannel) + { + return i; + } + } + return indexes[0]; } } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs index b92e133..ae64b50 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.IsNewerVersionAvailable.cs @@ -11,19 +11,20 @@ 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); + 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); + + Version currentVersion = Vars.AppVer; + Version currentLatest = new Version(CurrentUpdate.Latest); if (currentLatest > currentVersion) { return true; } - else - { - return false; - } + + return false; } } } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs index 04ba884..162f8f4 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update.cs @@ -8,17 +8,18 @@ public static partial class UpdateHelper { public class Update { + public string Details; + public List LangCode; + public string UpdateArchiveAddress; + public string UpdateChannel; + public Update() { Details = "(Load failed.)"; - LangCode = new List() { "en.integrated" }; + 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; } } } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs index b367afb..6d4cdea 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.Update2.cs @@ -8,15 +8,16 @@ public static partial class UpdateHelper { public class Update2 { + public string Latest; + public List UpdateCollection; + public UpdateLevel UpdateLevel; + public Update2() { Latest = "0.0.0.0"; UpdateLevel = UpdateLevel.Optional; UpdateCollection = new List(); } - public string Latest; - public UpdateLevel UpdateLevel; - public List UpdateCollection; } } } diff --git a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs index 8b5b11e..9770efb 100644 --- a/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs +++ b/pmcenter/Methods/UpdateHelper/Methods.UpdateHelper.UpdateLevel.cs @@ -9,7 +9,7 @@ public enum UpdateLevel Optional = 0, Recommended = 1, Important = 2, - Urgent = 3, + Urgent = 3 } } } diff --git a/pmcenter/Program.cs b/pmcenter/Program.cs index 79466ea..6adb773 100644 --- a/pmcenter/Program.cs +++ b/pmcenter/Program.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Net; using System.Net.Http; using System.Threading; @@ -20,15 +21,23 @@ namespace pmcenter { - public sealed partial class Program + public sealed 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 readonly List _checkPoints = new(); + + 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}: {new TimeSpan(_checkPoints[i].Tick - _checkPoints[i - 1].Tick).TotalMilliseconds}ms: {_checkPoints[i].Name} at {new TimeSpan(_checkPoints[i].Tick).TotalMilliseconds}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) @@ -38,12 +47,17 @@ public static void Main(string[] args) 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); + { + Log("This image of pmcenter is built for GitHub releases. Will use a different updating mechanism.", + "DELEGATOR"); + } + + Task mainAsyncTask = MainAsync(args); mainAsyncTask.Wait(); Log("Main worker accidentally exited. Stopping...", "DELEGATOR", LogLevel.Error); Environment.Exit(1); } + public static async Task MainAsync(string[] args) { try @@ -66,28 +80,29 @@ public static async Task MainAsync(string[] args) // $pmcenter_lang try { - var confByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_conf"); - var langByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_lang"); + string confByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_conf"); + string langByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_lang"); if (confByEnvironmentVar != null) { - if (System.IO.File.Exists(confByEnvironmentVar)) + if (File.Exists(confByEnvironmentVar)) { Vars.ConfFile = confByEnvironmentVar; } else { - Log($"==> The following file was not found: {confByEnvironmentVar}", "CORE", LogLevel.Info); + Log($"==> The following file was not found: {confByEnvironmentVar}"); } } + if (langByEnvironmentVar != null) { - if (System.IO.File.Exists(langByEnvironmentVar)) + if (File.Exists(langByEnvironmentVar)) { Vars.LangFile = langByEnvironmentVar; } else { - Log($"==> The following file was not found: {langByEnvironmentVar}", "CORE", LogLevel.Info); + Log($"==> The following file was not found: {langByEnvironmentVar}"); } } } @@ -95,6 +110,7 @@ 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}"); @@ -110,28 +126,33 @@ 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) { - 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("This may be the first time that you use the pmcenter bot."); + Log("Configuration guide could be found at https://see.wtf/feEJJ"); 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("You may need to check your settings and try again."); Environment.Exit(1); } // check if logs are being omitted if (Vars.CurrentConf.IgnoredLogModules.Count > 0) { - var tmp = Console.ForegroundColor; + ConsoleColor tmp = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("!!!!!!!!!! SOME LOG ENTRIES ARE HIDDEN ACCORDING TO CURRENT SETTINGS !!!!!!!!!!"); + 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.WriteLine( + "This warning will appear every time pmcenter starts up with \"IgnoredLogModules\" set."); Console.ForegroundColor = tmp; } + Check("Warnings displayed"); Log("==> Initializing module - THREADS"); @@ -143,6 +164,7 @@ public static async Task MainAsync(string[] args) { Thread.Sleep(100); } + Check("Rate limiter online"); Log("Starting UpdateChecker..."); @@ -161,6 +183,7 @@ public static async Task MainAsync(string[] args) Vars.UpdateCheckerStatus = ThreadStatus.Stopped; Log("Skipped."); } + Check("Update checker ready"); Log("Starting SyncConf..."); @@ -171,6 +194,7 @@ public static async Task MainAsync(string[] args) { Thread.Sleep(100); } + Check("Configurations autosaver online"); Log("==> Initializing module - BOT"); @@ -179,40 +203,51 @@ public static async Task MainAsync(string[] args) { Log("Activating SOCKS5 proxy..."); new WebProxy(); - List proxyInfoList = new List(); - foreach (var proxyInfo in Vars.CurrentConf.Socks5Proxies) + List proxyInfoList = new(); + foreach (Socks5Proxy proxyInfo in Vars.CurrentConf.Socks5Proxies) { - var proxyUri = new Uri($"socks5://{proxyInfo.ServerName}:{proxyInfo.ServerPort}"); + Uri proxyUri = new($"socks5://{proxyInfo.ServerName}:{proxyInfo.ServerPort}"); proxyInfoList.Add(new WebProxy(proxyUri) { - Credentials = proxyInfo.Username == null ? null : new NetworkCredential(proxyInfo.Username, proxyInfo.ProxyPass) + Credentials = proxyInfo.Username == null + ? null + : new NetworkCredential(proxyInfo.Username, proxyInfo.ProxyPass) }); } - var proxy = new LatencyBasedProxy(proxyInfoList, "https://telegram.org/"); + + LatencyBasedProxy proxy = new(proxyInfoList, "https://telegram.org/"); //{ // ResolveHostnamesLocally = Vars.CurrentConf.ResolveHostnamesLocally //}; Log("SOCKS5 proxy is enabled."); - var handler = new HttpClientHandler() + HttpClientHandler handler = new() { Proxy = proxy }; - var client = new HttpClient(handler); - Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, client, cancellationToken: Vars.CancellationTokenSource.Token); + HttpClient client = new(handler); + Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, client, + Vars.CancellationTokenSource.Token); } else { Log("SOCKS5 proxy is disabled."); - Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, cancellationToken: Vars.CancellationTokenSource.Token); + Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, + cancellationToken: Vars.CancellationTokenSource.Token); } + Check("Bot initialized"); Log("Validating API Key..."); 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 message processors..."); @@ -228,39 +263,45 @@ public static async Task MainAsync(string[] args) if (!Vars.CurrentConf.NoStartupMessage) { _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_BotStarted - .Replace("$1", $"{Math.Round(Vars.StartSW.Elapsed.TotalSeconds, 2)}s"), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: false).ConfigureAwait(false); + Vars.CurrentLang.Message_BotStarted + .Replace("$1", $"{Math.Round(Vars.StartSW.Elapsed.TotalSeconds, 2)}s"), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: false).ConfigureAwait(false); } } 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.Warning); + 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 - var netCoreVersion = GetNetCoreVersion(); + Version netCoreVersion = GetNetCoreVersion(); if (!CheckNetCoreVersion(netCoreVersion) && !Vars.CurrentConf.DisableNetCore3Check) { _ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, - Vars.CurrentLang.Message_NetCore31Required - .Replace("$1", netCoreVersion.ToString()), - parseMode: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: false).ConfigureAwait(false); + Vars.CurrentLang.Message_NetCore31Required + .Replace("$1", netCoreVersion.ToString()), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: false).ConfigureAwait(false); Vars.CurrentConf.DisableNetCore3Check = true; _ = await SaveConf(false, true); } } 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.Warning); + 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 runtime version check complete"); // check language mismatch @@ -268,14 +309,17 @@ public static async Task MainAsync(string[] args) { 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: ParseMode.Markdown, - linkPreviewOptions: false, - disableNotification: false).ConfigureAwait(false); + Vars.CurrentLang.Message_LangVerMismatch + .Replace("$1", Vars.CurrentLang.TargetVersion) + .Replace("$2", Vars.AppVer.ToString()), + parseMode: ParseMode.Markdown, + linkPreviewOptions: false, + disableNotification: false).ConfigureAwait(false); + } } + Check("Language version mismatch checked"); Check("Complete"); if (Vars.CurrentConf.AnalyzeStartupTime) @@ -287,11 +331,17 @@ 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); + } + } + + while (true) + { + Console.ReadKey(true); + } } catch (Exception ex) { diff --git a/pmcenter/Setup.cs b/pmcenter/Setup.cs index 78fcfd5..33d494a 100644 --- a/pmcenter/Setup.cs +++ b/pmcenter/Setup.cs @@ -12,17 +12,19 @@ using Telegram.Bot.Polling; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using File = System.IO.File; namespace pmcenter { public static class Setup { - private static readonly Conf.ConfObj newConf = new Conf.ConfObj(); + private static readonly Conf.ConfObj newConf = new(); private static TelegramBotClient testBot; private static CancellationTokenSource botCancelSource; - private static bool isUidReceived = false; + private static bool isUidReceived; private static long receivedUid = -1; private static string nickname = ""; + private static async Task OnUpdate(Update update) { Say("Update received."); @@ -31,7 +33,9 @@ private static async Task OnUpdate(Update update) { isUidReceived = true; receivedUid = update.Message.From.Id; - nickname = string.IsNullOrEmpty(update.Message.From.LastName) ? update.Message.From.FirstName : $"{update.Message.From.FirstName} {update.Message.From.LastName}"; + nickname = string.IsNullOrEmpty(update.Message.From.LastName) + ? update.Message.From.FirstName + : $"{update.Message.From.FirstName} {update.Message.From.LastName}"; testBot.OnUpdate -= OnUpdate; testBot.OnError -= OnError; } @@ -46,10 +50,12 @@ private static void Say(string input) { Console.WriteLine(input); } + private static void SIn(string input) { Console.Write(input); } + public static async Task SetupWizard() { Say(":) Welcome!"); @@ -79,37 +85,41 @@ public static async Task SetupWizard() Say(" All major configurations have been set!"); Say(""); SIn("=> Save configurations? [Y/n]: "); - var choice = Console.ReadLine(); + string choice = Console.ReadLine(); if (choice.ToLower() != "n") { - if (System.IO.File.Exists(Vars.ConfFile)) + if (File.Exists(Vars.ConfFile)) { Say("Warning: pmcenter.json already exists."); SIn(".. Moving the existing one to pmcenter.json.bak..."); - if (System.IO.File.Exists($"{Vars.ConfFile}.bak")) + if (File.Exists($"{Vars.ConfFile}.bak")) { SIn(" File exists, deleting..."); - System.IO.File.Delete($"{Vars.ConfFile}.bak"); + File.Delete($"{Vars.ConfFile}.bak"); } - System.IO.File.Move(Vars.ConfFile, $"{Vars.ConfFile}.bak"); + + File.Move(Vars.ConfFile, $"{Vars.ConfFile}.bak"); Say(" Done!"); } + SIn($"Saving configurations to {Vars.ConfFile}..."); Vars.CurrentConf = newConf; _ = await Conf.SaveConf().ConfigureAwait(false); Say(" Done!"); - if (System.IO.File.Exists(Vars.LangFile)) + if (File.Exists(Vars.LangFile)) { Say("Warning: pmcenter_locale.json already exists."); SIn(".. Moving the existing one to pmcenter_locale.json.bak..."); - if (System.IO.File.Exists($"{Vars.LangFile}.bak")) + if (File.Exists($"{Vars.LangFile}.bak")) { SIn(" File exists, deleting..."); - System.IO.File.Delete($"{Vars.LangFile}.bak"); + File.Delete($"{Vars.LangFile}.bak"); } - System.IO.File.Move(Vars.LangFile, $"{Vars.LangFile}.bak"); + + File.Move(Vars.LangFile, $"{Vars.LangFile}.bak"); Say(" Done!"); } + SIn($"Saving language file to {Vars.LangFile}..."); Vars.CurrentLang = new Lang.Language(); _ = await Lang.SaveLang().ConfigureAwait(false); @@ -129,15 +139,17 @@ public static async Task SetupWizard() { Say("OK. Come back later!"); } + Environment.Exit(0); } + private static async Task SetAPIKey() { Say("1> API Key"); Say(" API Key is necessary for any Telegram bot to contact with Telegram servers."); Say(" You can always get one for free at @BotFather"); Say(""); - EnterKey: + EnterKey: SIn("=> Enter your API Key: "); string key = Console.ReadLine(); SIn($".. Testing API Key: {key}..."); @@ -147,7 +159,7 @@ private static async Task SetAPIKey() testBot = new TelegramBotClient(key, cancellationToken: botCancelSource.Token); if (!await testBot.TestApiAsync().ConfigureAwait(false)) { - throw (new ArgumentException("API Key is not valid.")); + throw new ArgumentException("API Key is not valid."); } } catch (Exception ex) @@ -156,16 +168,18 @@ private static async Task SetAPIKey() Say($" Invalid API Key: {ex.Message}"); goto EnterKey; } + newConf.APIKey = key; Say(" Done!"); } + private static async Task SetUID() { Say("2> Owner ID"); Say(" Your Telegram UID is your unique and permanent identifier."); Say(" It is required to enable your pmcenter instance to contact with you."); Say(""); - EnterUID: + EnterUID: SIn("=> Enter your UID, or \"auto\" for automatic setup: "); string uid = Console.ReadLine(); if (uid.ToLower() == "auto") @@ -179,7 +193,9 @@ private static async Task SetUID() Thread.Sleep(200); } - _ = await testBot.SendTextMessageAsync(receivedUid, Markdown.Escape($"👋 *Hello my owner!\n* Your UID `{receivedUid}` is now being saved."), parseMode: ParseMode.Markdown); + _ = await testBot.SendTextMessageAsync(receivedUid, + Markdown.Escape($"👋 *Hello my owner!\n* Your UID `{receivedUid}` is now being saved."), + parseMode: ParseMode.Markdown); Say($"Hello, [{nickname}]! Your UID has been detected as {receivedUid}."); SIn($".. Saving UID: {receivedUid}..."); newConf.OwnerUID = receivedUid; @@ -201,6 +217,7 @@ private static async Task SetUID() } } } + private static void SetNotifPrefs() { Say("3> Notification preferences"); @@ -212,6 +229,7 @@ private static void SetNotifPrefs() newConf.DisableNotifications = muteNotif.ToLower() != "y" ? true : false; Say(" Done!"); } + private static void SetAutoBanPrefs() { Say("4> Anti-flood preferences"); @@ -223,6 +241,7 @@ private static void SetAutoBanPrefs() newConf.AutoBan = autoBan.ToLower() != "n" ? true : false; Say(" Done!"); } + private static void SetMessageLinks() { Say("4> Message links preferences"); diff --git a/pmcenter/Vars.cs b/pmcenter/Vars.cs index c0323d8..e614544 100644 --- a/pmcenter/Vars.cs +++ b/pmcenter/Vars.cs @@ -19,30 +19,38 @@ 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.2.0"); - public readonly static string AppExecutable = Assembly.GetExecutingAssembly().Location; - public readonly static string AppDirectory = Path.GetDirectoryName(AppExecutable); + public static readonly string AsciiArt = + " __ \n ____ ____ ___ ________ ____ / /____ _____\n / __ \\/ __ `__ \\/ ___/ _ \\/ __ \\/ __/ _ \\/ ___/\n / /_/ / / / / / / /__/ __/ / / / /_/ __/ / \n / .___/_/ /_/ /_/\\___/\\___/_/ /_/\\__/\\___/_/ \n/_/ "; + + public static readonly Version AppVer = new("2.0.2.0"); + public static readonly string AppExecutable = Assembly.GetExecutingAssembly().Location; + public static readonly 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"; - public readonly static string UpdateInfoURL = "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/updateinfo.json"; - public readonly static string UpdateInfo2URL = "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/updateinfo2.json"; - public readonly static string LocaleMapURL = "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/locales/locale_map.json"; + public static readonly string UpdateArchiveURL = "https://see.wtf/pmcenter-update"; + + public static readonly string UpdateInfoURL = + "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/updateinfo.json"; + + public static readonly string UpdateInfo2URL = + "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/updateinfo2.json"; + + public static readonly string LocaleMapURL = + "https://raw.githubusercontent.com/Elepover/pmcenter/$channel/locales/locale_map.json"; #if MASTER public readonly static string CompileChannel = "master"; #else - public readonly static string CompileChannel = "pmcenter-lazer"; + public static readonly string CompileChannel = "pmcenter-lazer"; #endif #if BUILT_FOR_GITHUB_RELEASES public readonly static bool GitHubReleases = true; #else - public readonly static bool GitHubReleases = false; + public static readonly bool GitHubReleases = false; #endif #if SELFCONTAINED public readonly static bool SelfContained = true; #else - public readonly static bool SelfContained = false; + public static readonly bool SelfContained = false; #endif // public readonly static long AnonymousChannelId = -1001228946795; // public readonly static string AnonymousChannelTitle = "a user"; @@ -59,12 +67,12 @@ public static class Vars public static bool ServiceMode = true; public static Methods.UpdateHelper.UpdateLevel UpdateLevel; public static Version UpdateVersion; - public static Stopwatch StartSW = new Stopwatch(); - public static List RateLimits = new List(); + public static Stopwatch StartSW = new(); + public static List RateLimits = new(); public static double TotalForwarded = 0; public static Conf.ConfObj CurrentConf; public static Lang.Language CurrentLang; - public static CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); + public static CancellationTokenSource CancellationTokenSource = new(); public static TelegramBotClient Bot; public static bool IsPerformanceTestExecuting = false; diff --git a/pmcenter/pmcenter.csproj b/pmcenter/pmcenter.csproj index 01c8e33..093ceb5 100644 --- a/pmcenter/pmcenter.csproj +++ b/pmcenter/pmcenter.csproj @@ -1,11 +1,11 @@  - - Exe - net8.0 - pmcenter.Program - - - - - + + Exe + net8.0 + pmcenter.Program + + + + + \ No newline at end of file